os_unix.cpp 14 KB

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