os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. gmtime_r(&t, &lt);
  168. } else {
  169. localtime_r(&t, &lt);
  170. }
  171. Date ret;
  172. ret.year = 1900 + lt.tm_year;
  173. // Index starting at 1 to match OS_Unix::get_date
  174. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  175. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  176. ret.month = (Month)(lt.tm_mon + 1);
  177. ret.day = lt.tm_mday;
  178. ret.weekday = (Weekday)lt.tm_wday;
  179. ret.dst = lt.tm_isdst;
  180. return ret;
  181. }
  182. OS::Time OS_Unix::get_time(bool utc) const {
  183. time_t t = time(NULL);
  184. struct tm lt;
  185. if (utc) {
  186. gmtime_r(&t, &lt);
  187. } else {
  188. localtime_r(&t, &lt);
  189. }
  190. Time ret;
  191. ret.hour = lt.tm_hour;
  192. ret.min = lt.tm_min;
  193. ret.sec = lt.tm_sec;
  194. get_time_zone_info();
  195. return ret;
  196. }
  197. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  198. time_t t = time(NULL);
  199. struct tm lt;
  200. localtime_r(&t, &lt);
  201. char name[16];
  202. strftime(name, 16, "%Z", &lt);
  203. name[15] = 0;
  204. TimeZoneInfo ret;
  205. ret.name = name;
  206. char bias_buf[16];
  207. strftime(bias_buf, 16, "%z", &lt);
  208. int bias;
  209. bias_buf[15] = 0;
  210. sscanf(bias_buf, "%d", &bias);
  211. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  212. int hour = (int)bias / 100;
  213. int minutes = bias % 100;
  214. if (bias < 0)
  215. ret.bias = hour * 60 - minutes;
  216. else
  217. ret.bias = hour * 60 + minutes;
  218. return ret;
  219. }
  220. void OS_Unix::delay_usec(uint32_t p_usec) const {
  221. struct timespec rem = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  222. while (nanosleep(&rem, &rem) == EINTR) {
  223. }
  224. }
  225. uint64_t OS_Unix::get_ticks_usec() const {
  226. #if defined(__APPLE__)
  227. uint64_t longtime = mach_absolute_time() * _clock_scale;
  228. #else
  229. // Unchecked return. Static analyzers might complain.
  230. // If _setup_clock() succeeded, we assume clock_gettime() works.
  231. struct timespec tv_now = { 0, 0 };
  232. clock_gettime(GODOT_CLOCK, &tv_now);
  233. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  234. #endif
  235. longtime -= _clock_start;
  236. return longtime;
  237. }
  238. 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) {
  239. #ifdef __EMSCRIPTEN__
  240. // Don't compile this code at all to avoid undefined references.
  241. // Actual virtual call goes to OS_JavaScript.
  242. ERR_FAIL_V(ERR_BUG);
  243. #else
  244. if (p_blocking && r_pipe) {
  245. String argss;
  246. argss = "\"" + p_path + "\"";
  247. for (int i = 0; i < p_arguments.size(); i++) {
  248. argss += String(" \"") + p_arguments[i] + "\"";
  249. }
  250. if (read_stderr) {
  251. argss += " 2>&1"; // Read stderr too
  252. } else {
  253. argss += " 2>/dev/null"; //silence stderr
  254. }
  255. FILE *f = popen(argss.utf8().get_data(), "r");
  256. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot pipe stream from process running with following arguments '" + argss + "'.");
  257. char buf[65535];
  258. while (fgets(buf, 65535, f)) {
  259. if (p_pipe_mutex) {
  260. p_pipe_mutex->lock();
  261. }
  262. (*r_pipe) += String::utf8(buf);
  263. if (p_pipe_mutex) {
  264. p_pipe_mutex->unlock();
  265. }
  266. }
  267. int rv = pclose(f);
  268. if (r_exitcode)
  269. *r_exitcode = WEXITSTATUS(rv);
  270. return OK;
  271. }
  272. pid_t pid = fork();
  273. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  274. if (pid == 0) {
  275. // is child
  276. if (!p_blocking) {
  277. // For non blocking calls, create a new session-ID so parent won't wait for it.
  278. // This ensures the process won't go zombie at end.
  279. setsid();
  280. }
  281. Vector<CharString> cs;
  282. cs.push_back(p_path.utf8());
  283. for (int i = 0; i < p_arguments.size(); i++)
  284. cs.push_back(p_arguments[i].utf8());
  285. Vector<char *> args;
  286. for (int i = 0; i < cs.size(); i++)
  287. args.push_back((char *)cs[i].get_data());
  288. args.push_back(0);
  289. execvp(p_path.utf8().get_data(), &args[0]);
  290. // still alive? something failed..
  291. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  292. raise(SIGKILL);
  293. }
  294. if (p_blocking) {
  295. int status;
  296. waitpid(pid, &status, 0);
  297. if (r_exitcode)
  298. *r_exitcode = WEXITSTATUS(status);
  299. } else {
  300. if (r_child_id)
  301. *r_child_id = pid;
  302. }
  303. return OK;
  304. #endif
  305. }
  306. Error OS_Unix::kill(const ProcessID &p_pid) {
  307. int ret = ::kill(p_pid, SIGKILL);
  308. if (!ret) {
  309. //avoid zombie process
  310. int st;
  311. ::waitpid(p_pid, &st, 0);
  312. }
  313. return ret ? ERR_INVALID_PARAMETER : OK;
  314. }
  315. int OS_Unix::get_process_id() const {
  316. return getpid();
  317. };
  318. bool OS_Unix::has_environment(const String &p_var) const {
  319. return getenv(p_var.utf8().get_data()) != NULL;
  320. }
  321. String OS_Unix::get_locale() const {
  322. if (!has_environment("LANG"))
  323. return "en";
  324. String locale = get_environment("LANG");
  325. int tp = locale.find(".");
  326. if (tp != -1)
  327. locale = locale.substr(0, tp);
  328. return locale;
  329. }
  330. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  331. String path = p_path;
  332. if (FileAccess::exists(path) && path.is_rel_path()) {
  333. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  334. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  335. path = "./" + path;
  336. }
  337. if (!FileAccess::exists(path)) {
  338. //this code exists so gdnative can load .so files from within the executable path
  339. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  340. }
  341. if (!FileAccess::exists(path)) {
  342. //this code exists so gdnative can load .so files from a standard unix location
  343. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  344. }
  345. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  346. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  347. return OK;
  348. }
  349. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  350. if (dlclose(p_library_handle)) {
  351. return FAILED;
  352. }
  353. return OK;
  354. }
  355. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  356. const char *error;
  357. dlerror(); // Clear existing errors
  358. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  359. error = dlerror();
  360. if (error != NULL) {
  361. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  362. return ERR_CANT_RESOLVE;
  363. }
  364. return OK;
  365. }
  366. Error OS_Unix::set_cwd(const String &p_cwd) {
  367. if (chdir(p_cwd.utf8().get_data()) != 0)
  368. return ERR_CANT_OPEN;
  369. return OK;
  370. }
  371. String OS_Unix::get_environment(const String &p_var) const {
  372. if (getenv(p_var.utf8().get_data()))
  373. return getenv(p_var.utf8().get_data());
  374. return "";
  375. }
  376. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  377. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  378. }
  379. int OS_Unix::get_processor_count() const {
  380. return sysconf(_SC_NPROCESSORS_CONF);
  381. }
  382. String OS_Unix::get_user_data_dir() const {
  383. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  384. if (appname != "") {
  385. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  386. if (use_custom_dir) {
  387. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  388. if (custom_dir == "") {
  389. custom_dir = appname;
  390. }
  391. return get_data_path().plus_file(custom_dir);
  392. } else {
  393. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  394. }
  395. }
  396. return ProjectSettings::get_singleton()->get_resource_path();
  397. }
  398. String OS_Unix::get_executable_path() const {
  399. #ifdef __linux__
  400. //fix for running from a symlink
  401. char buf[256];
  402. memset(buf, 0, 256);
  403. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  404. String b;
  405. if (len > 0) {
  406. b.parse_utf8(buf, len);
  407. }
  408. if (b == "") {
  409. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  410. return OS::get_executable_path();
  411. }
  412. return b;
  413. #elif defined(__OpenBSD__)
  414. char resolved_path[MAXPATHLEN];
  415. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  416. return String(resolved_path);
  417. #elif defined(__FreeBSD__)
  418. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  419. char buf[MAXPATHLEN];
  420. size_t len = sizeof(buf);
  421. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  422. WARN_PRINT("Couldn't get executable path from sysctl");
  423. return OS::get_executable_path();
  424. }
  425. String b;
  426. b.parse_utf8(buf);
  427. return b;
  428. #elif defined(__APPLE__)
  429. char temp_path[1];
  430. uint32_t buff_size = 1;
  431. _NSGetExecutablePath(temp_path, &buff_size);
  432. char *resolved_path = new char[buff_size + 1];
  433. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  434. WARN_PRINT("MAXPATHLEN is too small");
  435. String path(resolved_path);
  436. delete[] resolved_path;
  437. return path;
  438. #else
  439. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  440. return OS::get_executable_path();
  441. #endif
  442. }
  443. 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) {
  444. if (!should_log(true)) {
  445. return;
  446. }
  447. const char *err_details;
  448. if (p_rationale && p_rationale[0])
  449. err_details = p_rationale;
  450. else
  451. err_details = p_code;
  452. // Disable color codes if stdout is not a TTY.
  453. // This prevents Godot from writing ANSI escape codes when redirecting
  454. // stdout and stderr to a file.
  455. const bool tty = isatty(fileno(stdout));
  456. const char *red = tty ? "\E[0;31m" : "";
  457. const char *red_bold = tty ? "\E[1;31m" : "";
  458. const char *yellow = tty ? "\E[0;33m" : "";
  459. const char *yellow_bold = tty ? "\E[1;33m" : "";
  460. const char *magenta = tty ? "\E[0;35m" : "";
  461. const char *magenta_bold = tty ? "\E[1;35m" : "";
  462. const char *cyan = tty ? "\E[0;36m" : "";
  463. const char *cyan_bold = tty ? "\E[1;36m" : "";
  464. const char *reset = tty ? "\E[0m" : "";
  465. const char *bold = tty ? "\E[1m" : "";
  466. switch (p_type) {
  467. case ERR_WARNING:
  468. logf_error("%sWARNING: %s: %s%s%s\n", yellow_bold, p_function, reset, bold, err_details);
  469. logf_error("%s At: %s:%i.%s\n", yellow, p_file, p_line, reset);
  470. break;
  471. case ERR_SCRIPT:
  472. logf_error("%sSCRIPT ERROR: %s: %s%s%s\n", magenta_bold, p_function, reset, bold, err_details);
  473. logf_error("%s At: %s:%i.%s\n", magenta, p_file, p_line, reset);
  474. break;
  475. case ERR_SHADER:
  476. logf_error("%sSHADER ERROR: %s: %s%s%s\n", cyan_bold, p_function, reset, bold, err_details);
  477. logf_error("%s At: %s:%i.%s\n", cyan, p_file, p_line, reset);
  478. break;
  479. case ERR_ERROR:
  480. default:
  481. logf_error("%sERROR: %s: %s%s%s\n", red_bold, p_function, reset, bold, err_details);
  482. logf_error("%s At: %s:%i.%s\n", red, p_file, p_line, reset);
  483. break;
  484. }
  485. }
  486. UnixTerminalLogger::~UnixTerminalLogger() {}
  487. OS_Unix::OS_Unix() {
  488. Vector<Logger *> loggers;
  489. loggers.push_back(memnew(UnixTerminalLogger));
  490. _set_logger(memnew(CompositeLogger(loggers)));
  491. }
  492. #endif