os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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() == NULL)
  87. return;
  88. ScriptDebugger::get_singleton()->set_depth(-1);
  89. ScriptDebugger::get_singleton()->set_lines_left(1);
  90. }
  91. void OS_Unix::initialize_debugging() {
  92. if (ScriptDebugger::get_singleton() != NULL) {
  93. struct sigaction action;
  94. memset(&action, 0, sizeof(action));
  95. action.sa_handler = handle_interrupt;
  96. sigaction(SIGINT, &action, NULL);
  97. }
  98. }
  99. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  100. return 0;
  101. }
  102. void OS_Unix::initialize_core() {
  103. #if !defined(NO_THREADS)
  104. init_thread_posix();
  105. #endif
  106. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  107. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  108. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  109. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  110. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  111. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  112. #ifndef NO_NETWORK
  113. NetSocketPosix::make_default();
  114. IP_Unix::make_default();
  115. #endif
  116. _setup_clock();
  117. }
  118. void OS_Unix::finalize_core() {
  119. NetSocketPosix::cleanup();
  120. }
  121. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  122. fprintf(stderr, "ALERT: %s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  123. }
  124. String OS_Unix::get_stdin_string(bool p_block) {
  125. if (p_block) {
  126. char buff[1024];
  127. String ret = stdin_buf + fgets(buff, 1024, stdin);
  128. stdin_buf = "";
  129. return ret;
  130. }
  131. return "";
  132. }
  133. String OS_Unix::get_name() const {
  134. return "Unix";
  135. }
  136. uint64_t OS_Unix::get_unix_time() const {
  137. return time(NULL);
  138. };
  139. uint64_t OS_Unix::get_system_time_secs() const {
  140. struct timeval tv_now;
  141. gettimeofday(&tv_now, NULL);
  142. return uint64_t(tv_now.tv_sec);
  143. }
  144. uint64_t OS_Unix::get_system_time_msecs() const {
  145. struct timeval tv_now;
  146. gettimeofday(&tv_now, NULL);
  147. return uint64_t(tv_now.tv_sec) * 1000 + uint64_t(tv_now.tv_usec) / 1000;
  148. }
  149. OS::Date OS_Unix::get_date(bool utc) const {
  150. time_t t = time(NULL);
  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(NULL);
  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(NULL);
  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. return ret;
  205. }
  206. void OS_Unix::delay_usec(uint32_t p_usec) const {
  207. struct timespec requested = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  208. struct timespec remaining;
  209. while (nanosleep(&requested, &remaining) == -1 && errno == EINTR) {
  210. requested.tv_sec = remaining.tv_sec;
  211. requested.tv_nsec = remaining.tv_nsec;
  212. }
  213. }
  214. uint64_t OS_Unix::get_ticks_usec() const {
  215. #if defined(__APPLE__)
  216. uint64_t longtime = mach_absolute_time() * _clock_scale;
  217. #else
  218. // Unchecked return. Static analyzers might complain.
  219. // If _setup_clock() succeeded, we assume clock_gettime() works.
  220. struct timespec tv_now = { 0, 0 };
  221. clock_gettime(GODOT_CLOCK, &tv_now);
  222. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  223. #endif
  224. longtime -= _clock_start;
  225. return longtime;
  226. }
  227. 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) {
  228. #ifdef __EMSCRIPTEN__
  229. // Don't compile this code at all to avoid undefined references.
  230. // Actual virtual call goes to OS_JavaScript.
  231. ERR_FAIL_V(ERR_BUG);
  232. #else
  233. if (p_blocking && r_pipe) {
  234. String argss;
  235. argss = "\"" + p_path + "\"";
  236. for (int i = 0; i < p_arguments.size(); i++) {
  237. argss += String(" \"") + p_arguments[i] + "\"";
  238. }
  239. if (read_stderr) {
  240. argss += " 2>&1"; // Read stderr too
  241. } else {
  242. argss += " 2>/dev/null"; //silence stderr
  243. }
  244. FILE *f = popen(argss.utf8().get_data(), "r");
  245. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot pipe stream from process running with following arguments '" + argss + "'.");
  246. char buf[65535];
  247. while (fgets(buf, 65535, f)) {
  248. if (p_pipe_mutex) {
  249. p_pipe_mutex->lock();
  250. }
  251. (*r_pipe) += String::utf8(buf);
  252. if (p_pipe_mutex) {
  253. p_pipe_mutex->unlock();
  254. }
  255. }
  256. int rv = pclose(f);
  257. if (r_exitcode)
  258. *r_exitcode = WEXITSTATUS(rv);
  259. return OK;
  260. }
  261. pid_t pid = fork();
  262. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  263. if (pid == 0) {
  264. // is child
  265. if (!p_blocking) {
  266. // For non blocking calls, create a new session-ID so parent won't wait for it.
  267. // This ensures the process won't go zombie at end.
  268. setsid();
  269. }
  270. Vector<CharString> cs;
  271. cs.push_back(p_path.utf8());
  272. for (int i = 0; i < p_arguments.size(); i++)
  273. cs.push_back(p_arguments[i].utf8());
  274. Vector<char *> args;
  275. for (int i = 0; i < cs.size(); i++)
  276. args.push_back((char *)cs[i].get_data());
  277. args.push_back(0);
  278. execvp(p_path.utf8().get_data(), &args[0]);
  279. // still alive? something failed..
  280. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  281. raise(SIGKILL);
  282. }
  283. if (p_blocking) {
  284. int status;
  285. waitpid(pid, &status, 0);
  286. if (r_exitcode)
  287. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  288. } else {
  289. if (r_child_id)
  290. *r_child_id = pid;
  291. }
  292. return OK;
  293. #endif
  294. }
  295. Error OS_Unix::kill(const ProcessID &p_pid) {
  296. int ret = ::kill(p_pid, SIGKILL);
  297. if (!ret) {
  298. //avoid zombie process
  299. int st;
  300. ::waitpid(p_pid, &st, 0);
  301. }
  302. return ret ? ERR_INVALID_PARAMETER : OK;
  303. }
  304. int OS_Unix::get_process_id() const {
  305. return getpid();
  306. };
  307. bool OS_Unix::has_environment(const String &p_var) const {
  308. return getenv(p_var.utf8().get_data()) != NULL;
  309. }
  310. String OS_Unix::get_locale() const {
  311. if (!has_environment("LANG"))
  312. return "en";
  313. String locale = get_environment("LANG");
  314. int tp = locale.find(".");
  315. if (tp != -1)
  316. locale = locale.substr(0, tp);
  317. return locale;
  318. }
  319. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  320. String path = p_path;
  321. if (FileAccess::exists(path) && path.is_rel_path()) {
  322. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  323. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  324. path = "./" + path;
  325. }
  326. if (!FileAccess::exists(path)) {
  327. //this code exists so gdnative can load .so files from within the executable path
  328. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  329. }
  330. if (!FileAccess::exists(path)) {
  331. //this code exists so gdnative can load .so files from a standard unix location
  332. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  333. }
  334. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  335. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  336. return OK;
  337. }
  338. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  339. if (dlclose(p_library_handle)) {
  340. return FAILED;
  341. }
  342. return OK;
  343. }
  344. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  345. const char *error;
  346. dlerror(); // Clear existing errors
  347. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  348. error = dlerror();
  349. if (error != NULL) {
  350. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  351. return ERR_CANT_RESOLVE;
  352. }
  353. return OK;
  354. }
  355. Error OS_Unix::set_cwd(const String &p_cwd) {
  356. if (chdir(p_cwd.utf8().get_data()) != 0)
  357. return ERR_CANT_OPEN;
  358. return OK;
  359. }
  360. String OS_Unix::get_environment(const String &p_var) const {
  361. if (getenv(p_var.utf8().get_data()))
  362. return getenv(p_var.utf8().get_data());
  363. return "";
  364. }
  365. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  366. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  367. }
  368. int OS_Unix::get_processor_count() const {
  369. return sysconf(_SC_NPROCESSORS_CONF);
  370. }
  371. String OS_Unix::get_user_data_dir() const {
  372. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  373. if (appname != "") {
  374. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  375. if (use_custom_dir) {
  376. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  377. if (custom_dir == "") {
  378. custom_dir = appname;
  379. }
  380. return get_data_path().plus_file(custom_dir);
  381. } else {
  382. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  383. }
  384. }
  385. return ProjectSettings::get_singleton()->get_resource_path();
  386. }
  387. String OS_Unix::get_executable_path() const {
  388. #ifdef __linux__
  389. //fix for running from a symlink
  390. char buf[256];
  391. memset(buf, 0, 256);
  392. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  393. String b;
  394. if (len > 0) {
  395. b.parse_utf8(buf, len);
  396. }
  397. if (b == "") {
  398. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  399. return OS::get_executable_path();
  400. }
  401. return b;
  402. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  403. char resolved_path[MAXPATHLEN];
  404. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  405. return String(resolved_path);
  406. #elif defined(__FreeBSD__)
  407. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  408. char buf[MAXPATHLEN];
  409. size_t len = sizeof(buf);
  410. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  411. WARN_PRINT("Couldn't get executable path from sysctl");
  412. return OS::get_executable_path();
  413. }
  414. String b;
  415. b.parse_utf8(buf);
  416. return b;
  417. #elif defined(__APPLE__)
  418. char temp_path[1];
  419. uint32_t buff_size = 1;
  420. _NSGetExecutablePath(temp_path, &buff_size);
  421. char *resolved_path = new char[buff_size + 1];
  422. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  423. WARN_PRINT("MAXPATHLEN is too small");
  424. String path(resolved_path);
  425. delete[] resolved_path;
  426. return path;
  427. #else
  428. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  429. return OS::get_executable_path();
  430. #endif
  431. }
  432. 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) {
  433. if (!should_log(true)) {
  434. return;
  435. }
  436. const char *err_details;
  437. if (p_rationale && p_rationale[0])
  438. err_details = p_rationale;
  439. else
  440. err_details = p_code;
  441. // Disable color codes if stdout is not a TTY.
  442. // This prevents Godot from writing ANSI escape codes when redirecting
  443. // stdout and stderr to a file.
  444. const bool tty = isatty(fileno(stdout));
  445. const char *red = tty ? "\E[0;31m" : "";
  446. const char *red_bold = tty ? "\E[1;31m" : "";
  447. const char *yellow = tty ? "\E[0;33m" : "";
  448. const char *yellow_bold = tty ? "\E[1;33m" : "";
  449. const char *magenta = tty ? "\E[0;35m" : "";
  450. const char *magenta_bold = tty ? "\E[1;35m" : "";
  451. const char *cyan = tty ? "\E[0;36m" : "";
  452. const char *cyan_bold = tty ? "\E[1;36m" : "";
  453. const char *reset = tty ? "\E[0m" : "";
  454. const char *bold = tty ? "\E[1m" : "";
  455. switch (p_type) {
  456. case ERR_WARNING:
  457. logf_error("%sWARNING: %s: %s%s%s\n", yellow_bold, p_function, reset, bold, err_details);
  458. logf_error("%s At: %s:%i.%s\n", yellow, p_file, p_line, reset);
  459. break;
  460. case ERR_SCRIPT:
  461. logf_error("%sSCRIPT ERROR: %s: %s%s%s\n", magenta_bold, p_function, reset, bold, err_details);
  462. logf_error("%s At: %s:%i.%s\n", magenta, p_file, p_line, reset);
  463. break;
  464. case ERR_SHADER:
  465. logf_error("%sSHADER ERROR: %s: %s%s%s\n", cyan_bold, p_function, reset, bold, err_details);
  466. logf_error("%s At: %s:%i.%s\n", cyan, p_file, p_line, reset);
  467. break;
  468. case ERR_ERROR:
  469. default:
  470. logf_error("%sERROR: %s: %s%s%s\n", red_bold, p_function, reset, bold, err_details);
  471. logf_error("%s At: %s:%i.%s\n", red, p_file, p_line, reset);
  472. break;
  473. }
  474. }
  475. UnixTerminalLogger::~UnixTerminalLogger() {}
  476. OS_Unix::OS_Unix() {
  477. Vector<Logger *> loggers;
  478. loggers.push_back(memnew(UnixTerminalLogger));
  479. _set_logger(memnew(CompositeLogger(loggers)));
  480. }
  481. #endif