ProcessUtils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 "../Core/Mutex.h"
  23. #include "../Core/ProcessUtils.h"
  24. #include "../Math/MathDefs.h"
  25. #include <cstdio>
  26. #include <fcntl.h>
  27. #ifdef __APPLE__
  28. #include "TargetConditionals.h"
  29. #endif
  30. #if defined(IOS)
  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. }
  156. #else
  157. fprintf(error ? stderr : stdout, "%s", str.CString());
  158. #endif
  159. #endif
  160. }
  161. void PrintUnicodeLine(const String& str, bool error)
  162. {
  163. PrintUnicode(str + '\n', error);
  164. }
  165. void PrintLine(const String& str, bool error)
  166. {
  167. #if !defined(ANDROID) && !defined(IOS)
  168. fprintf(error ? stderr: stdout, "%s\n", str.CString());
  169. #endif
  170. }
  171. const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument)
  172. {
  173. arguments.Clear();
  174. unsigned cmdStart = 0, cmdEnd = 0;
  175. bool inCmd = false;
  176. bool inQuote = false;
  177. for (unsigned i = 0; i < cmdLine.Length(); ++i)
  178. {
  179. if (cmdLine[i] == '\"')
  180. inQuote = !inQuote;
  181. if (cmdLine[i] == ' ' && !inQuote)
  182. {
  183. if (inCmd)
  184. {
  185. inCmd = false;
  186. cmdEnd = i;
  187. // Do not store the first argument (executable name)
  188. if (!skipFirstArgument)
  189. arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));
  190. skipFirstArgument = false;
  191. }
  192. }
  193. else
  194. {
  195. if (!inCmd)
  196. {
  197. inCmd = true;
  198. cmdStart = i;
  199. }
  200. }
  201. }
  202. if (inCmd)
  203. {
  204. cmdEnd = cmdLine.Length();
  205. if (!skipFirstArgument)
  206. arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));
  207. }
  208. // Strip double quotes from the arguments
  209. for (unsigned i = 0; i < arguments.Size(); ++i)
  210. arguments[i].Replace("\"", "");
  211. return arguments;
  212. }
  213. const Vector<String>& ParseArguments(const char* cmdLine)
  214. {
  215. return ParseArguments(String(cmdLine));
  216. }
  217. const Vector<String>& ParseArguments(const WString& cmdLine)
  218. {
  219. return ParseArguments(String(cmdLine));
  220. }
  221. const Vector<String>& ParseArguments(const wchar_t* cmdLine)
  222. {
  223. return ParseArguments(String(cmdLine));
  224. }
  225. const Vector<String>& ParseArguments(int argc, char** argv)
  226. {
  227. String cmdLine;
  228. for (int i = 0; i < argc; ++i)
  229. cmdLine.AppendWithFormat("\"%s\" ", (const char*)argv[i]);
  230. return ParseArguments(cmdLine);
  231. }
  232. const Vector<String>& GetArguments()
  233. {
  234. return arguments;
  235. }
  236. String GetConsoleInput()
  237. {
  238. String ret;
  239. #ifdef ATOMIC_TESTING
  240. // When we are running automated tests, reading the console may block. Just return empty in that case
  241. return ret;
  242. #endif
  243. #ifdef WIN32
  244. HANDLE input = GetStdHandle(STD_INPUT_HANDLE);
  245. HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
  246. if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)
  247. return ret;
  248. // Use char-based input
  249. SetConsoleMode(input, ENABLE_PROCESSED_INPUT);
  250. INPUT_RECORD record;
  251. DWORD events = 0;
  252. DWORD readEvents = 0;
  253. if (!GetNumberOfConsoleInputEvents(input, &events))
  254. return ret;
  255. while (events--)
  256. {
  257. ReadConsoleInputW(input, &record, 1, &readEvents);
  258. if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
  259. {
  260. unsigned c = record.Event.KeyEvent.uChar.UnicodeChar;
  261. if (c)
  262. {
  263. if (c == '\b')
  264. {
  265. PrintUnicode("\b \b");
  266. int length = currentLine.LengthUTF8();
  267. if (length)
  268. currentLine = currentLine.SubstringUTF8(0, length - 1);
  269. }
  270. else if (c == '\r')
  271. {
  272. PrintUnicode("\n");
  273. ret = currentLine;
  274. currentLine.Clear();
  275. return ret;
  276. }
  277. else
  278. {
  279. // We have disabled echo, so echo manually
  280. wchar_t out = c;
  281. DWORD charsWritten;
  282. WriteConsoleW(output, &out, 1, &charsWritten, 0);
  283. currentLine.AppendUTF8(c);
  284. }
  285. }
  286. }
  287. }
  288. #elif !defined(ANDROID) && !defined(IOS)
  289. int flags = fcntl(STDIN_FILENO, F_GETFL);
  290. fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
  291. for (;;)
  292. {
  293. int ch = fgetc(stdin);
  294. if (ch >= 0 && ch != '\n')
  295. ret += (char)ch;
  296. else
  297. break;
  298. }
  299. #endif
  300. return ret;
  301. }
  302. String GetPlatform()
  303. {
  304. #if defined(ANDROID)
  305. return "Android";
  306. #elif defined(IOS)
  307. return "iOS";
  308. #elif defined(WIN32)
  309. return "Windows";
  310. #elif defined(__APPLE__)
  311. return "Mac OS X";
  312. #elif defined(RPI)
  313. return "Raspberry Pi";
  314. #elif defined(EMSCRIPTEN)
  315. return "HTML5";
  316. #elif defined(__linux__)
  317. return "Linux";
  318. #else
  319. return String::EMPTY;
  320. #endif
  321. }
  322. #if defined(ANDROID) || defined(RPI)
  323. static unsigned GetArmCPUCount()
  324. {
  325. FILE* fp;
  326. int res, i = -1, j = -1;
  327. fp = fopen("/sys/devices/system/cpu/present", "r");
  328. // If failed, return at least 1
  329. if (fp == 0)
  330. return 1;
  331. res = fscanf(fp, "%d-%d", &i, &j);
  332. fclose(fp);
  333. if (res == 1 && i == 0)
  334. return 1;
  335. else if (res == 2 && i == 0)
  336. return j + 1;
  337. // If failed, return at least 1
  338. return 1;
  339. }
  340. #endif
  341. unsigned GetNumPhysicalCPUs()
  342. {
  343. #if defined(IOS)
  344. host_basic_info_data_t data;
  345. GetCPUData(&data);
  346. #if defined(TARGET_IPHONE_SIMULATOR)
  347. // Hardcoded to dual-core on simulator mode even if the host has more
  348. return Min(2, data.physical_cpu);
  349. #else
  350. return data.physical_cpu;
  351. #endif
  352. #elif defined(ANDROID) || defined(RPI)
  353. return GetArmCPUCount();
  354. #elif !defined(EMSCRIPTEN)
  355. struct cpu_id_t data;
  356. GetCPUData(&data);
  357. return data.num_cores;
  358. #else
  359. /// \todo Implement properly
  360. return 1;
  361. #endif
  362. }
  363. unsigned GetNumLogicalCPUs()
  364. {
  365. #if defined(IOS)
  366. host_basic_info_data_t data;
  367. GetCPUData(&data);
  368. #if defined(TARGET_IPHONE_SIMULATOR)
  369. return Min(2, data.logical_cpu);
  370. #else
  371. return data.logical_cpu;
  372. #endif
  373. #elif defined(ANDROID) || defined (RPI)
  374. return GetArmCPUCount();
  375. #elif !defined(EMSCRIPTEN)
  376. struct cpu_id_t data;
  377. GetCPUData(&data);
  378. return data.num_logical_cpus;
  379. #else
  380. /// \todo Implement properly
  381. return 1;
  382. #endif
  383. }
  384. }