ProcessUtils.cpp 16 KB

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