os_unix.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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/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. #if defined(__APPLE__)
  41. #include <mach-o/dyld.h>
  42. #include <mach/host_info.h>
  43. #include <mach/mach_host.h>
  44. #include <mach/mach_time.h>
  45. #include <sys/sysctl.h>
  46. #endif
  47. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  48. #include <sys/param.h>
  49. #include <sys/sysctl.h>
  50. #endif
  51. #if defined(__FreeBSD__)
  52. #include <kvm.h>
  53. #endif
  54. #if defined(__OpenBSD__)
  55. #include <sys/swap.h>
  56. #include <uvm/uvmexp.h>
  57. #endif
  58. #if defined(__NetBSD__)
  59. #include <uvm/uvm_extern.h>
  60. #endif
  61. #include <dlfcn.h>
  62. #include <errno.h>
  63. #include <poll.h>
  64. #include <signal.h>
  65. #include <stdarg.h>
  66. #include <stdio.h>
  67. #include <stdlib.h>
  68. #include <string.h>
  69. #include <sys/resource.h>
  70. #include <sys/time.h>
  71. #include <sys/wait.h>
  72. #include <time.h>
  73. #include <unistd.h>
  74. #ifndef RTLD_DEEPBIND
  75. #define RTLD_DEEPBIND 0
  76. #endif
  77. #if defined(MACOS_ENABLED) || (defined(__ANDROID_API__) && __ANDROID_API__ >= 28)
  78. // Random location for getentropy. Fitting.
  79. #include <sys/random.h>
  80. #define UNIX_GET_ENTROPY
  81. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__GLIBC_MINOR__) && (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 26))
  82. // In <unistd.h>.
  83. // One day... (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 700)
  84. // https://publications.opengroup.org/standards/unix/c211
  85. #define UNIX_GET_ENTROPY
  86. #endif
  87. #if !defined(UNIX_GET_ENTROPY) && !defined(NO_URANDOM)
  88. #include <fcntl.h>
  89. #endif
  90. /// Clock Setup function (used by get_ticks_usec)
  91. static uint64_t _clock_start = 0;
  92. #if defined(__APPLE__)
  93. static double _clock_scale = 0;
  94. static void _setup_clock() {
  95. mach_timebase_info_data_t info;
  96. kern_return_t ret = mach_timebase_info(&info);
  97. ERR_FAIL_COND_MSG(ret != 0, "OS CLOCK IS NOT WORKING!");
  98. _clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
  99. _clock_start = mach_absolute_time() * _clock_scale;
  100. }
  101. #else
  102. #if defined(CLOCK_MONOTONIC_RAW) && !defined(WEB_ENABLED) // This is a better clock on Linux.
  103. #define GODOT_CLOCK CLOCK_MONOTONIC_RAW
  104. #else
  105. #define GODOT_CLOCK CLOCK_MONOTONIC
  106. #endif
  107. static void _setup_clock() {
  108. struct timespec tv_now = { 0, 0 };
  109. ERR_FAIL_COND_MSG(clock_gettime(GODOT_CLOCK, &tv_now) != 0, "OS CLOCK IS NOT WORKING!");
  110. _clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  111. }
  112. #endif
  113. static void handle_interrupt(int sig) {
  114. if (!EngineDebugger::is_active()) {
  115. return;
  116. }
  117. EngineDebugger::get_script_debugger()->set_depth(-1);
  118. EngineDebugger::get_script_debugger()->set_lines_left(1);
  119. }
  120. void OS_Unix::initialize_debugging() {
  121. if (EngineDebugger::is_active()) {
  122. struct sigaction action;
  123. memset(&action, 0, sizeof(action));
  124. action.sa_handler = handle_interrupt;
  125. sigaction(SIGINT, &action, nullptr);
  126. }
  127. }
  128. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  129. return 0;
  130. }
  131. void OS_Unix::initialize_core() {
  132. init_thread_posix();
  133. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  134. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  135. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  136. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  137. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  138. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  139. NetSocketPosix::make_default();
  140. IPUnix::make_default();
  141. _setup_clock();
  142. }
  143. void OS_Unix::finalize_core() {
  144. NetSocketPosix::cleanup();
  145. }
  146. Vector<String> OS_Unix::get_video_adapter_driver_info() const {
  147. return Vector<String>();
  148. }
  149. String OS_Unix::get_stdin_string() {
  150. char buff[1024];
  151. return String::utf8(fgets(buff, 1024, stdin));
  152. }
  153. Error OS_Unix::get_entropy(uint8_t *r_buffer, int p_bytes) {
  154. #if defined(UNIX_GET_ENTROPY)
  155. int left = p_bytes;
  156. int ofs = 0;
  157. do {
  158. int chunk = MIN(left, 256);
  159. ERR_FAIL_COND_V(getentropy(r_buffer + ofs, chunk), FAILED);
  160. left -= chunk;
  161. ofs += chunk;
  162. } while (left > 0);
  163. // Define this yourself if you don't want to fall back to /dev/urandom.
  164. #elif !defined(NO_URANDOM)
  165. int r = open("/dev/urandom", O_RDONLY);
  166. ERR_FAIL_COND_V(r < 0, FAILED);
  167. int left = p_bytes;
  168. do {
  169. ssize_t ret = read(r, r_buffer, p_bytes);
  170. ERR_FAIL_COND_V(ret <= 0, FAILED);
  171. left -= ret;
  172. } while (left > 0);
  173. #else
  174. return ERR_UNAVAILABLE;
  175. #endif
  176. return OK;
  177. }
  178. String OS_Unix::get_name() const {
  179. return "Unix";
  180. }
  181. String OS_Unix::get_distribution_name() const {
  182. return "";
  183. }
  184. String OS_Unix::get_version() const {
  185. return "";
  186. }
  187. double OS_Unix::get_unix_time() const {
  188. struct timeval tv_now;
  189. gettimeofday(&tv_now, nullptr);
  190. return (double)tv_now.tv_sec + double(tv_now.tv_usec) / 1000000;
  191. }
  192. OS::DateTime OS_Unix::get_datetime(bool p_utc) const {
  193. time_t t = time(nullptr);
  194. struct tm lt;
  195. if (p_utc) {
  196. gmtime_r(&t, &lt);
  197. } else {
  198. localtime_r(&t, &lt);
  199. }
  200. DateTime ret;
  201. ret.year = 1900 + lt.tm_year;
  202. // Index starting at 1 to match OS_Unix::get_date
  203. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  204. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  205. ret.month = (Month)(lt.tm_mon + 1);
  206. ret.day = lt.tm_mday;
  207. ret.weekday = (Weekday)lt.tm_wday;
  208. ret.hour = lt.tm_hour;
  209. ret.minute = lt.tm_min;
  210. ret.second = lt.tm_sec;
  211. ret.dst = lt.tm_isdst;
  212. return ret;
  213. }
  214. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  215. time_t t = time(nullptr);
  216. struct tm lt;
  217. localtime_r(&t, &lt);
  218. char name[16];
  219. strftime(name, 16, "%Z", &lt);
  220. name[15] = 0;
  221. TimeZoneInfo ret;
  222. ret.name = name;
  223. char bias_buf[16];
  224. strftime(bias_buf, 16, "%z", &lt);
  225. int bias;
  226. bias_buf[15] = 0;
  227. sscanf(bias_buf, "%d", &bias);
  228. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  229. int hour = (int)bias / 100;
  230. int minutes = bias % 100;
  231. if (bias < 0) {
  232. ret.bias = hour * 60 - minutes;
  233. } else {
  234. ret.bias = hour * 60 + minutes;
  235. }
  236. return ret;
  237. }
  238. void OS_Unix::delay_usec(uint32_t p_usec) const {
  239. struct timespec requested = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  240. struct timespec remaining;
  241. while (nanosleep(&requested, &remaining) == -1 && errno == EINTR) {
  242. requested.tv_sec = remaining.tv_sec;
  243. requested.tv_nsec = remaining.tv_nsec;
  244. }
  245. }
  246. uint64_t OS_Unix::get_ticks_usec() const {
  247. #if defined(__APPLE__)
  248. uint64_t longtime = mach_absolute_time() * _clock_scale;
  249. #else
  250. // Unchecked return. Static analyzers might complain.
  251. // If _setup_clock() succeeded, we assume clock_gettime() works.
  252. struct timespec tv_now = { 0, 0 };
  253. clock_gettime(GODOT_CLOCK, &tv_now);
  254. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  255. #endif
  256. longtime -= _clock_start;
  257. return longtime;
  258. }
  259. Dictionary OS_Unix::get_memory_info() const {
  260. Dictionary meminfo;
  261. meminfo["physical"] = -1;
  262. meminfo["free"] = -1;
  263. meminfo["available"] = -1;
  264. meminfo["stack"] = -1;
  265. #if defined(__APPLE__)
  266. int pagesize = 0;
  267. size_t len = sizeof(pagesize);
  268. if (sysctlbyname("vm.pagesize", &pagesize, &len, nullptr, 0) < 0) {
  269. ERR_PRINT(vformat("Could not get vm.pagesize, error code: %d - %s", errno, strerror(errno)));
  270. }
  271. int64_t phy_mem = 0;
  272. len = sizeof(phy_mem);
  273. if (sysctlbyname("hw.memsize", &phy_mem, &len, nullptr, 0) < 0) {
  274. ERR_PRINT(vformat("Could not get hw.memsize, error code: %d - %s", errno, strerror(errno)));
  275. }
  276. mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
  277. vm_statistics64_data_t vmstat;
  278. if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vmstat, &count) != KERN_SUCCESS) {
  279. ERR_PRINT("Could not get host vm statistics.");
  280. }
  281. struct xsw_usage swap_used;
  282. len = sizeof(swap_used);
  283. if (sysctlbyname("vm.swapusage", &swap_used, &len, nullptr, 0) < 0) {
  284. ERR_PRINT(vformat("Could not get vm.swapusage, error code: %d - %s", errno, strerror(errno)));
  285. }
  286. if (phy_mem != 0) {
  287. meminfo["physical"] = phy_mem;
  288. }
  289. if (vmstat.free_count * (int64_t)pagesize != 0) {
  290. meminfo["free"] = vmstat.free_count * (int64_t)pagesize;
  291. }
  292. if (swap_used.xsu_avail + vmstat.free_count * (int64_t)pagesize != 0) {
  293. meminfo["available"] = swap_used.xsu_avail + vmstat.free_count * (int64_t)pagesize;
  294. }
  295. #elif defined(__FreeBSD__)
  296. int pagesize = 0;
  297. size_t len = sizeof(pagesize);
  298. if (sysctlbyname("vm.stats.vm.v_page_size", &pagesize, &len, nullptr, 0) < 0) {
  299. ERR_PRINT(vformat("Could not get vm.stats.vm.v_page_size, error code: %d - %s", errno, strerror(errno)));
  300. }
  301. uint64_t mtotal = 0;
  302. len = sizeof(mtotal);
  303. if (sysctlbyname("vm.stats.vm.v_page_count", &mtotal, &len, nullptr, 0) < 0) {
  304. ERR_PRINT(vformat("Could not get vm.stats.vm.v_page_count, error code: %d - %s", errno, strerror(errno)));
  305. }
  306. uint64_t mfree = 0;
  307. len = sizeof(mfree);
  308. if (sysctlbyname("vm.stats.vm.v_free_count", &mfree, &len, nullptr, 0) < 0) {
  309. ERR_PRINT(vformat("Could not get vm.stats.vm.v_free_count, error code: %d - %s", errno, strerror(errno)));
  310. }
  311. uint64_t stotal = 0;
  312. uint64_t sused = 0;
  313. char errmsg[_POSIX2_LINE_MAX] = {};
  314. kvm_t *kd = kvm_openfiles(nullptr, "/dev/null", nullptr, 0, errmsg);
  315. if (kd == nullptr) {
  316. ERR_PRINT(vformat("kvm_openfiles failed, error: %s", errmsg));
  317. } else {
  318. struct kvm_swap swap_info[32];
  319. int count = kvm_getswapinfo(kd, swap_info, 32, 0);
  320. for (int i = 0; i < count; i++) {
  321. stotal += swap_info[i].ksw_total;
  322. sused += swap_info[i].ksw_used;
  323. }
  324. kvm_close(kd);
  325. }
  326. if (mtotal * pagesize != 0) {
  327. meminfo["physical"] = mtotal * pagesize;
  328. }
  329. if (mfree * pagesize != 0) {
  330. meminfo["free"] = mfree * pagesize;
  331. }
  332. if ((mfree + stotal - sused) * pagesize != 0) {
  333. meminfo["available"] = (mfree + stotal - sused) * pagesize;
  334. }
  335. #elif defined(__OpenBSD__)
  336. int pagesize = sysconf(_SC_PAGESIZE);
  337. const int mib[] = { CTL_VM, VM_UVMEXP };
  338. uvmexp uvmexp_info;
  339. size_t len = sizeof(uvmexp_info);
  340. if (sysctl(mib, 2, &uvmexp_info, &len, nullptr, 0) < 0) {
  341. ERR_PRINT(vformat("Could not get CTL_VM, VM_UVMEXP, error code: %d - %s", errno, strerror(errno)));
  342. }
  343. uint64_t stotal = 0;
  344. uint64_t sused = 0;
  345. int count = swapctl(SWAP_NSWAP, 0, 0);
  346. if (count > 0) {
  347. swapent swap_info[count];
  348. count = swapctl(SWAP_STATS, swap_info, count);
  349. for (int i = 0; i < count; i++) {
  350. if (swap_info[i].se_flags & SWF_ENABLE) {
  351. sused += swap_info[i].se_inuse;
  352. stotal += swap_info[i].se_nblks;
  353. }
  354. }
  355. }
  356. if (uvmexp_info.npages * pagesize != 0) {
  357. meminfo["physical"] = uvmexp_info.npages * pagesize;
  358. }
  359. if (uvmexp_info.free * pagesize != 0) {
  360. meminfo["free"] = uvmexp_info.free * pagesize;
  361. }
  362. if ((uvmexp_info.free * pagesize) + (stotal - sused) * DEV_BSIZE != 0) {
  363. meminfo["available"] = (uvmexp_info.free * pagesize) + (stotal - sused) * DEV_BSIZE;
  364. }
  365. #elif defined(__NetBSD__)
  366. int pagesize = sysconf(_SC_PAGESIZE);
  367. const int mib[] = { CTL_VM, VM_UVMEXP2 };
  368. uvmexp_sysctl uvmexp_info;
  369. size_t len = sizeof(uvmexp_info);
  370. if (sysctl(mib, 2, &uvmexp_info, &len, nullptr, 0) < 0) {
  371. ERR_PRINT(vformat("Could not get CTL_VM, VM_UVMEXP2, error code: %d - %s", errno, strerror(errno)));
  372. }
  373. if (uvmexp_info.npages * pagesize != 0) {
  374. meminfo["physical"] = uvmexp_info.npages * pagesize;
  375. }
  376. if (uvmexp_info.free * pagesize != 0) {
  377. meminfo["free"] = uvmexp_info.free * pagesize;
  378. }
  379. if ((uvmexp_info.free + uvmexp_info.swpages - uvmexp_info.swpginuse) * pagesize != 0) {
  380. meminfo["available"] = (uvmexp_info.free + uvmexp_info.swpages - uvmexp_info.swpginuse) * pagesize;
  381. }
  382. #else
  383. Error err;
  384. Ref<FileAccess> f = FileAccess::open("/proc/meminfo", FileAccess::READ, &err);
  385. uint64_t mtotal = 0;
  386. uint64_t mfree = 0;
  387. uint64_t sfree = 0;
  388. while (f.is_valid() && !f->eof_reached()) {
  389. String s = f->get_line().strip_edges();
  390. if (s.begins_with("MemTotal:")) {
  391. Vector<String> stok = s.replace("MemTotal:", "").strip_edges().split(" ");
  392. if (stok.size() == 2) {
  393. mtotal = stok[0].to_int() * 1024;
  394. }
  395. }
  396. if (s.begins_with("MemFree:")) {
  397. Vector<String> stok = s.replace("MemFree:", "").strip_edges().split(" ");
  398. if (stok.size() == 2) {
  399. mfree = stok[0].to_int() * 1024;
  400. }
  401. }
  402. if (s.begins_with("SwapFree:")) {
  403. Vector<String> stok = s.replace("SwapFree:", "").strip_edges().split(" ");
  404. if (stok.size() == 2) {
  405. sfree = stok[0].to_int() * 1024;
  406. }
  407. }
  408. }
  409. if (mtotal != 0) {
  410. meminfo["physical"] = mtotal;
  411. }
  412. if (mfree != 0) {
  413. meminfo["free"] = mfree;
  414. }
  415. if (mfree + sfree != 0) {
  416. meminfo["available"] = mfree + sfree;
  417. }
  418. #endif
  419. rlimit stackinfo = {};
  420. getrlimit(RLIMIT_STACK, &stackinfo);
  421. if (stackinfo.rlim_cur != 0) {
  422. meminfo["stack"] = (int64_t)stackinfo.rlim_cur;
  423. }
  424. return meminfo;
  425. }
  426. 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, bool p_open_console) {
  427. #ifdef __EMSCRIPTEN__
  428. // Don't compile this code at all to avoid undefined references.
  429. // Actual virtual call goes to OS_Web.
  430. ERR_FAIL_V(ERR_BUG);
  431. #else
  432. if (r_pipe) {
  433. String command = "\"" + p_path + "\"";
  434. for (int i = 0; i < p_arguments.size(); i++) {
  435. command += String(" \"") + p_arguments[i] + "\"";
  436. }
  437. if (read_stderr) {
  438. command += " 2>&1"; // Include stderr
  439. } else {
  440. command += " 2>/dev/null"; // Silence stderr
  441. }
  442. FILE *f = popen(command.utf8().get_data(), "r");
  443. ERR_FAIL_NULL_V_MSG(f, ERR_CANT_OPEN, "Cannot create pipe from command: " + command + ".");
  444. char buf[65535];
  445. while (fgets(buf, 65535, f)) {
  446. if (p_pipe_mutex) {
  447. p_pipe_mutex->lock();
  448. }
  449. String pipe_out;
  450. if (pipe_out.parse_utf8(buf) == OK) {
  451. (*r_pipe) += pipe_out;
  452. } else {
  453. (*r_pipe) += String(buf); // If not valid UTF-8 try decode as Latin-1
  454. }
  455. if (p_pipe_mutex) {
  456. p_pipe_mutex->unlock();
  457. }
  458. }
  459. int rv = pclose(f);
  460. if (r_exitcode) {
  461. *r_exitcode = WEXITSTATUS(rv);
  462. }
  463. return OK;
  464. }
  465. pid_t pid = fork();
  466. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  467. if (pid == 0) {
  468. // The child process
  469. Vector<CharString> cs;
  470. cs.push_back(p_path.utf8());
  471. for (int i = 0; i < p_arguments.size(); i++) {
  472. cs.push_back(p_arguments[i].utf8());
  473. }
  474. Vector<char *> args;
  475. for (int i = 0; i < cs.size(); i++) {
  476. args.push_back((char *)cs[i].get_data());
  477. }
  478. args.push_back(0);
  479. execvp(p_path.utf8().get_data(), &args[0]);
  480. // The execvp() function only returns if an error occurs.
  481. ERR_PRINT("Could not create child process: " + p_path);
  482. raise(SIGKILL);
  483. }
  484. int status;
  485. waitpid(pid, &status, 0);
  486. if (r_exitcode) {
  487. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  488. }
  489. return OK;
  490. #endif
  491. }
  492. Error OS_Unix::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  493. #ifdef __EMSCRIPTEN__
  494. // Don't compile this code at all to avoid undefined references.
  495. // Actual virtual call goes to OS_Web.
  496. ERR_FAIL_V(ERR_BUG);
  497. #else
  498. pid_t pid = fork();
  499. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  500. if (pid == 0) {
  501. // The new process
  502. // Create a new session-ID so parent won't wait for it.
  503. // This ensures the process won't go zombie at the end.
  504. setsid();
  505. Vector<CharString> cs;
  506. cs.push_back(p_path.utf8());
  507. for (int i = 0; i < p_arguments.size(); i++) {
  508. cs.push_back(p_arguments[i].utf8());
  509. }
  510. Vector<char *> args;
  511. for (int i = 0; i < cs.size(); i++) {
  512. args.push_back((char *)cs[i].get_data());
  513. }
  514. args.push_back(0);
  515. execvp(p_path.utf8().get_data(), &args[0]);
  516. // The execvp() function only returns if an error occurs.
  517. ERR_PRINT("Could not create child process: " + p_path);
  518. raise(SIGKILL);
  519. }
  520. if (r_child_id) {
  521. *r_child_id = pid;
  522. }
  523. return OK;
  524. #endif
  525. }
  526. Error OS_Unix::kill(const ProcessID &p_pid) {
  527. int ret = ::kill(p_pid, SIGKILL);
  528. if (!ret) {
  529. //avoid zombie process
  530. int st;
  531. ::waitpid(p_pid, &st, 0);
  532. }
  533. return ret ? ERR_INVALID_PARAMETER : OK;
  534. }
  535. int OS_Unix::get_process_id() const {
  536. return getpid();
  537. }
  538. bool OS_Unix::is_process_running(const ProcessID &p_pid) const {
  539. int status = 0;
  540. if (waitpid(p_pid, &status, WNOHANG) != 0) {
  541. return false;
  542. }
  543. return true;
  544. }
  545. String OS_Unix::get_locale() const {
  546. if (!has_environment("LANG")) {
  547. return "en";
  548. }
  549. String locale = get_environment("LANG");
  550. int tp = locale.find(".");
  551. if (tp != -1) {
  552. locale = locale.substr(0, tp);
  553. }
  554. return locale;
  555. }
  556. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path, String *r_resolved_path) {
  557. String path = p_path;
  558. if (FileAccess::exists(path) && path.is_relative_path()) {
  559. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  560. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  561. path = "./" + path;
  562. }
  563. if (!FileAccess::exists(path)) {
  564. // This code exists so GDExtension can load .so files from within the executable path.
  565. path = get_executable_path().get_base_dir().path_join(p_path.get_file());
  566. }
  567. if (!FileAccess::exists(path)) {
  568. // This code exists so GDExtension can load .so files from a standard unix location.
  569. path = get_executable_path().get_base_dir().path_join("../lib").path_join(p_path.get_file());
  570. }
  571. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW | RTLD_DEEPBIND);
  572. ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
  573. if (r_resolved_path != nullptr) {
  574. *r_resolved_path = path;
  575. }
  576. return OK;
  577. }
  578. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  579. if (dlclose(p_library_handle)) {
  580. return FAILED;
  581. }
  582. return OK;
  583. }
  584. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  585. const char *error;
  586. dlerror(); // Clear existing errors
  587. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  588. error = dlerror();
  589. if (error != nullptr) {
  590. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  591. return ERR_CANT_RESOLVE;
  592. }
  593. return OK;
  594. }
  595. Error OS_Unix::set_cwd(const String &p_cwd) {
  596. if (chdir(p_cwd.utf8().get_data()) != 0) {
  597. return ERR_CANT_OPEN;
  598. }
  599. return OK;
  600. }
  601. bool OS_Unix::has_environment(const String &p_var) const {
  602. return getenv(p_var.utf8().get_data()) != nullptr;
  603. }
  604. String OS_Unix::get_environment(const String &p_var) const {
  605. if (getenv(p_var.utf8().get_data())) {
  606. return getenv(p_var.utf8().get_data());
  607. }
  608. return "";
  609. }
  610. void OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  611. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  612. int err = setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ 1);
  613. ERR_FAIL_COND_MSG(err != 0, vformat("Failed setting environment variable '%s', the system is out of memory.", p_var));
  614. }
  615. void OS_Unix::unset_environment(const String &p_var) const {
  616. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  617. unsetenv(p_var.utf8().get_data());
  618. }
  619. String OS_Unix::get_user_data_dir() const {
  620. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  621. if (!appname.is_empty()) {
  622. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  623. if (use_custom_dir) {
  624. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  625. if (custom_dir.is_empty()) {
  626. custom_dir = appname;
  627. }
  628. return get_data_path().path_join(custom_dir);
  629. } else {
  630. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join(appname);
  631. }
  632. }
  633. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join("[unnamed project]");
  634. }
  635. String OS_Unix::get_executable_path() const {
  636. #ifdef __linux__
  637. //fix for running from a symlink
  638. char buf[256];
  639. memset(buf, 0, 256);
  640. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  641. String b;
  642. if (len > 0) {
  643. b.parse_utf8(buf, len);
  644. }
  645. if (b.is_empty()) {
  646. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  647. return OS::get_executable_path();
  648. }
  649. return b;
  650. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  651. char resolved_path[MAXPATHLEN];
  652. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  653. return String(resolved_path);
  654. #elif defined(__FreeBSD__)
  655. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  656. char buf[MAXPATHLEN];
  657. size_t len = sizeof(buf);
  658. if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0) {
  659. WARN_PRINT("Couldn't get executable path from sysctl");
  660. return OS::get_executable_path();
  661. }
  662. String b;
  663. b.parse_utf8(buf);
  664. return b;
  665. #elif defined(__APPLE__)
  666. char temp_path[1];
  667. uint32_t buff_size = 1;
  668. _NSGetExecutablePath(temp_path, &buff_size);
  669. char *resolved_path = new char[buff_size + 1];
  670. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1) {
  671. WARN_PRINT("MAXPATHLEN is too small");
  672. }
  673. String path = String::utf8(resolved_path);
  674. delete[] resolved_path;
  675. return path;
  676. #else
  677. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  678. return OS::get_executable_path();
  679. #endif
  680. }
  681. 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) {
  682. if (!should_log(true)) {
  683. return;
  684. }
  685. const char *err_details;
  686. if (p_rationale && p_rationale[0]) {
  687. err_details = p_rationale;
  688. } else {
  689. err_details = p_code;
  690. }
  691. // Disable color codes if stdout is not a TTY.
  692. // This prevents Godot from writing ANSI escape codes when redirecting
  693. // stdout and stderr to a file.
  694. const bool tty = isatty(fileno(stdout));
  695. const char *gray = tty ? "\E[0;90m" : "";
  696. const char *red = tty ? "\E[0;91m" : "";
  697. const char *red_bold = tty ? "\E[1;31m" : "";
  698. const char *yellow = tty ? "\E[0;93m" : "";
  699. const char *yellow_bold = tty ? "\E[1;33m" : "";
  700. const char *magenta = tty ? "\E[0;95m" : "";
  701. const char *magenta_bold = tty ? "\E[1;35m" : "";
  702. const char *cyan = tty ? "\E[0;96m" : "";
  703. const char *cyan_bold = tty ? "\E[1;36m" : "";
  704. const char *reset = tty ? "\E[0m" : "";
  705. switch (p_type) {
  706. case ERR_WARNING:
  707. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  708. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  709. break;
  710. case ERR_SCRIPT:
  711. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  712. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  713. break;
  714. case ERR_SHADER:
  715. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, err_details);
  716. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  717. break;
  718. case ERR_ERROR:
  719. default:
  720. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  721. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  722. break;
  723. }
  724. }
  725. UnixTerminalLogger::~UnixTerminalLogger() {}
  726. OS_Unix::OS_Unix() {
  727. Vector<Logger *> loggers;
  728. loggers.push_back(memnew(UnixTerminalLogger));
  729. _set_logger(memnew(CompositeLogger(loggers)));
  730. }
  731. #endif