ProcessUtils.cpp 11 KB

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