os_linux.odin 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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. Socket :: distinct int
  15. INVALID_HANDLE :: ~Handle(0)
  16. ERROR_NONE: Errno : 0
  17. EPERM: Errno : 1
  18. ENOENT: Errno : 2
  19. ESRCH: Errno : 3
  20. EINTR: Errno : 4
  21. EIO: Errno : 5
  22. ENXIO: Errno : 6
  23. EBADF: Errno : 9
  24. EAGAIN: Errno : 11
  25. ENOMEM: Errno : 12
  26. EACCES: Errno : 13
  27. EFAULT: Errno : 14
  28. EEXIST: Errno : 17
  29. ENODEV: Errno : 19
  30. ENOTDIR: Errno : 20
  31. EISDIR: Errno : 21
  32. EINVAL: Errno : 22
  33. ENFILE: Errno : 23
  34. EMFILE: Errno : 24
  35. ETXTBSY: Errno : 26
  36. EFBIG: Errno : 27
  37. ENOSPC: Errno : 28
  38. ESPIPE: Errno : 29
  39. EROFS: Errno : 30
  40. EPIPE: Errno : 32
  41. ERANGE: Errno : 34 /* Result too large */
  42. EDEADLK: Errno : 35 /* Resource deadlock would occur */
  43. ENAMETOOLONG: Errno : 36 /* File name too long */
  44. ENOLCK: Errno : 37 /* No record locks available */
  45. ENOSYS: Errno : 38 /* Invalid system call number */
  46. ENOTEMPTY: Errno : 39 /* Directory not empty */
  47. ELOOP: Errno : 40 /* Too many symbolic links encountered */
  48. EWOULDBLOCK: Errno : EAGAIN /* Operation would block */
  49. ENOMSG: Errno : 42 /* No message of desired type */
  50. EIDRM: Errno : 43 /* Identifier removed */
  51. ECHRNG: Errno : 44 /* Channel number out of range */
  52. EL2NSYNC: Errno : 45 /* Level 2 not synchronized */
  53. EL3HLT: Errno : 46 /* Level 3 halted */
  54. EL3RST: Errno : 47 /* Level 3 reset */
  55. ELNRNG: Errno : 48 /* Link number out of range */
  56. EUNATCH: Errno : 49 /* Protocol driver not attached */
  57. ENOCSI: Errno : 50 /* No CSI structure available */
  58. EL2HLT: Errno : 51 /* Level 2 halted */
  59. EBADE: Errno : 52 /* Invalid exchange */
  60. EBADR: Errno : 53 /* Invalid request descriptor */
  61. EXFULL: Errno : 54 /* Exchange full */
  62. ENOANO: Errno : 55 /* No anode */
  63. EBADRQC: Errno : 56 /* Invalid request code */
  64. EBADSLT: Errno : 57 /* Invalid slot */
  65. EDEADLOCK: Errno : EDEADLK
  66. EBFONT: Errno : 59 /* Bad font file format */
  67. ENOSTR: Errno : 60 /* Device not a stream */
  68. ENODATA: Errno : 61 /* No data available */
  69. ETIME: Errno : 62 /* Timer expired */
  70. ENOSR: Errno : 63 /* Out of streams resources */
  71. ENONET: Errno : 64 /* Machine is not on the network */
  72. ENOPKG: Errno : 65 /* Package not installed */
  73. EREMOTE: Errno : 66 /* Object is remote */
  74. ENOLINK: Errno : 67 /* Link has been severed */
  75. EADV: Errno : 68 /* Advertise error */
  76. ESRMNT: Errno : 69 /* Srmount error */
  77. ECOMM: Errno : 70 /* Communication error on send */
  78. EPROTO: Errno : 71 /* Protocol error */
  79. EMULTIHOP: Errno : 72 /* Multihop attempted */
  80. EDOTDOT: Errno : 73 /* RFS specific error */
  81. EBADMSG: Errno : 74 /* Not a data message */
  82. EOVERFLOW: Errno : 75 /* Value too large for defined data type */
  83. ENOTUNIQ: Errno : 76 /* Name not unique on network */
  84. EBADFD: Errno : 77 /* File descriptor in bad state */
  85. EREMCHG: Errno : 78 /* Remote address changed */
  86. ELIBACC: Errno : 79 /* Can not access a needed shared library */
  87. ELIBBAD: Errno : 80 /* Accessing a corrupted shared library */
  88. ELIBSCN: Errno : 81 /* .lib section in a.out corrupted */
  89. ELIBMAX: Errno : 82 /* Attempting to link in too many shared libraries */
  90. ELIBEXEC: Errno : 83 /* Cannot exec a shared library directly */
  91. EILSEQ: Errno : 84 /* Illegal byte sequence */
  92. ERESTART: Errno : 85 /* Interrupted system call should be restarted */
  93. ESTRPIPE: Errno : 86 /* Streams pipe error */
  94. EUSERS: Errno : 87 /* Too many users */
  95. ENOTSOCK: Errno : 88 /* Socket operation on non-socket */
  96. EDESTADDRREQ: Errno : 89 /* Destination address required */
  97. EMSGSIZE: Errno : 90 /* Message too long */
  98. EPROTOTYPE: Errno : 91 /* Protocol wrong type for socket */
  99. ENOPROTOOPT: Errno : 92 /* Protocol not available */
  100. EPROTONOSUPPORT:Errno : 93 /* Protocol not supported */
  101. ESOCKTNOSUPPORT:Errno : 94 /* Socket type not supported */
  102. EOPNOTSUPP: Errno : 95 /* Operation not supported on transport endpoint */
  103. EPFNOSUPPORT: Errno : 96 /* Protocol family not supported */
  104. EAFNOSUPPORT: Errno : 97 /* Address family not supported by protocol */
  105. EADDRINUSE: Errno : 98 /* Address already in use */
  106. EADDRNOTAVAIL: Errno : 99 /* Cannot assign requested address */
  107. ENETDOWN: Errno : 100 /* Network is down */
  108. ENETUNREACH: Errno : 101 /* Network is unreachable */
  109. ENETRESET: Errno : 102 /* Network dropped connection because of reset */
  110. ECONNABORTED: Errno : 103 /* Software caused connection abort */
  111. ECONNRESET: Errno : 104 /* Connection reset by peer */
  112. ENOBUFS: Errno : 105 /* No buffer space available */
  113. EISCONN: Errno : 106 /* Transport endpoint is already connected */
  114. ENOTCONN: Errno : 107 /* Transport endpoint is not connected */
  115. ESHUTDOWN: Errno : 108 /* Cannot send after transport endpoint shutdown */
  116. ETOOMANYREFS: Errno : 109 /* Too many references: cannot splice */
  117. ETIMEDOUT: Errno : 110 /* Connection timed out */
  118. ECONNREFUSED: Errno : 111 /* Connection refused */
  119. EHOSTDOWN: Errno : 112 /* Host is down */
  120. EHOSTUNREACH: Errno : 113 /* No route to host */
  121. EALREADY: Errno : 114 /* Operation already in progress */
  122. EINPROGRESS: Errno : 115 /* Operation now in progress */
  123. ESTALE: Errno : 116 /* Stale file handle */
  124. EUCLEAN: Errno : 117 /* Structure needs cleaning */
  125. ENOTNAM: Errno : 118 /* Not a XENIX named type file */
  126. ENAVAIL: Errno : 119 /* No XENIX semaphores available */
  127. EISNAM: Errno : 120 /* Is a named type file */
  128. EREMOTEIO: Errno : 121 /* Remote I/O error */
  129. EDQUOT: Errno : 122 /* Quota exceeded */
  130. ENOMEDIUM: Errno : 123 /* No medium found */
  131. EMEDIUMTYPE: Errno : 124 /* Wrong medium type */
  132. ECANCELED: Errno : 125 /* Operation Canceled */
  133. ENOKEY: Errno : 126 /* Required key not available */
  134. EKEYEXPIRED: Errno : 127 /* Key has expired */
  135. EKEYREVOKED: Errno : 128 /* Key has been revoked */
  136. EKEYREJECTED: Errno : 129 /* Key was rejected by service */
  137. /* for robust mutexes */
  138. EOWNERDEAD: Errno : 130 /* Owner died */
  139. ENOTRECOVERABLE: Errno : 131 /* State not recoverable */
  140. ERFKILL: Errno : 132 /* Operation not possible due to RF-kill */
  141. EHWPOISON: Errno : 133 /* Memory page has hardware error */
  142. ADDR_NO_RANDOMIZE :: 0x40000
  143. O_RDONLY :: 0x00000
  144. O_WRONLY :: 0x00001
  145. O_RDWR :: 0x00002
  146. O_CREATE :: 0x00040
  147. O_EXCL :: 0x00080
  148. O_NOCTTY :: 0x00100
  149. O_TRUNC :: 0x00200
  150. O_NONBLOCK :: 0x00800
  151. O_APPEND :: 0x00400
  152. O_SYNC :: 0x01000
  153. O_ASYNC :: 0x02000
  154. O_CLOEXEC :: 0x80000
  155. SEEK_DATA :: 3
  156. SEEK_HOLE :: 4
  157. SEEK_MAX :: SEEK_HOLE
  158. AF_UNSPEC: int : 0
  159. AF_UNIX: int : 1
  160. AF_LOCAL: int : AF_UNIX
  161. AF_INET: int : 2
  162. AF_INET6: int : 10
  163. AF_PACKET: int : 17
  164. AF_BLUETOOTH: int : 31
  165. SOCK_STREAM: int : 1
  166. SOCK_DGRAM: int : 2
  167. SOCK_RAW: int : 3
  168. SOCK_RDM: int : 4
  169. SOCK_SEQPACKET: int : 5
  170. SOCK_PACKET: int : 10
  171. INADDR_ANY: c.ulong : 0
  172. INADDR_BROADCAST: c.ulong : 0xffffffff
  173. INADDR_NONE: c.ulong : 0xffffffff
  174. INADDR_DUMMY: c.ulong : 0xc0000008
  175. IPPROTO_IP: int : 0
  176. IPPROTO_ICMP: int : 1
  177. IPPROTO_TCP: int : 6
  178. IPPROTO_UDP: int : 17
  179. IPPROTO_IPV6: int : 41
  180. IPPROTO_ETHERNET: int : 143
  181. IPPROTO_RAW: int : 255
  182. SHUT_RD: int : 0
  183. SHUT_WR: int : 1
  184. SHUT_RDWR: int : 2
  185. SOL_SOCKET: int : 1
  186. SO_DEBUG: int : 1
  187. SO_REUSEADDR: int : 2
  188. SO_DONTROUTE: int : 5
  189. SO_BROADCAST: int : 6
  190. SO_SNDBUF: int : 7
  191. SO_RCVBUF: int : 8
  192. SO_KEEPALIVE: int : 9
  193. SO_OOBINLINE: int : 10
  194. SO_LINGER: int : 13
  195. SO_REUSEPORT: int : 15
  196. SO_RCVTIMEO_NEW: int : 66
  197. SO_SNDTIMEO_NEW: int : 67
  198. TCP_NODELAY: int : 1
  199. TCP_CORK: int : 3
  200. MSG_TRUNC : int : 0x20
  201. // TODO: add remaining fcntl commands
  202. // reference: https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/fcntl.h
  203. F_GETFL: int : 3 /* Get file flags */
  204. F_SETFL: int : 4 /* Set file flags */
  205. // NOTE(zangent): These are OS specific!
  206. // Do not mix these up!
  207. RTLD_LAZY :: 0x001
  208. RTLD_NOW :: 0x002
  209. RTLD_BINDING_MASK :: 0x3
  210. RTLD_GLOBAL :: 0x100
  211. socklen_t :: c.int
  212. Timeval :: struct {
  213. seconds: i64,
  214. microseconds: int,
  215. }
  216. // "Argv" arguments converted to Odin strings
  217. args := _alloc_command_line_arguments()
  218. Unix_File_Time :: struct {
  219. seconds: i64,
  220. nanoseconds: i64,
  221. }
  222. OS_Stat :: struct {
  223. device_id: u64, // ID of device containing file
  224. serial: u64, // File serial number
  225. nlink: u64, // Number of hard links
  226. mode: u32, // Mode of the file
  227. uid: u32, // User ID of the file's owner
  228. gid: u32, // Group ID of the file's group
  229. _padding: i32, // 32 bits of padding
  230. rdev: u64, // Device ID, if device
  231. size: i64, // Size of the file, in bytes
  232. block_size: i64, // Optimal bllocksize for I/O
  233. blocks: i64, // Number of 512-byte blocks allocated
  234. last_access: Unix_File_Time, // Time of last access
  235. modified: Unix_File_Time, // Time of last modification
  236. status_change: Unix_File_Time, // Time of last status change
  237. _reserve1,
  238. _reserve2,
  239. _reserve3: i64,
  240. }
  241. // NOTE(laleksic, 2021-01-21): Comment and rename these to match OS_Stat above
  242. Dirent :: struct {
  243. ino: u64,
  244. off: u64,
  245. reclen: u16,
  246. type: u8,
  247. name: [256]byte,
  248. }
  249. ADDRESS_FAMILY :: u16
  250. SOCKADDR :: struct #packed {
  251. sa_family: ADDRESS_FAMILY,
  252. sa_data: [14]c.char,
  253. }
  254. SOCKADDR_STORAGE_LH :: struct #packed {
  255. ss_family: ADDRESS_FAMILY,
  256. __ss_pad1: [6]c.char,
  257. __ss_align: i64,
  258. __ss_pad2: [112]c.char,
  259. }
  260. sockaddr_in :: struct #packed {
  261. sin_family: ADDRESS_FAMILY,
  262. sin_port: u16be,
  263. sin_addr: in_addr,
  264. sin_zero: [8]c.char,
  265. }
  266. sockaddr_in6 :: struct #packed {
  267. sin6_family: ADDRESS_FAMILY,
  268. sin6_port: u16be,
  269. sin6_flowinfo: c.ulong,
  270. sin6_addr: in6_addr,
  271. sin6_scope_id: c.ulong,
  272. }
  273. in_addr :: struct #packed {
  274. s_addr: u32,
  275. }
  276. in6_addr :: struct #packed {
  277. s6_addr: [16]u8,
  278. }
  279. rtnl_link_stats :: struct #packed {
  280. rx_packets: u32,
  281. tx_packets: u32,
  282. rx_bytes: u32,
  283. tx_bytes: u32,
  284. rx_errors: u32,
  285. tx_errors: u32,
  286. rx_dropped: u32,
  287. tx_dropped: u32,
  288. multicast: u32,
  289. collisions: u32,
  290. rx_length_errors: u32,
  291. rx_over_errors: u32,
  292. rx_crc_errors: u32,
  293. rx_frame_errors: u32,
  294. rx_fifo_errors: u32,
  295. rx_missed_errors: u32,
  296. tx_aborted_errors: u32,
  297. tx_carrier_errors: u32,
  298. tx_fifo_errors: u32,
  299. tx_heartbeat_errors: u32,
  300. tx_window_errors: u32,
  301. rx_compressed: u32,
  302. tx_compressed: u32,
  303. rx_nohandler: u32,
  304. }
  305. SIOCGIFFLAG :: enum c.int {
  306. UP = 0, /* Interface is up. */
  307. BROADCAST = 1, /* Broadcast address valid. */
  308. DEBUG = 2, /* Turn on debugging. */
  309. LOOPBACK = 3, /* Is a loopback net. */
  310. POINT_TO_POINT = 4, /* Interface is point-to-point link. */
  311. NO_TRAILERS = 5, /* Avoid use of trailers. */
  312. RUNNING = 6, /* Resources allocated. */
  313. NOARP = 7, /* No address resolution protocol. */
  314. PROMISC = 8, /* Receive all packets. */
  315. ALL_MULTI = 9, /* Receive all multicast packets. Unimplemented. */
  316. MASTER = 10, /* Master of a load balancer. */
  317. SLAVE = 11, /* Slave of a load balancer. */
  318. MULTICAST = 12, /* Supports multicast. */
  319. PORTSEL = 13, /* Can set media type. */
  320. AUTOMEDIA = 14, /* Auto media select active. */
  321. DYNAMIC = 15, /* Dialup device with changing addresses. */
  322. LOWER_UP = 16,
  323. DORMANT = 17,
  324. ECHO = 18,
  325. }
  326. SIOCGIFFLAGS :: bit_set[SIOCGIFFLAG; c.int]
  327. ifaddrs :: struct {
  328. next: ^ifaddrs,
  329. name: cstring,
  330. flags: SIOCGIFFLAGS,
  331. address: ^SOCKADDR,
  332. netmask: ^SOCKADDR,
  333. broadcast_or_dest: ^SOCKADDR, // Broadcast or Point-to-Point address
  334. data: rawptr, // Address-specific data.
  335. }
  336. Dir :: distinct rawptr // DIR*
  337. // File type
  338. S_IFMT :: 0o170000 // Type of file mask
  339. S_IFIFO :: 0o010000 // Named pipe (fifo)
  340. S_IFCHR :: 0o020000 // Character special
  341. S_IFDIR :: 0o040000 // Directory
  342. S_IFBLK :: 0o060000 // Block special
  343. S_IFREG :: 0o100000 // Regular
  344. S_IFLNK :: 0o120000 // Symbolic link
  345. S_IFSOCK :: 0o140000 // Socket
  346. // File mode
  347. // Read, write, execute/search by owner
  348. S_IRWXU :: 0o0700 // RWX mask for owner
  349. S_IRUSR :: 0o0400 // R for owner
  350. S_IWUSR :: 0o0200 // W for owner
  351. S_IXUSR :: 0o0100 // X for owner
  352. // Read, write, execute/search by group
  353. S_IRWXG :: 0o0070 // RWX mask for group
  354. S_IRGRP :: 0o0040 // R for group
  355. S_IWGRP :: 0o0020 // W for group
  356. S_IXGRP :: 0o0010 // X for group
  357. // Read, write, execute/search by others
  358. S_IRWXO :: 0o0007 // RWX mask for other
  359. S_IROTH :: 0o0004 // R for other
  360. S_IWOTH :: 0o0002 // W for other
  361. S_IXOTH :: 0o0001 // X for other
  362. S_ISUID :: 0o4000 // Set user id on execution
  363. S_ISGID :: 0o2000 // Set group id on execution
  364. S_ISVTX :: 0o1000 // Directory restrcted delete
  365. S_ISLNK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFLNK }
  366. S_ISREG :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFREG }
  367. S_ISDIR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFDIR }
  368. S_ISCHR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFCHR }
  369. S_ISBLK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFBLK }
  370. S_ISFIFO :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFIFO }
  371. S_ISSOCK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFSOCK }
  372. F_OK :: 0 // Test for file existance
  373. X_OK :: 1 // Test for execute permission
  374. W_OK :: 2 // Test for write permission
  375. R_OK :: 4 // Test for read permission
  376. AT_FDCWD :: ~uintptr(99) /* -100 */
  377. AT_REMOVEDIR :: uintptr(0x200)
  378. AT_SYMLINK_NOFOLLOW :: uintptr(0x100)
  379. pollfd :: struct {
  380. fd: c.int,
  381. events: c.short,
  382. revents: c.short,
  383. }
  384. sigset_t :: distinct u64
  385. foreign libc {
  386. @(link_name="__errno_location") __errno_location :: proc() -> ^int ---
  387. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---
  388. @(link_name="get_nprocs") _unix_get_nprocs :: proc() -> c.int ---
  389. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---
  390. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  391. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  392. @(link_name="readdir_r") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  393. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---
  394. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---
  395. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  396. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
  397. @(link_name="execvp") _unix_execvp :: proc(path: cstring, argv: [^]cstring) -> int ---
  398. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  399. @(link_name="putenv") _unix_putenv :: proc(cstring) -> c.int ---
  400. @(link_name="setenv") _unix_setenv :: proc(key: cstring, value: cstring, overwrite: c.int) -> c.int ---
  401. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: rawptr) -> rawptr ---
  402. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  403. }
  404. foreign dl {
  405. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  406. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  407. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  408. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  409. @(link_name="getifaddrs") _getifaddrs :: proc(ifap: ^^ifaddrs) -> (c.int) ---
  410. @(link_name="freeifaddrs") _freeifaddrs :: proc(ifa: ^ifaddrs) ---
  411. }
  412. is_path_separator :: proc(r: rune) -> bool {
  413. return r == '/'
  414. }
  415. // determine errno from syscall return value
  416. @private
  417. _get_errno :: proc(res: int) -> Errno {
  418. if res < 0 && res > -4096 {
  419. return Errno(-res)
  420. }
  421. return 0
  422. }
  423. // get errno from libc
  424. get_last_error :: proc "contextless" () -> int {
  425. return __errno_location()^
  426. }
  427. personality :: proc(persona: u64) -> (Errno) {
  428. res := unix.sys_personality(persona)
  429. if res == -1 {
  430. return _get_errno(res)
  431. }
  432. return ERROR_NONE
  433. }
  434. fork :: proc() -> (Pid, Errno) {
  435. pid := unix.sys_fork()
  436. if pid == -1 {
  437. return -1, _get_errno(pid)
  438. }
  439. return Pid(pid), ERROR_NONE
  440. }
  441. execvp :: proc(path: string, args: []string) -> Errno {
  442. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  443. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  444. args_cstrs := make([]cstring, len(args) + 2, context.temp_allocator)
  445. args_cstrs[0] = strings.clone_to_cstring(path, context.temp_allocator)
  446. for i := 0; i < len(args); i += 1 {
  447. args_cstrs[i+1] = strings.clone_to_cstring(args[i], context.temp_allocator)
  448. }
  449. _unix_execvp(path_cstr, raw_data(args_cstrs))
  450. return Errno(get_last_error())
  451. }
  452. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0o000) -> (Handle, Errno) {
  453. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  454. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  455. handle := unix.sys_open(cstr, flags, uint(mode))
  456. if handle < 0 {
  457. return INVALID_HANDLE, _get_errno(handle)
  458. }
  459. return Handle(handle), ERROR_NONE
  460. }
  461. close :: proc(fd: Handle) -> Errno {
  462. return _get_errno(unix.sys_close(int(fd)))
  463. }
  464. read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  465. if len(data) == 0 {
  466. return 0, ERROR_NONE
  467. }
  468. bytes_read := unix.sys_read(int(fd), raw_data(data), len(data))
  469. if bytes_read < 0 {
  470. return -1, _get_errno(bytes_read)
  471. }
  472. return bytes_read, ERROR_NONE
  473. }
  474. write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  475. if len(data) == 0 {
  476. return 0, ERROR_NONE
  477. }
  478. bytes_written := unix.sys_write(int(fd), raw_data(data), len(data))
  479. if bytes_written < 0 {
  480. return -1, _get_errno(bytes_written)
  481. }
  482. return bytes_written, ERROR_NONE
  483. }
  484. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  485. if len(data) == 0 {
  486. return 0, ERROR_NONE
  487. }
  488. bytes_read := unix.sys_pread(int(fd), raw_data(data), len(data), offset)
  489. if bytes_read < 0 {
  490. return -1, _get_errno(bytes_read)
  491. }
  492. return bytes_read, ERROR_NONE
  493. }
  494. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  495. if len(data) == 0 {
  496. return 0, ERROR_NONE
  497. }
  498. bytes_written := unix.sys_pwrite(int(fd), raw_data(data), uint(len(data)), offset)
  499. if bytes_written < 0 {
  500. return -1, _get_errno(bytes_written)
  501. }
  502. return bytes_written, ERROR_NONE
  503. }
  504. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  505. res := unix.sys_lseek(int(fd), offset, whence)
  506. if res < 0 {
  507. return -1, _get_errno(int(res))
  508. }
  509. return i64(res), ERROR_NONE
  510. }
  511. file_size :: proc(fd: Handle) -> (i64, Errno) {
  512. // deliberately uninitialized; the syscall fills this buffer for us
  513. s: OS_Stat = ---
  514. result := unix.sys_fstat(int(fd), rawptr(&s))
  515. if result < 0 {
  516. return 0, _get_errno(result)
  517. }
  518. return max(s.size, 0), ERROR_NONE
  519. }
  520. rename :: proc(old_path, new_path: string) -> Errno {
  521. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  522. old_path_cstr := strings.clone_to_cstring(old_path, context.temp_allocator)
  523. new_path_cstr := strings.clone_to_cstring(new_path, context.temp_allocator)
  524. return _get_errno(unix.sys_rename(old_path_cstr, new_path_cstr))
  525. }
  526. remove :: proc(path: string) -> Errno {
  527. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  528. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  529. return _get_errno(unix.sys_unlink(path_cstr))
  530. }
  531. make_directory :: proc(path: string, mode: u32 = 0o775) -> Errno {
  532. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  533. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  534. return _get_errno(unix.sys_mkdir(path_cstr, uint(mode)))
  535. }
  536. remove_directory :: proc(path: string) -> Errno {
  537. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  538. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  539. return _get_errno(unix.sys_rmdir(path_cstr))
  540. }
  541. is_file_handle :: proc(fd: Handle) -> bool {
  542. s, err := _fstat(fd)
  543. if err != ERROR_NONE {
  544. return false
  545. }
  546. return S_ISREG(s.mode)
  547. }
  548. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  549. s: OS_Stat
  550. err: Errno
  551. if follow_links {
  552. s, err = _stat(path)
  553. } else {
  554. s, err = _lstat(path)
  555. }
  556. if err != ERROR_NONE {
  557. return false
  558. }
  559. return S_ISREG(s.mode)
  560. }
  561. is_dir_handle :: proc(fd: Handle) -> bool {
  562. s, err := _fstat(fd)
  563. if err != ERROR_NONE {
  564. return false
  565. }
  566. return S_ISDIR(s.mode)
  567. }
  568. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  569. s: OS_Stat
  570. err: Errno
  571. if follow_links {
  572. s, err = _stat(path)
  573. } else {
  574. s, err = _lstat(path)
  575. }
  576. if err != ERROR_NONE {
  577. return false
  578. }
  579. return S_ISDIR(s.mode)
  580. }
  581. is_file :: proc {is_file_path, is_file_handle}
  582. is_dir :: proc {is_dir_path, is_dir_handle}
  583. exists :: proc(path: string) -> bool {
  584. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  585. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  586. res := unix.sys_access(cpath, O_RDONLY)
  587. return res == 0
  588. }
  589. // NOTE(bill): Uses startup to initialize it
  590. stdin: Handle = 0
  591. stdout: Handle = 1
  592. stderr: Handle = 2
  593. /* TODO(zangent): Implement these!
  594. last_write_time :: proc(fd: Handle) -> File_Time {}
  595. last_write_time_by_name :: proc(name: string) -> File_Time {}
  596. */
  597. last_write_time :: proc(fd: Handle) -> (File_Time, Errno) {
  598. s, err := _fstat(fd)
  599. if err != ERROR_NONE {
  600. return 0, err
  601. }
  602. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  603. return File_Time(modified), ERROR_NONE
  604. }
  605. last_write_time_by_name :: proc(name: string) -> (File_Time, Errno) {
  606. s, err := _stat(name)
  607. if err != ERROR_NONE {
  608. return 0, err
  609. }
  610. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  611. return File_Time(modified), ERROR_NONE
  612. }
  613. @private
  614. _stat :: proc(path: string) -> (OS_Stat, Errno) {
  615. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  616. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  617. // deliberately uninitialized; the syscall fills this buffer for us
  618. s: OS_Stat = ---
  619. result := unix.sys_stat(cstr, &s)
  620. if result < 0 {
  621. return s, _get_errno(result)
  622. }
  623. return s, ERROR_NONE
  624. }
  625. @private
  626. _lstat :: proc(path: string) -> (OS_Stat, Errno) {
  627. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  628. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  629. // deliberately uninitialized; the syscall fills this buffer for us
  630. s: OS_Stat = ---
  631. result := unix.sys_lstat(cstr, &s)
  632. if result < 0 {
  633. return s, _get_errno(result)
  634. }
  635. return s, ERROR_NONE
  636. }
  637. @private
  638. _fstat :: proc(fd: Handle) -> (OS_Stat, Errno) {
  639. // deliberately uninitialized; the syscall fills this buffer for us
  640. s: OS_Stat = ---
  641. result := unix.sys_fstat(int(fd), rawptr(&s))
  642. if result < 0 {
  643. return s, _get_errno(result)
  644. }
  645. return s, ERROR_NONE
  646. }
  647. @private
  648. _fdopendir :: proc(fd: Handle) -> (Dir, Errno) {
  649. dirp := _unix_fdopendir(fd)
  650. if dirp == cast(Dir)nil {
  651. return nil, Errno(get_last_error())
  652. }
  653. return dirp, ERROR_NONE
  654. }
  655. @private
  656. _closedir :: proc(dirp: Dir) -> Errno {
  657. rc := _unix_closedir(dirp)
  658. if rc != 0 {
  659. return Errno(get_last_error())
  660. }
  661. return ERROR_NONE
  662. }
  663. @private
  664. _rewinddir :: proc(dirp: Dir) {
  665. _unix_rewinddir(dirp)
  666. }
  667. @private
  668. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Errno, end_of_stream: bool) {
  669. result: ^Dirent
  670. rc := _unix_readdir_r(dirp, &entry, &result)
  671. if rc != 0 {
  672. err = Errno(get_last_error())
  673. return
  674. }
  675. err = ERROR_NONE
  676. if result == nil {
  677. end_of_stream = true
  678. return
  679. }
  680. end_of_stream = false
  681. return
  682. }
  683. @private
  684. _readlink :: proc(path: string) -> (string, Errno) {
  685. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  686. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  687. bufsz : uint = 256
  688. buf := make([]byte, bufsz)
  689. for {
  690. rc := unix.sys_readlink(path_cstr, &(buf[0]), bufsz)
  691. if rc < 0 {
  692. delete(buf)
  693. return "", _get_errno(rc)
  694. } else if rc == int(bufsz) {
  695. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  696. bufsz *= 2
  697. delete(buf)
  698. buf = make([]byte, bufsz)
  699. } else {
  700. return strings.string_from_ptr(&buf[0], rc), ERROR_NONE
  701. }
  702. }
  703. }
  704. absolute_path_from_handle :: proc(fd: Handle) -> (string, Errno) {
  705. buf : [256]byte
  706. fd_str := strconv.itoa( buf[:], cast(int)fd )
  707. procfs_path := strings.concatenate( []string{ "/proc/self/fd/", fd_str } )
  708. defer delete(procfs_path)
  709. return _readlink(procfs_path)
  710. }
  711. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Errno) {
  712. rel := rel
  713. if rel == "" {
  714. rel = "."
  715. }
  716. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  717. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  718. path_ptr := _unix_realpath(rel_cstr, nil)
  719. if path_ptr == nil {
  720. return "", Errno(get_last_error())
  721. }
  722. defer _unix_free(path_ptr)
  723. path_cstr := transmute(cstring)path_ptr
  724. path = strings.clone( string(path_cstr) )
  725. return path, ERROR_NONE
  726. }
  727. access :: proc(path: string, mask: int) -> (bool, Errno) {
  728. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  729. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  730. result := unix.sys_access(cstr, mask)
  731. if result < 0 {
  732. return false, _get_errno(result)
  733. }
  734. return true, ERROR_NONE
  735. }
  736. heap_alloc :: proc(size: int, zero_memory := true) -> rawptr {
  737. if size <= 0 {
  738. return nil
  739. }
  740. if zero_memory {
  741. return _unix_calloc(1, c.size_t(size))
  742. } else {
  743. return _unix_malloc(c.size_t(size))
  744. }
  745. }
  746. heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
  747. // NOTE: _unix_realloc doesn't guarantee new memory will be zeroed on
  748. // POSIX platforms. Ensure your caller takes this into account.
  749. return _unix_realloc(ptr, c.size_t(new_size))
  750. }
  751. heap_free :: proc(ptr: rawptr) {
  752. _unix_free(ptr)
  753. }
  754. lookup_env :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  755. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
  756. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  757. // NOTE(tetra): Lifetime of 'cstr' is unclear, but _unix_free(cstr) segfaults.
  758. cstr := _unix_getenv(path_str)
  759. if cstr == nil {
  760. return "", false
  761. }
  762. return strings.clone(string(cstr), allocator), true
  763. }
  764. get_env :: proc(key: string, allocator := context.allocator) -> (value: string) {
  765. value, _ = lookup_env(key, allocator)
  766. return
  767. }
  768. set_env :: proc(key, value: string) -> Errno {
  769. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  770. key_cstring := strings.clone_to_cstring(key, context.temp_allocator)
  771. value_cstring := strings.clone_to_cstring(value, context.temp_allocator)
  772. // NOTE(GoNZooo): `setenv` instead of `putenv` because it copies both key and value more commonly
  773. res := _unix_setenv(key_cstring, value_cstring, 1)
  774. if res < 0 {
  775. return Errno(get_last_error())
  776. }
  777. return ERROR_NONE
  778. }
  779. unset_env :: proc(key: string) -> Errno {
  780. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  781. s := strings.clone_to_cstring(key, context.temp_allocator)
  782. res := _unix_putenv(s)
  783. if res < 0 {
  784. return Errno(get_last_error())
  785. }
  786. return ERROR_NONE
  787. }
  788. get_current_directory :: proc() -> string {
  789. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  790. // an authoritative value for it across all systems.
  791. // The largest value I could find was 4096, so might as well use the page size.
  792. page_size := get_page_size()
  793. buf := make([dynamic]u8, page_size)
  794. for {
  795. #no_bounds_check res := unix.sys_getcwd(&buf[0], uint(len(buf)))
  796. if res >= 0 {
  797. return strings.string_from_null_terminated_ptr(&buf[0], len(buf))
  798. }
  799. if _get_errno(res) != ERANGE {
  800. delete(buf)
  801. return ""
  802. }
  803. resize(&buf, len(buf)+page_size)
  804. }
  805. unreachable()
  806. }
  807. set_current_directory :: proc(path: string) -> (err: Errno) {
  808. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  809. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  810. res := unix.sys_chdir(cstr)
  811. if res < 0 {
  812. return _get_errno(res)
  813. }
  814. return ERROR_NONE
  815. }
  816. exit :: proc "contextless" (code: int) -> ! {
  817. runtime._cleanup_runtime_contextless()
  818. _unix_exit(c.int(code))
  819. }
  820. current_thread_id :: proc "contextless" () -> int {
  821. return unix.sys_gettid()
  822. }
  823. dlopen :: proc(filename: string, flags: int) -> rawptr {
  824. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  825. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  826. handle := _unix_dlopen(cstr, c.int(flags))
  827. return handle
  828. }
  829. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  830. assert(handle != nil)
  831. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  832. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  833. proc_handle := _unix_dlsym(handle, cstr)
  834. return proc_handle
  835. }
  836. dlclose :: proc(handle: rawptr) -> bool {
  837. assert(handle != nil)
  838. return _unix_dlclose(handle) == 0
  839. }
  840. dlerror :: proc() -> string {
  841. return string(_unix_dlerror())
  842. }
  843. get_page_size :: proc() -> int {
  844. // NOTE(tetra): The page size never changes, so why do anything complicated
  845. // if we don't have to.
  846. @static page_size := -1
  847. if page_size != -1 {
  848. return page_size
  849. }
  850. page_size = int(_unix_getpagesize())
  851. return page_size
  852. }
  853. @(private)
  854. _processor_core_count :: proc() -> int {
  855. return int(_unix_get_nprocs())
  856. }
  857. _alloc_command_line_arguments :: proc() -> []string {
  858. res := make([]string, len(runtime.args__))
  859. for arg, i in runtime.args__ {
  860. res[i] = string(arg)
  861. }
  862. return res
  863. }
  864. socket :: proc(domain: int, type: int, protocol: int) -> (Socket, Errno) {
  865. result := unix.sys_socket(domain, type, protocol)
  866. if result < 0 {
  867. return 0, _get_errno(result)
  868. }
  869. return Socket(result), ERROR_NONE
  870. }
  871. bind :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> (Errno) {
  872. result := unix.sys_bind(int(sd), addr, len)
  873. if result < 0 {
  874. return _get_errno(result)
  875. }
  876. return ERROR_NONE
  877. }
  878. connect :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> (Errno) {
  879. result := unix.sys_connect(int(sd), addr, len)
  880. if result < 0 {
  881. return _get_errno(result)
  882. }
  883. return ERROR_NONE
  884. }
  885. accept :: proc(sd: Socket, addr: ^SOCKADDR, len: rawptr) -> (Socket, Errno) {
  886. result := unix.sys_accept(int(sd), rawptr(addr), len)
  887. if result < 0 {
  888. return 0, _get_errno(result)
  889. }
  890. return Socket(result), ERROR_NONE
  891. }
  892. listen :: proc(sd: Socket, backlog: int) -> (Errno) {
  893. result := unix.sys_listen(int(sd), backlog)
  894. if result < 0 {
  895. return _get_errno(result)
  896. }
  897. return ERROR_NONE
  898. }
  899. setsockopt :: proc(sd: Socket, level: int, optname: int, optval: rawptr, optlen: socklen_t) -> (Errno) {
  900. result := unix.sys_setsockopt(int(sd), level, optname, optval, optlen)
  901. if result < 0 {
  902. return _get_errno(result)
  903. }
  904. return ERROR_NONE
  905. }
  906. recvfrom :: proc(sd: Socket, data: []byte, flags: int, addr: ^SOCKADDR, addr_size: ^socklen_t) -> (u32, Errno) {
  907. result := unix.sys_recvfrom(int(sd), raw_data(data), len(data), flags, addr, uintptr(addr_size))
  908. if result < 0 {
  909. return 0, _get_errno(int(result))
  910. }
  911. return u32(result), ERROR_NONE
  912. }
  913. recv :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Errno) {
  914. result := unix.sys_recvfrom(int(sd), raw_data(data), len(data), flags, nil, 0)
  915. if result < 0 {
  916. return 0, _get_errno(int(result))
  917. }
  918. return u32(result), ERROR_NONE
  919. }
  920. sendto :: proc(sd: Socket, data: []u8, flags: int, addr: ^SOCKADDR, addrlen: socklen_t) -> (u32, Errno) {
  921. result := unix.sys_sendto(int(sd), raw_data(data), len(data), flags, addr, addrlen)
  922. if result < 0 {
  923. return 0, _get_errno(int(result))
  924. }
  925. return u32(result), ERROR_NONE
  926. }
  927. send :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Errno) {
  928. result := unix.sys_sendto(int(sd), raw_data(data), len(data), 0, nil, 0)
  929. if result < 0 {
  930. return 0, _get_errno(int(result))
  931. }
  932. return u32(result), ERROR_NONE
  933. }
  934. shutdown :: proc(sd: Socket, how: int) -> (Errno) {
  935. result := unix.sys_shutdown(int(sd), how)
  936. if result < 0 {
  937. return _get_errno(result)
  938. }
  939. return ERROR_NONE
  940. }
  941. fcntl :: proc(fd: int, cmd: int, arg: int) -> (int, Errno) {
  942. result := unix.sys_fcntl(fd, cmd, arg)
  943. if result < 0 {
  944. return 0, _get_errno(result)
  945. }
  946. return result, ERROR_NONE
  947. }
  948. poll :: proc(fds: []pollfd, timeout: int) -> (int, Errno) {
  949. result := unix.sys_poll(raw_data(fds), uint(len(fds)), timeout)
  950. if result < 0 {
  951. return 0, _get_errno(result)
  952. }
  953. return result, ERROR_NONE
  954. }
  955. ppoll :: proc(fds: []pollfd, timeout: ^unix.timespec, sigmask: ^sigset_t) -> (int, Errno) {
  956. result := unix.sys_ppoll(raw_data(fds), uint(len(fds)), timeout, sigmask, size_of(sigset_t))
  957. if result < 0 {
  958. return 0, _get_errno(result)
  959. }
  960. return result, ERROR_NONE
  961. }