ProcessUtils.cpp 11 KB

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