os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /**************************************************************************/
  2. /* os_unix.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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() {
  122. char buff[1024];
  123. String ret = stdin_buf + fgets(buff, 1024, stdin);
  124. stdin_buf = "";
  125. return ret;
  126. }
  127. String OS_Unix::get_name() const {
  128. return "Unix";
  129. }
  130. uint64_t OS_Unix::get_unix_time() const {
  131. return time(nullptr);
  132. };
  133. uint64_t OS_Unix::get_system_time_secs() const {
  134. struct timeval tv_now;
  135. gettimeofday(&tv_now, nullptr);
  136. return uint64_t(tv_now.tv_sec);
  137. }
  138. uint64_t OS_Unix::get_system_time_msecs() const {
  139. struct timeval tv_now;
  140. gettimeofday(&tv_now, nullptr);
  141. return uint64_t(tv_now.tv_sec) * 1000 + uint64_t(tv_now.tv_usec) / 1000;
  142. }
  143. double OS_Unix::get_subsecond_unix_time() const {
  144. struct timeval tv_now;
  145. gettimeofday(&tv_now, nullptr);
  146. return (double)tv_now.tv_sec + double(tv_now.tv_usec) / 1000000;
  147. }
  148. OS::Date OS_Unix::get_date(bool utc) const {
  149. time_t t = time(nullptr);
  150. struct tm lt;
  151. if (utc) {
  152. gmtime_r(&t, &lt);
  153. } else {
  154. localtime_r(&t, &lt);
  155. }
  156. Date ret;
  157. ret.year = 1900 + lt.tm_year;
  158. // Index starting at 1 to match OS_Unix::get_date
  159. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  160. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  161. ret.month = (Month)(lt.tm_mon + 1);
  162. ret.day = lt.tm_mday;
  163. ret.weekday = (Weekday)lt.tm_wday;
  164. ret.dst = lt.tm_isdst;
  165. return ret;
  166. }
  167. OS::Time OS_Unix::get_time(bool utc) const {
  168. time_t t = time(nullptr);
  169. struct tm lt;
  170. if (utc) {
  171. gmtime_r(&t, &lt);
  172. } else {
  173. localtime_r(&t, &lt);
  174. }
  175. Time ret;
  176. ret.hour = lt.tm_hour;
  177. ret.min = lt.tm_min;
  178. ret.sec = lt.tm_sec;
  179. get_time_zone_info();
  180. return ret;
  181. }
  182. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  183. time_t t = time(nullptr);
  184. struct tm lt;
  185. localtime_r(&t, &lt);
  186. char name[16];
  187. strftime(name, 16, "%Z", &lt);
  188. name[15] = 0;
  189. TimeZoneInfo ret;
  190. ret.name = name;
  191. char bias_buf[16];
  192. strftime(bias_buf, 16, "%z", &lt);
  193. int bias;
  194. bias_buf[15] = 0;
  195. sscanf(bias_buf, "%d", &bias);
  196. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  197. int hour = (int)bias / 100;
  198. int minutes = bias % 100;
  199. if (bias < 0) {
  200. ret.bias = hour * 60 - minutes;
  201. } else {
  202. ret.bias = hour * 60 + minutes;
  203. }
  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, bool p_open_console) {
  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. }
  260. return OK;
  261. }
  262. pid_t pid = fork();
  263. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  264. if (pid == 0) {
  265. // is child
  266. if (!p_blocking) {
  267. // For non blocking calls, create a new session-ID so parent won't wait for it.
  268. // This ensures the process won't go zombie at end.
  269. setsid();
  270. }
  271. Vector<CharString> cs;
  272. cs.push_back(p_path.utf8());
  273. for (int i = 0; i < p_arguments.size(); i++) {
  274. cs.push_back(p_arguments[i].utf8());
  275. }
  276. Vector<char *> args;
  277. for (int i = 0; i < cs.size(); i++) {
  278. args.push_back((char *)cs[i].get_data());
  279. }
  280. args.push_back(0);
  281. execvp(p_path.utf8().get_data(), &args[0]);
  282. // still alive? something failed..
  283. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  284. raise(SIGKILL);
  285. }
  286. if (p_blocking) {
  287. int status;
  288. waitpid(pid, &status, 0);
  289. if (r_exitcode) {
  290. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  291. }
  292. } else {
  293. if (r_child_id) {
  294. *r_child_id = pid;
  295. }
  296. }
  297. return OK;
  298. #endif
  299. }
  300. Error OS_Unix::kill(const ProcessID &p_pid) {
  301. int ret = ::kill(p_pid, SIGKILL);
  302. if (!ret) {
  303. //avoid zombie process
  304. int st;
  305. ::waitpid(p_pid, &st, 0);
  306. }
  307. return ret ? ERR_INVALID_PARAMETER : OK;
  308. }
  309. int OS_Unix::get_process_id() const {
  310. return getpid();
  311. };
  312. bool OS_Unix::is_process_running(const ProcessID &p_pid) const {
  313. int status = 0;
  314. if (waitpid(p_pid, &status, WNOHANG) != 0) {
  315. return false;
  316. }
  317. return true;
  318. }
  319. bool OS_Unix::has_environment(const String &p_var) const {
  320. return getenv(p_var.utf8().get_data()) != nullptr;
  321. }
  322. String OS_Unix::get_locale() const {
  323. if (!has_environment("LANG")) {
  324. return "en";
  325. }
  326. String locale = get_environment("LANG");
  327. int tp = locale.find(".");
  328. if (tp != -1) {
  329. locale = locale.substr(0, tp);
  330. }
  331. return locale;
  332. }
  333. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  334. String path = p_path;
  335. if (FileAccess::exists(path) && path.is_rel_path()) {
  336. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  337. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  338. path = "./" + path;
  339. }
  340. if (!FileAccess::exists(path)) {
  341. //this code exists so gdnative can load .so files from within the executable path
  342. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  343. }
  344. if (!FileAccess::exists(path)) {
  345. //this code exists so gdnative can load .so files from a standard unix location
  346. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  347. }
  348. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  349. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  350. return OK;
  351. }
  352. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  353. if (dlclose(p_library_handle)) {
  354. return FAILED;
  355. }
  356. return OK;
  357. }
  358. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  359. const char *error;
  360. dlerror(); // Clear existing errors
  361. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  362. error = dlerror();
  363. if (error != nullptr) {
  364. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  365. return ERR_CANT_RESOLVE;
  366. }
  367. return OK;
  368. }
  369. Error OS_Unix::set_cwd(const String &p_cwd) {
  370. if (chdir(p_cwd.utf8().get_data()) != 0) {
  371. return ERR_CANT_OPEN;
  372. }
  373. return OK;
  374. }
  375. String OS_Unix::get_environment(const String &p_var) const {
  376. if (getenv(p_var.utf8().get_data())) {
  377. return getenv(p_var.utf8().get_data());
  378. }
  379. return "";
  380. }
  381. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  382. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  383. }
  384. String OS_Unix::get_user_data_dir() const {
  385. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  386. if (appname != "") {
  387. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  388. if (use_custom_dir) {
  389. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  390. if (custom_dir == "") {
  391. custom_dir = appname;
  392. }
  393. return get_data_path().plus_file(custom_dir);
  394. } else {
  395. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  396. }
  397. }
  398. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file("[unnamed project]");
  399. }
  400. String OS_Unix::get_executable_path() const {
  401. #ifdef __linux__
  402. //fix for running from a symlink
  403. char buf[256];
  404. memset(buf, 0, 256);
  405. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  406. String b;
  407. if (len > 0) {
  408. b.parse_utf8(buf, len);
  409. }
  410. if (b == "") {
  411. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  412. return OS::get_executable_path();
  413. }
  414. return b;
  415. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  416. char resolved_path[MAXPATHLEN];
  417. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  418. return String(resolved_path);
  419. #elif defined(__FreeBSD__)
  420. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  421. char buf[MAXPATHLEN];
  422. size_t len = sizeof(buf);
  423. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  424. WARN_PRINT("Couldn't get executable path from sysctl");
  425. return OS::get_executable_path();
  426. }
  427. String b;
  428. b.parse_utf8(buf);
  429. return b;
  430. #elif defined(__APPLE__)
  431. char temp_path[1];
  432. uint32_t buff_size = 1;
  433. _NSGetExecutablePath(temp_path, &buff_size);
  434. char *resolved_path = new char[buff_size + 1];
  435. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  436. WARN_PRINT("MAXPATHLEN is too small");
  437. String path(resolved_path);
  438. delete[] resolved_path;
  439. return path;
  440. #else
  441. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  442. return OS::get_executable_path();
  443. #endif
  444. }
  445. 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) {
  446. if (!should_log(true)) {
  447. return;
  448. }
  449. const char *err_details;
  450. if (p_rationale && p_rationale[0]) {
  451. err_details = p_rationale;
  452. } else {
  453. err_details = p_code;
  454. }
  455. // Disable color codes if stdout is not a TTY.
  456. // This prevents Godot from writing ANSI escape codes when redirecting
  457. // stdout and stderr to a file.
  458. const bool tty = isatty(fileno(stdout));
  459. const char *gray = tty ? "\E[0;90m" : "";
  460. const char *red = tty ? "\E[0;91m" : "";
  461. const char *red_bold = tty ? "\E[1;31m" : "";
  462. const char *yellow = tty ? "\E[0;93m" : "";
  463. const char *yellow_bold = tty ? "\E[1;33m" : "";
  464. const char *magenta = tty ? "\E[0;95m" : "";
  465. const char *magenta_bold = tty ? "\E[1;35m" : "";
  466. const char *cyan = tty ? "\E[0;96m" : "";
  467. const char *cyan_bold = tty ? "\E[1;36m" : "";
  468. const char *reset = tty ? "\E[0m" : "";
  469. switch (p_type) {
  470. case ERR_WARNING:
  471. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  472. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  473. break;
  474. case ERR_SCRIPT:
  475. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  476. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  477. break;
  478. case ERR_SHADER:
  479. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, err_details);
  480. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  481. break;
  482. case ERR_ERROR:
  483. default:
  484. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  485. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  486. break;
  487. }
  488. }
  489. UnixTerminalLogger::~UnixTerminalLogger() {}
  490. OS_Unix::OS_Unix() {
  491. Vector<Logger *> loggers;
  492. loggers.push_back(memnew(UnixTerminalLogger));
  493. _set_logger(memnew(CompositeLogger(loggers)));
  494. }
  495. #endif