os_unix.cpp 14 KB

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