os_netbsd.odin 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. package os
  2. foreign import dl "system:dl"
  3. foreign import libc "system:c"
  4. import "base:runtime"
  5. import "core:strings"
  6. import "core:sys/unix"
  7. import "core:c"
  8. Handle :: distinct i32
  9. File_Time :: distinct u64
  10. Errno :: distinct i32
  11. INVALID_HANDLE :: ~Handle(0)
  12. ERROR_NONE: Errno : 0 /* No error */
  13. EPERM: Errno : 1 /* Operation not permitted */
  14. ENOENT: Errno : 2 /* No such file or directory */
  15. EINTR: Errno : 4 /* Interrupted system call */
  16. ESRCH: Errno : 3 /* No such process */
  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. 11 was EAGAIN */
  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 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 or too small */
  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 option not available */
  59. EPROTONOSUPPORT: Errno : 43 /* Protocol not supported */
  60. ESOCKTNOSUPPORT: Errno : 44 /* Socket type not supported */
  61. EOPNOTSUPP: 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. /* SystemV IPC */
  103. EIDRM: Errno : 82 /* Identifier removed */
  104. ENOMSG: Errno : 83 /* No message of desired type */
  105. EOVERFLOW: Errno : 84 /* Value too large to be stored in data type */
  106. /* Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995 */
  107. EILSEQ: Errno : 85 /* Illegal byte sequence */
  108. /* From IEEE Std 1003.1-2001 */
  109. /* Base, Realtime, Threads or Thread Priority Scheduling option errors */
  110. ENOTSUP: Errno : 86 /* Not supported */
  111. /* Realtime option errors */
  112. ECANCELED: Errno : 87 /* Operation canceled */
  113. /* Realtime, XSI STREAMS option errors */
  114. EBADMSG: Errno : 88 /* Bad or Corrupt message */
  115. /* XSI STREAMS option errors */
  116. ENODATA: Errno : 89 /* No message available */
  117. ENOSR: Errno : 90 /* No STREAM resources */
  118. ENOSTR: Errno : 91 /* Not a STREAM */
  119. ETIME: Errno : 92 /* STREAM ioctl timeout */
  120. /* File system extended attribute errors */
  121. ENOATTR: Errno : 93 /* Attribute not found */
  122. /* Realtime, XSI STREAMS option errors */
  123. EMULTIHOP: Errno : 94 /* Multihop attempted */
  124. ENOLINK: Errno : 95 /* Link has been severed */
  125. EPROTO: Errno : 96 /* Protocol error */
  126. /* Robust mutexes */
  127. EOWNERDEAD: Errno : 97 /* Previous owner died */
  128. ENOTRECOVERABLE: Errno : 98 /* State not recoverable */
  129. ELAST: Errno : 98 /* Must equal largest errno */
  130. /* end of errno */
  131. O_RDONLY :: 0x000000000
  132. O_WRONLY :: 0x000000001
  133. O_RDWR :: 0x000000002
  134. O_CREATE :: 0x000000200
  135. O_EXCL :: 0x000000800
  136. O_NOCTTY :: 0x000008000
  137. O_TRUNC :: 0x000000400
  138. O_NONBLOCK :: 0x000000004
  139. O_APPEND :: 0x000000008
  140. O_SYNC :: 0x000000080
  141. O_ASYNC :: 0x000000040
  142. O_CLOEXEC :: 0x000400000
  143. RTLD_LAZY :: 0x001
  144. RTLD_NOW :: 0x002
  145. RTLD_GLOBAL :: 0x100
  146. RTLD_LOCAL :: 0x200
  147. RTLD_TRACE :: 0x200
  148. RTLD_NODELETE :: 0x01000
  149. RTLD_NOLOAD :: 0x02000
  150. F_GETPATH :: 15
  151. MAX_PATH :: 1024
  152. MAXNAMLEN :: 511
  153. args := _alloc_command_line_arguments()
  154. Unix_File_Time :: struct {
  155. seconds: time_t,
  156. nanoseconds: c.long,
  157. }
  158. dev_t :: u64
  159. ino_t :: u64
  160. nlink_t :: u32
  161. off_t :: i64
  162. mode_t :: u16
  163. pid_t :: u32
  164. uid_t :: u32
  165. gid_t :: u32
  166. blkcnt_t :: i64
  167. blksize_t :: i32
  168. fflags_t :: u32
  169. time_t :: i64
  170. OS_Stat :: struct {
  171. device_id: dev_t,
  172. mode: mode_t,
  173. _padding0: i16,
  174. ino: ino_t,
  175. nlink: nlink_t,
  176. uid: uid_t,
  177. gid: gid_t,
  178. _padding1: i32,
  179. rdev: dev_t,
  180. last_access: Unix_File_Time,
  181. modified: Unix_File_Time,
  182. status_change: Unix_File_Time,
  183. birthtime: Unix_File_Time,
  184. size: off_t,
  185. blocks: blkcnt_t,
  186. block_size: blksize_t,
  187. flags: fflags_t,
  188. gen: u32,
  189. lspare: [2]u32,
  190. }
  191. Dirent :: struct {
  192. ino: ino_t,
  193. reclen: u16,
  194. namlen: u16,
  195. type: u8,
  196. name: [MAXNAMLEN + 1]byte,
  197. }
  198. Dir :: distinct rawptr // DIR*
  199. // File type
  200. S_IFMT :: 0o170000 // Type of file mask
  201. S_IFIFO :: 0o010000 // Named pipe (fifo)
  202. S_IFCHR :: 0o020000 // Character special
  203. S_IFDIR :: 0o040000 // Directory
  204. S_IFBLK :: 0o060000 // Block special
  205. S_IFREG :: 0o100000 // Regular
  206. S_IFLNK :: 0o120000 // Symbolic link
  207. S_IFSOCK :: 0o140000 // Socket
  208. // File mode
  209. // Read, write, execute/search by owner
  210. S_IRWXU :: 0o0700 // RWX mask for owner
  211. S_IRUSR :: 0o0400 // R for owner
  212. S_IWUSR :: 0o0200 // W for owner
  213. S_IXUSR :: 0o0100 // X for owner
  214. // Read, write, execute/search by group
  215. S_IRWXG :: 0o0070 // RWX mask for group
  216. S_IRGRP :: 0o0040 // R for group
  217. S_IWGRP :: 0o0020 // W for group
  218. S_IXGRP :: 0o0010 // X for group
  219. // Read, write, execute/search by others
  220. S_IRWXO :: 0o0007 // RWX mask for other
  221. S_IROTH :: 0o0004 // R for other
  222. S_IWOTH :: 0o0002 // W for other
  223. S_IXOTH :: 0o0001 // X for other
  224. S_ISUID :: 0o4000 // Set user id on execution
  225. S_ISGID :: 0o2000 // Set group id on execution
  226. S_ISVTX :: 0o1000 // Directory restrcted delete
  227. S_ISLNK :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFLNK }
  228. S_ISREG :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFREG }
  229. S_ISDIR :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFDIR }
  230. S_ISCHR :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFCHR }
  231. S_ISBLK :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFBLK }
  232. S_ISFIFO :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFIFO }
  233. S_ISSOCK :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFSOCK }
  234. F_OK :: 0 // Test for file existance
  235. X_OK :: 1 // Test for execute permission
  236. W_OK :: 2 // Test for write permission
  237. R_OK :: 4 // Test for read permission
  238. foreign libc {
  239. @(link_name="__errno") __errno_location :: proc() -> ^c.int ---
  240. @(link_name="open") _unix_open :: proc(path: cstring, flags: c.int, mode: c.int) -> Handle ---
  241. @(link_name="close") _unix_close :: proc(fd: Handle) -> c.int ---
  242. @(link_name="read") _unix_read :: proc(fd: Handle, buf: rawptr, size: c.size_t) -> c.ssize_t ---
  243. @(link_name="write") _unix_write :: proc(fd: Handle, buf: rawptr, size: c.size_t) -> c.ssize_t ---
  244. @(link_name="lseek") _unix_seek :: proc(fd: Handle, offset: i64, whence: c.int) -> i64 ---
  245. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---
  246. @(link_name="stat") _unix_stat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---
  247. @(link_name="__lstat50") _unix_lstat :: proc(path: cstring, sb: ^OS_Stat) -> c.int ---
  248. @(link_name="__fstat50") _unix_fstat :: proc(fd: Handle, stat: ^OS_Stat) -> c.int ---
  249. @(link_name="readlink") _unix_readlink :: proc(path: cstring, buf: ^byte, bufsiz: c.size_t) -> c.ssize_t ---
  250. @(link_name="access") _unix_access :: proc(path: cstring, mask: c.int) -> c.int ---
  251. @(link_name="getcwd") _unix_getcwd :: proc(buf: cstring, len: c.size_t) -> cstring ---
  252. @(link_name="chdir") _unix_chdir :: proc(buf: cstring) -> c.int ---
  253. @(link_name="rename") _unix_rename :: proc(old, new: cstring) -> c.int ---
  254. @(link_name="unlink") _unix_unlink :: proc(path: cstring) -> c.int ---
  255. @(link_name="rmdir") _unix_rmdir :: proc(path: cstring) -> c.int ---
  256. @(link_name="mkdir") _unix_mkdir :: proc(path: cstring, mode: mode_t) -> c.int ---
  257. @(link_name="fcntl") _unix_fcntl :: proc(fd: Handle, cmd: c.int, arg: uintptr) -> c.int ---
  258. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---
  259. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  260. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  261. @(link_name="readdir_r") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  262. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---
  263. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---
  264. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  265. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
  266. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  267. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: rawptr) -> rawptr ---
  268. @(link_name="sysctlbyname") _sysctlbyname :: proc(path: cstring, oldp: rawptr, oldlenp: rawptr, newp: rawptr, newlen: int) -> c.int ---
  269. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  270. }
  271. foreign dl {
  272. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  273. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  274. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  275. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  276. }
  277. // NOTE(phix): Perhaps share the following functions with FreeBSD if they turn out to be the same in the end.
  278. is_path_separator :: proc(r: rune) -> bool {
  279. return r == '/'
  280. }
  281. get_last_error :: proc "contextless" () -> int {
  282. return int(__errno_location()^)
  283. }
  284. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0) -> (Handle, Errno) {
  285. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  286. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  287. handle := _unix_open(cstr, c.int(flags), c.int(mode))
  288. if handle == -1 {
  289. return INVALID_HANDLE, Errno(get_last_error())
  290. }
  291. return handle, ERROR_NONE
  292. }
  293. close :: proc(fd: Handle) -> Errno {
  294. result := _unix_close(fd)
  295. if result == -1 {
  296. return Errno(get_last_error())
  297. }
  298. return ERROR_NONE
  299. }
  300. // We set a max of 1GB to keep alignment and to be safe.
  301. @(private)
  302. MAX_RW :: 1 << 30
  303. read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  304. to_read := min(c.size_t(len(data)), MAX_RW)
  305. bytes_read := _unix_read(fd, &data[0], to_read)
  306. if bytes_read == -1 {
  307. return -1, Errno(get_last_error())
  308. }
  309. return int(bytes_read), ERROR_NONE
  310. }
  311. write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  312. if len(data) == 0 {
  313. return 0, ERROR_NONE
  314. }
  315. to_write := min(c.size_t(len(data)), MAX_RW)
  316. bytes_written := _unix_write(fd, &data[0], to_write)
  317. if bytes_written == -1 {
  318. return -1, Errno(get_last_error())
  319. }
  320. return int(bytes_written), ERROR_NONE
  321. }
  322. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  323. res := _unix_seek(fd, offset, c.int(whence))
  324. if res == -1 {
  325. return -1, Errno(get_last_error())
  326. }
  327. return res, ERROR_NONE
  328. }
  329. file_size :: proc(fd: Handle) -> (i64, Errno) {
  330. s, err := _fstat(fd)
  331. if err != ERROR_NONE {
  332. return -1, err
  333. }
  334. return s.size, ERROR_NONE
  335. }
  336. rename :: proc(old_path, new_path: string) -> Errno {
  337. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  338. old_path_cstr := strings.clone_to_cstring(old_path, context.temp_allocator)
  339. new_path_cstr := strings.clone_to_cstring(new_path, context.temp_allocator)
  340. res := _unix_rename(old_path_cstr, new_path_cstr)
  341. if res == -1 {
  342. return Errno(get_last_error())
  343. }
  344. return ERROR_NONE
  345. }
  346. remove :: proc(path: string) -> Errno {
  347. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  348. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  349. res := _unix_unlink(path_cstr)
  350. if res == -1 {
  351. return Errno(get_last_error())
  352. }
  353. return ERROR_NONE
  354. }
  355. make_directory :: proc(path: string, mode: mode_t = 0o775) -> Errno {
  356. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  357. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  358. res := _unix_mkdir(path_cstr, mode)
  359. if res == -1 {
  360. return Errno(get_last_error())
  361. }
  362. return ERROR_NONE
  363. }
  364. remove_directory :: proc(path: string) -> Errno {
  365. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  366. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  367. res := _unix_rmdir(path_cstr)
  368. if res == -1 {
  369. return Errno(get_last_error())
  370. }
  371. return ERROR_NONE
  372. }
  373. is_file_handle :: proc(fd: Handle) -> bool {
  374. s, err := _fstat(fd)
  375. if err != ERROR_NONE {
  376. return false
  377. }
  378. return S_ISREG(s.mode)
  379. }
  380. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  381. s: OS_Stat
  382. err: Errno
  383. if follow_links {
  384. s, err = _stat(path)
  385. } else {
  386. s, err = _lstat(path)
  387. }
  388. if err != ERROR_NONE {
  389. return false
  390. }
  391. return S_ISREG(s.mode)
  392. }
  393. is_dir_handle :: proc(fd: Handle) -> bool {
  394. s, err := _fstat(fd)
  395. if err != ERROR_NONE {
  396. return false
  397. }
  398. return S_ISDIR(s.mode)
  399. }
  400. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  401. s: OS_Stat
  402. err: Errno
  403. if follow_links {
  404. s, err = _stat(path)
  405. } else {
  406. s, err = _lstat(path)
  407. }
  408. if err != ERROR_NONE {
  409. return false
  410. }
  411. return S_ISDIR(s.mode)
  412. }
  413. is_file :: proc {is_file_path, is_file_handle}
  414. is_dir :: proc {is_dir_path, is_dir_handle}
  415. exists :: proc(path: string) -> bool {
  416. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  417. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  418. res := _unix_access(cpath, O_RDONLY)
  419. return res == 0
  420. }
  421. fcntl :: proc(fd: int, cmd: int, arg: int) -> (int, Errno) {
  422. result := _unix_fcntl(Handle(fd), c.int(cmd), uintptr(arg))
  423. if result < 0 {
  424. return 0, Errno(get_last_error())
  425. }
  426. return int(result), ERROR_NONE
  427. }
  428. // NOTE(bill): Uses startup to initialize it
  429. stdin: Handle = 0
  430. stdout: Handle = 1
  431. stderr: Handle = 2
  432. last_write_time :: proc(fd: Handle) -> (File_Time, Errno) {
  433. s, err := _fstat(fd)
  434. if err != ERROR_NONE {
  435. return 0, err
  436. }
  437. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  438. return File_Time(modified), ERROR_NONE
  439. }
  440. last_write_time_by_name :: proc(name: string) -> (File_Time, Errno) {
  441. s, err := _stat(name)
  442. if err != ERROR_NONE {
  443. return 0, err
  444. }
  445. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  446. return File_Time(modified), ERROR_NONE
  447. }
  448. @private
  449. _stat :: proc(path: string) -> (OS_Stat, Errno) {
  450. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  451. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  452. s: OS_Stat = ---
  453. result := _unix_lstat(cstr, &s)
  454. if result == -1 {
  455. return s, Errno(get_last_error())
  456. }
  457. return s, ERROR_NONE
  458. }
  459. @private
  460. _lstat :: proc(path: string) -> (OS_Stat, Errno) {
  461. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  462. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  463. // deliberately uninitialized
  464. s: OS_Stat = ---
  465. res := _unix_lstat(cstr, &s)
  466. if res == -1 {
  467. return s, Errno(get_last_error())
  468. }
  469. return s, ERROR_NONE
  470. }
  471. @private
  472. _fstat :: proc(fd: Handle) -> (OS_Stat, Errno) {
  473. s: OS_Stat = ---
  474. result := _unix_fstat(fd, &s)
  475. if result == -1 {
  476. return s, Errno(get_last_error())
  477. }
  478. return s, ERROR_NONE
  479. }
  480. @private
  481. _fdopendir :: proc(fd: Handle) -> (Dir, Errno) {
  482. dirp := _unix_fdopendir(fd)
  483. if dirp == cast(Dir)nil {
  484. return nil, Errno(get_last_error())
  485. }
  486. return dirp, ERROR_NONE
  487. }
  488. @private
  489. _closedir :: proc(dirp: Dir) -> Errno {
  490. rc := _unix_closedir(dirp)
  491. if rc != 0 {
  492. return Errno(get_last_error())
  493. }
  494. return ERROR_NONE
  495. }
  496. @private
  497. _rewinddir :: proc(dirp: Dir) {
  498. _unix_rewinddir(dirp)
  499. }
  500. @private
  501. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Errno, end_of_stream: bool) {
  502. result: ^Dirent
  503. rc := _unix_readdir_r(dirp, &entry, &result)
  504. if rc != 0 {
  505. err = Errno(get_last_error())
  506. return
  507. }
  508. err = ERROR_NONE
  509. if result == nil {
  510. end_of_stream = true
  511. return
  512. }
  513. return
  514. }
  515. @private
  516. _readlink :: proc(path: string) -> (string, Errno) {
  517. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  518. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  519. bufsz : uint = MAX_PATH
  520. buf := make([]byte, MAX_PATH)
  521. for {
  522. rc := _unix_readlink(path_cstr, &(buf[0]), bufsz)
  523. if rc == -1 {
  524. delete(buf)
  525. return "", Errno(get_last_error())
  526. } else if rc == int(bufsz) {
  527. bufsz += MAX_PATH
  528. delete(buf)
  529. buf = make([]byte, bufsz)
  530. } else {
  531. return strings.string_from_ptr(&buf[0], rc), ERROR_NONE
  532. }
  533. }
  534. return "", Errno{}
  535. }
  536. absolute_path_from_handle :: proc(fd: Handle) -> (string, Errno) {
  537. buf: [MAX_PATH]byte
  538. _, err := fcntl(int(fd), F_GETPATH, int(uintptr(&buf[0])))
  539. if err != ERROR_NONE {
  540. return "", err
  541. }
  542. path := strings.clone_from_cstring(cstring(&buf[0]))
  543. return path, err
  544. }
  545. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Errno) {
  546. rel := rel
  547. if rel == "" {
  548. rel = "."
  549. }
  550. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  551. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  552. path_ptr := _unix_realpath(rel_cstr, nil)
  553. if path_ptr == nil {
  554. return "", Errno(get_last_error())
  555. }
  556. defer _unix_free(path_ptr)
  557. path_cstr := transmute(cstring)path_ptr
  558. path = strings.clone( string(path_cstr) )
  559. return path, ERROR_NONE
  560. }
  561. access :: proc(path: string, mask: int) -> (bool, Errno) {
  562. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  563. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  564. result := _unix_access(cstr, c.int(mask))
  565. if result == -1 {
  566. return false, Errno(get_last_error())
  567. }
  568. return true, ERROR_NONE
  569. }
  570. lookup_env :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  571. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
  572. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  573. cstr := _unix_getenv(path_str)
  574. if cstr == nil {
  575. return "", false
  576. }
  577. return strings.clone(string(cstr), allocator), true
  578. }
  579. get_env :: proc(key: string, allocator := context.allocator) -> (value: string) {
  580. value, _ = lookup_env(key, allocator)
  581. return
  582. }
  583. get_current_directory :: proc() -> string {
  584. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  585. // an authoritative value for it across all systems.
  586. // The largest value I could find was 4096, so might as well use the page size.
  587. page_size := get_page_size()
  588. buf := make([dynamic]u8, page_size)
  589. #no_bounds_check for {
  590. cwd := _unix_getcwd(cstring(&buf[0]), c.size_t(len(buf)))
  591. if cwd != nil {
  592. return string(cwd)
  593. }
  594. if Errno(get_last_error()) != ERANGE {
  595. delete(buf)
  596. return ""
  597. }
  598. resize(&buf, len(buf)+page_size)
  599. }
  600. unreachable()
  601. }
  602. set_current_directory :: proc(path: string) -> (err: Errno) {
  603. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  604. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  605. res := _unix_chdir(cstr)
  606. if res == -1 do return Errno(get_last_error())
  607. return ERROR_NONE
  608. }
  609. exit :: proc "contextless" (code: int) -> ! {
  610. runtime._cleanup_runtime_contextless()
  611. _unix_exit(c.int(code))
  612. }
  613. current_thread_id :: proc "contextless" () -> int {
  614. return cast(int) unix.pthread_self()
  615. }
  616. dlopen :: proc(filename: string, flags: int) -> rawptr {
  617. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  618. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  619. handle := _unix_dlopen(cstr, c.int(flags))
  620. return handle
  621. }
  622. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  623. assert(handle != nil)
  624. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  625. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  626. proc_handle := _unix_dlsym(handle, cstr)
  627. return proc_handle
  628. }
  629. dlclose :: proc(handle: rawptr) -> bool {
  630. assert(handle != nil)
  631. return _unix_dlclose(handle) == 0
  632. }
  633. dlerror :: proc() -> string {
  634. return string(_unix_dlerror())
  635. }
  636. get_page_size :: proc() -> int {
  637. // NOTE(tetra): The page size never changes, so why do anything complicated
  638. // if we don't have to.
  639. @static page_size := -1
  640. if page_size != -1 do return page_size
  641. page_size = int(_unix_getpagesize())
  642. return page_size
  643. }
  644. @(private)
  645. _processor_core_count :: proc() -> int {
  646. count : int = 0
  647. count_size := size_of(count)
  648. if _sysctlbyname("hw.logicalcpu", &count, &count_size, nil, 0) == 0 {
  649. if count > 0 {
  650. return count
  651. }
  652. }
  653. return 1
  654. }
  655. _alloc_command_line_arguments :: proc() -> []string {
  656. res := make([]string, len(runtime.args__))
  657. for arg, i in runtime.args__ {
  658. res[i] = string(arg)
  659. }
  660. return res
  661. }