os_unix.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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_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 (ScriptDebugger::get_singleton() == NULL)
  89. return;
  90. ScriptDebugger::get_singleton()->set_depth(-1);
  91. ScriptDebugger::get_singleton()->set_lines_left(1);
  92. }
  93. void OS_Unix::initialize_debugging() {
  94. if (ScriptDebugger::get_singleton() != NULL) {
  95. struct sigaction action;
  96. memset(&action, 0, sizeof(action));
  97. action.sa_handler = handle_interrupt;
  98. sigaction(SIGINT, &action, NULL);
  99. }
  100. }
  101. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  102. return 0;
  103. }
  104. void OS_Unix::initialize_core() {
  105. #ifdef NO_THREADS
  106. ThreadDummy::make_default();
  107. SemaphoreDummy::make_default();
  108. MutexDummy::make_default();
  109. RWLockDummy::make_default();
  110. #else
  111. ThreadPosix::make_default();
  112. SemaphorePosix::make_default();
  113. MutexPosix::make_default();
  114. RWLockPosix::make_default();
  115. #endif
  116. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  117. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  118. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  119. //FileAccessBufferedFA<FileAccessUnix>::make_default();
  120. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  121. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  122. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  123. #ifndef NO_NETWORK
  124. NetSocketPosix::make_default();
  125. IP_Unix::make_default();
  126. #endif
  127. _setup_clock();
  128. }
  129. void OS_Unix::finalize_core() {
  130. NetSocketPosix::cleanup();
  131. }
  132. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  133. fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
  134. }
  135. String OS_Unix::get_stdin_string(bool p_block) {
  136. if (p_block) {
  137. char buff[1024];
  138. String ret = stdin_buf + fgets(buff, 1024, stdin);
  139. stdin_buf = "";
  140. return ret;
  141. }
  142. return "";
  143. }
  144. String OS_Unix::get_name() const {
  145. return "Unix";
  146. }
  147. uint64_t OS_Unix::get_unix_time() const {
  148. return time(NULL);
  149. };
  150. uint64_t OS_Unix::get_system_time_secs() const {
  151. struct timeval tv_now;
  152. gettimeofday(&tv_now, NULL);
  153. return uint64_t(tv_now.tv_sec);
  154. }
  155. uint64_t OS_Unix::get_system_time_msecs() const {
  156. struct timeval tv_now;
  157. gettimeofday(&tv_now, NULL);
  158. return uint64_t(tv_now.tv_sec * 1000 + tv_now.tv_usec / 1000);
  159. }
  160. OS::Date OS_Unix::get_date(bool utc) const {
  161. time_t t = time(NULL);
  162. struct tm *lt;
  163. if (utc)
  164. lt = gmtime(&t);
  165. else
  166. lt = localtime(&t);
  167. Date ret;
  168. ret.year = 1900 + lt->tm_year;
  169. // Index starting at 1 to match OS_Unix::get_date
  170. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  171. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  172. ret.month = (Month)(lt->tm_mon + 1);
  173. ret.day = lt->tm_mday;
  174. ret.weekday = (Weekday)lt->tm_wday;
  175. ret.dst = lt->tm_isdst;
  176. return ret;
  177. }
  178. OS::Time OS_Unix::get_time(bool utc) const {
  179. time_t t = time(NULL);
  180. struct tm *lt;
  181. if (utc)
  182. lt = gmtime(&t);
  183. else
  184. lt = localtime(&t);
  185. Time ret;
  186. ret.hour = lt->tm_hour;
  187. ret.min = lt->tm_min;
  188. ret.sec = lt->tm_sec;
  189. get_time_zone_info();
  190. return ret;
  191. }
  192. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  193. time_t t = time(NULL);
  194. struct tm *lt = localtime(&t);
  195. char name[16];
  196. strftime(name, 16, "%Z", lt);
  197. name[15] = 0;
  198. TimeZoneInfo ret;
  199. ret.name = name;
  200. char bias_buf[16];
  201. strftime(bias_buf, 16, "%z", lt);
  202. int bias;
  203. bias_buf[15] = 0;
  204. sscanf(bias_buf, "%d", &bias);
  205. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  206. int hour = (int)bias / 100;
  207. int minutes = bias % 100;
  208. if (bias < 0)
  209. ret.bias = hour * 60 - minutes;
  210. else
  211. ret.bias = hour * 60 + minutes;
  212. return ret;
  213. }
  214. void OS_Unix::delay_usec(uint32_t p_usec) const {
  215. struct timespec rem = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  216. while (nanosleep(&rem, &rem) == EINTR) {
  217. }
  218. }
  219. uint64_t OS_Unix::get_ticks_usec() const {
  220. #if defined(__APPLE__)
  221. uint64_t longtime = mach_absolute_time() * _clock_scale;
  222. #else
  223. // Unchecked return. Static analyzers might complain.
  224. // If _setup_clock() succeeded, we assume clock_gettime() works.
  225. struct timespec tv_now = { 0, 0 };
  226. clock_gettime(GODOT_CLOCK, &tv_now);
  227. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  228. #endif
  229. longtime -= _clock_start;
  230. return longtime;
  231. }
  232. 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) {
  233. #ifdef __EMSCRIPTEN__
  234. // Don't compile this code at all to avoid undefined references.
  235. // Actual virtual call goes to OS_JavaScript.
  236. ERR_FAIL_V(ERR_BUG);
  237. #else
  238. if (p_blocking && r_pipe) {
  239. String argss;
  240. argss = "\"" + p_path + "\"";
  241. for (int i = 0; i < p_arguments.size(); i++) {
  242. argss += String(" \"") + p_arguments[i] + "\"";
  243. }
  244. if (read_stderr) {
  245. argss += " 2>&1"; // Read stderr too
  246. } else {
  247. argss += " 2>/dev/null"; //silence stderr
  248. }
  249. FILE *f = popen(argss.utf8().get_data(), "r");
  250. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot pipe stream from process running with following arguments '" + argss + "'.");
  251. char buf[65535];
  252. while (fgets(buf, 65535, f)) {
  253. if (p_pipe_mutex) {
  254. p_pipe_mutex->lock();
  255. }
  256. (*r_pipe) += buf;
  257. if (p_pipe_mutex) {
  258. p_pipe_mutex->unlock();
  259. }
  260. }
  261. int rv = pclose(f);
  262. if (r_exitcode)
  263. *r_exitcode = rv;
  264. return OK;
  265. }
  266. pid_t pid = fork();
  267. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  268. if (pid == 0) {
  269. // is child
  270. if (!p_blocking) {
  271. // For non blocking calls, create a new session-ID so parent won't wait for it.
  272. // This ensures the process won't go zombie at end.
  273. setsid();
  274. }
  275. Vector<CharString> cs;
  276. cs.push_back(p_path.utf8());
  277. for (int i = 0; i < p_arguments.size(); i++)
  278. cs.push_back(p_arguments[i].utf8());
  279. Vector<char *> args;
  280. for (int i = 0; i < cs.size(); i++)
  281. args.push_back((char *)cs[i].get_data());
  282. args.push_back(0);
  283. execvp(p_path.utf8().get_data(), &args[0]);
  284. // still alive? something failed..
  285. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  286. abort();
  287. }
  288. if (p_blocking) {
  289. int status;
  290. waitpid(pid, &status, 0);
  291. if (r_exitcode)
  292. *r_exitcode = WEXITSTATUS(status);
  293. } else {
  294. if (r_child_id)
  295. *r_child_id = pid;
  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::has_environment(const String &p_var) const {
  313. return getenv(p_var.utf8().get_data()) != NULL;
  314. }
  315. String OS_Unix::get_locale() const {
  316. if (!has_environment("LANG"))
  317. return "en";
  318. String locale = get_environment("LANG");
  319. int tp = locale.find(".");
  320. if (tp != -1)
  321. locale = locale.substr(0, tp);
  322. return locale;
  323. }
  324. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  325. String path = p_path;
  326. if (FileAccess::exists(path) && path.is_rel_path()) {
  327. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  328. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  329. path = "./" + path;
  330. }
  331. if (!FileAccess::exists(path)) {
  332. //this code exists so gdnative can load .so files from within the executable path
  333. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  334. }
  335. if (!FileAccess::exists(path)) {
  336. //this code exists so gdnative can load .so files from a standard unix location
  337. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  338. }
  339. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  340. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  341. return OK;
  342. }
  343. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  344. if (dlclose(p_library_handle)) {
  345. return FAILED;
  346. }
  347. return OK;
  348. }
  349. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  350. const char *error;
  351. dlerror(); // Clear existing errors
  352. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  353. error = dlerror();
  354. if (error != NULL) {
  355. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  356. return ERR_CANT_RESOLVE;
  357. }
  358. return OK;
  359. }
  360. Error OS_Unix::set_cwd(const String &p_cwd) {
  361. if (chdir(p_cwd.utf8().get_data()) != 0)
  362. return ERR_CANT_OPEN;
  363. return OK;
  364. }
  365. String OS_Unix::get_environment(const String &p_var) const {
  366. if (getenv(p_var.utf8().get_data()))
  367. return getenv(p_var.utf8().get_data());
  368. return "";
  369. }
  370. bool OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  371. return setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ true) == 0;
  372. }
  373. int OS_Unix::get_processor_count() const {
  374. return sysconf(_SC_NPROCESSORS_CONF);
  375. }
  376. String OS_Unix::get_user_data_dir() const {
  377. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  378. if (appname != "") {
  379. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  380. if (use_custom_dir) {
  381. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  382. if (custom_dir == "") {
  383. custom_dir = appname;
  384. }
  385. return get_data_path().plus_file(custom_dir);
  386. } else {
  387. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  388. }
  389. }
  390. return ProjectSettings::get_singleton()->get_resource_path();
  391. }
  392. String OS_Unix::get_executable_path() const {
  393. #ifdef __linux__
  394. //fix for running from a symlink
  395. char buf[256];
  396. memset(buf, 0, 256);
  397. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  398. String b;
  399. if (len > 0) {
  400. b.parse_utf8(buf, len);
  401. }
  402. if (b == "") {
  403. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  404. return OS::get_executable_path();
  405. }
  406. return b;
  407. #elif defined(__OpenBSD__)
  408. char resolved_path[MAXPATHLEN];
  409. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  410. return String(resolved_path);
  411. #elif defined(__FreeBSD__)
  412. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  413. char buf[MAXPATHLEN];
  414. size_t len = sizeof(buf);
  415. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  416. WARN_PRINT("Couldn't get executable path from sysctl");
  417. return OS::get_executable_path();
  418. }
  419. String b;
  420. b.parse_utf8(buf);
  421. return b;
  422. #elif defined(__APPLE__)
  423. char temp_path[1];
  424. uint32_t buff_size = 1;
  425. _NSGetExecutablePath(temp_path, &buff_size);
  426. char *resolved_path = new char[buff_size + 1];
  427. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  428. WARN_PRINT("MAXPATHLEN is too small");
  429. String path(resolved_path);
  430. delete[] resolved_path;
  431. return path;
  432. #else
  433. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  434. return OS::get_executable_path();
  435. #endif
  436. }
  437. 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) {
  438. if (!should_log(true)) {
  439. return;
  440. }
  441. const char *err_details;
  442. if (p_rationale && p_rationale[0])
  443. err_details = p_rationale;
  444. else
  445. err_details = p_code;
  446. switch (p_type) {
  447. case ERR_WARNING:
  448. logf_error("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function, err_details);
  449. logf_error("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
  450. break;
  451. case ERR_SCRIPT:
  452. logf_error("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  453. logf_error("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
  454. break;
  455. case ERR_SHADER:
  456. logf_error("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  457. logf_error("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
  458. break;
  459. case ERR_ERROR:
  460. default:
  461. logf_error("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  462. logf_error("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
  463. break;
  464. }
  465. }
  466. UnixTerminalLogger::~UnixTerminalLogger() {}
  467. OS_Unix::OS_Unix() {
  468. Vector<Logger *> loggers;
  469. loggers.push_back(memnew(UnixTerminalLogger));
  470. _set_logger(memnew(CompositeLogger(loggers)));
  471. }
  472. #endif