os_linux.odin 39 KB

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