os_unix.cpp 25 KB

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