os_unix.cpp 28 KB

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