os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /*************************************************************************/
  2. /* os_unix.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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/config/project_settings.h"
  33. #include "core/debugger/engine_debugger.h"
  34. #include "core/debugger/script_debugger.h"
  35. #include "core/os/thread_dummy.h"
  36. #include "drivers/unix/dir_access_unix.h"
  37. #include "drivers/unix/file_access_unix.h"
  38. #include "drivers/unix/net_socket_posix.h"
  39. #include "drivers/unix/rw_lock_posix.h"
  40. #include "drivers/unix/thread_posix.h"
  41. #include "servers/rendering_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__) || defined(__NetBSD__)
  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 (!EngineDebugger::is_active()) {
  90. return;
  91. }
  92. EngineDebugger::get_script_debugger()->set_depth(-1);
  93. EngineDebugger::get_script_debugger()->set_lines_left(1);
  94. }
  95. void OS_Unix::initialize_debugging() {
  96. if (EngineDebugger::is_active()) {
  97. struct sigaction action;
  98. memset(&action, 0, sizeof(action));
  99. action.sa_handler = handle_interrupt;
  100. sigaction(SIGINT, &action, nullptr);
  101. }
  102. }
  103. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  104. return 0;
  105. }
  106. void OS_Unix::initialize_core() {
  107. #ifdef NO_THREADS
  108. ThreadDummy::make_default();
  109. RWLockDummy::make_default();
  110. #else
  111. ThreadPosix::make_default();
  112. RWLockPosix::make_default();
  113. #endif
  114. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  115. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  116. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  117. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  118. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  119. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  120. #ifndef NO_NETWORK
  121. NetSocketPosix::make_default();
  122. IP_Unix::make_default();
  123. #endif
  124. _setup_clock();
  125. }
  126. void OS_Unix::finalize_core() {
  127. NetSocketPosix::cleanup();
  128. }
  129. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  130. fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
  131. }
  132. String OS_Unix::get_stdin_string(bool p_block) {
  133. if (p_block) {
  134. char buff[1024];
  135. String ret = stdin_buf + fgets(buff, 1024, stdin);
  136. stdin_buf = "";
  137. return ret;
  138. }
  139. return "";
  140. }
  141. String OS_Unix::get_name() const {
  142. return "Unix";
  143. }
  144. double OS_Unix::get_unix_time() const {
  145. struct timeval tv_now;
  146. gettimeofday(&tv_now, nullptr);
  147. return (double)tv_now.tv_sec + double(tv_now.tv_usec) / 1000000;
  148. };
  149. OS::Date OS_Unix::get_date(bool utc) const {
  150. time_t t = time(nullptr);
  151. struct tm lt;
  152. if (utc) {
  153. gmtime_r(&t, &lt);
  154. } else {
  155. localtime_r(&t, &lt);
  156. }
  157. Date ret;
  158. ret.year = 1900 + lt.tm_year;
  159. // Index starting at 1 to match OS_Unix::get_date
  160. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  161. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  162. ret.month = (Month)(lt.tm_mon + 1);
  163. ret.day = lt.tm_mday;
  164. ret.weekday = (Weekday)lt.tm_wday;
  165. ret.dst = lt.tm_isdst;
  166. return ret;
  167. }
  168. OS::Time OS_Unix::get_time(bool utc) const {
  169. time_t t = time(nullptr);
  170. struct tm lt;
  171. if (utc) {
  172. gmtime_r(&t, &lt);
  173. } else {
  174. localtime_r(&t, &lt);
  175. }
  176. Time ret;
  177. ret.hour = lt.tm_hour;
  178. ret.min = lt.tm_min;
  179. ret.sec = lt.tm_sec;
  180. get_time_zone_info();
  181. return ret;
  182. }
  183. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  184. time_t t = time(nullptr);
  185. struct tm lt;
  186. localtime_r(&t, &lt);
  187. char name[16];
  188. strftime(name, 16, "%Z", &lt);
  189. name[15] = 0;
  190. TimeZoneInfo ret;
  191. ret.name = name;
  192. char bias_buf[16];
  193. strftime(bias_buf, 16, "%z", &lt);
  194. int bias;
  195. bias_buf[15] = 0;
  196. sscanf(bias_buf, "%d", &bias);
  197. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  198. int hour = (int)bias / 100;
  199. int minutes = bias % 100;
  200. if (bias < 0) {
  201. ret.bias = hour * 60 - minutes;
  202. } else {
  203. ret.bias = hour * 60 + minutes;
  204. }
  205. return ret;
  206. }
  207. void OS_Unix::delay_usec(uint32_t p_usec) const {
  208. struct timespec rem = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  209. while (nanosleep(&rem, &rem) == EINTR) {
  210. }
  211. }
  212. uint64_t OS_Unix::get_ticks_usec() const {
  213. #if defined(__APPLE__)
  214. uint64_t longtime = mach_absolute_time() * _clock_scale;
  215. #else
  216. // Unchecked return. Static analyzers might complain.
  217. // If _setup_clock() succeeded, we assume clock_gettime() works.
  218. struct timespec tv_now = { 0, 0 };
  219. clock_gettime(GODOT_CLOCK, &tv_now);
  220. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  221. #endif
  222. longtime -= _clock_start;
  223. return longtime;
  224. }
  225. Error OS_Unix::execute(const String &p_path, const List<String> &p_arguments, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex) {
  226. #ifdef __EMSCRIPTEN__
  227. // Don't compile this code at all to avoid undefined references.
  228. // Actual virtual call goes to OS_JavaScript.
  229. ERR_FAIL_V(ERR_BUG);
  230. #else
  231. if (r_pipe) {
  232. String command = "\"" + p_path + "\"";
  233. for (int i = 0; i < p_arguments.size(); i++) {
  234. command += String(" \"") + p_arguments[i] + "\"";
  235. }
  236. if (read_stderr) {
  237. command += " 2>&1"; // Include stderr
  238. } else {
  239. command += " 2>/dev/null"; // Silence stderr
  240. }
  241. FILE *f = popen(command.utf8().get_data(), "r");
  242. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot create pipe from command: " + command);
  243. char buf[65535];
  244. while (fgets(buf, 65535, f)) {
  245. if (p_pipe_mutex) {
  246. p_pipe_mutex->lock();
  247. }
  248. (*r_pipe) += String::utf8(buf);
  249. if (p_pipe_mutex) {
  250. p_pipe_mutex->unlock();
  251. }
  252. }
  253. int rv = pclose(f);
  254. if (r_exitcode) {
  255. *r_exitcode = WEXITSTATUS(rv);
  256. }
  257. return OK;
  258. }
  259. pid_t pid = fork();
  260. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  261. if (pid == 0) {
  262. // The child process
  263. Vector<char *> args;
  264. args.push_back((char *)p_path.utf8().get_data());
  265. for (int i = 0; i < p_arguments.size(); i++) {
  266. args.push_back((char *)p_arguments[i].utf8().get_data());
  267. }
  268. args.push_back(0);
  269. execvp(p_path.utf8().get_data(), &args[0]);
  270. // The execvp() function only returns if an error occurs.
  271. CRASH_NOW_MSG("Could not create child process: " + p_path);
  272. }
  273. int status;
  274. waitpid(pid, &status, 0);
  275. if (r_exitcode) {
  276. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  277. }
  278. return OK;
  279. #endif
  280. }
  281. Error OS_Unix::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id) {
  282. #ifdef __EMSCRIPTEN__
  283. // Don't compile this code at all to avoid undefined references.
  284. // Actual virtual call goes to OS_JavaScript.
  285. ERR_FAIL_V(ERR_BUG);
  286. #else
  287. pid_t pid = fork();
  288. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  289. if (pid == 0) {
  290. // The new process
  291. // Create a new session-ID so parent won't wait for it.
  292. // This ensures the process won't go zombie at the end.
  293. setsid();
  294. Vector<char *> args;
  295. args.push_back((char *)p_path.utf8().get_data());
  296. for (int i = 0; i < p_arguments.size(); i++) {
  297. args.push_back((char *)p_arguments[i].utf8().get_data());
  298. }
  299. args.push_back(0);
  300. execvp(p_path.utf8().get_data(), &args[0]);
  301. // The execvp() function only returns if an error occurs.
  302. CRASH_NOW_MSG("Could not create child process: " + p_path);
  303. }
  304. if (r_child_id) {
  305. *r_child_id = pid;
  306. }
  307. return OK;
  308. #endif
  309. }
  310. Error OS_Unix::kill(const ProcessID &p_pid) {
  311. int ret = ::kill(p_pid, SIGKILL);
  312. if (!ret) {
  313. //avoid zombie process
  314. int st;
  315. ::waitpid(p_pid, &st, 0);
  316. }
  317. return ret ? ERR_INVALID_PARAMETER : OK;
  318. }
  319. int OS_Unix::get_process_id() const {
  320. return getpid();
  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. int OS_Unix::get_processor_count() const {
  388. return sysconf(_SC_NPROCESSORS_CONF);
  389. }
  390. String OS_Unix::get_user_data_dir() const {
  391. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  392. if (appname != "") {
  393. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  394. if (use_custom_dir) {
  395. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  396. if (custom_dir == "") {
  397. custom_dir = appname;
  398. }
  399. return get_data_path().plus_file(custom_dir);
  400. } else {
  401. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  402. }
  403. }
  404. return ProjectSettings::get_singleton()->get_resource_path();
  405. }
  406. String OS_Unix::get_executable_path() const {
  407. #ifdef __linux__
  408. //fix for running from a symlink
  409. char buf[256];
  410. memset(buf, 0, 256);
  411. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  412. String b;
  413. if (len > 0) {
  414. b.parse_utf8(buf, len);
  415. }
  416. if (b == "") {
  417. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  418. return OS::get_executable_path();
  419. }
  420. return b;
  421. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  422. char resolved_path[MAXPATHLEN];
  423. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  424. return String(resolved_path);
  425. #elif defined(__FreeBSD__)
  426. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  427. char buf[MAXPATHLEN];
  428. size_t len = sizeof(buf);
  429. if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0) {
  430. WARN_PRINT("Couldn't get executable path from sysctl");
  431. return OS::get_executable_path();
  432. }
  433. String b;
  434. b.parse_utf8(buf);
  435. return b;
  436. #elif defined(__APPLE__)
  437. char temp_path[1];
  438. uint32_t buff_size = 1;
  439. _NSGetExecutablePath(temp_path, &buff_size);
  440. char *resolved_path = new char[buff_size + 1];
  441. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  442. WARN_PRINT("MAXPATHLEN is too small");
  443. String path(resolved_path);
  444. delete[] resolved_path;
  445. return path;
  446. #else
  447. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  448. return OS::get_executable_path();
  449. #endif
  450. }
  451. 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) {
  452. if (!should_log(true)) {
  453. return;
  454. }
  455. const char *err_details;
  456. if (p_rationale && p_rationale[0]) {
  457. err_details = p_rationale;
  458. } else {
  459. err_details = p_code;
  460. }
  461. // Disable color codes if stdout is not a TTY.
  462. // This prevents Godot from writing ANSI escape codes when redirecting
  463. // stdout and stderr to a file.
  464. const bool tty = isatty(fileno(stdout));
  465. const char *gray = tty ? "\E[0;90m" : "";
  466. const char *red = tty ? "\E[0;91m" : "";
  467. const char *red_bold = tty ? "\E[1;31m" : "";
  468. const char *yellow = tty ? "\E[0;93m" : "";
  469. const char *yellow_bold = tty ? "\E[1;33m" : "";
  470. const char *magenta = tty ? "\E[0;95m" : "";
  471. const char *magenta_bold = tty ? "\E[1;35m" : "";
  472. const char *cyan = tty ? "\E[0;96m" : "";
  473. const char *cyan_bold = tty ? "\E[1;36m" : "";
  474. const char *reset = tty ? "\E[0m" : "";
  475. switch (p_type) {
  476. case ERR_WARNING:
  477. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  478. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  479. break;
  480. case ERR_SCRIPT:
  481. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  482. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  483. break;
  484. case ERR_SHADER:
  485. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, err_details);
  486. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  487. break;
  488. case ERR_ERROR:
  489. default:
  490. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  491. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  492. break;
  493. }
  494. }
  495. UnixTerminalLogger::~UnixTerminalLogger() {}
  496. OS_Unix::OS_Unix() {
  497. Vector<Logger *> loggers;
  498. loggers.push_back(memnew(UnixTerminalLogger));
  499. _set_logger(memnew(CompositeLogger(loggers)));
  500. }
  501. #endif