os_unix.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*************************************************************************/
  2. /* os_unix.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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/os/thread_dummy.h"
  33. #include "core/project_settings.h"
  34. #include "drivers/unix/dir_access_unix.h"
  35. #include "drivers/unix/file_access_unix.h"
  36. #include "drivers/unix/mutex_posix.h"
  37. #include "drivers/unix/net_socket_posix.h"
  38. #include "drivers/unix/rw_lock_posix.h"
  39. #include "drivers/unix/semaphore_posix.h"
  40. #include "drivers/unix/thread_posix.h"
  41. #include "servers/visual_server.h"
  42. #ifdef __APPLE__
  43. #include <mach-o/dyld.h>
  44. #endif
  45. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  46. #include <sys/param.h>
  47. #include <sys/sysctl.h>
  48. #endif
  49. #include <assert.h>
  50. #include <dlfcn.h>
  51. #include <errno.h>
  52. #include <poll.h>
  53. #include <signal.h>
  54. #include <stdarg.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <sys/time.h>
  58. #include <sys/wait.h>
  59. #include <unistd.h>
  60. void OS_Unix::debug_break() {
  61. assert(false);
  62. };
  63. static void handle_interrupt(int sig) {
  64. if (ScriptDebugger::get_singleton() == NULL)
  65. return;
  66. ScriptDebugger::get_singleton()->set_depth(-1);
  67. ScriptDebugger::get_singleton()->set_lines_left(1);
  68. }
  69. void OS_Unix::initialize_debugging() {
  70. if (ScriptDebugger::get_singleton() != NULL) {
  71. struct sigaction action;
  72. action.sa_handler = handle_interrupt;
  73. sigaction(SIGINT, &action, NULL);
  74. }
  75. }
  76. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  77. return 0;
  78. }
  79. // Very simple signal handler to reap processes where ::execute was called with
  80. // !p_blocking
  81. void handle_sigchld(int sig) {
  82. int saved_errno = errno;
  83. while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {
  84. }
  85. errno = saved_errno;
  86. }
  87. void OS_Unix::initialize_core() {
  88. #ifdef NO_THREADS
  89. ThreadDummy::make_default();
  90. SemaphoreDummy::make_default();
  91. MutexDummy::make_default();
  92. RWLockDummy::make_default();
  93. #else
  94. ThreadPosix::make_default();
  95. SemaphorePosix::make_default();
  96. MutexPosix::make_default();
  97. RWLockPosix::make_default();
  98. #endif
  99. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  100. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  101. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  102. //FileAccessBufferedFA<FileAccessUnix>::make_default();
  103. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  104. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  105. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  106. #ifndef NO_NETWORK
  107. NetSocketPosix::make_default();
  108. IP_Unix::make_default();
  109. #endif
  110. ticks_start = 0;
  111. ticks_start = get_ticks_usec();
  112. struct sigaction sa;
  113. sa.sa_handler = &handle_sigchld;
  114. sigemptyset(&sa.sa_mask);
  115. sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
  116. if (sigaction(SIGCHLD, &sa, 0) == -1) {
  117. perror("ERROR sigaction() failed:");
  118. }
  119. }
  120. void OS_Unix::finalize_core() {
  121. }
  122. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  123. fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
  124. }
  125. String OS_Unix::get_stdin_string(bool p_block) {
  126. if (p_block) {
  127. char buff[1024];
  128. String ret = stdin_buf + fgets(buff, 1024, stdin);
  129. stdin_buf = "";
  130. return ret;
  131. }
  132. return "";
  133. }
  134. String OS_Unix::get_name() {
  135. return "Unix";
  136. }
  137. uint64_t OS_Unix::get_unix_time() const {
  138. return time(NULL);
  139. };
  140. uint64_t OS_Unix::get_system_time_secs() const {
  141. struct timeval tv_now;
  142. gettimeofday(&tv_now, NULL);
  143. return uint64_t(tv_now.tv_sec);
  144. }
  145. OS::Date OS_Unix::get_date(bool utc) const {
  146. time_t t = time(NULL);
  147. struct tm *lt;
  148. if (utc)
  149. lt = gmtime(&t);
  150. else
  151. lt = localtime(&t);
  152. Date ret;
  153. ret.year = 1900 + lt->tm_year;
  154. // Index starting at 1 to match OS_Unix::get_date
  155. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  156. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  157. ret.month = (Month)(lt->tm_mon + 1);
  158. ret.day = lt->tm_mday;
  159. ret.weekday = (Weekday)lt->tm_wday;
  160. ret.dst = lt->tm_isdst;
  161. return ret;
  162. }
  163. OS::Time OS_Unix::get_time(bool utc) const {
  164. time_t t = time(NULL);
  165. struct tm *lt;
  166. if (utc)
  167. lt = gmtime(&t);
  168. else
  169. lt = localtime(&t);
  170. Time ret;
  171. ret.hour = lt->tm_hour;
  172. ret.min = lt->tm_min;
  173. ret.sec = lt->tm_sec;
  174. get_time_zone_info();
  175. return ret;
  176. }
  177. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  178. time_t t = time(NULL);
  179. struct tm *lt = localtime(&t);
  180. char name[16];
  181. strftime(name, 16, "%Z", lt);
  182. name[15] = 0;
  183. TimeZoneInfo ret;
  184. ret.name = name;
  185. char bias_buf[16];
  186. strftime(bias_buf, 16, "%z", lt);
  187. int bias;
  188. bias_buf[15] = 0;
  189. sscanf(bias_buf, "%d", &bias);
  190. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  191. int hour = (int)bias / 100;
  192. int minutes = bias % 100;
  193. if (bias < 0)
  194. ret.bias = hour * 60 - minutes;
  195. else
  196. ret.bias = hour * 60 + minutes;
  197. return ret;
  198. }
  199. void OS_Unix::delay_usec(uint32_t p_usec) const {
  200. struct timespec rem = { static_cast<time_t>(p_usec / 1000000), static_cast<long>((p_usec % 1000000) * 1000) };
  201. while (nanosleep(&rem, &rem) == EINTR) {
  202. }
  203. }
  204. uint64_t OS_Unix::get_ticks_usec() const {
  205. struct timeval tv_now;
  206. gettimeofday(&tv_now, NULL);
  207. uint64_t longtime = (uint64_t)tv_now.tv_usec + (uint64_t)tv_now.tv_sec * 1000000L;
  208. longtime -= ticks_start;
  209. return longtime;
  210. }
  211. Error OS_Unix::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr) {
  212. if (p_blocking && r_pipe) {
  213. String argss;
  214. argss = "\"" + p_path + "\"";
  215. for (int i = 0; i < p_arguments.size(); i++) {
  216. argss += String(" \"") + p_arguments[i] + "\"";
  217. }
  218. if (read_stderr) {
  219. argss += " 2>&1"; // Read stderr too
  220. } else {
  221. argss += " 2>/dev/null"; //silence stderr
  222. }
  223. FILE *f = popen(argss.utf8().get_data(), "r");
  224. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  225. char buf[65535];
  226. while (fgets(buf, 65535, f)) {
  227. (*r_pipe) += buf;
  228. }
  229. int rv = pclose(f);
  230. if (r_exitcode)
  231. *r_exitcode = rv;
  232. return OK;
  233. }
  234. pid_t pid = fork();
  235. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  236. if (pid == 0) {
  237. // is child
  238. Vector<CharString> cs;
  239. cs.push_back(p_path.utf8());
  240. for (int i = 0; i < p_arguments.size(); i++)
  241. cs.push_back(p_arguments[i].utf8());
  242. Vector<char *> args;
  243. for (int i = 0; i < cs.size(); i++)
  244. args.push_back((char *)cs[i].get_data());
  245. args.push_back(0);
  246. execvp(p_path.utf8().get_data(), &args[0]);
  247. // still alive? something failed..
  248. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  249. abort();
  250. }
  251. if (p_blocking) {
  252. int status;
  253. waitpid(pid, &status, 0);
  254. if (r_exitcode)
  255. *r_exitcode = WEXITSTATUS(status);
  256. } else {
  257. if (r_child_id)
  258. *r_child_id = pid;
  259. }
  260. return OK;
  261. }
  262. Error OS_Unix::kill(const ProcessID &p_pid) {
  263. int ret = ::kill(p_pid, SIGKILL);
  264. if (!ret) {
  265. //avoid zombie process
  266. int st;
  267. ::waitpid(p_pid, &st, 0);
  268. }
  269. return ret ? ERR_INVALID_PARAMETER : OK;
  270. }
  271. int OS_Unix::get_process_id() const {
  272. return getpid();
  273. };
  274. bool OS_Unix::has_environment(const String &p_var) const {
  275. return getenv(p_var.utf8().get_data()) != NULL;
  276. }
  277. String OS_Unix::get_locale() const {
  278. if (!has_environment("LANG"))
  279. return "en";
  280. String locale = get_environment("LANG");
  281. int tp = locale.find(".");
  282. if (tp != -1)
  283. locale = locale.substr(0, tp);
  284. return locale;
  285. }
  286. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  287. String path = p_path;
  288. if (FileAccess::exists(path) && path.is_rel_path()) {
  289. // dlopen expects a slash, in this case a leading ./ for it to be interpreted as a relative path,
  290. // otherwise it will end up searching various system directories for the lib instead and finally failing.
  291. path = "./" + path;
  292. }
  293. if (!FileAccess::exists(path)) {
  294. //this code exists so gdnative can load .so files from within the executable path
  295. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  296. }
  297. if (!FileAccess::exists(path)) {
  298. //this code exists so gdnative can load .so files from a standard unix location
  299. path = get_executable_path().get_base_dir().plus_file("../lib").plus_file(p_path.get_file());
  300. }
  301. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  302. if (!p_library_handle) {
  303. ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  304. ERR_FAIL_V(ERR_CANT_OPEN);
  305. }
  306. return OK;
  307. }
  308. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  309. if (dlclose(p_library_handle)) {
  310. return FAILED;
  311. }
  312. return OK;
  313. }
  314. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  315. const char *error;
  316. dlerror(); // Clear existing errors
  317. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  318. error = dlerror();
  319. if (error != NULL) {
  320. if (!p_optional) {
  321. ERR_EXPLAIN("Can't resolve symbol " + p_name + ". Error: " + error);
  322. ERR_FAIL_V(ERR_CANT_RESOLVE);
  323. } else {
  324. return ERR_CANT_RESOLVE;
  325. }
  326. }
  327. return OK;
  328. }
  329. Error OS_Unix::set_cwd(const String &p_cwd) {
  330. if (chdir(p_cwd.utf8().get_data()) != 0)
  331. return ERR_CANT_OPEN;
  332. return OK;
  333. }
  334. String OS_Unix::get_environment(const String &p_var) const {
  335. if (getenv(p_var.utf8().get_data()))
  336. return getenv(p_var.utf8().get_data());
  337. return "";
  338. }
  339. int OS_Unix::get_processor_count() const {
  340. return sysconf(_SC_NPROCESSORS_CONF);
  341. }
  342. String OS_Unix::get_user_data_dir() const {
  343. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  344. if (appname != "") {
  345. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  346. if (use_custom_dir) {
  347. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  348. if (custom_dir == "") {
  349. custom_dir = appname;
  350. }
  351. return get_data_path().plus_file(custom_dir);
  352. } else {
  353. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname);
  354. }
  355. }
  356. return ProjectSettings::get_singleton()->get_resource_path();
  357. }
  358. String OS_Unix::get_executable_path() const {
  359. #ifdef __linux__
  360. //fix for running from a symlink
  361. char buf[256];
  362. memset(buf, 0, 256);
  363. readlink("/proc/self/exe", buf, sizeof(buf));
  364. String b;
  365. b.parse_utf8(buf);
  366. if (b == "") {
  367. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  368. return OS::get_executable_path();
  369. }
  370. return b;
  371. #elif defined(__OpenBSD__)
  372. char resolved_path[MAXPATHLEN];
  373. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  374. return String(resolved_path);
  375. #elif defined(__FreeBSD__)
  376. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  377. char buf[MAXPATHLEN];
  378. size_t len = sizeof(buf);
  379. if (sysctl(mib, 4, buf, &len, NULL, 0) != 0) {
  380. WARN_PRINT("Couldn't get executable path from sysctl");
  381. return OS::get_executable_path();
  382. }
  383. String b;
  384. b.parse_utf8(buf);
  385. return b;
  386. #elif defined(__APPLE__)
  387. char temp_path[1];
  388. uint32_t buff_size = 1;
  389. _NSGetExecutablePath(temp_path, &buff_size);
  390. char *resolved_path = new char[buff_size + 1];
  391. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  392. WARN_PRINT("MAXPATHLEN is too small");
  393. String path(resolved_path);
  394. delete[] resolved_path;
  395. return path;
  396. #else
  397. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  398. return OS::get_executable_path();
  399. #endif
  400. }
  401. void UnixTerminalLogger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
  402. if (!should_log(true)) {
  403. return;
  404. }
  405. const char *err_details;
  406. if (p_rationale && p_rationale[0])
  407. err_details = p_rationale;
  408. else
  409. err_details = p_code;
  410. switch (p_type) {
  411. case ERR_WARNING:
  412. logf_error("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function, err_details);
  413. logf_error("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
  414. break;
  415. case ERR_SCRIPT:
  416. logf_error("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  417. logf_error("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
  418. break;
  419. case ERR_SHADER:
  420. logf_error("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  421. logf_error("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
  422. break;
  423. case ERR_ERROR:
  424. default:
  425. logf_error("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  426. logf_error("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
  427. break;
  428. }
  429. }
  430. UnixTerminalLogger::~UnixTerminalLogger() {}
  431. OS_Unix::OS_Unix() {
  432. Vector<Logger *> loggers;
  433. loggers.push_back(memnew(UnixTerminalLogger));
  434. _set_logger(memnew(CompositeLogger(loggers)));
  435. }
  436. #endif