ProcessUtils.cpp 11 KB

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