os_netbsd.odin 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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:c"
  7. Handle :: distinct i32
  8. File_Time :: distinct u64
  9. INVALID_HANDLE :: ~Handle(0)
  10. _Platform_Error :: enum i32 {
  11. NONE = 0,
  12. EPERM = 1, /* Operation not permitted */
  13. ENOENT = 2, /* No such file or directory */
  14. EINTR = 4, /* Interrupted system call */
  15. ESRCH = 3, /* No such process */
  16. EIO = 5, /* Input/output error */
  17. ENXIO = 6, /* Device not configured */
  18. E2BIG = 7, /* Argument list too long */
  19. ENOEXEC = 8, /* Exec format error */
  20. EBADF = 9, /* Bad file descriptor */
  21. ECHILD = 10, /* No child processes */
  22. EDEADLK = 11, /* Resource deadlock avoided. 11 was EAGAIN */
  23. ENOMEM = 12, /* Cannot allocate memory */
  24. EACCES = 13, /* Permission denied */
  25. EFAULT = 14, /* Bad address */
  26. ENOTBLK = 15, /* Block device required */
  27. EBUSY = 16, /* Device busy */
  28. EEXIST = 17, /* File exists */
  29. EXDEV = 18, /* Cross-device link */
  30. ENODEV = 19, /* Operation not supported by device */
  31. ENOTDIR = 20, /* Not a directory */
  32. EISDIR = 21, /* Is a directory */
  33. EINVAL = 22, /* Invalid argument */
  34. ENFILE = 23, /* Too many open files in system */
  35. EMFILE = 24, /* Too many open files */
  36. ENOTTY = 25, /* Inappropriate ioctl for device */
  37. ETXTBSY = 26, /* Text file busy */
  38. EFBIG = 27, /* File too large */
  39. ENOSPC = 28, /* No space left on device */
  40. ESPIPE = 29, /* Illegal seek */
  41. EROFS = 30, /* Read-only file system */
  42. EMLINK = 31, /* Too many links */
  43. EPIPE = 32, /* Broken pipe */
  44. /* math software */
  45. EDOM = 33, /* Numerical argument out of domain */
  46. ERANGE = 34, /* Result too large or too small */
  47. /* non-blocking and interrupt i/o */
  48. EAGAIN = 35, /* Resource temporarily unavailable */
  49. EWOULDBLOCK = EAGAIN, /* Operation would block */
  50. EINPROGRESS = 36, /* Operation now in progress */
  51. EALREADY = 37, /* Operation already in progress */
  52. /* ipc/network software -- argument errors */
  53. ENOTSOCK = 38, /* Socket operation on non-socket */
  54. EDESTADDRREQ = 39, /* Destination address required */
  55. EMSGSIZE = 40, /* Message too long */
  56. EPROTOTYPE = 41, /* Protocol wrong type for socket */
  57. ENOPROTOOPT = 42, /* Protocol option not available */
  58. EPROTONOSUPPORT = 43, /* Protocol not supported */
  59. ESOCKTNOSUPPORT = 44, /* Socket type not supported */
  60. EOPNOTSUPP = 45, /* Operation not supported */
  61. EPFNOSUPPORT = 46, /* Protocol family not supported */
  62. EAFNOSUPPORT = 47, /* Address family not supported by protocol family */
  63. EADDRINUSE = 48, /* Address already in use */
  64. EADDRNOTAVAIL = 49, /* Can't assign requested address */
  65. /* ipc/network software -- operational errors */
  66. ENETDOWN = 50, /* Network is down */
  67. ENETUNREACH = 51, /* Network is unreachable */
  68. ENETRESET = 52, /* Network dropped connection on reset */
  69. ECONNABORTED = 53, /* Software caused connection abort */
  70. ECONNRESET = 54, /* Connection reset by peer */
  71. ENOBUFS = 55, /* No buffer space available */
  72. EISCONN = 56, /* Socket is already connected */
  73. ENOTCONN = 57, /* Socket is not connected */
  74. ESHUTDOWN = 58, /* Can't send after socket shutdown */
  75. ETOOMANYREFS = 59, /* Too many references: can't splice */
  76. ETIMEDOUT = 60, /* Operation timed out */
  77. ECONNREFUSED = 61, /* Connection refused */
  78. ELOOP = 62, /* Too many levels of symbolic links */
  79. ENAMETOOLONG = 63, /* File name too long */
  80. /* should be rearranged */
  81. EHOSTDOWN = 64, /* Host is down */
  82. EHOSTUNREACH = 65, /* No route to host */
  83. ENOTEMPTY = 66, /* Directory not empty */
  84. /* quotas & mush */
  85. EPROCLIM = 67, /* Too many processes */
  86. EUSERS = 68, /* Too many users */
  87. EDQUOT = 69, /* Disc quota exceeded */
  88. /* Network File System */
  89. ESTALE = 70, /* Stale NFS file handle */
  90. EREMOTE = 71, /* Too many levels of remote in path */
  91. EBADRPC = 72, /* RPC struct is bad */
  92. ERPCMISMATCH = 73, /* RPC version wrong */
  93. EPROGUNAVAIL = 74, /* RPC prog. not avail */
  94. EPROGMISMATCH = 75, /* Program version wrong */
  95. EPROCUNAVAIL = 76, /* Bad procedure for program */
  96. ENOLCK = 77, /* No locks available */
  97. ENOSYS = 78, /* Function not implemented */
  98. EFTYPE = 79, /* Inappropriate file type or format */
  99. EAUTH = 80, /* Authentication error */
  100. ENEEDAUTH = 81, /* Need authenticator */
  101. /* SystemV IPC */
  102. EIDRM = 82, /* Identifier removed */
  103. ENOMSG = 83, /* No message of desired type */
  104. EOVERFLOW = 84, /* Value too large to be stored in data type */
  105. /* Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995 */
  106. EILSEQ = 85, /* Illegal byte sequence */
  107. /* From IEEE Std 1003.1-2001 */
  108. /* Base, Realtime, Threads or Thread Priority Scheduling option errors */
  109. ENOTSUP = 86, /* Not supported */
  110. /* Realtime option errors */
  111. ECANCELED = 87, /* Operation canceled */
  112. /* Realtime, XSI STREAMS option errors */
  113. EBADMSG = 88, /* Bad or Corrupt message */
  114. /* XSI STREAMS option errors */
  115. ENODATA = 89, /* No message available */
  116. ENOSR = 90, /* No STREAM resources */
  117. ENOSTR = 91, /* Not a STREAM */
  118. ETIME = 92, /* STREAM ioctl timeout */
  119. /* File system extended attribute errors */
  120. ENOATTR = 93, /* Attribute not found */
  121. /* Realtime, XSI STREAMS option errors */
  122. EMULTIHOP = 94, /* Multihop attempted */
  123. ENOLINK = 95, /* Link has been severed */
  124. EPROTO = 96, /* Protocol error */
  125. /* Robust mutexes */
  126. EOWNERDEAD = 97, /* Previous owner died */
  127. ENOTRECOVERABLE = 98, /* State not recoverable */
  128. ELAST = 98, /* Must equal largest Error */
  129. }
  130. EPERM :: Platform_Error.EPERM /* Operation not permitted */
  131. ENOENT :: Platform_Error.ENOENT /* No such file or directory */
  132. EINTR :: Platform_Error.EINTR /* Interrupted system call */
  133. ESRCH :: Platform_Error.ESRCH /* No such process */
  134. EIO :: Platform_Error.EIO /* Input/output error */
  135. ENXIO :: Platform_Error.ENXIO /* Device not configured */
  136. E2BIG :: Platform_Error.E2BIG /* Argument list too long */
  137. ENOEXEC :: Platform_Error.ENOEXEC /* Exec format error */
  138. EBADF :: Platform_Error.EBADF /* Bad file descriptor */
  139. ECHILD :: Platform_Error.ECHILD /* No child processes */
  140. EDEADLK :: Platform_Error.EDEADLK /* Resource deadlock avoided. 11 was EAGAIN */
  141. ENOMEM :: Platform_Error.ENOMEM /* Cannot allocate memory */
  142. EACCES :: Platform_Error.EACCES /* Permission denied */
  143. EFAULT :: Platform_Error.EFAULT /* Bad address */
  144. ENOTBLK :: Platform_Error.ENOTBLK /* Block device required */
  145. EBUSY :: Platform_Error.EBUSY /* Device busy */
  146. EEXIST :: Platform_Error.EEXIST /* File exists */
  147. EXDEV :: Platform_Error.EXDEV /* Cross-device link */
  148. ENODEV :: Platform_Error.ENODEV /* Operation not supported by device */
  149. ENOTDIR :: Platform_Error.ENOTDIR /* Not a directory */
  150. EISDIR :: Platform_Error.EISDIR /* Is a directory */
  151. EINVAL :: Platform_Error.EINVAL /* Invalid argument */
  152. ENFILE :: Platform_Error.ENFILE /* Too many open files in system */
  153. EMFILE :: Platform_Error.EMFILE /* Too many open files */
  154. ENOTTY :: Platform_Error.ENOTTY /* Inappropriate ioctl for device */
  155. ETXTBSY :: Platform_Error.ETXTBSY /* Text file busy */
  156. EFBIG :: Platform_Error.EFBIG /* File too large */
  157. ENOSPC :: Platform_Error.ENOSPC /* No space left on device */
  158. ESPIPE :: Platform_Error.ESPIPE /* Illegal seek */
  159. EROFS :: Platform_Error.EROFS /* Read-only file system */
  160. EMLINK :: Platform_Error.EMLINK /* Too many links */
  161. EPIPE :: Platform_Error.EPIPE /* Broken pipe */
  162. /* math software */
  163. EDOM :: Platform_Error.EDOM /* Numerical argument out of domain */
  164. ERANGE :: Platform_Error.ERANGE /* Result too large or too small */
  165. /* non-blocking and interrupt i/o */
  166. EAGAIN :: Platform_Error.EAGAIN /* Resource temporarily unavailable */
  167. EWOULDBLOCK :: EAGAIN /* Operation would block */
  168. EINPROGRESS :: Platform_Error.EINPROGRESS /* Operation now in progress */
  169. EALREADY :: Platform_Error.EALREADY /* Operation already in progress */
  170. /* ipc/network software -- argument errors */
  171. ENOTSOCK :: Platform_Error.ENOTSOCK /* Socket operation on non-socket */
  172. EDESTADDRREQ :: Platform_Error.EDESTADDRREQ /* Destination address required */
  173. EMSGSIZE :: Platform_Error.EMSGSIZE /* Message too long */
  174. EPROTOTYPE :: Platform_Error.EPROTOTYPE /* Protocol wrong type for socket */
  175. ENOPROTOOPT :: Platform_Error.ENOPROTOOPT /* Protocol option not available */
  176. EPROTONOSUPPORT :: Platform_Error.EPROTONOSUPPORT /* Protocol not supported */
  177. ESOCKTNOSUPPORT :: Platform_Error.ESOCKTNOSUPPORT /* Socket type not supported */
  178. EOPNOTSUPP :: Platform_Error.EOPNOTSUPP /* Operation not supported */
  179. EPFNOSUPPORT :: Platform_Error.EPFNOSUPPORT /* Protocol family not supported */
  180. EAFNOSUPPORT :: Platform_Error.EAFNOSUPPORT /* Address family not supported by protocol family */
  181. EADDRINUSE :: Platform_Error.EADDRINUSE /* Address already in use */
  182. EADDRNOTAVAIL :: Platform_Error.EADDRNOTAVAIL /* Can't assign requested address */
  183. /* ipc/network software -- operational errors */
  184. ENETDOWN :: Platform_Error.ENETDOWN /* Network is down */
  185. ENETUNREACH :: Platform_Error.ENETUNREACH /* Network is unreachable */
  186. ENETRESET :: Platform_Error.ENETRESET /* Network dropped connection on reset */
  187. ECONNABORTED :: Platform_Error.ECONNABORTED /* Software caused connection abort */
  188. ECONNRESET :: Platform_Error.ECONNRESET /* Connection reset by peer */
  189. ENOBUFS :: Platform_Error.ENOBUFS /* No buffer space available */
  190. EISCONN :: Platform_Error.EISCONN /* Socket is already connected */
  191. ENOTCONN :: Platform_Error.ENOTCONN /* Socket is not connected */
  192. ESHUTDOWN :: Platform_Error.ESHUTDOWN /* Can't send after socket shutdown */
  193. ETOOMANYREFS :: Platform_Error.ETOOMANYREFS /* Too many references: can't splice */
  194. ETIMEDOUT :: Platform_Error.ETIMEDOUT /* Operation timed out */
  195. ECONNREFUSED :: Platform_Error.ECONNREFUSED /* Connection refused */
  196. ELOOP :: Platform_Error.ELOOP /* Too many levels of symbolic links */
  197. ENAMETOOLONG :: Platform_Error.ENAMETOOLONG /* File name too long */
  198. /* should be rearranged */
  199. EHOSTDOWN :: Platform_Error.EHOSTDOWN /* Host is down */
  200. EHOSTUNREACH :: Platform_Error.EHOSTUNREACH /* No route to host */
  201. ENOTEMPTY :: Platform_Error.ENOTEMPTY /* Directory not empty */
  202. /* quotas & mush */
  203. EPROCLIM :: Platform_Error.EPROCLIM /* Too many processes */
  204. EUSERS :: Platform_Error.EUSERS /* Too many users */
  205. EDQUOT :: Platform_Error.EDQUOT /* Disc quota exceeded */
  206. /* Network File System */
  207. ESTALE :: Platform_Error.ESTALE /* Stale NFS file handle */
  208. EREMOTE :: Platform_Error.EREMOTE /* Too many levels of remote in path */
  209. EBADRPC :: Platform_Error.EBADRPC /* RPC struct is bad */
  210. ERPCMISMATCH :: Platform_Error.ERPCMISMATCH /* RPC version wrong */
  211. EPROGUNAVAIL :: Platform_Error.EPROGUNAVAIL /* RPC prog. not avail */
  212. EPROGMISMATCH :: Platform_Error.EPROGMISMATCH /* Program version wrong */
  213. EPROCUNAVAIL :: Platform_Error.EPROCUNAVAIL /* Bad procedure for program */
  214. ENOLCK :: Platform_Error.ENOLCK /* No locks available */
  215. ENOSYS :: Platform_Error.ENOSYS /* Function not implemented */
  216. EFTYPE :: Platform_Error.EFTYPE /* Inappropriate file type or format */
  217. EAUTH :: Platform_Error.EAUTH /* Authentication error */
  218. ENEEDAUTH :: Platform_Error.ENEEDAUTH /* Need authenticator */
  219. /* SystemV IPC */
  220. EIDRM :: Platform_Error.EIDRM /* Identifier removed */
  221. ENOMSG :: Platform_Error.ENOMSG /* No message of desired type */
  222. EOVERFLOW :: Platform_Error.EOVERFLOW /* Value too large to be stored in data type */
  223. /* Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995 */
  224. EILSEQ :: Platform_Error.EILSEQ /* Illegal byte sequence */
  225. /* From IEEE Std 1003.1-2001 */
  226. /* Base, Realtime, Threads or Thread Priority Scheduling option errors */
  227. ENOTSUP :: Platform_Error.ENOTSUP /* Not supported */
  228. /* Realtime option errors */
  229. ECANCELED :: Platform_Error.ECANCELED /* Operation canceled */
  230. /* Realtime, XSI STREAMS option errors */
  231. EBADMSG :: Platform_Error.EBADMSG /* Bad or Corrupt message */
  232. /* XSI STREAMS option errors */
  233. ENODATA :: Platform_Error.ENODATA /* No message available */
  234. ENOSR :: Platform_Error.ENOSR /* No STREAM resources */
  235. ENOSTR :: Platform_Error.ENOSTR /* Not a STREAM */
  236. ETIME :: Platform_Error.ETIME /* STREAM ioctl timeout */
  237. /* File system extended attribute errors */
  238. ENOATTR :: Platform_Error.ENOATTR /* Attribute not found */
  239. /* Realtime, XSI STREAMS option errors */
  240. EMULTIHOP :: Platform_Error.EMULTIHOP /* Multihop attempted */
  241. ENOLINK :: Platform_Error.ENOLINK /* Link has been severed */
  242. EPROTO :: Platform_Error.EPROTO /* Protocol error */
  243. /* Robust mutexes */
  244. EOWNERDEAD :: Platform_Error.EOWNERDEAD /* Previous owner died */
  245. ENOTRECOVERABLE :: Platform_Error.ENOTRECOVERABLE /* State not recoverable */
  246. ELAST :: Platform_Error.ELAST /* Must equal largest Error */
  247. /* end of Error */
  248. O_RDONLY :: 0x000000000
  249. O_WRONLY :: 0x000000001
  250. O_RDWR :: 0x000000002
  251. O_CREATE :: 0x000000200
  252. O_EXCL :: 0x000000800
  253. O_NOCTTY :: 0x000008000
  254. O_TRUNC :: 0x000000400
  255. O_NONBLOCK :: 0x000000004
  256. O_APPEND :: 0x000000008
  257. O_SYNC :: 0x000000080
  258. O_ASYNC :: 0x000000040
  259. O_CLOEXEC :: 0x000400000
  260. RTLD_LAZY :: 0x001
  261. RTLD_NOW :: 0x002
  262. RTLD_GLOBAL :: 0x100
  263. RTLD_LOCAL :: 0x200
  264. RTLD_TRACE :: 0x200
  265. RTLD_NODELETE :: 0x01000
  266. RTLD_NOLOAD :: 0x02000
  267. F_GETPATH :: 15
  268. MAX_PATH :: 1024
  269. MAXNAMLEN :: 511
  270. args := _alloc_command_line_arguments()
  271. Unix_File_Time :: struct {
  272. seconds: time_t,
  273. nanoseconds: c.long,
  274. }
  275. dev_t :: u64
  276. ino_t :: u64
  277. nlink_t :: u32
  278. off_t :: i64
  279. mode_t :: u32
  280. pid_t :: u32
  281. uid_t :: u32
  282. gid_t :: u32
  283. blkcnt_t :: i64
  284. blksize_t :: i32
  285. fflags_t :: u32
  286. time_t :: i64
  287. OS_Stat :: struct {
  288. device_id: dev_t,
  289. mode: mode_t,
  290. _padding0: i16,
  291. ino: ino_t,
  292. nlink: nlink_t,
  293. uid: uid_t,
  294. gid: gid_t,
  295. _padding1: i32,
  296. rdev: dev_t,
  297. last_access: Unix_File_Time,
  298. modified: Unix_File_Time,
  299. status_change: Unix_File_Time,
  300. birthtime: Unix_File_Time,
  301. size: off_t,
  302. blocks: blkcnt_t,
  303. block_size: blksize_t,
  304. flags: fflags_t,
  305. gen: u32,
  306. lspare: [2]u32,
  307. }
  308. Dirent :: struct {
  309. ino: ino_t,
  310. reclen: u16,
  311. namlen: u16,
  312. type: u8,
  313. name: [MAXNAMLEN + 1]byte,
  314. }
  315. Dir :: distinct rawptr // DIR*
  316. // File type
  317. S_IFMT :: 0o170000 // Type of file mask
  318. S_IFIFO :: 0o010000 // Named pipe (fifo)
  319. S_IFCHR :: 0o020000 // Character special
  320. S_IFDIR :: 0o040000 // Directory
  321. S_IFBLK :: 0o060000 // Block special
  322. S_IFREG :: 0o100000 // Regular
  323. S_IFLNK :: 0o120000 // Symbolic link
  324. S_IFSOCK :: 0o140000 // Socket
  325. // File mode
  326. // Read, write, execute/search by owner
  327. S_IRWXU :: 0o0700 // RWX mask for owner
  328. S_IRUSR :: 0o0400 // R for owner
  329. S_IWUSR :: 0o0200 // W for owner
  330. S_IXUSR :: 0o0100 // X for owner
  331. // Read, write, execute/search by group
  332. S_IRWXG :: 0o0070 // RWX mask for group
  333. S_IRGRP :: 0o0040 // R for group
  334. S_IWGRP :: 0o0020 // W for group
  335. S_IXGRP :: 0o0010 // X for group
  336. // Read, write, execute/search by others
  337. S_IRWXO :: 0o0007 // RWX mask for other
  338. S_IROTH :: 0o0004 // R for other
  339. S_IWOTH :: 0o0002 // W for other
  340. S_IXOTH :: 0o0001 // X for other
  341. S_ISUID :: 0o4000 // Set user id on execution
  342. S_ISGID :: 0o2000 // Set group id on execution
  343. S_ISVTX :: 0o1000 // Directory restrcted delete
  344. @(require_results) S_ISLNK :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFLNK }
  345. @(require_results) S_ISREG :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFREG }
  346. @(require_results) S_ISDIR :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFDIR }
  347. @(require_results) S_ISCHR :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFCHR }
  348. @(require_results) S_ISBLK :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFBLK }
  349. @(require_results) S_ISFIFO :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFIFO }
  350. @(require_results) S_ISSOCK :: #force_inline proc "contextless" (m: mode_t) -> bool { return (m & S_IFMT) == S_IFSOCK }
  351. F_OK :: 0 // Test for file existance
  352. X_OK :: 1 // Test for execute permission
  353. W_OK :: 2 // Test for write permission
  354. R_OK :: 4 // Test for read permission
  355. foreign libc {
  356. @(link_name="__errno") __errno_location :: proc() -> ^c.int ---
  357. @(link_name="open") _unix_open :: proc(path: cstring, flags: c.int, #c_vararg mode: ..u32) -> Handle ---
  358. @(link_name="close") _unix_close :: proc(fd: Handle) -> c.int ---
  359. @(link_name="read") _unix_read :: proc(fd: Handle, buf: rawptr, size: c.size_t) -> c.ssize_t ---
  360. @(link_name="pread") _unix_pread :: proc(fd: Handle, buf: rawptr, size: c.size_t, offset: i64) -> c.ssize_t ---
  361. @(link_name="write") _unix_write :: proc(fd: Handle, buf: rawptr, size: c.size_t) -> c.ssize_t ---
  362. @(link_name="pwrite") _unix_pwrite :: proc(fd: Handle, buf: rawptr, size: c.size_t, offset: i64) -> c.ssize_t ---
  363. @(link_name="lseek") _unix_seek :: proc(fd: Handle, offset: i64, whence: c.int) -> i64 ---
  364. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---
  365. @(link_name="stat") _unix_stat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---
  366. @(link_name="__lstat50") _unix_lstat :: proc(path: cstring, sb: ^OS_Stat) -> c.int ---
  367. @(link_name="__fstat50") _unix_fstat :: proc(fd: Handle, stat: ^OS_Stat) -> c.int ---
  368. @(link_name="readlink") _unix_readlink :: proc(path: cstring, buf: ^byte, bufsiz: c.size_t) -> c.ssize_t ---
  369. @(link_name="access") _unix_access :: proc(path: cstring, mask: c.int) -> c.int ---
  370. @(link_name="getcwd") _unix_getcwd :: proc(buf: cstring, len: c.size_t) -> cstring ---
  371. @(link_name="chdir") _unix_chdir :: proc(buf: cstring) -> c.int ---
  372. @(link_name="rename") _unix_rename :: proc(old, new: cstring) -> c.int ---
  373. @(link_name="unlink") _unix_unlink :: proc(path: cstring) -> c.int ---
  374. @(link_name="rmdir") _unix_rmdir :: proc(path: cstring) -> c.int ---
  375. @(link_name="mkdir") _unix_mkdir :: proc(path: cstring, mode: mode_t) -> c.int ---
  376. @(link_name="fcntl") _unix_fcntl :: proc(fd: Handle, cmd: c.int, #c_vararg args: ..any) -> c.int ---
  377. @(link_name="fsync") _unix_fsync :: proc(fd: Handle) -> c.int ---
  378. @(link_name="dup") _unix_dup :: proc(fd: Handle) -> Handle ---
  379. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---
  380. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  381. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  382. @(link_name="__readdir_r30") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  383. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---
  384. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---
  385. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  386. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
  387. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  388. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: [^]byte = nil) -> cstring ---
  389. @(link_name="sysctlbyname") _sysctlbyname :: proc(path: cstring, oldp: rawptr, oldlenp: rawptr, newp: rawptr, newlen: int) -> c.int ---
  390. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  391. }
  392. foreign dl {
  393. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  394. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  395. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  396. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  397. }
  398. @(private)
  399. foreign libc {
  400. _lwp_self :: proc() -> i32 ---
  401. }
  402. // NOTE(phix): Perhaps share the following functions with FreeBSD if they turn out to be the same in the end.
  403. @(require_results)
  404. is_path_separator :: proc(r: rune) -> bool {
  405. return r == '/'
  406. }
  407. @(require_results, no_instrumentation)
  408. get_last_error :: proc "contextless" () -> Error {
  409. return Platform_Error(__errno_location()^)
  410. }
  411. @(require_results)
  412. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0) -> (Handle, Error) {
  413. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  414. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  415. handle := _unix_open(cstr, c.int(flags), c.uint(mode))
  416. if handle == -1 {
  417. return INVALID_HANDLE, get_last_error()
  418. }
  419. return handle, nil
  420. }
  421. close :: proc(fd: Handle) -> Error {
  422. result := _unix_close(fd)
  423. if result == -1 {
  424. return get_last_error()
  425. }
  426. return nil
  427. }
  428. flush :: proc(fd: Handle) -> Error {
  429. result := _unix_fsync(fd)
  430. if result == -1 {
  431. return get_last_error()
  432. }
  433. return nil
  434. }
  435. // We set a max of 1GB to keep alignment and to be safe.
  436. @(private)
  437. MAX_RW :: 1 << 30
  438. read :: proc(fd: Handle, data: []byte) -> (int, Error) {
  439. to_read := min(c.size_t(len(data)), MAX_RW)
  440. bytes_read := _unix_read(fd, &data[0], to_read)
  441. if bytes_read == -1 {
  442. return -1, get_last_error()
  443. }
  444. return int(bytes_read), nil
  445. }
  446. write :: proc(fd: Handle, data: []byte) -> (int, Error) {
  447. if len(data) == 0 {
  448. return 0, nil
  449. }
  450. to_write := min(c.size_t(len(data)), MAX_RW)
  451. bytes_written := _unix_write(fd, &data[0], to_write)
  452. if bytes_written == -1 {
  453. return -1, get_last_error()
  454. }
  455. return int(bytes_written), nil
  456. }
  457. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (n: int, err: Error) {
  458. if len(data) == 0 {
  459. return 0, nil
  460. }
  461. to_read := min(uint(len(data)), MAX_RW)
  462. bytes_read := _unix_pread(fd, raw_data(data), to_read, offset)
  463. if bytes_read < 0 {
  464. return -1, get_last_error()
  465. }
  466. return bytes_read, nil
  467. }
  468. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (n: int, err: Error) {
  469. if len(data) == 0 {
  470. return 0, nil
  471. }
  472. to_write := min(uint(len(data)), MAX_RW)
  473. bytes_written := _unix_pwrite(fd, raw_data(data), to_write, offset)
  474. if bytes_written < 0 {
  475. return -1, get_last_error()
  476. }
  477. return bytes_written, nil
  478. }
  479. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Error) {
  480. switch whence {
  481. case SEEK_SET, SEEK_CUR, SEEK_END:
  482. break
  483. case:
  484. return 0, .Invalid_Whence
  485. }
  486. res := _unix_seek(fd, offset, c.int(whence))
  487. if res == -1 {
  488. errno := get_last_error()
  489. switch errno {
  490. case .EINVAL:
  491. return 0, .Invalid_Offset
  492. }
  493. return 0, errno
  494. }
  495. return res, nil
  496. }
  497. @(require_results)
  498. file_size :: proc(fd: Handle) -> (size: i64, err: Error) {
  499. size = -1
  500. s := _fstat(fd) or_return
  501. size = s.size
  502. return
  503. }
  504. rename :: proc(old_path, new_path: string) -> Error {
  505. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  506. old_path_cstr := strings.clone_to_cstring(old_path, context.temp_allocator)
  507. new_path_cstr := strings.clone_to_cstring(new_path, context.temp_allocator)
  508. res := _unix_rename(old_path_cstr, new_path_cstr)
  509. if res == -1 {
  510. return get_last_error()
  511. }
  512. return nil
  513. }
  514. remove :: proc(path: string) -> Error {
  515. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  516. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  517. res := _unix_unlink(path_cstr)
  518. if res == -1 {
  519. return get_last_error()
  520. }
  521. return nil
  522. }
  523. make_directory :: proc(path: string, mode: mode_t = 0o775) -> Error {
  524. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  525. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  526. res := _unix_mkdir(path_cstr, mode)
  527. if res == -1 {
  528. return get_last_error()
  529. }
  530. return nil
  531. }
  532. remove_directory :: proc(path: string) -> Error {
  533. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  534. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  535. res := _unix_rmdir(path_cstr)
  536. if res == -1 {
  537. return get_last_error()
  538. }
  539. return nil
  540. }
  541. @(require_results)
  542. is_file_handle :: proc(fd: Handle) -> bool {
  543. s, err := _fstat(fd)
  544. if err != nil {
  545. return false
  546. }
  547. return S_ISREG(s.mode)
  548. }
  549. @(require_results)
  550. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  551. s: OS_Stat
  552. err: Error
  553. if follow_links {
  554. s, err = _stat(path)
  555. } else {
  556. s, err = _lstat(path)
  557. }
  558. if err != nil {
  559. return false
  560. }
  561. return S_ISREG(s.mode)
  562. }
  563. @(require_results)
  564. is_dir_handle :: proc(fd: Handle) -> bool {
  565. s, err := _fstat(fd)
  566. if err != nil {
  567. return false
  568. }
  569. return S_ISDIR(s.mode)
  570. }
  571. @(require_results)
  572. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  573. s: OS_Stat
  574. err: Error
  575. if follow_links {
  576. s, err = _stat(path)
  577. } else {
  578. s, err = _lstat(path)
  579. }
  580. if err != nil {
  581. return false
  582. }
  583. return S_ISDIR(s.mode)
  584. }
  585. is_file :: proc {is_file_path, is_file_handle}
  586. is_dir :: proc {is_dir_path, is_dir_handle}
  587. @(require_results)
  588. exists :: proc(path: string) -> bool {
  589. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  590. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  591. res := _unix_access(cpath, O_RDONLY)
  592. return res == 0
  593. }
  594. @(require_results)
  595. fcntl :: proc(fd: int, cmd: int, arg: int) -> (int, Error) {
  596. result := _unix_fcntl(Handle(fd), c.int(cmd), uintptr(arg))
  597. if result < 0 {
  598. return 0, get_last_error()
  599. }
  600. return int(result), nil
  601. }
  602. // NOTE(bill): Uses startup to initialize it
  603. stdin: Handle = 0
  604. stdout: Handle = 1
  605. stderr: Handle = 2
  606. @(require_results)
  607. last_write_time :: proc(fd: Handle) -> (time: File_Time, err: Error) {
  608. s := _fstat(fd) or_return
  609. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  610. return File_Time(modified), nil
  611. }
  612. @(require_results)
  613. last_write_time_by_name :: proc(name: string) -> (time: File_Time, err: Error) {
  614. s := _stat(name) or_return
  615. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  616. return File_Time(modified), nil
  617. }
  618. @(private, require_results, no_sanitize_memory)
  619. _stat :: proc(path: string) -> (OS_Stat, Error) {
  620. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  621. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  622. s: OS_Stat = ---
  623. result := _unix_lstat(cstr, &s)
  624. if result == -1 {
  625. return s, get_last_error()
  626. }
  627. return s, nil
  628. }
  629. @(private, require_results, no_sanitize_memory)
  630. _lstat :: proc(path: string) -> (OS_Stat, Error) {
  631. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  632. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  633. // deliberately uninitialized
  634. s: OS_Stat = ---
  635. res := _unix_lstat(cstr, &s)
  636. if res == -1 {
  637. return s, get_last_error()
  638. }
  639. return s, nil
  640. }
  641. @(private, require_results, no_sanitize_memory)
  642. _fstat :: proc(fd: Handle) -> (OS_Stat, Error) {
  643. s: OS_Stat = ---
  644. result := _unix_fstat(fd, &s)
  645. if result == -1 {
  646. return s, get_last_error()
  647. }
  648. return s, nil
  649. }
  650. @(private, require_results)
  651. _fdopendir :: proc(fd: Handle) -> (Dir, Error) {
  652. dirp := _unix_fdopendir(fd)
  653. if dirp == cast(Dir)nil {
  654. return nil, get_last_error()
  655. }
  656. return dirp, nil
  657. }
  658. @(private)
  659. _closedir :: proc(dirp: Dir) -> Error {
  660. rc := _unix_closedir(dirp)
  661. if rc != 0 {
  662. return get_last_error()
  663. }
  664. return nil
  665. }
  666. @(private)
  667. _rewinddir :: proc(dirp: Dir) {
  668. _unix_rewinddir(dirp)
  669. }
  670. @(private, require_results)
  671. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Error, end_of_stream: bool) {
  672. result: ^Dirent
  673. rc := _unix_readdir_r(dirp, &entry, &result)
  674. if rc != 0 {
  675. err = get_last_error()
  676. return
  677. }
  678. err = nil
  679. if result == nil {
  680. end_of_stream = true
  681. return
  682. }
  683. return
  684. }
  685. @(private, require_results)
  686. _readlink :: proc(path: string) -> (string, Error) {
  687. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  688. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  689. bufsz : uint = MAX_PATH
  690. buf := make([]byte, MAX_PATH)
  691. for {
  692. rc := _unix_readlink(path_cstr, &(buf[0]), bufsz)
  693. if rc == -1 {
  694. delete(buf)
  695. return "", get_last_error()
  696. } else if rc == int(bufsz) {
  697. bufsz += MAX_PATH
  698. delete(buf)
  699. buf = make([]byte, bufsz)
  700. } else {
  701. return strings.string_from_ptr(&buf[0], rc), nil
  702. }
  703. }
  704. return "", Error{}
  705. }
  706. @(private, require_results)
  707. _dup :: proc(fd: Handle) -> (Handle, Error) {
  708. dup := _unix_dup(fd)
  709. if dup == -1 {
  710. return INVALID_HANDLE, get_last_error()
  711. }
  712. return dup, nil
  713. }
  714. @(require_results)
  715. absolute_path_from_handle :: proc(fd: Handle) -> (path: string, err: Error) {
  716. buf: [MAX_PATH]byte
  717. _ = fcntl(int(fd), F_GETPATH, int(uintptr(&buf[0]))) or_return
  718. return strings.clone_from_cstring(cstring(&buf[0]))
  719. }
  720. @(require_results)
  721. absolute_path_from_relative :: proc(rel: string, allocator := context.allocator) -> (path: string, err: Error) {
  722. rel := rel
  723. if rel == "" {
  724. rel = "."
  725. }
  726. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  727. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  728. path_ptr := _unix_realpath(rel_cstr, nil)
  729. if path_ptr == nil {
  730. return "", get_last_error()
  731. }
  732. defer _unix_free(rawptr(path_ptr))
  733. return strings.clone(string(path_ptr), allocator)
  734. }
  735. access :: proc(path: string, mask: int) -> (bool, Error) {
  736. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  737. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  738. result := _unix_access(cstr, c.int(mask))
  739. if result == -1 {
  740. return false, get_last_error()
  741. }
  742. return true, nil
  743. }
  744. @(require_results)
  745. lookup_env_alloc :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  746. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
  747. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  748. // NOTE(tetra): Lifetime of 'cstr' is unclear, but _unix_free(cstr) segfaults.
  749. cstr := _unix_getenv(path_str)
  750. if cstr == nil {
  751. return "", false
  752. }
  753. return strings.clone(string(cstr), allocator), true
  754. }
  755. @(require_results)
  756. lookup_env_buffer :: proc(buf: []u8, key: string) -> (value: string, err: Error) {
  757. if len(key) + 1 > len(buf) {
  758. return "", .Buffer_Full
  759. } else {
  760. copy(buf, key)
  761. }
  762. if value = string(_unix_getenv(cstring(raw_data(buf)))); value == "" {
  763. return "", .Env_Var_Not_Found
  764. } else {
  765. if len(value) > len(buf) {
  766. return "", .Buffer_Full
  767. } else {
  768. copy(buf, value)
  769. return string(buf[:len(value)]), nil
  770. }
  771. }
  772. }
  773. lookup_env :: proc{lookup_env_alloc, lookup_env_buffer}
  774. @(require_results)
  775. get_env_alloc :: proc(key: string, allocator := context.allocator) -> (value: string) {
  776. value, _ = lookup_env(key, allocator)
  777. return
  778. }
  779. @(require_results)
  780. get_env_buf :: proc(buf: []u8, key: string) -> (value: string) {
  781. value, _ = lookup_env(buf, key)
  782. return
  783. }
  784. get_env :: proc{get_env_alloc, get_env_buf}
  785. @(require_results)
  786. get_current_directory :: proc(allocator := context.allocator) -> string {
  787. context.allocator = allocator
  788. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  789. // an authoritative value for it across all systems.
  790. // The largest value I could find was 4096, so might as well use the page size.
  791. page_size := get_page_size()
  792. buf := make([dynamic]u8, page_size)
  793. #no_bounds_check for {
  794. cwd := _unix_getcwd(cstring(&buf[0]), c.size_t(len(buf)))
  795. if cwd != nil {
  796. return string(cwd)
  797. }
  798. if get_last_error() != ERANGE {
  799. delete(buf)
  800. return ""
  801. }
  802. resize(&buf, len(buf)+page_size)
  803. }
  804. unreachable()
  805. }
  806. set_current_directory :: proc(path: string) -> (err: Error) {
  807. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  808. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  809. res := _unix_chdir(cstr)
  810. if res == -1 {
  811. return get_last_error()
  812. }
  813. return nil
  814. }
  815. exit :: proc "contextless" (code: int) -> ! {
  816. runtime._cleanup_runtime_contextless()
  817. _unix_exit(c.int(code))
  818. }
  819. @(require_results)
  820. current_thread_id :: proc "contextless" () -> int {
  821. return int(_lwp_self())
  822. }
  823. @(require_results)
  824. dlopen :: proc(filename: string, flags: int) -> rawptr {
  825. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  826. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  827. handle := _unix_dlopen(cstr, c.int(flags))
  828. return handle
  829. }
  830. @(require_results)
  831. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  832. assert(handle != nil)
  833. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  834. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  835. proc_handle := _unix_dlsym(handle, cstr)
  836. return proc_handle
  837. }
  838. dlclose :: proc(handle: rawptr) -> bool {
  839. assert(handle != nil)
  840. return _unix_dlclose(handle) == 0
  841. }
  842. @(require_results)
  843. dlerror :: proc() -> string {
  844. return string(_unix_dlerror())
  845. }
  846. @(require_results)
  847. get_page_size :: proc() -> int {
  848. // NOTE(tetra): The page size never changes, so why do anything complicated
  849. // if we don't have to.
  850. @static page_size := -1
  851. if page_size != -1 {
  852. return page_size
  853. }
  854. page_size = int(_unix_getpagesize())
  855. return page_size
  856. }
  857. @(private, require_results)
  858. _processor_core_count :: proc() -> int {
  859. count : int = 0
  860. count_size := size_of(count)
  861. if _sysctlbyname("hw.ncpu", &count, &count_size, nil, 0) == 0 {
  862. if count > 0 {
  863. return count
  864. }
  865. }
  866. return 1
  867. }
  868. @(private, require_results)
  869. _alloc_command_line_arguments :: proc() -> []string {
  870. res := make([]string, len(runtime.args__))
  871. for _, i in res {
  872. res[i] = string(runtime.args__[i])
  873. }
  874. return res
  875. }
  876. @(private, fini)
  877. _delete_command_line_arguments :: proc() {
  878. delete(args)
  879. }