ProcessUtils.cpp 13 KB

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