os.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #pragma once
  24. #include "config.h"
  25. #include "types.h"
  26. #include "vector.h"
  27. #include "dynamic_string.h"
  28. #include "string_utils.h"
  29. #include "temp_allocator.h"
  30. #if CROWN_PLATFORM_POSIX
  31. #include "assert.h"
  32. #include <cstdarg>
  33. #include <cstdio>
  34. #include <cstdlib>
  35. #include <dirent.h>
  36. #include <dlfcn.h>
  37. #include <sys/stat.h>
  38. #include <sys/time.h>
  39. #include <sys/types.h>
  40. #include <sys/wait.h>
  41. #include <errno.h>
  42. #include <time.h>
  43. #include <unistd.h>
  44. #elif CROWN_PLATFORM_WINDOWS
  45. #include <win_headers.h>
  46. #include <io.h>
  47. #endif
  48. #if CROWN_PLATFORM_ANDROID
  49. #include <android/log.h>
  50. #endif
  51. namespace crown
  52. {
  53. #if CROWN_PLATFORM_LINUX
  54. const size_t MAX_PATH_LENGTH = 1024;
  55. const char PATH_SEPARATOR = '/';
  56. #elif CROWN_PLATFORM_WINDOWS
  57. const size_t MAX_PATH_LENGTH = 1024;
  58. const char PATH_SEPARATOR = '\\';
  59. #define snprintf _snprintf
  60. #elif CROWN_PLATFORM_ANDROID
  61. const size_t MAX_PATH_LENGTH = 1024;
  62. const char PATH_SEPARATOR = '/';
  63. #endif
  64. namespace os
  65. {
  66. //-----------------------------------------------------------------------------
  67. inline void log_debug(const char* string, va_list arg)
  68. {
  69. #if CROWN_PLATFORM_ANDROID
  70. __android_log_vprint(ANDROID_LOG_DEBUG, "crown", string, arg);
  71. #else
  72. vprintf(string, arg);
  73. printf("\n");
  74. #endif
  75. }
  76. //-----------------------------------------------------------------------------
  77. inline void log_error(const char* string, va_list arg)
  78. {
  79. #if CROWN_PLATFORM_ANDROID
  80. __android_log_vprint(ANDROID_LOG_ERROR, "crown", string, arg);
  81. #else
  82. vprintf(string, arg);
  83. printf("\n");
  84. #endif
  85. }
  86. //-----------------------------------------------------------------------------
  87. inline void log_warning(const char* string, va_list arg)
  88. {
  89. #if CROWN_PLATFORM_ANDROID
  90. __android_log_vprint(ANDROID_LOG_WARN, "crown", string, arg);
  91. #else
  92. vprintf(string, arg);
  93. printf("\n");
  94. #endif
  95. }
  96. //-----------------------------------------------------------------------------
  97. inline void log_info(const char* string, va_list arg)
  98. {
  99. #if CROWN_PLATFORM_ANDROID
  100. __android_log_vprint(ANDROID_LOG_INFO, "crown", string, arg);
  101. #else
  102. vprintf(string, arg);
  103. printf("\n");
  104. #endif
  105. }
  106. //-----------------------------------------------------------------------------
  107. inline bool is_root_path(const char* path)
  108. {
  109. #if CROWN_PLATFORM_POSIX
  110. return (path != NULL && string::strlen(path) == 1 && path[0] == PATH_SEPARATOR);
  111. #elif CROWN_PLATFORM_WINDOWS
  112. return (path != NULL && string::strlen(path) == 3 && string::is_alpha(path[0]) &&
  113. path[1] == ':' && path[2] == PATH_SEPARATOR);
  114. #endif
  115. }
  116. //-----------------------------------------------------------------------------
  117. inline bool is_absolute_path(const char* path)
  118. {
  119. #if CROWN_PLATFORM_POSIX
  120. return (path != NULL && string::strlen(path) >= 1 && path[0] == PATH_SEPARATOR);
  121. #elif CROWN_PLATFORM_WINDOWS
  122. return (path != NULL && string::strlen(path) >= 3 && string::is_alpha(path[0]) &&
  123. path[1] == ':' && path[2] == PATH_SEPARATOR);
  124. #endif
  125. }
  126. inline bool exists(const char* path)
  127. {
  128. #if CROWN_PLATFORM_POSIX
  129. return access(path, F_OK) != -1;
  130. #elif CROWN_PLATFORM_WINDOWS
  131. return _access(path, 0) != -1;
  132. #endif
  133. }
  134. /// Returns whether the path is a directory.
  135. inline bool is_directory(const char* path)
  136. {
  137. #if CROWN_PLATFORM_POSIX
  138. struct stat info;
  139. memset(&info, 0, sizeof(struct stat));
  140. int err = lstat(path, &info);
  141. CE_ASSERT(err == 0, "lstat: errno = %d", errno);
  142. CE_UNUSED(err);
  143. return ((S_ISDIR(info.st_mode) == 1) && (S_ISLNK(info.st_mode) == 0));
  144. #elif CROWN_PLATFORM_WINDOWS
  145. DWORD fattr = GetFileAttributes(path);
  146. return (fattr != INVALID_FILE_ATTRIBUTES && (fattr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  147. #endif
  148. }
  149. /// Returns whether the path is a regular file.
  150. inline bool is_file(const char* path)
  151. {
  152. #if CROWN_PLATFORM_POSIX
  153. struct stat info;
  154. memset(&info, 0, sizeof(struct stat));
  155. int err = lstat(path, &info);
  156. CE_ASSERT(err == 0, "lstat: errno = %d", errno);
  157. CE_UNUSED(err);
  158. return ((S_ISREG(info.st_mode) == 1) && (S_ISLNK(info.st_mode) == 0));
  159. #elif CROWN_PLATFORM_WINDOWS
  160. DWORD fattr = GetFileAttributes(path);
  161. return (fattr != INVALID_FILE_ATTRIBUTES && (fattr & FILE_ATTRIBUTE_DIRECTORY) == 0);
  162. #endif
  163. }
  164. /// Creates a regular file.
  165. inline void create_file(const char* path)
  166. {
  167. #if CROWN_PLATFORM_POSIX
  168. // Permission mask: rw-r--r--
  169. int err = ::mknod(path, S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH, 0);
  170. CE_ASSERT(err == 0, "mknod: errno = %d", errno);
  171. CE_UNUSED(err);
  172. #elif CROWN_PLATFORM_WINDOWS
  173. HANDLE hfile = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  174. CE_ASSERT(hfile != INVALID_HANDLE_VALUE, "CreateFile: GetLastError = %d", GetLastError());
  175. CloseHandle(hfile);
  176. #endif
  177. }
  178. /// Deletes a regular file.
  179. inline void delete_file(const char* path)
  180. {
  181. #if CROWN_PLATFORM_POSIX
  182. int err = ::unlink(path);
  183. CE_ASSERT(err == 0, "unlink: errno = %d", errno);
  184. CE_UNUSED(err);
  185. #elif CROWN_PLATFORM_WINDOWS
  186. BOOL err = DeleteFile(path);
  187. CE_ASSERT(err != 0, "DeleteFile: GetLastError = %d", GetLastError());
  188. CE_UNUSED(err);
  189. #endif
  190. }
  191. /// Creates a directory. Returns true if success, false if not
  192. inline void create_directory(const char* path)
  193. {
  194. #if CROWN_PLATFORM_POSIX
  195. // rwxr-xr-x
  196. int err = ::mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  197. CE_ASSERT(err == 0, "mkdir: errno = %d", errno);
  198. CE_UNUSED(err);
  199. #elif CROWN_PLATFORM_WINDOWS
  200. BOOL err = CreateDirectory(path, NULL);
  201. CE_ASSERT(err != 0, "CreateDirectory: GetLastError = %d", GetLastError());
  202. CE_UNUSED(err);
  203. #endif
  204. }
  205. /// Deletes a directory. Returns true if success, false if not
  206. inline void delete_directory(const char* path)
  207. {
  208. #if CROWN_PLATFORM_POSIX
  209. int err = ::rmdir(path);
  210. CE_ASSERT(err == 0, "rmdir: errno = %d", errno);
  211. CE_UNUSED(err);
  212. #elif CROWN_PLATFORM_WINDOWS
  213. BOOL err = RemoveDirectory(path);
  214. CE_ASSERT(err != 0, "RemoveDirectory: GetLastError = %d", GetLastError());
  215. CE_UNUSED(err);
  216. #endif
  217. }
  218. /// Returns the list of @a files in the given @a dir directory. Optionally walks into
  219. /// subdirectories whether @a recursive is true.
  220. /// @note
  221. /// Does not follow symbolic links.
  222. inline void list_files(const char* path, Vector<DynamicString>& files)
  223. {
  224. #if CROWN_PLATFORM_POSIX
  225. DIR *dir;
  226. struct dirent *entry;
  227. if (!(dir = opendir(path)))
  228. {
  229. return;
  230. }
  231. while ((entry = readdir(dir)))
  232. {
  233. if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
  234. {
  235. continue;
  236. }
  237. DynamicString filename(default_allocator());
  238. filename = entry->d_name;
  239. vector::push_back(files, filename);
  240. }
  241. closedir(dir);
  242. #elif CROWN_PLATFORM_WINDOWS
  243. HANDLE file = INVALID_HANDLE_VALUE;
  244. WIN32_FIND_DATA ffd;
  245. char cur_path[MAX_PATH_LENGTH];
  246. string::strncpy(cur_path, path, string::strlen(path) + 1);
  247. string::strncat(cur_path, "\\*", 2);
  248. file = FindFirstFile(cur_path, &ffd);
  249. do
  250. {
  251. CE_ASSERT(file != INVALID_HANDLE_VALUE, "Unable to list files. errono %d", GetLastError());
  252. if ((string::strcmp(ffd.cFileName, ".") == 0) || (string::strcmp(ffd.cFileName, "..") == 0))
  253. {
  254. continue;
  255. }
  256. DynamicString filename(default_allocator());
  257. filename = ffd.cFileName;
  258. vector::push_back(files, filename);
  259. }
  260. while (FindNextFile(file, &ffd) != 0);
  261. FindClose(file);
  262. #endif
  263. }
  264. /// Returns os-dependent path from os-indipendent @a path
  265. inline const char* normalize_path(const char* path)
  266. {
  267. #if CROWN_PLATFORM_POSIX
  268. static char norm[MAX_PATH_LENGTH];
  269. char* cur = norm;
  270. while ((*path) != '\0')
  271. {
  272. if ((*path) == '\\')
  273. {
  274. (*cur) = PATH_SEPARATOR;
  275. }
  276. else
  277. {
  278. (*cur) = (*path);
  279. }
  280. path++;
  281. cur++;
  282. }
  283. return norm;
  284. #elif CROWN_PLATFORM_WINDOWS
  285. static char norm[MAX_PATH_LENGTH];
  286. for (uint32_t i = 0; i < string::strlen(path)+1; i++)
  287. {
  288. if (path[i] == '/')
  289. {
  290. norm[i] = '\\';
  291. }
  292. else
  293. {
  294. norm[i] = path[i];
  295. }
  296. }
  297. return norm;
  298. #endif
  299. }
  300. inline const char* getcwd(char* buf, size_t size)
  301. {
  302. #if CROWN_PLATFORM_POSIX
  303. return ::getcwd(buf, size);
  304. #elif CROWN_PLATFORM_WINDOWS
  305. GetCurrentDirectory(size, buf);
  306. return buf;
  307. #endif
  308. }
  309. inline const char* getenv(const char* name)
  310. {
  311. #if CROWN_PLATFORM_POSIX
  312. return ::getenv(name);
  313. #elif CROWN_PLATFORM_WINDOWS
  314. // GetEnvironmentVariable(name, buf, size);
  315. #endif
  316. }
  317. inline int64_t clocktime()
  318. {
  319. #if CROWN_PLATFORM_POSIX
  320. timespec ttime;
  321. clock_gettime(CLOCK_MONOTONIC, &ttime);
  322. return ttime.tv_sec * int64_t(1000000000) + ttime.tv_nsec;
  323. #elif CROWN_PLATFORM_WINDOWS
  324. LARGE_INTEGER ttime;
  325. QueryPerformanceCounter(&ttime);
  326. return (int64_t) ttime.QuadPart;
  327. #endif
  328. }
  329. inline int64_t clockfrequency()
  330. {
  331. #if CROWN_PLATFORM_POSIX
  332. return int32_t(1000000000);
  333. #elif CROWN_PLATFORM_WINDOWS
  334. LARGE_INTEGER freq;
  335. QueryPerformanceFrequency(&freq);
  336. return (int64_t) freq.QuadPart;
  337. #endif
  338. }
  339. inline void* open_library(const char* path)
  340. {
  341. #if CROWN_PLATFORM_POSIX
  342. return ::dlopen(path, RTLD_LAZY);
  343. #elif CROWN_PLATFORM_WINDOWS
  344. return (void*) LoadLibraryA(path);
  345. #endif
  346. }
  347. inline void close_library(void* library)
  348. {
  349. #if CROWN_PLATFORM_POSIX
  350. dlclose(library);
  351. #elif CROWN_PLATFORM_WINDOWS
  352. FreeLibrary((HMODULE) library);
  353. #endif
  354. }
  355. inline void* lookup_symbol(void* library, const char* name)
  356. {
  357. #if CROWN_PLATFORM_POSIX
  358. return ::dlsym(library, name);
  359. #elif CROWN_PLATFORM_WINDOWS
  360. return (void*) GetProcAddress((HMODULE) library, name);
  361. #endif
  362. }
  363. /// Executes a process.
  364. /// @a args is an array of arguments where:
  365. /// @a args[0] is the path to the program executable,
  366. /// @a args[1, 2, ..., n-1] is a list of arguments to pass to the executable,
  367. /// @a args[n] is NULL.
  368. inline void execute_process(const char* args[])
  369. {
  370. #if CROWN_PLATFORM_POSIX
  371. pid_t pid = fork();
  372. CE_ASSERT(pid != -1, "fork: errno = %d", errno);
  373. if (pid)
  374. {
  375. int32_t dummy;
  376. wait(&dummy);
  377. }
  378. else
  379. {
  380. int err = execv(args[0], (char* const*)args);
  381. CE_ASSERT(err != -1, "execv: errno = %d", errno);
  382. CE_UNUSED(err);
  383. exit(EXIT_SUCCESS);
  384. }
  385. #elif CROWN_PLATFORM_WINDOWS
  386. STARTUPINFO info;
  387. memset(&info, 0, sizeof(info));
  388. info.cb = sizeof(info);
  389. PROCESS_INFORMATION process;
  390. memset(&process, 0, sizeof(process));
  391. DynamicString cmds(default_allocator());
  392. for (uint32_t i = 0; args[i] != NULL; i++)
  393. {
  394. cmds += args[i];
  395. cmds += ' ';
  396. }
  397. // Necessary because CreateProcess second argument must be non-const
  398. char tmp[1024];
  399. string::strncpy(tmp, normalize_path(cmds.c_str()), string::strlen(cmds.c_str()));
  400. int err = CreateProcess(args[0], tmp, NULL, NULL, TRUE, 0, NULL, NULL, &info, &process);
  401. CE_ASSERT(err != 0, "CreateProcess: GetLastError = %d", GetLastError());
  402. CE_UNUSED(err);
  403. ::WaitForSingleObject(process.hProcess, INFINITE);
  404. CloseHandle(process.hProcess);
  405. CloseHandle(process.hThread);
  406. #endif
  407. }
  408. } // namespace os
  409. } // namespace crown