os_unix.cpp 15 KB

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