os_unix.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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. Dictionary OS_Unix::execute_with_pipe(const String &p_path, const List<String> &p_arguments, bool p_blocking) {
  517. #define CLEAN_PIPES \
  518. if (pipe_in[0] >= 0) { \
  519. ::close(pipe_in[0]); \
  520. } \
  521. if (pipe_in[1] >= 0) { \
  522. ::close(pipe_in[1]); \
  523. } \
  524. if (pipe_out[0] >= 0) { \
  525. ::close(pipe_out[0]); \
  526. } \
  527. if (pipe_out[1] >= 0) { \
  528. ::close(pipe_out[1]); \
  529. } \
  530. if (pipe_err[0] >= 0) { \
  531. ::close(pipe_err[0]); \
  532. } \
  533. if (pipe_err[1] >= 0) { \
  534. ::close(pipe_err[1]); \
  535. }
  536. Dictionary ret;
  537. #ifdef __EMSCRIPTEN__
  538. // Don't compile this code at all to avoid undefined references.
  539. // Actual virtual call goes to OS_Web.
  540. ERR_FAIL_V(ret);
  541. #else
  542. // Create pipes.
  543. int pipe_in[2] = { -1, -1 };
  544. int pipe_out[2] = { -1, -1 };
  545. int pipe_err[2] = { -1, -1 };
  546. ERR_FAIL_COND_V(pipe(pipe_in) != 0, ret);
  547. if (pipe(pipe_out) != 0) {
  548. CLEAN_PIPES
  549. ERR_FAIL_V(ret);
  550. }
  551. if (pipe(pipe_err) != 0) {
  552. CLEAN_PIPES
  553. ERR_FAIL_V(ret);
  554. }
  555. // Create process.
  556. pid_t pid = fork();
  557. if (pid < 0) {
  558. CLEAN_PIPES
  559. ERR_FAIL_V(ret);
  560. }
  561. if (pid == 0) {
  562. // The child process.
  563. Vector<CharString> cs;
  564. cs.push_back(p_path.utf8());
  565. for (const String &arg : p_arguments) {
  566. cs.push_back(arg.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. ::close(STDIN_FILENO);
  574. ::dup2(pipe_in[0], STDIN_FILENO);
  575. ::close(STDOUT_FILENO);
  576. ::dup2(pipe_out[1], STDOUT_FILENO);
  577. ::close(STDERR_FILENO);
  578. ::dup2(pipe_err[1], STDERR_FILENO);
  579. CLEAN_PIPES
  580. execvp(p_path.utf8().get_data(), &args[0]);
  581. // The execvp() function only returns if an error occurs.
  582. ERR_PRINT("Could not create child process: " + p_path);
  583. raise(SIGKILL);
  584. }
  585. ::close(pipe_in[0]);
  586. ::close(pipe_out[1]);
  587. ::close(pipe_err[1]);
  588. Ref<FileAccessUnixPipe> main_pipe;
  589. main_pipe.instantiate();
  590. main_pipe->open_existing(pipe_out[0], pipe_in[1], p_blocking);
  591. Ref<FileAccessUnixPipe> err_pipe;
  592. err_pipe.instantiate();
  593. err_pipe->open_existing(pipe_err[0], 0, p_blocking);
  594. ProcessInfo pi;
  595. process_map_mutex.lock();
  596. process_map->insert(pid, pi);
  597. process_map_mutex.unlock();
  598. ret["stdio"] = main_pipe;
  599. ret["stderr"] = err_pipe;
  600. ret["pid"] = pid;
  601. #undef CLEAN_PIPES
  602. return ret;
  603. #endif
  604. }
  605. 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) {
  606. #ifdef __EMSCRIPTEN__
  607. // Don't compile this code at all to avoid undefined references.
  608. // Actual virtual call goes to OS_Web.
  609. ERR_FAIL_V(ERR_BUG);
  610. #else
  611. if (r_pipe) {
  612. String command = "\"" + p_path + "\"";
  613. for (const String &arg : p_arguments) {
  614. command += String(" \"") + arg + "\"";
  615. }
  616. if (read_stderr) {
  617. command += " 2>&1"; // Include stderr
  618. } else {
  619. command += " 2>/dev/null"; // Silence stderr
  620. }
  621. FILE *f = popen(command.utf8().get_data(), "r");
  622. ERR_FAIL_NULL_V_MSG(f, ERR_CANT_OPEN, "Cannot create pipe from command: " + command + ".");
  623. char buf[65535];
  624. while (fgets(buf, 65535, f)) {
  625. if (p_pipe_mutex) {
  626. p_pipe_mutex->lock();
  627. }
  628. String pipe_out;
  629. if (pipe_out.parse_utf8(buf) == OK) {
  630. (*r_pipe) += pipe_out;
  631. } else {
  632. (*r_pipe) += String(buf); // If not valid UTF-8 try decode as Latin-1
  633. }
  634. if (p_pipe_mutex) {
  635. p_pipe_mutex->unlock();
  636. }
  637. }
  638. int rv = pclose(f);
  639. if (r_exitcode) {
  640. *r_exitcode = WEXITSTATUS(rv);
  641. }
  642. return OK;
  643. }
  644. pid_t pid = fork();
  645. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  646. if (pid == 0) {
  647. // The child process
  648. Vector<CharString> cs;
  649. cs.push_back(p_path.utf8());
  650. for (const String &arg : p_arguments) {
  651. cs.push_back(arg.utf8());
  652. }
  653. Vector<char *> args;
  654. for (int i = 0; i < cs.size(); i++) {
  655. args.push_back((char *)cs[i].get_data());
  656. }
  657. args.push_back(0);
  658. execvp(p_path.utf8().get_data(), &args[0]);
  659. // The execvp() function only returns if an error occurs.
  660. ERR_PRINT("Could not create child process: " + p_path);
  661. raise(SIGKILL);
  662. }
  663. int status;
  664. waitpid(pid, &status, 0);
  665. if (r_exitcode) {
  666. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  667. }
  668. return OK;
  669. #endif
  670. }
  671. Error OS_Unix::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  672. #ifdef __EMSCRIPTEN__
  673. // Don't compile this code at all to avoid undefined references.
  674. // Actual virtual call goes to OS_Web.
  675. ERR_FAIL_V(ERR_BUG);
  676. #else
  677. pid_t pid = fork();
  678. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  679. if (pid == 0) {
  680. // The new process
  681. // Create a new session-ID so parent won't wait for it.
  682. // This ensures the process won't go zombie at the end.
  683. setsid();
  684. Vector<CharString> cs;
  685. cs.push_back(p_path.utf8());
  686. for (const String &arg : p_arguments) {
  687. cs.push_back(arg.utf8());
  688. }
  689. Vector<char *> args;
  690. for (int i = 0; i < cs.size(); i++) {
  691. args.push_back((char *)cs[i].get_data());
  692. }
  693. args.push_back(0);
  694. execvp(p_path.utf8().get_data(), &args[0]);
  695. // The execvp() function only returns if an error occurs.
  696. ERR_PRINT("Could not create child process: " + p_path);
  697. raise(SIGKILL);
  698. }
  699. ProcessInfo pi;
  700. process_map_mutex.lock();
  701. process_map->insert(pid, pi);
  702. process_map_mutex.unlock();
  703. if (r_child_id) {
  704. *r_child_id = pid;
  705. }
  706. return OK;
  707. #endif
  708. }
  709. Error OS_Unix::kill(const ProcessID &p_pid) {
  710. int ret = ::kill(p_pid, SIGKILL);
  711. if (!ret) {
  712. //avoid zombie process
  713. int st;
  714. ::waitpid(p_pid, &st, 0);
  715. }
  716. return ret ? ERR_INVALID_PARAMETER : OK;
  717. }
  718. int OS_Unix::get_process_id() const {
  719. return getpid();
  720. }
  721. bool OS_Unix::is_process_running(const ProcessID &p_pid) const {
  722. MutexLock lock(process_map_mutex);
  723. const ProcessInfo *pi = process_map->getptr(p_pid);
  724. if (pi && !pi->is_running) {
  725. return false;
  726. }
  727. int status = 0;
  728. if (waitpid(p_pid, &status, WNOHANG) != 0) {
  729. if (pi) {
  730. pi->is_running = false;
  731. pi->exit_code = status;
  732. }
  733. return false;
  734. }
  735. return true;
  736. }
  737. int OS_Unix::get_process_exit_code(const ProcessID &p_pid) const {
  738. MutexLock lock(process_map_mutex);
  739. const ProcessInfo *pi = process_map->getptr(p_pid);
  740. if (pi && !pi->is_running) {
  741. return pi->exit_code;
  742. }
  743. int status = 0;
  744. if (waitpid(p_pid, &status, WNOHANG) != 0) {
  745. status = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  746. if (pi) {
  747. pi->is_running = false;
  748. pi->exit_code = status;
  749. }
  750. return status;
  751. }
  752. return -1;
  753. }
  754. String OS_Unix::get_locale() const {
  755. if (!has_environment("LANG")) {
  756. return "en";
  757. }
  758. String locale = get_environment("LANG");
  759. int tp = locale.find_char('.');
  760. if (tp != -1) {
  761. locale = locale.substr(0, tp);
  762. }
  763. return locale;
  764. }
  765. Error OS_Unix::open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data) {
  766. String path = p_path;
  767. if (FileAccess::exists(path) && path.is_relative_path()) {
  768. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  769. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  770. path = "./" + path;
  771. }
  772. if (!FileAccess::exists(path)) {
  773. // This code exists so GDExtension can load .so files from within the executable path.
  774. path = get_executable_path().get_base_dir().path_join(p_path.get_file());
  775. }
  776. if (!FileAccess::exists(path)) {
  777. // This code exists so GDExtension can load .so files from a standard unix location.
  778. path = get_executable_path().get_base_dir().path_join("../lib").path_join(p_path.get_file());
  779. }
  780. ERR_FAIL_COND_V(!FileAccess::exists(path), ERR_FILE_NOT_FOUND);
  781. p_library_handle = dlopen(path.utf8().get_data(), GODOT_DLOPEN_MODE);
  782. ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, dlerror()));
  783. if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
  784. *p_data->r_resolved_path = path;
  785. }
  786. return OK;
  787. }
  788. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  789. if (dlclose(p_library_handle)) {
  790. return FAILED;
  791. }
  792. return OK;
  793. }
  794. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String &p_name, void *&p_symbol_handle, bool p_optional) {
  795. const char *error;
  796. dlerror(); // Clear existing errors
  797. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  798. error = dlerror();
  799. if (error != nullptr) {
  800. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  801. return ERR_CANT_RESOLVE;
  802. }
  803. return OK;
  804. }
  805. Error OS_Unix::set_cwd(const String &p_cwd) {
  806. if (chdir(p_cwd.utf8().get_data()) != 0) {
  807. return ERR_CANT_OPEN;
  808. }
  809. return OK;
  810. }
  811. bool OS_Unix::has_environment(const String &p_var) const {
  812. return getenv(p_var.utf8().get_data()) != nullptr;
  813. }
  814. String OS_Unix::get_environment(const String &p_var) const {
  815. const char *val = getenv(p_var.utf8().get_data());
  816. if (val == nullptr) { // Not set; return empty string
  817. return "";
  818. }
  819. String s;
  820. if (s.parse_utf8(val) == OK) {
  821. return s;
  822. }
  823. return String(val); // Not valid UTF-8, so return as-is
  824. }
  825. void OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  826. 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));
  827. int err = setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ 1);
  828. ERR_FAIL_COND_MSG(err != 0, vformat("Failed setting environment variable '%s', the system is out of memory.", p_var));
  829. }
  830. void OS_Unix::unset_environment(const String &p_var) const {
  831. 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));
  832. unsetenv(p_var.utf8().get_data());
  833. }
  834. String OS_Unix::get_user_data_dir(const String &p_user_dir) const {
  835. return get_data_path().path_join(p_user_dir);
  836. }
  837. String OS_Unix::get_executable_path() const {
  838. #ifdef __linux__
  839. //fix for running from a symlink
  840. char buf[256];
  841. memset(buf, 0, 256);
  842. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  843. String b;
  844. if (len > 0) {
  845. b.parse_utf8(buf, len);
  846. }
  847. if (b.is_empty()) {
  848. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  849. return OS::get_executable_path();
  850. }
  851. return b;
  852. #elif defined(__OpenBSD__)
  853. char resolved_path[MAXPATHLEN];
  854. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  855. return String(resolved_path);
  856. #elif defined(__NetBSD__)
  857. int mib[4] = { CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME };
  858. char buf[MAXPATHLEN];
  859. size_t len = sizeof(buf);
  860. if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0) {
  861. WARN_PRINT("Couldn't get executable path from sysctl");
  862. return OS::get_executable_path();
  863. }
  864. // 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:
  865. char resolved_path[MAXPATHLEN];
  866. realpath(buf, resolved_path);
  867. return String(resolved_path);
  868. #elif defined(__FreeBSD__)
  869. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  870. char buf[MAXPATHLEN];
  871. size_t len = sizeof(buf);
  872. if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0) {
  873. WARN_PRINT("Couldn't get executable path from sysctl");
  874. return OS::get_executable_path();
  875. }
  876. String b;
  877. b.parse_utf8(buf);
  878. return b;
  879. #elif defined(__APPLE__)
  880. char temp_path[1];
  881. uint32_t buff_size = 1;
  882. _NSGetExecutablePath(temp_path, &buff_size);
  883. char *resolved_path = new char[buff_size + 1];
  884. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1) {
  885. WARN_PRINT("MAXPATHLEN is too small");
  886. }
  887. String path = String::utf8(resolved_path);
  888. delete[] resolved_path;
  889. return path;
  890. #else
  891. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  892. return OS::get_executable_path();
  893. #endif
  894. }
  895. 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) {
  896. if (!should_log(true)) {
  897. return;
  898. }
  899. const char *err_details;
  900. if (p_rationale && p_rationale[0]) {
  901. err_details = p_rationale;
  902. } else {
  903. err_details = p_code;
  904. }
  905. // Disable color codes if stdout is not a TTY.
  906. // This prevents Godot from writing ANSI escape codes when redirecting
  907. // stdout and stderr to a file.
  908. const bool tty = isatty(fileno(stdout));
  909. const char *gray = tty ? "\E[0;90m" : "";
  910. const char *red = tty ? "\E[0;91m" : "";
  911. const char *red_bold = tty ? "\E[1;31m" : "";
  912. const char *yellow = tty ? "\E[0;93m" : "";
  913. const char *yellow_bold = tty ? "\E[1;33m" : "";
  914. const char *magenta = tty ? "\E[0;95m" : "";
  915. const char *magenta_bold = tty ? "\E[1;35m" : "";
  916. const char *cyan = tty ? "\E[0;96m" : "";
  917. const char *cyan_bold = tty ? "\E[1;36m" : "";
  918. const char *reset = tty ? "\E[0m" : "";
  919. switch (p_type) {
  920. case ERR_WARNING:
  921. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  922. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  923. break;
  924. case ERR_SCRIPT:
  925. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  926. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  927. break;
  928. case ERR_SHADER:
  929. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, err_details);
  930. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  931. break;
  932. case ERR_ERROR:
  933. default:
  934. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  935. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  936. break;
  937. }
  938. }
  939. UnixTerminalLogger::~UnixTerminalLogger() {}
  940. OS_Unix::OS_Unix() {
  941. Vector<Logger *> loggers;
  942. loggers.push_back(memnew(UnixTerminalLogger));
  943. _set_logger(memnew(CompositeLogger(loggers)));
  944. }
  945. #endif