os_unix.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. #ifdef __APPLE__
  41. #include <mach-o/dyld.h>
  42. #include <mach/mach_time.h>
  43. #endif
  44. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  45. #include <sys/param.h>
  46. #include <sys/sysctl.h>
  47. #endif
  48. #include <dlfcn.h>
  49. #include <errno.h>
  50. #include <poll.h>
  51. #include <signal.h>
  52. #include <stdarg.h>
  53. #include <stdio.h>
  54. #include <stdlib.h>
  55. #include <string.h>
  56. #include <sys/time.h>
  57. #include <sys/wait.h>
  58. #include <time.h>
  59. #include <unistd.h>
  60. #if defined(MACOS_ENABLED) || (defined(__ANDROID_API__) && __ANDROID_API__ >= 28)
  61. // Random location for getentropy. Fitting.
  62. #include <sys/random.h>
  63. #define UNIX_GET_ENTROPY
  64. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__GLIBC_MINOR__) && (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 26))
  65. // In <unistd.h>.
  66. // One day... (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 700)
  67. // https://publications.opengroup.org/standards/unix/c211
  68. #define UNIX_GET_ENTROPY
  69. #endif
  70. #if !defined(UNIX_GET_ENTROPY) && !defined(NO_URANDOM)
  71. #include <fcntl.h>
  72. #endif
  73. /// Clock Setup function (used by get_ticks_usec)
  74. static uint64_t _clock_start = 0;
  75. #if defined(__APPLE__)
  76. static double _clock_scale = 0;
  77. static void _setup_clock() {
  78. mach_timebase_info_data_t info;
  79. kern_return_t ret = mach_timebase_info(&info);
  80. ERR_FAIL_COND_MSG(ret != 0, "OS CLOCK IS NOT WORKING!");
  81. _clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
  82. _clock_start = mach_absolute_time() * _clock_scale;
  83. }
  84. #else
  85. #if defined(CLOCK_MONOTONIC_RAW) && !defined(WEB_ENABLED) // This is a better clock on Linux.
  86. #define GODOT_CLOCK CLOCK_MONOTONIC_RAW
  87. #else
  88. #define GODOT_CLOCK CLOCK_MONOTONIC
  89. #endif
  90. static void _setup_clock() {
  91. struct timespec tv_now = { 0, 0 };
  92. ERR_FAIL_COND_MSG(clock_gettime(GODOT_CLOCK, &tv_now) != 0, "OS CLOCK IS NOT WORKING!");
  93. _clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  94. }
  95. #endif
  96. static void handle_interrupt(int sig) {
  97. if (!EngineDebugger::is_active()) {
  98. return;
  99. }
  100. EngineDebugger::get_script_debugger()->set_depth(-1);
  101. EngineDebugger::get_script_debugger()->set_lines_left(1);
  102. }
  103. void OS_Unix::initialize_debugging() {
  104. if (EngineDebugger::is_active()) {
  105. struct sigaction action;
  106. memset(&action, 0, sizeof(action));
  107. action.sa_handler = handle_interrupt;
  108. sigaction(SIGINT, &action, nullptr);
  109. }
  110. }
  111. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  112. return 0;
  113. }
  114. void OS_Unix::initialize_core() {
  115. init_thread_posix();
  116. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  117. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  118. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  119. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  120. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  121. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  122. NetSocketPosix::make_default();
  123. IPUnix::make_default();
  124. _setup_clock();
  125. }
  126. void OS_Unix::finalize_core() {
  127. NetSocketPosix::cleanup();
  128. }
  129. Vector<String> OS_Unix::get_video_adapter_driver_info() const {
  130. return Vector<String>();
  131. }
  132. String OS_Unix::get_stdin_string() {
  133. char buff[1024];
  134. return String::utf8(fgets(buff, 1024, stdin));
  135. }
  136. Error OS_Unix::get_entropy(uint8_t *r_buffer, int p_bytes) {
  137. #if defined(UNIX_GET_ENTROPY)
  138. int left = p_bytes;
  139. int ofs = 0;
  140. do {
  141. int chunk = MIN(left, 256);
  142. ERR_FAIL_COND_V(getentropy(r_buffer + ofs, chunk), FAILED);
  143. left -= chunk;
  144. ofs += chunk;
  145. } while (left > 0);
  146. // Define this yourself if you don't want to fall back to /dev/urandom.
  147. #elif !defined(NO_URANDOM)
  148. int r = open("/dev/urandom", O_RDONLY);
  149. ERR_FAIL_COND_V(r < 0, FAILED);
  150. int left = p_bytes;
  151. do {
  152. ssize_t ret = read(r, r_buffer, p_bytes);
  153. ERR_FAIL_COND_V(ret <= 0, FAILED);
  154. left -= ret;
  155. } while (left > 0);
  156. #else
  157. return ERR_UNAVAILABLE;
  158. #endif
  159. return OK;
  160. }
  161. String OS_Unix::get_name() const {
  162. return "Unix";
  163. }
  164. String OS_Unix::get_distribution_name() const {
  165. return "";
  166. }
  167. String OS_Unix::get_version() const {
  168. return "";
  169. }
  170. double OS_Unix::get_unix_time() const {
  171. struct timeval tv_now;
  172. gettimeofday(&tv_now, nullptr);
  173. return (double)tv_now.tv_sec + double(tv_now.tv_usec) / 1000000;
  174. }
  175. OS::DateTime OS_Unix::get_datetime(bool p_utc) const {
  176. time_t t = time(nullptr);
  177. struct tm lt;
  178. if (p_utc) {
  179. gmtime_r(&t, &lt);
  180. } else {
  181. localtime_r(&t, &lt);
  182. }
  183. DateTime ret;
  184. ret.year = 1900 + lt.tm_year;
  185. // Index starting at 1 to match OS_Unix::get_date
  186. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  187. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  188. ret.month = (Month)(lt.tm_mon + 1);
  189. ret.day = lt.tm_mday;
  190. ret.weekday = (Weekday)lt.tm_wday;
  191. ret.hour = lt.tm_hour;
  192. ret.minute = lt.tm_min;
  193. ret.second = lt.tm_sec;
  194. ret.dst = lt.tm_isdst;
  195. return ret;
  196. }
  197. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  198. time_t t = time(nullptr);
  199. struct tm lt;
  200. localtime_r(&t, &lt);
  201. char name[16];
  202. strftime(name, 16, "%Z", &lt);
  203. name[15] = 0;
  204. TimeZoneInfo ret;
  205. ret.name = name;
  206. char bias_buf[16];
  207. strftime(bias_buf, 16, "%z", &lt);
  208. int bias;
  209. bias_buf[15] = 0;
  210. sscanf(bias_buf, "%d", &bias);
  211. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  212. int hour = (int)bias / 100;
  213. int minutes = bias % 100;
  214. if (bias < 0) {
  215. ret.bias = hour * 60 - minutes;
  216. } else {
  217. ret.bias = hour * 60 + minutes;
  218. }
  219. return ret;
  220. }
  221. void OS_Unix::delay_usec(uint32_t p_usec) const {
  222. struct timespec requested = { static_cast<time_t>(p_usec / 1000000), (static_cast<long>(p_usec) % 1000000) * 1000 };
  223. struct timespec remaining;
  224. while (nanosleep(&requested, &remaining) == -1 && errno == EINTR) {
  225. requested.tv_sec = remaining.tv_sec;
  226. requested.tv_nsec = remaining.tv_nsec;
  227. }
  228. }
  229. uint64_t OS_Unix::get_ticks_usec() const {
  230. #if defined(__APPLE__)
  231. uint64_t longtime = mach_absolute_time() * _clock_scale;
  232. #else
  233. // Unchecked return. Static analyzers might complain.
  234. // If _setup_clock() succeeded, we assume clock_gettime() works.
  235. struct timespec tv_now = { 0, 0 };
  236. clock_gettime(GODOT_CLOCK, &tv_now);
  237. uint64_t longtime = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
  238. #endif
  239. longtime -= _clock_start;
  240. return longtime;
  241. }
  242. 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) {
  243. #ifdef __EMSCRIPTEN__
  244. // Don't compile this code at all to avoid undefined references.
  245. // Actual virtual call goes to OS_Web.
  246. ERR_FAIL_V(ERR_BUG);
  247. #else
  248. if (r_pipe) {
  249. String command = "\"" + p_path + "\"";
  250. for (int i = 0; i < p_arguments.size(); i++) {
  251. command += String(" \"") + p_arguments[i] + "\"";
  252. }
  253. if (read_stderr) {
  254. command += " 2>&1"; // Include stderr
  255. } else {
  256. command += " 2>/dev/null"; // Silence stderr
  257. }
  258. FILE *f = popen(command.utf8().get_data(), "r");
  259. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot create pipe from command: " + command);
  260. char buf[65535];
  261. while (fgets(buf, 65535, f)) {
  262. if (p_pipe_mutex) {
  263. p_pipe_mutex->lock();
  264. }
  265. String pipe_out;
  266. if (pipe_out.parse_utf8(buf) == OK) {
  267. (*r_pipe) += pipe_out;
  268. } else {
  269. (*r_pipe) += String(buf); // If not valid UTF-8 try decode as Latin-1
  270. }
  271. if (p_pipe_mutex) {
  272. p_pipe_mutex->unlock();
  273. }
  274. }
  275. int rv = pclose(f);
  276. if (r_exitcode) {
  277. *r_exitcode = WEXITSTATUS(rv);
  278. }
  279. return OK;
  280. }
  281. pid_t pid = fork();
  282. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  283. if (pid == 0) {
  284. // The child process
  285. Vector<CharString> cs;
  286. cs.push_back(p_path.utf8());
  287. for (int i = 0; i < p_arguments.size(); i++) {
  288. cs.push_back(p_arguments[i].utf8());
  289. }
  290. Vector<char *> args;
  291. for (int i = 0; i < cs.size(); i++) {
  292. args.push_back((char *)cs[i].get_data());
  293. }
  294. args.push_back(0);
  295. execvp(p_path.utf8().get_data(), &args[0]);
  296. // The execvp() function only returns if an error occurs.
  297. ERR_PRINT("Could not create child process: " + p_path);
  298. raise(SIGKILL);
  299. }
  300. int status;
  301. waitpid(pid, &status, 0);
  302. if (r_exitcode) {
  303. *r_exitcode = WIFEXITED(status) ? WEXITSTATUS(status) : status;
  304. }
  305. return OK;
  306. #endif
  307. }
  308. Error OS_Unix::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  309. #ifdef __EMSCRIPTEN__
  310. // Don't compile this code at all to avoid undefined references.
  311. // Actual virtual call goes to OS_Web.
  312. ERR_FAIL_V(ERR_BUG);
  313. #else
  314. pid_t pid = fork();
  315. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  316. if (pid == 0) {
  317. // The new process
  318. // Create a new session-ID so parent won't wait for it.
  319. // This ensures the process won't go zombie at the end.
  320. setsid();
  321. Vector<CharString> cs;
  322. cs.push_back(p_path.utf8());
  323. for (int i = 0; i < p_arguments.size(); i++) {
  324. cs.push_back(p_arguments[i].utf8());
  325. }
  326. Vector<char *> args;
  327. for (int i = 0; i < cs.size(); i++) {
  328. args.push_back((char *)cs[i].get_data());
  329. }
  330. args.push_back(0);
  331. execvp(p_path.utf8().get_data(), &args[0]);
  332. // The execvp() function only returns if an error occurs.
  333. ERR_PRINT("Could not create child process: " + p_path);
  334. raise(SIGKILL);
  335. }
  336. if (r_child_id) {
  337. *r_child_id = pid;
  338. }
  339. return OK;
  340. #endif
  341. }
  342. Error OS_Unix::kill(const ProcessID &p_pid) {
  343. int ret = ::kill(p_pid, SIGKILL);
  344. if (!ret) {
  345. //avoid zombie process
  346. int st;
  347. ::waitpid(p_pid, &st, 0);
  348. }
  349. return ret ? ERR_INVALID_PARAMETER : OK;
  350. }
  351. int OS_Unix::get_process_id() const {
  352. return getpid();
  353. }
  354. bool OS_Unix::is_process_running(const ProcessID &p_pid) const {
  355. int status = 0;
  356. if (waitpid(p_pid, &status, WNOHANG) != 0) {
  357. return false;
  358. }
  359. return true;
  360. }
  361. String OS_Unix::get_locale() const {
  362. if (!has_environment("LANG")) {
  363. return "en";
  364. }
  365. String locale = get_environment("LANG");
  366. int tp = locale.find(".");
  367. if (tp != -1) {
  368. locale = locale.substr(0, tp);
  369. }
  370. return locale;
  371. }
  372. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path, String *r_resolved_path) {
  373. String path = p_path;
  374. if (FileAccess::exists(path) && path.is_relative_path()) {
  375. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  376. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  377. path = "./" + path;
  378. }
  379. if (!FileAccess::exists(path)) {
  380. // This code exists so GDExtension can load .so files from within the executable path.
  381. path = get_executable_path().get_base_dir().path_join(p_path.get_file());
  382. }
  383. if (!FileAccess::exists(path)) {
  384. // This code exists so GDExtension can load .so files from a standard unix location.
  385. path = get_executable_path().get_base_dir().path_join("../lib").path_join(p_path.get_file());
  386. }
  387. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  388. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  389. if (r_resolved_path != nullptr) {
  390. *r_resolved_path = path;
  391. }
  392. return OK;
  393. }
  394. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  395. if (dlclose(p_library_handle)) {
  396. return FAILED;
  397. }
  398. return OK;
  399. }
  400. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  401. const char *error;
  402. dlerror(); // Clear existing errors
  403. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  404. error = dlerror();
  405. if (error != nullptr) {
  406. ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
  407. return ERR_CANT_RESOLVE;
  408. }
  409. return OK;
  410. }
  411. Error OS_Unix::set_cwd(const String &p_cwd) {
  412. if (chdir(p_cwd.utf8().get_data()) != 0) {
  413. return ERR_CANT_OPEN;
  414. }
  415. return OK;
  416. }
  417. bool OS_Unix::has_environment(const String &p_var) const {
  418. return getenv(p_var.utf8().get_data()) != nullptr;
  419. }
  420. String OS_Unix::get_environment(const String &p_var) const {
  421. if (getenv(p_var.utf8().get_data())) {
  422. return getenv(p_var.utf8().get_data());
  423. }
  424. return "";
  425. }
  426. void OS_Unix::set_environment(const String &p_var, const String &p_value) const {
  427. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  428. int err = setenv(p_var.utf8().get_data(), p_value.utf8().get_data(), /* overwrite: */ 1);
  429. ERR_FAIL_COND_MSG(err != 0, vformat("Failed setting environment variable '%s', the system is out of memory.", p_var));
  430. }
  431. void OS_Unix::unset_environment(const String &p_var) const {
  432. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  433. unsetenv(p_var.utf8().get_data());
  434. }
  435. String OS_Unix::get_user_data_dir() const {
  436. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  437. if (!appname.is_empty()) {
  438. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  439. if (use_custom_dir) {
  440. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  441. if (custom_dir.is_empty()) {
  442. custom_dir = appname;
  443. }
  444. return get_data_path().path_join(custom_dir);
  445. } else {
  446. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join(appname);
  447. }
  448. }
  449. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join("[unnamed project]");
  450. }
  451. String OS_Unix::get_executable_path() const {
  452. #ifdef __linux__
  453. //fix for running from a symlink
  454. char buf[256];
  455. memset(buf, 0, 256);
  456. ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf));
  457. String b;
  458. if (len > 0) {
  459. b.parse_utf8(buf, len);
  460. }
  461. if (b.is_empty()) {
  462. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  463. return OS::get_executable_path();
  464. }
  465. return b;
  466. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  467. char resolved_path[MAXPATHLEN];
  468. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  469. return String(resolved_path);
  470. #elif defined(__FreeBSD__)
  471. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  472. char buf[MAXPATHLEN];
  473. size_t len = sizeof(buf);
  474. if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0) {
  475. WARN_PRINT("Couldn't get executable path from sysctl");
  476. return OS::get_executable_path();
  477. }
  478. String b;
  479. b.parse_utf8(buf);
  480. return b;
  481. #elif defined(__APPLE__)
  482. char temp_path[1];
  483. uint32_t buff_size = 1;
  484. _NSGetExecutablePath(temp_path, &buff_size);
  485. char *resolved_path = new char[buff_size + 1];
  486. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1) {
  487. WARN_PRINT("MAXPATHLEN is too small");
  488. }
  489. String path = String::utf8(resolved_path);
  490. delete[] resolved_path;
  491. return path;
  492. #else
  493. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  494. return OS::get_executable_path();
  495. #endif
  496. }
  497. 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) {
  498. if (!should_log(true)) {
  499. return;
  500. }
  501. const char *err_details;
  502. if (p_rationale && p_rationale[0]) {
  503. err_details = p_rationale;
  504. } else {
  505. err_details = p_code;
  506. }
  507. // Disable color codes if stdout is not a TTY.
  508. // This prevents Godot from writing ANSI escape codes when redirecting
  509. // stdout and stderr to a file.
  510. const bool tty = isatty(fileno(stdout));
  511. const char *gray = tty ? "\E[0;90m" : "";
  512. const char *red = tty ? "\E[0;91m" : "";
  513. const char *red_bold = tty ? "\E[1;31m" : "";
  514. const char *yellow = tty ? "\E[0;93m" : "";
  515. const char *yellow_bold = tty ? "\E[1;33m" : "";
  516. const char *magenta = tty ? "\E[0;95m" : "";
  517. const char *magenta_bold = tty ? "\E[1;35m" : "";
  518. const char *cyan = tty ? "\E[0;96m" : "";
  519. const char *cyan_bold = tty ? "\E[1;36m" : "";
  520. const char *reset = tty ? "\E[0m" : "";
  521. switch (p_type) {
  522. case ERR_WARNING:
  523. logf_error("%sWARNING:%s %s\n", yellow_bold, yellow, err_details);
  524. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  525. break;
  526. case ERR_SCRIPT:
  527. logf_error("%sSCRIPT ERROR:%s %s\n", magenta_bold, magenta, err_details);
  528. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  529. break;
  530. case ERR_SHADER:
  531. logf_error("%sSHADER ERROR:%s %s\n", cyan_bold, cyan, err_details);
  532. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  533. break;
  534. case ERR_ERROR:
  535. default:
  536. logf_error("%sERROR:%s %s\n", red_bold, red, err_details);
  537. logf_error("%s at: %s (%s:%i)%s\n", gray, p_function, p_file, p_line, reset);
  538. break;
  539. }
  540. }
  541. UnixTerminalLogger::~UnixTerminalLogger() {}
  542. OS_Unix::OS_Unix() {
  543. Vector<Logger *> loggers;
  544. loggers.push_back(memnew(UnixTerminalLogger));
  545. _set_logger(memnew(CompositeLogger(loggers)));
  546. }
  547. #endif