os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /*************************************************************************/
  2. /* os_unix.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os_unix.h"
  31. #ifdef UNIX_ENABLED
  32. #include "core/os/thread_dummy.h"
  33. #include "core/project_settings.h"
  34. #include "drivers/unix/dir_access_unix.h"
  35. #include "drivers/unix/file_access_unix.h"
  36. #include "drivers/unix/mutex_posix.h"
  37. #include "drivers/unix/net_socket_posix.h"
  38. #include "drivers/unix/rw_lock_posix.h"
  39. #include "drivers/unix/semaphore_posix.h"
  40. #include "drivers/unix/thread_posix.h"
  41. #include "servers/visual_server.h"
  42. #ifdef __APPLE__
  43. #include <mach-o/dyld.h>
  44. #include <mach/mach_time.h>
  45. #endif
  46. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  47. #include <sys/param.h>
  48. #include <sys/sysctl.h>
  49. #endif
  50. #include <assert.h>
  51. #include <dlfcn.h>
  52. #include <errno.h>
  53. #include <poll.h>
  54. #include <signal.h>
  55. #include <stdarg.h>
  56. #include <stdio.h>
  57. #include <stdlib.h>
  58. #include <string.h>
  59. #include <sys/time.h>
  60. #include <sys/wait.h>
  61. #include <unistd.h>
  62. /// Clock Setup function (used by get_ticks_usec)
  63. static uint64_t _clock_start = 0;
  64. #if defined(__APPLE__)
  65. static double _clock_scale = 0;
  66. static void _setup_clock() {
  67. mach_timebase_info_data_t info;
  68. kern_return_t ret = mach_timebase_info(&info);
  69. ERR_FAIL_COND_MSG(ret != 0, "OS CLOCK IS NOT WORKING!");
  70. _clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
  71. _clock_start = mach_absolute_time() * _clock_scale;
  72. }
  73. #else
  74. #if defined(CLOCK_MONOTONIC_RAW) && !defined(JAVASCRIPT_ENABLED) // This is a better clock on Linux.
  75. #define GODOT_CLOCK CLOCK_MONOTONIC_RAW
  76. #else
  77. #define GODOT_CLOCK CLOCK_MONOTONIC
  78. #endif
  79. static void _setup_clock() {
  80. struct timespec tv_now = { 0, 0 };
  81. ERR_FAIL_COND_MSG(clock_gettime(GODOT_CLOCK, &tv_now) != 0, "OS CLOCK IS NOT WORKING!");
  82. _clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  83. }
  84. #endif
  85. void OS_Unix::debug_break() {
  86. assert(false);
  87. };
  88. static void handle_interrupt(int sig) {
  89. if (ScriptDebugger::get_singleton() == NULL)
  90. return;
  91. ScriptDebugger::get_singleton()->set_depth(-1);
  92. ScriptDebugger::get_singleton()->set_lines_left(1);
  93. }
  94. void OS_Unix::initialize_debugging() {
  95. if (ScriptDebugger::get_singleton() != NULL) {
  96. struct sigaction action;
  97. memset(&action, 0, sizeof(action));
  98. action.sa_handler = handle_interrupt;
  99. sigaction(SIGINT, &action, NULL);
  100. }
  101. }
  102. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  103. return 0;
  104. }
  105. void OS_Unix::initialize_core() {
  106. #ifdef NO_THREADS
  107. ThreadDummy::make_default();
  108. SemaphoreDummy::make_default();
  109. MutexDummy::make_default();
  110. RWLockDummy::make_default();
  111. #else
  112. ThreadPosix::make_default();
  113. #if !defined(OSX_ENABLED) && !defined(IPHONE_ENABLED)
  114. SemaphorePosix::make_default();
  115. #endif
  116. MutexPosix::make_default();
  117. RWLockPosix::make_default();
  118. #endif
  119. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  120. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  121. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  122. //FileAccessBufferedFA<FileAccessUnix>::make_default();
  123. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  124. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  125. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  126. #ifndef NO_NETWORK
  127. NetSocketPosix::make_default();
  128. IP_Unix::make_default();
  129. #endif
  130. _setup_clock();
  131. }
  132. void OS_Unix::finalize_core() {
  133. NetSocketPosix::cleanup();
  134. }
  135. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  136. fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
  137. }
  138. String OS_Unix::get_stdin_string(bool p_block) {
  139. if (p_block) {
  140. char buff[1024];
  141. String ret = stdin_buf + fgets(buff, 1024, stdin);
  142. stdin_buf = "";
  143. return ret;
  144. }
  145. return "";
  146. }
  147. String OS_Unix::get_name() const {
  148. return "Unix";
  149. }
  150. uint64_t OS_Unix::get_unix_time() const {
  151. return time(NULL);
  152. };
  153. uint64_t OS_Unix::get_system_time_secs() const {
  154. struct timeval tv_now;
  155. gettimeofday(&tv_now, NULL);
  156. return uint64_t(tv_now.tv_sec);
  157. }
  158. uint64_t OS_Unix::get_system_time_msecs() const {
  159. struct timeval tv_now;
  160. gettimeofday(&tv_now, NULL);
  161. return uint64_t(tv_now.tv_sec) * 1000 + uint64_t(tv_now.tv_usec) / 1000;
  162. }
  163. OS::Date OS_Unix::get_date(bool utc) const {
  164. time_t t = time(NULL);
  165. struct tm *lt;
  166. if (utc)
  167. lt = gmtime(&t);
  168. else
  169. lt = localtime(&t);
  170. Date ret;
  171. ret.year = 1900 + lt->tm_year;
  172. // Index starting at 1 to match OS_Unix::get_date
  173. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  174. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  175. ret.month = (Month)(lt->tm_mon + 1);
  176. ret.day = lt->tm_mday;
  177. ret.weekday = (Weekday)lt->tm_wday;
  178. ret.dst = lt->tm_isdst;
  179. return ret;
  180. }
  181. OS::Time OS_Unix::get_time(bool utc) const {
  182. time_t t = time(NULL);
  183. struct tm *lt;
  184. if (utc)
  185. lt = gmtime(&t);
  186. else
  187. lt = localtime(&t);
  188. Time ret;
  189. ret.hour = lt->tm_hour;
  190. ret.min = lt->tm_min;
  191. ret.sec = lt->tm_sec;
  192. get_time_zone_info();
  193. return ret;
  194. }
  195. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  196. time_t t = time(NULL);
  197. struct tm *lt = localtime(&t);
  198. char name[16];
  199. strftime(name, 16, "%Z", lt);
  200. name[15] = 0;
  201. TimeZoneInfo ret;
  202. ret.name = name;
  203. char bias_buf[16];
  204. strftime(bias_buf, 16, "%z", lt);
  205. int bias;
  206. bias_buf[15] = 0;
  207. sscanf(bias_buf, "%d", &bias);
  208. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  209. int hour = (int)bias / 100;
  210. int minutes = bias % 100;
  211. if (bias < 0)
  212. ret.bias = hour * 60 - minutes;
  213. else
  214. ret.bias = hour * 60 + minutes;
  215. return ret;
  216. }
  217. void OS_Unix::delay_usec(uint32_t p_usec) const {
  218. struct timespec rem = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  219. while (nanosleep(&rem, &rem) == EINTR) {
  220. }
  221. }
  222. uint64_t OS_Unix::get_ticks_usec() const {
  223. #if defined(__APPLE__)
  224. uint64_t longtime = mach_absolute_time() * _clock_scale;
  225. #else
  226. // Unchecked return. Static analyzers might complain.
  227. // If _setup_clock() succeeded, we assume clock_gettime() works.
  228. struct timespec tv_now = { 0, 0 };
  229. clock_gettime(GODOT_CLOCK, &tv_now);
  230. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  231. #endif
  232. longtime -= _clock_start;
  233. return longtime;
  234. }
  235. Error OS_Unix::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex) {
  236. #ifdef __EMSCRIPTEN__
  237. // Don't compile this code at all to avoid undefined references.
  238. // Actual virtual call goes to OS_JavaScript.
  239. ERR_FAIL_V(ERR_BUG);
  240. #else
  241. if (p_blocking && r_pipe) {
  242. String argss;
  243. argss = "\"" + p_path + "\"";
  244. for (int i = 0; i < p_arguments.size(); i++) {
  245. argss += String(" \"") + p_arguments[i] + "\"";
  246. }
  247. if (read_stderr) {
  248. argss += " 2>&1"; // Read stderr too
  249. } else {
  250. argss += " 2>/dev/null"; //silence stderr
  251. }
  252. FILE *f = popen(argss.utf8().get_data(), "r");
  253. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot pipe stream from process running with following arguments '" + argss + "'.");
  254. char buf[65535];
  255. while (fgets(buf, 65535, f)) {
  256. if (p_pipe_mutex) {
  257. p_pipe_mutex->lock();
  258. }
  259. (*r_pipe) += String::utf8(buf);
  260. if (p_pipe_mutex) {
  261. p_pipe_mutex->unlock();
  262. }
  263. }
  264. int rv = pclose(f);
  265. if (r_exitcode)
  266. *r_exitcode = WEXITSTATUS(rv);
  267. return OK;
  268. }
  269. pid_t pid = fork();
  270. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  271. if (pid == 0) {
  272. // is child
  273. if (!p_blocking) {
  274. // For non blocking calls, create a new session-ID so parent won't wait for it.
  275. // This ensures the process won't go zombie at end.
  276. setsid();
  277. }
  278. Vector<CharString> cs;
  279. cs.push_back(p_path.utf8());
  280. for (int i = 0; i < p_arguments.size(); i++)
  281. cs.push_back(p_arguments[i].utf8());
  282. Vector<char *> args;
  283. for (int i = 0; i < cs.size(); i++)
  284. args.push_back((char *)cs[i].get_data());
  285. args.push_back(0);
  286. execvp(p_path.utf8().get_data(), &args[0]);
  287. // still alive? something failed..
  288. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  289. raise(SIGKILL);
  290. }
  291. if (p_blocking) {
  292. int status;
  293. waitpid(pid, &status, 0);
  294. if (r_exitcode)
  295. *r_exitcode = WEXITSTATUS(status);
  296. } else {
  297. if (r_child_id)
  298. *r_child_id = pid;
  299. }
  300. return OK;
  301. #endif
  302. }
  303. Error OS_Unix::kill(const ProcessID &p_pid) {
  304. int ret = ::kill(p_pid, SIGKILL);
  305. if (!ret) {
  306. //avoid zombie process
  307. int st;
  308. ::waitpid(p_pid, &st, 0);
  309. }
  310. return ret ? ERR_INVALID_PARAMETER : OK;
  311. }
  312. int OS_Unix::get_process_id() const {
  313. return getpid();
  314. };
  315. bool OS_Unix::has_environment(const String &p_var) const {
  316. return getenv(p_var.utf8().get_data()) != NULL;
  317. }
  318. String OS_Unix::get_locale() const {
  319. if (!has_environment("LANG"))
  320. return "en";
  321. String locale = get_environment("LANG");
  322. int tp = locale.find(".");
  323. if (tp != -1)
  324. locale = locale.substr(0, tp);
  325. return locale;
  326. }
  327. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  328. String path = p_path;
  329. if (FileAccess::exists(path) && path.is_rel_path()) {
  330. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  331. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  332. path = "./" + path;
  333. }
  334. if (!FileAccess::exists(path)) {
  335. //this code exists so gdnative can load .so files from within the executable path
  336. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  337. }
  338. if (!FileAccess::exists(path)) {
  339. //this code exists so gdnative can load .so files from a standard unix location
  340. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  341. }
  342. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  343. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  344. return OK;
  345. }
  346. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  347. if (dlclose(p_library_handle)) {
  348. return FAILED;
  349. }
  350. return OK;
  351. }
  352. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  353. const char *error;
  354. dlerror(); // Clear existing errors
  355. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  356. error = dlerror();
  357. if (error != NULL) {
  358. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  359. return ERR_CANT_RESOLVE;
  360. }
  361. return OK;
  362. }
  363. Error OS_Unix::set_cwd(const String &p_cwd) {
  364. if (chdir(p_cwd.utf8().get_data()) != 0)
  365. return ERR_CANT_OPEN;
  366. return OK;
  367. }
  368. String OS_Unix::get_environment(const String &p_var) const {
  369. if (getenv(p_var.utf8().get_data()))
  370. return getenv(p_var.utf8().get_data());
  371. return "";
  372. }
  373. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  374. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  375. }
  376. int OS_Unix::get_processor_count() const {
  377. return sysconf(_SC_NPROCESSORS_CONF);
  378. }
  379. String OS_Unix::get_user_data_dir() const {
  380. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  381. if (appname != "") {
  382. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  383. if (use_custom_dir) {
  384. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  385. if (custom_dir == "") {
  386. custom_dir = appname;
  387. }
  388. return get_data_path().plus_file(custom_dir);
  389. } else {
  390. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  391. }
  392. }
  393. return ProjectSettings::get_singleton()->get_resource_path();
  394. }
  395. String OS_Unix::get_executable_path() const {
  396. #ifdef __linux__
  397. //fix for running from a symlink
  398. char buf[256];
  399. memset(buf, 0, 256);
  400. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  401. String b;
  402. if (len > 0) {
  403. b.parse_utf8(buf, len);
  404. }
  405. if (b == "") {
  406. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  407. return OS::get_executable_path();
  408. }
  409. return b;
  410. #elif defined(__OpenBSD__)
  411. char resolved_path[MAXPATHLEN];
  412. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  413. return String(resolved_path);
  414. #elif defined(__FreeBSD__)
  415. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  416. char buf[MAXPATHLEN];
  417. size_t len = sizeof(buf);
  418. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  419. WARN_PRINT("Couldn't get executable path from sysctl");
  420. return OS::get_executable_path();
  421. }
  422. String b;
  423. b.parse_utf8(buf);
  424. return b;
  425. #elif defined(__APPLE__)
  426. char temp_path[1];
  427. uint32_t buff_size = 1;
  428. _NSGetExecutablePath(temp_path, &buff_size);
  429. char *resolved_path = new char[buff_size + 1];
  430. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  431. WARN_PRINT("MAXPATHLEN is too small");
  432. String path(resolved_path);
  433. delete[] resolved_path;
  434. return path;
  435. #else
  436. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  437. return OS::get_executable_path();
  438. #endif
  439. }
  440. void UnixTerminalLogger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
  441. if (!should_log(true)) {
  442. return;
  443. }
  444. const char *err_details;
  445. if (p_rationale && p_rationale[0])
  446. err_details = p_rationale;
  447. else
  448. err_details = p_code;
  449. // Disable color codes if stdout is not a TTY.
  450. // This prevents Godot from writing ANSI escape codes when redirecting
  451. // stdout and stderr to a file.
  452. const bool tty = isatty(fileno(stdout));
  453. const char *red = tty ? "\E[0;31m" : "";
  454. const char *red_bold = tty ? "\E[1;31m" : "";
  455. const char *yellow = tty ? "\E[0;33m" : "";
  456. const char *yellow_bold = tty ? "\E[1;33m" : "";
  457. const char *magenta = tty ? "\E[0;35m" : "";
  458. const char *magenta_bold = tty ? "\E[1;35m" : "";
  459. const char *cyan = tty ? "\E[0;36m" : "";
  460. const char *cyan_bold = tty ? "\E[1;36m" : "";
  461. const char *reset = tty ? "\E[0m" : "";
  462. const char *bold = tty ? "\E[1m" : "";
  463. switch (p_type) {
  464. case ERR_WARNING:
  465. logf_error("%sWARNING: %s: %s%s%s\n", yellow_bold, p_function, reset, bold, err_details);
  466. logf_error("%s At: %s:%i.%s\n", yellow, p_file, p_line, reset);
  467. break;
  468. case ERR_SCRIPT:
  469. logf_error("%sSCRIPT ERROR: %s: %s%s%s\n", magenta_bold, p_function, reset, bold, err_details);
  470. logf_error("%s At: %s:%i.%s\n", magenta, p_file, p_line, reset);
  471. break;
  472. case ERR_SHADER:
  473. logf_error("%sSHADER ERROR: %s: %s%s%s\n", cyan_bold, p_function, reset, bold, err_details);
  474. logf_error("%s At: %s:%i.%s\n", cyan, p_file, p_line, reset);
  475. break;
  476. case ERR_ERROR:
  477. default:
  478. logf_error("%sERROR: %s: %s%s%s\n", red_bold, p_function, reset, bold, err_details);
  479. logf_error("%s At: %s:%i.%s\n", red, p_file, p_line, reset);
  480. break;
  481. }
  482. }
  483. UnixTerminalLogger::~UnixTerminalLogger() {}
  484. OS_Unix::OS_Unix() {
  485. Vector<Logger *> loggers;
  486. loggers.push_back(memnew(UnixTerminalLogger));
  487. _set_logger(memnew(CompositeLogger(loggers)));
  488. }
  489. #endif