ProcessUtils.cpp 12 KB

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