os_unix.cpp 19 KB

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