os_unix.cpp 12 KB

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