os_unix.cpp 17 KB

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