os_linux.odin 27 KB

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