os_unix.cpp 13 KB

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