os_unix.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "os_unix.h"
  30. #ifdef UNIX_ENABLED
  31. #include "servers/visual_server.h"
  32. #include "core/os/thread_dummy.h"
  33. #include "mutex_posix.h"
  34. #include "rw_lock_posix.h"
  35. #include "semaphore_posix.h"
  36. #include "thread_posix.h"
  37. //#include "core/io/file_access_buffered_fa.h"
  38. #include "dir_access_unix.h"
  39. #include "file_access_unix.h"
  40. #include "packet_peer_udp_posix.h"
  41. #include "stream_peer_tcp_posix.h"
  42. #include "tcp_server_posix.h"
  43. #ifdef __APPLE__
  44. #include <mach-o/dyld.h>
  45. #endif
  46. #ifdef __FreeBSD__
  47. #include <sys/param.h>
  48. #endif
  49. #include "global_config.h"
  50. #include <assert.h>
  51. #include <dlfcn.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. case ERR_SHADER:
  83. print("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  84. print("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
  85. break;
  86. }
  87. }
  88. void OS_Unix::debug_break() {
  89. assert(false);
  90. };
  91. int OS_Unix::get_audio_driver_count() const {
  92. return 1;
  93. }
  94. const char *OS_Unix::get_audio_driver_name(int p_driver) const {
  95. return "dummy";
  96. }
  97. int OS_Unix::unix_initialize_audio(int p_audio_driver) {
  98. return 0;
  99. }
  100. // Very simple signal handler to reap processes where ::execute was called with
  101. // !p_blocking
  102. void handle_sigchld(int sig) {
  103. int saved_errno = errno;
  104. while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {
  105. }
  106. errno = saved_errno;
  107. }
  108. void OS_Unix::initialize_core() {
  109. #ifdef NO_PTHREADS
  110. ThreadDummy::make_default();
  111. SemaphoreDummy::make_default();
  112. MutexDummy::make_default();
  113. #else
  114. ThreadPosix::make_default();
  115. SemaphorePosix::make_default();
  116. MutexPosix::make_default();
  117. RWLockPosix::make_default();
  118. #endif
  119. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
  120. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_USERDATA);
  121. FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_FILESYSTEM);
  122. //FileAccessBufferedFA<FileAccessUnix>::make_default();
  123. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_RESOURCES);
  124. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_USERDATA);
  125. DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
  126. #ifndef NO_NETWORK
  127. TCPServerPosix::make_default();
  128. StreamPeerTCPPosix::make_default();
  129. PacketPeerUDPPosix::make_default();
  130. IP_Unix::make_default();
  131. #endif
  132. ticks_start = 0;
  133. ticks_start = get_ticks_usec();
  134. struct sigaction sa;
  135. sa.sa_handler = &handle_sigchld;
  136. sigemptyset(&sa.sa_mask);
  137. sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
  138. if (sigaction(SIGCHLD, &sa, 0) == -1) {
  139. perror("ERROR sigaction() failed:");
  140. }
  141. }
  142. void OS_Unix::finalize_core() {
  143. }
  144. void OS_Unix::vprint(const char *p_format, va_list p_list, bool p_stder) {
  145. if (p_stder) {
  146. vfprintf(stderr, p_format, p_list);
  147. fflush(stderr);
  148. } else {
  149. vprintf(p_format, p_list);
  150. fflush(stdout);
  151. }
  152. }
  153. void OS_Unix::print(const char *p_format, ...) {
  154. va_list argp;
  155. va_start(argp, p_format);
  156. vprintf(p_format, argp);
  157. va_end(argp);
  158. }
  159. void OS_Unix::alert(const String &p_alert, const String &p_title) {
  160. fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
  161. }
  162. static int has_data(FILE *p_fd, int timeout_usec = 0) {
  163. fd_set readset;
  164. int fd = fileno(p_fd);
  165. FD_ZERO(&readset);
  166. FD_SET(fd, &readset);
  167. timeval time;
  168. time.tv_sec = 0;
  169. time.tv_usec = timeout_usec;
  170. int res = 0; //select(fd + 1, &readset, NULL, NULL, &time);
  171. return res > 0;
  172. };
  173. String OS_Unix::get_stdin_string(bool p_block) {
  174. String ret;
  175. if (p_block) {
  176. char buff[1024];
  177. ret = stdin_buf + fgets(buff, 1024, stdin);
  178. stdin_buf = "";
  179. return ret;
  180. };
  181. while (has_data(stdin)) {
  182. char ch;
  183. read(fileno(stdin), &ch, 1);
  184. if (ch == '\n') {
  185. ret = stdin_buf;
  186. stdin_buf = "";
  187. return ret;
  188. } else {
  189. char str[2] = { ch, 0 };
  190. stdin_buf += str;
  191. };
  192. };
  193. return "";
  194. }
  195. String OS_Unix::get_name() {
  196. return "Unix";
  197. }
  198. uint64_t OS_Unix::get_unix_time() const {
  199. return time(NULL);
  200. };
  201. uint64_t OS_Unix::get_system_time_secs() const {
  202. struct timeval tv_now;
  203. gettimeofday(&tv_now, NULL);
  204. //localtime(&tv_now.tv_usec);
  205. //localtime((const long *)&tv_now.tv_usec);
  206. return uint64_t(tv_now.tv_sec);
  207. }
  208. OS::Date OS_Unix::get_date(bool utc) const {
  209. time_t t = time(NULL);
  210. struct tm *lt;
  211. if (utc)
  212. lt = gmtime(&t);
  213. else
  214. lt = localtime(&t);
  215. Date ret;
  216. ret.year = 1900 + lt->tm_year;
  217. // Index starting at 1 to match OS_Unix::get_date
  218. // and Windows SYSTEMTIME and tm_mon follows the typical structure
  219. // of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
  220. ret.month = (Month)(lt->tm_mon + 1);
  221. ret.day = lt->tm_mday;
  222. ret.weekday = (Weekday)lt->tm_wday;
  223. ret.dst = lt->tm_isdst;
  224. return ret;
  225. }
  226. OS::Time OS_Unix::get_time(bool utc) const {
  227. time_t t = time(NULL);
  228. struct tm *lt;
  229. if (utc)
  230. lt = gmtime(&t);
  231. else
  232. lt = localtime(&t);
  233. Time ret;
  234. ret.hour = lt->tm_hour;
  235. ret.min = lt->tm_min;
  236. ret.sec = lt->tm_sec;
  237. get_time_zone_info();
  238. return ret;
  239. }
  240. OS::TimeZoneInfo OS_Unix::get_time_zone_info() const {
  241. time_t t = time(NULL);
  242. struct tm *lt = localtime(&t);
  243. char name[16];
  244. strftime(name, 16, "%Z", lt);
  245. name[15] = 0;
  246. TimeZoneInfo ret;
  247. ret.name = name;
  248. char bias_buf[16];
  249. strftime(bias_buf, 16, "%z", lt);
  250. int bias;
  251. bias_buf[15] = 0;
  252. sscanf(bias_buf, "%d", &bias);
  253. // convert from ISO 8601 (1 minute=1, 1 hour=100) to minutes
  254. int hour = (int)bias / 100;
  255. int minutes = bias % 100;
  256. if (bias < 0)
  257. ret.bias = hour * 60 - minutes;
  258. else
  259. ret.bias = hour * 60 + minutes;
  260. return ret;
  261. }
  262. void OS_Unix::delay_usec(uint32_t p_usec) const {
  263. usleep(p_usec);
  264. }
  265. uint64_t OS_Unix::get_ticks_usec() const {
  266. struct timeval tv_now;
  267. gettimeofday(&tv_now, NULL);
  268. uint64_t longtime = (uint64_t)tv_now.tv_usec + (uint64_t)tv_now.tv_sec * 1000000L;
  269. longtime -= ticks_start;
  270. return longtime;
  271. }
  272. 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) {
  273. if (p_blocking && r_pipe) {
  274. String argss;
  275. argss = "\"" + p_path + "\"";
  276. for (int i = 0; i < p_arguments.size(); i++) {
  277. argss += String(" \"") + p_arguments[i] + "\"";
  278. }
  279. argss += " 2>/dev/null"; //silence stderr
  280. FILE *f = popen(argss.utf8().get_data(), "r");
  281. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  282. char buf[65535];
  283. while (fgets(buf, 65535, f)) {
  284. (*r_pipe) += buf;
  285. }
  286. int rv = pclose(f);
  287. if (r_exitcode)
  288. *r_exitcode = rv;
  289. return OK;
  290. }
  291. pid_t pid = fork();
  292. ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
  293. if (pid == 0) {
  294. // is child
  295. Vector<CharString> cs;
  296. cs.push_back(p_path.utf8());
  297. for (int i = 0; i < p_arguments.size(); i++)
  298. cs.push_back(p_arguments[i].utf8());
  299. Vector<char *> args;
  300. for (int i = 0; i < cs.size(); i++)
  301. args.push_back((char *)cs[i].get_data()); // shitty C cast
  302. args.push_back(0);
  303. #ifdef __FreeBSD__
  304. if (p_path.find("/")) {
  305. // exec name contains path so use it
  306. execv(p_path.utf8().get_data(), &args[0]);
  307. } else {
  308. // use program name and search through PATH to find it
  309. execvp(getprogname(), &args[0]);
  310. }
  311. #else
  312. execv(p_path.utf8().get_data(), &args[0]);
  313. #endif
  314. // still alive? something failed..
  315. fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
  316. abort();
  317. }
  318. if (p_blocking) {
  319. int status;
  320. waitpid(pid, &status, 0);
  321. if (r_exitcode)
  322. *r_exitcode = WEXITSTATUS(status);
  323. } else {
  324. if (r_child_id)
  325. *r_child_id = pid;
  326. }
  327. return OK;
  328. }
  329. Error OS_Unix::kill(const ProcessID &p_pid) {
  330. int ret = ::kill(p_pid, SIGKILL);
  331. if (!ret) {
  332. //avoid zombie process
  333. int st;
  334. ::waitpid(p_pid, &st, 0);
  335. }
  336. return ret ? ERR_INVALID_PARAMETER : OK;
  337. }
  338. int OS_Unix::get_process_ID() const {
  339. return getpid();
  340. };
  341. bool OS_Unix::has_environment(const String &p_var) const {
  342. return getenv(p_var.utf8().get_data()) != NULL;
  343. }
  344. String OS_Unix::get_locale() const {
  345. if (!has_environment("LANG"))
  346. return "en";
  347. String locale = get_environment("LANG");
  348. int tp = locale.find(".");
  349. if (tp != -1)
  350. locale = locale.substr(0, tp);
  351. return locale;
  352. }
  353. Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle) {
  354. p_library_handle = dlopen(p_path.utf8().get_data(), RTLD_NOW);
  355. if (!p_library_handle) {
  356. ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  357. ERR_FAIL_V(ERR_CANT_OPEN);
  358. }
  359. return OK;
  360. }
  361. Error OS_Unix::close_dynamic_library(void *p_library_handle) {
  362. if (dlclose(p_library_handle)) {
  363. return FAILED;
  364. }
  365. return OK;
  366. }
  367. Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle) {
  368. char *error;
  369. dlerror(); // Clear existing errors
  370. p_symbol_handle = dlsym(p_library_handle, p_name.utf8().get_data());
  371. error = dlerror();
  372. if (error != NULL) {
  373. ERR_EXPLAIN("Can't resolve symbol " + p_name + ". Error: " + error);
  374. ERR_FAIL_V(ERR_CANT_RESOLVE);
  375. }
  376. return OK;
  377. }
  378. Error OS_Unix::set_cwd(const String &p_cwd) {
  379. if (chdir(p_cwd.utf8().get_data()) != 0)
  380. return ERR_CANT_OPEN;
  381. return OK;
  382. }
  383. String OS_Unix::get_environment(const String &p_var) const {
  384. if (getenv(p_var.utf8().get_data()))
  385. return getenv(p_var.utf8().get_data());
  386. return "";
  387. }
  388. int OS_Unix::get_processor_count() const {
  389. return sysconf(_SC_NPROCESSORS_CONF);
  390. }
  391. String OS_Unix::get_data_dir() const {
  392. String an = get_safe_application_name();
  393. if (an != "") {
  394. if (has_environment("HOME")) {
  395. bool use_godot = GlobalConfig::get_singleton()->get("application/use_shared_user_dir");
  396. if (use_godot)
  397. return get_environment("HOME") + "/.godot/app_userdata/" + an;
  398. else
  399. return get_environment("HOME") + "/." + an;
  400. }
  401. }
  402. return GlobalConfig::get_singleton()->get_resource_path();
  403. }
  404. bool OS_Unix::check_feature_support(const String &p_feature) {
  405. return VisualServer::get_singleton()->has_os_feature(p_feature);
  406. }
  407. String OS_Unix::get_installed_templates_path() const {
  408. String p = get_global_settings_path();
  409. if (p != "")
  410. return p + "/templates/";
  411. else
  412. return "";
  413. }
  414. String OS_Unix::get_executable_path() const {
  415. #ifdef __linux__
  416. //fix for running from a symlink
  417. char buf[256];
  418. memset(buf, 0, 256);
  419. readlink("/proc/self/exe", buf, sizeof(buf));
  420. String b;
  421. b.parse_utf8(buf);
  422. if (b == "") {
  423. WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
  424. return OS::get_executable_path();
  425. }
  426. return b;
  427. #elif defined(__FreeBSD__)
  428. char resolved_path[MAXPATHLEN];
  429. realpath(OS::get_executable_path().utf8().get_data(), resolved_path);
  430. return String(resolved_path);
  431. #elif defined(__APPLE__)
  432. char temp_path[1];
  433. uint32_t buff_size = 1;
  434. _NSGetExecutablePath(temp_path, &buff_size);
  435. char *resolved_path = new char[buff_size + 1];
  436. if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
  437. WARN_PRINT("MAXPATHLEN is too small");
  438. String path(resolved_path);
  439. delete[] resolved_path;
  440. return path;
  441. #else
  442. ERR_PRINT("Warning, don't know how to obtain executable path on this OS! Please override this function properly.");
  443. return OS::get_executable_path();
  444. #endif
  445. }
  446. #endif