os_unix.cpp 26 KB

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