os.h 12 KB

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