ProcessUtils.cpp 16 KB

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