ProcessUtils.cpp 11 KB

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