os_linux.odin 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. nanoseconds: 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. foreign libc {
  380. @(link_name="__errno_location") __errno_location :: proc() -> ^int ---
  381. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---
  382. @(link_name="get_nprocs") _unix_get_nprocs :: proc() -> c.int ---
  383. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---
  384. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  385. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  386. @(link_name="readdir_r") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  387. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---
  388. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---
  389. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  390. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
  391. @(link_name="execvp") _unix_execvp :: proc(path: cstring, argv: [^]cstring) -> int ---
  392. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  393. @(link_name="putenv") _unix_putenv :: proc(cstring) -> c.int ---
  394. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: rawptr) -> rawptr ---
  395. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  396. }
  397. foreign dl {
  398. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  399. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  400. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  401. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  402. @(link_name="getifaddrs") _getifaddrs :: proc(ifap: ^^ifaddrs) -> (c.int) ---
  403. @(link_name="freeifaddrs") _freeifaddrs :: proc(ifa: ^ifaddrs) ---
  404. }
  405. is_path_separator :: proc(r: rune) -> bool {
  406. return r == '/'
  407. }
  408. // determine errno from syscall return value
  409. @private
  410. _get_errno :: proc(res: int) -> Errno {
  411. if res < 0 && res > -4096 {
  412. return Errno(-res)
  413. }
  414. return 0
  415. }
  416. // get errno from libc
  417. get_last_error :: proc "contextless" () -> int {
  418. return __errno_location()^
  419. }
  420. personality :: proc(persona: u64) -> (Errno) {
  421. res := unix.sys_personality(persona)
  422. if res == -1 {
  423. return _get_errno(res)
  424. }
  425. return ERROR_NONE
  426. }
  427. fork :: proc() -> (Pid, Errno) {
  428. pid := unix.sys_fork()
  429. if pid == -1 {
  430. return -1, _get_errno(pid)
  431. }
  432. return Pid(pid), ERROR_NONE
  433. }
  434. execvp :: proc(path: string, args: []string) -> Errno {
  435. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  436. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  437. args_cstrs := make([]cstring, len(args) + 2, context.temp_allocator)
  438. args_cstrs[0] = strings.clone_to_cstring(path, context.temp_allocator)
  439. for i := 0; i < len(args); i += 1 {
  440. args_cstrs[i+1] = strings.clone_to_cstring(args[i], context.temp_allocator)
  441. }
  442. _unix_execvp(path_cstr, raw_data(args_cstrs))
  443. return Errno(get_last_error())
  444. }
  445. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0o000) -> (Handle, Errno) {
  446. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  447. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  448. handle := unix.sys_open(cstr, flags, uint(mode))
  449. if handle < 0 {
  450. return INVALID_HANDLE, _get_errno(handle)
  451. }
  452. return Handle(handle), ERROR_NONE
  453. }
  454. close :: proc(fd: Handle) -> Errno {
  455. return _get_errno(unix.sys_close(int(fd)))
  456. }
  457. read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  458. if len(data) == 0 {
  459. return 0, ERROR_NONE
  460. }
  461. bytes_read := unix.sys_read(int(fd), raw_data(data), len(data))
  462. if bytes_read < 0 {
  463. return -1, _get_errno(bytes_read)
  464. }
  465. return bytes_read, ERROR_NONE
  466. }
  467. write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  468. if len(data) == 0 {
  469. return 0, ERROR_NONE
  470. }
  471. bytes_written := unix.sys_write(int(fd), raw_data(data), len(data))
  472. if bytes_written < 0 {
  473. return -1, _get_errno(bytes_written)
  474. }
  475. return bytes_written, ERROR_NONE
  476. }
  477. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  478. if len(data) == 0 {
  479. return 0, ERROR_NONE
  480. }
  481. bytes_read := unix.sys_pread(int(fd), raw_data(data), len(data), offset)
  482. if bytes_read < 0 {
  483. return -1, _get_errno(bytes_read)
  484. }
  485. return bytes_read, ERROR_NONE
  486. }
  487. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  488. if len(data) == 0 {
  489. return 0, ERROR_NONE
  490. }
  491. bytes_written := unix.sys_pwrite(int(fd), raw_data(data), uint(len(data)), offset)
  492. if bytes_written < 0 {
  493. return -1, _get_errno(bytes_written)
  494. }
  495. return bytes_written, ERROR_NONE
  496. }
  497. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  498. res := unix.sys_lseek(int(fd), offset, whence)
  499. if res < 0 {
  500. return -1, _get_errno(int(res))
  501. }
  502. return i64(res), ERROR_NONE
  503. }
  504. file_size :: proc(fd: Handle) -> (i64, Errno) {
  505. // deliberately uninitialized; the syscall fills this buffer for us
  506. s: OS_Stat = ---
  507. result := unix.sys_fstat(int(fd), rawptr(&s))
  508. if result < 0 {
  509. return 0, _get_errno(result)
  510. }
  511. return max(s.size, 0), ERROR_NONE
  512. }
  513. rename :: proc(old_path, new_path: string) -> Errno {
  514. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  515. old_path_cstr := strings.clone_to_cstring(old_path, context.temp_allocator)
  516. new_path_cstr := strings.clone_to_cstring(new_path, context.temp_allocator)
  517. return _get_errno(unix.sys_rename(old_path_cstr, new_path_cstr))
  518. }
  519. remove :: proc(path: string) -> Errno {
  520. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  521. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  522. return _get_errno(unix.sys_unlink(path_cstr))
  523. }
  524. make_directory :: proc(path: string, mode: u32 = 0o775) -> Errno {
  525. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  526. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  527. return _get_errno(unix.sys_mkdir(path_cstr, uint(mode)))
  528. }
  529. remove_directory :: proc(path: string) -> Errno {
  530. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  531. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  532. return _get_errno(unix.sys_rmdir(path_cstr))
  533. }
  534. is_file_handle :: proc(fd: Handle) -> bool {
  535. s, err := _fstat(fd)
  536. if err != ERROR_NONE {
  537. return false
  538. }
  539. return S_ISREG(s.mode)
  540. }
  541. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  542. s: OS_Stat
  543. err: Errno
  544. if follow_links {
  545. s, err = _stat(path)
  546. } else {
  547. s, err = _lstat(path)
  548. }
  549. if err != ERROR_NONE {
  550. return false
  551. }
  552. return S_ISREG(s.mode)
  553. }
  554. is_dir_handle :: proc(fd: Handle) -> bool {
  555. s, err := _fstat(fd)
  556. if err != ERROR_NONE {
  557. return false
  558. }
  559. return S_ISDIR(s.mode)
  560. }
  561. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  562. s: OS_Stat
  563. err: Errno
  564. if follow_links {
  565. s, err = _stat(path)
  566. } else {
  567. s, err = _lstat(path)
  568. }
  569. if err != ERROR_NONE {
  570. return false
  571. }
  572. return S_ISDIR(s.mode)
  573. }
  574. is_file :: proc {is_file_path, is_file_handle}
  575. is_dir :: proc {is_dir_path, is_dir_handle}
  576. exists :: proc(path: string) -> bool {
  577. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  578. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  579. res := unix.sys_access(cpath, O_RDONLY)
  580. return res == 0
  581. }
  582. // NOTE(bill): Uses startup to initialize it
  583. stdin: Handle = 0
  584. stdout: Handle = 1
  585. stderr: Handle = 2
  586. /* TODO(zangent): Implement these!
  587. last_write_time :: proc(fd: Handle) -> File_Time {}
  588. last_write_time_by_name :: proc(name: string) -> File_Time {}
  589. */
  590. last_write_time :: proc(fd: Handle) -> (File_Time, Errno) {
  591. s, err := _fstat(fd)
  592. if err != ERROR_NONE {
  593. return 0, err
  594. }
  595. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  596. return File_Time(modified), ERROR_NONE
  597. }
  598. last_write_time_by_name :: proc(name: string) -> (File_Time, Errno) {
  599. s, err := _stat(name)
  600. if err != ERROR_NONE {
  601. return 0, err
  602. }
  603. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  604. return File_Time(modified), ERROR_NONE
  605. }
  606. @private
  607. _stat :: proc(path: string) -> (OS_Stat, Errno) {
  608. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  609. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  610. // deliberately uninitialized; the syscall fills this buffer for us
  611. s: OS_Stat = ---
  612. result := unix.sys_stat(cstr, &s)
  613. if result < 0 {
  614. return s, _get_errno(result)
  615. }
  616. return s, ERROR_NONE
  617. }
  618. @private
  619. _lstat :: proc(path: string) -> (OS_Stat, Errno) {
  620. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  621. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  622. // deliberately uninitialized; the syscall fills this buffer for us
  623. s: OS_Stat = ---
  624. result := unix.sys_lstat(cstr, &s)
  625. if result < 0 {
  626. return s, _get_errno(result)
  627. }
  628. return s, ERROR_NONE
  629. }
  630. @private
  631. _fstat :: proc(fd: Handle) -> (OS_Stat, Errno) {
  632. // deliberately uninitialized; the syscall fills this buffer for us
  633. s: OS_Stat = ---
  634. result := unix.sys_fstat(int(fd), rawptr(&s))
  635. if result < 0 {
  636. return s, _get_errno(result)
  637. }
  638. return s, ERROR_NONE
  639. }
  640. @private
  641. _fdopendir :: proc(fd: Handle) -> (Dir, Errno) {
  642. dirp := _unix_fdopendir(fd)
  643. if dirp == cast(Dir)nil {
  644. return nil, Errno(get_last_error())
  645. }
  646. return dirp, ERROR_NONE
  647. }
  648. @private
  649. _closedir :: proc(dirp: Dir) -> Errno {
  650. rc := _unix_closedir(dirp)
  651. if rc != 0 {
  652. return Errno(get_last_error())
  653. }
  654. return ERROR_NONE
  655. }
  656. @private
  657. _rewinddir :: proc(dirp: Dir) {
  658. _unix_rewinddir(dirp)
  659. }
  660. @private
  661. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Errno, end_of_stream: bool) {
  662. result: ^Dirent
  663. rc := _unix_readdir_r(dirp, &entry, &result)
  664. if rc != 0 {
  665. err = Errno(get_last_error())
  666. return
  667. }
  668. err = ERROR_NONE
  669. if result == nil {
  670. end_of_stream = true
  671. return
  672. }
  673. end_of_stream = false
  674. return
  675. }
  676. @private
  677. _readlink :: proc(path: string) -> (string, Errno) {
  678. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  679. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  680. bufsz : uint = 256
  681. buf := make([]byte, bufsz)
  682. for {
  683. rc := unix.sys_readlink(path_cstr, &(buf[0]), bufsz)
  684. if rc < 0 {
  685. delete(buf)
  686. return "", _get_errno(rc)
  687. } else if rc == int(bufsz) {
  688. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  689. bufsz *= 2
  690. delete(buf)
  691. buf = make([]byte, bufsz)
  692. } else {
  693. return strings.string_from_ptr(&buf[0], rc), ERROR_NONE
  694. }
  695. }
  696. }
  697. absolute_path_from_handle :: proc(fd: Handle) -> (string, Errno) {
  698. buf : [256]byte
  699. fd_str := strconv.itoa( buf[:], cast(int)fd )
  700. procfs_path := strings.concatenate( []string{ "/proc/self/fd/", fd_str } )
  701. defer delete(procfs_path)
  702. return _readlink(procfs_path)
  703. }
  704. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Errno) {
  705. rel := rel
  706. if rel == "" {
  707. rel = "."
  708. }
  709. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  710. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  711. path_ptr := _unix_realpath(rel_cstr, nil)
  712. if path_ptr == nil {
  713. return "", Errno(get_last_error())
  714. }
  715. defer _unix_free(path_ptr)
  716. path_cstr := transmute(cstring)path_ptr
  717. path = strings.clone( string(path_cstr) )
  718. return path, ERROR_NONE
  719. }
  720. access :: proc(path: string, mask: int) -> (bool, Errno) {
  721. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  722. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  723. result := unix.sys_access(cstr, mask)
  724. if result < 0 {
  725. return false, _get_errno(result)
  726. }
  727. return true, ERROR_NONE
  728. }
  729. heap_alloc :: proc(size: int, zero_memory := true) -> rawptr {
  730. if size <= 0 {
  731. return nil
  732. }
  733. if zero_memory {
  734. return _unix_calloc(1, c.size_t(size))
  735. } else {
  736. return _unix_malloc(c.size_t(size))
  737. }
  738. }
  739. heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
  740. // NOTE: _unix_realloc doesn't guarantee new memory will be zeroed on
  741. // POSIX platforms. Ensure your caller takes this into account.
  742. return _unix_realloc(ptr, c.size_t(new_size))
  743. }
  744. heap_free :: proc(ptr: rawptr) {
  745. _unix_free(ptr)
  746. }
  747. lookup_env :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  748. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
  749. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  750. // NOTE(tetra): Lifetime of 'cstr' is unclear, but _unix_free(cstr) segfaults.
  751. cstr := _unix_getenv(path_str)
  752. if cstr == nil {
  753. return "", false
  754. }
  755. return strings.clone(string(cstr), allocator), true
  756. }
  757. get_env :: proc(key: string, allocator := context.allocator) -> (value: string) {
  758. value, _ = lookup_env(key, allocator)
  759. return
  760. }
  761. set_env :: proc(key, value: string) -> Errno {
  762. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  763. s := strings.concatenate({key, "=", value, "\x00"}, context.temp_allocator)
  764. res := _unix_putenv(strings.unsafe_string_to_cstring(s))
  765. if res < 0 {
  766. return Errno(get_last_error())
  767. }
  768. return ERROR_NONE
  769. }
  770. unset_env :: proc(key: string) -> Errno {
  771. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  772. s := strings.clone_to_cstring(key, context.temp_allocator)
  773. res := _unix_putenv(s)
  774. if res < 0 {
  775. return Errno(get_last_error())
  776. }
  777. return ERROR_NONE
  778. }
  779. get_current_directory :: proc() -> string {
  780. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  781. // an authoritative value for it across all systems.
  782. // The largest value I could find was 4096, so might as well use the page size.
  783. page_size := get_page_size()
  784. buf := make([dynamic]u8, page_size)
  785. for {
  786. #no_bounds_check res := unix.sys_getcwd(&buf[0], uint(len(buf)))
  787. if res >= 0 {
  788. return strings.string_from_null_terminated_ptr(&buf[0], len(buf))
  789. }
  790. if _get_errno(res) != ERANGE {
  791. delete(buf)
  792. return ""
  793. }
  794. resize(&buf, len(buf)+page_size)
  795. }
  796. unreachable()
  797. }
  798. set_current_directory :: proc(path: string) -> (err: Errno) {
  799. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  800. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  801. res := unix.sys_chdir(cstr)
  802. if res < 0 {
  803. return _get_errno(res)
  804. }
  805. return ERROR_NONE
  806. }
  807. exit :: proc "contextless" (code: int) -> ! {
  808. runtime._cleanup_runtime_contextless()
  809. _unix_exit(c.int(code))
  810. }
  811. current_thread_id :: proc "contextless" () -> int {
  812. return unix.sys_gettid()
  813. }
  814. dlopen :: proc(filename: string, flags: int) -> rawptr {
  815. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  816. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  817. handle := _unix_dlopen(cstr, c.int(flags))
  818. return handle
  819. }
  820. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  821. assert(handle != nil)
  822. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  823. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  824. proc_handle := _unix_dlsym(handle, cstr)
  825. return proc_handle
  826. }
  827. dlclose :: proc(handle: rawptr) -> bool {
  828. assert(handle != nil)
  829. return _unix_dlclose(handle) == 0
  830. }
  831. dlerror :: proc() -> string {
  832. return string(_unix_dlerror())
  833. }
  834. get_page_size :: proc() -> int {
  835. // NOTE(tetra): The page size never changes, so why do anything complicated
  836. // if we don't have to.
  837. @static page_size := -1
  838. if page_size != -1 {
  839. return page_size
  840. }
  841. page_size = int(_unix_getpagesize())
  842. return page_size
  843. }
  844. @(private)
  845. _processor_core_count :: proc() -> int {
  846. return int(_unix_get_nprocs())
  847. }
  848. _alloc_command_line_arguments :: proc() -> []string {
  849. res := make([]string, len(runtime.args__))
  850. for arg, i in runtime.args__ {
  851. res[i] = string(arg)
  852. }
  853. return res
  854. }
  855. socket :: proc(domain: int, type: int, protocol: int) -> (Socket, Errno) {
  856. result := unix.sys_socket(domain, type, protocol)
  857. if result < 0 {
  858. return 0, _get_errno(result)
  859. }
  860. return Socket(result), ERROR_NONE
  861. }
  862. bind :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> (Errno) {
  863. result := unix.sys_bind(int(sd), addr, len)
  864. if result < 0 {
  865. return _get_errno(result)
  866. }
  867. return ERROR_NONE
  868. }
  869. connect :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> (Errno) {
  870. result := unix.sys_connect(int(sd), addr, len)
  871. if result < 0 {
  872. return _get_errno(result)
  873. }
  874. return ERROR_NONE
  875. }
  876. accept :: proc(sd: Socket, addr: ^SOCKADDR, len: rawptr) -> (Socket, Errno) {
  877. result := unix.sys_accept(int(sd), rawptr(addr), len)
  878. if result < 0 {
  879. return 0, _get_errno(result)
  880. }
  881. return Socket(result), ERROR_NONE
  882. }
  883. listen :: proc(sd: Socket, backlog: int) -> (Errno) {
  884. result := unix.sys_listen(int(sd), backlog)
  885. if result < 0 {
  886. return _get_errno(result)
  887. }
  888. return ERROR_NONE
  889. }
  890. setsockopt :: proc(sd: Socket, level: int, optname: int, optval: rawptr, optlen: socklen_t) -> (Errno) {
  891. result := unix.sys_setsockopt(int(sd), level, optname, optval, optlen)
  892. if result < 0 {
  893. return _get_errno(result)
  894. }
  895. return ERROR_NONE
  896. }
  897. recvfrom :: proc(sd: Socket, data: []byte, flags: int, addr: ^SOCKADDR, addr_size: ^socklen_t) -> (u32, Errno) {
  898. result := unix.sys_recvfrom(int(sd), raw_data(data), len(data), flags, addr, uintptr(addr_size))
  899. if result < 0 {
  900. return 0, _get_errno(int(result))
  901. }
  902. return u32(result), ERROR_NONE
  903. }
  904. recv :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Errno) {
  905. result := unix.sys_recvfrom(int(sd), raw_data(data), len(data), flags, nil, 0)
  906. if result < 0 {
  907. return 0, _get_errno(int(result))
  908. }
  909. return u32(result), ERROR_NONE
  910. }
  911. sendto :: proc(sd: Socket, data: []u8, flags: int, addr: ^SOCKADDR, addrlen: socklen_t) -> (u32, Errno) {
  912. result := unix.sys_sendto(int(sd), raw_data(data), len(data), flags, addr, addrlen)
  913. if result < 0 {
  914. return 0, _get_errno(int(result))
  915. }
  916. return u32(result), ERROR_NONE
  917. }
  918. send :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Errno) {
  919. result := unix.sys_sendto(int(sd), raw_data(data), len(data), 0, nil, 0)
  920. if result < 0 {
  921. return 0, _get_errno(int(result))
  922. }
  923. return u32(result), ERROR_NONE
  924. }
  925. shutdown :: proc(sd: Socket, how: int) -> (Errno) {
  926. result := unix.sys_shutdown(int(sd), how)
  927. if result < 0 {
  928. return _get_errno(result)
  929. }
  930. return ERROR_NONE
  931. }
  932. fcntl :: proc(fd: int, cmd: int, arg: int) -> (int, Errno) {
  933. result := unix.sys_fcntl(fd, cmd, arg)
  934. if result < 0 {
  935. return 0, _get_errno(result)
  936. }
  937. return result, ERROR_NONE
  938. }