os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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/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 <assert.h>
  47. #include <dlfcn.h>
  48. #include <errno.h>
  49. #include <poll.h>
  50. #include <signal.h>
  51. #include <stdarg.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <string.h>
  55. #include <sys/time.h>
  56. #include <sys/wait.h>
  57. #include <time.h>
  58. #include <unistd.h>
  59. /// Clock Setup function (used by get_ticks_usec)
  60. static uint64_t _clock_start = 0;
  61. #if defined(__APPLE__)
  62. static double _clock_scale = 0;
  63. static void _setup_clock() {
  64. mach_timebase_info_data_t info;
  65. kern_return_t ret = mach_timebase_info(&info);
  66. ERR_FAIL_COND_MSG(ret != 0, "OS CLOCK IS NOT WORKING!");
  67. _clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
  68. _clock_start = mach_absolute_time() * _clock_scale;
  69. }
  70. #else
  71. #if defined(CLOCK_MONOTONIC_RAW) && !defined(JAVASCRIPT_ENABLED) // This is a better clock on Linux.
  72. #define GODOT_CLOCK CLOCK_MONOTONIC_RAW
  73. #else
  74. #define GODOT_CLOCK CLOCK_MONOTONIC
  75. #endif
  76. static void _setup_clock() {
  77. struct timespec tv_now = { 0, 0 };
  78. ERR_FAIL_COND_MSG(clock_gettime(GODOT_CLOCK, &tv_now) != 0, "OS CLOCK IS NOT WORKING!");
  79. _clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  80. }
  81. #endif
  82. void OS_Unix::debug_break() {
  83. assert(false);
  84. };
  85. static void handle_interrupt(int sig) {
  86. if (ScriptDebugger::get_singleton() == nullptr) {
  87. return;
  88. }
  89. ScriptDebugger::get_singleton()->set_depth(-1);
  90. ScriptDebugger::get_singleton()->set_lines_left(1);
  91. }
  92. void OS_Unix::initialize_debugging() {
  93. if (ScriptDebugger::get_singleton() != nullptr) {
  94. struct sigaction action;
  95. memset(&action, 0, sizeof(action));
  96. action.sa_handler = handle_interrupt;
  97. sigaction(SIGINT, &action, nullptr);
  98. }
  99. }
  100. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  101. return 0;
  102. }
  103. void OS_Unix::initialize_core() {
  104. #if !defined(NO_THREADS)
  105. init_thread_posix();
  106. #endif
  107. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  108. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  109. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  110. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  111. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  112. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  113. #ifndef NO_NETWORK
  114. NetSocketPosix::make_default();
  115. IP_Unix::make_default();
  116. #endif
  117. _setup_clock();
  118. }
  119. void OS_Unix::finalize_core() {
  120. NetSocketPosix::cleanup();
  121. }
  122. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  123. fprintf(stderr, "ALERT: %s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  124. }
  125. String OS_Unix::get_stdin_string(bool p_block) {
  126. if (p_block) {
  127. char buff[1024];
  128. String ret = stdin_buf + fgets(buff, 1024, stdin);
  129. stdin_buf = "";
  130. return ret;
  131. }
  132. return "";
  133. }
  134. String OS_Unix::get_name() const {
  135. return "Unix";
  136. }
  137. uint64_t OS_Unix::get_unix_time() const {
  138. return time(nullptr);
  139. };
  140. uint64_t OS_Unix::get_system_time_secs() const {
  141. struct timeval tv_now;
  142. gettimeofday(&tv_now, nullptr);
  143. return uint64_t(tv_now.tv_sec);
  144. }
  145. uint64_t OS_Unix::get_system_time_msecs() const {
  146. struct timeval tv_now;
  147. gettimeofday(&tv_now, nullptr);
  148. return uint64_t(tv_now.tv_sec) * 1000 + uint64_t(tv_now.tv_usec) / 1000;
  149. }
  150. OS::Date OS_Unix::get_date(bool utc) const {
  151. time_t t = time(nullptr);
  152. struct tm lt;
  153. if (utc) {
  154. gmtime_r(&t, &lt);
  155. } else {
  156. localtime_r(&t, &lt);
  157. }
  158. Date ret;
  159. ret.year = 1900 + lt.tm_year;
  160. // Index starting at 1 to match OS_Unix::get_date
  161. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  162. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  163. ret.month = (Month)(lt.tm_mon + 1);
  164. ret.day = lt.tm_mday;
  165. ret.weekday = (Weekday)lt.tm_wday;
  166. ret.dst = lt.tm_isdst;
  167. return ret;
  168. }
  169. OS::Time OS_Unix::get_time(bool utc) const {
  170. time_t t = time(nullptr);
  171. struct tm lt;
  172. if (utc) {
  173. gmtime_r(&t, &lt);
  174. } else {
  175. localtime_r(&t, &lt);
  176. }
  177. Time ret;
  178. ret.hour = lt.tm_hour;
  179. ret.min = lt.tm_min;
  180. ret.sec = lt.tm_sec;
  181. get_time_zone_info();
  182. return ret;
  183. }
  184. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  185. time_t t = time(nullptr);
  186. struct tm lt;
  187. localtime_r(&t, &lt);
  188. char name[16];
  189. strftime(name, 16, "%Z", &lt);
  190. name[15] = 0;
  191. TimeZoneInfo ret;
  192. ret.name = name;
  193. char bias_buf[16];
  194. strftime(bias_buf, 16, "%z", &lt);
  195. int bias;
  196. bias_buf[15] = 0;
  197. sscanf(bias_buf, "%d", &bias);
  198. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  199. int hour = (int)bias / 100;
  200. int minutes = bias % 100;
  201. if (bias < 0) {
  202. ret.bias = hour * 60 - minutes;
  203. } else {
  204. ret.bias = hour * 60 + minutes;
  205. }
  206. return ret;
  207. }
  208. void OS_Unix::delay_usec(uint32_t p_usec) const {
  209. struct timespec requested = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  210. struct timespec remaining;
  211. while (nanosleep(&requested, &remaining) == -1 && errno == EINTR) {
  212. requested.tv_sec = remaining.tv_sec;
  213. requested.tv_nsec = remaining.tv_nsec;
  214. }
  215. }
  216. uint64_t OS_Unix::get_ticks_usec() const {
  217. #if defined(__APPLE__)
  218. uint64_t longtime = mach_absolute_time() * _clock_scale;
  219. #else
  220. // Unchecked return. Static analyzers might complain.
  221. // If _setup_clock() succeeded, we assume clock_gettime() works.
  222. struct timespec tv_now = { 0, 0 };
  223. clock_gettime(GODOT_CLOCK, &tv_now);
  224. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  225. #endif
  226. longtime -= _clock_start;
  227. return longtime;
  228. }
  229. 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) {
  230. #ifdef __EMSCRIPTEN__
  231. // Don't compile this code at all to avoid undefined references.
  232. // Actual virtual call goes to OS_JavaScript.
  233. ERR_FAIL_V(ERR_BUG);
  234. #else
  235. if (p_blocking && r_pipe) {
  236. String argss;
  237. argss = "\"" + p_path + "\"";
  238. for (int i = 0; i < p_arguments.size(); i++) {
  239. argss += String(" \"") + p_arguments[i] + "\"";
  240. }
  241. if (read_stderr) {
  242. argss += " 2>&1"; // Read stderr too
  243. } else {
  244. argss += " 2>/dev/null"; //silence stderr
  245. }
  246. FILE *f = popen(argss.utf8().get_data(), "r");
  247. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot pipe stream from process running with following arguments '" + argss + "'.");
  248. char buf[65535];
  249. while (fgets(buf, 65535, f)) {
  250. if (p_pipe_mutex) {
  251. p_pipe_mutex->lock();
  252. }
  253. (*r_pipe) += String::utf8(buf);
  254. if (p_pipe_mutex) {
  255. p_pipe_mutex->unlock();
  256. }
  257. }
  258. int rv = pclose(f);
  259. if (r_exitcode) {
  260. *r_exitcode = WEXITSTATUS(rv);
  261. }
  262. return OK;
  263. }
  264. pid_t pid = fork();
  265. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  266. if (pid == 0) {
  267. // is child
  268. if (!p_blocking) {
  269. // For non blocking calls, create a new session-ID so parent won't wait for it.
  270. // This ensures the process won't go zombie at end.
  271. setsid();
  272. }
  273. Vector<CharString> cs;
  274. cs.push_back(p_path.utf8());
  275. for (int i = 0; i < p_arguments.size(); i++) {
  276. cs.push_back(p_arguments[i].utf8());
  277. }
  278. Vector<char *> args;
  279. for (int i = 0; i < cs.size(); i++) {
  280. args.push_back((char *)cs[i].get_data());
  281. }
  282. args.push_back(0);
  283. execvp(p_path.utf8().get_data(), &args[0]);
  284. // still alive? something failed..
  285. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  286. raise(SIGKILL);
  287. }
  288. if (p_blocking) {
  289. int status;
  290. waitpid(pid, &status, 0);
  291. if (r_exitcode) {
  292. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  293. }
  294. } else {
  295. if (r_child_id) {
  296. *r_child_id = pid;
  297. }
  298. }
  299. return OK;
  300. #endif
  301. }
  302. Error OS_Unix::kill(const ProcessID &p_pid) {
  303. int ret = ::kill(p_pid, SIGKILL);
  304. if (!ret) {
  305. //avoid zombie process
  306. int st;
  307. ::waitpid(p_pid, &st, 0);
  308. }
  309. return ret ? ERR_INVALID_PARAMETER : OK;
  310. }
  311. int OS_Unix::get_process_id() const {
  312. return getpid();
  313. };
  314. bool OS_Unix::has_environment(const String &p_var) const {
  315. return getenv(p_var.utf8().get_data()) != nullptr;
  316. }
  317. String OS_Unix::get_locale() const {
  318. if (!has_environment("LANG")) {
  319. return "en";
  320. }
  321. String locale = get_environment("LANG");
  322. int tp = locale.find(".");
  323. if (tp != -1) {
  324. locale = locale.substr(0, tp);
  325. }
  326. return locale;
  327. }
  328. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  329. String path = p_path;
  330. if (FileAccess::exists(path) && path.is_rel_path()) {
  331. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  332. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  333. path = "./" + path;
  334. }
  335. if (!FileAccess::exists(path)) {
  336. //this code exists so gdnative can load .so files from within the executable path
  337. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  338. }
  339. if (!FileAccess::exists(path)) {
  340. //this code exists so gdnative can load .so files from a standard unix location
  341. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  342. }
  343. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  344. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  345. return OK;
  346. }
  347. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  348. if (dlclose(p_library_handle)) {
  349. return FAILED;
  350. }
  351. return OK;
  352. }
  353. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  354. const char *error;
  355. dlerror(); // Clear existing errors
  356. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  357. error = dlerror();
  358. if (error != nullptr) {
  359. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  360. return ERR_CANT_RESOLVE;
  361. }
  362. return OK;
  363. }
  364. Error OS_Unix::set_cwd(const String &p_cwd) {
  365. if (chdir(p_cwd.utf8().get_data()) != 0) {
  366. return ERR_CANT_OPEN;
  367. }
  368. return OK;
  369. }
  370. String OS_Unix::get_environment(const String &p_var) const {
  371. if (getenv(p_var.utf8().get_data())) {
  372. return getenv(p_var.utf8().get_data());
  373. }
  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 get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file("[unnamed project]");
  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__) || defined(__NetBSD__)
  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. }
  453. // Disable color codes if stdout is not a TTY.
  454. // This prevents Godot from writing ANSI escape codes when redirecting
  455. // stdout and stderr to a file.
  456. const bool tty = isatty(fileno(stdout));
  457. const char *gray = tty ? "\E[0;90m" : "";
  458. const char *red = tty ? "\E[0;91m" : "";
  459. const char *red_bold = tty ? "\E[1;31m" : "";
  460. const char *yellow = tty ? "\E[0;93m" : "";
  461. const char *yellow_bold = tty ? "\E[1;33m" : "";
  462. const char *magenta = tty ? "\E[0;95m" : "";
  463. const char *magenta_bold = tty ? "\E[1;35m" : "";
  464. const char *cyan = tty ? "\E[0;96m" : "";
  465. const char *cyan_bold = tty ? "\E[1;36m" : "";
  466. const char *reset = tty ? "\E[0m" : "";
  467. switch (p_type) {
  468. case ERR_WARNING:
  469. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  470. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  471. break;
  472. case ERR_SCRIPT:
  473. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  474. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  475. break;
  476. case ERR_SHADER:
  477. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, 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_ERROR:
  481. default:
  482. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  483. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  484. break;
  485. }
  486. }
  487. UnixTerminalLogger::~UnixTerminalLogger() {}
  488. OS_Unix::OS_Unix() {
  489. Vector<Logger *> loggers;
  490. loggers.push_back(memnew(UnixTerminalLogger));
  491. _set_logger(memnew(CompositeLogger(loggers)));
  492. }
  493. #endif