os_unix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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 "drivers/unix/dir_access_unix.h"
  36. #include "drivers/unix/file_access_unix.h"
  37. #include "drivers/unix/net_socket_posix.h"
  38. #include "drivers/unix/thread_posix.h"
  39. #include "servers/rendering_server.h"
  40. #ifdef __APPLE__
  41. #include <mach-o/dyld.h>
  42. #include <mach/mach_time.h>
  43. #endif
  44. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  45. #include <sys/param.h>
  46. #include <sys/sysctl.h>
  47. #endif
  48. #include <assert.h>
  49. #include <dlfcn.h>
  50. #include <errno.h>
  51. #include <poll.h>
  52. #include <signal.h>
  53. #include <stdarg.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <sys/time.h>
  58. #include <sys/wait.h>
  59. #include <time.h>
  60. #include <unistd.h>
  61. /// Clock Setup function (used by get_ticks_usec)
  62. static uint64_t _clock_start = 0;
  63. #if defined(__APPLE__)
  64. static double _clock_scale = 0;
  65. static void _setup_clock() {
  66. mach_timebase_info_data_t info;
  67. kern_return_t ret = mach_timebase_info(&info);
  68. ERR_FAIL_COND_MSG(ret != 0, "OS CLOCK IS NOT WORKING!");
  69. _clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
  70. _clock_start = mach_absolute_time() * _clock_scale;
  71. }
  72. #else
  73. #if defined(CLOCK_MONOTONIC_RAW) && !defined(JAVASCRIPT_ENABLED) // This is a better clock on Linux.
  74. #define GODOT_CLOCK CLOCK_MONOTONIC_RAW
  75. #else
  76. #define GODOT_CLOCK CLOCK_MONOTONIC
  77. #endif
  78. static void _setup_clock() {
  79. struct timespec tv_now = { 0, 0 };
  80. ERR_FAIL_COND_MSG(clock_gettime(GODOT_CLOCK, &tv_now) != 0, "OS CLOCK IS NOT WORKING!");
  81. _clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  82. }
  83. #endif
  84. void OS_Unix::debug_break() {
  85. assert(false);
  86. };
  87. static void handle_interrupt(int sig) {
  88. if (!EngineDebugger::is_active()) {
  89. return;
  90. }
  91. EngineDebugger::get_script_debugger()->set_depth(-1);
  92. EngineDebugger::get_script_debugger()->set_lines_left(1);
  93. }
  94. void OS_Unix::initialize_debugging() {
  95. if (EngineDebugger::is_active()) {
  96. struct sigaction action;
  97. memset(&action, 0, sizeof(action));
  98. action.sa_handler = handle_interrupt;
  99. sigaction(SIGINT, &action, nullptr);
  100. }
  101. }
  102. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  103. return 0;
  104. }
  105. void OS_Unix::initialize_core() {
  106. #if !defined(NO_THREADS)
  107. init_thread_posix();
  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. IPUnix::make_default();
  118. #endif
  119. _setup_clock();
  120. }
  121. void OS_Unix::finalize_core() {
  122. NetSocketPosix::cleanup();
  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. double OS_Unix::get_unix_time() const {
  137. struct timeval tv_now;
  138. gettimeofday(&tv_now, nullptr);
  139. return (double)tv_now.tv_sec + double(tv_now.tv_usec) / 1000000;
  140. };
  141. OS::Date OS_Unix::get_date(bool utc) const {
  142. time_t t = time(nullptr);
  143. struct tm lt;
  144. if (utc) {
  145. gmtime_r(&t, &lt);
  146. } else {
  147. localtime_r(&t, &lt);
  148. }
  149. Date ret;
  150. ret.year = 1900 + lt.tm_year;
  151. // Index starting at 1 to match OS_Unix::get_date
  152. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  153. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  154. ret.month = (Month)(lt.tm_mon + 1);
  155. ret.day = lt.tm_mday;
  156. ret.weekday = (Weekday)lt.tm_wday;
  157. ret.dst = lt.tm_isdst;
  158. return ret;
  159. }
  160. OS::Time OS_Unix::get_time(bool utc) const {
  161. time_t t = time(nullptr);
  162. struct tm lt;
  163. if (utc) {
  164. gmtime_r(&t, &lt);
  165. } else {
  166. localtime_r(&t, &lt);
  167. }
  168. Time ret;
  169. ret.hour = lt.tm_hour;
  170. ret.minute = lt.tm_min;
  171. ret.second = lt.tm_sec;
  172. get_time_zone_info();
  173. return ret;
  174. }
  175. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  176. time_t t = time(nullptr);
  177. struct tm lt;
  178. localtime_r(&t, &lt);
  179. char name[16];
  180. strftime(name, 16, "%Z", &lt);
  181. name[15] = 0;
  182. TimeZoneInfo ret;
  183. ret.name = name;
  184. char bias_buf[16];
  185. strftime(bias_buf, 16, "%z", &lt);
  186. int bias;
  187. bias_buf[15] = 0;
  188. sscanf(bias_buf, "%d", &bias);
  189. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  190. int hour = (int)bias / 100;
  191. int minutes = bias % 100;
  192. if (bias < 0) {
  193. ret.bias = hour * 60 - minutes;
  194. } else {
  195. ret.bias = hour * 60 + minutes;
  196. }
  197. return ret;
  198. }
  199. void OS_Unix::delay_usec(uint32_t p_usec) const {
  200. struct timespec requested = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  201. struct timespec remaining;
  202. while (nanosleep(&requested, &remaining) == -1 && errno == EINTR) {
  203. requested.tv_sec = remaining.tv_sec;
  204. requested.tv_nsec = remaining.tv_nsec;
  205. }
  206. }
  207. uint64_t OS_Unix::get_ticks_usec() const {
  208. #if defined(__APPLE__)
  209. uint64_t longtime = mach_absolute_time() * _clock_scale;
  210. #else
  211. // Unchecked return. Static analyzers might complain.
  212. // If _setup_clock() succeeded, we assume clock_gettime() works.
  213. struct timespec tv_now = { 0, 0 };
  214. clock_gettime(GODOT_CLOCK, &tv_now);
  215. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  216. #endif
  217. longtime -= _clock_start;
  218. return longtime;
  219. }
  220. 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) {
  221. #ifdef __EMSCRIPTEN__
  222. // Don't compile this code at all to avoid undefined references.
  223. // Actual virtual call goes to OS_JavaScript.
  224. ERR_FAIL_V(ERR_BUG);
  225. #else
  226. if (r_pipe) {
  227. String command = "\"" + p_path + "\"";
  228. for (int i = 0; i < p_arguments.size(); i++) {
  229. command += String(" \"") + p_arguments[i] + "\"";
  230. }
  231. if (read_stderr) {
  232. command += " 2>&1"; // Include stderr
  233. } else {
  234. command += " 2>/dev/null"; // Silence stderr
  235. }
  236. FILE *f = popen(command.utf8().get_data(), "r");
  237. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot create pipe from command: " + command);
  238. char buf[65535];
  239. while (fgets(buf, 65535, f)) {
  240. if (p_pipe_mutex) {
  241. p_pipe_mutex->lock();
  242. }
  243. (*r_pipe) += String::utf8(buf);
  244. if (p_pipe_mutex) {
  245. p_pipe_mutex->unlock();
  246. }
  247. }
  248. int rv = pclose(f);
  249. if (r_exitcode) {
  250. *r_exitcode = WEXITSTATUS(rv);
  251. }
  252. return OK;
  253. }
  254. pid_t pid = fork();
  255. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  256. if (pid == 0) {
  257. // The child process
  258. Vector<CharString> cs;
  259. cs.push_back(p_path.utf8());
  260. for (int i = 0; i < p_arguments.size(); i++) {
  261. cs.push_back(p_arguments[i].utf8());
  262. }
  263. Vector<char *> args;
  264. for (int i = 0; i < cs.size(); i++) {
  265. args.push_back((char *)cs[i].get_data());
  266. }
  267. args.push_back(0);
  268. execvp(p_path.utf8().get_data(), &args[0]);
  269. // The execvp() function only returns if an error occurs.
  270. ERR_PRINT("Could not create child process: " + p_path);
  271. raise(SIGKILL);
  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<CharString> cs;
  295. cs.push_back(p_path.utf8());
  296. for (int i = 0; i < p_arguments.size(); i++) {
  297. cs.push_back(p_arguments[i].utf8());
  298. }
  299. Vector<char *> args;
  300. for (int i = 0; i < cs.size(); i++) {
  301. args.push_back((char *)cs[i].get_data());
  302. }
  303. args.push_back(0);
  304. execvp(p_path.utf8().get_data(), &args[0]);
  305. // The execvp() function only returns if an error occurs.
  306. ERR_PRINT("Could not create child process: " + p_path);
  307. raise(SIGKILL);
  308. }
  309. if (r_child_id) {
  310. *r_child_id = pid;
  311. }
  312. return OK;
  313. #endif
  314. }
  315. Error OS_Unix::kill(const ProcessID &p_pid) {
  316. int ret = ::kill(p_pid, SIGKILL);
  317. if (!ret) {
  318. //avoid zombie process
  319. int st;
  320. ::waitpid(p_pid, &st, 0);
  321. }
  322. return ret ? ERR_INVALID_PARAMETER : OK;
  323. }
  324. int OS_Unix::get_process_id() const {
  325. return getpid();
  326. };
  327. bool OS_Unix::has_environment(const String &p_var) const {
  328. return getenv(p_var.utf8().get_data()) != nullptr;
  329. }
  330. String OS_Unix::get_locale() const {
  331. if (!has_environment("LANG")) {
  332. return "en";
  333. }
  334. String locale = get_environment("LANG");
  335. int tp = locale.find(".");
  336. if (tp != -1) {
  337. locale = locale.substr(0, tp);
  338. }
  339. return locale;
  340. }
  341. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  342. String path = p_path;
  343. if (FileAccess::exists(path) && path.is_relative_path()) {
  344. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  345. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  346. path = "./" + path;
  347. }
  348. if (!FileAccess::exists(path)) {
  349. //this code exists so gdnative can load .so files from within the executable path
  350. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  351. }
  352. if (!FileAccess::exists(path)) {
  353. //this code exists so gdnative can load .so files from a standard unix location
  354. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  355. }
  356. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  357. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  358. return OK;
  359. }
  360. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  361. if (dlclose(p_library_handle)) {
  362. return FAILED;
  363. }
  364. return OK;
  365. }
  366. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  367. const char *error;
  368. dlerror(); // Clear existing errors
  369. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  370. error = dlerror();
  371. if (error != nullptr) {
  372. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  373. return ERR_CANT_RESOLVE;
  374. }
  375. return OK;
  376. }
  377. Error OS_Unix::set_cwd(const String &p_cwd) {
  378. if (chdir(p_cwd.utf8().get_data()) != 0) {
  379. return ERR_CANT_OPEN;
  380. }
  381. return OK;
  382. }
  383. String OS_Unix::get_environment(const String &p_var) const {
  384. if (getenv(p_var.utf8().get_data())) {
  385. return getenv(p_var.utf8().get_data());
  386. }
  387. return "";
  388. }
  389. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  390. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  391. }
  392. int OS_Unix::get_processor_count() const {
  393. return sysconf(_SC_NPROCESSORS_CONF);
  394. }
  395. String OS_Unix::get_user_data_dir() const {
  396. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  397. if (appname != "") {
  398. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  399. if (use_custom_dir) {
  400. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  401. if (custom_dir == "") {
  402. custom_dir = appname;
  403. }
  404. return get_data_path().plus_file(custom_dir);
  405. } else {
  406. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  407. }
  408. }
  409. return ProjectSettings::get_singleton()->get_resource_path();
  410. }
  411. String OS_Unix::get_executable_path() const {
  412. #ifdef __linux__
  413. //fix for running from a symlink
  414. char buf[256];
  415. memset(buf, 0, 256);
  416. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  417. String b;
  418. if (len > 0) {
  419. b.parse_utf8(buf, len);
  420. }
  421. if (b == "") {
  422. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  423. return OS::get_executable_path();
  424. }
  425. return b;
  426. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  427. char resolved_path[MAXPATHLEN];
  428. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  429. return String(resolved_path);
  430. #elif defined(__FreeBSD__)
  431. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  432. char buf[MAXPATHLEN];
  433. size_t len = sizeof(buf);
  434. if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0) {
  435. WARN_PRINT("Couldn't get executable path from sysctl");
  436. return OS::get_executable_path();
  437. }
  438. String b;
  439. b.parse_utf8(buf);
  440. return b;
  441. #elif defined(__APPLE__)
  442. char temp_path[1];
  443. uint32_t buff_size = 1;
  444. _NSGetExecutablePath(temp_path, &buff_size);
  445. char *resolved_path = new char[buff_size + 1];
  446. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  447. WARN_PRINT("MAXPATHLEN is too small");
  448. String path(resolved_path);
  449. delete[] resolved_path;
  450. return path;
  451. #else
  452. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  453. return OS::get_executable_path();
  454. #endif
  455. }
  456. void UnixTerminalLogger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, ErrorType p_type) {
  457. if (!should_log(true)) {
  458. return;
  459. }
  460. const char *err_details;
  461. if (p_rationale && p_rationale[0]) {
  462. err_details = p_rationale;
  463. } else {
  464. err_details = p_code;
  465. }
  466. // Disable color codes if stdout is not a TTY.
  467. // This prevents Godot from writing ANSI escape codes when redirecting
  468. // stdout and stderr to a file.
  469. const bool tty = isatty(fileno(stdout));
  470. const char *gray = tty ? "\E[0;90m" : "";
  471. const char *red = tty ? "\E[0;91m" : "";
  472. const char *red_bold = tty ? "\E[1;31m" : "";
  473. const char *yellow = tty ? "\E[0;93m" : "";
  474. const char *yellow_bold = tty ? "\E[1;33m" : "";
  475. const char *magenta = tty ? "\E[0;95m" : "";
  476. const char *magenta_bold = tty ? "\E[1;35m" : "";
  477. const char *cyan = tty ? "\E[0;96m" : "";
  478. const char *cyan_bold = tty ? "\E[1;36m" : "";
  479. const char *reset = tty ? "\E[0m" : "";
  480. switch (p_type) {
  481. case ERR_WARNING:
  482. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  483. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  484. break;
  485. case ERR_SCRIPT:
  486. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  487. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  488. break;
  489. case ERR_SHADER:
  490. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, err_details);
  491. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  492. break;
  493. case ERR_ERROR:
  494. default:
  495. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  496. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  497. break;
  498. }
  499. }
  500. UnixTerminalLogger::~UnixTerminalLogger() {}
  501. OS_Unix::OS_Unix() {
  502. Vector<Logger *> loggers;
  503. loggers.push_back(memnew(UnixTerminalLogger));
  504. _set_logger(memnew(CompositeLogger(loggers)));
  505. }
  506. #endif