os_unix.cpp 29 KB

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