os_unix.cpp 12 KB

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