os_linux.odin 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. package os
  2. foreign import dl "system:dl"
  3. foreign import libc "system:c"
  4. import "core:runtime"
  5. import "core:strings"
  6. import "core:c"
  7. import "core:strconv"
  8. import "core:intrinsics"
  9. import "core:sys/unix"
  10. Handle :: distinct i32
  11. File_Time :: distinct u64
  12. Errno :: distinct i32
  13. INVALID_HANDLE :: ~Handle(0)
  14. ERROR_NONE: Errno : 0
  15. EPERM: Errno : 1
  16. ENOENT: Errno : 2
  17. ESRCH: Errno : 3
  18. EINTR: Errno : 4
  19. EIO: Errno : 5
  20. ENXIO: Errno : 6
  21. EBADF: Errno : 9
  22. EAGAIN: Errno : 11
  23. ENOMEM: Errno : 12
  24. EACCES: Errno : 13
  25. EFAULT: Errno : 14
  26. EEXIST: Errno : 17
  27. ENODEV: Errno : 19
  28. ENOTDIR: Errno : 20
  29. EISDIR: Errno : 21
  30. EINVAL: Errno : 22
  31. ENFILE: Errno : 23
  32. EMFILE: Errno : 24
  33. ETXTBSY: Errno : 26
  34. EFBIG: Errno : 27
  35. ENOSPC: Errno : 28
  36. ESPIPE: Errno : 29
  37. EROFS: Errno : 30
  38. EPIPE: Errno : 32
  39. ERANGE: Errno : 34 /* Result too large */
  40. EDEADLK: Errno : 35 /* Resource deadlock would occur */
  41. ENAMETOOLONG: Errno : 36 /* File name too long */
  42. ENOLCK: Errno : 37 /* No record locks available */
  43. ENOSYS: Errno : 38 /* Invalid system call number */
  44. ENOTEMPTY: Errno : 39 /* Directory not empty */
  45. ELOOP: Errno : 40 /* Too many symbolic links encountered */
  46. EWOULDBLOCK: Errno : EAGAIN /* Operation would block */
  47. ENOMSG: Errno : 42 /* No message of desired type */
  48. EIDRM: Errno : 43 /* Identifier removed */
  49. ECHRNG: Errno : 44 /* Channel number out of range */
  50. EL2NSYNC: Errno : 45 /* Level 2 not synchronized */
  51. EL3HLT: Errno : 46 /* Level 3 halted */
  52. EL3RST: Errno : 47 /* Level 3 reset */
  53. ELNRNG: Errno : 48 /* Link number out of range */
  54. EUNATCH: Errno : 49 /* Protocol driver not attached */
  55. ENOCSI: Errno : 50 /* No CSI structure available */
  56. EL2HLT: Errno : 51 /* Level 2 halted */
  57. EBADE: Errno : 52 /* Invalid exchange */
  58. EBADR: Errno : 53 /* Invalid request descriptor */
  59. EXFULL: Errno : 54 /* Exchange full */
  60. ENOANO: Errno : 55 /* No anode */
  61. EBADRQC: Errno : 56 /* Invalid request code */
  62. EBADSLT: Errno : 57 /* Invalid slot */
  63. EDEADLOCK: Errno : EDEADLK
  64. EBFONT: Errno : 59 /* Bad font file format */
  65. ENOSTR: Errno : 60 /* Device not a stream */
  66. ENODATA: Errno : 61 /* No data available */
  67. ETIME: Errno : 62 /* Timer expired */
  68. ENOSR: Errno : 63 /* Out of streams resources */
  69. ENONET: Errno : 64 /* Machine is not on the network */
  70. ENOPKG: Errno : 65 /* Package not installed */
  71. EREMOTE: Errno : 66 /* Object is remote */
  72. ENOLINK: Errno : 67 /* Link has been severed */
  73. EADV: Errno : 68 /* Advertise error */
  74. ESRMNT: Errno : 69 /* Srmount error */
  75. ECOMM: Errno : 70 /* Communication error on send */
  76. EPROTO: Errno : 71 /* Protocol error */
  77. EMULTIHOP: Errno : 72 /* Multihop attempted */
  78. EDOTDOT: Errno : 73 /* RFS specific error */
  79. EBADMSG: Errno : 74 /* Not a data message */
  80. EOVERFLOW: Errno : 75 /* Value too large for defined data type */
  81. ENOTUNIQ: Errno : 76 /* Name not unique on network */
  82. EBADFD: Errno : 77 /* File descriptor in bad state */
  83. EREMCHG: Errno : 78 /* Remote address changed */
  84. ELIBACC: Errno : 79 /* Can not access a needed shared library */
  85. ELIBBAD: Errno : 80 /* Accessing a corrupted shared library */
  86. ELIBSCN: Errno : 81 /* .lib section in a.out corrupted */
  87. ELIBMAX: Errno : 82 /* Attempting to link in too many shared libraries */
  88. ELIBEXEC: Errno : 83 /* Cannot exec a shared library directly */
  89. EILSEQ: Errno : 84 /* Illegal byte sequence */
  90. ERESTART: Errno : 85 /* Interrupted system call should be restarted */
  91. ESTRPIPE: Errno : 86 /* Streams pipe error */
  92. EUSERS: Errno : 87 /* Too many users */
  93. ENOTSOCK: Errno : 88 /* Socket operation on non-socket */
  94. EDESTADDRREQ: Errno : 89 /* Destination address required */
  95. EMSGSIZE: Errno : 90 /* Message too long */
  96. EPROTOTYPE: Errno : 91 /* Protocol wrong type for socket */
  97. ENOPROTOOPT: Errno : 92 /* Protocol not available */
  98. EPROTONOSUPPORT:Errno : 93 /* Protocol not supported */
  99. ESOCKTNOSUPPORT:Errno : 94 /* Socket type not supported */
  100. EOPNOTSUPP: Errno : 95 /* Operation not supported on transport endpoint */
  101. EPFNOSUPPORT: Errno : 96 /* Protocol family not supported */
  102. EAFNOSUPPORT: Errno : 97 /* Address family not supported by protocol */
  103. EADDRINUSE: Errno : 98 /* Address already in use */
  104. EADDRNOTAVAIL: Errno : 99 /* Cannot assign requested address */
  105. ENETDOWN: Errno : 100 /* Network is down */
  106. ENETUNREACH: Errno : 101 /* Network is unreachable */
  107. ENETRESET: Errno : 102 /* Network dropped connection because of reset */
  108. ECONNABORTED: Errno : 103 /* Software caused connection abort */
  109. ECONNRESET: Errno : 104 /* Connection reset by peer */
  110. ENOBUFS: Errno : 105 /* No buffer space available */
  111. EISCONN: Errno : 106 /* Transport endpoint is already connected */
  112. ENOTCONN: Errno : 107 /* Transport endpoint is not connected */
  113. ESHUTDOWN: Errno : 108 /* Cannot send after transport endpoint shutdown */
  114. ETOOMANYREFS: Errno : 109 /* Too many references: cannot splice */
  115. ETIMEDOUT: Errno : 110 /* Connection timed out */
  116. ECONNREFUSED: Errno : 111 /* Connection refused */
  117. EHOSTDOWN: Errno : 112 /* Host is down */
  118. EHOSTUNREACH: Errno : 113 /* No route to host */
  119. EALREADY: Errno : 114 /* Operation already in progress */
  120. EINPROGRESS: Errno : 115 /* Operation now in progress */
  121. ESTALE: Errno : 116 /* Stale file handle */
  122. EUCLEAN: Errno : 117 /* Structure needs cleaning */
  123. ENOTNAM: Errno : 118 /* Not a XENIX named type file */
  124. ENAVAIL: Errno : 119 /* No XENIX semaphores available */
  125. EISNAM: Errno : 120 /* Is a named type file */
  126. EREMOTEIO: Errno : 121 /* Remote I/O error */
  127. EDQUOT: Errno : 122 /* Quota exceeded */
  128. ENOMEDIUM: Errno : 123 /* No medium found */
  129. EMEDIUMTYPE: Errno : 124 /* Wrong medium type */
  130. ECANCELED: Errno : 125 /* Operation Canceled */
  131. ENOKEY: Errno : 126 /* Required key not available */
  132. EKEYEXPIRED: Errno : 127 /* Key has expired */
  133. EKEYREVOKED: Errno : 128 /* Key has been revoked */
  134. EKEYREJECTED: Errno : 129 /* Key was rejected by service */
  135. /* for robust mutexes */
  136. EOWNERDEAD: Errno : 130 /* Owner died */
  137. ENOTRECOVERABLE: Errno : 131 /* State not recoverable */
  138. ERFKILL: Errno : 132 /* Operation not possible due to RF-kill */
  139. EHWPOISON: Errno : 133 /* Memory page has hardware error */
  140. O_RDONLY :: 0x00000
  141. O_WRONLY :: 0x00001
  142. O_RDWR :: 0x00002
  143. O_CREATE :: 0x00040
  144. O_EXCL :: 0x00080
  145. O_NOCTTY :: 0x00100
  146. O_TRUNC :: 0x00200
  147. O_NONBLOCK :: 0x00800
  148. O_APPEND :: 0x00400
  149. O_SYNC :: 0x01000
  150. O_ASYNC :: 0x02000
  151. O_CLOEXEC :: 0x80000
  152. SEEK_SET :: 0
  153. SEEK_CUR :: 1
  154. SEEK_END :: 2
  155. SEEK_DATA :: 3
  156. SEEK_HOLE :: 4
  157. SEEK_MAX :: SEEK_HOLE
  158. // NOTE(zangent): These are OS specific!
  159. // Do not mix these up!
  160. RTLD_LAZY :: 0x001
  161. RTLD_NOW :: 0x002
  162. RTLD_BINDING_MASK :: 0x3
  163. RTLD_GLOBAL :: 0x100
  164. // "Argv" arguments converted to Odin strings
  165. args := _alloc_command_line_arguments()
  166. Unix_File_Time :: struct {
  167. seconds: i64,
  168. nanoseconds: i64,
  169. }
  170. OS_Stat :: struct {
  171. device_id: u64, // ID of device containing file
  172. serial: u64, // File serial number
  173. nlink: u64, // Number of hard links
  174. mode: u32, // Mode of the file
  175. uid: u32, // User ID of the file's owner
  176. gid: u32, // Group ID of the file's group
  177. _padding: i32, // 32 bits of padding
  178. rdev: u64, // Device ID, if device
  179. size: i64, // Size of the file, in bytes
  180. block_size: i64, // Optimal bllocksize for I/O
  181. blocks: i64, // Number of 512-byte blocks allocated
  182. last_access: Unix_File_Time, // Time of last access
  183. modified: Unix_File_Time, // Time of last modification
  184. status_change: Unix_File_Time, // Time of last status change
  185. _reserve1,
  186. _reserve2,
  187. _reserve3: i64,
  188. }
  189. // NOTE(laleksic, 2021-01-21): Comment and rename these to match OS_Stat above
  190. Dirent :: struct {
  191. ino: u64,
  192. off: u64,
  193. reclen: u16,
  194. type: u8,
  195. name: [256]byte,
  196. }
  197. Dir :: distinct rawptr // DIR*
  198. // File type
  199. S_IFMT :: 0o170000 // Type of file mask
  200. S_IFIFO :: 0o010000 // Named pipe (fifo)
  201. S_IFCHR :: 0o020000 // Character special
  202. S_IFDIR :: 0o040000 // Directory
  203. S_IFBLK :: 0o060000 // Block special
  204. S_IFREG :: 0o100000 // Regular
  205. S_IFLNK :: 0o120000 // Symbolic link
  206. S_IFSOCK :: 0o140000 // Socket
  207. // File mode
  208. // Read, write, execute/search by owner
  209. S_IRWXU :: 0o0700 // RWX mask for owner
  210. S_IRUSR :: 0o0400 // R for owner
  211. S_IWUSR :: 0o0200 // W for owner
  212. S_IXUSR :: 0o0100 // X for owner
  213. // Read, write, execute/search by group
  214. S_IRWXG :: 0o0070 // RWX mask for group
  215. S_IRGRP :: 0o0040 // R for group
  216. S_IWGRP :: 0o0020 // W for group
  217. S_IXGRP :: 0o0010 // X for group
  218. // Read, write, execute/search by others
  219. S_IRWXO :: 0o0007 // RWX mask for other
  220. S_IROTH :: 0o0004 // R for other
  221. S_IWOTH :: 0o0002 // W for other
  222. S_IXOTH :: 0o0001 // X for other
  223. S_ISUID :: 0o4000 // Set user id on execution
  224. S_ISGID :: 0o2000 // Set group id on execution
  225. S_ISVTX :: 0o1000 // Directory restrcted delete
  226. S_ISLNK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFLNK }
  227. S_ISREG :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFREG }
  228. S_ISDIR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFDIR }
  229. S_ISCHR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFCHR }
  230. S_ISBLK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFBLK }
  231. S_ISFIFO :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFIFO }
  232. S_ISSOCK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFSOCK }
  233. F_OK :: 0 // Test for file existance
  234. X_OK :: 1 // Test for execute permission
  235. W_OK :: 2 // Test for write permission
  236. R_OK :: 4 // Test for read permission
  237. AT_FDCWD :: -100
  238. AT_REMOVEDIR :: uintptr(0x200)
  239. AT_SYMLINK_NOFOLLOW :: uintptr(0x100)
  240. _unix_open :: proc(path: cstring, flags: int, mode: int = 0o000) -> Handle {
  241. when ODIN_ARCH != "arm64" {
  242. res := int(intrinsics.syscall(unix.SYS_open, uintptr(rawptr(path)), uintptr(flags), uintptr(mode)))
  243. } else { // NOTE: arm64 does not have open
  244. res := int(intrinsics.syscall(unix.SYS_openat, uintptr(AT_FDCWD), uintptr(rawptr(path), uintptr(flags), uintptr(mode))))
  245. }
  246. return -1 if res < 0 else Handle(res)
  247. }
  248. _unix_close :: proc(fd: Handle) -> int {
  249. return int(intrinsics.syscall(unix.SYS_close, uintptr(fd)))
  250. }
  251. _unix_read :: proc(fd: Handle, buf: rawptr, size: uint) -> int {
  252. return int(intrinsics.syscall(unix.SYS_read, uintptr(fd), uintptr(buf), uintptr(size)))
  253. }
  254. _unix_write :: proc(fd: Handle, buf: rawptr, size: uint) -> int {
  255. return int(intrinsics.syscall(unix.SYS_write, uintptr(fd), uintptr(buf), uintptr(size)))
  256. }
  257. _unix_seek :: proc(fd: Handle, offset: i64, whence: int) -> i64 {
  258. when ODIN_ARCH == "amd64" || ODIN_ARCH == "arm64" {
  259. return i64(intrinsics.syscall(unix.SYS_lseek, uintptr(fd), uintptr(offset), uintptr(whence)))
  260. } else {
  261. low := uintptr(offset & 0xFFFFFFFF)
  262. high := uintptr(offset >> 32)
  263. result: i64
  264. res := i64(intrinsics.syscall(unix.SYS__llseek, uintptr(fd), high, low, &result, uintptr(whence)))
  265. return -1 if res < 0 else result
  266. }
  267. }
  268. _unix_stat :: proc(path: cstring, stat: ^OS_Stat) -> int {
  269. when ODIN_ARCH == "amd64" {
  270. return int(intrinsics.syscall(unix.SYS_stat, uintptr(rawptr(path)), uintptr(stat)))
  271. } else when ODIN_ARCH != "arm64" {
  272. return int(intrinsics.syscall(unix.SYS_stat64, uintptr(rawptr(path)), uintptr(stat)))
  273. } else { // NOTE: arm64 does not have stat
  274. return int(intrinsics.syscall(unix.SYS_fstatat, uintptr(AT_FDCWD), uintptr(rawptr(path)), uintptr(stat), 0))
  275. }
  276. }
  277. _unix_fstat :: proc(fd: Handle, stat: ^OS_Stat) -> int {
  278. when ODIN_ARCH == "amd64" || ODIN_ARCH == "arm64" {
  279. return int(intrinsics.syscall(unix.SYS_fstat, uintptr(fd), uintptr(stat)))
  280. } else {
  281. return int(intrinsics.syscall(unix.SYS_fstat64, uintptr(fd), uintptr(stat)))
  282. }
  283. }
  284. _unix_lstat :: proc(path: cstring, stat: ^OS_Stat) -> int {
  285. when ODIN_ARCH == "amd64" {
  286. return int(intrinsics.syscall(unix.SYS_lstat, uintptr(rawptr(path)), uintptr(stat)))
  287. } else when ODIN_ARCH != "arm64" {
  288. return int(intrinsics.syscall(unix.SYS_lstat64, uintptr(rawptr(path)), uintptr(stat)))
  289. } else { // NOTE: arm64 does not have any lstat
  290. return int(intrinsics.syscall(unix.SYS_fstatat, uintptr(AT_FDCWD), uintptr(rawptr(path)), uintptr(stat), AT_SYMLINK_NOFOLLOW))
  291. }
  292. }
  293. _unix_readlink :: proc(path: cstring, buf: rawptr, bufsiz: uint) -> int {
  294. when ODIN_ARCH != "arm64" {
  295. return int(intrinsics.syscall(unix.SYS_readlink, uintptr(rawptr(path)), uintptr(buf), uintptr(bufsiz)))
  296. } else { // NOTE: arm64 does not have readlink
  297. return int(intrinsics.syscall(unix.SYS_readlinkat, uintptr(AT_FDCWD), uintptr(rawptr(path)), uintptr(buf), uintptr(bufsiz)))
  298. }
  299. }
  300. _unix_access :: proc(path: cstring, mask: int) -> int {
  301. when ODIN_ARCH != "arm64" {
  302. return int(intrinsics.syscall(unix.SYS_access, uintptr(rawptr(path)), uintptr(mask)))
  303. } else { // NOTE: arm64 does not have access
  304. return int(intrinsics.syscall(unix.SYS_faccessat, uintptr(AT_FDCWD), uintptr(rawptr(path)), uintptr(mask)))
  305. }
  306. }
  307. _unix_getcwd :: proc(buf: rawptr, size: uint) -> int {
  308. return int(intrinsics.syscall(unix.SYS_getcwd, uintptr(buf), uintptr(size)))
  309. }
  310. _unix_chdir :: proc(path: cstring) -> int {
  311. return int(intrinsics.syscall(unix.SYS_chdir, uintptr(rawptr(path))))
  312. }
  313. _unix_rename :: proc(old, new: cstring) -> int {
  314. when ODIN_ARCH != "arm64" {
  315. return int(intrinsics.syscall(unix.SYS_rename, uintptr(rawptr(old)), uintptr(rawptr(new))))
  316. } else { // NOTE: arm64 does not have rename
  317. return int(intrinsics.syscall(unix.SYS_renameat, uintptr(AT_FDCWD), uintptr(rawptr(old)), uintptr(rawptr(new))))
  318. }
  319. }
  320. _unix_unlink :: proc(path: cstring) -> int {
  321. when ODIN_ARCH != "arm64" {
  322. return int(intrinsics.syscall(unix.SYS_unlink, uintptr(rawptr(path))))
  323. } else { // NOTE: arm64 does not have unlink
  324. return int(intrinsics.syscall(unix.SYS_unlinkat, uintptr(AT_FDCWD), uintptr(rawptr(path), 0)))
  325. }
  326. }
  327. _unix_rmdir :: proc(path: cstring) -> int {
  328. when ODIN_ARCH != "arm64" {
  329. return int(intrinsics.syscall(unix.SYS_rmdir, uintptr(rawptr(path))))
  330. } else { // NOTE: arm64 does not have rmdir
  331. return int(intrinsics.syscall(unix.SYS_unlinkat, uintptr(AT_FDCWD), uintptr(rawptr(path)), AT_REMOVEDIR))
  332. }
  333. }
  334. _unix_mkdir :: proc(path: cstring, mode: u32) -> int {
  335. when ODIN_ARCH != "arm64" {
  336. return int(intrinsics.syscall(unix.SYS_mkdir, uintptr(rawptr(path)), uintptr(mode)))
  337. } else { // NOTE: arm64 does not have mkdir
  338. return int(intrinsics.syscall(unix.SYS_mkdirat, uintptr(AT_FDCWD), uintptr(rawptr(path)), uintptr(mode)))
  339. }
  340. }
  341. foreign libc {
  342. @(link_name="__errno_location") __errno_location :: proc() -> ^int ---
  343. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---
  344. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---
  345. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  346. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  347. @(link_name="readdir_r") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  348. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---
  349. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---
  350. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  351. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
  352. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  353. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: rawptr) -> rawptr ---
  354. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  355. }
  356. foreign dl {
  357. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  358. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  359. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  360. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  361. }
  362. is_path_separator :: proc(r: rune) -> bool {
  363. return r == '/'
  364. }
  365. // determine errno from syscall return value
  366. @private
  367. _get_errno :: proc(res: int) -> Errno {
  368. if res < 0 && res > -4096 {
  369. return Errno(-res)
  370. }
  371. return 0
  372. }
  373. // get errno from libc
  374. get_last_error :: proc() -> int {
  375. return __errno_location()^
  376. }
  377. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0) -> (Handle, Errno) {
  378. cstr := strings.clone_to_cstring(path)
  379. handle := _unix_open(cstr, flags, mode)
  380. defer delete(cstr)
  381. if handle < 0 {
  382. return INVALID_HANDLE, _get_errno(int(handle))
  383. }
  384. return handle, ERROR_NONE
  385. }
  386. close :: proc(fd: Handle) -> Errno {
  387. return _get_errno(_unix_close(fd))
  388. }
  389. read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  390. bytes_read := _unix_read(fd, &data[0], c.size_t(len(data)))
  391. if bytes_read < 0 {
  392. return -1, _get_errno(bytes_read)
  393. }
  394. return bytes_read, ERROR_NONE
  395. }
  396. write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  397. if len(data) == 0 {
  398. return 0, ERROR_NONE
  399. }
  400. bytes_written := _unix_write(fd, &data[0], uint(len(data)))
  401. if bytes_written < 0 {
  402. return -1, _get_errno(bytes_written)
  403. }
  404. return int(bytes_written), ERROR_NONE
  405. }
  406. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  407. res := _unix_seek(fd, offset, whence)
  408. if res < 0 {
  409. return -1, _get_errno(int(res))
  410. }
  411. return res, ERROR_NONE
  412. }
  413. file_size :: proc(fd: Handle) -> (i64, Errno) {
  414. s, err := _fstat(fd)
  415. if err != ERROR_NONE {
  416. return 0, err
  417. }
  418. return max(s.size, 0), ERROR_NONE
  419. }
  420. rename :: proc(old_path, new_path: string) -> Errno {
  421. old_path_cstr := strings.clone_to_cstring(old_path, context.temp_allocator)
  422. new_path_cstr := strings.clone_to_cstring(new_path, context.temp_allocator)
  423. return _get_errno(_unix_rename(old_path_cstr, new_path_cstr))
  424. }
  425. remove :: proc(path: string) -> Errno {
  426. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  427. return _get_errno(_unix_unlink(path_cstr))
  428. }
  429. make_directory :: proc(path: string, mode: u32 = 0o775) -> Errno {
  430. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  431. return _get_errno(_unix_mkdir(path_cstr, mode))
  432. }
  433. remove_directory :: proc(path: string) -> Errno {
  434. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  435. return _get_errno(_unix_rmdir(path_cstr))
  436. }
  437. is_file_handle :: proc(fd: Handle) -> bool {
  438. s, err := _fstat(fd)
  439. if err != ERROR_NONE {
  440. return false
  441. }
  442. return S_ISREG(s.mode)
  443. }
  444. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  445. s: OS_Stat
  446. err: Errno
  447. if follow_links {
  448. s, err = _stat(path)
  449. } else {
  450. s, err = _lstat(path)
  451. }
  452. if err != ERROR_NONE {
  453. return false
  454. }
  455. return S_ISREG(s.mode)
  456. }
  457. is_dir_handle :: proc(fd: Handle) -> bool {
  458. s, err := _fstat(fd)
  459. if err != ERROR_NONE {
  460. return false
  461. }
  462. return S_ISDIR(s.mode)
  463. }
  464. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  465. s: OS_Stat
  466. err: Errno
  467. if follow_links {
  468. s, err = _stat(path)
  469. } else {
  470. s, err = _lstat(path)
  471. }
  472. if err != ERROR_NONE {
  473. return false
  474. }
  475. return S_ISDIR(s.mode)
  476. }
  477. is_file :: proc {is_file_path, is_file_handle}
  478. is_dir :: proc {is_dir_path, is_dir_handle}
  479. // NOTE(bill): Uses startup to initialize it
  480. stdin: Handle = 0
  481. stdout: Handle = 1
  482. stderr: Handle = 2
  483. /* TODO(zangent): Implement these!
  484. last_write_time :: proc(fd: Handle) -> File_Time {}
  485. last_write_time_by_name :: proc(name: string) -> File_Time {}
  486. */
  487. last_write_time :: proc(fd: Handle) -> (File_Time, Errno) {
  488. s, err := _fstat(fd)
  489. if err != ERROR_NONE {
  490. return 0, err
  491. }
  492. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  493. return File_Time(modified), ERROR_NONE
  494. }
  495. last_write_time_by_name :: proc(name: string) -> (File_Time, Errno) {
  496. s, err := _stat(name)
  497. if err != ERROR_NONE {
  498. return 0, err
  499. }
  500. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  501. return File_Time(modified), ERROR_NONE
  502. }
  503. @private
  504. _stat :: proc(path: string) -> (OS_Stat, Errno) {
  505. cstr := strings.clone_to_cstring(path)
  506. defer delete(cstr)
  507. s: OS_Stat
  508. result := _unix_stat(cstr, &s)
  509. if result < 0 {
  510. return s, _get_errno(result)
  511. }
  512. return s, ERROR_NONE
  513. }
  514. @private
  515. _lstat :: proc(path: string) -> (OS_Stat, Errno) {
  516. cstr := strings.clone_to_cstring(path)
  517. defer delete(cstr)
  518. s: OS_Stat
  519. result := _unix_lstat(cstr, &s)
  520. if result < 0 {
  521. return s, _get_errno(result)
  522. }
  523. return s, ERROR_NONE
  524. }
  525. @private
  526. _fstat :: proc(fd: Handle) -> (OS_Stat, Errno) {
  527. s: OS_Stat
  528. result := _unix_fstat(fd, &s)
  529. if result < 0 {
  530. return s, _get_errno(result)
  531. }
  532. return s, ERROR_NONE
  533. }
  534. @private
  535. _fdopendir :: proc(fd: Handle) -> (Dir, Errno) {
  536. dirp := _unix_fdopendir(fd)
  537. if dirp == cast(Dir)nil {
  538. return nil, Errno(get_last_error())
  539. }
  540. return dirp, ERROR_NONE
  541. }
  542. @private
  543. _closedir :: proc(dirp: Dir) -> Errno {
  544. rc := _unix_closedir(dirp)
  545. if rc != 0 {
  546. return Errno(get_last_error())
  547. }
  548. return ERROR_NONE
  549. }
  550. @private
  551. _rewinddir :: proc(dirp: Dir) {
  552. _unix_rewinddir(dirp)
  553. }
  554. @private
  555. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Errno, end_of_stream: bool) {
  556. result: ^Dirent
  557. rc := _unix_readdir_r(dirp, &entry, &result)
  558. if rc != 0 {
  559. err = Errno(get_last_error())
  560. return
  561. }
  562. err = ERROR_NONE
  563. if result == nil {
  564. end_of_stream = true
  565. return
  566. }
  567. end_of_stream = false
  568. return
  569. }
  570. @private
  571. _readlink :: proc(path: string) -> (string, Errno) {
  572. path_cstr := strings.clone_to_cstring(path)
  573. defer delete(path_cstr)
  574. bufsz : uint = 256
  575. buf := make([]byte, bufsz)
  576. for {
  577. rc := _unix_readlink(path_cstr, &(buf[0]), bufsz)
  578. if rc < 0 {
  579. delete(buf)
  580. return "", _get_errno(rc)
  581. } else if rc == int(bufsz) {
  582. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  583. bufsz *= 2
  584. delete(buf)
  585. buf = make([]byte, bufsz)
  586. } else {
  587. return strings.string_from_ptr(&buf[0], rc), ERROR_NONE
  588. }
  589. }
  590. }
  591. absolute_path_from_handle :: proc(fd: Handle) -> (string, Errno) {
  592. buf : [256]byte
  593. fd_str := strconv.itoa( buf[:], cast(int)fd )
  594. procfs_path := strings.concatenate( []string{ "/proc/self/fd/", fd_str } )
  595. defer delete(procfs_path)
  596. return _readlink(procfs_path)
  597. }
  598. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Errno) {
  599. rel := rel
  600. if rel == "" {
  601. rel = "."
  602. }
  603. rel_cstr := strings.clone_to_cstring(rel)
  604. defer delete(rel_cstr)
  605. path_ptr := _unix_realpath(rel_cstr, nil)
  606. if path_ptr == nil {
  607. return "", Errno(get_last_error())
  608. }
  609. defer _unix_free(path_ptr)
  610. path_cstr := transmute(cstring)path_ptr
  611. path = strings.clone( string(path_cstr) )
  612. return path, ERROR_NONE
  613. }
  614. access :: proc(path: string, mask: int) -> (bool, Errno) {
  615. cstr := strings.clone_to_cstring(path)
  616. defer delete(cstr)
  617. result := _unix_access(cstr, mask)
  618. if result < 0 {
  619. return false, _get_errno(result)
  620. }
  621. return true, ERROR_NONE
  622. }
  623. heap_alloc :: proc(size: int) -> rawptr {
  624. assert(size >= 0)
  625. return _unix_calloc(1, c.size_t(size))
  626. }
  627. heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
  628. return _unix_realloc(ptr, c.size_t(new_size))
  629. }
  630. heap_free :: proc(ptr: rawptr) {
  631. _unix_free(ptr)
  632. }
  633. getenv :: proc(name: string) -> (string, bool) {
  634. path_str := strings.clone_to_cstring(name)
  635. defer delete(path_str)
  636. cstr := _unix_getenv(path_str)
  637. if cstr == nil {
  638. return "", false
  639. }
  640. return string(cstr), true
  641. }
  642. get_current_directory :: proc() -> string {
  643. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  644. // an authoritative value for it across all systems.
  645. // The largest value I could find was 4096, so might as well use the page size.
  646. page_size := get_page_size()
  647. buf := make([dynamic]u8, page_size)
  648. for {
  649. #no_bounds_check res := _unix_getcwd(&buf[0], uint(len(buf)))
  650. if res >= 0 {
  651. return strings.string_from_nul_terminated_ptr(&buf[0], len(buf))
  652. }
  653. if _get_errno(res) != ERANGE {
  654. return ""
  655. }
  656. resize(&buf, len(buf)+page_size)
  657. }
  658. unreachable()
  659. }
  660. set_current_directory :: proc(path: string) -> (err: Errno) {
  661. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  662. res := _unix_chdir(cstr)
  663. if res < 0 {
  664. return _get_errno(res)
  665. }
  666. return ERROR_NONE
  667. }
  668. exit :: proc "contextless" (code: int) -> ! {
  669. _unix_exit(c.int(code))
  670. }
  671. current_thread_id :: proc "contextless" () -> int {
  672. return unix.sys_gettid()
  673. }
  674. dlopen :: proc(filename: string, flags: int) -> rawptr {
  675. cstr := strings.clone_to_cstring(filename)
  676. defer delete(cstr)
  677. handle := _unix_dlopen(cstr, c.int(flags))
  678. return handle
  679. }
  680. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  681. assert(handle != nil)
  682. cstr := strings.clone_to_cstring(symbol)
  683. defer delete(cstr)
  684. proc_handle := _unix_dlsym(handle, cstr)
  685. return proc_handle
  686. }
  687. dlclose :: proc(handle: rawptr) -> bool {
  688. assert(handle != nil)
  689. return _unix_dlclose(handle) == 0
  690. }
  691. dlerror :: proc() -> string {
  692. return string(_unix_dlerror())
  693. }
  694. get_page_size :: proc() -> int {
  695. // NOTE(tetra): The page size never changes, so why do anything complicated
  696. // if we don't have to.
  697. @static page_size := -1
  698. if page_size != -1 {
  699. return page_size
  700. }
  701. page_size = int(_unix_getpagesize())
  702. return page_size
  703. }
  704. _alloc_command_line_arguments :: proc() -> []string {
  705. res := make([]string, len(runtime.args__))
  706. for arg, i in runtime.args__ {
  707. res[i] = string(arg)
  708. }
  709. return res
  710. }