os_unix.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*************************************************************************/
  2. /* os_unix.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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/mutex_posix.h"
  37. #include "drivers/unix/net_socket_posix.h"
  38. #include "drivers/unix/rw_lock_posix.h"
  39. #include "drivers/unix/semaphore_posix.h"
  40. #include "drivers/unix/thread_posix.h"
  41. #include "servers/visual_server.h"
  42. #ifdef __APPLE__
  43. #include <mach-o/dyld.h>
  44. #include <mach/mach_time.h>
  45. #endif
  46. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  47. #include <sys/param.h>
  48. #include <sys/sysctl.h>
  49. #endif
  50. #include <assert.h>
  51. #include <dlfcn.h>
  52. #include <errno.h>
  53. #include <poll.h>
  54. #include <signal.h>
  55. #include <stdarg.h>
  56. #include <stdlib.h>
  57. #include <string.h>
  58. #include <sys/time.h>
  59. #include <sys/wait.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_EXPLAIN("OS CLOCK IS NOT WORKING!");
  69. ERR_FAIL_COND(ret != 0);
  70. _clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
  71. _clock_start = mach_absolute_time() * _clock_scale;
  72. }
  73. #else
  74. #if defined(CLOCK_MONOTONIC_RAW) && !defined(JAVASCRIPT_ENABLED) // This is a better clock on Linux.
  75. #define GODOT_CLOCK CLOCK_MONOTONIC_RAW
  76. #else
  77. #define GODOT_CLOCK CLOCK_MONOTONIC
  78. #endif
  79. static void _setup_clock() {
  80. struct timespec tv_now = { 0, 0 };
  81. ERR_EXPLAIN("OS CLOCK IS NOT WORKING!");
  82. ERR_FAIL_COND(clock_gettime(GODOT_CLOCK, &tv_now) != 0);
  83. _clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  84. }
  85. #endif
  86. void OS_Unix::debug_break() {
  87. assert(false);
  88. };
  89. static void handle_interrupt(int sig) {
  90. if (ScriptDebugger::get_singleton() == NULL)
  91. return;
  92. ScriptDebugger::get_singleton()->set_depth(-1);
  93. ScriptDebugger::get_singleton()->set_lines_left(1);
  94. }
  95. void OS_Unix::initialize_debugging() {
  96. if (ScriptDebugger::get_singleton() != NULL) {
  97. struct sigaction action;
  98. memset(&action, 0, sizeof(action));
  99. action.sa_handler = handle_interrupt;
  100. sigaction(SIGINT, &action, NULL);
  101. }
  102. }
  103. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  104. return 0;
  105. }
  106. // Very simple signal handler to reap processes where ::execute was called with
  107. // !p_blocking
  108. void handle_sigchld(int sig) {
  109. int saved_errno = errno;
  110. while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {
  111. }
  112. errno = saved_errno;
  113. }
  114. void OS_Unix::initialize_core() {
  115. #ifdef NO_THREADS
  116. ThreadDummy::make_default();
  117. SemaphoreDummy::make_default();
  118. MutexDummy::make_default();
  119. RWLockDummy::make_default();
  120. #else
  121. ThreadPosix::make_default();
  122. SemaphorePosix::make_default();
  123. MutexPosix::make_default();
  124. RWLockPosix::make_default();
  125. #endif
  126. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  127. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  128. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  129. //FileAccessBufferedFA<FileAccessUnix>::make_default();
  130. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  131. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  132. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  133. #ifndef NO_NETWORK
  134. NetSocketPosix::make_default();
  135. IP_Unix::make_default();
  136. #endif
  137. _setup_clock();
  138. struct sigaction sa;
  139. sa.sa_handler = &handle_sigchld;
  140. sigemptyset(&sa.sa_mask);
  141. sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
  142. if (sigaction(SIGCHLD, &sa, 0) == -1) {
  143. perror("ERROR sigaction() failed:");
  144. }
  145. }
  146. void OS_Unix::finalize_core() {
  147. NetSocketPosix::cleanup();
  148. }
  149. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  150. fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
  151. }
  152. String OS_Unix::get_stdin_string(bool p_block) {
  153. if (p_block) {
  154. char buff[1024];
  155. String ret = stdin_buf + fgets(buff, 1024, stdin);
  156. stdin_buf = "";
  157. return ret;
  158. }
  159. return "";
  160. }
  161. String OS_Unix::get_name() {
  162. return "Unix";
  163. }
  164. uint64_t OS_Unix::get_unix_time() const {
  165. return time(NULL);
  166. };
  167. uint64_t OS_Unix::get_system_time_secs() const {
  168. struct timeval tv_now;
  169. gettimeofday(&tv_now, NULL);
  170. return uint64_t(tv_now.tv_sec);
  171. }
  172. uint64_t OS_Unix::get_system_time_msecs() const {
  173. struct timeval tv_now;
  174. gettimeofday(&tv_now, NULL);
  175. return uint64_t(tv_now.tv_sec * 1000 + tv_now.tv_usec / 1000);
  176. }
  177. OS::Date OS_Unix::get_date(bool utc) const {
  178. time_t t = time(NULL);
  179. struct tm *lt;
  180. if (utc)
  181. lt = gmtime(&t);
  182. else
  183. lt = localtime(&t);
  184. Date ret;
  185. ret.year = 1900 + lt->tm_year;
  186. // Index starting at 1 to match OS_Unix::get_date
  187. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  188. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  189. ret.month = (Month)(lt->tm_mon + 1);
  190. ret.day = lt->tm_mday;
  191. ret.weekday = (Weekday)lt->tm_wday;
  192. ret.dst = lt->tm_isdst;
  193. return ret;
  194. }
  195. OS::Time OS_Unix::get_time(bool utc) const {
  196. time_t t = time(NULL);
  197. struct tm *lt;
  198. if (utc)
  199. lt = gmtime(&t);
  200. else
  201. lt = localtime(&t);
  202. Time ret;
  203. ret.hour = lt->tm_hour;
  204. ret.min = lt->tm_min;
  205. ret.sec = lt->tm_sec;
  206. get_time_zone_info();
  207. return ret;
  208. }
  209. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  210. time_t t = time(NULL);
  211. struct tm *lt = localtime(&t);
  212. char name[16];
  213. strftime(name, 16, "%Z", lt);
  214. name[15] = 0;
  215. TimeZoneInfo ret;
  216. ret.name = name;
  217. char bias_buf[16];
  218. strftime(bias_buf, 16, "%z", lt);
  219. int bias;
  220. bias_buf[15] = 0;
  221. sscanf(bias_buf, "%d", &bias);
  222. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  223. int hour = (int)bias / 100;
  224. int minutes = bias % 100;
  225. if (bias < 0)
  226. ret.bias = hour * 60 - minutes;
  227. else
  228. ret.bias = hour * 60 + minutes;
  229. return ret;
  230. }
  231. void OS_Unix::delay_usec(uint32_t p_usec) const {
  232. struct timespec rem = { static_cast<time_t>(p_usec / 1000000), static_cast<long>((p_usec % 1000000) * 1000) };
  233. while (nanosleep(&rem, &rem) == EINTR) {
  234. }
  235. }
  236. uint64_t OS_Unix::get_ticks_usec() const {
  237. #if defined(__APPLE__)
  238. uint64_t longtime = mach_absolute_time() * _clock_scale;
  239. #else
  240. // Unchecked return. Static analyzers might complain.
  241. // If _setup_clock() succeeded, we assume clock_gettime() works.
  242. struct timespec tv_now = { 0, 0 };
  243. clock_gettime(GODOT_CLOCK, &tv_now);
  244. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  245. #endif
  246. longtime -= _clock_start;
  247. return longtime;
  248. }
  249. 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) {
  250. #ifdef __EMSCRIPTEN__
  251. // Don't compile this code at all to avoid undefined references.
  252. // Actual virtual call goes to OS_JavaScript.
  253. ERR_FAIL_V(ERR_BUG);
  254. #else
  255. if (p_blocking && r_pipe) {
  256. String argss;
  257. argss = "\"" + p_path + "\"";
  258. for (int i = 0; i < p_arguments.size(); i++) {
  259. argss += String(" \"") + p_arguments[i] + "\"";
  260. }
  261. if (read_stderr) {
  262. argss += " 2>&1"; // Read stderr too
  263. } else {
  264. argss += " 2>/dev/null"; //silence stderr
  265. }
  266. FILE *f = popen(argss.utf8().get_data(), "r");
  267. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  268. char buf[65535];
  269. while (fgets(buf, 65535, f)) {
  270. (*r_pipe) += buf;
  271. }
  272. int rv = pclose(f);
  273. if (r_exitcode)
  274. *r_exitcode = rv;
  275. return OK;
  276. }
  277. pid_t pid = fork();
  278. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  279. if (pid == 0) {
  280. // is child
  281. Vector<CharString> cs;
  282. cs.push_back(p_path.utf8());
  283. for (int i = 0; i < p_arguments.size(); i++)
  284. cs.push_back(p_arguments[i].utf8());
  285. Vector<char *> args;
  286. for (int i = 0; i < cs.size(); i++)
  287. args.push_back((char *)cs[i].get_data());
  288. args.push_back(0);
  289. execvp(p_path.utf8().get_data(), &args[0]);
  290. // still alive? something failed..
  291. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  292. abort();
  293. }
  294. if (p_blocking) {
  295. int status;
  296. waitpid(pid, &status, 0);
  297. if (r_exitcode)
  298. *r_exitcode = WEXITSTATUS(status);
  299. } else {
  300. if (r_child_id)
  301. *r_child_id = pid;
  302. }
  303. return OK;
  304. #endif
  305. }
  306. Error OS_Unix::kill(const ProcessID &p_pid) {
  307. int ret = ::kill(p_pid, SIGKILL);
  308. if (!ret) {
  309. //avoid zombie process
  310. int st;
  311. ::waitpid(p_pid, &st, 0);
  312. }
  313. return ret ? ERR_INVALID_PARAMETER : OK;
  314. }
  315. int OS_Unix::get_process_id() const {
  316. return getpid();
  317. };
  318. bool OS_Unix::has_environment(const String &p_var) const {
  319. return getenv(p_var.utf8().get_data()) != NULL;
  320. }
  321. String OS_Unix::get_locale() const {
  322. if (!has_environment("LANG"))
  323. return "en";
  324. String locale = get_environment("LANG");
  325. int tp = locale.find(".");
  326. if (tp != -1)
  327. locale = locale.substr(0, tp);
  328. return locale;
  329. }
  330. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  331. String path = p_path;
  332. if (FileAccess::exists(path) && path.is_rel_path()) {
  333. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  334. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  335. path = "./" + path;
  336. }
  337. if (!FileAccess::exists(path)) {
  338. //this code exists so gdnative can load .so files from within the executable path
  339. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  340. }
  341. if (!FileAccess::exists(path)) {
  342. //this code exists so gdnative can load .so files from a standard unix location
  343. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  344. }
  345. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  346. if (!p_library_handle) {
  347. ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  348. ERR_FAIL_V(ERR_CANT_OPEN);
  349. }
  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 != NULL) {
  364. if (!p_optional) {
  365. ERR_EXPLAIN("Can't resolve symbol " + p_name + ". Error: " + error);
  366. ERR_FAIL_V(ERR_CANT_RESOLVE);
  367. } else {
  368. return ERR_CANT_RESOLVE;
  369. }
  370. }
  371. return OK;
  372. }
  373. Error OS_Unix::set_cwd(const String &p_cwd) {
  374. if (chdir(p_cwd.utf8().get_data()) != 0)
  375. return ERR_CANT_OPEN;
  376. return OK;
  377. }
  378. String OS_Unix::get_environment(const String &p_var) const {
  379. if (getenv(p_var.utf8().get_data()))
  380. return getenv(p_var.utf8().get_data());
  381. return "";
  382. }
  383. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  384. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  385. }
  386. int OS_Unix::get_processor_count() const {
  387. return sysconf(_SC_NPROCESSORS_CONF);
  388. }
  389. String OS_Unix::get_user_data_dir() const {
  390. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  391. if (appname != "") {
  392. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  393. if (use_custom_dir) {
  394. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  395. if (custom_dir == "") {
  396. custom_dir = appname;
  397. }
  398. return get_data_path().plus_file(custom_dir);
  399. } else {
  400. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  401. }
  402. }
  403. return ProjectSettings::get_singleton()->get_resource_path();
  404. }
  405. String OS_Unix::get_executable_path() const {
  406. #ifdef __linux__
  407. //fix for running from a symlink
  408. char buf[256];
  409. memset(buf, 0, 256);
  410. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  411. String b;
  412. if (len > 0) {
  413. b.parse_utf8(buf, len);
  414. }
  415. if (b == "") {
  416. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  417. return OS::get_executable_path();
  418. }
  419. return b;
  420. #elif defined(__OpenBSD__)
  421. char resolved_path[MAXPATHLEN];
  422. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  423. return String(resolved_path);
  424. #elif defined(__FreeBSD__)
  425. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  426. char buf[MAXPATHLEN];
  427. size_t len = sizeof(buf);
  428. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  429. WARN_PRINT("Couldn't get executable path from sysctl");
  430. return OS::get_executable_path();
  431. }
  432. String b;
  433. b.parse_utf8(buf);
  434. return b;
  435. #elif defined(__APPLE__)
  436. char temp_path[1];
  437. uint32_t buff_size = 1;
  438. _NSGetExecutablePath(temp_path, &buff_size);
  439. char *resolved_path = new char[buff_size + 1];
  440. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  441. WARN_PRINT("MAXPATHLEN is too small");
  442. String path(resolved_path);
  443. delete[] resolved_path;
  444. return path;
  445. #else
  446. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  447. return OS::get_executable_path();
  448. #endif
  449. }
  450. 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) {
  451. if (!should_log(true)) {
  452. return;
  453. }
  454. const char *err_details;
  455. if (p_rationale && p_rationale[0])
  456. err_details = p_rationale;
  457. else
  458. err_details = p_code;
  459. switch (p_type) {
  460. case ERR_WARNING:
  461. logf_error("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function, err_details);
  462. logf_error("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
  463. break;
  464. case ERR_SCRIPT:
  465. logf_error("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  466. logf_error("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
  467. break;
  468. case ERR_SHADER:
  469. logf_error("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  470. logf_error("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
  471. break;
  472. case ERR_ERROR:
  473. default:
  474. logf_error("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  475. logf_error("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
  476. break;
  477. }
  478. }
  479. UnixTerminalLogger::~UnixTerminalLogger() {}
  480. OS_Unix::OS_Unix() {
  481. Vector<Logger *> loggers;
  482. loggers.push_back(memnew(UnixTerminalLogger));
  483. _set_logger(memnew(CompositeLogger(loggers)));
  484. }
  485. #endif