ProcessUtils.cpp 13 KB

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