os_unix.cpp 17 KB

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