os_linux.odin 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 :: 0x001
  217. RTLD_NOW :: 0x002
  218. RTLD_BINDING_MASK :: 0x3
  219. RTLD_GLOBAL :: 0x100
  220. socklen_t :: c.int
  221. Timeval :: struct {
  222. seconds: i64,
  223. microseconds: int,
  224. }
  225. // "Argv" arguments converted to Odin strings
  226. args := _alloc_command_line_arguments()
  227. Unix_File_Time :: struct {
  228. seconds: i64,
  229. nanoseconds: i64,
  230. }
  231. when ODIN_ARCH == .arm64 || ODIN_ARCH == .riscv64 {
  232. OS_Stat :: struct {
  233. device_id: u64, // ID of device containing file
  234. serial: u64, // File serial number
  235. mode: u32, // Mode of the file
  236. nlink: u32, // Number of hard links
  237. uid: u32, // User ID of the file's owner
  238. gid: u32, // Group ID of the file's group
  239. rdev: u64, // Device ID, if device
  240. _: u64, // Padding
  241. size: i64, // Size of the file, in bytes
  242. block_size: i32, // Optimal blocksize for I/O
  243. _: i32, // Padding
  244. blocks: i64, // Number of 512-byte blocks allocated
  245. last_access: Unix_File_Time, // Time of last access
  246. modified: Unix_File_Time, // Time of last modification
  247. status_change: Unix_File_Time, // Time of last status change
  248. _reserved: [2]i32,
  249. }
  250. #assert(size_of(OS_Stat) == 128)
  251. } else {
  252. OS_Stat :: struct {
  253. device_id: u64, // ID of device containing file
  254. serial: u64, // File serial number
  255. nlink: u64, // Number of hard links
  256. mode: u32, // Mode of the file
  257. uid: u32, // User ID of the file's owner
  258. gid: u32, // Group ID of the file's group
  259. _: i32, // 32 bits of padding
  260. rdev: u64, // Device ID, if device
  261. size: i64, // Size of the file, in bytes
  262. block_size: i64, // Optimal bllocksize for I/O
  263. blocks: i64, // Number of 512-byte blocks allocated
  264. last_access: Unix_File_Time, // Time of last access
  265. modified: Unix_File_Time, // Time of last modification
  266. status_change: Unix_File_Time, // Time of last status change
  267. _reserved: [3]i64,
  268. }
  269. }
  270. // NOTE(laleksic, 2021-01-21): Comment and rename these to match OS_Stat above
  271. Dirent :: struct {
  272. ino: u64,
  273. off: u64,
  274. reclen: u16,
  275. type: u8,
  276. name: [256]byte,
  277. }
  278. ADDRESS_FAMILY :: u16
  279. SOCKADDR :: struct #packed {
  280. sa_family: ADDRESS_FAMILY,
  281. sa_data: [14]c.char,
  282. }
  283. SOCKADDR_STORAGE_LH :: struct #packed {
  284. ss_family: ADDRESS_FAMILY,
  285. __ss_pad1: [6]c.char,
  286. __ss_align: i64,
  287. __ss_pad2: [112]c.char,
  288. }
  289. sockaddr_in :: struct #packed {
  290. sin_family: ADDRESS_FAMILY,
  291. sin_port: u16be,
  292. sin_addr: in_addr,
  293. sin_zero: [8]c.char,
  294. }
  295. sockaddr_in6 :: struct #packed {
  296. sin6_family: ADDRESS_FAMILY,
  297. sin6_port: u16be,
  298. sin6_flowinfo: c.ulong,
  299. sin6_addr: in6_addr,
  300. sin6_scope_id: c.ulong,
  301. }
  302. in_addr :: struct #packed {
  303. s_addr: u32,
  304. }
  305. in6_addr :: struct #packed {
  306. s6_addr: [16]u8,
  307. }
  308. rtnl_link_stats :: struct #packed {
  309. rx_packets: u32,
  310. tx_packets: u32,
  311. rx_bytes: u32,
  312. tx_bytes: u32,
  313. rx_errors: u32,
  314. tx_errors: u32,
  315. rx_dropped: u32,
  316. tx_dropped: u32,
  317. multicast: u32,
  318. collisions: u32,
  319. rx_length_errors: u32,
  320. rx_over_errors: u32,
  321. rx_crc_errors: u32,
  322. rx_frame_errors: u32,
  323. rx_fifo_errors: u32,
  324. rx_missed_errors: u32,
  325. tx_aborted_errors: u32,
  326. tx_carrier_errors: u32,
  327. tx_fifo_errors: u32,
  328. tx_heartbeat_errors: u32,
  329. tx_window_errors: u32,
  330. rx_compressed: u32,
  331. tx_compressed: u32,
  332. rx_nohandler: u32,
  333. }
  334. SIOCGIFFLAG :: enum c.int {
  335. UP = 0, /* Interface is up. */
  336. BROADCAST = 1, /* Broadcast address valid. */
  337. DEBUG = 2, /* Turn on debugging. */
  338. LOOPBACK = 3, /* Is a loopback net. */
  339. POINT_TO_POINT = 4, /* Interface is point-to-point link. */
  340. NO_TRAILERS = 5, /* Avoid use of trailers. */
  341. RUNNING = 6, /* Resources allocated. */
  342. NOARP = 7, /* No address resolution protocol. */
  343. PROMISC = 8, /* Receive all packets. */
  344. ALL_MULTI = 9, /* Receive all multicast packets. Unimplemented. */
  345. MASTER = 10, /* Master of a load balancer. */
  346. SLAVE = 11, /* Slave of a load balancer. */
  347. MULTICAST = 12, /* Supports multicast. */
  348. PORTSEL = 13, /* Can set media type. */
  349. AUTOMEDIA = 14, /* Auto media select active. */
  350. DYNAMIC = 15, /* Dialup device with changing addresses. */
  351. LOWER_UP = 16,
  352. DORMANT = 17,
  353. ECHO = 18,
  354. }
  355. SIOCGIFFLAGS :: bit_set[SIOCGIFFLAG; c.int]
  356. ifaddrs :: struct {
  357. next: ^ifaddrs,
  358. name: cstring,
  359. flags: SIOCGIFFLAGS,
  360. address: ^SOCKADDR,
  361. netmask: ^SOCKADDR,
  362. broadcast_or_dest: ^SOCKADDR, // Broadcast or Point-to-Point address
  363. data: rawptr, // Address-specific data.
  364. }
  365. Dir :: distinct rawptr // DIR*
  366. // File type
  367. S_IFMT :: 0o170000 // Type of file mask
  368. S_IFIFO :: 0o010000 // Named pipe (fifo)
  369. S_IFCHR :: 0o020000 // Character special
  370. S_IFDIR :: 0o040000 // Directory
  371. S_IFBLK :: 0o060000 // Block special
  372. S_IFREG :: 0o100000 // Regular
  373. S_IFLNK :: 0o120000 // Symbolic link
  374. S_IFSOCK :: 0o140000 // Socket
  375. // File mode
  376. // Read, write, execute/search by owner
  377. S_IRWXU :: 0o0700 // RWX mask for owner
  378. S_IRUSR :: 0o0400 // R for owner
  379. S_IWUSR :: 0o0200 // W for owner
  380. S_IXUSR :: 0o0100 // X for owner
  381. // Read, write, execute/search by group
  382. S_IRWXG :: 0o0070 // RWX mask for group
  383. S_IRGRP :: 0o0040 // R for group
  384. S_IWGRP :: 0o0020 // W for group
  385. S_IXGRP :: 0o0010 // X for group
  386. // Read, write, execute/search by others
  387. S_IRWXO :: 0o0007 // RWX mask for other
  388. S_IROTH :: 0o0004 // R for other
  389. S_IWOTH :: 0o0002 // W for other
  390. S_IXOTH :: 0o0001 // X for other
  391. S_ISUID :: 0o4000 // Set user id on execution
  392. S_ISGID :: 0o2000 // Set group id on execution
  393. S_ISVTX :: 0o1000 // Directory restrcted delete
  394. @(require_results) S_ISLNK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFLNK }
  395. @(require_results) S_ISREG :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFREG }
  396. @(require_results) S_ISDIR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFDIR }
  397. @(require_results) S_ISCHR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFCHR }
  398. @(require_results) S_ISBLK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFBLK }
  399. @(require_results) S_ISFIFO :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFIFO }
  400. @(require_results) S_ISSOCK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFSOCK }
  401. F_OK :: 0 // Test for file existance
  402. X_OK :: 1 // Test for execute permission
  403. W_OK :: 2 // Test for write permission
  404. R_OK :: 4 // Test for read permission
  405. AT_FDCWD :: ~uintptr(99) /* -100 */
  406. AT_REMOVEDIR :: uintptr(0x200)
  407. AT_SYMLINK_NOFOLLOW :: uintptr(0x100)
  408. pollfd :: struct {
  409. fd: c.int,
  410. events: c.short,
  411. revents: c.short,
  412. }
  413. sigset_t :: distinct u64
  414. foreign libc {
  415. @(link_name="__errno_location") __errno_location :: proc() -> ^c.int ---
  416. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---
  417. @(link_name="get_nprocs") _unix_get_nprocs :: proc() -> c.int ---
  418. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---
  419. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  420. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  421. @(link_name="readdir_r") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  422. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---
  423. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---
  424. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  425. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
  426. @(link_name="execvp") _unix_execvp :: proc(path: cstring, argv: [^]cstring) -> int ---
  427. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  428. @(link_name="putenv") _unix_putenv :: proc(cstring) -> c.int ---
  429. @(link_name="setenv") _unix_setenv :: proc(key: cstring, value: cstring, overwrite: c.int) -> c.int ---
  430. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: [^]byte = nil) -> cstring ---
  431. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  432. }
  433. foreign dl {
  434. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  435. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  436. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  437. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  438. @(link_name="getifaddrs") _getifaddrs :: proc(ifap: ^^ifaddrs) -> (c.int) ---
  439. @(link_name="freeifaddrs") _freeifaddrs :: proc(ifa: ^ifaddrs) ---
  440. }
  441. @(require_results)
  442. is_path_separator :: proc(r: rune) -> bool {
  443. return r == '/'
  444. }
  445. // determine errno from syscall return value
  446. @(private, require_results)
  447. _get_errno :: proc(res: int) -> Error {
  448. if res < 0 && res > -4096 {
  449. return Platform_Error(-res)
  450. }
  451. return nil
  452. }
  453. // get errno from libc
  454. @(require_results, no_instrumentation)
  455. get_last_error :: proc "contextless" () -> Error {
  456. err := Platform_Error(__errno_location()^)
  457. #partial switch err {
  458. case .NONE:
  459. return nil
  460. case .EPERM:
  461. return .Permission_Denied
  462. case .EEXIST:
  463. return .Exist
  464. case .ENOENT:
  465. return .Not_Exist
  466. }
  467. return err
  468. }
  469. personality :: proc(persona: u64) -> Error {
  470. res := unix.sys_personality(persona)
  471. if res == -1 {
  472. return _get_errno(res)
  473. }
  474. return nil
  475. }
  476. @(require_results)
  477. fork :: proc() -> (Pid, Error) {
  478. pid := unix.sys_fork()
  479. if pid == -1 {
  480. return -1, _get_errno(pid)
  481. }
  482. return Pid(pid), nil
  483. }
  484. execvp :: proc(path: string, args: []string) -> Error {
  485. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  486. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  487. args_cstrs := make([]cstring, len(args) + 2, context.temp_allocator)
  488. args_cstrs[0] = strings.clone_to_cstring(path, context.temp_allocator)
  489. for i := 0; i < len(args); i += 1 {
  490. args_cstrs[i+1] = strings.clone_to_cstring(args[i], context.temp_allocator)
  491. }
  492. _unix_execvp(path_cstr, raw_data(args_cstrs))
  493. return get_last_error()
  494. }
  495. @(require_results)
  496. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0o000) -> (Handle, Error) {
  497. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  498. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  499. handle := unix.sys_open(cstr, flags, uint(mode))
  500. if handle < 0 {
  501. return INVALID_HANDLE, _get_errno(handle)
  502. }
  503. return Handle(handle), nil
  504. }
  505. close :: proc(fd: Handle) -> Error {
  506. return _get_errno(unix.sys_close(int(fd)))
  507. }
  508. flush :: proc(fd: Handle) -> Error {
  509. return _get_errno(unix.sys_fsync(int(fd)))
  510. }
  511. // If you read or write more than `SSIZE_MAX` bytes, result is implementation defined (probably an error).
  512. // `SSIZE_MAX` is also implementation defined but usually the max of a `ssize_t` which is `max(int)` in Odin.
  513. // In practice a read/write call would probably never read/write these big buffers all at once,
  514. // which is why the number of bytes is returned and why there are procs that will call this in a
  515. // loop for you.
  516. // We set a max of 1GB to keep alignment and to be safe.
  517. @(private)
  518. MAX_RW :: 1 << 30
  519. read :: proc(fd: Handle, data: []byte) -> (int, Error) {
  520. if len(data) == 0 {
  521. return 0, nil
  522. }
  523. to_read := min(uint(len(data)), MAX_RW)
  524. bytes_read := unix.sys_read(int(fd), raw_data(data), to_read)
  525. if bytes_read < 0 {
  526. return -1, _get_errno(bytes_read)
  527. }
  528. return bytes_read, nil
  529. }
  530. write :: proc(fd: Handle, data: []byte) -> (int, Error) {
  531. if len(data) == 0 {
  532. return 0, nil
  533. }
  534. to_write := min(uint(len(data)), MAX_RW)
  535. bytes_written := unix.sys_write(int(fd), raw_data(data), to_write)
  536. if bytes_written < 0 {
  537. return -1, _get_errno(bytes_written)
  538. }
  539. return bytes_written, nil
  540. }
  541. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Error) {
  542. if len(data) == 0 {
  543. return 0, nil
  544. }
  545. to_read := min(uint(len(data)), MAX_RW)
  546. bytes_read := unix.sys_pread(int(fd), raw_data(data), to_read, offset)
  547. if bytes_read < 0 {
  548. return -1, _get_errno(bytes_read)
  549. }
  550. return bytes_read, nil
  551. }
  552. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Error) {
  553. if len(data) == 0 {
  554. return 0, nil
  555. }
  556. to_write := min(uint(len(data)), MAX_RW)
  557. bytes_written := unix.sys_pwrite(int(fd), raw_data(data), to_write, offset)
  558. if bytes_written < 0 {
  559. return -1, _get_errno(bytes_written)
  560. }
  561. return bytes_written, nil
  562. }
  563. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Error) {
  564. switch whence {
  565. case SEEK_SET, SEEK_CUR, SEEK_END:
  566. break
  567. case:
  568. return 0, .Invalid_Whence
  569. }
  570. res := unix.sys_lseek(int(fd), offset, whence)
  571. if res < 0 {
  572. errno := _get_errno(int(res))
  573. switch errno {
  574. case .EINVAL:
  575. return 0, .Invalid_Offset
  576. }
  577. return 0, errno
  578. }
  579. return i64(res), nil
  580. }
  581. @(require_results)
  582. file_size :: proc(fd: Handle) -> (i64, Error) {
  583. // deliberately uninitialized; the syscall fills this buffer for us
  584. s: OS_Stat = ---
  585. result := unix.sys_fstat(int(fd), rawptr(&s))
  586. if result < 0 {
  587. return 0, _get_errno(result)
  588. }
  589. return max(s.size, 0), nil
  590. }
  591. rename :: proc(old_path, new_path: string) -> Error {
  592. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  593. old_path_cstr := strings.clone_to_cstring(old_path, context.temp_allocator)
  594. new_path_cstr := strings.clone_to_cstring(new_path, context.temp_allocator)
  595. return _get_errno(unix.sys_rename(old_path_cstr, new_path_cstr))
  596. }
  597. remove :: proc(path: string) -> Error {
  598. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  599. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  600. return _get_errno(unix.sys_unlink(path_cstr))
  601. }
  602. make_directory :: proc(path: string, mode: u32 = 0o775) -> Error {
  603. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  604. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  605. return _get_errno(unix.sys_mkdir(path_cstr, uint(mode)))
  606. }
  607. remove_directory :: proc(path: string) -> Error {
  608. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  609. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  610. return _get_errno(unix.sys_rmdir(path_cstr))
  611. }
  612. @(require_results)
  613. is_file_handle :: proc(fd: Handle) -> bool {
  614. s, err := _fstat(fd)
  615. if err != nil {
  616. return false
  617. }
  618. return S_ISREG(s.mode)
  619. }
  620. @(require_results)
  621. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  622. s: OS_Stat
  623. err: Error
  624. if follow_links {
  625. s, err = _stat(path)
  626. } else {
  627. s, err = _lstat(path)
  628. }
  629. if err != nil {
  630. return false
  631. }
  632. return S_ISREG(s.mode)
  633. }
  634. @(require_results)
  635. is_dir_handle :: proc(fd: Handle) -> bool {
  636. s, err := _fstat(fd)
  637. if err != nil {
  638. return false
  639. }
  640. return S_ISDIR(s.mode)
  641. }
  642. @(require_results)
  643. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  644. s: OS_Stat
  645. err: Error
  646. if follow_links {
  647. s, err = _stat(path)
  648. } else {
  649. s, err = _lstat(path)
  650. }
  651. if err != nil {
  652. return false
  653. }
  654. return S_ISDIR(s.mode)
  655. }
  656. is_file :: proc {is_file_path, is_file_handle}
  657. is_dir :: proc {is_dir_path, is_dir_handle}
  658. @(require_results)
  659. exists :: proc(path: string) -> bool {
  660. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  661. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  662. res := unix.sys_access(cpath, O_RDONLY)
  663. return res == 0
  664. }
  665. // NOTE(bill): Uses startup to initialize it
  666. stdin: Handle = 0
  667. stdout: Handle = 1
  668. stderr: Handle = 2
  669. /* TODO(zangent): Implement these!
  670. last_write_time :: proc(fd: Handle) -> File_Time {}
  671. last_write_time_by_name :: proc(name: string) -> File_Time {}
  672. */
  673. @(require_results)
  674. last_write_time :: proc(fd: Handle) -> (time: File_Time, err: Error) {
  675. s := _fstat(fd) or_return
  676. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  677. return File_Time(modified), nil
  678. }
  679. @(require_results)
  680. last_write_time_by_name :: proc(name: string) -> (time: File_Time, err: Error) {
  681. s := _stat(name) or_return
  682. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  683. return File_Time(modified), nil
  684. }
  685. @(private, require_results)
  686. _stat :: proc(path: string) -> (OS_Stat, Error) {
  687. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  688. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  689. // deliberately uninitialized; the syscall fills this buffer for us
  690. s: OS_Stat = ---
  691. result := unix.sys_stat(cstr, &s)
  692. if result < 0 {
  693. return s, _get_errno(result)
  694. }
  695. return s, nil
  696. }
  697. @(private, require_results)
  698. _lstat :: proc(path: string) -> (OS_Stat, Error) {
  699. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  700. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  701. // deliberately uninitialized; the syscall fills this buffer for us
  702. s: OS_Stat = ---
  703. result := unix.sys_lstat(cstr, &s)
  704. if result < 0 {
  705. return s, _get_errno(result)
  706. }
  707. return s, nil
  708. }
  709. @(private, require_results)
  710. _fstat :: proc(fd: Handle) -> (OS_Stat, Error) {
  711. // deliberately uninitialized; the syscall fills this buffer for us
  712. s: OS_Stat = ---
  713. result := unix.sys_fstat(int(fd), rawptr(&s))
  714. if result < 0 {
  715. return s, _get_errno(result)
  716. }
  717. return s, nil
  718. }
  719. @(private, require_results)
  720. _fdopendir :: proc(fd: Handle) -> (Dir, Error) {
  721. dirp := _unix_fdopendir(fd)
  722. if dirp == cast(Dir)nil {
  723. return nil, get_last_error()
  724. }
  725. return dirp, nil
  726. }
  727. @(private)
  728. _closedir :: proc(dirp: Dir) -> Error {
  729. rc := _unix_closedir(dirp)
  730. if rc != 0 {
  731. return get_last_error()
  732. }
  733. return nil
  734. }
  735. @(private)
  736. _rewinddir :: proc(dirp: Dir) {
  737. _unix_rewinddir(dirp)
  738. }
  739. @(private, require_results)
  740. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Error, end_of_stream: bool) {
  741. result: ^Dirent
  742. rc := _unix_readdir_r(dirp, &entry, &result)
  743. if rc != 0 {
  744. err = get_last_error()
  745. return
  746. }
  747. err = nil
  748. if result == nil {
  749. end_of_stream = true
  750. return
  751. }
  752. end_of_stream = false
  753. return
  754. }
  755. @(private, require_results)
  756. _readlink :: proc(path: string) -> (string, Error) {
  757. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  758. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  759. bufsz : uint = 256
  760. buf := make([]byte, bufsz)
  761. for {
  762. rc := unix.sys_readlink(path_cstr, &(buf[0]), bufsz)
  763. if rc < 0 {
  764. delete(buf)
  765. return "", _get_errno(rc)
  766. } else if rc == int(bufsz) {
  767. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  768. bufsz *= 2
  769. delete(buf)
  770. buf = make([]byte, bufsz)
  771. } else {
  772. return strings.string_from_ptr(&buf[0], rc), nil
  773. }
  774. }
  775. }
  776. @(private, require_results)
  777. _dup :: proc(fd: Handle) -> (Handle, Error) {
  778. dup, err := linux.dup(linux.Fd(fd))
  779. return Handle(dup), err
  780. }
  781. @(require_results)
  782. absolute_path_from_handle :: proc(fd: Handle) -> (string, Error) {
  783. buf : [256]byte
  784. fd_str := strconv.itoa( buf[:], cast(int)fd )
  785. procfs_path := strings.concatenate( []string{ "/proc/self/fd/", fd_str } )
  786. defer delete(procfs_path)
  787. return _readlink(procfs_path)
  788. }
  789. @(require_results)
  790. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Error) {
  791. rel := rel
  792. if rel == "" {
  793. rel = "."
  794. }
  795. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  796. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  797. path_ptr := _unix_realpath(rel_cstr, nil)
  798. if path_ptr == nil {
  799. return "", get_last_error()
  800. }
  801. defer _unix_free(rawptr(path_ptr))
  802. path = strings.clone(string(path_ptr))
  803. return path, nil
  804. }
  805. access :: proc(path: string, mask: int) -> (bool, Error) {
  806. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  807. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  808. result := unix.sys_access(cstr, mask)
  809. if result < 0 {
  810. return false, _get_errno(result)
  811. }
  812. return true, nil
  813. }
  814. @(require_results)
  815. lookup_env :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  816. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
  817. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  818. // NOTE(tetra): Lifetime of 'cstr' is unclear, but _unix_free(cstr) segfaults.
  819. cstr := _unix_getenv(path_str)
  820. if cstr == nil {
  821. return "", false
  822. }
  823. return strings.clone(string(cstr), allocator), true
  824. }
  825. @(require_results)
  826. get_env :: proc(key: string, allocator := context.allocator) -> (value: string) {
  827. value, _ = lookup_env(key, allocator)
  828. return
  829. }
  830. set_env :: proc(key, value: string) -> Error {
  831. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  832. key_cstring := strings.clone_to_cstring(key, context.temp_allocator)
  833. value_cstring := strings.clone_to_cstring(value, context.temp_allocator)
  834. // NOTE(GoNZooo): `setenv` instead of `putenv` because it copies both key and value more commonly
  835. res := _unix_setenv(key_cstring, value_cstring, 1)
  836. if res < 0 {
  837. return get_last_error()
  838. }
  839. return nil
  840. }
  841. unset_env :: proc(key: string) -> Error {
  842. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  843. s := strings.clone_to_cstring(key, context.temp_allocator)
  844. res := _unix_putenv(s)
  845. if res < 0 {
  846. return get_last_error()
  847. }
  848. return nil
  849. }
  850. @(require_results)
  851. get_current_directory :: proc(allocator := context.allocator) -> string {
  852. context.allocator = allocator
  853. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  854. // an authoritative value for it across all systems.
  855. // The largest value I could find was 4096, so might as well use the page size.
  856. page_size := get_page_size()
  857. buf := make([dynamic]u8, page_size)
  858. for {
  859. #no_bounds_check res := unix.sys_getcwd(&buf[0], uint(len(buf)))
  860. if res >= 0 {
  861. return strings.string_from_null_terminated_ptr(&buf[0], len(buf))
  862. }
  863. if _get_errno(res) != ERANGE {
  864. delete(buf)
  865. return ""
  866. }
  867. resize(&buf, len(buf)+page_size)
  868. }
  869. unreachable()
  870. }
  871. set_current_directory :: proc(path: string) -> (err: Error) {
  872. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  873. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  874. res := unix.sys_chdir(cstr)
  875. if res < 0 {
  876. return _get_errno(res)
  877. }
  878. return nil
  879. }
  880. exit :: proc "contextless" (code: int) -> ! {
  881. runtime._cleanup_runtime_contextless()
  882. _unix_exit(c.int(code))
  883. }
  884. @(require_results)
  885. current_thread_id :: proc "contextless" () -> int {
  886. return unix.sys_gettid()
  887. }
  888. @(require_results)
  889. dlopen :: proc(filename: string, flags: int) -> rawptr {
  890. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  891. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  892. handle := _unix_dlopen(cstr, c.int(flags))
  893. return handle
  894. }
  895. @(require_results)
  896. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  897. assert(handle != nil)
  898. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  899. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  900. proc_handle := _unix_dlsym(handle, cstr)
  901. return proc_handle
  902. }
  903. dlclose :: proc(handle: rawptr) -> bool {
  904. assert(handle != nil)
  905. return _unix_dlclose(handle) == 0
  906. }
  907. dlerror :: proc() -> string {
  908. return string(_unix_dlerror())
  909. }
  910. @(require_results)
  911. get_page_size :: proc() -> int {
  912. // NOTE(tetra): The page size never changes, so why do anything complicated
  913. // if we don't have to.
  914. @static page_size := -1
  915. if page_size != -1 {
  916. return page_size
  917. }
  918. page_size = int(_unix_getpagesize())
  919. return page_size
  920. }
  921. @(private, require_results)
  922. _processor_core_count :: proc() -> int {
  923. return int(_unix_get_nprocs())
  924. }
  925. @(require_results)
  926. _alloc_command_line_arguments :: proc() -> []string {
  927. res := make([]string, len(runtime.args__))
  928. for arg, i in runtime.args__ {
  929. res[i] = string(arg)
  930. }
  931. return res
  932. }
  933. @(require_results)
  934. socket :: proc(domain: int, type: int, protocol: int) -> (Socket, Error) {
  935. result := unix.sys_socket(domain, type, protocol)
  936. if result < 0 {
  937. return 0, _get_errno(result)
  938. }
  939. return Socket(result), nil
  940. }
  941. bind :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> Error {
  942. result := unix.sys_bind(int(sd), addr, len)
  943. if result < 0 {
  944. return _get_errno(result)
  945. }
  946. return nil
  947. }
  948. connect :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> Error {
  949. result := unix.sys_connect(int(sd), addr, len)
  950. if result < 0 {
  951. return _get_errno(result)
  952. }
  953. return nil
  954. }
  955. accept :: proc(sd: Socket, addr: ^SOCKADDR, len: rawptr) -> (Socket, Error) {
  956. result := unix.sys_accept(int(sd), rawptr(addr), len)
  957. if result < 0 {
  958. return 0, _get_errno(result)
  959. }
  960. return Socket(result), nil
  961. }
  962. listen :: proc(sd: Socket, backlog: int) -> Error {
  963. result := unix.sys_listen(int(sd), backlog)
  964. if result < 0 {
  965. return _get_errno(result)
  966. }
  967. return nil
  968. }
  969. setsockopt :: proc(sd: Socket, level: int, optname: int, optval: rawptr, optlen: socklen_t) -> Error {
  970. result := unix.sys_setsockopt(int(sd), level, optname, optval, optlen)
  971. if result < 0 {
  972. return _get_errno(result)
  973. }
  974. return nil
  975. }
  976. recvfrom :: proc(sd: Socket, data: []byte, flags: int, addr: ^SOCKADDR, addr_size: ^socklen_t) -> (u32, Error) {
  977. result := unix.sys_recvfrom(int(sd), raw_data(data), len(data), flags, addr, uintptr(addr_size))
  978. if result < 0 {
  979. return 0, _get_errno(int(result))
  980. }
  981. return u32(result), nil
  982. }
  983. recv :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Error) {
  984. result := unix.sys_recvfrom(int(sd), raw_data(data), len(data), flags, nil, 0)
  985. if result < 0 {
  986. return 0, _get_errno(int(result))
  987. }
  988. return u32(result), nil
  989. }
  990. sendto :: proc(sd: Socket, data: []u8, flags: int, addr: ^SOCKADDR, addrlen: socklen_t) -> (u32, Error) {
  991. result := unix.sys_sendto(int(sd), raw_data(data), len(data), flags, addr, addrlen)
  992. if result < 0 {
  993. return 0, _get_errno(int(result))
  994. }
  995. return u32(result), nil
  996. }
  997. send :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Error) {
  998. result := unix.sys_sendto(int(sd), raw_data(data), len(data), 0, nil, 0)
  999. if result < 0 {
  1000. return 0, _get_errno(int(result))
  1001. }
  1002. return u32(result), nil
  1003. }
  1004. shutdown :: proc(sd: Socket, how: int) -> Error {
  1005. result := unix.sys_shutdown(int(sd), how)
  1006. if result < 0 {
  1007. return _get_errno(result)
  1008. }
  1009. return nil
  1010. }
  1011. fcntl :: proc(fd: int, cmd: int, arg: int) -> (int, Error) {
  1012. result := unix.sys_fcntl(fd, cmd, arg)
  1013. if result < 0 {
  1014. return 0, _get_errno(result)
  1015. }
  1016. return result, nil
  1017. }
  1018. @(require_results)
  1019. poll :: proc(fds: []pollfd, timeout: int) -> (int, Error) {
  1020. result := unix.sys_poll(raw_data(fds), uint(len(fds)), timeout)
  1021. if result < 0 {
  1022. return 0, _get_errno(result)
  1023. }
  1024. return result, nil
  1025. }
  1026. @(require_results)
  1027. ppoll :: proc(fds: []pollfd, timeout: ^unix.timespec, sigmask: ^sigset_t) -> (int, Error) {
  1028. result := unix.sys_ppoll(raw_data(fds), uint(len(fds)), timeout, sigmask, size_of(sigset_t))
  1029. if result < 0 {
  1030. return 0, _get_errno(result)
  1031. }
  1032. return result, nil
  1033. }