os_darwin.odin 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. package os
  2. foreign import dl "system:dl"
  3. foreign import libc "System.framework"
  4. foreign import pthread "System.framework"
  5. import "core:runtime"
  6. import "core:strings"
  7. import "core:c"
  8. Handle :: distinct i32
  9. File_Time :: distinct u64
  10. Errno :: distinct int
  11. INVALID_HANDLE :: ~Handle(0)
  12. ERROR_NONE: Errno : 0
  13. EPERM: Errno : 1 /* Operation not permitted */
  14. ENOENT: Errno : 2 /* No such file or directory */
  15. ESRCH: Errno : 3 /* No such process */
  16. EINTR: Errno : 4 /* Interrupted system call */
  17. EIO: Errno : 5 /* Input/output error */
  18. ENXIO: Errno : 6 /* Device not configured */
  19. E2BIG: Errno : 7 /* Argument list too long */
  20. ENOEXEC: Errno : 8 /* Exec format error */
  21. EBADF: Errno : 9 /* Bad file descriptor */
  22. ECHILD: Errno : 10 /* No child processes */
  23. EDEADLK: Errno : 11 /* Resource deadlock avoided */
  24. ENOMEM: Errno : 12 /* Cannot allocate memory */
  25. EACCES: Errno : 13 /* Permission denied */
  26. EFAULT: Errno : 14 /* Bad address */
  27. ENOTBLK: Errno : 15 /* Block device required */
  28. EBUSY: Errno : 16 /* Device / Resource busy */
  29. EEXIST: Errno : 17 /* File exists */
  30. EXDEV: Errno : 18 /* Cross-device link */
  31. ENODEV: Errno : 19 /* Operation not supported by device */
  32. ENOTDIR: Errno : 20 /* Not a directory */
  33. EISDIR: Errno : 21 /* Is a directory */
  34. EINVAL: Errno : 22 /* Invalid argument */
  35. ENFILE: Errno : 23 /* Too many open files in system */
  36. EMFILE: Errno : 24 /* Too many open files */
  37. ENOTTY: Errno : 25 /* Inappropriate ioctl for device */
  38. ETXTBSY: Errno : 26 /* Text file busy */
  39. EFBIG: Errno : 27 /* File too large */
  40. ENOSPC: Errno : 28 /* No space left on device */
  41. ESPIPE: Errno : 29 /* Illegal seek */
  42. EROFS: Errno : 30 /* Read-only file system */
  43. EMLINK: Errno : 31 /* Too many links */
  44. EPIPE: Errno : 32 /* Broken pipe */
  45. /* math software */
  46. EDOM: Errno : 33 /* Numerical argument out of domain */
  47. ERANGE: Errno : 34 /* Result too large */
  48. /* non-blocking and interrupt i/o */
  49. EAGAIN: Errno : 35 /* Resource temporarily unavailable */
  50. EWOULDBLOCK: Errno : EAGAIN /* Operation would block */
  51. EINPROGRESS: Errno : 36 /* Operation now in progress */
  52. EALREADY: Errno : 37 /* Operation already in progress */
  53. /* ipc/network software -- argument errors */
  54. ENOTSOCK: Errno : 38 /* Socket operation on non-socket */
  55. EDESTADDRREQ: Errno : 39 /* Destination address required */
  56. EMSGSIZE: Errno : 40 /* Message too long */
  57. EPROTOTYPE: Errno : 41 /* Protocol wrong type for socket */
  58. ENOPROTOOPT: Errno : 42 /* Protocol not available */
  59. EPROTONOSUPPORT: Errno : 43 /* Protocol not supported */
  60. ESOCKTNOSUPPORT: Errno : 44 /* Socket type not supported */
  61. ENOTSUP: Errno : 45 /* Operation not supported */
  62. EPFNOSUPPORT: Errno : 46 /* Protocol family not supported */
  63. EAFNOSUPPORT: Errno : 47 /* Address family not supported by protocol family */
  64. EADDRINUSE: Errno : 48 /* Address already in use */
  65. EADDRNOTAVAIL: Errno : 49 /* Can't assign requested address */
  66. /* ipc/network software -- operational errors */
  67. ENETDOWN: Errno : 50 /* Network is down */
  68. ENETUNREACH: Errno : 51 /* Network is unreachable */
  69. ENETRESET: Errno : 52 /* Network dropped connection on reset */
  70. ECONNABORTED: Errno : 53 /* Software caused connection abort */
  71. ECONNRESET: Errno : 54 /* Connection reset by peer */
  72. ENOBUFS: Errno : 55 /* No buffer space available */
  73. EISCONN: Errno : 56 /* Socket is already connected */
  74. ENOTCONN: Errno : 57 /* Socket is not connected */
  75. ESHUTDOWN: Errno : 58 /* Can't send after socket shutdown */
  76. ETOOMANYREFS: Errno : 59 /* Too many references: can't splice */
  77. ETIMEDOUT: Errno : 60 /* Operation timed out */
  78. ECONNREFUSED: Errno : 61 /* Connection refused */
  79. ELOOP: Errno : 62 /* Too many levels of symbolic links */
  80. ENAMETOOLONG: Errno : 63 /* File name too long */
  81. /* should be rearranged */
  82. EHOSTDOWN: Errno : 64 /* Host is down */
  83. EHOSTUNREACH: Errno : 65 /* No route to host */
  84. ENOTEMPTY: Errno : 66 /* Directory not empty */
  85. /* quotas & mush */
  86. EPROCLIM: Errno : 67 /* Too many processes */
  87. EUSERS: Errno : 68 /* Too many users */
  88. EDQUOT: Errno : 69 /* Disc quota exceeded */
  89. /* Network File System */
  90. ESTALE: Errno : 70 /* Stale NFS file handle */
  91. EREMOTE: Errno : 71 /* Too many levels of remote in path */
  92. EBADRPC: Errno : 72 /* RPC struct is bad */
  93. ERPCMISMATCH: Errno : 73 /* RPC version wrong */
  94. EPROGUNAVAIL: Errno : 74 /* RPC prog. not avail */
  95. EPROGMISMATCH: Errno : 75 /* Program version wrong */
  96. EPROCUNAVAIL: Errno : 76 /* Bad procedure for program */
  97. ENOLCK: Errno : 77 /* No locks available */
  98. ENOSYS: Errno : 78 /* Function not implemented */
  99. EFTYPE: Errno : 79 /* Inappropriate file type or format */
  100. EAUTH: Errno : 80 /* Authentication error */
  101. ENEEDAUTH: Errno : 81 /* Need authenticator */
  102. /* Intelligent device errors */
  103. EPWROFF: Errno : 82 /* Device power is off */
  104. EDEVERR: Errno : 83 /* Device error, e.g. paper out */
  105. EOVERFLOW: Errno : 84 /* Value too large to be stored in data type */
  106. /* Program loading errors */
  107. EBADEXEC: Errno : 85 /* Bad executable */
  108. EBADARCH: Errno : 86 /* Bad CPU type in executable */
  109. ESHLIBVERS: Errno : 87 /* Shared library version mismatch */
  110. EBADMACHO: Errno : 88 /* Malformed Macho file */
  111. ECANCELED: Errno : 89 /* Operation canceled */
  112. EIDRM: Errno : 90 /* Identifier removed */
  113. ENOMSG: Errno : 91 /* No message of desired type */
  114. EILSEQ: Errno : 92 /* Illegal byte sequence */
  115. ENOATTR: Errno : 93 /* Attribute not found */
  116. EBADMSG: Errno : 94 /* Bad message */
  117. EMULTIHOP: Errno : 95 /* Reserved */
  118. ENODATA: Errno : 96 /* No message available on STREAM */
  119. ENOLINK: Errno : 97 /* Reserved */
  120. ENOSR: Errno : 98 /* No STREAM resources */
  121. ENOSTR: Errno : 99 /* Not a STREAM */
  122. EPROTO: Errno : 100 /* Protocol error */
  123. ETIME: Errno : 101 /* STREAM ioctl timeout */
  124. ENOPOLICY: Errno : 103 /* No such policy registered */
  125. ENOTRECOVERABLE: Errno : 104 /* State not recoverable */
  126. EOWNERDEAD: Errno : 105 /* Previous owner died */
  127. EQFULL: Errno : 106 /* Interface output queue is full */
  128. ELAST: Errno : 106 /* Must be equal largest errno */
  129. O_RDONLY :: 0x0000
  130. O_WRONLY :: 0x0001
  131. O_RDWR :: 0x0002
  132. O_CREATE :: 0x0200
  133. O_EXCL :: 0x0800
  134. O_NOCTTY :: 0
  135. O_TRUNC :: 0x0400
  136. O_NONBLOCK :: 0x0004
  137. O_APPEND :: 0x0008
  138. O_SYNC :: 0x0080
  139. O_ASYNC :: 0x0040
  140. O_CLOEXEC :: 0x1000000
  141. SEEK_DATA :: 3
  142. SEEK_HOLE :: 4
  143. SEEK_MAX :: SEEK_HOLE
  144. // NOTE(zangent): These are OS specific!
  145. // Do not mix these up!
  146. RTLD_LAZY :: 0x1
  147. RTLD_NOW :: 0x2
  148. RTLD_LOCAL :: 0x4
  149. RTLD_GLOBAL :: 0x8
  150. RTLD_NODELETE :: 0x80
  151. RTLD_NOLOAD :: 0x10
  152. RTLD_FIRST :: 0x100
  153. // "Argv" arguments converted to Odin strings
  154. args := _alloc_command_line_arguments()
  155. Unix_File_Time :: struct {
  156. seconds: i64,
  157. nanoseconds: i64,
  158. }
  159. OS_Stat :: struct {
  160. device_id: i32, // ID of device containing file
  161. mode: u16, // Mode of the file
  162. nlink: u16, // Number of hard links
  163. serial: u64, // File serial number
  164. uid: u32, // User ID of the file's owner
  165. gid: u32, // Group ID of the file's group
  166. rdev: i32, // Device ID, if device
  167. last_access: Unix_File_Time, // Time of last access
  168. modified: Unix_File_Time, // Time of last modification
  169. status_change: Unix_File_Time, // Time of last status change
  170. created: Unix_File_Time, // Time of creation
  171. size: i64, // Size of the file, in bytes
  172. blocks: i64, // Number of blocks allocated for the file
  173. block_size: i32, // Optimal blocksize for I/O
  174. flags: u32, // User-defined flags for the file
  175. gen_num: u32, // File generation number ..?
  176. _spare: i32, // RESERVED
  177. _reserve1,
  178. _reserve2: i64, // RESERVED
  179. }
  180. DARWIN_MAXPATHLEN :: 1024
  181. Dirent :: struct {
  182. ino: u64,
  183. off: u64,
  184. reclen: u16,
  185. namlen: u16,
  186. type: u8,
  187. name: [DARWIN_MAXPATHLEN]byte,
  188. }
  189. Dir :: distinct rawptr // DIR*
  190. // File type
  191. S_IFMT :: 0o170000 // Type of file mask
  192. S_IFIFO :: 0o010000 // Named pipe (fifo)
  193. S_IFCHR :: 0o020000 // Character special
  194. S_IFDIR :: 0o040000 // Directory
  195. S_IFBLK :: 0o060000 // Block special
  196. S_IFREG :: 0o100000 // Regular
  197. S_IFLNK :: 0o120000 // Symbolic link
  198. S_IFSOCK :: 0o140000 // Socket
  199. // File mode
  200. // Read, write, execute/search by owner
  201. S_IRWXU :: 0o0700 // RWX mask for owner
  202. S_IRUSR :: 0o0400 // R for owner
  203. S_IWUSR :: 0o0200 // W for owner
  204. S_IXUSR :: 0o0100 // X for owner
  205. // Read, write, execute/search by group
  206. S_IRWXG :: 0o0070 // RWX mask for group
  207. S_IRGRP :: 0o0040 // R for group
  208. S_IWGRP :: 0o0020 // W for group
  209. S_IXGRP :: 0o0010 // X for group
  210. // Read, write, execute/search by others
  211. S_IRWXO :: 0o0007 // RWX mask for other
  212. S_IROTH :: 0o0004 // R for other
  213. S_IWOTH :: 0o0002 // W for other
  214. S_IXOTH :: 0o0001 // X for other
  215. S_ISUID :: 0o4000 // Set user id on execution
  216. S_ISGID :: 0o2000 // Set group id on execution
  217. S_ISVTX :: 0o1000 // Directory restrcted delete
  218. S_ISLNK :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFLNK }
  219. S_ISREG :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFREG }
  220. S_ISDIR :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFDIR }
  221. S_ISCHR :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFCHR }
  222. S_ISBLK :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFBLK }
  223. S_ISFIFO :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFIFO }
  224. S_ISSOCK :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFSOCK }
  225. R_OK :: 4 // Test for read permission
  226. W_OK :: 2 // Test for write permission
  227. X_OK :: 1 // Test for execute permission
  228. F_OK :: 0 // Test for file existance
  229. F_GETPATH :: 50 // return the full path of the fd
  230. foreign libc {
  231. @(link_name="__error") __error :: proc() -> ^int ---
  232. @(link_name="open") _unix_open :: proc(path: cstring, flags: i32, mode: u16) -> Handle ---
  233. @(link_name="close") _unix_close :: proc(handle: Handle) -> c.int ---
  234. @(link_name="read") _unix_read :: proc(handle: Handle, buffer: rawptr, count: int) -> int ---
  235. @(link_name="write") _unix_write :: proc(handle: Handle, buffer: rawptr, count: int) -> int ---
  236. @(link_name="lseek") _unix_lseek :: proc(fs: Handle, offset: int, whence: int) -> int ---
  237. @(link_name="gettid") _unix_gettid :: proc() -> u64 ---
  238. @(link_name="getpagesize") _unix_getpagesize :: proc() -> i32 ---
  239. @(link_name="stat64") _unix_stat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---
  240. @(link_name="lstat64") _unix_lstat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---
  241. @(link_name="fstat64") _unix_fstat :: proc(fd: Handle, stat: ^OS_Stat) -> c.int ---
  242. @(link_name="readlink") _unix_readlink :: proc(path: cstring, buf: ^byte, bufsiz: c.size_t) -> c.ssize_t ---
  243. @(link_name="access") _unix_access :: proc(path: cstring, mask: int) -> int ---
  244. @(link_name="fdopendir$INODE64") _unix_fdopendir_amd64 :: proc(fd: Handle) -> Dir ---
  245. @(link_name="readdir_r$INODE64") _unix_readdir_r_amd64 :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  246. @(link_name="fdopendir") _unix_fdopendir_arm64 :: proc(fd: Handle) -> Dir ---
  247. @(link_name="readdir_r") _unix_readdir_r_arm64 :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  248. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  249. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  250. @(link_name="__fcntl") _unix__fcntl :: proc(fd: Handle, cmd: c.int, buf: ^byte) -> c.int ---
  251. @(link_name="rename") _unix_rename :: proc(old: cstring, new: cstring) -> c.int ---
  252. @(link_name="remove") _unix_remove :: proc(path: cstring) -> c.int ---
  253. @(link_name="fchmod") _unix_fchmod :: proc(fd: Handle, mode: u16) -> c.int ---
  254. @(link_name="malloc") _unix_malloc :: proc(size: int) -> rawptr ---
  255. @(link_name="calloc") _unix_calloc :: proc(num, size: int) -> rawptr ---
  256. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  257. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: int) -> rawptr ---
  258. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  259. @(link_name="getcwd") _unix_getcwd :: proc(buf: cstring, len: c.size_t) -> cstring ---
  260. @(link_name="chdir") _unix_chdir :: proc(buf: cstring) -> c.int ---
  261. @(link_name="mkdir") _unix_mkdir :: proc(buf: cstring, mode: u16) -> c.int ---
  262. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: rawptr) -> rawptr ---
  263. @(link_name="strerror") _darwin_string_error :: proc(num : c.int) -> cstring ---
  264. @(link_name="sysctlbyname") _sysctlbyname :: proc(path: cstring, oldp: rawptr, oldlenp: rawptr, newp: rawptr, newlen: int) -> c.int ---
  265. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  266. }
  267. when ODIN_ARCH != .arm64 {
  268. _unix_fdopendir :: proc {_unix_fdopendir_amd64}
  269. _unix_readdir_r :: proc {_unix_readdir_r_amd64}
  270. } else {
  271. _unix_fdopendir :: proc {_unix_fdopendir_arm64}
  272. _unix_readdir_r :: proc {_unix_readdir_r_arm64}
  273. }
  274. foreign dl {
  275. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: int) -> rawptr ---
  276. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  277. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> int ---
  278. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  279. }
  280. get_last_error :: proc "contextless" () -> int {
  281. return __error()^
  282. }
  283. get_last_error_string :: proc() -> string {
  284. return cast(string)_darwin_string_error(cast(c.int)get_last_error())
  285. }
  286. open :: proc(path: string, flags: int = O_RDWR, mode: int = 0) -> (Handle, Errno) {
  287. isDir := is_dir_path(path)
  288. flags := flags
  289. if isDir {
  290. /*
  291. @INFO(Platin): To make it impossible to use the wrong flag for dir's
  292. as you can't write to a dir only read which makes it fail to open
  293. */
  294. flags = O_RDONLY
  295. }
  296. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  297. handle := _unix_open(cstr, i32(flags), u16(mode))
  298. if handle == -1 {
  299. return INVALID_HANDLE, cast(Errno)get_last_error()
  300. }
  301. /*
  302. @INFO(Platin): this is only done because O_CREATE for some reason fails to apply mode
  303. should not happen if the handle is a directory
  304. */
  305. if mode != 0 && !isDir {
  306. err := fchmod(handle, cast(u16)mode)
  307. if err != 0 {
  308. _unix_close(handle)
  309. return INVALID_HANDLE, cast(Errno)err
  310. }
  311. }
  312. return handle, 0
  313. }
  314. fchmod :: proc(fd: Handle, mode: u16) -> Errno {
  315. return cast(Errno)_unix_fchmod(fd, mode)
  316. }
  317. close :: proc(fd: Handle) -> bool {
  318. return _unix_close(fd) == 0
  319. }
  320. @(private)
  321. MAX_RW :: 0x7fffffff // The limit on Darwin is max(i32), trying to read/write more than that fails.
  322. write :: proc(fd: Handle, data: []u8) -> (int, Errno) {
  323. assert(fd != -1)
  324. bytes_total := len(data)
  325. bytes_written_total := 0
  326. for bytes_written_total < bytes_total {
  327. bytes_to_write := min(bytes_total - bytes_written_total, MAX_RW)
  328. slice := data[bytes_written_total:bytes_written_total + bytes_to_write]
  329. bytes_written := _unix_write(fd, raw_data(slice), bytes_to_write)
  330. if bytes_written == -1 {
  331. return bytes_written_total, 1
  332. }
  333. bytes_written_total += bytes_written
  334. }
  335. return bytes_written_total, 0
  336. }
  337. read :: proc(fd: Handle, data: []u8) -> (int, Errno) {
  338. assert(fd != -1)
  339. bytes_total := len(data)
  340. bytes_read_total := 0
  341. for bytes_read_total < bytes_total {
  342. bytes_to_read := min(bytes_total - bytes_read_total, MAX_RW)
  343. slice := data[bytes_read_total:bytes_read_total + bytes_to_read]
  344. bytes_read := _unix_read(fd, raw_data(slice), bytes_to_read)
  345. if bytes_read == -1 {
  346. return bytes_read_total, 1
  347. }
  348. if bytes_read == 0 {
  349. break
  350. }
  351. bytes_read_total += bytes_read
  352. }
  353. return bytes_read_total, 0
  354. }
  355. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  356. assert(fd != -1)
  357. final_offset := i64(_unix_lseek(fd, int(offset), whence))
  358. if final_offset == -1 {
  359. return 0, 1
  360. }
  361. return final_offset, 0
  362. }
  363. file_size :: proc(fd: Handle) -> (i64, Errno) {
  364. prev, _ := seek(fd, 0, SEEK_CUR)
  365. size, err := seek(fd, 0, SEEK_END)
  366. seek(fd, prev, SEEK_SET)
  367. return i64(size), err
  368. }
  369. // NOTE(bill): Uses startup to initialize it
  370. stdin: Handle = 0 // get_std_handle(win32.STD_INPUT_HANDLE);
  371. stdout: Handle = 1 // get_std_handle(win32.STD_OUTPUT_HANDLE);
  372. stderr: Handle = 2 // get_std_handle(win32.STD_ERROR_HANDLE);
  373. /* TODO(zangent): Implement these!
  374. last_write_time :: proc(fd: Handle) -> File_Time {}
  375. last_write_time_by_name :: proc(name: string) -> File_Time {}
  376. */
  377. is_path_separator :: proc(r: rune) -> bool {
  378. return r == '/'
  379. }
  380. is_file_handle :: proc(fd: Handle) -> bool {
  381. s, err := _fstat(fd)
  382. if err != ERROR_NONE {
  383. return false
  384. }
  385. return S_ISREG(s.mode)
  386. }
  387. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  388. s: OS_Stat
  389. err: Errno
  390. if follow_links {
  391. s, err = _stat(path)
  392. } else {
  393. s, err = _lstat(path)
  394. }
  395. if err != ERROR_NONE {
  396. return false
  397. }
  398. return S_ISREG(s.mode)
  399. }
  400. is_dir_handle :: proc(fd: Handle) -> bool {
  401. s, err := _fstat(fd)
  402. if err != ERROR_NONE {
  403. return false
  404. }
  405. return S_ISDIR(s.mode)
  406. }
  407. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  408. s: OS_Stat
  409. err: Errno
  410. if follow_links {
  411. s, err = _stat(path)
  412. } else {
  413. s, err = _lstat(path)
  414. }
  415. if err != ERROR_NONE {
  416. return false
  417. }
  418. return S_ISDIR(s.mode)
  419. }
  420. is_file :: proc {is_file_path, is_file_handle}
  421. is_dir :: proc {is_dir_path, is_dir_handle}
  422. exists :: proc(path: string) -> bool {
  423. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  424. res := _unix_access(cpath, O_RDONLY)
  425. return res == 0
  426. }
  427. rename :: proc(old: string, new: string) -> bool {
  428. old_cstr := strings.clone_to_cstring(old, context.temp_allocator)
  429. new_cstr := strings.clone_to_cstring(new, context.temp_allocator)
  430. return _unix_rename(old_cstr, new_cstr) != -1
  431. }
  432. remove :: proc(path: string) -> bool {
  433. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  434. return _unix_remove(path_cstr) != -1
  435. }
  436. @private
  437. _stat :: proc(path: string) -> (OS_Stat, Errno) {
  438. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  439. s: OS_Stat
  440. result := _unix_stat(cstr, &s)
  441. if result == -1 {
  442. return s, Errno(get_last_error())
  443. }
  444. return s, ERROR_NONE
  445. }
  446. @private
  447. _lstat :: proc(path: string) -> (OS_Stat, Errno) {
  448. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  449. s: OS_Stat
  450. result := _unix_lstat(cstr, &s)
  451. if result == -1 {
  452. return s, Errno(get_last_error())
  453. }
  454. return s, ERROR_NONE
  455. }
  456. @private
  457. _fstat :: proc(fd: Handle) -> (OS_Stat, Errno) {
  458. s: OS_Stat
  459. result := _unix_fstat(fd, &s)
  460. if result == -1 {
  461. return s, Errno(get_last_error())
  462. }
  463. return s, ERROR_NONE
  464. }
  465. @private
  466. _fdopendir :: proc(fd: Handle) -> (Dir, Errno) {
  467. dirp := _unix_fdopendir(fd)
  468. if dirp == cast(Dir)nil {
  469. return nil, Errno(get_last_error())
  470. }
  471. return dirp, ERROR_NONE
  472. }
  473. @private
  474. _closedir :: proc(dirp: Dir) -> Errno {
  475. rc := _unix_closedir(dirp)
  476. if rc != 0 {
  477. return Errno(get_last_error())
  478. }
  479. return ERROR_NONE
  480. }
  481. @private
  482. _rewinddir :: proc(dirp: Dir) {
  483. _unix_rewinddir(dirp)
  484. }
  485. @private
  486. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Errno, end_of_stream: bool) {
  487. result: ^Dirent
  488. rc := _unix_readdir_r(dirp, &entry, &result)
  489. if rc != 0 {
  490. err = Errno(get_last_error())
  491. return
  492. }
  493. err = ERROR_NONE
  494. if result == nil {
  495. end_of_stream = true
  496. return
  497. }
  498. end_of_stream = false
  499. return
  500. }
  501. @private
  502. _readlink :: proc(path: string) -> (string, Errno) {
  503. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  504. bufsz : uint = 256
  505. buf := make([]byte, bufsz)
  506. for {
  507. rc := _unix_readlink(path_cstr, &(buf[0]), bufsz)
  508. if rc == -1 {
  509. delete(buf)
  510. return "", Errno(get_last_error())
  511. } else if rc == int(bufsz) {
  512. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  513. bufsz *= 2
  514. delete(buf)
  515. buf = make([]byte, bufsz)
  516. } else {
  517. return strings.string_from_ptr(&buf[0], rc), ERROR_NONE
  518. }
  519. }
  520. }
  521. absolute_path_from_handle :: proc(fd: Handle) -> (string, Errno) {
  522. buf : [256]byte
  523. res := _unix__fcntl(fd, F_GETPATH, &buf[0])
  524. if res != 0 {
  525. return "", Errno(get_last_error())
  526. }
  527. path := strings.clone_from_cstring(cstring(&buf[0]))
  528. return path, ERROR_NONE
  529. }
  530. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Errno) {
  531. rel := rel
  532. if rel == "" {
  533. rel = "."
  534. }
  535. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  536. path_ptr := _unix_realpath(rel_cstr, nil)
  537. if path_ptr == nil {
  538. return "", Errno(get_last_error())
  539. }
  540. defer _unix_free(path_ptr)
  541. path_cstr := transmute(cstring)path_ptr
  542. path = strings.clone( string(path_cstr) )
  543. return path, ERROR_NONE
  544. }
  545. access :: proc(path: string, mask: int) -> bool {
  546. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  547. return _unix_access(cstr, mask) == 0
  548. }
  549. heap_alloc :: proc(size: int, zero_memory := true) -> rawptr {
  550. if size <= 0 {
  551. return nil
  552. }
  553. if zero_memory {
  554. return _unix_calloc(1, size)
  555. } else {
  556. return _unix_malloc(size)
  557. }
  558. }
  559. heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
  560. // NOTE: _unix_realloc doesn't guarantee new memory will be zeroed on
  561. // POSIX platforms. Ensure your caller takes this into account.
  562. return _unix_realloc(ptr, new_size)
  563. }
  564. heap_free :: proc(ptr: rawptr) {
  565. _unix_free(ptr)
  566. }
  567. lookup_env :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  568. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  569. cstr := _unix_getenv(path_str)
  570. if cstr == nil {
  571. return "", false
  572. }
  573. return strings.clone(string(cstr), allocator), true
  574. }
  575. get_env :: proc(key: string, allocator := context.allocator) -> (value: string) {
  576. value, _ = lookup_env(key, allocator)
  577. return
  578. }
  579. get_current_directory :: proc() -> string {
  580. page_size := get_page_size() // NOTE(tetra): See note in os_linux.odin/get_current_directory.
  581. buf := make([dynamic]u8, page_size)
  582. for {
  583. cwd := _unix_getcwd(cstring(raw_data(buf)), c.size_t(len(buf)))
  584. if cwd != nil {
  585. return string(cwd)
  586. }
  587. if Errno(get_last_error()) != ERANGE {
  588. return ""
  589. }
  590. resize(&buf, len(buf)+page_size)
  591. }
  592. unreachable()
  593. }
  594. set_current_directory :: proc(path: string) -> (err: Errno) {
  595. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  596. res := _unix_chdir(cstr)
  597. if res == -1 {
  598. return Errno(get_last_error())
  599. }
  600. return ERROR_NONE
  601. }
  602. make_directory :: proc(path: string, mode: u16 = 0o775) -> Errno {
  603. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  604. res := _unix_mkdir(path_cstr, mode)
  605. if res == -1 {
  606. return Errno(get_last_error())
  607. }
  608. return ERROR_NONE
  609. }
  610. exit :: proc "contextless" (code: int) -> ! {
  611. runtime._cleanup_runtime_contextless()
  612. _unix_exit(i32(code))
  613. }
  614. current_thread_id :: proc "contextless" () -> int {
  615. tid: u64
  616. // NOTE(Oskar): available from OSX 10.6 and iOS 3.2.
  617. // For older versions there is `syscall(SYS_thread_selfid)`, but not really
  618. // the same thing apparently.
  619. foreign pthread { pthread_threadid_np :: proc "c" (rawptr, ^u64) -> c.int --- }
  620. pthread_threadid_np(nil, &tid)
  621. return int(tid)
  622. }
  623. dlopen :: proc(filename: string, flags: int) -> rawptr {
  624. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  625. handle := _unix_dlopen(cstr, flags)
  626. return handle
  627. }
  628. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  629. assert(handle != nil)
  630. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  631. proc_handle := _unix_dlsym(handle, cstr)
  632. return proc_handle
  633. }
  634. dlclose :: proc(handle: rawptr) -> bool {
  635. assert(handle != nil)
  636. return _unix_dlclose(handle) == 0
  637. }
  638. dlerror :: proc() -> string {
  639. return string(_unix_dlerror())
  640. }
  641. get_page_size :: proc() -> int {
  642. // NOTE(tetra): The page size never changes, so why do anything complicated
  643. // if we don't have to.
  644. @static page_size := -1
  645. if page_size != -1 {
  646. return page_size
  647. }
  648. page_size = int(_unix_getpagesize())
  649. return page_size
  650. }
  651. @(private)
  652. _processor_core_count :: proc() -> int {
  653. count : int = 0
  654. count_size := size_of(count)
  655. if _sysctlbyname("hw.logicalcpu", &count, &count_size, nil, 0) == 0 {
  656. if count > 0 {
  657. return count
  658. }
  659. }
  660. return 1
  661. }
  662. _alloc_command_line_arguments :: proc() -> []string {
  663. res := make([]string, len(runtime.args__))
  664. for arg, i in runtime.args__ {
  665. res[i] = string(arg)
  666. }
  667. return res
  668. }