os_unix.cpp 13 KB

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