os_unix.cpp 35 KB

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