os_unix.cpp 25 KB

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