ProcessUtils.cpp 12 KB

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