ProcessUtils.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/ProcessUtils.h"
  24. #include "../IO/FileSystem.h"
  25. #include <cstdio>
  26. #include <fcntl.h>
  27. #ifdef __APPLE__
  28. #include "TargetConditionals.h"
  29. #endif
  30. #if defined(IOS)
  31. #include "../Math/MathDefs.h"
  32. #include <mach/mach_host.h>
  33. #elif !defined(__linux__) && !defined(__EMSCRIPTEN__)
  34. #include <LibCpuId/libcpuid.h>
  35. #endif
  36. #ifdef _WIN32
  37. #include <windows.h>
  38. #include <io.h>
  39. #if defined(_MSC_VER)
  40. #include <float.h>
  41. #endif
  42. #else
  43. #include <unistd.h>
  44. #include <sys/sysinfo.h>
  45. #endif
  46. #if defined(__EMSCRIPTEN__) && defined(__EMSCRIPTEN_PTHREADS__)
  47. #include <emscripten/threading.h>
  48. #endif
  49. #if defined(__i386__)
  50. // From http://stereopsis.com/FPU.html
  51. #define FPU_CW_PREC_MASK 0x0300
  52. #define FPU_CW_PREC_SINGLE 0x0000
  53. #define FPU_CW_PREC_DOUBLE 0x0200
  54. #define FPU_CW_PREC_EXTENDED 0x0300
  55. #define FPU_CW_ROUND_MASK 0x0c00
  56. #define FPU_CW_ROUND_NEAR 0x0000
  57. #define FPU_CW_ROUND_DOWN 0x0400
  58. #define FPU_CW_ROUND_UP 0x0800
  59. #define FPU_CW_ROUND_CHOP 0x0c00
  60. inline unsigned GetFPUState()
  61. {
  62. unsigned control = 0;
  63. __asm__ __volatile__ ("fnstcw %0" : "=m" (control));
  64. return control;
  65. }
  66. inline void SetFPUState(unsigned control)
  67. {
  68. __asm__ __volatile__ ("fldcw %0" : : "m" (control));
  69. }
  70. #endif
  71. #ifndef MINI_URHO
  72. #include <SDL/SDL.h>
  73. #endif
  74. #include "../DebugNew.h"
  75. namespace Urho3D
  76. {
  77. #ifdef _WIN32
  78. static bool consoleOpened = false;
  79. #endif
  80. static String currentLine;
  81. static Vector<String> arguments;
  82. static String miniDumpDir;
  83. #if defined(IOS)
  84. static void GetCPUData(host_basic_info_data_t* data)
  85. {
  86. mach_msg_type_number_t infoCount;
  87. infoCount = HOST_BASIC_INFO_COUNT;
  88. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount);
  89. }
  90. #elif defined(__linux__)
  91. struct CpuCoreCount
  92. {
  93. unsigned numPhysicalCores_;
  94. unsigned numLogicalCores_;
  95. };
  96. // This function is used by all the target triplets with Linux as the OS, such as Android, RPI, desktop Linux, etc
  97. static void GetCPUData(struct CpuCoreCount* data)
  98. {
  99. // Sanity check
  100. assert(data);
  101. // At least return 1 core
  102. data->numPhysicalCores_ = data->numLogicalCores_ = 1;
  103. FILE* fp;
  104. int res;
  105. unsigned i, j;
  106. fp = fopen("/sys/devices/system/cpu/present", "r");
  107. if (fp)
  108. {
  109. res = fscanf(fp, "%d-%d", &i, &j);
  110. fclose(fp);
  111. if (res == 2 && i == 0)
  112. {
  113. data->numPhysicalCores_ = data->numLogicalCores_ = j + 1;
  114. fp = fopen("/sys/devices/system/cpu/cpu0/topology/thread_siblings_list", "r");
  115. if (fp)
  116. {
  117. res = fscanf(fp, "%d,%d,%d,%d", &i, &j, &i, &j);
  118. fclose(fp);
  119. // Having sibling thread(s) indicates the CPU is using HT/SMT technology
  120. if (res > 1)
  121. data->numPhysicalCores_ /= res;
  122. }
  123. }
  124. }
  125. }
  126. #elif !defined(__EMSCRIPTEN__)
  127. static void GetCPUData(struct cpu_id_t* data)
  128. {
  129. if (cpu_identify(0, data) < 0)
  130. {
  131. data->num_logical_cpus = 1;
  132. data->num_cores = 1;
  133. }
  134. }
  135. #endif
  136. void InitFPU()
  137. {
  138. // Make sure FPU is in round-to-nearest, single precision mode
  139. // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly
  140. #if defined(_MSC_VER) && defined(_M_IX86)
  141. _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);
  142. #elif defined(__i386__)
  143. unsigned control = GetFPUState();
  144. control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);
  145. control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);
  146. SetFPUState(control);
  147. #endif
  148. }
  149. void ErrorDialog(const String& title, const String& message)
  150. {
  151. #ifndef MINI_URHO
  152. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.CString(), message.CString(), 0);
  153. #endif
  154. }
  155. void ErrorExit(const String& message, int exitCode)
  156. {
  157. if (!message.Empty())
  158. PrintLine(message, true);
  159. exit(exitCode);
  160. }
  161. void OpenConsoleWindow()
  162. {
  163. #ifdef _WIN32
  164. if (consoleOpened)
  165. return;
  166. AllocConsole();
  167. freopen("CONIN$", "r", stdin);
  168. freopen("CONOUT$", "w", stdout);
  169. consoleOpened = true;
  170. #endif
  171. }
  172. void PrintUnicode(const String& str, bool error)
  173. {
  174. #if !defined(__ANDROID__) && !defined(IOS)
  175. #ifdef _WIN32
  176. // If the output stream has been redirected, use fprintf instead of WriteConsoleW,
  177. // though it means that proper Unicode output will not work
  178. FILE* out = error ? stderr : stdout;
  179. if (!_isatty(_fileno(out)))
  180. fprintf(out, "%s", str.CString());
  181. else
  182. {
  183. HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE);
  184. if (stream == INVALID_HANDLE_VALUE)
  185. return;
  186. WString strW(str);
  187. DWORD charsWritten;
  188. WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0);
  189. }
  190. #else
  191. fprintf(error ? stderr : stdout, "%s", str.CString());
  192. #endif
  193. #endif
  194. }
  195. void PrintUnicodeLine(const String& str, bool error)
  196. {
  197. PrintUnicode(str + "\n", error);
  198. }
  199. void PrintLine(const String& str, bool error)
  200. {
  201. #if !defined(__ANDROID__) && !defined(IOS)
  202. fprintf(error ? stderr : stdout, "%s\n", str.CString());
  203. #endif
  204. }
  205. const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument)
  206. {
  207. arguments.Clear();
  208. unsigned cmdStart = 0, cmdEnd = 0;
  209. bool inCmd = false;
  210. bool inQuote = false;
  211. for (unsigned i = 0; i < cmdLine.Length(); ++i)
  212. {
  213. if (cmdLine[i] == '\"')
  214. inQuote = !inQuote;
  215. if (cmdLine[i] == ' ' && !inQuote)
  216. {
  217. if (inCmd)
  218. {
  219. inCmd = false;
  220. cmdEnd = i;
  221. // Do not store the first argument (executable name)
  222. if (!skipFirstArgument)
  223. arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));
  224. skipFirstArgument = false;
  225. }
  226. }
  227. else
  228. {
  229. if (!inCmd)
  230. {
  231. inCmd = true;
  232. cmdStart = i;
  233. }
  234. }
  235. }
  236. if (inCmd)
  237. {
  238. cmdEnd = cmdLine.Length();
  239. if (!skipFirstArgument)
  240. arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));
  241. }
  242. // Strip double quotes from the arguments
  243. for (unsigned i = 0; i < arguments.Size(); ++i)
  244. arguments[i].Replace("\"", "");
  245. return arguments;
  246. }
  247. const Vector<String>& ParseArguments(const char* cmdLine)
  248. {
  249. return ParseArguments(String(cmdLine));
  250. }
  251. const Vector<String>& ParseArguments(const WString& cmdLine)
  252. {
  253. return ParseArguments(String(cmdLine));
  254. }
  255. const Vector<String>& ParseArguments(const wchar_t* cmdLine)
  256. {
  257. return ParseArguments(String(cmdLine));
  258. }
  259. const Vector<String>& ParseArguments(int argc, char** argv)
  260. {
  261. String cmdLine;
  262. for (int i = 0; i < argc; ++i)
  263. cmdLine.AppendWithFormat("\"%s\" ", (const char*)argv[i]);
  264. return ParseArguments(cmdLine);
  265. }
  266. const Vector<String>& GetArguments()
  267. {
  268. return arguments;
  269. }
  270. String GetConsoleInput()
  271. {
  272. String ret;
  273. #ifdef URHO3D_TESTING
  274. // When we are running automated tests, reading the console may block. Just return empty in that case
  275. return ret;
  276. #else
  277. #ifdef _WIN32
  278. HANDLE input = GetStdHandle(STD_INPUT_HANDLE);
  279. HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
  280. if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)
  281. return ret;
  282. // Use char-based input
  283. SetConsoleMode(input, ENABLE_PROCESSED_INPUT);
  284. INPUT_RECORD record;
  285. DWORD events = 0;
  286. DWORD readEvents = 0;
  287. if (!GetNumberOfConsoleInputEvents(input, &events))
  288. return ret;
  289. while (events--)
  290. {
  291. ReadConsoleInputW(input, &record, 1, &readEvents);
  292. if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
  293. {
  294. unsigned c = record.Event.KeyEvent.uChar.UnicodeChar;
  295. if (c)
  296. {
  297. if (c == '\b')
  298. {
  299. PrintUnicode("\b \b");
  300. int length = currentLine.LengthUTF8();
  301. if (length)
  302. currentLine = currentLine.SubstringUTF8(0, length - 1);
  303. }
  304. else if (c == '\r')
  305. {
  306. PrintUnicode("\n");
  307. ret = currentLine;
  308. currentLine.Clear();
  309. return ret;
  310. }
  311. else
  312. {
  313. // We have disabled echo, so echo manually
  314. wchar_t out = c;
  315. DWORD charsWritten;
  316. WriteConsoleW(output, &out, 1, &charsWritten, 0);
  317. currentLine.AppendUTF8(c);
  318. }
  319. }
  320. }
  321. }
  322. #elif !defined(__ANDROID__) && !defined(IOS)
  323. int flags = fcntl(STDIN_FILENO, F_GETFL);
  324. fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
  325. for (;;)
  326. {
  327. int ch = fgetc(stdin);
  328. if (ch >= 0 && ch != '\n')
  329. ret += (char)ch;
  330. else
  331. break;
  332. }
  333. #endif
  334. return ret;
  335. #endif
  336. }
  337. String GetPlatform()
  338. {
  339. #if defined(__ANDROID__)
  340. return "Android";
  341. #elif defined(IOS)
  342. return "iOS";
  343. #elif defined(_WIN32)
  344. return "Windows";
  345. #elif defined(__APPLE__)
  346. return "Mac OS X";
  347. #elif defined(RPI)
  348. return "Raspberry Pi";
  349. #elif defined(__EMSCRIPTEN__)
  350. return "Web";
  351. #elif defined(__linux__)
  352. return "Linux";
  353. #else
  354. return String::EMPTY;
  355. #endif
  356. }
  357. unsigned GetNumPhysicalCPUs()
  358. {
  359. #if defined(IOS)
  360. host_basic_info_data_t data;
  361. GetCPUData(&data);
  362. #if defined(TARGET_IPHONE_SIMULATOR)
  363. // Hardcoded to dual-core on simulator mode even if the host has more
  364. return Min(2, data.physical_cpu);
  365. #else
  366. return data.physical_cpu;
  367. #endif
  368. #elif defined(__linux__)
  369. struct CpuCoreCount data;
  370. GetCPUData(&data);
  371. return data.numPhysicalCores_;
  372. #elif defined(__EMSCRIPTEN__)
  373. #ifdef __EMSCRIPTEN_PTHREADS__
  374. return emscripten_num_logical_cores();
  375. #else
  376. return 1; // Targeting a single-threaded Emscripten build.
  377. #endif
  378. #else
  379. struct cpu_id_t data;
  380. GetCPUData(&data);
  381. return (unsigned)data.num_cores;
  382. #endif
  383. }
  384. unsigned GetNumLogicalCPUs()
  385. {
  386. #if defined(IOS)
  387. host_basic_info_data_t data;
  388. GetCPUData(&data);
  389. #if defined(TARGET_IPHONE_SIMULATOR)
  390. return Min(2, data.logical_cpu);
  391. #else
  392. return data.logical_cpu;
  393. #endif
  394. #elif defined(__linux__)
  395. struct CpuCoreCount data;
  396. GetCPUData(&data);
  397. return data.numLogicalCores_;
  398. #elif defined(__EMSCRIPTEN__)
  399. #ifdef __EMSCRIPTEN_PTHREADS__
  400. return emscripten_num_logical_cores();
  401. #else
  402. return 1; // Targeting a single-threaded Emscripten build.
  403. #endif
  404. #else
  405. struct cpu_id_t data;
  406. GetCPUData(&data);
  407. return (unsigned)data.num_logical_cpus;
  408. #endif
  409. }
  410. void SetMiniDumpDir(const String& pathName)
  411. {
  412. miniDumpDir = AddTrailingSlash(pathName);
  413. }
  414. String GetMiniDumpDir()
  415. {
  416. #ifndef MINI_URHO
  417. if (miniDumpDir.Empty())
  418. {
  419. char* pathName = SDL_GetPrefPath("urho3d", "crashdumps");
  420. if (pathName)
  421. {
  422. String ret(pathName);
  423. SDL_free(pathName);
  424. return ret;
  425. }
  426. }
  427. #endif
  428. return miniDumpDir;
  429. }
  430. unsigned long long GetTotalMemory()
  431. {
  432. #if defined(__linux__)
  433. struct sysinfo s;
  434. if(sysinfo(&s) != -1)
  435. return s.totalram;
  436. #elif defined(_WIN32)
  437. MEMORYSTATUSEX state;
  438. state.dwLength = sizeof(state);
  439. if(GlobalMemoryStatusEx(&state))
  440. return state.ullTotalPhys;
  441. #else
  442. #endif
  443. return 0ull;
  444. }
  445. }