os_darwin.odin 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. package os
  2. foreign import dl "system:dl"
  3. foreign import libc "system:System"
  4. foreign import pthread "system:System"
  5. import "base:runtime"
  6. import "core:strings"
  7. import "core:c"
  8. Handle :: distinct i32
  9. File_Time :: distinct u64
  10. INVALID_HANDLE :: ~Handle(0)
  11. _Platform_Error :: enum i32 {
  12. NONE = 0,
  13. EPERM = 1, /* Operation not permitted */
  14. ENOENT = 2, /* No such file or directory */
  15. ESRCH = 3, /* No such process */
  16. EINTR = 4, /* Interrupted system call */
  17. EIO = 5, /* Input/output error */
  18. ENXIO = 6, /* Device not configured */
  19. E2BIG = 7, /* Argument list too long */
  20. ENOEXEC = 8, /* Exec format error */
  21. EBADF = 9, /* Bad file descriptor */
  22. ECHILD = 10, /* No child processes */
  23. EDEADLK = 11, /* Resource deadlock avoided */
  24. ENOMEM = 12, /* Cannot allocate memory */
  25. EACCES = 13, /* Permission denied */
  26. EFAULT = 14, /* Bad address */
  27. ENOTBLK = 15, /* Block device required */
  28. EBUSY = 16, /* Device / Resource busy */
  29. EEXIST = 17, /* File exists */
  30. EXDEV = 18, /* Cross-device link */
  31. ENODEV = 19, /* Operation not supported by device */
  32. ENOTDIR = 20, /* Not a directory */
  33. EISDIR = 21, /* Is a directory */
  34. EINVAL = 22, /* Invalid argument */
  35. ENFILE = 23, /* Too many open files in system */
  36. EMFILE = 24, /* Too many open files */
  37. ENOTTY = 25, /* Inappropriate ioctl for device */
  38. ETXTBSY = 26, /* Text file busy */
  39. EFBIG = 27, /* File too large */
  40. ENOSPC = 28, /* No space left on device */
  41. ESPIPE = 29, /* Illegal seek */
  42. EROFS = 30, /* Read-only file system */
  43. EMLINK = 31, /* Too many links */
  44. EPIPE = 32, /* Broken pipe */
  45. /* math software */
  46. EDOM = 33, /* Numerical argument out of domain */
  47. ERANGE = 34, /* Result too large */
  48. /* non-blocking and interrupt i/o */
  49. EAGAIN = 35, /* Resource temporarily unavailable */
  50. EWOULDBLOCK = EAGAIN, /* Operation would block */
  51. EINPROGRESS = 36, /* Operation now in progress */
  52. EALREADY = 37, /* Operation already in progress */
  53. /* ipc/network software -- argument errors */
  54. ENOTSOCK = 38, /* Socket operation on non-socket */
  55. EDESTADDRREQ = 39, /* Destination address required */
  56. EMSGSIZE = 40, /* Message too long */
  57. EPROTOTYPE = 41, /* Protocol wrong type for socket */
  58. ENOPROTOOPT = 42, /* Protocol not available */
  59. EPROTONOSUPPORT = 43, /* Protocol not supported */
  60. ESOCKTNOSUPPORT = 44, /* Socket type not supported */
  61. ENOTSUP = 45, /* Operation not supported */
  62. EOPNOTSUPP = ENOTSUP,
  63. EPFNOSUPPORT = 46, /* Protocol family not supported */
  64. EAFNOSUPPORT = 47, /* Address family not supported by protocol family */
  65. EADDRINUSE = 48, /* Address already in use */
  66. EADDRNOTAVAIL = 49, /* Can't assign requested address */
  67. /* ipc/network software -- operational errors */
  68. ENETDOWN = 50, /* Network is down */
  69. ENETUNREACH = 51, /* Network is unreachable */
  70. ENETRESET = 52, /* Network dropped connection on reset */
  71. ECONNABORTED = 53, /* Software caused connection abort */
  72. ECONNRESET = 54, /* Connection reset by peer */
  73. ENOBUFS = 55, /* No buffer space available */
  74. EISCONN = 56, /* Socket is already connected */
  75. ENOTCONN = 57, /* Socket is not connected */
  76. ESHUTDOWN = 58, /* Can't send after socket shutdown */
  77. ETOOMANYREFS = 59, /* Too many references: can't splice */
  78. ETIMEDOUT = 60, /* Operation timed out */
  79. ECONNREFUSED = 61, /* Connection refused */
  80. ELOOP = 62, /* Too many levels of symbolic links */
  81. ENAMETOOLONG = 63, /* File name too long */
  82. /* should be rearranged */
  83. EHOSTDOWN = 64, /* Host is down */
  84. EHOSTUNREACH = 65, /* No route to host */
  85. ENOTEMPTY = 66, /* Directory not empty */
  86. /* quotas & mush */
  87. EPROCLIM = 67, /* Too many processes */
  88. EUSERS = 68, /* Too many users */
  89. EDQUOT = 69, /* Disc quota exceeded */
  90. /* Network File System */
  91. ESTALE = 70, /* Stale NFS file handle */
  92. EREMOTE = 71, /* Too many levels of remote in path */
  93. EBADRPC = 72, /* RPC struct is bad */
  94. ERPCMISMATCH = 73, /* RPC version wrong */
  95. EPROGUNAVAIL = 74, /* RPC prog. not avail */
  96. EPROGMISMATCH = 75, /* Program version wrong */
  97. EPROCUNAVAIL = 76, /* Bad procedure for program */
  98. ENOLCK = 77, /* No locks available */
  99. ENOSYS = 78, /* Function not implemented */
  100. EFTYPE = 79, /* Inappropriate file type or format */
  101. EAUTH = 80, /* Authentication error */
  102. ENEEDAUTH = 81, /* Need authenticator */
  103. /* Intelligent device errors */
  104. EPWROFF = 82, /* Device power is off */
  105. EDEVERR = 83, /* Device error, e.g. paper out */
  106. EOVERFLOW = 84, /* Value too large to be stored in data type */
  107. /* Program loading errors */
  108. EBADEXEC = 85, /* Bad executable */
  109. EBADARCH = 86, /* Bad CPU type in executable */
  110. ESHLIBVERS = 87, /* Shared library version mismatch */
  111. EBADMACHO = 88, /* Malformed Macho file */
  112. ECANCELED = 89, /* Operation canceled */
  113. EIDRM = 90, /* Identifier removed */
  114. ENOMSG = 91, /* No message of desired type */
  115. EILSEQ = 92, /* Illegal byte sequence */
  116. ENOATTR = 93, /* Attribute not found */
  117. EBADMSG = 94, /* Bad message */
  118. EMULTIHOP = 95, /* Reserved */
  119. ENODATA = 96, /* No message available on STREAM */
  120. ENOLINK = 97, /* Reserved */
  121. ENOSR = 98, /* No STREAM resources */
  122. ENOSTR = 99, /* Not a STREAM */
  123. EPROTO = 100, /* Protocol error */
  124. ETIME = 101, /* STREAM ioctl timeout */
  125. ENOPOLICY = 103, /* No such policy registered */
  126. ENOTRECOVERABLE = 104, /* State not recoverable */
  127. EOWNERDEAD = 105, /* Previous owner died */
  128. EQFULL = 106, /* Interface output queue is full */
  129. ELAST = 106, /* Must be equal largest errno */
  130. }
  131. EPERM :: _Platform_Error.EPERM
  132. ENOENT :: _Platform_Error.ENOENT
  133. ESRCH :: _Platform_Error.ESRCH
  134. EINTR :: _Platform_Error.EINTR
  135. EIO :: _Platform_Error.EIO
  136. ENXIO :: _Platform_Error.ENXIO
  137. E2BIG :: _Platform_Error.E2BIG
  138. ENOEXEC :: _Platform_Error.ENOEXEC
  139. EBADF :: _Platform_Error.EBADF
  140. ECHILD :: _Platform_Error.ECHILD
  141. EDEADLK :: _Platform_Error.EDEADLK
  142. ENOMEM :: _Platform_Error.ENOMEM
  143. EACCES :: _Platform_Error.EACCES
  144. EFAULT :: _Platform_Error.EFAULT
  145. ENOTBLK :: _Platform_Error.ENOTBLK
  146. EBUSY :: _Platform_Error.EBUSY
  147. EEXIST :: _Platform_Error.EEXIST
  148. EXDEV :: _Platform_Error.EXDEV
  149. ENODEV :: _Platform_Error.ENODEV
  150. ENOTDIR :: _Platform_Error.ENOTDIR
  151. EISDIR :: _Platform_Error.EISDIR
  152. EINVAL :: _Platform_Error.EINVAL
  153. ENFILE :: _Platform_Error.ENFILE
  154. EMFILE :: _Platform_Error.EMFILE
  155. ENOTTY :: _Platform_Error.ENOTTY
  156. ETXTBSY :: _Platform_Error.ETXTBSY
  157. EFBIG :: _Platform_Error.EFBIG
  158. ENOSPC :: _Platform_Error.ENOSPC
  159. ESPIPE :: _Platform_Error.ESPIPE
  160. EROFS :: _Platform_Error.EROFS
  161. EMLINK :: _Platform_Error.EMLINK
  162. EPIPE :: _Platform_Error.EPIPE
  163. /* math software */
  164. EDOM :: _Platform_Error.EDOM
  165. ERANGE :: _Platform_Error.ERANGE
  166. /* non-blocking and interrupt i/o */
  167. EAGAIN :: _Platform_Error.EAGAIN
  168. EWOULDBLOCK :: _Platform_Error.EWOULDBLOCK
  169. EINPROGRESS :: _Platform_Error.EINPROGRESS
  170. EALREADY :: _Platform_Error.EALREADY
  171. /* ipc/network software -- argument errors */
  172. ENOTSOCK :: _Platform_Error.ENOTSOCK
  173. EDESTADDRREQ :: _Platform_Error.EDESTADDRREQ
  174. EMSGSIZE :: _Platform_Error.EMSGSIZE
  175. EPROTOTYPE :: _Platform_Error.EPROTOTYPE
  176. ENOPROTOOPT :: _Platform_Error.ENOPROTOOPT
  177. EPROTONOSUPPORT :: _Platform_Error.EPROTONOSUPPORT
  178. ESOCKTNOSUPPORT :: _Platform_Error.ESOCKTNOSUPPORT
  179. ENOTSUP :: _Platform_Error.ENOTSUP
  180. EOPNOTSUPP :: _Platform_Error.EOPNOTSUPP
  181. EPFNOSUPPORT :: _Platform_Error.EPFNOSUPPORT
  182. EAFNOSUPPORT :: _Platform_Error.EAFNOSUPPORT
  183. EADDRINUSE :: _Platform_Error.EADDRINUSE
  184. EADDRNOTAVAIL :: _Platform_Error.EADDRNOTAVAIL
  185. /* ipc/network software -- operational errors */
  186. ENETDOWN :: _Platform_Error.ENETDOWN
  187. ENETUNREACH :: _Platform_Error.ENETUNREACH
  188. ENETRESET :: _Platform_Error.ENETRESET
  189. ECONNABORTED :: _Platform_Error.ECONNABORTED
  190. ECONNRESET :: _Platform_Error.ECONNRESET
  191. ENOBUFS :: _Platform_Error.ENOBUFS
  192. EISCONN :: _Platform_Error.EISCONN
  193. ENOTCONN :: _Platform_Error.ENOTCONN
  194. ESHUTDOWN :: _Platform_Error.ESHUTDOWN
  195. ETOOMANYREFS :: _Platform_Error.ETOOMANYREFS
  196. ETIMEDOUT :: _Platform_Error.ETIMEDOUT
  197. ECONNREFUSED :: _Platform_Error.ECONNREFUSED
  198. ELOOP :: _Platform_Error.ELOOP
  199. ENAMETOOLONG :: _Platform_Error.ENAMETOOLONG
  200. /* should be rearranged */
  201. EHOSTDOWN :: _Platform_Error.EHOSTDOWN
  202. EHOSTUNREACH :: _Platform_Error.EHOSTUNREACH
  203. ENOTEMPTY :: _Platform_Error.ENOTEMPTY
  204. /* quotas & mush */
  205. EPROCLIM :: _Platform_Error.EPROCLIM
  206. EUSERS :: _Platform_Error.EUSERS
  207. EDQUOT :: _Platform_Error.EDQUOT
  208. /* Network File System */
  209. ESTALE :: _Platform_Error.ESTALE
  210. EREMOTE :: _Platform_Error.EREMOTE
  211. EBADRPC :: _Platform_Error.EBADRPC
  212. ERPCMISMATCH :: _Platform_Error.ERPCMISMATCH
  213. EPROGUNAVAIL :: _Platform_Error.EPROGUNAVAIL
  214. EPROGMISMATCH :: _Platform_Error.EPROGMISMATCH
  215. EPROCUNAVAIL :: _Platform_Error.EPROCUNAVAIL
  216. ENOLCK :: _Platform_Error.ENOLCK
  217. ENOSYS :: _Platform_Error.ENOSYS
  218. EFTYPE :: _Platform_Error.EFTYPE
  219. EAUTH :: _Platform_Error.EAUTH
  220. ENEEDAUTH :: _Platform_Error.ENEEDAUTH
  221. /* Intelligent device errors */
  222. EPWROFF :: _Platform_Error.EPWROFF
  223. EDEVERR :: _Platform_Error.EDEVERR
  224. EOVERFLOW :: _Platform_Error.EOVERFLOW
  225. /* Program loading errors */
  226. EBADEXEC :: _Platform_Error.EBADEXEC
  227. EBADARCH :: _Platform_Error.EBADARCH
  228. ESHLIBVERS :: _Platform_Error.ESHLIBVERS
  229. EBADMACHO :: _Platform_Error.EBADMACHO
  230. ECANCELED :: _Platform_Error.ECANCELED
  231. EIDRM :: _Platform_Error.EIDRM
  232. ENOMSG :: _Platform_Error.ENOMSG
  233. EILSEQ :: _Platform_Error.EILSEQ
  234. ENOATTR :: _Platform_Error.ENOATTR
  235. EBADMSG :: _Platform_Error.EBADMSG
  236. EMULTIHOP :: _Platform_Error.EMULTIHOP
  237. ENODATA :: _Platform_Error.ENODATA
  238. ENOLINK :: _Platform_Error.ENOLINK
  239. ENOSR :: _Platform_Error.ENOSR
  240. ENOSTR :: _Platform_Error.ENOSTR
  241. EPROTO :: _Platform_Error.EPROTO
  242. ETIME :: _Platform_Error.ETIME
  243. ENOPOLICY :: _Platform_Error.ENOPOLICY
  244. ENOTRECOVERABLE :: _Platform_Error.ENOTRECOVERABLE
  245. EOWNERDEAD :: _Platform_Error.EOWNERDEAD
  246. EQFULL :: _Platform_Error.EQFULL
  247. ELAST :: _Platform_Error.ELAST
  248. O_RDONLY :: 0x0000
  249. O_WRONLY :: 0x0001
  250. O_RDWR :: 0x0002
  251. O_CREATE :: 0x0200
  252. O_EXCL :: 0x0800
  253. O_NOCTTY :: 0
  254. O_TRUNC :: 0x0400
  255. O_NONBLOCK :: 0x0004
  256. O_APPEND :: 0x0008
  257. O_SYNC :: 0x0080
  258. O_ASYNC :: 0x0040
  259. O_CLOEXEC :: 0x1000000
  260. SEEK_DATA :: 3
  261. SEEK_HOLE :: 4
  262. SEEK_MAX :: SEEK_HOLE
  263. // NOTE(zangent): These are OS specific!
  264. // Do not mix these up!
  265. RTLD_LAZY :: 0x1
  266. RTLD_NOW :: 0x2
  267. RTLD_LOCAL :: 0x4
  268. RTLD_GLOBAL :: 0x8
  269. RTLD_NODELETE :: 0x80
  270. RTLD_NOLOAD :: 0x10
  271. RTLD_FIRST :: 0x100
  272. SOL_SOCKET :: 0xFFFF
  273. SOCK_STREAM :: 1
  274. SOCK_DGRAM :: 2
  275. SOCK_RAW :: 3
  276. SOCK_RDM :: 4
  277. SOCK_SEQPACKET :: 5
  278. SO_DEBUG :: 0x0001
  279. SO_ACCEPTCONN :: 0x0002
  280. SO_REUSEADDR :: 0x0004
  281. SO_KEEPALIVE :: 0x0008
  282. SO_DONTROUTE :: 0x0010
  283. SO_BROADCAST :: 0x0020
  284. SO_USELOOPBACK :: 0x0040
  285. SO_LINGER :: 0x0080
  286. SO_OOBINLINE :: 0x0100
  287. SO_REUSEPORT :: 0x0200
  288. SO_TIMESTAMP :: 0x0400
  289. SO_DONTTRUNC :: 0x2000
  290. SO_WANTMORE :: 0x4000
  291. SO_WANTOOBFLAG :: 0x8000
  292. SO_SNDBUF :: 0x1001
  293. SO_RCVBUF :: 0x1002
  294. SO_SNDLOWAT :: 0x1003
  295. SO_RCVLOWAT :: 0x1004
  296. SO_SNDTIMEO :: 0x1005
  297. SO_RCVTIMEO :: 0x1006
  298. SO_ERROR :: 0x1007
  299. SO_TYPE :: 0x1008
  300. SO_PRIVSTATE :: 0x1009
  301. SO_NREAD :: 0x1020
  302. SO_NKE :: 0x1021
  303. AF_UNSPEC :: 0
  304. AF_LOCAL :: 1
  305. AF_UNIX :: AF_LOCAL
  306. AF_INET :: 2
  307. AF_IMPLINK :: 3
  308. AF_PUP :: 4
  309. AF_CHAOS :: 5
  310. AF_NS :: 6
  311. AF_ISO :: 7
  312. AF_OSI :: AF_ISO
  313. AF_ECMA :: 8
  314. AF_DATAKIT :: 9
  315. AF_CCITT :: 10
  316. AF_SNA :: 11
  317. AF_DECnet :: 12
  318. AF_DLI :: 13
  319. AF_LAT :: 14
  320. AF_HYLINK :: 15
  321. AF_APPLETALK :: 16
  322. AF_ROUTE :: 17
  323. AF_LINK :: 18
  324. pseudo_AF_XTP :: 19
  325. AF_COIP :: 20
  326. AF_CNT :: 21
  327. pseudo_AF_RTIP :: 22
  328. AF_IPX :: 23
  329. AF_SIP :: 24
  330. pseudo_AF_PIP :: 25
  331. pseudo_AF_BLUE :: 26
  332. AF_NDRV :: 27
  333. AF_ISDN :: 28
  334. AF_E164 :: AF_ISDN
  335. pseudo_AF_KEY :: 29
  336. AF_INET6 :: 30
  337. AF_NATM :: 31
  338. AF_SYSTEM :: 32
  339. AF_NETBIOS :: 33
  340. AF_PPP :: 34
  341. TCP_NODELAY :: 0x01
  342. TCP_MAXSEG :: 0x02
  343. TCP_NOPUSH :: 0x04
  344. TCP_NOOPT :: 0x08
  345. IPPROTO_ICMP :: 1
  346. IPPROTO_TCP :: 6
  347. IPPROTO_UDP :: 17
  348. SHUT_RD :: 0
  349. SHUT_WR :: 1
  350. SHUT_RDWR :: 2
  351. F_GETFL: int : 3 /* Get file flags */
  352. F_SETFL: int : 4 /* Set file flags */
  353. // "Argv" arguments converted to Odin strings
  354. args := _alloc_command_line_arguments()
  355. Unix_File_Time :: struct {
  356. seconds: i64,
  357. nanoseconds: i64,
  358. }
  359. OS_Stat :: struct {
  360. device_id: i32, // ID of device containing file
  361. mode: u16, // Mode of the file
  362. nlink: u16, // Number of hard links
  363. serial: u64, // File serial number
  364. uid: u32, // User ID of the file's owner
  365. gid: u32, // Group ID of the file's group
  366. rdev: i32, // Device ID, if device
  367. last_access: Unix_File_Time, // Time of last access
  368. modified: Unix_File_Time, // Time of last modification
  369. status_change: Unix_File_Time, // Time of last status change
  370. created: Unix_File_Time, // Time of creation
  371. size: i64, // Size of the file, in bytes
  372. blocks: i64, // Number of blocks allocated for the file
  373. block_size: i32, // Optimal blocksize for I/O
  374. flags: u32, // User-defined flags for the file
  375. gen_num: u32, // File generation number ..?
  376. _spare: i32, // RESERVED
  377. _reserve1,
  378. _reserve2: i64, // RESERVED
  379. }
  380. DARWIN_MAXPATHLEN :: 1024
  381. Dirent :: struct {
  382. ino: u64,
  383. off: u64,
  384. reclen: u16,
  385. namlen: u16,
  386. type: u8,
  387. name: [DARWIN_MAXPATHLEN]byte,
  388. }
  389. Dir :: distinct rawptr // DIR*
  390. ADDRESS_FAMILY :: c.char
  391. SOCKADDR :: struct #packed {
  392. len: c.char,
  393. family: ADDRESS_FAMILY,
  394. sa_data: [14]c.char,
  395. }
  396. SOCKADDR_STORAGE_LH :: struct #packed {
  397. len: c.char,
  398. family: ADDRESS_FAMILY,
  399. __ss_pad1: [6]c.char,
  400. __ss_align: i64,
  401. __ss_pad2: [112]c.char,
  402. }
  403. sockaddr_in :: struct #packed {
  404. sin_len: c.char,
  405. sin_family: ADDRESS_FAMILY,
  406. sin_port: u16be,
  407. sin_addr: in_addr,
  408. sin_zero: [8]c.char,
  409. }
  410. sockaddr_in6 :: struct #packed {
  411. sin6_len: c.char,
  412. sin6_family: ADDRESS_FAMILY,
  413. sin6_port: u16be,
  414. sin6_flowinfo: c.uint,
  415. sin6_addr: in6_addr,
  416. sin6_scope_id: c.uint,
  417. }
  418. in_addr :: struct #packed {
  419. s_addr: u32,
  420. }
  421. in6_addr :: struct #packed {
  422. s6_addr: [16]u8,
  423. }
  424. // https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/sys/socket.h#L1025-L1027
  425. // Prevent the raising of SIGPIPE on writing to a closed network socket.
  426. MSG_NOSIGNAL :: 0x80000
  427. SIOCGIFFLAG :: enum c.int {
  428. UP = 0, /* Interface is up. */
  429. BROADCAST = 1, /* Broadcast address valid. */
  430. DEBUG = 2, /* Turn on debugging. */
  431. LOOPBACK = 3, /* Is a loopback net. */
  432. POINT_TO_POINT = 4, /* Interface is point-to-point link. */
  433. NO_TRAILERS = 5, /* Avoid use of trailers. */
  434. RUNNING = 6, /* Resources allocated. */
  435. NOARP = 7, /* No address resolution protocol. */
  436. PROMISC = 8, /* Receive all packets. */
  437. ALL_MULTI = 9, /* Receive all multicast packets. Unimplemented. */
  438. }
  439. SIOCGIFFLAGS :: bit_set[SIOCGIFFLAG; c.int]
  440. ifaddrs :: struct {
  441. next: ^ifaddrs,
  442. name: cstring,
  443. flags: SIOCGIFFLAGS,
  444. address: ^SOCKADDR,
  445. netmask: ^SOCKADDR,
  446. broadcast_or_dest: ^SOCKADDR, // Broadcast or Point-to-Point address
  447. data: rawptr, // Address-specific data.
  448. }
  449. Timeval :: struct {
  450. seconds: i64,
  451. microseconds: int,
  452. }
  453. Linger :: struct {
  454. onoff: int,
  455. linger: int,
  456. }
  457. Socket :: distinct int
  458. socklen_t :: c.int
  459. // File type
  460. S_IFMT :: 0o170000 // Type of file mask
  461. S_IFIFO :: 0o010000 // Named pipe (fifo)
  462. S_IFCHR :: 0o020000 // Character special
  463. S_IFDIR :: 0o040000 // Directory
  464. S_IFBLK :: 0o060000 // Block special
  465. S_IFREG :: 0o100000 // Regular
  466. S_IFLNK :: 0o120000 // Symbolic link
  467. S_IFSOCK :: 0o140000 // Socket
  468. // File mode
  469. // Read, write, execute/search by owner
  470. S_IRWXU :: 0o0700 // RWX mask for owner
  471. S_IRUSR :: 0o0400 // R for owner
  472. S_IWUSR :: 0o0200 // W for owner
  473. S_IXUSR :: 0o0100 // X for owner
  474. // Read, write, execute/search by group
  475. S_IRWXG :: 0o0070 // RWX mask for group
  476. S_IRGRP :: 0o0040 // R for group
  477. S_IWGRP :: 0o0020 // W for group
  478. S_IXGRP :: 0o0010 // X for group
  479. // Read, write, execute/search by others
  480. S_IRWXO :: 0o0007 // RWX mask for other
  481. S_IROTH :: 0o0004 // R for other
  482. S_IWOTH :: 0o0002 // W for other
  483. S_IXOTH :: 0o0001 // X for other
  484. S_ISUID :: 0o4000 // Set user id on execution
  485. S_ISGID :: 0o2000 // Set group id on execution
  486. S_ISVTX :: 0o1000 // Directory restrcted delete
  487. @(require_results) S_ISLNK :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFLNK }
  488. @(require_results) S_ISREG :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFREG }
  489. @(require_results) S_ISDIR :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFDIR }
  490. @(require_results) S_ISCHR :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFCHR }
  491. @(require_results) S_ISBLK :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFBLK }
  492. @(require_results) S_ISFIFO :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFIFO }
  493. @(require_results) S_ISSOCK :: #force_inline proc(m: u16) -> bool { return (m & S_IFMT) == S_IFSOCK }
  494. R_OK :: 4 // Test for read permission
  495. W_OK :: 2 // Test for write permission
  496. X_OK :: 1 // Test for execute permission
  497. F_OK :: 0 // Test for file existance
  498. F_GETPATH :: 50 // return the full path of the fd
  499. foreign libc {
  500. @(link_name="__error") __error :: proc() -> ^c.int ---
  501. @(link_name="open") _unix_open :: proc(path: cstring, flags: i32, #c_vararg mode: ..u16) -> Handle ---
  502. @(link_name="close") _unix_close :: proc(handle: Handle) -> c.int ---
  503. @(link_name="read") _unix_read :: proc(handle: Handle, buffer: rawptr, count: c.size_t) -> int ---
  504. @(link_name="write") _unix_write :: proc(handle: Handle, buffer: rawptr, count: c.size_t) -> int ---
  505. @(link_name="pread") _unix_pread :: proc(handle: Handle, buffer: rawptr, count: c.size_t, offset: i64) -> int ---
  506. @(link_name="pwrite") _unix_pwrite :: proc(handle: Handle, buffer: rawptr, count: c.size_t, offset: i64) -> int ---
  507. @(link_name="lseek") _unix_lseek :: proc(fs: Handle, offset: int, whence: c.int) -> int ---
  508. @(link_name="gettid") _unix_gettid :: proc() -> u64 ---
  509. @(link_name="getpagesize") _unix_getpagesize :: proc() -> i32 ---
  510. @(link_name="stat64") _unix_stat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---
  511. @(link_name="lstat64") _unix_lstat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---
  512. @(link_name="fstat64") _unix_fstat :: proc(fd: Handle, stat: ^OS_Stat) -> c.int ---
  513. @(link_name="readlink") _unix_readlink :: proc(path: cstring, buf: ^byte, bufsiz: c.size_t) -> c.ssize_t ---
  514. @(link_name="access") _unix_access :: proc(path: cstring, mask: c.int) -> c.int ---
  515. @(link_name="fsync") _unix_fsync :: proc(handle: Handle) -> c.int ---
  516. @(link_name="dup") _unix_dup :: proc(handle: Handle) -> Handle ---
  517. @(link_name="fdopendir$INODE64") _unix_fdopendir_amd64 :: proc(fd: Handle) -> Dir ---
  518. @(link_name="readdir_r$INODE64") _unix_readdir_r_amd64 :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  519. @(link_name="fdopendir") _unix_fdopendir_arm64 :: proc(fd: Handle) -> Dir ---
  520. @(link_name="readdir_r") _unix_readdir_r_arm64 :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---
  521. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---
  522. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---
  523. @(link_name="__fcntl") _unix__fcntl :: proc(fd: Handle, cmd: c.int, arg: uintptr) -> c.int ---
  524. @(link_name="rename") _unix_rename :: proc(old: cstring, new: cstring) -> c.int ---
  525. @(link_name="remove") _unix_remove :: proc(path: cstring) -> c.int ---
  526. @(link_name="fchmod") _unix_fchmod :: proc(fd: Handle, mode: u16) -> c.int ---
  527. @(link_name="malloc") _unix_malloc :: proc(size: int) -> rawptr ---
  528. @(link_name="calloc") _unix_calloc :: proc(num, size: int) -> rawptr ---
  529. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---
  530. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: int) -> rawptr ---
  531. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---
  532. @(link_name="unsetenv") _unix_unsetenv :: proc(cstring) -> c.int ---
  533. @(link_name="setenv") _unix_setenv :: proc(key: cstring, value: cstring, overwrite: c.int) -> c.int ---
  534. @(link_name="getcwd") _unix_getcwd :: proc(buf: cstring, len: c.size_t) -> cstring ---
  535. @(link_name="chdir") _unix_chdir :: proc(buf: cstring) -> c.int ---
  536. @(link_name="mkdir") _unix_mkdir :: proc(buf: cstring, mode: u16) -> c.int ---
  537. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: [^]byte = nil) -> cstring ---
  538. @(link_name="strerror") _darwin_string_error :: proc(num : c.int) -> cstring ---
  539. @(link_name="sysctlbyname") _sysctlbyname :: proc(path: cstring, oldp: rawptr, oldlenp: rawptr, newp: rawptr, newlen: int) -> c.int ---
  540. @(link_name="socket") _unix_socket :: proc(domain: c.int, type: c.int, protocol: c.int) -> c.int ---
  541. @(link_name="listen") _unix_listen :: proc(socket: c.int, backlog: c.int) -> c.int ---
  542. @(link_name="accept") _unix_accept :: proc(socket: c.int, addr: rawptr, addr_len: rawptr) -> c.int ---
  543. @(link_name="connect") _unix_connect :: proc(socket: c.int, addr: rawptr, addr_len: socklen_t) -> c.int ---
  544. @(link_name="bind") _unix_bind :: proc(socket: c.int, addr: rawptr, addr_len: socklen_t) -> c.int ---
  545. @(link_name="setsockopt") _unix_setsockopt :: proc(socket: c.int, level: c.int, opt_name: c.int, opt_val: rawptr, opt_len: socklen_t) -> c.int ---
  546. @(link_name="getsockopt") _unix_getsockopt :: proc(socket: c.int, level: c.int, opt_name: c.int, opt_val: rawptr, opt_len: ^socklen_t) -> c.int ---
  547. @(link_name="recvfrom") _unix_recvfrom :: proc(socket: c.int, buffer: rawptr, buffer_len: c.size_t, flags: c.int, addr: rawptr, addr_len: ^socklen_t) -> c.ssize_t ---
  548. @(link_name="recv") _unix_recv :: proc(socket: c.int, buffer: rawptr, buffer_len: c.size_t, flags: c.int) -> c.ssize_t ---
  549. @(link_name="sendto") _unix_sendto :: proc(socket: c.int, buffer: rawptr, buffer_len: c.size_t, flags: c.int, addr: rawptr, addr_len: socklen_t) -> c.ssize_t ---
  550. @(link_name="send") _unix_send :: proc(socket: c.int, buffer: rawptr, buffer_len: c.size_t, flags: c.int) -> c.ssize_t ---
  551. @(link_name="shutdown") _unix_shutdown :: proc(socket: c.int, how: c.int) -> c.int ---
  552. @(link_name="getifaddrs") _getifaddrs :: proc(ifap: ^^ifaddrs) -> (c.int) ---
  553. @(link_name="freeifaddrs") _freeifaddrs :: proc(ifa: ^ifaddrs) ---
  554. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---
  555. }
  556. when ODIN_ARCH != .arm64 {
  557. _unix_fdopendir :: proc {_unix_fdopendir_amd64}
  558. _unix_readdir_r :: proc {_unix_readdir_r_amd64}
  559. } else {
  560. _unix_fdopendir :: proc {_unix_fdopendir_arm64}
  561. _unix_readdir_r :: proc {_unix_readdir_r_arm64}
  562. }
  563. foreign dl {
  564. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---
  565. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---
  566. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---
  567. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---
  568. }
  569. @(require_results, no_instrumentation)
  570. get_last_error :: proc "contextless" () -> Error {
  571. return Platform_Error(__error()^)
  572. }
  573. @(require_results)
  574. get_last_error_string :: proc() -> string {
  575. return string(_darwin_string_error(__error()^))
  576. }
  577. @(require_results)
  578. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0) -> (handle: Handle, err: Error) {
  579. isDir := is_dir_path(path)
  580. flags := flags
  581. if isDir {
  582. /*
  583. @INFO(Platin): To make it impossible to use the wrong flag for dir's
  584. as you can't write to a dir only read which makes it fail to open
  585. */
  586. flags = O_RDONLY
  587. }
  588. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  589. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  590. handle = _unix_open(cstr, i32(flags), u16(mode))
  591. if handle == INVALID_HANDLE {
  592. err = get_last_error()
  593. return
  594. }
  595. return
  596. }
  597. fchmod :: proc(fd: Handle, mode: u16) -> Error {
  598. return cast(Platform_Error)_unix_fchmod(fd, mode)
  599. }
  600. close :: proc(fd: Handle) -> Error {
  601. return cast(Platform_Error)_unix_close(fd)
  602. }
  603. // If you read or write more than `SSIZE_MAX` bytes, most darwin implementations will return `EINVAL`
  604. // but it is really implementation defined. `SSIZE_MAX` is also implementation defined but usually
  605. // the max of an i32 on Darwin.
  606. // In practice a read/write call would probably never read/write these big buffers all at once,
  607. // which is why the number of bytes is returned and why there are procs that will call this in a
  608. // loop for you.
  609. // We set a max of 1GB to keep alignment and to be safe.
  610. @(private)
  611. MAX_RW :: 1 << 30
  612. write :: proc(fd: Handle, data: []byte) -> (int, Error) {
  613. if len(data) == 0 {
  614. return 0, nil
  615. }
  616. to_write := min(c.size_t(len(data)), MAX_RW)
  617. bytes_written := _unix_write(fd, raw_data(data), to_write)
  618. if bytes_written < 0 {
  619. return -1, get_last_error()
  620. }
  621. return bytes_written, nil
  622. }
  623. read :: proc(fd: Handle, data: []u8) -> (int, Error) {
  624. if len(data) == 0 {
  625. return 0, nil
  626. }
  627. to_read := min(c.size_t(len(data)), MAX_RW)
  628. bytes_read := _unix_read(fd, raw_data(data), to_read)
  629. if bytes_read < 0 {
  630. return -1, get_last_error()
  631. }
  632. return bytes_read, nil
  633. }
  634. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Error) {
  635. if len(data) == 0 {
  636. return 0, nil
  637. }
  638. to_read := min(c.size_t(len(data)), MAX_RW)
  639. bytes_read := _unix_pread(fd, raw_data(data), to_read, offset)
  640. if bytes_read < 0 {
  641. return -1, get_last_error()
  642. }
  643. return bytes_read, nil
  644. }
  645. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Error) {
  646. if len(data) == 0 {
  647. return 0, nil
  648. }
  649. to_write := min(c.size_t(len(data)), MAX_RW)
  650. bytes_written := _unix_pwrite(fd, raw_data(data), to_write, offset)
  651. if bytes_written < 0 {
  652. return -1, get_last_error()
  653. }
  654. return bytes_written, nil
  655. }
  656. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Error) {
  657. assert(fd != -1)
  658. switch whence {
  659. case SEEK_SET, SEEK_CUR, SEEK_END:
  660. break
  661. case:
  662. return 0, .Invalid_Whence
  663. }
  664. final_offset := i64(_unix_lseek(fd, int(offset), c.int(whence)))
  665. if final_offset == -1 {
  666. errno := get_last_error()
  667. switch errno {
  668. case .EINVAL:
  669. return 0, .Invalid_Offset
  670. }
  671. return 0, errno
  672. }
  673. return final_offset, nil
  674. }
  675. @(require_results)
  676. file_size :: proc(fd: Handle) -> (i64, Error) {
  677. prev, _ := seek(fd, 0, SEEK_CUR)
  678. size, err := seek(fd, 0, SEEK_END)
  679. seek(fd, prev, SEEK_SET)
  680. return i64(size), err
  681. }
  682. // NOTE(bill): Uses startup to initialize it
  683. stdin: Handle = 0 // get_std_handle(win32.STD_INPUT_HANDLE);
  684. stdout: Handle = 1 // get_std_handle(win32.STD_OUTPUT_HANDLE);
  685. stderr: Handle = 2 // get_std_handle(win32.STD_ERROR_HANDLE);
  686. @(require_results)
  687. last_write_time :: proc(fd: Handle) -> (time: File_Time, err: Error) {
  688. s := _fstat(fd) or_return
  689. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  690. return File_Time(modified), nil
  691. }
  692. @(require_results)
  693. last_write_time_by_name :: proc(name: string) -> (time: File_Time, err: Error) {
  694. s := _stat(name) or_return
  695. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds
  696. return File_Time(modified), nil
  697. }
  698. @(require_results)
  699. is_path_separator :: proc(r: rune) -> bool {
  700. return r == '/'
  701. }
  702. @(require_results)
  703. is_file_handle :: proc(fd: Handle) -> bool {
  704. s, err := _fstat(fd)
  705. if err != nil {
  706. return false
  707. }
  708. return S_ISREG(s.mode)
  709. }
  710. @(require_results)
  711. is_file_path :: proc(path: string, follow_links: bool = true) -> bool {
  712. s: OS_Stat
  713. err: Error
  714. if follow_links {
  715. s, err = _stat(path)
  716. } else {
  717. s, err = _lstat(path)
  718. }
  719. if err != nil {
  720. return false
  721. }
  722. return S_ISREG(s.mode)
  723. }
  724. @(require_results)
  725. is_dir_handle :: proc(fd: Handle) -> bool {
  726. s, err := _fstat(fd)
  727. if err != nil {
  728. return false
  729. }
  730. return S_ISDIR(s.mode)
  731. }
  732. @(require_results)
  733. is_dir_path :: proc(path: string, follow_links: bool = true) -> bool {
  734. s: OS_Stat
  735. err: Error
  736. if follow_links {
  737. s, err = _stat(path)
  738. } else {
  739. s, err = _lstat(path)
  740. }
  741. if err != nil {
  742. return false
  743. }
  744. return S_ISDIR(s.mode)
  745. }
  746. is_file :: proc {is_file_path, is_file_handle}
  747. is_dir :: proc {is_dir_path, is_dir_handle}
  748. @(require_results)
  749. exists :: proc(path: string) -> bool {
  750. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  751. cpath := strings.clone_to_cstring(path, context.temp_allocator)
  752. res := _unix_access(cpath, O_RDONLY)
  753. return res == 0
  754. }
  755. rename :: proc(old: string, new: string) -> bool {
  756. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  757. old_cstr := strings.clone_to_cstring(old, context.temp_allocator)
  758. new_cstr := strings.clone_to_cstring(new, context.temp_allocator)
  759. return _unix_rename(old_cstr, new_cstr) != -1
  760. }
  761. remove :: proc(path: string) -> Error {
  762. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  763. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  764. res := _unix_remove(path_cstr)
  765. if res == -1 {
  766. return get_last_error()
  767. }
  768. return nil
  769. }
  770. @(private, require_results)
  771. _stat :: proc(path: string) -> (OS_Stat, Error) {
  772. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  773. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  774. s: OS_Stat
  775. result := _unix_stat(cstr, &s)
  776. if result == -1 {
  777. return s, get_last_error()
  778. }
  779. return s, nil
  780. }
  781. @(private, require_results)
  782. _lstat :: proc(path: string) -> (OS_Stat, Error) {
  783. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  784. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  785. s: OS_Stat
  786. result := _unix_lstat(cstr, &s)
  787. if result == -1 {
  788. return s, get_last_error()
  789. }
  790. return s, nil
  791. }
  792. @(private, require_results)
  793. _fstat :: proc(fd: Handle) -> (OS_Stat, Error) {
  794. s: OS_Stat
  795. result := _unix_fstat(fd, &s)
  796. if result == -1 {
  797. return s, get_last_error()
  798. }
  799. return s, nil
  800. }
  801. @(private, require_results)
  802. _fdopendir :: proc(fd: Handle) -> (Dir, Error) {
  803. dirp := _unix_fdopendir(fd)
  804. if dirp == cast(Dir)nil {
  805. return nil, get_last_error()
  806. }
  807. return dirp, nil
  808. }
  809. @(private)
  810. _closedir :: proc(dirp: Dir) -> Error {
  811. rc := _unix_closedir(dirp)
  812. if rc != 0 {
  813. return get_last_error()
  814. }
  815. return nil
  816. }
  817. @(private)
  818. _rewinddir :: proc(dirp: Dir) {
  819. _unix_rewinddir(dirp)
  820. }
  821. @(private, require_results)
  822. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Error, end_of_stream: bool) {
  823. result: ^Dirent
  824. rc := _unix_readdir_r(dirp, &entry, &result)
  825. if rc != 0 {
  826. err = get_last_error()
  827. return
  828. }
  829. if result == nil {
  830. end_of_stream = true
  831. return
  832. }
  833. end_of_stream = false
  834. return
  835. }
  836. @(private, require_results)
  837. _readlink :: proc(path: string) -> (string, Error) {
  838. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  839. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  840. bufsz : uint = 256
  841. buf := make([]byte, bufsz)
  842. for {
  843. rc := _unix_readlink(path_cstr, &(buf[0]), bufsz)
  844. if rc == -1 {
  845. delete(buf)
  846. return "", get_last_error()
  847. } else if rc == int(bufsz) {
  848. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  849. bufsz *= 2
  850. delete(buf)
  851. buf = make([]byte, bufsz)
  852. } else {
  853. return strings.string_from_ptr(&buf[0], rc), nil
  854. }
  855. }
  856. }
  857. @(private, require_results)
  858. _dup :: proc(fd: Handle) -> (Handle, Error) {
  859. dup := _unix_dup(fd)
  860. if dup == -1 {
  861. return INVALID_HANDLE, get_last_error()
  862. }
  863. return dup, nil
  864. }
  865. @(require_results)
  866. absolute_path_from_handle :: proc(fd: Handle) -> (path: string, err: Error) {
  867. buf: [DARWIN_MAXPATHLEN]byte
  868. _ = fcntl(int(fd), F_GETPATH, int(uintptr(&buf[0]))) or_return
  869. return strings.clone_from_cstring(cstring(&buf[0]))
  870. }
  871. @(require_results)
  872. absolute_path_from_relative :: proc(rel: string, allocator := context.allocator) -> (path: string, err: Error) {
  873. rel := rel
  874. if rel == "" {
  875. rel = "."
  876. }
  877. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == context.allocator)
  878. rel_cstr := strings.clone_to_cstring(rel, context.temp_allocator)
  879. path_ptr := _unix_realpath(rel_cstr, nil)
  880. if path_ptr == nil {
  881. return "", get_last_error()
  882. }
  883. defer _unix_free(rawptr(path_ptr))
  884. return strings.clone(string(path_ptr), allocator)
  885. }
  886. access :: proc(path: string, mask: int) -> bool {
  887. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  888. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  889. return _unix_access(cstr, c.int(mask)) == 0
  890. }
  891. flush :: proc(fd: Handle) -> Error {
  892. return cast(Platform_Error)_unix_fsync(fd)
  893. }
  894. @(require_results)
  895. lookup_env_alloc :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
  896. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
  897. path_str := strings.clone_to_cstring(key, context.temp_allocator)
  898. // NOTE(tetra): Lifetime of 'cstr' is unclear, but _unix_free(cstr) segfaults.
  899. cstr := _unix_getenv(path_str)
  900. if cstr == nil {
  901. return "", false
  902. }
  903. return strings.clone(string(cstr), allocator), true
  904. }
  905. @(require_results)
  906. lookup_env_buffer :: proc(buf: []u8, key: string) -> (value: string, err: Error) {
  907. if len(key) + 1 > len(buf) {
  908. return "", .Buffer_Full
  909. } else {
  910. copy(buf, key)
  911. }
  912. if value = string(_unix_getenv(cstring(raw_data(buf)))); value == "" {
  913. return "", .Env_Var_Not_Found
  914. } else {
  915. if len(value) > len(buf) {
  916. return "", .Buffer_Full
  917. } else {
  918. copy(buf, value)
  919. return string(buf[:len(value)]), nil
  920. }
  921. }
  922. }
  923. lookup_env :: proc{lookup_env_alloc, lookup_env_buffer}
  924. @(require_results)
  925. get_env_alloc :: proc(key: string, allocator := context.allocator) -> (value: string) {
  926. value, _ = lookup_env(key, allocator)
  927. return
  928. }
  929. @(require_results)
  930. get_env_buf :: proc(buf: []u8, key: string) -> (value: string) {
  931. value, _ = lookup_env(buf, key)
  932. return
  933. }
  934. get_env :: proc{get_env_alloc, get_env_buf}
  935. set_env :: proc(key, value: string) -> Error {
  936. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  937. key_cstring := strings.clone_to_cstring(key, context.temp_allocator)
  938. value_cstring := strings.clone_to_cstring(value, context.temp_allocator)
  939. res := _unix_setenv(key_cstring, value_cstring, 1)
  940. if res < 0 {
  941. return get_last_error()
  942. }
  943. return nil
  944. }
  945. unset_env :: proc(key: string) -> Error {
  946. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  947. s := strings.clone_to_cstring(key, context.temp_allocator)
  948. res := _unix_unsetenv(s)
  949. if res < 0 {
  950. return get_last_error()
  951. }
  952. return nil
  953. }
  954. @(require_results)
  955. get_current_directory :: proc(allocator := context.allocator) -> string {
  956. context.allocator = allocator
  957. page_size := get_page_size() // NOTE(tetra): See note in os_linux.odin/get_current_directory.
  958. buf := make([dynamic]u8, page_size)
  959. for {
  960. cwd := _unix_getcwd(cstring(raw_data(buf)), c.size_t(len(buf)))
  961. if cwd != nil {
  962. return string(cwd)
  963. }
  964. if get_last_error() != ERANGE {
  965. delete(buf)
  966. return ""
  967. }
  968. resize(&buf, len(buf)+page_size)
  969. }
  970. unreachable()
  971. }
  972. set_current_directory :: proc(path: string) -> (err: Error) {
  973. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  974. cstr := strings.clone_to_cstring(path, context.temp_allocator)
  975. res := _unix_chdir(cstr)
  976. if res == -1 {
  977. return get_last_error()
  978. }
  979. return nil
  980. }
  981. make_directory :: proc(path: string, mode: u16 = 0o775) -> Error {
  982. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  983. path_cstr := strings.clone_to_cstring(path, context.temp_allocator)
  984. res := _unix_mkdir(path_cstr, mode)
  985. if res == -1 {
  986. return get_last_error()
  987. }
  988. return nil
  989. }
  990. exit :: proc "contextless" (code: int) -> ! {
  991. runtime._cleanup_runtime_contextless()
  992. _unix_exit(i32(code))
  993. }
  994. @(require_results)
  995. current_thread_id :: proc "contextless" () -> int {
  996. tid: u64
  997. // NOTE(Oskar): available from OSX 10.6 and iOS 3.2.
  998. // For older versions there is `syscall(SYS_thread_selfid)`, but not really
  999. // the same thing apparently.
  1000. foreign pthread { pthread_threadid_np :: proc "c" (rawptr, ^u64) -> c.int --- }
  1001. pthread_threadid_np(nil, &tid)
  1002. return int(tid)
  1003. }
  1004. @(require_results)
  1005. dlopen :: proc(filename: string, flags: int) -> rawptr {
  1006. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  1007. cstr := strings.clone_to_cstring(filename, context.temp_allocator)
  1008. handle := _unix_dlopen(cstr, c.int(flags))
  1009. return handle
  1010. }
  1011. @(require_results)
  1012. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  1013. assert(handle != nil)
  1014. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  1015. cstr := strings.clone_to_cstring(symbol, context.temp_allocator)
  1016. proc_handle := _unix_dlsym(handle, cstr)
  1017. return proc_handle
  1018. }
  1019. dlclose :: proc(handle: rawptr) -> bool {
  1020. assert(handle != nil)
  1021. return _unix_dlclose(handle) == 0
  1022. }
  1023. dlerror :: proc() -> string {
  1024. return string(_unix_dlerror())
  1025. }
  1026. @(require_results)
  1027. get_page_size :: proc() -> int {
  1028. // NOTE(tetra): The page size never changes, so why do anything complicated
  1029. // if we don't have to.
  1030. @static page_size := -1
  1031. if page_size != -1 {
  1032. return page_size
  1033. }
  1034. page_size = int(_unix_getpagesize())
  1035. return page_size
  1036. }
  1037. @(private, require_results)
  1038. _processor_core_count :: proc() -> int {
  1039. count : int = 0
  1040. count_size := size_of(count)
  1041. if _sysctlbyname("hw.logicalcpu", &count, &count_size, nil, 0) == 0 {
  1042. if count > 0 {
  1043. return count
  1044. }
  1045. }
  1046. return 1
  1047. }
  1048. @(private, require_results)
  1049. _alloc_command_line_arguments :: proc "contextless" () -> []string {
  1050. context = runtime.default_context()
  1051. res := make([]string, len(runtime.args__))
  1052. for _, i in res {
  1053. res[i] = string(runtime.args__[i])
  1054. }
  1055. return res
  1056. }
  1057. @(private, fini)
  1058. _delete_command_line_arguments :: proc "contextless" () {
  1059. context = runtime.default_context()
  1060. delete(args)
  1061. }
  1062. socket :: proc(domain: int, type: int, protocol: int) -> (Socket, Error) {
  1063. result := _unix_socket(c.int(domain), c.int(type), c.int(protocol))
  1064. if result < 0 {
  1065. return 0, get_last_error()
  1066. }
  1067. return Socket(result), nil
  1068. }
  1069. connect :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> Error {
  1070. result := _unix_connect(c.int(sd), addr, len)
  1071. if result < 0 {
  1072. return get_last_error()
  1073. }
  1074. return nil
  1075. }
  1076. bind :: proc(sd: Socket, addr: ^SOCKADDR, len: socklen_t) -> (Error) {
  1077. result := _unix_bind(c.int(sd), addr, len)
  1078. if result < 0 {
  1079. return get_last_error()
  1080. }
  1081. return nil
  1082. }
  1083. accept :: proc(sd: Socket, addr: ^SOCKADDR, len: rawptr) -> (Socket, Error) {
  1084. result := _unix_accept(c.int(sd), rawptr(addr), len)
  1085. if result < 0 {
  1086. return 0, get_last_error()
  1087. }
  1088. return Socket(result), nil
  1089. }
  1090. listen :: proc(sd: Socket, backlog: int) -> (Error) {
  1091. result := _unix_listen(c.int(sd), c.int(backlog))
  1092. if result < 0 {
  1093. return get_last_error()
  1094. }
  1095. return nil
  1096. }
  1097. setsockopt :: proc(sd: Socket, level: int, optname: int, optval: rawptr, optlen: socklen_t) -> Error {
  1098. result := _unix_setsockopt(c.int(sd), c.int(level), c.int(optname), optval, optlen)
  1099. if result < 0 {
  1100. return get_last_error()
  1101. }
  1102. return nil
  1103. }
  1104. getsockopt :: proc(sd: Socket, level: int, optname: int, optval: rawptr, optlen: socklen_t) -> Error {
  1105. optlen := optlen
  1106. result := _unix_getsockopt(c.int(sd), c.int(level), c.int(optname), optval, &optlen)
  1107. if result < 0 {
  1108. return get_last_error()
  1109. }
  1110. return nil
  1111. }
  1112. recvfrom :: proc(sd: Socket, data: []byte, flags: int, addr: ^SOCKADDR, addr_size: ^socklen_t) -> (u32, Error) {
  1113. result := _unix_recvfrom(c.int(sd), raw_data(data), len(data), c.int(flags), addr, addr_size)
  1114. if result < 0 {
  1115. return 0, get_last_error()
  1116. }
  1117. return u32(result), nil
  1118. }
  1119. recv :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Error) {
  1120. result := _unix_recv(c.int(sd), raw_data(data), len(data), c.int(flags))
  1121. if result < 0 {
  1122. return 0, get_last_error()
  1123. }
  1124. return u32(result), nil
  1125. }
  1126. sendto :: proc(sd: Socket, data: []u8, flags: int, addr: ^SOCKADDR, addrlen: socklen_t) -> (u32, Error) {
  1127. result := _unix_sendto(c.int(sd), raw_data(data), len(data), c.int(flags), addr, addrlen)
  1128. if result < 0 {
  1129. return 0, get_last_error()
  1130. }
  1131. return u32(result), nil
  1132. }
  1133. send :: proc(sd: Socket, data: []byte, flags: int) -> (u32, Error) {
  1134. result := _unix_send(c.int(sd), raw_data(data), len(data), i32(flags))
  1135. if result < 0 {
  1136. return 0, get_last_error()
  1137. }
  1138. return u32(result), nil
  1139. }
  1140. shutdown :: proc(sd: Socket, how: int) -> (Error) {
  1141. result := _unix_shutdown(c.int(sd), c.int(how))
  1142. if result < 0 {
  1143. return get_last_error()
  1144. }
  1145. return nil
  1146. }
  1147. fcntl :: proc(fd: int, cmd: int, arg: int) -> (int, Error) {
  1148. result := _unix__fcntl(Handle(fd), c.int(cmd), uintptr(arg))
  1149. if result < 0 {
  1150. return 0, get_last_error()
  1151. }
  1152. return int(result), nil
  1153. }