mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
669
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f1a3aceb1 | ||
|
|
1dc5cdc944 | ||
|
|
781b0cfab5 | ||
|
|
e96ba28879 | ||
|
|
c0e3eea428 | ||
|
|
53b1815f41 | ||
|
|
8e71dd3e0d | ||
|
|
677e51f1f2 | ||
|
|
cf29202fc7 | ||
|
|
406f7634f1 | ||
|
|
1da023b4ca | ||
|
|
abc83c2de1 | ||
|
|
2949c1bfcb | ||
|
|
fa6a245b37 | ||
|
|
640e5755b5 | ||
|
|
1c44ed678c | ||
|
|
6c5077b2d2 | ||
|
|
762c819b0f | ||
|
|
013178c00e | ||
|
|
70505cf6fc | ||
|
|
d1b4ed40f2 | ||
|
|
20dddc22ed | ||
|
|
f6105a8be1 | ||
|
|
65df702254 | ||
|
|
77882a1fc8 | ||
|
|
402eb4b586 | ||
|
|
7f6a009cc4 | ||
|
|
8f2745da9a | ||
|
|
74c1ef0581 | ||
|
|
6dbc60a373 | ||
|
|
443e03c16f | ||
|
|
1e6e65ede7 | ||
|
|
90a005db2f | ||
|
|
98517ef93b | ||
|
|
f28e22fbc1 | ||
|
|
e16b3f1066 | ||
|
|
a3e9687c91 | ||
|
|
b1f3496e31 | ||
|
|
15479b53b9 | ||
|
|
688716f8a2 | ||
|
|
6374a4ab3a | ||
|
|
feb66db229 | ||
|
|
a51425f6d8 | ||
|
|
da235b4503 | ||
|
|
86fdc1dd1d | ||
|
|
d0f7d75929 | ||
|
|
f325ebf78f | ||
|
|
4179b2cce5 | ||
|
|
f5fe750a57 | ||
|
|
9bf5df3d10 | ||
|
|
d27cb52754 | ||
|
|
faae10c4ec | ||
|
|
a85b97fc62 | ||
|
|
92481cc056 | ||
|
|
f0d63f4282 | ||
|
|
486d48c80f | ||
|
|
95ed6aa2a4 | ||
|
|
b832f4134a | ||
|
|
0eab740450 | ||
|
|
cbf57d4575 | ||
|
|
c3b7f2a48e | ||
|
|
cf36a2fe7b | ||
|
|
74a7b6f618 | ||
|
|
9a9b78e4e9 | ||
|
|
292eb44442 | ||
|
|
b2237390d8 | ||
|
|
671a219316 | ||
|
|
5cf1e06016 | ||
|
|
411318ca34 | ||
|
|
e6796eb47d | ||
|
|
b0d4217c8c | ||
|
|
85e911cd30 | ||
|
|
65f43f5d57 | ||
|
|
b62bce1bc4 | ||
|
|
6843adad5a | ||
|
|
4699556133 | ||
|
|
1c80f27aef | ||
|
|
59b5659a1e | ||
|
|
dc65a924d9 | ||
|
|
3b8124e350 | ||
|
|
241fedcbbd | ||
|
|
1b452c2996 | ||
|
|
869129b7bf | ||
|
|
5c2854d7bd | ||
|
|
6dc13544bb | ||
|
|
d0ef8d091d | ||
|
|
79b7490ae9 | ||
|
|
c5c1a835d6 | ||
|
|
27bc5e7e8d | ||
|
|
c49268ed91 | ||
|
|
704705c5c5 | ||
|
|
16cfbd4f8b | ||
|
|
755a5b4b3d | ||
|
|
6485260369 | ||
|
|
d4e86324e9 | ||
|
|
29b14a3025 | ||
|
|
6a63f086f6 | ||
|
|
b9e0ecaa60 | ||
|
|
6e3259aec3 | ||
|
|
d4373e36f6 | ||
|
|
a6d4c153b7 | ||
|
|
4df226b098 | ||
|
|
a2ca84e281 | ||
|
|
980a71f20c | ||
|
|
bd49600d62 | ||
|
|
0ecb080d5c | ||
|
|
bed8e28860 | ||
|
|
2e81d94142 | ||
|
|
75c85d47e7 | ||
|
|
5b7e24a6b1 | ||
|
|
6baba54adb | ||
|
|
27b4a4a03a | ||
|
|
8ac955bde7 | ||
|
|
617edb8398 | ||
|
|
5db65c3086 | ||
|
|
2159235ef0 | ||
|
|
dd5313284d | ||
|
|
2a069e401b | ||
|
|
e775d1bf59 | ||
|
|
e4b352c650 | ||
|
|
ab11b74b39 | ||
|
|
353a48d98d | ||
|
|
aa7ed87b5f | ||
|
|
73067f8221 | ||
|
|
a352b4c224 | ||
|
|
cd18a372c0 | ||
|
|
0d9e29baa0 | ||
|
|
4966bcbf8b | ||
|
|
71be76265f | ||
|
|
90a174256e | ||
|
|
a9597cc068 | ||
|
|
50688cacbd | ||
|
|
bd155c104f | ||
|
|
52930bf6be | ||
|
|
7c072c0d97 | ||
|
|
5d61ccdc7e | ||
|
|
2b266acf85 | ||
|
|
101cc809ba | ||
|
|
0b30161977 | ||
|
|
b349ff8c05 | ||
|
|
7cb32eb7a4 | ||
|
|
a6515006f5 | ||
|
|
7edc09a749 | ||
|
|
03604ffcd9 | ||
|
|
2d0912acba | ||
|
|
16cdb0d008 | ||
|
|
e2ae946862 | ||
|
|
f05c1d815d | ||
|
|
0601f0edec | ||
|
|
a10991ab88 | ||
|
|
b5544ba79a | ||
|
|
dda389ed2b | ||
|
|
d3c632e868 | ||
|
|
326260ee3b | ||
|
|
d5f004e6f1 | ||
|
|
38cd4aaf65 | ||
|
|
41de235573 | ||
|
|
efc401eb32 | ||
|
|
73da907161 | ||
|
|
124e17164c | ||
|
|
d7ca4a9e4c | ||
|
|
4a55025558 | ||
|
|
8771bb6199 | ||
|
|
e927959165 | ||
|
|
f52438c1b8 | ||
|
|
636e14a3d2 | ||
|
|
7c504cabbf | ||
|
|
0b7fc03c76 | ||
|
|
a7e7c56fec | ||
|
|
c124911240 | ||
|
|
a17caca7af | ||
|
|
1cfd5105b2 | ||
|
|
76a2dc6162 | ||
|
|
e0aa78a944 | ||
|
|
1494bb89fc | ||
|
|
e358151f96 | ||
|
|
e7723528a1 | ||
|
|
58bce128ce | ||
|
|
5b670937e3 | ||
|
|
74bc402c95 | ||
|
|
96c5f3b852 | ||
|
|
776989a955 | ||
|
|
671bd1a573 | ||
|
|
69ba2cd76e | ||
|
|
ede51c41cb | ||
|
|
64545cfc87 | ||
|
|
7502b711c9 | ||
|
|
abcf8e31b3 | ||
|
|
0a3460f369 | ||
|
|
c50ad26d06 | ||
|
|
666fba77fc | ||
|
|
360e6f70f0 | ||
|
|
e402d5fa38 | ||
|
|
1bd796b6b9 | ||
|
|
7e888c0cb4 | ||
|
|
d937d15735 | ||
|
|
8af20f00ab | ||
|
|
9a8bef12be | ||
|
|
e60d362ada | ||
|
|
b7b66845da | ||
|
|
4fdc665a0f | ||
|
|
3e0b318176 | ||
|
|
a2bc5f0625 | ||
|
|
2cc89c12b3 | ||
|
|
e59002fa14 | ||
|
|
ebbbc31709 | ||
|
|
c6cc06d24d | ||
|
|
669763cfd5 | ||
|
|
6fa5c8a6c1 | ||
|
|
2cae953181 | ||
|
|
03453849a2 | ||
|
|
0d7feaa50c | ||
|
|
34f4970c1c | ||
|
|
2986958695 | ||
|
|
30d09ac188 | ||
|
|
686feb3a39 | ||
|
|
56dad9d66e | ||
|
|
929b835515 | ||
|
|
26f8c4f195 | ||
|
|
de8779fb3d | ||
|
|
491b97c7c0 | ||
|
|
814d09c7ea | ||
|
|
61280ab365 | ||
|
|
cc4afd1a71 | ||
|
|
348b497836 | ||
|
|
0323dff7db | ||
|
|
4d2c21f6b3 | ||
|
|
45e26e7cc1 | ||
|
|
9554473133 | ||
|
|
c0fa05b225 | ||
|
|
51d396093d | ||
|
|
6d25d11066 | ||
|
|
cb63c9a073 | ||
|
|
4471eaa313 | ||
|
|
f86edc7020 | ||
|
|
71db29e931 | ||
|
|
043bda4234 | ||
|
|
4278ed8d97 | ||
|
|
cf6956a19a | ||
|
|
91bd99f29a | ||
|
|
7c0af0ded6 | ||
|
|
7e474cb4bd | ||
|
|
b0e5ec8932 | ||
|
|
538ae25062 | ||
|
|
fb3c3abebf | ||
|
|
f6b96c3ba7 | ||
|
|
7c6ad0fc39 | ||
|
|
13851a3421 | ||
|
|
8f8d80a4fe | ||
|
|
608a75b962 | ||
|
|
0dbbab4aa1 | ||
|
|
2eb655e0b7 | ||
|
|
53afbde6ab | ||
|
|
07a3f090d7 | ||
|
|
dda2b535b7 | ||
|
|
0ed3416369 | ||
|
|
766415499c | ||
|
|
097805e869 | ||
|
|
e65f5a6cad | ||
|
|
2e372aa16c | ||
|
|
4956c2c512 | ||
|
|
0dcedcb7bb | ||
|
|
b083113aef | ||
|
|
f9a2b9443b | ||
|
|
b252c123a7 | ||
|
|
e133abb3e0 | ||
|
|
b11b33ab57 | ||
|
|
55350cd06d | ||
|
|
87f8e49ba7 | ||
|
|
d5f59fe404 | ||
|
|
c2e385e849 | ||
|
|
4911642226 | ||
|
|
40e1deb663 | ||
|
|
eee0145671 | ||
|
|
90dba1dc68 | ||
|
|
501bb7d052 | ||
|
|
67a2fd2ca1 | ||
|
|
bc16a3c120 | ||
|
|
98712f67f2 | ||
|
|
2f5b12b854 | ||
|
|
905f9f842d | ||
|
|
a07696ace3 | ||
|
|
57d515e1d0 | ||
|
|
2f4c8c216c | ||
|
|
70f197f036 | ||
|
|
f477389569 | ||
|
|
bc4e6e3bea | ||
|
|
d8dd95176b | ||
|
|
2ae0c650be | ||
|
|
478da393fa | ||
|
|
80587df07f | ||
|
|
4bbe3f3eeb | ||
|
|
9ddc89964b | ||
|
|
18a52c4729 | ||
|
|
1c1ad1d3f4 | ||
|
|
2fdd948a28 | ||
|
|
227ebbbe2d | ||
|
|
b6bd66889b | ||
|
|
395a77f0aa | ||
|
|
b1618475cc | ||
|
|
b2711a872a | ||
|
|
b6a7776360 | ||
|
|
0b3b691d0b | ||
|
|
0610d8f893 | ||
|
|
0ea6743c17 | ||
|
|
890830fff1 | ||
|
|
a5f13c77b8 | ||
|
|
086219bf62 | ||
|
|
11d9d4a78e | ||
|
|
0c11feadd4 | ||
|
|
2410aed341 | ||
|
|
9ec41a667c | ||
|
|
9226c72b3a | ||
|
|
d9d138a88e | ||
|
|
13ad3fe4ac | ||
|
|
2610d66a52 | ||
|
|
e0d9cb0638 | ||
|
|
c4fef8b59a | ||
|
|
f97a80426c | ||
|
|
e5198c2b2d | ||
|
|
9a1530813e | ||
|
|
b63d24d465 | ||
|
|
a717516d69 | ||
|
|
d89ca1d511 | ||
|
|
d32abd8c6e | ||
|
|
d75acaac3a | ||
|
|
5fedb102b5 | ||
|
|
960067d31a | ||
|
|
0bb855ac35 | ||
|
|
3f68d42246 | ||
|
|
c72c758953 | ||
|
|
a067a0751a | ||
|
|
e1191b2ba5 | ||
|
|
c7eaf63462 | ||
|
|
4f5b5fb40d | ||
|
|
5059730d24 | ||
|
|
8de80270cb | ||
|
|
41daa93a5d | ||
|
|
2adb6b41cc | ||
|
|
6ee9a58c36 | ||
|
|
7f9dba80cf | ||
|
|
08ed962064 | ||
|
|
08ea3343a5 | ||
|
|
a66176f518 | ||
|
|
33b58a8110 | ||
|
|
52d9c99a94 | ||
|
|
b93169b8e2 | ||
|
|
9a046498d0 | ||
|
|
a56bcda3c1 | ||
|
|
f7c05e1fb8 | ||
|
|
7fc787e6ba | ||
|
|
779c9ac628 | ||
|
|
2f6c4e0f03 | ||
|
|
d121081c01 | ||
|
|
a6675d7e5c | ||
|
|
329c5f59a2 | ||
|
|
6dd0eba8e3 | ||
|
|
4b70ffe375 | ||
|
|
8757fae97c | ||
|
|
d2b78f801b | ||
|
|
d6687d2bbb | ||
|
|
528e7485ba | ||
|
|
a6c5a39ca5 | ||
|
|
55e55c1978 | ||
|
|
bc097e91dc | ||
|
|
227a38f230 | ||
|
|
bbe2f1c192 | ||
|
|
e580c13ca8 | ||
|
|
a6149c215e | ||
|
|
de2d6e2d39 | ||
|
|
0d4c6fc971 | ||
|
|
27ccce55db | ||
|
|
321a71c2e9 | ||
|
|
131326c8ae | ||
|
|
c0273af7e5 | ||
|
|
f91cb6b8de | ||
|
|
f9c2a2b8e7 | ||
|
|
61e4ca4b81 | ||
|
|
f3154e33ec | ||
|
|
99feed67fe | ||
|
|
40d22dace6 | ||
|
|
595c862c19 | ||
|
|
3d6cba22b6 | ||
|
|
f5b8e02ba7 | ||
|
|
7e2f797fb4 | ||
|
|
3a649e32a6 | ||
|
|
5695a8831b | ||
|
|
f38d72f310 | ||
|
|
a49ba8a8b3 | ||
|
|
c47779fac0 | ||
|
|
344b3b85f8 | ||
|
|
a98cd3f2da | ||
|
|
3760dc265a | ||
|
|
baa3d62569 | ||
|
|
ea77ef8a21 | ||
|
|
9d325b29ce | ||
|
|
7798f0c957 | ||
|
|
5691e92a4b | ||
|
|
28ce835363 | ||
|
|
05eac87c08 | ||
|
|
c029c1bfbd | ||
|
|
261ca250fe | ||
|
|
014f8b78eb | ||
|
|
41f9676907 | ||
|
|
d4ca203c09 | ||
|
|
2f91217c90 | ||
|
|
27275f843a | ||
|
|
b40b09440c | ||
|
|
0e652c4d25 | ||
|
|
009b07e140 | ||
|
|
1b8167d354 | ||
|
|
2ac80d6f4e | ||
|
|
7fff872441 | ||
|
|
d6b40a7284 | ||
|
|
72c316ba86 | ||
|
|
48455a9135 | ||
|
|
880ec9086e | ||
|
|
9ad16c0aae | ||
|
|
91155fd527 | ||
|
|
49dd7977ca | ||
|
|
5e24673259 | ||
|
|
d338de1478 | ||
|
|
f3b8cc473d | ||
|
|
a34201439c | ||
|
|
12573bfb88 | ||
|
|
3a1b4a8e05 | ||
|
|
d9b03016dc | ||
|
|
f18ed75481 | ||
|
|
d895f2a828 | ||
|
|
283e8d6b7b | ||
|
|
901f4c80c4 | ||
|
|
0064649631 | ||
|
|
5ba137703c | ||
|
|
6983196ad6 | ||
|
|
a22e5f6858 | ||
|
|
0c6ef16ca9 | ||
|
|
7f6e673750 | ||
|
|
74366c3341 | ||
|
|
5bfed03c97 | ||
|
|
d4ca4129a0 | ||
|
|
a396967e3a | ||
|
|
bb03f0fba3 | ||
|
|
02481e0daa | ||
|
|
7107a570b4 | ||
|
|
b1b7b60a55 | ||
|
|
2228d64644 | ||
|
|
fdbcecab0b | ||
|
|
e5fdf9ea96 | ||
|
|
3b053e055b | ||
|
|
90702d6d15 | ||
|
|
849d005b2b | ||
|
|
8790e47013 | ||
|
|
f27874d762 | ||
|
|
df7341ee2b | ||
|
|
4d735a6631 | ||
|
|
bebd7c146e | ||
|
|
4fa2a719c5 | ||
|
|
0d824eee86 | ||
|
|
eb566de2d3 | ||
|
|
a4fb6cb206 | ||
|
|
7e73a336fb | ||
|
|
85b83fddb1 | ||
|
|
55fd6e7150 | ||
|
|
7ea32aefce | ||
|
|
ef94a37193 | ||
|
|
61a2af5e8b | ||
|
|
eb3b1fa54b | ||
|
|
f1393b76f3 | ||
|
|
f369347b73 | ||
|
|
1a3e37d791 | ||
|
|
a9f92a6e31 | ||
|
|
6f793cfe60 | ||
|
|
fcb0b69df6 | ||
|
|
822e4814d1 | ||
|
|
32966f975d | ||
|
|
10c070abd6 | ||
|
|
60299362ed | ||
|
|
baab9b26b7 | ||
|
|
fbd61a676d | ||
|
|
f21f6a8866 | ||
|
|
c8a44d836f | ||
|
|
b80d743dab | ||
|
|
eeeb81d0cd | ||
|
|
234e15320e | ||
|
|
154cbf7c95 | ||
|
|
3f4e7cb45c | ||
|
|
11d481252d | ||
|
|
2e8f58ac41 | ||
|
|
5cd7eade6d | ||
|
|
b2d4917ebe | ||
|
|
d96435c72b | ||
|
|
95784d018f | ||
|
|
448bef7c38 | ||
|
|
69e737de3d | ||
|
|
afeecb6c28 | ||
|
|
69eee996ac | ||
|
|
209dfeacb8 | ||
|
|
b2b60a6b94 | ||
|
|
e11703d915 | ||
|
|
8df901cb24 | ||
|
|
938fda53e2 | ||
|
|
e7ffa45882 | ||
|
|
607542a559 | ||
|
|
b9e4d2b2ba | ||
|
|
473b493ab0 | ||
|
|
9eb1f34cbf | ||
|
|
7a18b4bf34 | ||
|
|
6c64372b85 | ||
|
|
3a4e2f8071 | ||
|
|
53471ce33b | ||
|
|
f1d7eb52c6 | ||
|
|
cf7530848e | ||
|
|
5ae5d5a3af | ||
|
|
bcc7f6d569 | ||
|
|
e293300430 | ||
|
|
4cafcc96f6 | ||
|
|
85de4e51e2 | ||
|
|
d4e2b09c37 | ||
|
|
5ea5b2e89a | ||
|
|
8564f96d1f | ||
|
|
b85a788897 | ||
|
|
88a60e08b3 | ||
|
|
4c612a1e29 | ||
|
|
603c451818 | ||
|
|
2662793bd6 | ||
|
|
d581098eeb | ||
|
|
edbc9e4fdc | ||
|
|
d2ba781702 | ||
|
|
a1f77d0e1a | ||
|
|
9c42c54644 | ||
|
|
3841a7531f | ||
|
|
3b43b391b5 | ||
|
|
c64775ef71 | ||
|
|
4c96faa6d8 | ||
|
|
19e7f0fdd4 | ||
|
|
02811ea6b4 | ||
|
|
2ce971a831 | ||
|
|
80788529b5 | ||
|
|
05fb1f1142 | ||
|
|
8d2dda76fa | ||
|
|
c1789e0525 | ||
|
|
6a9e38e7bd | ||
|
|
848a927122 | ||
|
|
2b30f8820c | ||
|
|
318d2159d1 | ||
|
|
1a8d472f35 | ||
|
|
f9d6b48027 | ||
|
|
d82bccbb17 | ||
|
|
9c17c8562d | ||
|
|
0d6be7ac22 | ||
|
|
f9266c8518 | ||
|
|
b7dc8e8e41 | ||
|
|
b642f54526 | ||
|
|
36987d6d37 | ||
|
|
082adfe732 | ||
|
|
abc0a6d26f | ||
|
|
c3559ecd61 | ||
|
|
8e09ede76d | ||
|
|
25c4b1ad75 | ||
|
|
7d45e0dd46 | ||
|
|
aac7f54e89 | ||
|
|
62e62b3a7c | ||
|
|
ab09f04cfe | ||
|
|
a6fd8ba9ba | ||
|
|
0cf079efea | ||
|
|
3433699e6e | ||
|
|
52f603c6b3 | ||
|
|
d18980c960 | ||
|
|
08800445eb | ||
|
|
de1f8bce5e | ||
|
|
0368ce547b | ||
|
|
7b14e48d0d | ||
|
|
c456f4186e | ||
|
|
ec395a7aa2 | ||
|
|
f1f59e148f | ||
|
|
37a5bbb965 | ||
|
|
d8c0e24651 | ||
|
|
f07d14ddb1 | ||
|
|
63b05e24e8 | ||
|
|
b0e2a510ed | ||
|
|
9620c1d30e | ||
|
|
c7259554b5 | ||
|
|
c3a7235bf7 | ||
|
|
e5a56da50e | ||
|
|
73baf1113d | ||
|
|
cf5e688e70 | ||
|
|
93d600b5c9 | ||
|
|
7fe8e6cfc2 | ||
|
|
84077b3b4b | ||
|
|
027c936a26 | ||
|
|
f5ad5e57fb | ||
|
|
2357d6932c | ||
|
|
33773a8eb9 | ||
|
|
21638a06b1 | ||
|
|
ec7d406cd4 | ||
|
|
c6456a9c03 | ||
|
|
cfd3f9da90 | ||
|
|
dd45c80062 | ||
|
|
40b6b0ef8c | ||
|
|
dae787c199 | ||
|
|
5ca37e7d39 | ||
|
|
14597334dc | ||
|
|
403776dc2a | ||
|
|
6609a401b9 | ||
|
|
17e9790792 | ||
|
|
def7b1a70c | ||
|
|
c86758849a | ||
|
|
afb7fa4eef | ||
|
|
f59a0b73ce | ||
|
|
8441d4a310 | ||
|
|
adca1f70b1 | ||
|
|
cc1962b882 | ||
|
|
6b15689813 | ||
|
|
51f6be041f | ||
|
|
e49d2b9bd2 | ||
|
|
c6b2119c81 | ||
|
|
c2e8f24c7c | ||
|
|
5c3617b9e9 | ||
|
|
9a812b5fef | ||
|
|
882466a730 | ||
|
|
11f1c6da5a | ||
|
|
b92be8a02a | ||
|
|
c81d5f35e1 | ||
|
|
fb0efe832c | ||
|
|
495f729347 | ||
|
|
7654f14f8c | ||
|
|
0e060b7a7a | ||
|
|
1ccaee141c | ||
|
|
8a8552f617 | ||
|
|
ad407249fe | ||
|
|
faffb9a15a | ||
|
|
547b2a5828 | ||
|
|
87e68fca36 | ||
|
|
f32faad415 | ||
|
|
a3aff2f913 | ||
|
|
8730f2cf25 | ||
|
|
65693b8b80 | ||
|
|
f5edd720bd | ||
|
|
6189c1f553 | ||
|
|
6b4084c69f | ||
|
|
b596783bd9 | ||
|
|
b58450413e | ||
|
|
d099546787 | ||
|
|
0762f57d80 | ||
|
|
e4d06ae3ea | ||
|
|
d259ef476e | ||
|
|
5e03246e4e | ||
|
|
40b5b3068b | ||
|
|
e8bb779909 | ||
|
|
6ee96ffdb5 | ||
|
|
0539daa364 | ||
|
|
669dcf2c25 | ||
|
|
9123120c08 | ||
|
|
bf16d3da30 | ||
|
|
2df5b0b031 | ||
|
|
af4544c869 | ||
|
|
1f821a8539 | ||
|
|
996e940942 | ||
|
|
6338029b74 | ||
|
|
15794f5cad | ||
|
|
164fe8ce93 | ||
|
|
e1ab868059 | ||
|
|
022a7fe638 | ||
|
|
32026456ba | ||
|
|
0062c82c90 | ||
|
|
4116b8cbfb | ||
|
|
adbf8d2856 | ||
|
|
a87eaf71f6 | ||
|
|
1d1bef36c9 |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# Lines starting with '#' are comments.
|
||||
# Each line is a case-sensitive file pattern followed by one or more owners.
|
||||
# Order is important. The last matching pattern has the most precedence.
|
||||
# More information: https://docs.github.com/en/articles/about-code-owners
|
||||
#
|
||||
# Please mirror the repository's file hierarchy in case-sensitive lexicographic
|
||||
# order.
|
||||
|
||||
# Default owners
|
||||
* @glessard @lorentey @milseman
|
||||
|
||||
# Swift CI configuration files
|
||||
.swiftci/ @shahmishal
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Create PR to merge release branch into the main branch
|
||||
# Changes should land on the earliest release branch they will need to ship on and then be automatically forwarded to main
|
||||
permissions:
|
||||
contents: read
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 9 * * *'
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
create_merge_pr:
|
||||
name: Create PR to merge release branch into main branch
|
||||
uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.18
|
||||
with:
|
||||
base_branch: main
|
||||
head_branch: release/1.9.x
|
||||
pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on main. If yes, merge the PR. Otherwise revert changes that should not be included on this branch.
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
if: (github.event_name == 'schedule' && github.repository == 'apple/swift-system') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Create PR to merge the previous release branch into the current release branch
|
||||
# Changes should land on the earliest release branch they will need to ship on and then be automatically forwarded to later release branches and main
|
||||
permissions:
|
||||
contents: read
|
||||
on:
|
||||
schedule:
|
||||
# An hour before automerge_to_main.yml. Runs at the same time would collide due to <HH-MM> branch naming.
|
||||
- cron: '0 8 * * *'
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
create_merge_pr:
|
||||
name: Create PR to merge previous release branch into current release branch
|
||||
uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.18
|
||||
with:
|
||||
base_branch: release/1.9.x
|
||||
head_branch: release/1.8.x
|
||||
pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on this release branch. If yes, merge the PR. Otherwise revert changes that should not be included on this branch.
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
if: (github.event_name == 'schedule' && github.repository == 'apple/swift-system') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork
|
||||
@@ -0,0 +1,116 @@
|
||||
name: Pull request
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, ready_for_review]
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.18
|
||||
with:
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
|
||||
linux_os_versions: '["noble", "jammy", "focal"]'
|
||||
linux_exclude_swift_versions: |
|
||||
[
|
||||
{"swift_version": "6.1"},
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.4"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_macos_checks: true
|
||||
macos_exclude_xcode_versions: |
|
||||
[
|
||||
{"xcode_version": "swift_6.1"},
|
||||
]
|
||||
windows_exclude_swift_versions: |
|
||||
[
|
||||
{"swift_version": "6.1"},
|
||||
]
|
||||
enable_linux_static_sdk_build: true
|
||||
linux_static_sdk_exclude_swift_versions: |
|
||||
[
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_wasm_sdk_build: true
|
||||
wasm_exclude_swift_versions: |
|
||||
[
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_android_sdk_build: true
|
||||
enable_android_sdk_checks: true
|
||||
enable_freebsd_checks: true
|
||||
|
||||
build-abi-stable:
|
||||
name: Build ABI Stable
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.18
|
||||
with:
|
||||
enable_linux_checks: false
|
||||
enable_macos_checks: true
|
||||
macos_exclude_xcode_versions: |
|
||||
[
|
||||
{"xcode_version": "swift_6.1"},
|
||||
]
|
||||
enable_windows_checks: false
|
||||
# Only build
|
||||
macos_build_command: "xcrun swift build --build-tests"
|
||||
# Enable availability to match ABI stable verion of system.
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE"
|
||||
|
||||
cmake_build:
|
||||
name: CMake Validation
|
||||
runs-on: ubuntu-latest
|
||||
container: swiftlang/swift:nightly-main-noble
|
||||
steps:
|
||||
- name: Copy Sources
|
||||
uses: actions/checkout@v6
|
||||
- name: Install Dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
apt update && apt install -y curl ninja-build jq
|
||||
curl -fsSL "https://github.com/Kitware/CMake/releases/download/v4.0.2/cmake-4.0.2-linux-$(uname -m).tar.gz" \
|
||||
| tar --strip-components=1 -xz -C /usr/local
|
||||
- name: Configure Project
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p build/.cmake/api/v1/query
|
||||
touch build/.cmake/api/v1/query/codemodel-v2
|
||||
cmake -G 'Ninja' -B build -S . -DCMAKE_C_COMPILER=clang -DCMAKE_Swift_COMPILER=swiftc -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=YES
|
||||
- name: Validate CMake File Lists
|
||||
shell: bash
|
||||
run: |
|
||||
swift package describe --type json > /tmp/swiftpm.json
|
||||
cat build/.cmake/api/v1/reply/target-SystemPackage-*.json > /tmp/cmake.json
|
||||
jq '.targets[] | select(.name == "SystemPackage") | .sources[]' /tmp/swiftpm.json | sort > /tmp/swiftpm-list.txt
|
||||
jq '.sources[].path[15:]' /tmp/cmake.json | sort > /tmp/cmake-list.txt
|
||||
comm -23 /tmp/swiftpm-list.txt /tmp/cmake-list.txt > /tmp/missing.txt
|
||||
if [ -s /tmp/missing.txt ]; then
|
||||
echo "::error::SystemPackage CMakeLists.txt does not match SwiftPM. Missing sources:"
|
||||
cat /tmp/missing.txt
|
||||
exit 1
|
||||
fi
|
||||
echo "::notice::SystemPackage CMakeLists.txt matches SwiftPM"
|
||||
- name: Build Project with CMake
|
||||
shell: bash
|
||||
run: cmake --build build
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.18
|
||||
with:
|
||||
license_header_check_project_name: "Swift.org"
|
||||
# https://github.com/apple/swift-system/issues/224
|
||||
docs_check_enabled: false
|
||||
unacceptable_language_check_enabled: false
|
||||
license_header_check_enabled: false
|
||||
format_check_enabled: false
|
||||
python_lint_check_enabled: false
|
||||
+3
-2
@@ -2,7 +2,8 @@
|
||||
/.swiftpm
|
||||
/.build
|
||||
/Packages
|
||||
swift-system.xcodeproj
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
.*.sw?
|
||||
.docc-build
|
||||
/.swiftpm
|
||||
.docc-build
|
||||
@@ -0,0 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [SystemPackage]
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.10-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.9-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
macOSSwiftPackageJob {
|
||||
swift_version = "6.0"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
nightly_docker_tag = "nightly-6.0-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
macOSSwiftPackageJob {
|
||||
swift_version = "main"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
nightly_docker_tag = "nightly-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
WindowsSwiftPackageWithDockerImageJob {
|
||||
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
|
||||
repo = "swift-system"
|
||||
branch = "main"
|
||||
sub_dir = "swift-system"
|
||||
label = "windows-server-2019"
|
||||
}
|
||||
+5
-1
@@ -7,10 +7,14 @@ Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16.0)
|
||||
cmake_minimum_required(VERSION 3.29)
|
||||
project(SwiftSystem
|
||||
LANGUAGES C Swift)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
set(CMAKE_Swift_LANGUAGE_VERSION 6)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
+152
-38
@@ -1,43 +1,157 @@
|
||||
// swift-tools-version:5.2
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
// swift-tools-version:6.2
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
struct Available {
|
||||
var name: String
|
||||
var version: String
|
||||
var osAvailability: String
|
||||
var sourceAvailability: String
|
||||
|
||||
init(
|
||||
_ version: String,
|
||||
_ osAvailability: String
|
||||
) {
|
||||
self.name = "System"
|
||||
self.version = version
|
||||
self.osAvailability = osAvailability
|
||||
self.sourceAvailability = "macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0"
|
||||
}
|
||||
|
||||
var swiftSetting: SwiftSetting {
|
||||
#if SYSTEM_ABI_STABLE
|
||||
// Use availability matching Darwin API.
|
||||
let availability = self.osAvailability
|
||||
#else
|
||||
// Use availability matching SwiftPM default.
|
||||
let availability = self.sourceAvailability
|
||||
#endif
|
||||
return .enableExperimentalFeature(
|
||||
"AvailabilityMacro=\(self.name) \(version):\(availability)")
|
||||
}
|
||||
}
|
||||
|
||||
let availability: [Available] = [
|
||||
Available("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
|
||||
|
||||
Available("0.0.2", "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0"),
|
||||
|
||||
Available("0.0.3", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
|
||||
Available("1.1.0", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
|
||||
|
||||
Available("1.1.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
Available("1.2.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
|
||||
Available("1.2.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
Available("1.3.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
|
||||
Available("1.3.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
Available("1.3.2", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
Available("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
|
||||
Available("1.7.0", "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0"),
|
||||
|
||||
Available("1.9.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
|
||||
Available("199", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
]
|
||||
|
||||
let swiftSettingsAvailability = availability.map(\.swiftSetting)
|
||||
|
||||
#if SYSTEM_CI
|
||||
let swiftSettingsCI: [SwiftSetting] = [
|
||||
.unsafeFlags(["-require-explicit-availability=error"]),
|
||||
]
|
||||
#else
|
||||
let swiftSettingsCI: [SwiftSetting] = []
|
||||
#endif
|
||||
|
||||
let swiftSettings = swiftSettingsAvailability + swiftSettingsCI + [
|
||||
.define(
|
||||
"SYSTEM_PACKAGE_DARWIN",
|
||||
.when(platforms: [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS])),
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug)),
|
||||
.enableExperimentalFeature("Lifetimes"),
|
||||
.enableUpcomingFeature("MemberImportVisibility"),
|
||||
]
|
||||
|
||||
let cSettings: [CSetting] = [
|
||||
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])),
|
||||
]
|
||||
|
||||
#if SYSTEM_ABI_STABLE
|
||||
let platforms: [SupportedPlatform] = [
|
||||
.macOS("26"),
|
||||
.iOS("26"),
|
||||
.watchOS("26"),
|
||||
.tvOS("26"),
|
||||
.visionOS("26"),
|
||||
]
|
||||
#else
|
||||
let platforms: [SupportedPlatform]? = nil
|
||||
#endif
|
||||
|
||||
#if os(Linux)
|
||||
let filesToExclude = ["CMakeLists.txt"]
|
||||
#else
|
||||
let filesToExclude = ["CMakeLists.txt", "IORing"]
|
||||
#endif
|
||||
|
||||
#if os(Linux)
|
||||
let testsToExclude:[String] = []
|
||||
#else
|
||||
let testsToExclude = ["IORequestTests.swift", "IORingTests.swift"]
|
||||
#endif
|
||||
|
||||
let package = Package(
|
||||
name: "swift-system",
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: []),
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: ["CSystem"],
|
||||
path: "Sources/System",
|
||||
cSettings: [
|
||||
.define("_CRT_SECURE_NO_WARNINGS")
|
||||
],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug))
|
||||
]),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE")
|
||||
]),
|
||||
]
|
||||
name: "swift-system",
|
||||
platforms: platforms,
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: [],
|
||||
exclude: ["CMakeLists.txt"],
|
||||
cSettings: cSettings),
|
||||
.systemLibrary(
|
||||
name: "CSystemStatFS",
|
||||
path: "Sources/CSystemStatFS"),
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: [
|
||||
"CSystem",
|
||||
.target(name: "CSystemStatFS", condition: .when(platforms: [.linux])),
|
||||
],
|
||||
path: "Sources/System",
|
||||
exclude: filesToExclude,
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
exclude: testsToExclude,
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
// Builds a SystemPackage consumer with MemberImportVisibility enabled.
|
||||
// Fails if a C member of a vended type is attributed to the CSystem module.
|
||||
.testTarget(
|
||||
name: "MemberImportVisibility",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]),
|
||||
],
|
||||
swiftLanguageModes: [.v6]
|
||||
)
|
||||
@@ -0,0 +1,985 @@
|
||||
# Stat for Swift System
|
||||
|
||||
* Proposal: [SYS-0006](0006-system-stat.md)
|
||||
* Authors: [Jonathan Flat](https://github.com/jrflat), [Michael Ilseman](https://github.com/milseman), [Rauhul Varma](https://github.com/rauhul)
|
||||
* Review Manager: TBD
|
||||
* Status: **Awaiting review**
|
||||
* Implementation: [apple/swift-system#256](https://github.com/apple/swift-system/pull/256)
|
||||
* Review: ([pitch](https://forums.swift.org/t/pitch-stat-types-for-swift-system/81616))
|
||||
|
||||
#### Revision history
|
||||
|
||||
* **v1** Initial version
|
||||
* **v2** Moved `UTCClock.Instant` properties to **Future Directions** and exposed C `timespec` properties. Expanded **Alternatives Considered** for `Stat` name and time properties.
|
||||
* **v3** Add `init(_:)` to wrapper types, clarify `FileType(rawValue:)` behavior with `S_IFMT`, rename `.pipe` to `.fifo`, mention `ALLPERMS` instead of `0o7777`, explain "is"-less flag names in **Alternatives Considered**, fix conditionals for FreeBSD flags, clarify that `.type` and `.permissions` depend on `.mode`, clarify that size property behaviors are file system-dependent.
|
||||
|
||||
## Introduction
|
||||
|
||||
This proposal introduces a Swift-native `Stat` type to the System library, providing comprehensive access to file metadata on Unix-like platforms through type-safe, platform-aware APIs that wrap the C `stat` types and system calls.
|
||||
|
||||
## Motivation
|
||||
|
||||
Currently, Swift developers who want to work with the file system's lowest level API can only do so through bridged C interfaces. These interfaces lack type safety and require writing non-idiomatic Swift, leading to errors and confusion.
|
||||
|
||||
The goal of the `Stat` type is to provide a faithful and performant Swift wrapper around the underlying C system calls while adding type safety, platform abstraction, and improved discoverability/usability with clear naming. For more on the motivation behind System, see [https://www.swift.org/blog/swift-system](https://www.swift.org/blog/swift-system)
|
||||
|
||||
## Proposed solution
|
||||
|
||||
This proposal adds a `struct Stat` that is available on Unix-like platforms. See discussion on Windows-specific API in **Future Directions**.
|
||||
|
||||
### `Stat` - File Metadata
|
||||
A Swift wrapper around the C `stat` struct that provides type-safe access to file metadata:
|
||||
|
||||
```swift
|
||||
// Get file status from path String
|
||||
let stat = try Stat("/path/to/file")
|
||||
|
||||
// From FileDescriptor
|
||||
let stat = try fd.stat()
|
||||
|
||||
// From FilePath
|
||||
let stat = try filePath.stat()
|
||||
|
||||
// `followTargetSymlink: true` (default) behaves like `stat()`
|
||||
// `followTargetSymlink: false` behaves like `lstat()`
|
||||
let stat = try symlinkPath.stat(followTargetSymlink: false)
|
||||
|
||||
// Supply flags and optional file descriptor to use the `fstatat()` variant
|
||||
let stat = try Stat("path/to/file", relativeTo: fd, flags: .symlinkNoFollow)
|
||||
|
||||
print("Size: \(stat.size) bytes")
|
||||
print("Size allocated: \(stat.sizeAllocated) bytes")
|
||||
print("Type: \(stat.type)") // .regular, .directory, .symbolicLink, etc.
|
||||
print("Permissions: \(stat.permissions)")
|
||||
print("Modified: \(stat.modificationTime)")
|
||||
|
||||
// Platform-specific information when available
|
||||
#if canImport(Darwin) || os(FreeBSD)
|
||||
print("Creation time: \(stat.creationTime)")
|
||||
#endif
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
All initializers throw the existing `Errno` type:
|
||||
|
||||
```swift
|
||||
do {
|
||||
let stat = try Stat("/nonexistent/file")
|
||||
} catch Errno.noSuchFileOrDirectory {
|
||||
print("File not found")
|
||||
} catch {
|
||||
print("Other error: \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
These initializers use a typed `throws(Errno)` and require Swift 6.0 or later.
|
||||
|
||||
## Detailed design
|
||||
|
||||
See the **Appendix** section at the end of this proposal for a table view of Swift API to C mappings.
|
||||
|
||||
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability, except `Stat`'s `==` and `hash(into:)`, which are ordinary `public` API.
|
||||
|
||||
### FileType
|
||||
|
||||
This proposal introduces `FileType` and `FileMode` types to represent `mode_t` values from the C `stat` struct. The type and permissions of a `FileMode` can be modified for convenience, and `FileMode` handles the respective bit masking.
|
||||
|
||||
```swift
|
||||
/// A file type matching those contained in a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw file-type bits from the C mode.
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed file type from the raw C `mode_t`.
|
||||
///
|
||||
/// - Note: This initializer stores the `rawValue` directly and **does not**
|
||||
/// mask the value with `S_IFMT`. If the supplied `rawValue` contains bits
|
||||
/// outside of the `S_IFMT` mask, the resulting `FileType` will not compare
|
||||
/// equal to constants like `.directory` and `.symbolicLink`, which may
|
||||
/// be unexpected.
|
||||
///
|
||||
/// If you're unsure whether the `mode_t` contains bits outside of `S_IFMT`,
|
||||
/// you can use `FileMode(rawValue:)` instead to get a strongly-typed
|
||||
/// `FileMode`, then call `.type` to get the properly masked `FileType`.
|
||||
public init(rawValue: CInterop.Mode)
|
||||
|
||||
/// Directory
|
||||
///
|
||||
/// The corresponding C constant is `S_IFDIR`.
|
||||
public static var directory: FileType { get }
|
||||
|
||||
/// Character special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFCHR`.
|
||||
public static var characterSpecial: FileType { get }
|
||||
|
||||
/// Block special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFBLK`.
|
||||
public static var blockSpecial: FileType { get }
|
||||
|
||||
/// Regular file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFREG`.
|
||||
public static var regular: FileType { get }
|
||||
|
||||
/// FIFO (or named pipe)
|
||||
///
|
||||
/// The corresponding C constant is `S_IFIFO`.
|
||||
public static var fifo: FileType { get }
|
||||
|
||||
/// Symbolic link
|
||||
///
|
||||
/// The corresponding C constant is `S_IFLNK`.
|
||||
public static var symbolicLink: FileType { get }
|
||||
|
||||
/// Socket
|
||||
///
|
||||
/// The corresponding C constant is `S_IFSOCK`.
|
||||
public static var socket: FileType { get }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Whiteout file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFWHT`.
|
||||
public static var whiteout: FileType { get }
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
### FileMode
|
||||
```swift
|
||||
/// A strongly-typed file mode representing a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C mode.
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed `FileMode` from the raw C value.
|
||||
public init(rawValue: CInterop.Mode)
|
||||
|
||||
/// Creates a strongly-typed `FileMode` from the raw C value.
|
||||
public init(_ rawValue: CInterop.Mode)
|
||||
|
||||
/// Creates a `FileMode` from the given file type and permissions.
|
||||
///
|
||||
/// - Note: This initializer masks the inputs with their respective bit masks.
|
||||
public init(type: FileType, permissions: FilePermissions)
|
||||
|
||||
/// The file's type, from the mode's file-type bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the file-type bit mask `S_IFMT`.
|
||||
public var type: FileType { get set }
|
||||
|
||||
/// The file's permissions, from the mode's permission bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the permissions bit mask `ALLPERMS`.
|
||||
public var permissions: FilePermissions { get set }
|
||||
}
|
||||
```
|
||||
|
||||
### Supporting ID Types
|
||||
|
||||
This proposal also uses new `DeviceID`, `UserID`, `GroupID`, and `Inode` types to represent the respective C data types found in `stat`. These are strongly-typed structs instead of `CInterop` typealiases to prevent ambiguity in future System implementations and to allow for added functionality.
|
||||
|
||||
For example, with an implementation of `chown`, a developer might accidentally misplace user and group parameters with no warning if both were a typealias of the underlying `unsigned int`. Furthermore, a strongly-typed `DeviceID` would allow us to add functionality such as a `makedev` function, or `major` and `minor` getters.
|
||||
|
||||
For now, we define the following for use in `Stat`.
|
||||
|
||||
```swift
|
||||
@frozen
|
||||
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.UserID
|
||||
public init(rawValue: CInterop.UserID)
|
||||
public init(_ rawValue: CInterop.UserID)
|
||||
}
|
||||
|
||||
@frozen
|
||||
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.GroupID
|
||||
public init(rawValue: CInterop.GroupID)
|
||||
public init(_ rawValue: CInterop.GroupID)
|
||||
}
|
||||
|
||||
@frozen
|
||||
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.DeviceID
|
||||
public init(rawValue: CInterop.DeviceID)
|
||||
public init(_ rawValue: CInterop.DeviceID)
|
||||
}
|
||||
|
||||
@frozen
|
||||
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.Inode
|
||||
public init(rawValue: CInterop.Inode)
|
||||
public init(_ rawValue: CInterop.Inode)
|
||||
}
|
||||
```
|
||||
|
||||
Each type stores a `CInterop` typealias to ensure an appropriate `rawValue` for the current platform. Added functionality is outside the scope of this proposal and will be included in a future proposal.
|
||||
|
||||
### FileFlags
|
||||
|
||||
A new `FileFlags` type represents file-specific flags found in a `stat` struct on Darwin, FreeBSD, and OpenBSD. This type would also be useful for an implementation of `chflags()`.
|
||||
|
||||
```swift
|
||||
/// File-specific flags found in the `st_flags` property of a `stat` struct
|
||||
/// or used as input to `chflags()`.
|
||||
///
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@frozen
|
||||
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
public let rawValue: CInterop.FileFlags
|
||||
|
||||
/// Creates a strongly-typed `FileFlags` from the raw C value.
|
||||
public init(rawValue: CInterop.FileFlags)
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
/// Do not dump the file during backups.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NODUMP`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var noDump: FileFlags { get }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_IMMUTABLE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var userImmutable: FileFlags { get }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `UF_APPEND`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var userAppend: FileFlags { get }
|
||||
|
||||
/// File has been archived.
|
||||
///
|
||||
/// The corresponding C constant is `SF_ARCHIVED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var archived: FileFlags { get }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_IMMUTABLE`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var systemImmutable: FileFlags { get }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `SF_APPEND`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var systemAppend: FileFlags { get }
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Directory is opaque when viewed through a union mount.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OPAQUE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var opaque: FileFlags { get }
|
||||
|
||||
/// File should not be displayed in a GUI.
|
||||
///
|
||||
/// The corresponding C constant is `UF_HIDDEN`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var hidden: FileFlags { get }
|
||||
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_NOUNLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var systemNoUnlink: FileFlags { get }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// File is compressed at the file system level.
|
||||
///
|
||||
/// The corresponding C constant is `UF_COMPRESSED`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
public static var compressed: FileFlags { get }
|
||||
|
||||
/// File is tracked for the purpose of document IDs.
|
||||
///
|
||||
/// The corresponding C constant is `UF_TRACKED`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var tracked: FileFlags { get }
|
||||
|
||||
/// File requires an entitlement for reading and writing.
|
||||
///
|
||||
/// The corresponding C constant is `UF_DATAVAULT`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var dataVault: FileFlags { get }
|
||||
|
||||
/// File requires an entitlement for writing.
|
||||
///
|
||||
/// The corresponding C constant is `SF_RESTRICTED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var restricted: FileFlags { get }
|
||||
|
||||
/// File is a firmlink.
|
||||
///
|
||||
/// Firmlinks are used by macOS to create transparent links between
|
||||
/// the read-only system volume and writable data volume. For example,
|
||||
/// the `/Applications` folder on the system volume is a firmlink to
|
||||
/// the `/Applications` folder on the data volume, allowing the user
|
||||
/// to see both system- and user-installed applications in a single folder.
|
||||
///
|
||||
/// The corresponding C constant is `SF_FIRMLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var firmlink: FileFlags { get }
|
||||
|
||||
/// File is a dataless placeholder (content is stored remotely).
|
||||
///
|
||||
/// The system will attempt to materialize the file when accessed according to
|
||||
/// the dataless file materialization policy of the accessing thread or process.
|
||||
/// See `getiopolicy_np(3)`.
|
||||
///
|
||||
/// The corresponding C constant is `SF_DATALESS`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
public static var dataless: FileFlags { get }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NOUNLINK`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var userNoUnlink: FileFlags { get }
|
||||
|
||||
/// File has the Windows offline attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_OFFLINE` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OFFLINE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var offline: FileFlags { get }
|
||||
|
||||
/// File is read-only.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_READONLY` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_READONLY`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var readOnly: FileFlags { get }
|
||||
|
||||
/// File contains a Windows reparse point.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_REPARSE_POINT` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_REPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var reparse: FileFlags { get }
|
||||
|
||||
/// File is sparse.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SPARSE_FILE` attribute,
|
||||
/// or to indicate a sparse file.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var sparse: FileFlags { get }
|
||||
|
||||
/// File has the Windows system attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SYSTEM` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SYSTEM`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var system: FileFlags { get }
|
||||
|
||||
/// File is a snapshot.
|
||||
///
|
||||
/// The corresponding C constant is `SF_SNAPSHOT`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var snapshot: FileFlags { get }
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
### Stat
|
||||
|
||||
`Stat` can be initialized from a `FilePath`, `UnsafePointer<CChar>`, or `FileDescriptor`. This proposal also includes functions on `FileDescriptor` and `FilePath` for creating a `Stat` object, seen in the section below.
|
||||
|
||||
The initializer accepting a `FileDescriptor` corresponds to `fstat()`. If the file descriptor points to a symlink, this will return information about the symlink itself.
|
||||
|
||||
In the non-`FileDescriptor` case, one form of the initializer takes a `followTargetSymlink: Bool = true` parameter. The default `true` corresponds to `stat()` and will follow a symlink at the end of the path. Setting `followTargetSymlink: false` corresponds to `lstat()` and will return information about the symlink itself.
|
||||
|
||||
The other form of the initializer receives a path, which can be optionally resolved against a given file descriptor, and a set of `Stat.Flags`. These APIs correspond to the `fstatat()` system call and use a default file descriptor of `AT_FDCWD` if one isn't supplied.
|
||||
|
||||
```swift
|
||||
/// A Swift wrapper of the C `stat` struct.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C `stat` struct.
|
||||
public var rawValue: CInterop.Stat
|
||||
|
||||
/// Creates a Swift `Stat` from the raw C struct.
|
||||
public init(rawValue: CInterop.Stat)
|
||||
|
||||
// MARK: Stat.Flags
|
||||
|
||||
/// Flags representing those passed to `fstatat()`.
|
||||
@frozen
|
||||
public struct Flags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a strongly-typed `Stat.Flags` from raw C flags.
|
||||
public init(rawValue: CInt)
|
||||
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW`.
|
||||
public static var symlinkNoFollow: Flags { get }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
/// If _any_ symbolic link is encountered during path resolution, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW_ANY`.
|
||||
/// - Note: Only available on Darwin.
|
||||
public static var symlinkNoFollowAny: Flags { get }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// If the path does not reside in the hierarchy beneath the starting directory, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_RESOLVE_BENEATH`.
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
@available(macOS 26.0, iOS 26.0, tvOS 26.0, watchOS 26.0, visionOS 26.0, *)
|
||||
public static var resolveBeneath: Flags { get }
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD) || os(Linux) || os(Android)
|
||||
/// If the path is an empty string (or `NULL` since Linux 6.11),
|
||||
/// return information about the given file descriptor.
|
||||
///
|
||||
/// The corresponding C constant is `AT_EMPTY_PATH`.
|
||||
/// - Note: Only available on FreeBSD, Linux, and Android.
|
||||
public static var emptyPath: Flags { get }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from a `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// ID of device containing file
|
||||
///
|
||||
/// The corresponding C property is `st_dev`.
|
||||
public var deviceID: DeviceID { get set }
|
||||
|
||||
/// Inode number
|
||||
///
|
||||
/// The corresponding C property is `st_ino`.
|
||||
public var inode: Inode { get set }
|
||||
|
||||
/// File mode
|
||||
///
|
||||
/// The corresponding C property is `st_mode`.
|
||||
public var mode: FileMode { get set }
|
||||
|
||||
/// File type for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.type`. Modifying this
|
||||
/// property will update the underlying `st_mode` accordingly.
|
||||
public var type: FileType { get set }
|
||||
|
||||
/// File permissions for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.permissions`. Modifying
|
||||
/// this property will update the underlying `st_mode` accordingly.
|
||||
public var permissions: FilePermissions { get set }
|
||||
|
||||
/// Number of hard links
|
||||
///
|
||||
/// The corresponding C property is `st_nlink`.
|
||||
public var linkCount: Int { get set }
|
||||
|
||||
/// User ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_uid`.
|
||||
public var userID: UserID { get set }
|
||||
|
||||
/// Group ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_gid`.
|
||||
public var groupID: GroupID { get set }
|
||||
|
||||
/// Device ID (if special file)
|
||||
///
|
||||
/// For character or block special files, the returned `DeviceID` may have
|
||||
/// meaningful `.major` and `.minor` values. For non-special files, this
|
||||
/// property is usually meaningless and often set to 0.
|
||||
///
|
||||
/// The corresponding C property is `st_rdev`.
|
||||
public var specialDeviceID: DeviceID { get set }
|
||||
|
||||
/// Total size, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_size` field,
|
||||
/// which can have file system-dependent behavior. For example, this property
|
||||
/// can return different values for a file's data fork and resource fork, and some
|
||||
/// file systems report logical size rather than actual disk usage for compressed
|
||||
/// or cloned files.
|
||||
///
|
||||
/// The corresponding C property is `st_size`.
|
||||
public var size: Int64 { get set }
|
||||
|
||||
/// Block size for filesystem I/O, in bytes
|
||||
///
|
||||
/// The corresponding C property is `st_blksize`.
|
||||
public var preferredIOBlockSize: Int { get set }
|
||||
|
||||
/// Number of 512-byte blocks allocated
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file system-dependent behavior.
|
||||
///
|
||||
/// The corresponding C property is `st_blocks`.
|
||||
public var blocksAllocated: Int64 { get set }
|
||||
|
||||
/// Total size allocated, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file system-dependent behavior.
|
||||
///
|
||||
/// - Note: Calculated as `512 * blocksAllocated`.
|
||||
public var sizeAllocated: Int64 { get }
|
||||
|
||||
// NOTE: "st_" property names are used for the `timespec` properties so
|
||||
// we can reserve `accessTime`, `modificationTime`, etc. for potential
|
||||
// `UTCClock.Instant` properties in the future.
|
||||
// See Future Directions for more info.
|
||||
|
||||
/// Time of last access, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin).
|
||||
public var st_atim: timespec { get set }
|
||||
|
||||
/// Time of last modification, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin).
|
||||
public var st_mtim: timespec { get set }
|
||||
|
||||
/// Time of last status (inode) change, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin).
|
||||
public var st_ctim: timespec { get set }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Time of file creation, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin).
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
public var st_birthtim: timespec { get set }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// File flags
|
||||
///
|
||||
/// The corresponding C property is `st_flags`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
public var flags: FileFlags { get set }
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number may be used to distinguish between different
|
||||
/// files that have used the same inode over time.
|
||||
///
|
||||
/// The corresponding C property is `st_gen`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
|
||||
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
|
||||
public var generationNumber: UInt64 { get set }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
extension Stat: Equatable {
|
||||
/// Compares the meaningful file-metadata fields of two `Stat` values.
|
||||
///
|
||||
/// Alignment padding and platform reserved/"spare" fields are not compared.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool
|
||||
}
|
||||
|
||||
extension Stat: Hashable {
|
||||
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
|
||||
public func hash(into hasher: inout Hasher)
|
||||
}
|
||||
```
|
||||
|
||||
### FileDescriptor and FilePath Extensions
|
||||
|
||||
```swift
|
||||
extension FileDescriptor {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
public func stat(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
public func stat(
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public func stat(
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public func stat(
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
}
|
||||
```
|
||||
|
||||
### CInterop Extensions
|
||||
|
||||
This proposal extends the existing `CInterop` namespace with platform-appropriate typealiases for the underlying C types. These typealiases are used as the `rawValue` for their strongly-typed representations.
|
||||
|
||||
```swift
|
||||
extension CInterop {
|
||||
public typealias Stat
|
||||
public typealias Inode
|
||||
public typealias UserID
|
||||
public typealias GroupID
|
||||
public typealias DeviceID
|
||||
public typealias FileFlags
|
||||
}
|
||||
```
|
||||
|
||||
## Source compatibility
|
||||
|
||||
This proposal is additive and source-compatible with existing code.
|
||||
|
||||
## ABI compatibility
|
||||
|
||||
This proposal is additive and ABI-compatible with existing code.
|
||||
|
||||
## Implications on adoption
|
||||
|
||||
This feature can be freely adopted and un-adopted in source code with no deployment constraints and without affecting source or ABI compatibility.
|
||||
|
||||
## Future directions
|
||||
|
||||
To remain faithful to the underlying system calls, we don't anticipate extending `Stat`. However, the types introduced in this proposal could serve as the foundation of broader file system APIs in Swift.
|
||||
|
||||
While this proposal does not include `Stat` on Windows, a separate proposal should provide Swift-native wrappers of idiomatic `GetFileInformation` functions with their associated types.
|
||||
|
||||
A more general `FileInfo` API could then build on these OS-specific types to provide an ergonomic, cross-platform abstraction for file metadata. These future cross-platform APIs might be better implemented outside of System, such as in Foundation, the standard library, or somewhere in between. They could provide additional information or convenience features, such as reading and modifying extended attributes or setting file timestamps.
|
||||
|
||||
In the future, more functionality could be added to types such as `DeviceID`.
|
||||
|
||||
### Using `UTCClock.Instant` for time properties
|
||||
|
||||
When the `UTCClock` proposal and code destination is finalized, we could use the `UTCClock.Instant` type for `Stat` time properties:
|
||||
|
||||
```swift
|
||||
extension Stat {
|
||||
/// Time of last access, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin).
|
||||
public var accessTime: UTCClock.Instant { get set }
|
||||
|
||||
/// Time of last modification, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin).
|
||||
public var modificationTime: UTCClock.Instant { get set }
|
||||
|
||||
/// Time of last status (inode) change, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin).
|
||||
public var changeTime: UTCClock.Instant { get set }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Time of file creation, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin).
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
public var creationTime: UTCClock.Instant { get set }
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
We would reserve the more ergonomic `accessTime`, `modificationTime`, etc. names for these future extensions.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### `FileInfo` as the lowest-level type
|
||||
An alternative approach could be to have a more general `FileInfo` type be the lowest level of abstraction provided by the System library. This type would then handle all the `stat` or Windows-specific struct storage and accessors. However, this alternative:
|
||||
|
||||
- Is inconsistent with System's philosophy of providing low-level system abstractions.
|
||||
- Introduces an even larger number of system-specific APIs on each type.
|
||||
- Misses out on the familiarity of the `stat` name. Developers know what to look for and what to expect from this type.
|
||||
|
||||
### Single combined type for both file and file system metadata
|
||||
Combining `Stat` and `StatFS` (separate proposal) into a single type was considered but rejected because file and file system information serve different purposes and are typically needed in different contexts. Storing and/or initializing both `stat` and `statfs` structs unnecessarily reduces performance when one isn't needed.
|
||||
|
||||
### Making `Stat` available on Windows
|
||||
It's possible to make `Stat` available on Windows and use either the non-native `_stat` functions from CRT or populate the information via a separate `GetFileInformation` call. However, many of the `stat` fields are not- or less-applicable on Windows and are treated as such by `_stat`. For instance, `st_uid` is always zero on Windows, `st_ino` has no meaning in FAT, HPFS, or NTFS file systems, and `st_mode` can only specify a regular file, directory, or character special, with the executable bit depending entirely on the file's path extension.
|
||||
|
||||
Rather than forcing Windows file metadata semantics into a cross-platform `Stat` type, we should instead create Windows-specific types that give developers full access to platform-native file metadata. Combined with a higher-level `FileInfo` type that _is_ cross-platform, this gives the best of both low-level and platform-agnostic APIs.
|
||||
|
||||
### Only have `FilePath` and `FileDescriptor` extensions rather than initializers that accept these types
|
||||
While having `.stat()` functions on `FilePath` and `FileDescriptor` is preferred for ergonomics and function chaining, this technique might lack the discoverability of having an initializer on `Stat` directly. This proposal therefore includes both the initializers and extensions.
|
||||
|
||||
### Types for time properties
|
||||
|
||||
`UTCClock.Instant` would ideally be chosen over alternatives such as `Duration` or a new `Timespec` type to provide a comparable instant in time rather than a duration since the Epoch. However, this would depend on lowering `UTCClock` to System or the standard library and depends on that separate proposal.
|
||||
|
||||
Exposing a `timespec` property directly also has benefits; it's faithful to the underlying system's type and already has conversion support to/from `Duration` in the standard library.
|
||||
|
||||
Given that `timespec` is not particularly crufty and already has public API supporting its conversions, we decided to expose the raw `timespec` for now under the original C property names (`st_atim`, `st_mtim`, etc.) and reserve more ergonomic names for future extensions.
|
||||
|
||||
### Type names
|
||||
|
||||
`Stat` was chosen over alternatives like `FileStat` or `FileStatus` for its brevity and likeness to the "stat" system call. Unlike generic names such as `FileInfo` or `FileMetadata`, `Stat` emphasizes the platform-specific nature of this type.
|
||||
|
||||
`Stat` and (possible future) `StatFS` names were chosen over `FileStat` and `FileSystemStat`, or a namespaced `File.Stat` and `FileSystem.Stat`, because `Stat` is recognized more as its own concept rather than shorthand for "status." Thus, using `FileSystem.Stat` or `FileSystemStat` for `statfs` in the future might lead to confusion. Also, precedence from other languages' `stat` APIs that use a "file system" namespace might add to this confusion:
|
||||
|
||||
```
|
||||
Rust: fs::metadata() -> fs::Metadata
|
||||
Python: os.stat() -> os.stat_result
|
||||
Go: os.Stat() -> fs.FileInfo
|
||||
```
|
||||
|
||||
`Inode` was chosen over alternatives like `FileIndex` or `FileID` to emphasize the platform-specific nature. `IndexNode` is a bit verbose, and despite its etymology, "inode" is now ubiquitous and understood as a single word, making the capitalization `Inode` preferable to `INode`.
|
||||
|
||||
### `FileFlags` naming conventions
|
||||
|
||||
`FileFlags` property names such as `hidden` and `compressed` could alternatively use an "is" prefix commonly seen in boolean properties to form `.isHidden` and `.isCompressed`. However, we chose to omit the "is" prefix for the following reasons:
|
||||
|
||||
- The "is"-less flag names are succinct and closely aligned with the underlying C constants they represent.
|
||||
- `OptionSet` property names often use an adjective ("hidden") rather than a predicate ("is hidden") when describing a single subject, such as a file. This is likely because "is" does not add to the flow of `flags.contains(.isHidden)` like it does for a direct boolean property, such as `file.isHidden`.
|
||||
- For both `OptionSet` APIs that describe a single subject and those that describe a collection of elements, there's precedence to omit the "is". Examples of single-subject `OptionSet` APIs include `UIControl.State`, which uses `.highlighted` and `.disabled` rather than `.isHighlighted` and `.isDisabled`, and `FilePermissions`, which uses `.ownerRead` rather than `.isOwnerReadable`. Examples of multi-subject `OptionSet` APIs include `Edge.Set`, which uses `.top` and `.bottom`, and `ShippingOptions` from the `OptionSet` documentation, which uses `.nextDay`, `.priority`, etc.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
These new APIs build on excellent types currently available in the System library.
|
||||
|
||||
## Appendix
|
||||
|
||||
### Swift API to C Mappings
|
||||
|
||||
The following tables show the mapping between Swift APIs and their underlying C system calls across different operating systems:
|
||||
|
||||
#### `Stat` Initializer Mappings
|
||||
|
||||
The `retryOnInterrupt: Bool = true` parameter is omitted for clarity.
|
||||
|
||||
| Swift API | Unix-like Platforms |
|
||||
|-----------|---------------------|
|
||||
| `Stat(_ path: FilePath, followTargetSymlink: true)` | `stat()` |
|
||||
| `Stat(_ path: UnsafePointer<CChar>, followTargetSymlink: true)` | `stat()` |
|
||||
||
|
||||
| `Stat(_ path: FilePath, followTargetSymlink: false)` | `lstat()` |
|
||||
| `Stat(_ path: UnsafePointer<CChar>, followTargetSymlink: false)` | `lstat()` |
|
||||
||
|
||||
| `Stat(_ path: FilePath, relativeTo: FileDescriptor, flags: Stat.Flags)` | `fstatat()` |
|
||||
| `Stat(_ path: UnsafePointer<CChar>, relativeTo: FileDescriptor, flags: Stat.Flags)` | `fstatat()` |
|
||||
||
|
||||
| `Stat(_ fd: FileDescriptor)` | `fstat()` |
|
||||
| `FileDescriptor.stat()` | `fstat()` |
|
||||
||
|
||||
| `FilePath.stat(followTargetSymlink: true)` | `stat()` |
|
||||
| `FilePath.stat(followTargetSymlink: false)` | `lstat()` |
|
||||
| `FilePath.stat(relativeTo: FileDescriptor, flags: Stat.Flags)` | `fstatat()` |
|
||||
|
||||
#### `Stat` Property Mappings
|
||||
|
||||
`"` denotes the same property name across all operating systems.
|
||||
|
||||
| Swift Property | Darwin | FreeBSD | OpenBSD | Linux | Android | WASI |
|
||||
|----------------|--------|---------|---------|-------|---------|------|
|
||||
| `deviceID` | `st_dev` | " | " | " | " | " |
|
||||
| `inode` | `st_ino` | " | " | " | " | " |
|
||||
| `mode` | `st_mode` | " | " | " | " | " |
|
||||
| `linkCount` | `st_nlink` | " | " | " | " | " |
|
||||
| `userID` | `st_uid` | " | " | " | " | " |
|
||||
| `groupID` | `st_gid` | " | " | " | " | " |
|
||||
| `specialDeviceID` | `st_rdev` | " | " | " | " | " |
|
||||
| `size` | `st_size` | " | " | " | " | " |
|
||||
| `preferredIOBlockSize` | `st_blksize` | " | " | " | " | " |
|
||||
| `blocksAllocated` | `st_blocks` | " | " | " | " | " |
|
||||
| `st_atim` | `st_atimespec` | `st_atim` | `st_atim` | `st_atim` | `st_atim` | `st_atim` |
|
||||
| `st_mtim` | `st_mtimespec` | `st_mtim` | `st_mtim` | `st_mtim` | `st_mtim` | `st_mtim` |
|
||||
| `st_ctim` | `st_ctimespec` | `st_ctim` | `st_ctim` | `st_ctim` | `st_ctim` | `st_ctim` |
|
||||
| `st_birthtim` | `st_birthtimespec` | `st_birthtim` | N/A | N/A | N/A | N/A |
|
||||
| `flags` | `st_flags` | `st_flags` | `st_flags` | N/A | N/A | N/A |
|
||||
| `generationNumber` | `st_gen` | `st_gen` | `st_gen` | N/A | N/A | N/A |
|
||||
|
||||
#### `Stat.Flags` Mappings
|
||||
|
||||
| Swift Flag | Darwin | FreeBSD | OpenBSD | Linux | Android | WASI |
|
||||
|------------|--------|---------|---------|-------|---------|------|
|
||||
| `symlinkNoFollow` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` |
|
||||
| `symlinkNoFollowAny` | `AT_SYMLINK_NOFOLLOW_ANY` | N/A | N/A | N/A | N/A | N/A |
|
||||
| `resolveBeneath` | `AT_RESOLVE_BENEATH` | `AT_RESOLVE_BENEATH` | N/A | N/A | N/A | N/A |
|
||||
| `emptyPath` | N/A | `AT_EMPTY_PATH` | N/A | `AT_EMPTY_PATH` | `AT_EMPTY_PATH` | N/A |
|
||||
|
||||
#### `FileFlags` Mappings
|
||||
|
||||
**Note:** `FileFlags` is only available on Darwin, FreeBSD, and OpenBSD.
|
||||
|
||||
| Swift Flag | Darwin | FreeBSD | OpenBSD |
|
||||
|------------|--------|---------|---------|
|
||||
| `noDump` | `UF_NODUMP` | `UF_NODUMP` | `UF_NODUMP` |
|
||||
| `userImmutable` | `UF_IMMUTABLE` | `UF_IMMUTABLE` | `UF_IMMUTABLE` |
|
||||
| `userAppend` | `UF_APPEND` | `UF_APPEND` | `UF_APPEND` |
|
||||
| `archived` | `SF_ARCHIVED` | `SF_ARCHIVED` | `SF_ARCHIVED` |
|
||||
| `systemImmutable` | `SF_IMMUTABLE` | `SF_IMMUTABLE` | `SF_IMMUTABLE` |
|
||||
| `systemAppend` | `SF_APPEND` | `SF_APPEND` | `SF_APPEND` |
|
||||
| `opaque` | `UF_OPAQUE` | `UF_OPAQUE` | N/A |
|
||||
| `hidden` | `UF_HIDDEN` | `UF_HIDDEN` | N/A |
|
||||
| `systemNoUnlink` | `SF_NOUNLINK` | `SF_NOUNLINK` | N/A |
|
||||
| `compressed` | `UF_COMPRESSED` | N/A | N/A |
|
||||
| `tracked` | `UF_TRACKED` | N/A | N/A |
|
||||
| `dataVault` | `UF_DATAVAULT` | N/A | N/A |
|
||||
| `restricted` | `SF_RESTRICTED` | N/A | N/A |
|
||||
| `firmlink` | `SF_FIRMLINK` | N/A | N/A |
|
||||
| `dataless` | `SF_DATALESS` | N/A | N/A |
|
||||
| `userNoUnlink` | N/A | `UF_NOUNLINK` | N/A |
|
||||
| `offline` | N/A | `UF_OFFLINE` | N/A |
|
||||
| `readOnly` | N/A | `UF_READONLY` | N/A |
|
||||
| `reparse` | N/A | `UF_REPARSE` | N/A |
|
||||
| `sparse` | N/A | `UF_SPARSE` | N/A |
|
||||
| `system` | N/A | `UF_SYSTEM` | N/A |
|
||||
| `snapshot` | N/A | `SF_SNAPSHOT` | N/A |
|
||||
@@ -0,0 +1,190 @@
|
||||
# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor`
|
||||
|
||||
* Proposal: SYS-0007
|
||||
* Authors: Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
|
||||
|
||||
* Other Reviews: [Swift Forums Pitch](https://forums.swift.org/t/82486)
|
||||
|
||||
#### Revision history
|
||||
|
||||
* **v1** Initial version
|
||||
* **v2** Add Windows version of `pipe(options:)`
|
||||
* **v3** Add Darwin versions of `dup3` and `pipe2` wrappers
|
||||
|
||||
## Introduction
|
||||
|
||||
Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively.
|
||||
|
||||
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD, Android, and the Apple operating systems based on Darwin 27.0 or newer; `pipe(options:)` will also be available on Windows.
|
||||
|
||||
## Motivation
|
||||
|
||||
It is considered best practice to set the `O_CLOEXEC` (close-on-exec) bit on newly created file descriptors to prevent them from being inherited by subprocesses.
|
||||
|
||||
Some POSIX functions such as `open` provide a "flags" parameter allowing the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`.
|
||||
|
||||
POSIX 2024 corrects this deficiency for `dup2` and `pipe` by introducing `dup3` and `pipe2` variants that allow the close-on-exec bit to be set atomically.
|
||||
|
||||
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defense in depth with respect to opened file descriptors.
|
||||
|
||||
## Proposed solution
|
||||
|
||||
This proposal adds new overloads to `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` that will wrap the functionality of the `dup3` and `pipe2` functions.
|
||||
|
||||
## Example usage
|
||||
|
||||
```swift
|
||||
import System
|
||||
|
||||
let fd0 = try FileDescriptor.open("/tmp/test.txt", .readOnly)
|
||||
let fd1 = FileDescriptor(rawValue: 731)
|
||||
let fd2 = try fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec])
|
||||
```
|
||||
|
||||
## Detailed design
|
||||
|
||||
`FileDescriptor` will add the following overloads and types:
|
||||
|
||||
```swift
|
||||
struct FileDescriptor {
|
||||
/// Creates a unidirectional data channel, which can be used for
|
||||
/// interprocess communication.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options. On Windows, the
|
||||
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
|
||||
/// but this overload disables it when called with an empty option set.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - options: The behavior for creating the pipe.
|
||||
///
|
||||
/// - Returns: The pair of file descriptors.
|
||||
///
|
||||
/// The corresponding C function is `pipe2`.
|
||||
public static func pipe(
|
||||
options: PipeOptions
|
||||
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor)
|
||||
|
||||
/// Duplicate this file descriptor and return the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - target: The desired target file descriptor.
|
||||
/// - options: The behavior for creating the target file descriptor.
|
||||
/// - retryOnInterrupt: Whether to retry the operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
///
|
||||
/// If the `target` descriptor is the same as `self`, then EINVAL is thrown.
|
||||
/// If the `target` descriptor is already in use, then it is first
|
||||
/// deallocated as if a close(2) call had been done first.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options, because `dup3` with
|
||||
/// no set options is not required to behave identically to `dup2`.
|
||||
///
|
||||
/// File descriptors are merely references to some underlying system resource.
|
||||
/// The system does not distinguish between the original and the new file
|
||||
/// descriptor in any way. For example, read, write and seek operations on
|
||||
/// one of them also affect the logical file position in the other, and
|
||||
/// append mode, non-blocking I/O and asynchronous I/O options are shared
|
||||
/// between the references. If a separate pointer into the file is desired,
|
||||
/// a different object reference to the file must be obtained by issuing an
|
||||
/// additional call to `open`.
|
||||
///
|
||||
/// However, each file descriptor maintains its own close-on-exec and
|
||||
/// close-on-fork flags.
|
||||
///
|
||||
/// The corresponding C function is `dup3`.
|
||||
@discardableResult
|
||||
public func duplicate(
|
||||
as target: FileDescriptor,
|
||||
options: DuplicateOptions,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> FileDescriptor
|
||||
|
||||
/// Options that specify behavior for a newly-created pipe.
|
||||
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
public var rawValue: CInt
|
||||
|
||||
/// Create a strongly-typed options value from raw C options.
|
||||
public init(rawValue: CInt)
|
||||
|
||||
/// Indicates that all subsequent input and output operations
|
||||
/// on the pipe's file descriptors will be nonblocking.
|
||||
///
|
||||
/// The corresponding C constant is `O_NONBLOCK`.
|
||||
public static var nonBlocking: PipeOptions
|
||||
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open across calls to the `exec(2)`
|
||||
/// family of functions. If you specify this option, the system closes the
|
||||
/// file descriptor when replacing this process with another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
public static var closeOnExec: PipeOptions
|
||||
|
||||
/// Indicates that forking a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open across calls to the `fork(2)`
|
||||
/// function. If you specify this option, the system closes the file
|
||||
/// descriptor when forking this process into another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOFORK`.
|
||||
public static var closeOnFork: PipeOptions
|
||||
}
|
||||
|
||||
/// Options that specify behavior for a duplicated file descriptor.
|
||||
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
public var rawValue: CInt
|
||||
|
||||
/// Create a strongly-typed options value from raw C options.
|
||||
public init(rawValue: CInt)
|
||||
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open across calls to the `exec(2)`
|
||||
/// family of functions. If you specify this option, the system closes the
|
||||
/// file descriptor when replacing this process with another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
public static var closeOnExec: DuplicateOptions
|
||||
|
||||
/// Indicates that forking a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open across calls to the `fork(2)`
|
||||
/// function. If you specify this option, the system closes the file
|
||||
/// descriptor when forking this process into another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOFORK`.
|
||||
public static var closeOnFork: DuplicateOptions
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`pipe(options:)` is added for Windows with the option `.closeOnExec`, but `duplicate(as:options:)` is not added because the underlying API does not match `dup3`.
|
||||
|
||||
`closeOnFork` is unavailable on Linux and Android, as the underlying `O_CLOFORK` constant does not exist.
|
||||
|
||||
## Impact on existing code
|
||||
|
||||
This change will have no impact on existing code, as it is purely additive.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
None. The underlying POSIX API are additions that help C developers follow best practices, and these overloads provide the same value to Swift developers.
|
||||
@@ -0,0 +1,262 @@
|
||||
# Back-Deploy CInterop.stat for Migration Compatibility
|
||||
|
||||
* Proposal: SYS-0008
|
||||
* Author: [Jonathan Flat](https://github.com/jrflat)
|
||||
* Status: **Awaiting review**
|
||||
* Implementation: [apple/swift-system#299](https://github.com/apple/swift-system/pull/299)
|
||||
* Review: ([pitch](https://forums.swift.org/t/pitch-back-deploy-system-cinterop-stat-for-migration-compatibility/84930))
|
||||
|
||||
#### Revision history
|
||||
|
||||
* **v1** Initial version
|
||||
* **v2** Clarify that `CInterop.stat(_:_:)` is a new function
|
||||
* **v3** Explain why this proposal should not set a precedence for future System APIs
|
||||
|
||||
## Introduction
|
||||
|
||||
This proposal introduces `CInterop.stat(_:_:)` and back-deploys the `CInterop.Stat` typealias from System to make them available on older OS versions, enabling a migration path for clients who may encounter naming conflicts with `FilePath.stat()` or `FileDescriptor.stat()` when System's new `Stat` API ships.
|
||||
|
||||
## Motivation
|
||||
|
||||
The introduction of `FilePath.stat()` and `FileDescriptor.stat()` in [SYS-0006](0006-system-stat.md) creates a potential source compatibility issue for a small number of clients. While we estimate this affects an exceedingly rare set of developers (1 case found in public GitHub repositories), we want to provide a clear migration path.
|
||||
|
||||
### Compatibility scenario
|
||||
|
||||
Some clients may have extended `FilePath` or `FileDescriptor` with custom functions that use `Darwin.stat()` and `Darwin.stat(_:_:)` **without** the `Darwin.` (or other libc) module qualification inside the function body:
|
||||
|
||||
```swift
|
||||
extension FilePath {
|
||||
func isRegularFile() -> Bool {
|
||||
var s = stat() // Calls Darwin.stat(_:_:) - unqualified!
|
||||
guard stat(self.string, &s) == 0 else { // Calls Darwin.stat(_:_:) - unqualified!
|
||||
return false
|
||||
}
|
||||
return s.st_mode & S_IFMT == S_IFREG
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When the new `FilePath.stat()` API from SYS-0006 ships, these unqualified calls to `stat()` and `stat(_:_:)` will refer to the new instance method, causing build errors:
|
||||
|
||||
```
|
||||
error: Call can throw, but it is not marked with 'try' and the error is not handled
|
||||
error: Use of 'stat' refers to instance method rather than global function 'stat' in module 'Darwin'
|
||||
```
|
||||
|
||||
### Why not just use `Darwin.stat`?
|
||||
|
||||
Clients could resolve the ambiguity by qualifying their calls with `Darwin.`, `Glibc.`, etc. However, this approach has several limitations:
|
||||
|
||||
1. **Cross-platform code**: Clients writing code for multiple platforms would need platform-specific `#if` blocks with code for each platform's libc module.
|
||||
2. **Awkward syntax**: Due to the overload between the `stat` type and `stat(_:_:)` function, clients must use the verbose `Darwin.stat(_:_:)(path, &s)` syntax to call the function, which is unintuitive.
|
||||
3. **Older deployment targets**: Clients supporting older deployment targets can't use the new `System.Stat` API on older OS versions but still need to avoid build breakage when compiled with an SDK that includes the new `FilePath.stat()`
|
||||
|
||||
By back-deploying `CInterop.stat(_:_:)` to `System 0.0.2 (macOS 12.0, iOS 15.0)`, we provide a cross-platform, ergonomic solution: clients can replace `stat(_:_:)` with `CInterop.stat(_:_:)` for older deployment targets, and use the new `Stat` API moving forward.
|
||||
|
||||
## Proposed solution
|
||||
|
||||
Back-deploy `CInterop.Stat` and `CInterop.stat(_:_:)` to `@available(System 0.0.2, *)`, making them available on `macOS 12.0, iOS 15.0` and aligned. Note that `System 0.0.2` already maps to earliest source availability when System is used as a package, so the back-deployment is only relevant for System as an OS framework.
|
||||
|
||||
### API Overview
|
||||
|
||||
```swift
|
||||
#if !os(Windows)
|
||||
@available(System 0.0.2, *) // Original availability of CInterop
|
||||
extension CInterop {
|
||||
public typealias Stat = stat
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
The implementation uses `@_alwaysEmitIntoClient` to make the function available on older OS versions by embedding the implementation in client code. This makes sense for a widely-available and standardized C function like `stat()`.
|
||||
|
||||
### Migration guidance
|
||||
|
||||
If you have `FilePath` or `FileDescriptor` extensions that use unqualified `stat()` calls and need to support older deployment targets, migrate to `CInterop.Stat` (type) and `CInterop.stat(_:_:)` (function):
|
||||
|
||||
#### Before:
|
||||
|
||||
```swift
|
||||
extension FilePath {
|
||||
func isRegularFile() throws -> Bool {
|
||||
var s = stat()
|
||||
guard stat(self.string, &s) == 0 else {
|
||||
throw Errno.current
|
||||
}
|
||||
return s.st_mode & S_IFMT == S_IFREG
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### After:
|
||||
|
||||
```swift
|
||||
extension FilePath {
|
||||
func isRegularFile() throws -> Bool {
|
||||
var s = CInterop.Stat() // stat() --> CInterop.Stat()
|
||||
guard CInterop.stat(self.string, &s) == 0 else { // stat(_:_:) --> CInterop.stat(_:_:)
|
||||
throw Errno.current
|
||||
}
|
||||
return s.st_mode & S_IFMT == S_IFREG
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Migrate to the new `Stat` API:
|
||||
|
||||
Migrate to the more ergonomic interface on newer OS versions using `if #available`:
|
||||
|
||||
```swift
|
||||
extension FilePath {
|
||||
func isRegularFile() throws -> Bool {
|
||||
if #available(macOS X, iOS Y, *) {
|
||||
return try stat().type == .regular // Calls FilePath.stat()
|
||||
}
|
||||
var s = CInterop.Stat()
|
||||
guard CInterop.stat(self.string, &s) == 0 else {
|
||||
throw Errno.current
|
||||
}
|
||||
return s.st_mode & S_IFMT == S_IFREG
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you may use just the new API if your deployment target supports it.
|
||||
|
||||
#### Who should use `CInterop.stat(_:_:)`?
|
||||
|
||||
This scenario is rare and only occurs when a project meets **all** of the following conditions:
|
||||
|
||||
1. Has a custom extension on `FilePath` or `FileDescriptor`, that
|
||||
2. Uses **unqualified** `stat()` or `stat(_:_:)` calls inside that method, and
|
||||
3. Needs to support deployment targets older than the new `Stat` API availability
|
||||
|
||||
If your code uses qualified calls, e.g. `Darwin.stat()`, or uses a wrapper around `stat()` already, it is **not** affected by this issue and no migration is needed.
|
||||
|
||||
## Detailed design
|
||||
|
||||
### CInterop extension
|
||||
|
||||
```swift
|
||||
#if !os(Windows)
|
||||
@available(System 0.0.2, *) // Original availability of CInterop
|
||||
extension CInterop {
|
||||
/// The C `stat` struct.
|
||||
public typealias Stat = stat
|
||||
|
||||
/// Calls the C `stat()` function.
|
||||
///
|
||||
/// This is a direct wrapper around the C `stat()` system call.
|
||||
/// For a more ergonomic Swift API, use `Stat` instead.
|
||||
///
|
||||
/// - Warning: This API is primarily intended for migration purposes when
|
||||
/// supporting older deployment targets. If your deployment target supports
|
||||
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
|
||||
/// type-safe, ergonomic access to file metadata in Swift.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: A null-terminated C string representing the file path.
|
||||
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
|
||||
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
|
||||
@_alwaysEmitIntoClient
|
||||
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
system_stat(path, &s)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
### Internal wrapper
|
||||
|
||||
The `system_stat` wrapper is also marked `@_alwaysEmitIntoClient` so it can be inlined. `system_stat` calls the global `stat` function for the current platform.
|
||||
|
||||
```swift
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func system_stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
stat(path, &s)
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
## Source compatibility
|
||||
|
||||
This proposal is additive and source-compatible.
|
||||
|
||||
## ABI compatibility
|
||||
|
||||
This proposal is ABI-compatible. The use of `@_alwaysEmitIntoClient` ensures that the implementation is embedded in client code.
|
||||
|
||||
## Implications on adoption
|
||||
|
||||
Clients can adopt `CInterop.Stat` and `CInterop.stat(_:_:)` to support older deployment targets when building with the new SDK.
|
||||
|
||||
## Future directions
|
||||
|
||||
Once clients can raise their deployment targets to support the new `Stat` API introduced in SYS-0006, they should migrate to it, which provides:
|
||||
|
||||
- Type-safe, ergonomic Swift interfaces
|
||||
- Strongly-typed wrappers (`FileType`, `FileMode`, `FilePermissions`, etc.)
|
||||
- Proper error handling with typed throws
|
||||
|
||||
## Why this should not set a precedent for CInterop functions
|
||||
|
||||
We should not expose `CInterop` functions for most, if not all, other methods that shadow a global function. `stat` is a special case for a few reasons:
|
||||
|
||||
- Many other syscalls gain a more Swift-y API name, e.g. `dup/dup2` → `duplicate(as:)`, `ftruncate` → `resize(to:)`, `umask` → `FilePermissions.creationMask` if that becomes API, etc. Those renames mean user extensions are unlikely to collide with future System API. `stat` is one of the few syscalls whose C name is already clear and idiomatic enough to use directly as the Swift API name.
|
||||
- Many syscalls that do keep their C name (e.g. `open`, `close`, `read`, `write`) have been in System since the beginning, so there was never a window where someone would have needed to create their own extension for that functionality.
|
||||
- `stat` is both widely used and was missing from System for some time, which creates a better chance for migration friction.
|
||||
- Other syscalls that could be added to System naturally disambiguate through parameter labels. Names like `rename`, `link`, and `unlink` would require non-optional arguments (e.g. `rename(to:)`, `link(to:)`), so their Swift signatures wouldn't collide with the bare C functions. `stat` is unusual in that it works as a zero-argument call on `FilePath`/`FileDescriptor` and has the same shape as the global C `stat()` struct initializer.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### Do nothing
|
||||
|
||||
We could choose not to provide a migration path and let affected clients handle the ambiguity by:
|
||||
|
||||
1. Qualifying their calls with platform-specific modules (e.g. `Darwin.stat`)
|
||||
2. Wrapping `stat()` in another function
|
||||
3. Raising their deployment target to use the new `Stat` API
|
||||
|
||||
However, this creates an unnecessary burden for the (admittedly rare) affected clients, especially those who need to maintain backward compatibility with older OS versions.
|
||||
|
||||
### Use a different name for `FilePath.stat()`
|
||||
|
||||
We could use a different name such as `FilePath.statInfo()`, `FilePath.status()`, `FilePath.Stat()`, or `FilePath.fileInfo()`. However, considering the rarity of the issue, changing to a less concise, discoverable, and expressive function name is not preferrable when we can offer a migration solution.
|
||||
|
||||
### Create `stat()` overloads directly on `FilePath`
|
||||
|
||||
We could create `stat()` extensions on `FilePath` within System that guide a developer to use the new instance method via `try stat()`, e.g:
|
||||
|
||||
```swift
|
||||
extension FilePath {
|
||||
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
|
||||
public func stat() -> CInterop.Stat {
|
||||
CInterop.Stat()
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
|
||||
public func stat(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ s: inout CInterop.Stat
|
||||
) -> Int32 {
|
||||
system_stat(path, &s)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is beneficial because it prevents any SDK breakage with only a System change. However, this is not a great long-term solution to have as public API because:
|
||||
|
||||
- It makes choosing the right `stat()` more confusing with 5 total overloads.
|
||||
- It hurts discoverability for the new `Stat` API.
|
||||
|
||||
### Expose the internal `system_stat` wrapper directly
|
||||
|
||||
This would achieve the same effect as exposing `CInterop.stat(_:_:)`, but goes against the API naming/organization patterns in System. `CInterop` seems like a clear place for the direct C `stat` wrapper to belong.
|
||||
|
||||
### Back-deploy the full `Stat` API
|
||||
|
||||
Unlike functions and typealiases, types such as `Stat`, `FileType`, `FileMode`, etc. would require significant coordination and effort to back-deploy, making this alternative less desirable, especially considering it's not required to address the issue.
|
||||
@@ -0,0 +1,972 @@
|
||||
# StatFS for Swift System
|
||||
|
||||
* Proposal: [SYS-0009](0009-system-statfs.md)
|
||||
* Authors: [Jonathan Flat](https://github.com/jrflat)
|
||||
* Review Manager: TBD
|
||||
* Status: **Implemented**
|
||||
* Implementation: [apple/swift-system#361](https://github.com/apple/swift-system/pull/361)
|
||||
* Review: ([pitch](https://forums.swift.org/t/pitch-statfs-and-supporting-types/88151))
|
||||
|
||||
#### Revision history
|
||||
|
||||
* **v1** Initial version
|
||||
* **v2** Use `statfs` on Linux and Android, make `StatFS` unavailable on WASI, omit Linux flags the kernel never reports, add descriptions for `MountFlags` and `FileSystemID`, and back-deploy `CInterop.StatFS` with `CInterop.statfs(_:_:)` for migration
|
||||
* **v3** Rename `MountFlags` constants for consistency, remove `type` on Darwin and FreeBSD, and remove the `statfs()` methods on `FilePath` and `FileDescriptor`, eliminating the need for `CInterop` back-deployment
|
||||
* **v4** Add `FileSystemTypeName` wrapper
|
||||
|
||||
## Introduction
|
||||
|
||||
This proposal introduces a Swift-native `StatFS` type to the System library, providing comprehensive access to file system metadata on Unix-like platforms through type-safe, platform-aware APIs that wrap the underlying C `statfs` system calls.
|
||||
|
||||
## Motivation
|
||||
|
||||
Currently, Swift developers who want to work with the file system's lowest level API can only do so through bridged C interfaces. These interfaces lack type safety and require writing non-idiomatic Swift, leading to errors and confusion.
|
||||
|
||||
The C `statfs` interfaces add a few problems of their own:
|
||||
|
||||
- On Linux, Swift's Glibc module doesn't export `statfs`, so calling it requires a C shim.
|
||||
- Block counts are in units of `f_bsize` on Darwin and BSD, but `f_frsize` on Linux and Android, so computing space in bytes requires platform-specific code.
|
||||
- Field widths and signedness vary by platform and C library. For example, `f_bavail` is signed on FreeBSD and OpenBSD.
|
||||
|
||||
The goal of the `StatFS` type is to provide a faithful and performant Swift wrapper around the underlying C system calls while adding type safety, platform abstraction, and improved discoverability/usability with clear naming. For more on the motivation behind System, see [https://www.swift.org/blog/swift-system](https://www.swift.org/blog/swift-system).
|
||||
|
||||
## Proposed solution
|
||||
|
||||
This proposal adds a `struct StatFS` that is available on Unix-like platforms. On Windows and WASI, the struct is declared but marked unavailable (see **Availability on Windows and WASI**). Windows-specific file system APIs and WASI support are discussed in **Future directions**.
|
||||
|
||||
`StatFS` is a Swift wrapper around the C `statfs` struct, which provides information about file systems. This type uses `statfs` rather than the POSIX `statvfs` for the additional information it provides, such as the file system type. Computed properties like `.totalSpace` and `.availableSpace` are supplied for convenience.
|
||||
|
||||
```swift
|
||||
// Get file system information from a path
|
||||
let statfs = try StatFS("/")
|
||||
|
||||
// From FileDescriptor
|
||||
let fdStatFS = try StatFS(fd)
|
||||
|
||||
// From FilePath
|
||||
let pathStatFS = try StatFS(filePath)
|
||||
|
||||
print("File system ID: \(statfs.fileSystemID)")
|
||||
print("Total space: \(statfs.totalSpace) bytes")
|
||||
print("Available space: \(statfs.availableSpace) bytes")
|
||||
|
||||
// Check mount flags
|
||||
if statfs.mountFlags.contains(.readOnly) {
|
||||
print("File system is read-only")
|
||||
}
|
||||
|
||||
// Platform-specific information when available
|
||||
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
|
||||
print("File system is mounted at \(statfs.mountPoint)")
|
||||
print("File system is mounted from \(statfs.mountSource)")
|
||||
#endif
|
||||
|
||||
#if os(anyAppleOS)
|
||||
if statfs.typeName == .apfs {
|
||||
print("File system is APFS")
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
### Error handling
|
||||
|
||||
The throwing initializers use a typed `throws(Errno)` and require Swift 6.0 or later:
|
||||
|
||||
```swift
|
||||
do {
|
||||
let statfs = try StatFS("/nonexistent/file")
|
||||
} catch Errno.noSuchFileOrDirectory {
|
||||
print("File not found")
|
||||
} catch {
|
||||
print("Other error: \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
## Detailed design
|
||||
|
||||
See the **Appendix** section at the end of this proposal for a table view of Swift API to C mappings.
|
||||
|
||||
All APIs will be marked `@export(implementation)` for performance, except `StatFS`'s `==` and `hash(into:)`, and descriptions, which are ordinary `public` APIs. Until the package requires Swift 6.4, the implementation will use the equivalent `@_alwaysEmitIntoClient` instead.
|
||||
|
||||
### `MountFlags`
|
||||
|
||||
This proposal introduces a `MountFlags` type representing flags that could be present in a `statfs` struct. On Darwin and BSD, many of these flags could also be passed to a future implementation of `mount`, though some, like `local` and `rootFileSystem`, only describe state the kernel reports. (Linux `mount(2)` instead takes a separate `MS_*` set, distinct from the `ST_*` flags `statfs` reports.) Mount-specific flags are outside the scope of this proposal (see **Future directions**).
|
||||
|
||||
`MountFlags` uses a `CInterop` typealias for its `rawValue` to support different widths of integers used on different operating systems. On Linux and Android, `CInterop.MountFlags` is `CUnsignedLong` rather than the type of `f_flags`, which varies by C library (glibc's is a signed `long`).
|
||||
|
||||
Glibc and musl also define `ST_WRITE`, `ST_APPEND`, and `ST_IMMUTABLE`, but Linux never reports them in `f_flags`, so `MountFlags` omits them. For space, doc comments are omitted for flags that aren't available on Darwin.
|
||||
|
||||
```swift
|
||||
/// Flags describing a mounted file system.
|
||||
///
|
||||
/// These are the flags reported in the `f_flags` field of a `statfs` struct.
|
||||
/// Some reflect options employed when mounting the file system, while others,
|
||||
/// like `local` and `rootFileSystem`, describe state the kernel reports.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
@frozen
|
||||
public struct MountFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C flags.
|
||||
public let rawValue: CInterop.MountFlags
|
||||
|
||||
/// Creates a strongly-typed `MountFlags` from the raw C value.
|
||||
public init(rawValue: CInterop.MountFlags)
|
||||
|
||||
// Flags available on all platforms
|
||||
|
||||
/// The file system is mounted read-only, even for the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_RDONLY` on Darwin and BSD,
|
||||
/// or `ST_RDONLY` otherwise.
|
||||
public static var readOnly: MountFlags { get }
|
||||
|
||||
/// The file system is written to synchronously.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SYNCHRONOUS` on Darwin and BSD,
|
||||
/// or `ST_SYNCHRONOUS` otherwise.
|
||||
public static var synchronous: MountFlags { get }
|
||||
|
||||
/// Programs may not be executed from the file system.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOEXEC` on Darwin and BSD,
|
||||
/// or `ST_NOEXEC` otherwise.
|
||||
public static var noExecution: MountFlags { get }
|
||||
|
||||
/// Set-user-ID and set-group-ID (setuid and setgid) bits are not honored on
|
||||
/// the file system.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD,
|
||||
/// or `ST_NOSUID` otherwise.
|
||||
public static var noSetUserID: MountFlags { get }
|
||||
|
||||
/// Access times are not updated on the file system.
|
||||
///
|
||||
/// - Note: On OpenBSD, access time may still be updated when the
|
||||
/// modification or status-change time is also being updated.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD,
|
||||
/// or `ST_NOATIME` otherwise.
|
||||
public static var noAccessTime: MountFlags { get }
|
||||
|
||||
// Flags available on all platforms except FreeBSD
|
||||
|
||||
#if !os(FreeBSD)
|
||||
/// Special files may not be interpreted on the file system.
|
||||
///
|
||||
/// - Note: Not available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NODEV` on Darwin and OpenBSD,
|
||||
/// or `ST_NODEV` otherwise.
|
||||
public static var noDevices: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on Linux and Android
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
public static var mandatoryLocking: MountFlags { get }
|
||||
public static var noDirectoryAccessTime: MountFlags { get }
|
||||
public static var relativeAccessTime: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on Linux, Android, and FreeBSD
|
||||
|
||||
#if os(Linux) || os(Android) || os(FreeBSD)
|
||||
public static var noSymlinkFollowing: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
|
||||
/// The file system is written to asynchronously.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_ASYNC`.
|
||||
public static var asynchronous: MountFlags { get }
|
||||
|
||||
/// The file system is exported for use over the network via NFS.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_EXPORTED`.
|
||||
public static var exported: MountFlags { get }
|
||||
|
||||
/// The file system is stored locally, rather than being accessed over a network.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_LOCAL`.
|
||||
public static var local: MountFlags { get }
|
||||
|
||||
/// Quotas are enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_QUOTA`.
|
||||
public static var quotasEnabled: MountFlags { get }
|
||||
|
||||
/// The file system is the root file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_ROOTFS`.
|
||||
public static var rootFileSystem: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on Darwin and FreeBSD
|
||||
|
||||
#if os(anyAppleOS) || os(FreeBSD)
|
||||
/// The file system is unioned with the underlying file system, rather than
|
||||
/// obscuring it.
|
||||
///
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_UNION`.
|
||||
public static var union: MountFlags { get }
|
||||
|
||||
/// The file system was mounted by the automounter.
|
||||
///
|
||||
/// - Note: Only available on Darwin and FreeBSD. See `automount(8)`.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_AUTOMOUNTED`.
|
||||
public static var automounted: MountFlags { get }
|
||||
|
||||
/// The file system maintains Mandatory Access Control (MAC) labels for
|
||||
/// individual objects.
|
||||
///
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_MULTILABEL`.
|
||||
public static var multiLabel: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on FreeBSD and OpenBSD
|
||||
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
public static var exportedReadOnly: MountFlags { get }
|
||||
public static var exportedByDefault: MountFlags { get }
|
||||
public static var exportedAnonymously: MountFlags { get }
|
||||
public static var softUpdates: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on Darwin only
|
||||
|
||||
#if os(anyAppleOS)
|
||||
/// Per-file encrypted data protection is enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_CPROTECT`.
|
||||
public static var contentProtection: MountFlags { get }
|
||||
|
||||
/// The file system resides on removable media.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_REMOVABLE`.
|
||||
public static var removable: MountFlags { get }
|
||||
|
||||
/// The file system is quarantined.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_QUARANTINE`.
|
||||
public static var quarantined: MountFlags { get }
|
||||
|
||||
/// The file system supports volfs.
|
||||
///
|
||||
/// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DOVOLFS`.
|
||||
public static var supportsVolfs: MountFlags { get }
|
||||
|
||||
/// The file system should not be presented to the user for browsing
|
||||
/// (e.g. hidden in Finder).
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DONTBROWSE`.
|
||||
public static var noBrowsing: MountFlags { get }
|
||||
|
||||
/// The file system ignores ownership information.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`.
|
||||
public static var ignoresOwnership: MountFlags { get }
|
||||
|
||||
/// The file system is journaled.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_JOURNALED`.
|
||||
public static var journaled: MountFlags { get }
|
||||
|
||||
/// User extended attributes are not allowed on the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOUSERXATTR`.
|
||||
public static var noUserExtendedAttributes: MountFlags { get }
|
||||
|
||||
/// The file system defers writes.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DEFWRITE`.
|
||||
public static var defersWrites: MountFlags { get }
|
||||
|
||||
/// Symbolic links are not followed when resolving the mount point.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOFOLLOW`.
|
||||
public static var noSymlinkFollowingAtMountPoint: MountFlags { get }
|
||||
|
||||
/// The file system is a snapshot.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SNAPSHOT`.
|
||||
public static var snapshot: MountFlags { get }
|
||||
|
||||
/// Access times are always updated when files are read. Without this flag,
|
||||
/// the file system may skip some access time updates for performance.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_STRICTATIME`.
|
||||
public static var strictAccessTime: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on FreeBSD only
|
||||
|
||||
#if os(FreeBSD)
|
||||
public static var exportedWithKerberos: MountFlags { get }
|
||||
public static var exportedPublicly: MountFlags { get }
|
||||
public static var posixACLs: MountFlags { get }
|
||||
public static var geomJournaled: MountFlags { get }
|
||||
public static var excludedFromDiskFreeReports: MountFlags { get }
|
||||
public static var nfs4ACLs: MountFlags { get }
|
||||
public static var noClusteredReads: MountFlags { get }
|
||||
public static var noClusteredWrites: MountFlags { get }
|
||||
public static var setUserIDDirectories: MountFlags { get }
|
||||
public static var softUpdatesJournaling: MountFlags { get }
|
||||
public static var untrusted: MountFlags { get }
|
||||
public static var userMounted: MountFlags { get }
|
||||
public static var verified: MountFlags { get }
|
||||
#endif
|
||||
|
||||
// Flags available on OpenBSD only
|
||||
|
||||
#if os(OpenBSD)
|
||||
public static var noPermissionChecks: MountFlags { get }
|
||||
public static var writeExecuteAllowed: MountFlags { get }
|
||||
#endif
|
||||
}
|
||||
|
||||
extension MountFlags: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the mount flags.
|
||||
public var description: String { get }
|
||||
|
||||
/// A textual representation of the mount flags, suitable for debugging.
|
||||
public var debugDescription: String { get }
|
||||
}
|
||||
```
|
||||
|
||||
Like `FilePermissions`, `MountFlags` describes itself by listing its flags, such as `[.readOnly, .local]`.
|
||||
|
||||
### `FileSystemID`, `FileSystemType`, `FileSystemSubtype`, and `FileSystemTypeName`
|
||||
|
||||
```swift
|
||||
/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs`
|
||||
/// struct.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
@frozen
|
||||
public struct FileSystemID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C file system ID.
|
||||
public var rawValue: CInterop.FileSystemID
|
||||
|
||||
/// Creates a strongly-typed `FileSystemID` from the raw C value.
|
||||
public init(rawValue: CInterop.FileSystemID)
|
||||
|
||||
/// Creates a strongly-typed `FileSystemID` from the raw C value.
|
||||
public init(_ rawValue: CInterop.FileSystemID)
|
||||
}
|
||||
|
||||
extension FileSystemID: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the file system ID.
|
||||
public var description: String { get }
|
||||
|
||||
/// A textual representation of the file system ID, suitable for debugging.
|
||||
public var debugDescription: String { get }
|
||||
}
|
||||
|
||||
// `FileSystemType` is available on Linux and Android, where `f_type` is the
|
||||
// file system's magic number. Darwin and FreeBSD report a kernel-assigned
|
||||
// index in `f_type`, so `typeName` identifies the file system there instead.
|
||||
// `FileSystemSubtype` is Darwin-only. Both fit in a `UInt32` on every platform
|
||||
// that provides them, so no `CInterop` typealias is needed.
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
/// A Swift wrapper of the C `f_type` file system type found in a `statfs`
|
||||
/// struct.
|
||||
///
|
||||
/// - Note: Only available on Linux and Android.
|
||||
@frozen
|
||||
public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C file system type.
|
||||
public var rawValue: UInt32
|
||||
|
||||
/// Creates a strongly-typed `FileSystemType` from the raw C value.
|
||||
public init(rawValue: UInt32)
|
||||
|
||||
/// Creates a strongly-typed `FileSystemType` from the raw C value.
|
||||
public init(_ rawValue: UInt32)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(anyAppleOS)
|
||||
/// A Swift wrapper of the C `f_fssubtype` file system subtype found in a
|
||||
/// `statfs` struct on Darwin.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
@frozen
|
||||
public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C file system subtype.
|
||||
public var rawValue: UInt32
|
||||
|
||||
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
|
||||
public init(rawValue: UInt32)
|
||||
|
||||
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
|
||||
public init(_ rawValue: UInt32)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
|
||||
/// A Swift wrapper of the C `f_fstypename` file system type name found in a
|
||||
/// `statfs` struct.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
@frozen
|
||||
public struct FileSystemTypeName: RawRepresentable, Sendable, Hashable, Codable, ExpressibleByStringLiteral {
|
||||
/// The raw file system type name.
|
||||
public var rawValue: String
|
||||
|
||||
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
|
||||
public init(rawValue: String)
|
||||
|
||||
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
|
||||
public init(_ rawValue: String)
|
||||
|
||||
/// Creates a `FileSystemTypeName` from a string literal, such as `"apfs"`.
|
||||
public init(stringLiteral value: String)
|
||||
|
||||
// Type names available on Darwin only
|
||||
|
||||
#if os(anyAppleOS)
|
||||
/// The Apple File System (APFS).
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding `f_fstypename` value is `"apfs"`.
|
||||
public static var apfs: FileSystemTypeName { get }
|
||||
|
||||
/// The Mac OS Extended file system (HFS Plus).
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding `f_fstypename` value is `"hfs"`.
|
||||
public static var hfs: FileSystemTypeName { get }
|
||||
#endif
|
||||
}
|
||||
|
||||
extension FileSystemTypeName: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// The file system type name, such as `apfs`.
|
||||
public var description: String { get }
|
||||
|
||||
/// The file system type name as a quoted string, such as `"apfs"`.
|
||||
public var debugDescription: String { get }
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
`CInterop.FileSystemID` is the C `fsid_t` struct (a fixed two-element `int32_t` array), which provides no synthesized conformances. `FileSystemID` implements `Equatable`, `Hashable`, and `Codable` manually in terms of its elements, named `val` on Darwin and BSD and `__val` on Linux and Android. It encodes them as an unkeyed container of two `Int32` values and describes itself by listing them, such as `FileSystemID(16777239, 26)`.
|
||||
|
||||
`FileSystemTypeName` wraps `f_fstypename` so that well-known type names can be offered as constants, such as `.apfs`. It conforms to `ExpressibleByStringLiteral` so comparisons against names without a constant like `statfs.typeName == "nfs"` still read naturally. This proposal only provides constants for `"apfs"` and `"hfs"`. Other names can be added in the future when their stability is confirmed.
|
||||
|
||||
### `StatFS`
|
||||
|
||||
`StatFS` offers initializers that accept a `FilePath`, null-terminated `UnsafePointer<CChar>`, or `FileDescriptor`.
|
||||
|
||||
The underlying C fields for each numeric property vary in signedness and width across platforms. Rather than create a platform-dependent type for each, we choose one fixed integer type per property — `Int` or `UInt64` — and clamp when getting or setting the value.
|
||||
|
||||
Block sizes and lengths (`blockSize`, `preferredIOBlockSize`, `fragmentSize`, and `maximumNameLength`) are exposed as `Int`. Most modern file systems report 4KiB block sizes by default, and in practice, the highest value seen on specialized (often network) file systems is on the order of 1MiB. The preferred I/O size could similarly reach values around 16MiB. These are still orders of magnitude smaller than `Int.max`, even for 32-bit platforms.
|
||||
|
||||
Block and inode counts, and the space values computed from them, are exposed as `UInt64` to preserve their full unsigned range on every platform. Real-world values can exceed `Int64.max`, and space computations can overflow and saturate to `UInt64.max`. Clamping lets us report `0` for the signed "available to non-superuser" counts that some BSDs allow to go negative.
|
||||
|
||||
```swift
|
||||
/// A Swift wrapper of the C `statfs` struct.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
/// - Note: The numeric properties clamp when converting to or from the
|
||||
/// underlying C field. Use `rawValue` for exact, unclamped access.
|
||||
@frozen
|
||||
public struct StatFS: RawRepresentable, Sendable, Hashable {
|
||||
/// The raw C `statfs` struct.
|
||||
public var rawValue: CInterop.StatFS
|
||||
|
||||
/// Creates a Swift `StatFS` from the raw C struct.
|
||||
public init(rawValue: CInterop.StatFS)
|
||||
|
||||
/// Creates a `StatFS` from a `FilePath`.
|
||||
///
|
||||
/// The corresponding C function is `statfs()`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
|
||||
///
|
||||
/// The corresponding C function is `statfs()`.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `StatFS` from a `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstatfs()`.
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// File system block size, in bytes.
|
||||
///
|
||||
/// - Note: On Darwin and BSD, this is the fundamental size for block counts.
|
||||
/// Other platforms use `fragmentSize` (`f_frsize`) instead.
|
||||
///
|
||||
/// The corresponding C property is `f_bsize`.
|
||||
public var blockSize: Int { get set }
|
||||
|
||||
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
|
||||
/// Block size for optimal data transfer, in bytes.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_iosize`.
|
||||
public var preferredIOBlockSize: Int { get set }
|
||||
#else
|
||||
/// File system fragment size, in bytes.
|
||||
///
|
||||
/// - Note: On Linux and Android, this is the fundamental size for block
|
||||
/// counts. Not present on Darwin or BSD, which use `blockSize` instead.
|
||||
///
|
||||
/// The corresponding C property is `f_frsize`.
|
||||
public var fragmentSize: Int { get set }
|
||||
#endif
|
||||
|
||||
/// Total number of blocks in the file system.
|
||||
///
|
||||
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
|
||||
/// otherwise.
|
||||
///
|
||||
/// The corresponding C property is `f_blocks`.
|
||||
public var totalBlocks: UInt64 { get set }
|
||||
|
||||
/// Total size of the file system, in bytes.
|
||||
///
|
||||
/// - Note: Computed for convenience as `totalBlocks` times the fundamental
|
||||
/// block size (see `totalBlocks`). Saturates to `UInt64.max` on overflow.
|
||||
public var totalSpace: UInt64 { get }
|
||||
|
||||
/// Number of free blocks in the file system.
|
||||
///
|
||||
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
|
||||
/// otherwise.
|
||||
///
|
||||
/// The corresponding C property is `f_bfree`.
|
||||
public var freeBlocks: UInt64 { get set }
|
||||
|
||||
/// Free space in the file system, in bytes.
|
||||
///
|
||||
/// - Note: Computed for convenience as `freeBlocks` times the fundamental
|
||||
/// block size (see `freeBlocks`). Saturates to `UInt64.max` on overflow.
|
||||
public var freeSpace: UInt64 { get }
|
||||
|
||||
/// Number of free blocks available to non-superuser.
|
||||
///
|
||||
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
|
||||
/// otherwise. On FreeBSD and OpenBSD, the underlying C property is
|
||||
/// signed; negative values are clamped to 0.
|
||||
///
|
||||
/// The corresponding C property is `f_bavail`.
|
||||
public var availableBlocks: UInt64 { get set }
|
||||
|
||||
/// Available space in the file system for non-superuser, in bytes.
|
||||
///
|
||||
/// - Note: Computed for convenience as `availableBlocks` times the fundamental
|
||||
/// block size (see `availableBlocks`). Saturates to `UInt64.max` on overflow.
|
||||
public var availableSpace: UInt64 { get }
|
||||
|
||||
/// Total number of inodes in the file system.
|
||||
///
|
||||
/// The corresponding C property is `f_files`.
|
||||
public var totalInodes: UInt64 { get set }
|
||||
|
||||
/// Number of free inodes in the file system.
|
||||
///
|
||||
/// - Note: On FreeBSD, this reports the inodes available to a non-superuser
|
||||
/// rather than the total free count, and the underlying C field is signed
|
||||
/// (negative values are clamped to 0); on other platforms, it is the total
|
||||
/// number of free inodes.
|
||||
///
|
||||
/// The corresponding C property is `f_ffree`.
|
||||
public var freeInodes: UInt64 { get set }
|
||||
|
||||
#if os(OpenBSD)
|
||||
/// Number of free inodes available to non-superuser.
|
||||
///
|
||||
/// - Note: Darwin, FreeBSD, Linux, and Android `statfs` do not report it.
|
||||
/// On OpenBSD, the underlying C property is signed; negative values are
|
||||
/// clamped to 0.
|
||||
///
|
||||
/// The corresponding C property is `f_favail`.
|
||||
public var availableInodes: UInt64 { get set }
|
||||
#endif
|
||||
|
||||
#if !os(anyAppleOS)
|
||||
/// Maximum length of a file name on the file system, in bytes.
|
||||
///
|
||||
/// - Note: Darwin's `statfs` does not report it.
|
||||
///
|
||||
/// The corresponding C property is `f_namelen` on Linux and Android, or
|
||||
/// `f_namemax` otherwise.
|
||||
public var maximumNameLength: Int { get set }
|
||||
#endif
|
||||
|
||||
/// File system ID.
|
||||
///
|
||||
/// The corresponding C property is `f_fsid`.
|
||||
public var fileSystemID: FileSystemID { get set }
|
||||
|
||||
/// Flags describing how the file system is mounted.
|
||||
///
|
||||
/// - Note: On Linux, the kernel also sets an `ST_VALID` bit in `f_flags`
|
||||
/// to mark the field as filled in. It isn't a mount flag, so this
|
||||
/// property omits it like glibc's `statvfs` and Bionic's `statfs` do.
|
||||
/// The setter preserves it.
|
||||
///
|
||||
/// The corresponding C property is `f_flags`.
|
||||
public var mountFlags: MountFlags { get set }
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
/// File system type.
|
||||
///
|
||||
/// - Note: This is the file system's magic number, such as `0xEF53` for
|
||||
/// ext4. Only available on Linux and Android. On Darwin and BSD, use
|
||||
/// `typeName` to identify the file system.
|
||||
///
|
||||
/// The corresponding C property is `f_type`.
|
||||
public var type: FileSystemType { get set }
|
||||
#endif
|
||||
|
||||
#if os(anyAppleOS)
|
||||
/// File system subtype.
|
||||
///
|
||||
/// - Note: This is a numeric value whose meaning depends on `typeName`,
|
||||
/// with no stable, public constants. Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C property is `f_fssubtype`.
|
||||
public var subtype: FileSystemSubtype { get set }
|
||||
#endif
|
||||
|
||||
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
|
||||
/// User that mounted the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_owner`.
|
||||
public var owner: UserID { get set }
|
||||
|
||||
/// File system type name, such as "apfs".
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_fstypename`.
|
||||
public var typeName: FileSystemTypeName { get }
|
||||
|
||||
/// Directory where the file system is mounted, such as "/System/Volumes/Data".
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_mntonname`.
|
||||
public var mountPoint: FilePath { get }
|
||||
|
||||
/// The source of the mounted file system, such as "/dev/disk3s7".
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_mntfromname`.
|
||||
public var mountSource: FilePath { get }
|
||||
#endif
|
||||
|
||||
/// Compares the file system metadata fields of two `StatFS` values,
|
||||
/// including fields not exposed as properties, such as `f_flags_ext` on
|
||||
/// Darwin.
|
||||
///
|
||||
/// Fields are compared by their raw C values. Reserved/"spare" fields and
|
||||
/// OpenBSD's `mount_info` union are not compared. Name buffers are compared
|
||||
/// only up to their NUL terminators.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool
|
||||
|
||||
/// Hashes the file system metadata fields of a `StatFS` struct.
|
||||
///
|
||||
/// These are the same fields compared by `==`. Reserved/"spare" fields are
|
||||
/// not hashed, and name buffers are hashed only up to their NUL terminators.
|
||||
public func hash(into hasher: inout Hasher)
|
||||
}
|
||||
```
|
||||
|
||||
`typeName`, `mountPoint`, and `mountSource` are get-only because they are backed by fixed-size C character buffers, which a non-throwing setter could not safely fill without risking silent truncation. Callers that need to write these fields can do so through `rawValue` directly.
|
||||
|
||||
`StatFS` conforms to `Hashable` (and therefore `Equatable`) by comparing and hashing the raw values of its C fields, as `Stat` does, so two `StatFS` values are equal when their `rawValue`s match in every meaningful field. Comparing the clamped properties instead would treat different raw values like two negative `f_bavail` counts as equal, and would ignore fields without a property. A byte-wise comparison would be unreliable because the bytes following each name buffer's NUL terminator are unspecified, and the struct may carry reserved/spare padding.
|
||||
|
||||
### CInterop extensions
|
||||
|
||||
This proposal extends the existing `CInterop` namespace with platform-appropriate typealiases for the underlying C types. Each is used as the `rawValue` for a corresponding strongly-typed representation.
|
||||
|
||||
```swift
|
||||
extension CInterop {
|
||||
/// The C `statfs` struct.
|
||||
public typealias StatFS = statfs
|
||||
|
||||
public typealias FileSystemID = fsid_t
|
||||
|
||||
#if os(anyAppleOS) || os(OpenBSD)
|
||||
public typealias MountFlags = UInt32
|
||||
#elseif os(FreeBSD)
|
||||
public typealias MountFlags = UInt64
|
||||
#else
|
||||
public typealias MountFlags = CUnsignedLong
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
All three have the same availability as the rest of this proposal.
|
||||
|
||||
### Vending `struct statfs` on glibc platforms
|
||||
|
||||
Unlike the Musl and Android modules, Swift's Glibc module doesn't export `<sys/vfs.h>`, which declares `struct statfs`. On glibc platforms, System therefore vends `struct statfs` from a new module, `CSystemStatFS`, that contains only this header, and re-exports it so clients can access `rawValue`'s fields under `MemberImportVisibility`. As a result, importing System on glibc platforms also brings C's `statfs()` and `fstatfs()` into scope. The Glibc module does export `fsid_t`, so accessing the `__val` field of a `CInterop.FileSystemID` under `MemberImportVisibility` requires importing Glibc.
|
||||
|
||||
### Availability on Windows and WASI
|
||||
|
||||
Windows has no `statfs`/`statvfs`. Rather than omit the type there, where usage would fail with an unhelpful `cannot find 'StatFS' in scope`, we declare an unavailable stub with a message suggesting the relevant Win32 APIs. In the future, the message could suggest dedicated System APIs instead.
|
||||
|
||||
`wasi-libc` has no `statfs`, and in the current `wasi-libc`, `statvfs` and `fstatvfs` are unconditional stubs (in `libc-bottom-half/sources/posix.c`) that set `errno` to `ENOSYS` and return `-1`:
|
||||
|
||||
```c
|
||||
int statvfs(const char *__restrict path, struct statvfs *__restrict buf) {
|
||||
// TODO: We plan to support this eventually in WASI, but not yet.
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
```
|
||||
|
||||
As a result, `StatFS` initializers would always fail at runtime on WASI and throw `Errno.noFunction`, so WASI gets an unavailable stub as well.
|
||||
|
||||
```swift
|
||||
#if os(Windows)
|
||||
@available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.")
|
||||
public struct StatFS {
|
||||
public init(_ path: FilePath, retryOnInterrupt: Bool = true) throws(Errno)
|
||||
public init(_ path: UnsafePointer<CChar>, retryOnInterrupt: Bool = true) throws(Errno)
|
||||
public init(_ fd: FileDescriptor, retryOnInterrupt: Bool = true) throws(Errno)
|
||||
}
|
||||
#elseif os(WASI)
|
||||
@available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.")
|
||||
public struct StatFS {
|
||||
// The same three initializers
|
||||
}
|
||||
#else
|
||||
// ...
|
||||
#endif
|
||||
```
|
||||
|
||||
Marking the type covers the three throwing initializers each stub declares. The other types and `CInterop` additions in this proposal aren't declared on either platform.
|
||||
|
||||
## Source compatibility
|
||||
|
||||
This proposal is additive, but on glibc platforms, clients that already vend `struct statfs` from their own module (since Swift's Glibc module doesn't export it) may need to import both that module and System in each file that accesses `statfs` fields. When two modules declare the same C struct, `MemberImportVisibility` attributes its fields to the module the compiler reaches the struct through first, which can differ between debug and release builds. In testing, a client that used `StatFS.rawValue` in one file and its own module's `statfs` in another built in debug but failed in release, reporting a missing import of `CSystemStatFS`.
|
||||
|
||||
## ABI compatibility
|
||||
|
||||
This proposal is additive and ABI-compatible with existing code.
|
||||
|
||||
## Implications on adoption
|
||||
|
||||
This feature can be freely adopted and un-adopted in source code with no deployment constraints and without affecting source or ABI compatibility.
|
||||
|
||||
## Future directions
|
||||
|
||||
To remain faithful to the underlying system calls, we don't anticipate extending `StatFS`. However, the types introduced in this proposal could serve as the foundation of broader file system APIs in Swift.
|
||||
|
||||
For instance, on Darwin and BSD, `MountFlags` could be useful for a future `mount()` implementation, and a future Swift wrapper of `getfsstat()` could return an array of `StatFS` structs.
|
||||
|
||||
A Linux `mount(2)` wrapper would look different. There, the flags `statfs` reports (`ST_*`) are a distinct set from the flags `mount(2)` accepts (`MS_*`), so a mount wrapper would need its own input type rather than reusing `MountFlags`. The `MS_*` set also mixes per-mount options with operation selectors like bind, move, remount, and propagation changes, so an idiomatic wrapper would likely split these into separate functions. A new implementation might also prefer the newer `fsopen` / `fsmount` / `move_mount` family over classic `mount(2)`. Because Linux's `mount` signature differs from Darwin's and BSD's, any such wrapper would be platform-specific.
|
||||
|
||||
Once `wasi-libc` implements `statvfs`, a future proposal could make `StatFS` available on WASI by wrapping `statvfs` and `fstatvfs`.
|
||||
|
||||
On Darwin, `f_flags_ext` reports extended flags such as `MNT_EXT_ROOT_DATA_VOL` and `MNT_EXT_FSKIT`. They're reachable through `rawValue` today, and a future proposal could expose them as their own option set.
|
||||
|
||||
If Swift's Glibc module exports `<sys/vfs.h>` in the future, `CSystemStatFS` would become redundant. System could keep re-exporting it, but accessing `rawValue`'s fields under `MemberImportVisibility` would then require importing Glibc, as with `CInterop.Stat`.
|
||||
|
||||
While this proposal does not include `StatFS` on Windows, SYS-0017 proposes `volumeInformation()` on `Win32.FileHandle`, a Swift-native wrapper of `GetVolumeInformationByHandleW`. Other volume APIs, such as `GetDiskFreeSpaceExW` and `DeviceIoControl`, could follow with their associated types.
|
||||
|
||||
A more general `FileSystemInfo` API could then build on these OS-specific types to provide an ergonomic, cross-platform abstraction for file system metadata. These future cross-platform APIs might be better implemented outside of System, such as in Foundation or another dedicated package.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### `FileSystemInfo` as the lowest-level type
|
||||
|
||||
An alternative approach could be to have a more general `FileSystemInfo` type be the lowest level of abstraction provided by the System library. This type would then handle all the `statfs` or Windows-specific struct storage and accessors. However, this alternative:
|
||||
|
||||
- Is inconsistent with System's philosophy of providing low-level system abstractions.
|
||||
- Introduces an even larger number of system-specific APIs on each type.
|
||||
- Misses out on the familiarity of the `statfs` name. Developers know what to look for and what to expect from this type.
|
||||
|
||||
### Single combined type for both file and file system metadata
|
||||
|
||||
Combining `Stat` ([SYS-0006](https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md)) and `StatFS` into a single type was considered but rejected because file and file system information serve different purposes and are typically needed in different contexts. Storing and/or initializing both `stat` and `statfs` structs unnecessarily reduces performance when one isn't needed.
|
||||
|
||||
### Separate `StatFS` and `StatVFS` types
|
||||
|
||||
Having separate types for `statfs` and `statvfs` would increase cognitive overhead and confusion for developers deciding which to choose. It would require additional documentation explaining differences that are transparently handled by platform availability, and would require duplicate code. On operating systems where `statfs` exposes additional information, such as Darwin, FreeBSD, and Linux, `statvfs` is just a wrapper around `statfs`, so there's little upside to providing a `StatVFS` type here. One upside might be that all properties of `StatVFS` would be available where the struct itself is available, but this likely doesn't outweigh the cost of having two types.
|
||||
|
||||
### Use `statvfs` on Linux and Android
|
||||
|
||||
`statvfs` is the POSIX interface, and the Glibc, Musl, and Android modules all export it, so System wouldn't need a `CSystemStatFS` module, which can conflict with clients' own `statfs` modules (see **Source compatibility**). However, on Linux, `statvfs` is also a wrapper around `statfs`, and it drops useful information: 1) with Bionic or glibc before 2.39, `f_type`, the file system magic number (such as `0xEF53` for ext4) that Linux code conventionally uses to identify a file system is absent; and 2) with musl or 32-bit platforms, half of the 2-word `fsid_t` is omitted. `statvfs`'s only extra field, `f_favail`, is a copy of `f_ffree` in glibc, musl, and Bionic.
|
||||
|
||||
### Add `statfs()` methods to `FilePath` and `FileDescriptor`
|
||||
|
||||
Like `FilePath.stat()` and `FileDescriptor.stat()` in [SYS-0006](https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md), `StatFS` could offer `statfs()` methods alongside its initializers. However, `statfs` describes the file system containing a file rather than the file itself, so it's not as closely tied to the individual `FilePath` or `FileDescriptor`. The proposed initializers can still chain, as in `try StatFS(path).availableSpace`.
|
||||
|
||||
The methods would also shadow the C `statfs` struct initializer and function inside extensions of those types, so existing code that calls them unqualified there would no longer compile. [SYS-0008](0008-backdeploy-cinterop-stat.md) back-deployed `CInterop.stat(_:_:)` as a migration path for the same issue with `stat()`. Leaving out the methods avoids the break and the need for new `CInterop` APIs. They could always be added later, along with a migration path, if desired.
|
||||
|
||||
### Expose `type` and `subtype` as raw integers
|
||||
|
||||
`FileSystemType` and `FileSystemSubtype` wrap `UInt32` values that, except for Linux magic numbers, have no stable, public constants, so exposing `type` and `subtype` as bare `UInt32` was considered. We keep the wrapper types for fidelity to the underlying struct and for consistency with `FileSystemID`, which is similarly opaque. The wrappers also give these fields distinct types, avoiding accidental cross-comparisons and granting flexibility to add members later, if desired.
|
||||
|
||||
### Expose `typeName` as a `String`
|
||||
|
||||
`typeName` could be a `String` like Foundation's `volumeTypeName` resource value. Unlike Linux magic numbers, type names are already readable, so `typeName == "apfs"` works about as well as a constant would. However, a wrapper allows us to provide constants like `.apfs`, which help with discoverability and avoid mistakes like comparing against `"APFS"`. And `ExpressibleByStringLiteral` allows us to still keep the ergonomics of literal comparison.
|
||||
|
||||
### Make `StatFS` available on WASI
|
||||
|
||||
`StatFS` could wrap `statvfs` and `fstatvfs` on WASI, as v1 of this proposal did. This would let developers write code that is otherwise portable across Unix-like platforms, and since clients calling `try StatFS(...)` are expected to handle a potential `Errno`, the always-failing calls wouldn't degrade ergonomics. It would also keep the availability coupled: once `wasi-libc` gains real `statvfs` support, System would pick it up automatically without needing to track it.
|
||||
|
||||
However, the portability would only be at compile time, since every call would throw `Errno.noFunction`. The WASI mappings, such as reading `mountFlags` from `f_flag` and an integer `FileSystemID` that other platforms can't decode, would also be designed against `wasi-libc`'s stubs. Leaving WASI out also lets `StatFS` wrap `statfs` on every platform where it's available, instead of `statvfs` on WASI alone. Making `StatFS` available later is additive, while reshaping it after it ships would be source-breaking.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Thank you to Michael Ilseman for discussions on the shape and future directions of this API.
|
||||
|
||||
## Appendix
|
||||
|
||||
### Swift API to C mapping
|
||||
|
||||
The following tables show the mapping between Swift APIs and their underlying C system calls across different operating systems:
|
||||
|
||||
#### `StatFS` function mappings
|
||||
|
||||
The `retryOnInterrupt: Bool = true` parameter is omitted for clarity.
|
||||
|
||||
| Swift API | Darwin / BSD / Linux / Android |
|
||||
|-----------|--------------------------------|
|
||||
| `StatFS(_ path: UnsafePointer<CChar>)` | `statfs()` |
|
||||
| `StatFS(_ path: FilePath)` | `statfs()` |
|
||||
| | |
|
||||
| `StatFS(_ fd: FileDescriptor)` | `fstatfs()` |
|
||||
|
||||
#### `StatFS` property mappings
|
||||
|
||||
`"` denotes the same property name across all operating systems.
|
||||
|
||||
| Swift Property | Darwin | FreeBSD | OpenBSD | Linux | Android |
|
||||
|----------------|--------|---------|---------|-------|---------|
|
||||
| `blockSize` | `f_bsize` | " | " | " | " |
|
||||
| `preferredIOBlockSize` | `f_iosize` | `f_iosize` | `f_iosize` | N/A | N/A |
|
||||
| `fragmentSize` | N/A | N/A | N/A | `f_frsize` | `f_frsize` |
|
||||
| `totalBlocks` | `f_blocks` | " | " | " | " |
|
||||
| `freeBlocks` | `f_bfree` | " | " | " | " |
|
||||
| `availableBlocks` | `f_bavail` | " | " | " | " |
|
||||
| `totalInodes` | `f_files` | " | " | " | " |
|
||||
| `freeInodes` | `f_ffree` | " | " | " | " |
|
||||
| `availableInodes` | N/A | N/A | `f_favail` | N/A | N/A |
|
||||
| `maximumNameLength` | N/A | `f_namemax` | `f_namemax` | `f_namelen` | `f_namelen` |
|
||||
| `fileSystemID` | `f_fsid` | " | " | " | " |
|
||||
| `mountFlags` | `f_flags` | " | " | " | " |
|
||||
| `type` | N/A | N/A | N/A | `f_type` | `f_type` |
|
||||
| `subtype` | `f_fssubtype` | N/A | N/A | N/A | N/A |
|
||||
| `owner` | `f_owner` | `f_owner` | `f_owner` | N/A | N/A |
|
||||
| `typeName` | `f_fstypename` | `f_fstypename` | `f_fstypename` | N/A | N/A |
|
||||
| `mountPoint` | `f_mntonname` | `f_mntonname` | `f_mntonname` | N/A | N/A |
|
||||
| `mountSource` | `f_mntfromname` | `f_mntfromname` | `f_mntfromname` | N/A | N/A |
|
||||
|
||||
#### `MountFlags` mappings
|
||||
|
||||
| Swift Flag | Darwin | FreeBSD | OpenBSD | Linux | Android |
|
||||
|------------|--------|---------|---------|-------|---------|
|
||||
| `readOnly` | `MNT_RDONLY` | `MNT_RDONLY` | `MNT_RDONLY` | `ST_RDONLY` | `ST_RDONLY` |
|
||||
| `synchronous` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `ST_SYNCHRONOUS` | `ST_SYNCHRONOUS` |
|
||||
| `noExecution` | `MNT_NOEXEC` | `MNT_NOEXEC` | `MNT_NOEXEC` | `ST_NOEXEC` | `ST_NOEXEC` |
|
||||
| `noSetUserID` | `MNT_NOSUID` | `MNT_NOSUID` | `MNT_NOSUID` | `ST_NOSUID` | `ST_NOSUID` |
|
||||
| `noAccessTime` | `MNT_NOATIME` | `MNT_NOATIME` | `MNT_NOATIME` | `ST_NOATIME` | `ST_NOATIME` |
|
||||
| `noDevices` | `MNT_NODEV` | N/A | `MNT_NODEV` | `ST_NODEV` | `ST_NODEV` |
|
||||
| `mandatoryLocking` | N/A | N/A | N/A | `ST_MANDLOCK` | `ST_MANDLOCK` |
|
||||
| `noDirectoryAccessTime` | N/A | N/A | N/A | `ST_NODIRATIME` | `ST_NODIRATIME` |
|
||||
| `relativeAccessTime` | N/A | N/A | N/A | `ST_RELATIME` | `ST_RELATIME` |
|
||||
| `noSymlinkFollowing` | N/A | `MNT_NOSYMFOLLOW` | N/A | `ST_NOSYMFOLLOW` | `ST_NOSYMFOLLOW` |
|
||||
| `asynchronous` | `MNT_ASYNC` | `MNT_ASYNC` | `MNT_ASYNC` | N/A | N/A |
|
||||
| `exported` | `MNT_EXPORTED` | `MNT_EXPORTED` | `MNT_EXPORTED` | N/A | N/A |
|
||||
| `local` | `MNT_LOCAL` | `MNT_LOCAL` | `MNT_LOCAL` | N/A | N/A |
|
||||
| `quotasEnabled` | `MNT_QUOTA` | `MNT_QUOTA` | `MNT_QUOTA` | N/A | N/A |
|
||||
| `rootFileSystem` | `MNT_ROOTFS` | `MNT_ROOTFS` | `MNT_ROOTFS` | N/A | N/A |
|
||||
| `union` | `MNT_UNION` | `MNT_UNION` | N/A | N/A | N/A |
|
||||
| `automounted` | `MNT_AUTOMOUNTED` | `MNT_AUTOMOUNTED` | N/A | N/A | N/A |
|
||||
| `multiLabel` | `MNT_MULTILABEL` | `MNT_MULTILABEL` | N/A | N/A | N/A |
|
||||
| `exportedReadOnly` | N/A | `MNT_EXRDONLY` | `MNT_EXRDONLY` | N/A | N/A |
|
||||
| `exportedByDefault` | N/A | `MNT_DEFEXPORTED` | `MNT_DEFEXPORTED` | N/A | N/A |
|
||||
| `exportedAnonymously` | N/A | `MNT_EXPORTANON` | `MNT_EXPORTANON` | N/A | N/A |
|
||||
| `softUpdates` | N/A | `MNT_SOFTDEP` | `MNT_SOFTDEP` | N/A | N/A |
|
||||
| `contentProtection` | `MNT_CPROTECT` | N/A | N/A | N/A | N/A |
|
||||
| `removable` | `MNT_REMOVABLE` | N/A | N/A | N/A | N/A |
|
||||
| `quarantined` | `MNT_QUARANTINE` | N/A | N/A | N/A | N/A |
|
||||
| `supportsVolfs` | `MNT_DOVOLFS` | N/A | N/A | N/A | N/A |
|
||||
| `noBrowsing` | `MNT_DONTBROWSE` | N/A | N/A | N/A | N/A |
|
||||
| `ignoresOwnership` | `MNT_IGNORE_OWNERSHIP` | N/A | N/A | N/A | N/A |
|
||||
| `journaled` | `MNT_JOURNALED` | N/A | N/A | N/A | N/A |
|
||||
| `noUserExtendedAttributes` | `MNT_NOUSERXATTR` | N/A | N/A | N/A | N/A |
|
||||
| `defersWrites` | `MNT_DEFWRITE` | N/A | N/A | N/A | N/A |
|
||||
| `noSymlinkFollowingAtMountPoint` | `MNT_NOFOLLOW` | N/A | N/A | N/A | N/A |
|
||||
| `snapshot` | `MNT_SNAPSHOT` | N/A | N/A | N/A | N/A |
|
||||
| `strictAccessTime` | `MNT_STRICTATIME` | N/A | N/A | N/A | N/A |
|
||||
| `exportedWithKerberos` | N/A | `MNT_EXKERB` | N/A | N/A | N/A |
|
||||
| `exportedPublicly` | N/A | `MNT_EXPUBLIC` | N/A | N/A | N/A |
|
||||
| `posixACLs` | N/A | `MNT_ACLS` | N/A | N/A | N/A |
|
||||
| `geomJournaled` | N/A | `MNT_GJOURNAL` | N/A | N/A | N/A |
|
||||
| `excludedFromDiskFreeReports` | N/A | `MNT_IGNORE` | N/A | N/A | N/A |
|
||||
| `nfs4ACLs` | N/A | `MNT_NFS4ACLS` | N/A | N/A | N/A |
|
||||
| `noClusteredReads` | N/A | `MNT_NOCLUSTERR` | N/A | N/A | N/A |
|
||||
| `noClusteredWrites` | N/A | `MNT_NOCLUSTERW` | N/A | N/A | N/A |
|
||||
| `setUserIDDirectories` | N/A | `MNT_SUIDDIR` | N/A | N/A | N/A |
|
||||
| `softUpdatesJournaling` | N/A | `MNT_SUJ` | N/A | N/A | N/A |
|
||||
| `untrusted` | N/A | `MNT_UNTRUSTED` | N/A | N/A | N/A |
|
||||
| `userMounted` | N/A | `MNT_USER` | N/A | N/A | N/A |
|
||||
| `verified` | N/A | `MNT_VERIFIED` | N/A | N/A | N/A |
|
||||
| `noPermissionChecks` | N/A | N/A | `MNT_NOPERM` | N/A | N/A |
|
||||
| `writeExecuteAllowed` | N/A | N/A | `MNT_WXALLOWED` | N/A | N/A |
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
Swift System provides idiomatic interfaces to system calls and low-level currency types. Our vision is for System to act as the single home for low-level system interfaces for all supported Swift platforms.
|
||||
|
||||
## Multi-platform not Cross-platform
|
||||
## No Cross-platform Abstractions
|
||||
|
||||
System is a multi-platform library, not a cross-platform one. It provides a separate set of APIs and behaviors on every supported platform, closely reflecting the underlying OS interfaces. A single import will pull in the native platform interfaces specific for the targeted OS.
|
||||
Swift System is not a cross-platform library. It provides a separate set of APIs and behaviors on every supported platform, closely reflecting the underlying OS interfaces. A single import will pull in the native platform interfaces specific for the targeted OS.
|
||||
|
||||
Our immediate goal is to simplify building cross-platform libraries and applications such as SwiftNIO and SwiftPM. System does not eliminate the need for `#if os()` conditionals to implement cross-platform abstractions, but it does make it safer and more expressive to fill out the platform-specific parts.
|
||||
Our immediate goal is to simplify building cross-platform libraries and applications such as SwiftNIO and SwiftPM. It is not a design goal for System to eliminate the need for `#if os()` conditionals to implement cross-platform abstractions; rather, our goal is to make it safer and more expressive to fill out the platform-specific parts.
|
||||
|
||||
(That said, it is desirable to avoid unnecessary differences -- for example, when two operating systems share the same C name for a system call, ideally Swift System would expose them using the same Swift name. This is a particularly obvious expectation for system interfaces that implement an industry standard, such as POSIX.)
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -22,13 +24,15 @@ try fd.closeAfter {
|
||||
}
|
||||
```
|
||||
|
||||
[API documentation](https://swiftpackageindex.com/apple/swift-system/documentation/SystemPackage)
|
||||
|
||||
## Adding `SystemPackage` as a Dependency
|
||||
|
||||
To use the `SystemPackage` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.8.0"),
|
||||
```
|
||||
|
||||
Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
@@ -37,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.8.0"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
@@ -51,14 +55,75 @@ let package = Package(
|
||||
|
||||
## Source Stability
|
||||
|
||||
The Swift System package is source stable. The version numbers follow [Semantic Versioning][semver] -- source breaking changes to public API can only land in a new major version.
|
||||
At this time, the Swift System package supports three types of operating systems: Darwin-based, POSIX-like, and Windows. The source-stability status of the package differs according to the platform:
|
||||
|
||||
| Platform type | Source Stability |
|
||||
| ----------------- | --------------- |
|
||||
| Darwin (macOS, iOS, etc.) | Stable |
|
||||
| POSIX (Linux, WASI, etc.) | Stable |
|
||||
| Windows | Unstable |
|
||||
|
||||
The package version numbers follow [Semantic Versioning][semver] -- source breaking changes to source-stable public API can only land in a new major version. However, platforms for which support has not reached source stability may see source-breaking changes in a new minor version.
|
||||
|
||||
[semver]: https://semver.org
|
||||
|
||||
## Contributing
|
||||
The public API of the swift-system package consists of non-underscored declarations that are marked `public` in the `SystemPackage` module.
|
||||
|
||||
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
By "underscored declarations" we mean declarations that have a leading underscore anywhere in their fully qualified name. For instance, here are some names that wouldn't be considered part of the public API, even if they were technically marked public:
|
||||
|
||||
## LICENSE
|
||||
- `FooModule.Bar._someMember(value:)` (underscored member)
|
||||
- `FooModule._Bar.someMember` (underscored type)
|
||||
- `_FooModule.Bar` (underscored module)
|
||||
- `FooModule.Bar.init(_value:)` (underscored initializer)
|
||||
|
||||
Interfaces that aren't part of the public API may continue to change in any release, including patch releases. If you have a use case that requires using non-public APIs, please submit a Feature Request describing it! We'd like the public interface to be as useful as possible -- although preferably without compromising safety or limiting future evolution.
|
||||
|
||||
Future minor versions of the package may update these rules as needed.
|
||||
|
||||
## Toolchain Requirements
|
||||
|
||||
The following table maps existing package releases to their minimum required Swift toolchain release:
|
||||
|
||||
| Package version | Swift version | Xcode release |
|
||||
| ----------------------- | --------------- | ------------- |
|
||||
| swift-system 1.3.x | >= Swift 5.8 | >= Xcode 14.3 |
|
||||
| swift-system 1.4.0 through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 |
|
||||
| swift-system 1.7.0 through 1.8.x | >= Swift 6.1 | >= Xcode 16.3 |
|
||||
|
||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so.
|
||||
|
||||
(Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.)
|
||||
|
||||
## Licensing
|
||||
|
||||
See [LICENSE](LICENSE.txt) for license information.
|
||||
|
||||
## Contributing
|
||||
|
||||
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
### Branching Strategy
|
||||
|
||||
We maintain separate branches for each active minor version of the package:
|
||||
|
||||
| Package version | Branch |
|
||||
| ----------------------- | ----------- |
|
||||
| swift-system 1.3.x | release/1.3.0 |
|
||||
| swift-system 1.4.x | release/1.4.0 |
|
||||
| swift-system 1.5.x | release/1.5.0 |
|
||||
| swift-system 1.6.x | release/1.6.0 |
|
||||
| swift-system 1.7.x | release/1.7.0 |
|
||||
| swift-system 1.8.x | release/1.8.x |
|
||||
| swift-system 1.9.x (unreleased) | release/1.9.x |
|
||||
|
||||
Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction:
|
||||
|
||||
`release/1.8.x` → `release/1.9.x` → `main`
|
||||
|
||||
For example, anything landing on `release/1.8.x` will eventually appear on `release/1.9.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Merges into `release/1.9.x` and `main` are performed by the [release](.github/workflows/automerge_to_release.yml) and [main](.github/workflows/automerge_to_main.yml) automergers; propagation from older release branches is performed by project maintainers.)
|
||||
|
||||
### Code of Conduct
|
||||
|
||||
Like all Swift.org projects, we would like the Swift System project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc].
|
||||
|
||||
[coc]: https://github.com/apple/.github/blob/main/CODE_OF_CONDUCT.md
|
||||
@@ -8,4 +8,7 @@ See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_subdirectory(CSystem)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
add_subdirectory(CSystemStatFS)
|
||||
endif()
|
||||
add_subdirectory(System)
|
||||
@@ -1,20 +1,22 @@
|
||||
#[[
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(CSystem INTERFACE)
|
||||
target_include_directories(CSystem INTERFACE
|
||||
include)
|
||||
|
||||
add_library(CSystem STATIC shims.c)
|
||||
target_include_directories(CSystem PUBLIC
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
||||
$<INSTALL_INTERFACE:include/CSystem>)
|
||||
|
||||
install(FILES
|
||||
include/CSystemLinux.h
|
||||
include/CSystemWindows.h
|
||||
include/CSystemShared.h
|
||||
include/CSystemWASI.h
|
||||
include/io_uring.h
|
||||
include/module.modulemap
|
||||
DESTINATION include/CSystem)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -9,17 +9,36 @@
|
||||
|
||||
#ifdef __linux__
|
||||
|
||||
#include <sys/epoll.h>
|
||||
// Glibc doesn't export eventfd, which the tests use.
|
||||
#include <sys/eventfd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <sys/types.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
// Test-only getters for constants that require _GNU_SOURCE.
|
||||
unsigned long long _system_get_ST_RDONLY(void);
|
||||
unsigned long long _system_get_ST_NOSUID(void);
|
||||
unsigned long long _system_get_ST_NODEV(void);
|
||||
unsigned long long _system_get_ST_NOEXEC(void);
|
||||
unsigned long long _system_get_ST_SYNCHRONOUS(void);
|
||||
unsigned long long _system_get_ST_MANDLOCK(void);
|
||||
unsigned long long _system_get_ST_NOATIME(void);
|
||||
unsigned long long _system_get_ST_NODIRATIME(void);
|
||||
unsigned long long _system_get_ST_RELATIME(void);
|
||||
unsigned long long _system_get_ST_NOSYMFOLLOW(void);
|
||||
|
||||
#if !defined(__ANDROID__)
|
||||
#include <stddef.h>
|
||||
#include "io_uring.h"
|
||||
|
||||
// Defined in shims.c, which can include the libc headers they need.
|
||||
extern int csystem_io_uring_setup(unsigned int entries,
|
||||
struct io_uring_params *p);
|
||||
extern int csystem_io_uring_enter(int fd, unsigned int to_submit,
|
||||
unsigned int min_complete,
|
||||
unsigned int flags, void *sig);
|
||||
extern int csystem_io_uring_enter2(int fd, unsigned int to_submit,
|
||||
unsigned int min_complete,
|
||||
unsigned int flags, void *args, size_t sz);
|
||||
extern int csystem_io_uring_register(int fd, unsigned int opcode, void *arg,
|
||||
unsigned int nr_args);
|
||||
#endif // !defined(__ANDROID__)
|
||||
|
||||
#endif // __linux__
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if !defined(_WIN32)
|
||||
extern int csystem_posix_pipe2(int fildes[2], int flag);
|
||||
#endif
|
||||
|
||||
extern int csystem_posix_dup3(int fildes, int fildes2, int flag);
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
// Thread-safe replacement for strerror(3).
|
||||
//
|
||||
// Writes the message for `errnum` into `buf`, which holds `buflen` bytes, and
|
||||
// always NUL-terminates it if `buflen` is not zero. Returns 0 on success, or an
|
||||
// error number (e.g. EINVAL for an unknown `errnum`, ERANGE if the message was
|
||||
// truncated). A message that exactly fills the buffer is also reported as
|
||||
// ERANGE, because not every C library can tell that apart from truncation.
|
||||
// Even on failure, `buf` may contain a message such as "Unknown error 1234".
|
||||
//
|
||||
// This hides the differences between the XSI and GNU variants of strerror_r,
|
||||
// and uses strerror_s on Windows.
|
||||
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen);
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#if __wasi__
|
||||
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h> // For NAME_MAX
|
||||
|
||||
// wasi-libc defines the following constants in a way that Clang Importer can't
|
||||
// understand, so we need to expose them manually.
|
||||
static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; }
|
||||
static inline int32_t _getConst_O_APPEND(void) { return O_APPEND; }
|
||||
static inline int32_t _getConst_O_CREAT(void) { return O_CREAT; }
|
||||
static inline int32_t _getConst_O_DIRECTORY(void) { return O_DIRECTORY; }
|
||||
static inline int32_t _getConst_O_EXCL(void) { return O_EXCL; }
|
||||
static inline int32_t _getConst_O_NONBLOCK(void) { return O_NONBLOCK; }
|
||||
static inline int32_t _getConst_O_TRUNC(void) { return O_TRUNC; }
|
||||
static inline int32_t _getConst_O_WRONLY(void) { return O_WRONLY; }
|
||||
|
||||
static inline int32_t _getConst_EWOULDBLOCK(void) { return EWOULDBLOCK; }
|
||||
static inline int32_t _getConst_EOPNOTSUPP(void) { return EOPNOTSUPP; }
|
||||
|
||||
static inline uint8_t _getConst_DT_DIR(void) { return DT_DIR; }
|
||||
|
||||
// Modified dirent struct that can be imported to Swift
|
||||
struct _system_dirent {
|
||||
ino_t d_ino;
|
||||
unsigned char d_type;
|
||||
// char d_name[] cannot be imported to Swift
|
||||
char d_name[NAME_MAX + 1];
|
||||
};
|
||||
|
||||
// Convert WASI dirent with d_name[] to _system_dirent
|
||||
static inline
|
||||
struct _system_dirent *
|
||||
_system_dirent_from_wasi_dirent(const struct dirent *wasi_dirent) {
|
||||
|
||||
// Match readdir behavior and use thread-local storage for the converted dirent
|
||||
static __thread struct _system_dirent _converted_dirent;
|
||||
|
||||
if (wasi_dirent == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
memset(&_converted_dirent, 0, sizeof(struct _system_dirent));
|
||||
|
||||
_converted_dirent.d_ino = wasi_dirent->d_ino;
|
||||
_converted_dirent.d_type = wasi_dirent->d_type;
|
||||
|
||||
strncpy(_converted_dirent.d_name, wasi_dirent->d_name, NAME_MAX);
|
||||
_converted_dirent.d_name[NAME_MAX] = '\0';
|
||||
|
||||
return &_converted_dirent;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,17 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#define NOMINMAX
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define VC_EXTRA_LEAN
|
||||
#include <Windows.h>
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,208 @@
|
||||
#pragma once
|
||||
|
||||
// Types only: the syscall wrappers need libc headers, so they're in shims.c.
|
||||
|
||||
#define __SWIFT_IORING_SQE_FALLBACK_STRUCT { \
|
||||
__u8 opcode; \
|
||||
__u8 flags; \
|
||||
__u16 ioprio; \
|
||||
__s32 fd; \
|
||||
union { \
|
||||
__u64 off; \
|
||||
__u64 addr2; \
|
||||
struct { \
|
||||
__u32 cmd_op; \
|
||||
__u32 __pad1; \
|
||||
}; \
|
||||
}; \
|
||||
union { \
|
||||
__u64 addr; \
|
||||
__u64 splice_off_in; \
|
||||
struct { \
|
||||
__u32 level; \
|
||||
__u32 optname; \
|
||||
}; \
|
||||
}; \
|
||||
__u32 len; \
|
||||
union { \
|
||||
__kernel_rwf_t rw_flags; \
|
||||
__u32 fsync_flags; \
|
||||
__u16 poll_events; \
|
||||
__u32 poll32_events; \
|
||||
__u32 sync_range_flags; \
|
||||
__u32 msg_flags; \
|
||||
__u32 timeout_flags; \
|
||||
__u32 accept_flags; \
|
||||
__u32 cancel_flags; \
|
||||
__u32 open_flags; \
|
||||
__u32 statx_flags; \
|
||||
__u32 fadvise_advice; \
|
||||
__u32 splice_flags; \
|
||||
__u32 rename_flags; \
|
||||
__u32 unlink_flags; \
|
||||
__u32 hardlink_flags; \
|
||||
__u32 xattr_flags; \
|
||||
__u32 msg_ring_flags; \
|
||||
__u32 uring_cmd_flags; \
|
||||
__u32 waitid_flags; \
|
||||
__u32 futex_flags; \
|
||||
__u32 install_fd_flags; \
|
||||
__u32 nop_flags; \
|
||||
}; \
|
||||
__u64 user_data; \
|
||||
union { \
|
||||
__u16 buf_index; \
|
||||
__u16 buf_group; \
|
||||
} __attribute__((packed)); \
|
||||
__u16 personality; \
|
||||
union { \
|
||||
__s32 splice_fd_in; \
|
||||
__u32 file_index; \
|
||||
__u32 optlen; \
|
||||
struct { \
|
||||
__u16 addr_len; \
|
||||
__u16 __pad3[1]; \
|
||||
}; \
|
||||
}; \
|
||||
union { \
|
||||
struct { \
|
||||
__u64 addr3; \
|
||||
__u64 __pad2[1]; \
|
||||
}; \
|
||||
__u64 optval; \
|
||||
__u8 cmd[0]; \
|
||||
}; \
|
||||
}
|
||||
|
||||
#if __has_include(<linux/io_uring.h>)
|
||||
#include <linux/io_uring.h>
|
||||
|
||||
#ifdef IORING_TIMEOUT_BOOTTIME
|
||||
// Kernel version >= 5.15, io_uring_sqe has file_index
|
||||
// and all current Swift operations are supported.
|
||||
#define __SWIFT_IORING_SUPPORTED 1
|
||||
typedef struct io_uring_sqe swift_io_uring_sqe;
|
||||
#else
|
||||
// io_uring_sqe is missing properties that IORequest expects.
|
||||
// This configuration is not supported for now.
|
||||
//
|
||||
// Define a fallback struct to avoid build errors, but IORing
|
||||
// will throw ENOTSUP on initialization.
|
||||
#define __SWIFT_IORING_SUPPORTED 0
|
||||
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
#endif
|
||||
|
||||
// We can define more specific availability later
|
||||
|
||||
#ifdef IORING_FEAT_RW_CUR_POS
|
||||
// Kernel version >= 5.6, io_uring_sqe has open_flags
|
||||
#endif
|
||||
|
||||
#ifdef IORING_FEAT_NODROP
|
||||
// Kernel version >= 5.5, io_uring_sqe has cancel_flags
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK)
|
||||
#include <stdint.h>
|
||||
|
||||
#define __SWIFT_IORING_SUPPORTED 0
|
||||
|
||||
#define IORING_OFF_SQ_RING 0ULL
|
||||
#define IORING_OFF_CQ_RING 0x8000000ULL
|
||||
#define IORING_OFF_SQES 0x10000000ULL
|
||||
|
||||
#define IORING_ENTER_GETEVENTS (1U << 0)
|
||||
#define IORING_ENTER_EXT_ARG (1U << 3)
|
||||
|
||||
#define IORING_FEAT_SINGLE_MMAP (1U << 0)
|
||||
#define IORING_FEAT_NODROP (1U << 1)
|
||||
#define IORING_FEAT_SUBMIT_STABLE (1U << 2)
|
||||
#define IORING_FEAT_RW_CUR_POS (1U << 3)
|
||||
#define IORING_FEAT_CUR_PERSONALITY (1U << 4)
|
||||
#define IORING_FEAT_FAST_POLL (1U << 5)
|
||||
#define IORING_FEAT_POLL_32BITS (1U << 6)
|
||||
#define IORING_FEAT_SQPOLL_NONFIXED (1U << 7)
|
||||
#define IORING_FEAT_EXT_ARG (1U << 8)
|
||||
#define IORING_FEAT_NATIVE_WORKERS (1U << 9)
|
||||
#define IORING_FEAT_RSRC_TAGS (1U << 10)
|
||||
#define IORING_FEAT_CQE_SKIP (1U << 11)
|
||||
#define IORING_FEAT_LINKED_FILE (1U << 12)
|
||||
#define IORING_FEAT_REG_REG_RING (1U << 13)
|
||||
#define IORING_FEAT_RECVSEND_BUNDLE (1U << 14)
|
||||
#define IORING_FEAT_MIN_TIMEOUT (1U << 15)
|
||||
#define IORING_FEAT_RW_ATTR (1U << 16)
|
||||
#define IORING_FEAT_NO_IOWAIT (1U << 17)
|
||||
|
||||
#if !defined(_ASM_GENERIC_INT_LL64_H) && !defined(_ASM_GENERIC_INT_L64_H) && !defined(_UAPI_ASM_GENERIC_INT_LL64_H) && !defined(_UAPI_ASM_GENERIC_INT_L64_H)
|
||||
typedef uint8_t __u8;
|
||||
typedef uint16_t __u16;
|
||||
typedef uint32_t __u32;
|
||||
typedef uint64_t __u64;
|
||||
typedef int32_t __s32;
|
||||
#endif
|
||||
|
||||
#ifndef __kernel_rwf_t
|
||||
typedef int __kernel_rwf_t;
|
||||
#endif
|
||||
|
||||
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
|
||||
struct io_uring_cqe {
|
||||
__u64 user_data;
|
||||
__s32 res;
|
||||
__u32 flags;
|
||||
};
|
||||
|
||||
struct io_sqring_offsets {
|
||||
__u32 head;
|
||||
__u32 tail;
|
||||
__u32 ring_mask;
|
||||
__u32 ring_entries;
|
||||
__u32 flags;
|
||||
__u32 dropped;
|
||||
__u32 array;
|
||||
__u32 resv1;
|
||||
__u64 user_addr;
|
||||
};
|
||||
|
||||
struct io_cqring_offsets {
|
||||
__u32 head;
|
||||
__u32 tail;
|
||||
__u32 ring_mask;
|
||||
__u32 ring_entries;
|
||||
__u32 overflow;
|
||||
__u32 cqes;
|
||||
__u32 flags;
|
||||
__u32 resv1;
|
||||
__u64 user_addr;
|
||||
};
|
||||
|
||||
struct io_uring_params {
|
||||
__u32 sq_entries;
|
||||
__u32 cq_entries;
|
||||
__u32 flags;
|
||||
__u32 sq_thread_cpu;
|
||||
__u32 sq_thread_idle;
|
||||
__u32 features;
|
||||
__u32 wq_fd;
|
||||
__u32 resv[3];
|
||||
struct io_sqring_offsets sq_off;
|
||||
struct io_cqring_offsets cq_off;
|
||||
};
|
||||
#endif // __has_include(<linux/io_uring.h>)
|
||||
|
||||
/*
|
||||
struct io_uring_getevents_arg {
|
||||
__u64 sigmask;
|
||||
__u32 sigmask_sz;
|
||||
__u32 min_wait_usec; //used to be called `pad`. This compatibility wrapper avoids dealing with that.
|
||||
__u64 ts;
|
||||
};
|
||||
*/
|
||||
struct swift_io_uring_getevents_arg {
|
||||
__u64 sigmask;
|
||||
__u32 sigmask_sz;
|
||||
__u32 min_wait_usec;
|
||||
__u64 ts;
|
||||
};
|
||||
@@ -1,5 +1,17 @@
|
||||
// System imports CSystem with `internal import`. Don't include a header that
|
||||
// the platform's C module also includes: CSystem would then co-own its
|
||||
// declarations, so Swift would limit them to CSystem's import access level and
|
||||
// could credit their members to CSystem under MemberImportVisibility.
|
||||
// (CSystemWASI.h still does; see Constants.swift.)
|
||||
module CSystem {
|
||||
header "CSystemShared.h"
|
||||
header "CSystemLinux.h"
|
||||
header "CSystemWindows.h"
|
||||
header "CSystemWASI.h"
|
||||
export *
|
||||
}
|
||||
|
||||
// IORing's inlinable code stores these types, so System imports this module
|
||||
// with `public import`. Keep libc headers out of it too.
|
||||
module CSystemIOUring {
|
||||
header "io_uring.h"
|
||||
}
|
||||
+158
-3
@@ -1,18 +1,173 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#ifdef __linux__
|
||||
#if defined(__FreeBSD__)
|
||||
#define __BSD_VISIBLE
|
||||
#endif
|
||||
#if defined(__FreeBSD__) || defined(__OpenBSD__)
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef __linux__
|
||||
#define _GNU_SOURCE
|
||||
#include <signal.h>
|
||||
#include <sys/statvfs.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
#include <CSystemLinux.h>
|
||||
|
||||
unsigned long long _system_get_ST_RDONLY(void) { return ST_RDONLY; }
|
||||
unsigned long long _system_get_ST_NOSUID(void) { return ST_NOSUID; }
|
||||
unsigned long long _system_get_ST_NODEV(void) { return ST_NODEV; }
|
||||
unsigned long long _system_get_ST_NOEXEC(void) { return ST_NOEXEC; }
|
||||
unsigned long long _system_get_ST_SYNCHRONOUS(void) { return ST_SYNCHRONOUS; }
|
||||
unsigned long long _system_get_ST_MANDLOCK(void) { return ST_MANDLOCK; }
|
||||
unsigned long long _system_get_ST_NOATIME(void) { return ST_NOATIME; }
|
||||
unsigned long long _system_get_ST_NODIRATIME(void) { return ST_NODIRATIME; }
|
||||
unsigned long long _system_get_ST_RELATIME(void) { return ST_RELATIME; }
|
||||
|
||||
// ST_NOSYMFOLLOW wasn't defined until glibc 2.34. 0x2000 is the bit the
|
||||
// kernel's internal <linux/statfs.h> and newer glibc both use.
|
||||
#ifndef ST_NOSYMFOLLOW
|
||||
#define ST_NOSYMFOLLOW 0x2000
|
||||
#endif
|
||||
unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; }
|
||||
#endif
|
||||
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <CSystemShared.h>
|
||||
|
||||
static int csystem_strerror_r_impl(int errnum, char *buf, size_t buflen) {
|
||||
#if defined(_WIN32)
|
||||
#include <CSystemWindows.h>
|
||||
return strerror_s(buf, buflen, errnum);
|
||||
#elif defined(_GNU_SOURCE) && \
|
||||
(defined(__GLIBC__) || (defined(__ANDROID__) && __ANDROID_API__ >= 23))
|
||||
// With _GNU_SOURCE (defined above on Linux), glibc and bionic provide the
|
||||
// GNU variant, which returns a pointer to the message. That pointer is
|
||||
// either `buf` or an immutable static string, so copying from it is safe.
|
||||
const char *message = strerror_r(errnum, buf, buflen);
|
||||
if (message == NULL) {
|
||||
return EINVAL;
|
||||
}
|
||||
if (message != buf) {
|
||||
size_t length = strlen(message);
|
||||
if (length >= buflen) {
|
||||
memcpy(buf, message, buflen - 1);
|
||||
buf[buflen - 1] = '\0';
|
||||
return ERANGE;
|
||||
}
|
||||
memcpy(buf, message, length + 1);
|
||||
}
|
||||
return 0;
|
||||
#else
|
||||
// XSI variant (Darwin, FreeBSD, OpenBSD, musl, WASI). Some implementations
|
||||
// return -1 and set errno instead of returning the error number.
|
||||
int result = strerror_r(errnum, buf, buflen);
|
||||
if (result == -1) {
|
||||
result = errno;
|
||||
}
|
||||
return result;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen) {
|
||||
if (buf == NULL || buflen == 0) {
|
||||
return ERANGE;
|
||||
}
|
||||
buf[0] = '\0';
|
||||
int result = csystem_strerror_r_impl(errnum, buf, buflen);
|
||||
buf[buflen - 1] = '\0';
|
||||
// strerror_s on Windows and bionic's strerror_r silently truncate the
|
||||
// message and return 0. Report a message that fills the whole buffer as
|
||||
// ERANGE on every platform, since it may have been truncated.
|
||||
if (result == 0 && strlen(buf) == buflen - 1) {
|
||||
result = ERANGE;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__)
|
||||
#define HAVE_PIPE2_DUP3
|
||||
#endif
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#include <Availability.h>
|
||||
#if defined(__MAC_27_0)
|
||||
#include <unistd.h>
|
||||
#define HAVE_PIPE2_DUP3
|
||||
#endif
|
||||
#endif // defined(__APPLE__)
|
||||
|
||||
// Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h
|
||||
|
||||
#if !defined(_WIN32)
|
||||
extern int csystem_posix_pipe2(int fildes[2], int flag) {
|
||||
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
|
||||
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
|
||||
return pipe2(fildes, flag);
|
||||
__builtin_trap();
|
||||
#elif defined(HAVE_PIPE2_DUP3)
|
||||
return pipe2(fildes, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
#endif // !defined(_WIN32)
|
||||
|
||||
extern int csystem_posix_dup3(int fildes, int fildes2, int flag) {
|
||||
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
|
||||
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
|
||||
return dup3(fildes, fildes2, flag);
|
||||
__builtin_trap();
|
||||
#elif defined(HAVE_PIPE2_DUP3)
|
||||
return dup3(fildes, fildes2, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
# ifndef __NR_io_uring_setup
|
||||
# define __NR_io_uring_setup 425
|
||||
# endif
|
||||
# ifndef __NR_io_uring_enter
|
||||
# define __NR_io_uring_enter 426
|
||||
# endif
|
||||
# ifndef __NR_io_uring_register
|
||||
# define __NR_io_uring_register 427
|
||||
# endif
|
||||
|
||||
extern int csystem_io_uring_setup(unsigned int entries,
|
||||
struct io_uring_params *p) {
|
||||
return syscall(__NR_io_uring_setup, entries, p);
|
||||
}
|
||||
|
||||
extern int csystem_io_uring_enter2(int fd, unsigned int to_submit,
|
||||
unsigned int min_complete,
|
||||
unsigned int flags, void *args, size_t sz) {
|
||||
return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags,
|
||||
args, sz);
|
||||
}
|
||||
|
||||
extern int csystem_io_uring_enter(int fd, unsigned int to_submit,
|
||||
unsigned int min_complete,
|
||||
unsigned int flags, void *sig) {
|
||||
return csystem_io_uring_enter2(fd, to_submit, min_complete, flags, sig,
|
||||
_NSIG / 8);
|
||||
}
|
||||
|
||||
extern int csystem_io_uring_register(int fd, unsigned int opcode, void *arg,
|
||||
unsigned int nr_args) {
|
||||
return syscall(__NR_io_uring_register, fd, opcode, arg, nr_args);
|
||||
}
|
||||
#endif // defined(__linux__) && !defined(__ANDROID__)
|
||||
@@ -0,0 +1,19 @@
|
||||
#[[
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(CSystemStatFS INTERFACE)
|
||||
target_include_directories(CSystemStatFS INTERFACE
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>"
|
||||
$<INSTALL_INTERFACE:include/CSystemStatFS>)
|
||||
|
||||
install(FILES
|
||||
CSystemStatFS.h
|
||||
module.modulemap
|
||||
DESTINATION include/CSystemStatFS)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystemStatFS)
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// Unlike the Musl and Android modules, Glibc doesn't export <sys/vfs.h>,
|
||||
// which declares `struct statfs` and `statfs()`/`fstatfs()`. SystemPackage
|
||||
// re-exports this module on glibc platforms so that clients can use the
|
||||
// raw `CInterop.StatFS` value under MemberImportVisibility.
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
#include <sys/vfs.h>
|
||||
#endif
|
||||
@@ -0,0 +1,4 @@
|
||||
module CSystemStatFS [system] {
|
||||
header "CSystemStatFS.h"
|
||||
export *
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#[[
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -9,6 +9,7 @@ See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
add_library(SystemPackage
|
||||
Errno.swift
|
||||
ErrnoWindows.swift
|
||||
FileDescriptor.swift
|
||||
FileHelpers.swift
|
||||
FileOperations.swift
|
||||
@@ -18,9 +19,32 @@ add_library(SystemPackage
|
||||
SystemString.swift
|
||||
Util.swift
|
||||
Util+StringArray.swift
|
||||
UtilConsumers.swift)
|
||||
UtilConsumers.swift
|
||||
WinSDK+Overlay.swift)
|
||||
set_target_properties(SystemPackage PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
# Availability macro definitions.
|
||||
# Should stay in sync with the `availability` array in Package.swift,
|
||||
# matching `sourceAvailability`, which is the minimum Swift availability.
|
||||
# Availability support for Darwin platforms is omitted.
|
||||
set(SWIFT_SYSTEM_AVAILABILITY_VERSIONS
|
||||
0.0.1 0.0.2 0.0.3
|
||||
1.1.0 1.1.1 1.2.0 1.2.1 1.3.0 1.3.1 1.3.2 1.4.0
|
||||
1.7.0 1.9.0
|
||||
199)
|
||||
set(SWIFT_SYSTEM_SOURCE_AVAILABILITY
|
||||
"macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0")
|
||||
set(SWIFT_SYSTEM_AVAILABILITY_MACRO)
|
||||
foreach(version IN LISTS SWIFT_SYSTEM_AVAILABILITY_VERSIONS)
|
||||
list(APPEND SWIFT_SYSTEM_AVAILABILITY_MACRO
|
||||
"SHELL:-enable-experimental-feature \"AvailabilityMacro=System ${version}:${SWIFT_SYSTEM_SOURCE_AVAILABILITY}\"")
|
||||
endforeach()
|
||||
|
||||
target_compile_options(SystemPackage PRIVATE
|
||||
-enable-experimental-feature Lifetimes
|
||||
${SWIFT_SYSTEM_AVAILABILITY_MACRO}
|
||||
"SHELL:-package-name swift-system")
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePath.swift
|
||||
FilePath/FilePathComponents.swift
|
||||
@@ -28,7 +52,27 @@ target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePathParsing.swift
|
||||
FilePath/FilePathString.swift
|
||||
FilePath/FilePathSyntax.swift
|
||||
FilePath/FilePathTemp.swift
|
||||
FilePath/FilePathTempPosix.swift
|
||||
FilePath/FilePathTempWindows.swift
|
||||
FilePath/FilePathWindows.swift)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FileSystem/FileFlags.swift
|
||||
FileSystem/FileMode.swift
|
||||
FileSystem/FileType.swift
|
||||
FileSystem/Identifiers.swift
|
||||
FileSystem/MountFlags.swift
|
||||
FileSystem/Stat.swift
|
||||
FileSystem/StatFS.swift)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
IORing/IOCompletion.swift
|
||||
IORing/IORequest.swift
|
||||
IORing/IORing.swift
|
||||
IORing/IORing+Util.swift
|
||||
IORing/PollEvents.swift
|
||||
IORing/RawIORequest.swift)
|
||||
endif()
|
||||
target_sources(SystemPackage PRIVATE
|
||||
Internals/Backcompat.swift
|
||||
Internals/CInterop.swift
|
||||
@@ -40,7 +84,15 @@ target_sources(SystemPackage PRIVATE
|
||||
Internals/WindowsSyscallAdapters.swift)
|
||||
target_link_libraries(SystemPackage PUBLIC
|
||||
CSystem)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_link_libraries(SystemPackage PUBLIC
|
||||
CSystemStatFS)
|
||||
endif()
|
||||
|
||||
set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS")
|
||||
if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS)
|
||||
target_compile_definitions(SystemPackage PRIVATE SYSTEM_PACKAGE_DARWIN)
|
||||
endif()
|
||||
|
||||
_install_target(SystemPackage)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage)
|
||||
+199
-139
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
import WinSDK
|
||||
|
||||
extension Errno {
|
||||
internal init(windowsError: DWORD) {
|
||||
self.init(rawValue: _mapWindowsErrorToErrno(windowsError))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+191
-43
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -14,7 +14,7 @@
|
||||
/// of `FileDescriptor` values,
|
||||
/// in the same way as you manage a raw C file handle.
|
||||
@frozen
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
/// The raw C file handle.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -26,7 +26,7 @@ public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
}
|
||||
|
||||
// Standard file descriptors.
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// The standard input file descriptor, with a numeric value of 0.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -41,11 +41,12 @@ extension FileDescriptor {
|
||||
public static var standardError: FileDescriptor { .init(rawValue: 2) }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// The desired read and write access for a newly opened file.
|
||||
@frozen
|
||||
public struct AccessMode: RawRepresentable, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct AccessMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C access mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -87,7 +88,8 @@ extension FileDescriptor {
|
||||
|
||||
/// Options that specify behavior for a newly-opened file.
|
||||
@frozen
|
||||
public struct OpenOptions: OptionSet, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct OpenOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -96,9 +98,6 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInt) { self.init(rawValue: raw) }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that opening the file doesn't
|
||||
/// wait for the file or device to become available.
|
||||
@@ -115,7 +114,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_NONBLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nonBlocking: OpenOptions { OpenOptions(_O_NONBLOCK) }
|
||||
public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "nonBlocking")
|
||||
@@ -131,7 +130,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_APPEND`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var append: OpenOptions { OpenOptions(_O_APPEND) }
|
||||
public static var append: OpenOptions { .init(rawValue: _O_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "append")
|
||||
@@ -141,7 +140,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_CREAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var create: OpenOptions { OpenOptions(_O_CREAT) }
|
||||
public static var create: OpenOptions { .init(rawValue: _O_CREAT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "create")
|
||||
@@ -155,7 +154,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_TRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var truncate: OpenOptions { OpenOptions(_O_TRUNC) }
|
||||
public static var truncate: OpenOptions { .init(rawValue: _O_TRUNC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "truncate")
|
||||
@@ -177,13 +176,13 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EXCL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exclusiveCreate: OpenOptions { OpenOptions(_O_EXCL) }
|
||||
public static var exclusiveCreate: OpenOptions { .init(rawValue: _O_EXCL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exclusiveCreate")
|
||||
public static var O_EXCL: OpenOptions { exclusiveCreate }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Indicates that opening the file
|
||||
/// atomically obtains a shared lock on the file.
|
||||
///
|
||||
@@ -195,7 +194,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_SHLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sharedLock: OpenOptions { OpenOptions(_O_SHLOCK) }
|
||||
public static var sharedLock: OpenOptions { .init(rawValue: _O_SHLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "sharedLock")
|
||||
@@ -212,7 +211,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EXLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exclusiveLock: OpenOptions { OpenOptions(_O_EXLOCK) }
|
||||
public static var exclusiveLock: OpenOptions { .init(rawValue: _O_EXLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exclusiveLock")
|
||||
@@ -230,7 +229,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_NOFOLLOW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noFollow: OpenOptions { OpenOptions(_O_NOFOLLOW) }
|
||||
public static var noFollow: OpenOptions { .init(rawValue: _O_NOFOLLOW) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "noFollow")
|
||||
@@ -244,14 +243,30 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_DIRECTORY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: OpenOptions { OpenOptions(_O_DIRECTORY) }
|
||||
public static var directory: OpenOptions { .init(rawValue: _O_DIRECTORY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "directory")
|
||||
public static var O_DIRECTORY: OpenOptions { directory }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if os(FreeBSD)
|
||||
/// Indicates that each write operation is synchronous.
|
||||
///
|
||||
/// If this option is specified,
|
||||
/// each time you write to the file,
|
||||
/// the new data is written immediately and synchronously to the disk.
|
||||
///
|
||||
/// The corresponding C constant is `O_SYNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sync: OpenOptions { .init(rawValue: _O_SYNC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "sync")
|
||||
public static var O_SYNC: OpenOptions { sync }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Indicates that opening the file
|
||||
/// opens symbolic links instead of following them.
|
||||
///
|
||||
@@ -263,7 +278,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_SYMLINK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlink: OpenOptions { OpenOptions(_O_SYMLINK) }
|
||||
public static var symlink: OpenOptions { .init(rawValue: _O_SYMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "symlink")
|
||||
@@ -279,39 +294,166 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EVTONLY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var eventOnly: OpenOptions { OpenOptions(_O_EVTONLY) }
|
||||
public static var eventOnly: OpenOptions { .init(rawValue: _O_EVTONLY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "eventOnly")
|
||||
public static var O_EVTONLY: OpenOptions { eventOnly }
|
||||
#endif
|
||||
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
/// across calls to the `exec(2)` family of functions.
|
||||
/// If you specify this option, the system closes the file
|
||||
/// descriptor when replacing this process with another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_CLOEXEC: OpenOptions { closeOnExec }
|
||||
|
||||
#if os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_NOINHERIT: OpenOptions { closeOnExec }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Options that specify behavior for a newly-created pipe.
|
||||
@frozen
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
/// Create a strongly-typed options value from raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that all subsequent input and output operations
|
||||
/// on the pipe's file descriptors will be nonblocking.
|
||||
///
|
||||
/// The corresponding C constant is `O_NONBLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nonBlocking: PipeOptions { .init(rawValue: _O_NONBLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "nonBlocking")
|
||||
public static var O_NONBLOCK: PipeOptions { nonBlocking }
|
||||
#endif // !os(Windows)
|
||||
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
/// across calls to the `exec(2)` family of functions.
|
||||
/// If you specify this option, the system closes the file
|
||||
/// descriptor when replacing this process with another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: PipeOptions { .init(rawValue: _O_CLOEXEC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_CLOEXEC: PipeOptions { closeOnExec }
|
||||
|
||||
#if os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_NOINHERIT: PipeOptions { closeOnExec }
|
||||
#endif
|
||||
|
||||
#if !os(Windows) && !os(WASI) && !os(Linux) && !os(Android)
|
||||
/// Indicates that forking a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
/// across calls to the `fork(2)` function.
|
||||
/// If you specify this option, the system closes the file
|
||||
/// descriptor when forking this process into another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOFORK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnFork: PipeOptions { .init(rawValue: _O_CLOFORK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnFork")
|
||||
public static var O_CLOFORK: PipeOptions { closeOnFork }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Options that specify behavior for a duplicated file descriptor.
|
||||
@frozen
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
/// Create a strongly-typed options value from raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
/// across calls to the `exec(2)` family of functions.
|
||||
/// If you specify this option,
|
||||
/// the file descriptor is closed when replacing this process
|
||||
/// with another process.
|
||||
/// If you specify this option, the system closes the file
|
||||
/// descriptor when replacing this process with another process.
|
||||
///
|
||||
/// The state of the file
|
||||
/// descriptor flags can be inspected using `F_GETFD`,
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: OpenOptions { OpenOptions(_O_CLOEXEC) }
|
||||
public static var closeOnExec: DuplicateOptions { .init(rawValue: _O_CLOEXEC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_CLOEXEC: OpenOptions { closeOnExec }
|
||||
public static var O_CLOEXEC: DuplicateOptions { closeOnExec }
|
||||
|
||||
#if !os(WASI) && !os(Linux) && !os(Android)
|
||||
/// Indicates that forking a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
/// across calls to the `fork(2)` function.
|
||||
/// If you specify this option, the system closes the file
|
||||
/// descriptor when forking this process into another process.
|
||||
///
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOFORK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnFork: DuplicateOptions { .init(rawValue: _O_CLOFORK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnFork")
|
||||
public static var O_CLOFORK: DuplicateOptions { closeOnFork }
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Options for specifying what a file descriptor's offset is relative to.
|
||||
@frozen
|
||||
public struct SeekOrigin: RawRepresentable, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct SeekOrigin: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -354,7 +496,7 @@ extension FileDescriptor {
|
||||
|
||||
// TODO: These are available on some versions of Linux with appropriate
|
||||
// macro defines.
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Indicates that the offset should be set
|
||||
/// to the next hole after the specified number of bytes.
|
||||
///
|
||||
@@ -382,11 +524,10 @@ extension FileDescriptor {
|
||||
@available(*, unavailable, renamed: "nextData")
|
||||
public static var SEEK_DATA: SeekOrigin { nextData }
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor.AccessMode
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -405,7 +546,7 @@ extension FileDescriptor.AccessMode
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor.SeekOrigin
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -416,7 +557,7 @@ extension FileDescriptor.SeekOrigin
|
||||
case .start: return "start"
|
||||
case .current: return "current"
|
||||
case .end: return "end"
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
case .nextHole: return "nextHole"
|
||||
case .nextData: return "nextData"
|
||||
#endif
|
||||
@@ -428,14 +569,14 @@ extension FileDescriptor.SeekOrigin
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor.OpenOptions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
/// A textual representation of the open options.
|
||||
@inline(never)
|
||||
public var description: String {
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
(.append, ".append"),
|
||||
@@ -456,6 +597,19 @@ extension FileDescriptor.OpenOptions
|
||||
(.truncate, ".truncate"),
|
||||
(.exclusiveCreate, ".exclusiveCreate"),
|
||||
]
|
||||
#elseif os(FreeBSD)
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
(.append, ".append"),
|
||||
(.create, ".create"),
|
||||
(.truncate, ".truncate"),
|
||||
(.exclusiveCreate, ".exclusiveCreate"),
|
||||
(.sharedLock, ".sharedLock"),
|
||||
(.exclusiveLock, ".exclusiveLock"),
|
||||
(.sync, ".sync"),
|
||||
(.noFollow, ".noFollow"),
|
||||
(.closeOnExec, ".closeOnExec")
|
||||
]
|
||||
#else
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
@@ -475,13 +629,7 @@ extension FileDescriptor.OpenOptions
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
// The decision on whether to make FileDescriptor Sendable or not
|
||||
// is currently being discussed in https://github.com/apple/swift-system/pull/112
|
||||
//@available(*, unavailable, message: "File descriptors are not completely thread-safe.")
|
||||
//extension FileDescriptor: Sendable {}
|
||||
|
||||
extension FileDescriptor.AccessMode: Sendable {}
|
||||
extension FileDescriptor.OpenOptions: Sendable {}
|
||||
extension FileDescriptor.SeekOrigin: Sendable {}
|
||||
#endif
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// Runs a closure and then closes the file descriptor, even if an error occurs.
|
||||
///
|
||||
+195
-35
@@ -1,13 +1,13 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
@@ -16,6 +16,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -55,6 +57,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -88,8 +92,10 @@ extension FileDescriptor {
|
||||
if let permissions = permissions {
|
||||
return system_open(path, oFlag, permissions.rawValue)
|
||||
}
|
||||
precondition(!options.contains(.create),
|
||||
"Create must be given permissions")
|
||||
if options.contains(.create) {
|
||||
fatalError(
|
||||
"FileDescriptor.open: 'permissions' must not be nil when 'options' contains '.create'")
|
||||
}
|
||||
return system_open(path, oFlag)
|
||||
}
|
||||
return descOrError.map { FileDescriptor(rawValue: $0) }
|
||||
@@ -102,6 +108,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -135,8 +143,6 @@ extension FileDescriptor {
|
||||
if let permissions = permissions {
|
||||
return system_open(path, oFlag, permissions.rawValue)
|
||||
}
|
||||
precondition(!options.contains(.create),
|
||||
"Create must be given permissions")
|
||||
return system_open(path, oFlag)
|
||||
}
|
||||
return descOrError.map { FileDescriptor(rawValue: $0) }
|
||||
@@ -158,7 +164,7 @@ extension FileDescriptor {
|
||||
nothingOrErrno(retryOnInterrupt: false) { system_close(self.rawValue) }
|
||||
}
|
||||
|
||||
/// Reposition the offset for the given file descriptor.
|
||||
/// Repositions the offset for the given file descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The new offset for the file descriptor.
|
||||
@@ -224,7 +230,7 @@ extension FileDescriptor {
|
||||
internal func _read(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<Int, Errno> {
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_read(self.rawValue, buffer.baseAddress, buffer.count)
|
||||
}
|
||||
@@ -369,15 +375,16 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
#if !os(WASI)
|
||||
@available(System 0.0.2, *)
|
||||
extension FileDescriptor {
|
||||
/// Duplicate this file descriptor and return the newly created copy.
|
||||
/// Duplicates this file descriptor and returns the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
/// - target: The desired target file descriptor, or `nil`, in which case
|
||||
/// the copy is assigned to the file descriptor with the lowest raw value
|
||||
/// that is not currently in use by the process.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// - retryOnInterrupt: Whether to retry the duplicate operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
@@ -396,10 +403,9 @@ extension FileDescriptor {
|
||||
///
|
||||
/// However, each file descriptor maintains its own close-on-exec flag.
|
||||
///
|
||||
///
|
||||
/// The corresponding C functions are `dup` and `dup2`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
public func duplicate(
|
||||
as target: FileDescriptor? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
@@ -407,17 +413,77 @@ extension FileDescriptor {
|
||||
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
/// Duplicate this file descriptor and return the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - target: The desired target file descriptor.
|
||||
/// - options: The behavior for creating the target file descriptor.
|
||||
/// - retryOnInterrupt: Whether to retry the operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
///
|
||||
/// If the `target` descriptor is the same as `self`, then EINVAL is thrown.
|
||||
/// If the `target` descriptor is already in use, then it is first
|
||||
/// deallocated as if a close(2) call had been done first.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options, because `dup3` with
|
||||
/// no set options is not required to behave identically to `dup2`.
|
||||
///
|
||||
/// File descriptors are merely references to some underlying system resource.
|
||||
/// The system does not distinguish between the original and the new file
|
||||
/// descriptor in any way. For example, read, write and seek operations on
|
||||
/// one of them also affect the logical file position in the other, and
|
||||
/// append mode, non-blocking I/O and asynchronous I/O options are shared
|
||||
/// between the references. If a separate pointer into the file is desired,
|
||||
/// a different object reference to the file must be obtained by issuing an
|
||||
/// additional call to `open`.
|
||||
///
|
||||
/// However, each file descriptor maintains its own close-on-exec and
|
||||
/// close-on-fork flags.
|
||||
///
|
||||
/// The corresponding C function is `dup3`.
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func duplicate(
|
||||
as target: FileDescriptor,
|
||||
options: DuplicateOptions,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> FileDescriptor {
|
||||
let result = _duplicate(
|
||||
as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor?,
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<FileDescriptor, Errno> {
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
if let target = target {
|
||||
return system_dup2(self.rawValue, target.rawValue)
|
||||
if let target {
|
||||
system_dup2(self.rawValue, target.rawValue)
|
||||
} else {
|
||||
system_dup(self.rawValue)
|
||||
}
|
||||
return system_dup(self.rawValue)
|
||||
}.map(FileDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor,
|
||||
options: Int32,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_dup3(self.rawValue, target.rawValue, options)
|
||||
}.map(FileDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
@@ -432,25 +498,57 @@ extension FileDescriptor {
|
||||
public func dup2() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "duplicate")
|
||||
public func dup3() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
|
||||
#if !os(WASI)
|
||||
@available(System 1.1.0, *)
|
||||
extension FileDescriptor {
|
||||
/// Create a pipe, a unidirectional data channel which can be used for interprocess communication.
|
||||
/// Creates a unidirectional data channel, which can be used for
|
||||
/// interprocess communication.
|
||||
///
|
||||
/// - Returns: The pair of file descriptors.
|
||||
///
|
||||
/// The corresponding C function is `pipe`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
@available(System 1.1.0, *)
|
||||
public static func pipe(
|
||||
) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
try _pipe().get()
|
||||
}
|
||||
|
||||
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
/// Creates a unidirectional data channel, which can be used for
|
||||
/// interprocess communication.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options. On Windows, the
|
||||
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
|
||||
/// but this overload disables it when called with an empty option set.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - options: The behavior for creating the pipe.
|
||||
///
|
||||
/// - Returns: The pair of file descriptors.
|
||||
///
|
||||
/// The corresponding C function is `pipe2`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
public static func pipe(
|
||||
options: PipeOptions
|
||||
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
try _pipe(options: options.rawValue).get()
|
||||
}
|
||||
|
||||
@available(System 1.1.0, *)
|
||||
@usableFromInline
|
||||
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
|
||||
internal static func _pipe(
|
||||
) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
|
||||
var fds: (Int32, Int32) = (-1, -1)
|
||||
return withUnsafeMutablePointer(to: &fds) { pointer in
|
||||
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
|
||||
@@ -460,13 +558,33 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@usableFromInline
|
||||
internal static func _pipe(
|
||||
options: Int32,
|
||||
) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
|
||||
var fds: (Int32, Int32) = (-1, -1)
|
||||
return withUnsafeMutablePointer(to: &fds) { pointer in
|
||||
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
system_pipe2(fds, options)
|
||||
}.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "pipe")
|
||||
public static func pipe2() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
|
||||
@available(System 1.2.0, *)
|
||||
extension FileDescriptor {
|
||||
/// Truncate or extend the file referenced by this file descriptor.
|
||||
/// Truncates or extends the file referenced by this file descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newSize: The length in bytes to resize the file to.
|
||||
@@ -486,7 +604,7 @@ extension FileDescriptor {
|
||||
/// associated with the file.
|
||||
///
|
||||
/// The corresponding C function is `ftruncate`.
|
||||
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@available(System 1.2.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func resize(
|
||||
to newSize: Int64,
|
||||
@@ -498,7 +616,7 @@ extension FileDescriptor {
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@available(System 1.2.0, *)
|
||||
@usableFromInline
|
||||
internal func _resize(
|
||||
to newSize: Int64,
|
||||
@@ -509,4 +627,46 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(WASI) // WASI has no umask
|
||||
extension FilePermissions {
|
||||
/// The file creation permission mask (aka "umask").
|
||||
///
|
||||
/// Permissions set in this mask will be cleared by functions that create
|
||||
/// files or directories. Note that this mask is process-wide, and that
|
||||
/// *getting* it is not thread safe.
|
||||
internal static var creationMask: FilePermissions {
|
||||
get {
|
||||
let oldMask = _umask(0o22)
|
||||
_ = _umask(oldMask)
|
||||
return FilePermissions(rawValue: oldMask)
|
||||
}
|
||||
set {
|
||||
_ = _umask(newValue.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Change the file creation permission mask, run some code, then
|
||||
/// restore it to its original value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - permissions: The new permission mask.
|
||||
///
|
||||
/// This is more efficient than reading `creationMask` and restoring it
|
||||
/// afterwards, because of the way reading the creation mask works.
|
||||
internal static func withCreationMask<R>(
|
||||
_ permissions: FilePermissions,
|
||||
body: () throws -> R
|
||||
) rethrows -> R {
|
||||
let oldMask = _umask(permissions.rawValue)
|
||||
defer {
|
||||
_ = _umask(oldMask)
|
||||
}
|
||||
return try body()
|
||||
}
|
||||
|
||||
internal static func _umask(_ mode: CModeT) -> CModeT {
|
||||
return system_umask(mode)
|
||||
}
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
@@ -37,8 +37,8 @@
|
||||
/// However, the rules for path equivalence
|
||||
/// are file-system–specific and have additional considerations
|
||||
/// like case insensitivity, Unicode normalization, and symbolic links.
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct FilePath {
|
||||
@available(System 0.0.1, *)
|
||||
public struct FilePath: Sendable {
|
||||
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
|
||||
// components, etc.
|
||||
internal var _storage: SystemString
|
||||
@@ -59,15 +59,32 @@ public struct FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
/// The length of the file path, excluding the null terminator.
|
||||
public var length: Int { _storage.length }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FilePath: Hashable, Codable {}
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: Hashable {}
|
||||
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
extension FilePath: Sendable {}
|
||||
#endif
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: Codable {
|
||||
// Encoder is synthesized; it probably should have been explicit and used
|
||||
// a single-value container, but making that change now is somewhat risky.
|
||||
|
||||
// Decoder is written explicitly to ensure that we validate invariants on
|
||||
// untrusted input.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self._storage = try container.decode(SystemString.self, forKey: ._storage)
|
||||
guard _invariantsSatisfied() else {
|
||||
throw DecodingError.dataCorruptedError(
|
||||
forKey: ._storage,
|
||||
in: container,
|
||||
debugDescription:
|
||||
"Encoding does not satisfy the invariants of FilePath"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - API
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// A bidirectional, range replaceable collection of the non-root components
|
||||
/// that make up a file path.
|
||||
@@ -28,7 +28,8 @@ extension FilePath {
|
||||
///
|
||||
/// path.components.removeAll { $0.kind == .currentDirectory }
|
||||
/// // path is "/home/username/bin/scripts/tree"
|
||||
public struct ComponentView {
|
||||
@available(System 0.0.2, *)
|
||||
public struct ComponentView: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _start: SystemString.Index
|
||||
|
||||
@@ -39,30 +40,6 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE // Workaround for a __consuming getter bug in Swift 5.3.3
|
||||
/// View the non-root components that make up this path.
|
||||
public var components: ComponentView {
|
||||
get { ComponentView(self) }
|
||||
_modify {
|
||||
// RRC's empty init means that we can't guarantee that the yielded
|
||||
// view will restore our root. So copy it out first.
|
||||
//
|
||||
// TODO(perf): Small-form root (especially on Unix). Have Root
|
||||
// always copy out (not worth ref counting). Make sure that we're
|
||||
// not needlessly sliding values around or triggering a COW
|
||||
let rootStr = self.root?._systemString ?? SystemString()
|
||||
var comp = ComponentView(self)
|
||||
self = FilePath()
|
||||
defer {
|
||||
self = comp._path
|
||||
if root?._slice.elementsEqual(rootStr) != true {
|
||||
self.root = Root(rootStr)
|
||||
}
|
||||
}
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#else
|
||||
/// View the non-root components that make up this path.
|
||||
public var components: ComponentView {
|
||||
__consuming get { ComponentView(self) }
|
||||
@@ -85,13 +62,14 @@ extension FilePath {
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView: BidirectionalCollection {
|
||||
public typealias Element = FilePath.Component
|
||||
public struct Index: Comparable, Hashable {
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
public struct Index: Sendable, Comparable, Hashable {
|
||||
internal typealias Storage = SystemString.Index
|
||||
|
||||
internal var _storage: Storage
|
||||
@@ -122,7 +100,7 @@ extension FilePath.ComponentView: BidirectionalCollection {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView: RangeReplaceableCollection {
|
||||
public init() {
|
||||
self.init(FilePath())
|
||||
@@ -165,14 +143,16 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
|
||||
str.append(platformSeparator)
|
||||
}
|
||||
str.appendComponents(components: newElements)
|
||||
if !atEnd {
|
||||
// If we're replacing through the end, we must not leave a trailing
|
||||
// separator.
|
||||
if subrange.upperBound != endIndex {
|
||||
str.append(platformSeparator)
|
||||
}
|
||||
_path._storage.replaceSubrange(range, with: str)
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Create a file path from a root and a collection of components.
|
||||
public init<C: Collection>(
|
||||
@@ -201,7 +181,7 @@ extension FilePath {
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
_start ..< _path._storage.endIndex
|
||||
@@ -214,7 +194,7 @@ extension FilePath.ComponentView: _PathSlice {
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
@@ -239,8 +219,3 @@ extension FilePath.ComponentView {
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
extension FilePath.ComponentView: Sendable {}
|
||||
extension FilePath.ComponentView.Index: Sendable {}
|
||||
#endif
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - API
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Represents a root of a file path.
|
||||
///
|
||||
@@ -28,7 +28,8 @@ extension FilePath {
|
||||
/// * `\\server\share\`
|
||||
/// * `\\?\UNC\server\share\`
|
||||
/// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\`
|
||||
public struct Root {
|
||||
@available(System 0.0.2, *)
|
||||
public struct Root: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _rootEnd: SystemString.Index
|
||||
|
||||
@@ -54,7 +55,8 @@ extension FilePath {
|
||||
/// file.kind == .regular // true
|
||||
/// file.extension // "txt"
|
||||
/// path.append(file) // path is "/tmp/foo.txt"
|
||||
public struct Component {
|
||||
@available(System 0.0.2, *)
|
||||
public struct Component: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _range: Range<SystemString.Index>
|
||||
|
||||
@@ -72,13 +74,14 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
|
||||
/// Whether a component is a regular file or directory name, or a special
|
||||
/// directory `.` or `..`
|
||||
@frozen
|
||||
public enum Kind {
|
||||
@available(System 0.0.2, *)
|
||||
public enum Kind: Sendable {
|
||||
/// The special directory `.`, representing the current directory.
|
||||
case currentDirectory
|
||||
|
||||
@@ -97,7 +100,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
// TODO: Windows analysis APIs
|
||||
}
|
||||
@@ -143,7 +146,7 @@ extension _StrSlice {
|
||||
internal func _withSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try _storage.withSystemChars {
|
||||
try _storage.withNullTerminatedSystemChars {
|
||||
try f(UnsafeBufferPointer(rebasing: $0[_range]))
|
||||
}
|
||||
}
|
||||
@@ -183,17 +186,17 @@ extension _PathSlice {
|
||||
internal var _storage: SystemString { _path._storage }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component: _PathSlice {
|
||||
}
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
(..<_rootEnd).relative(to: _path._storage)
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: _PlatformStringable {
|
||||
func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
|
||||
try _storage.withPlatformString(body)
|
||||
@@ -205,7 +208,7 @@ extension FilePath: _PlatformStringable {
|
||||
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
// The index of the `.` denoting an extension
|
||||
internal func _extensionIndex() -> SystemString.Index? {
|
||||
@@ -234,7 +237,7 @@ internal func _makeExtension(_ ext: String) -> SystemString {
|
||||
return result
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
internal init?(_ str: SystemString) {
|
||||
// FIXME: explicit null root? Or something else?
|
||||
@@ -247,7 +250,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
internal init?(_ str: SystemString) {
|
||||
// FIXME: explicit null root? Or something else?
|
||||
@@ -262,7 +265,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
// TODO: ensure this all gets easily optimized away in release...
|
||||
internal func _invariantCheck() {
|
||||
@@ -275,7 +278,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
@@ -285,9 +288,3 @@ extension FilePath.Root {
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
extension FilePath.Root: Sendable {}
|
||||
extension FilePath.Component: Sendable {}
|
||||
extension FilePath.Component.Kind: Sendable {}
|
||||
#endif
|
||||
@@ -89,6 +89,11 @@ extension SystemString {
|
||||
// `_prenormalizeWindowsRoots` and resume.
|
||||
readIdx = _prenormalizeWindowsRoots()
|
||||
writeIdx = readIdx
|
||||
|
||||
// Skip redundant separators
|
||||
while readIdx < endIndex && isSeparator(self[readIdx]) {
|
||||
self.formIndex(after: &readIdx)
|
||||
}
|
||||
} else {
|
||||
assert(genericSeparator == platformSeparator)
|
||||
}
|
||||
@@ -111,7 +116,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal mutating func _removeTrailingSeparator() {
|
||||
_storage._removeTrailingSeparator()
|
||||
@@ -192,7 +197,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal var _relativeStart: SystemString.Index {
|
||||
_storage._relativePathStart
|
||||
@@ -204,7 +209,7 @@ extension FilePath {
|
||||
|
||||
// Parse separators
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal typealias _Index = SystemString.Index
|
||||
|
||||
@@ -268,7 +273,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView {
|
||||
// TODO: Store this...
|
||||
internal var _relativeStart: SystemString.Index {
|
||||
@@ -293,7 +298,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
// Asserting self is a root, returns whether this is an
|
||||
// absolute root.
|
||||
@@ -318,7 +323,7 @@ extension FilePath.Root {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal var _portableDescription: String {
|
||||
guard _windowsPaths else { return description }
|
||||
@@ -330,14 +335,17 @@ extension FilePath {
|
||||
// Whether we are providing Windows paths
|
||||
@inline(__always)
|
||||
internal var _windowsPaths: Bool {
|
||||
if let forceWindowsPaths = forceWindowsPaths {
|
||||
return forceWindowsPaths
|
||||
}
|
||||
#if os(Windows)
|
||||
return true
|
||||
#else
|
||||
return forceWindowsPaths
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
// Whether we should add a separator when doing an append
|
||||
internal var _needsSeparatorForAppend: Bool {
|
||||
@@ -365,15 +373,20 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK: - Invariants
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
internal func _invariantsSatisfied() -> Bool {
|
||||
var normal = self
|
||||
normal._normalizeSeparators()
|
||||
precondition(self == normal)
|
||||
precondition(!self._storage._hasTrailingSeparator())
|
||||
precondition(_hasRoot == (self.root != nil))
|
||||
guard self == normal else { return false }
|
||||
guard !self._storage._hasTrailingSeparator() else { return false }
|
||||
guard _hasRoot == (self.root != nil) else { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
precondition(_invariantsSatisfied())
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - Platform string
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Creates a file path by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
@@ -109,7 +109,7 @@ extension FilePath {
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
/// Creates a file path component by copying bytes from a null-terminated
|
||||
/// platform string.
|
||||
@@ -198,7 +198,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
/// Creates a file path root by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
@@ -287,7 +287,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - String literals
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: ExpressibleByStringLiteral {
|
||||
/// Creates a file path from a string literal.
|
||||
///
|
||||
@@ -306,7 +306,7 @@ extension FilePath: ExpressibleByStringLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
/// Create a file path component from a string literal.
|
||||
///
|
||||
@@ -331,7 +331,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
/// Create a file path root from a string literal.
|
||||
///
|
||||
@@ -356,7 +356,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
|
||||
// MARK: - Printing and dumping
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the file path.
|
||||
///
|
||||
@@ -372,7 +372,7 @@ extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
|
||||
/// A textual representation of the path component.
|
||||
@@ -389,7 +389,7 @@ extension FilePath.Component: CustomStringConvertible, CustomDebugStringConverti
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
|
||||
/// A textual representation of the path root.
|
||||
@@ -409,7 +409,7 @@ extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
// MARK: - Convenience helpers
|
||||
|
||||
// Convenience helpers
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Creates a string by interpreting the path’s content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
@@ -420,7 +420,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
/// Creates a string by interpreting the component’s content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
@@ -431,7 +431,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
/// On Unix, this returns `"/"`.
|
||||
///
|
||||
@@ -445,7 +445,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - Decoding and validating
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the file path's content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
@@ -461,7 +461,10 @@ extension String {
|
||||
public init(decoding path: FilePath) {
|
||||
self.init(_decoding: path)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string from a file path, validating its contents as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
///
|
||||
@@ -470,12 +473,13 @@ extension String {
|
||||
///
|
||||
/// If the contents of the file path isn't a well-formed Unicode string,
|
||||
/// this initializer returns `nil`.
|
||||
@available(System 0.0.2, *)
|
||||
public init?(validating path: FilePath) {
|
||||
self.init(_validating: path)
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the path component's content as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
@@ -505,7 +509,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// On Unix, creates the string `"/"`
|
||||
///
|
||||
@@ -558,7 +562,7 @@ extension String {
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension String {
|
||||
@available(*, deprecated, renamed: "init(decoding:)")
|
||||
public init(_ path: FilePath) { self.init(decoding: path) }
|
||||
@@ -568,7 +572,7 @@ extension String {
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
/// For backwards compatibility only. This initializer is equivalent to
|
||||
/// the preferred `FilePath(platformString:)`.
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - Query API
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns true if this path uniquely identifies the location of
|
||||
/// a file without reference to an additional starting location.
|
||||
@@ -99,7 +99,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK: - Decompose a path
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns the root of a path if there is one, otherwise `nil`.
|
||||
///
|
||||
@@ -182,7 +182,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns the final component of the path.
|
||||
/// Returns `nil` if the path is empty or only contains a root.
|
||||
@@ -252,7 +252,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
/// The extension of this file or directory component.
|
||||
///
|
||||
@@ -283,7 +283,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
|
||||
/// The extension of the file or directory last component.
|
||||
@@ -349,7 +349,7 @@ extension FilePath {
|
||||
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Whether the path is in lexical-normal form, that is `.` and `..`
|
||||
/// components have been collapsed lexically (i.e. without following
|
||||
@@ -430,7 +430,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// Modification and concatenation API
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
// TODO(Windows docs): example with roots
|
||||
/// If `prefix` is a prefix of `self`, removes it and returns `true`.
|
||||
@@ -583,7 +583,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK - Renamed
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
@available(*, unavailable, renamed: "removingLastComponent()")
|
||||
public var dirname: FilePath { removingLastComponent() }
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// MARK: - API
|
||||
|
||||
/// Create a temporary path for the duration of the closure.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - basename: The base name for the temporary path.
|
||||
/// - body: The closure to execute.
|
||||
///
|
||||
/// Creates a temporary directory with a name based on the given `basename`,
|
||||
/// executes `body`, passing in the path of the created directory, then
|
||||
/// deletes the directory and all of its contents before returning.
|
||||
internal func withTemporaryFilePath<R>(
|
||||
basename: FilePath.Component,
|
||||
_ body: (FilePath) throws -> R
|
||||
) throws -> R {
|
||||
let temporaryDir = try createUniqueTemporaryDirectory(basename: basename)
|
||||
defer {
|
||||
try? _recursiveRemove(at: temporaryDir)
|
||||
}
|
||||
|
||||
return try body(temporaryDir)
|
||||
}
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
fileprivate let base64 = Array<UInt8>(
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8
|
||||
)
|
||||
|
||||
/// Create a directory that is only accessible to the current user.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the directory to create.
|
||||
/// - Returns: `true` if a new directory was created.
|
||||
///
|
||||
/// This function will throw if there is an error, except if the error
|
||||
/// is that the directory exists, in which case it returns `false`.
|
||||
fileprivate func makeLockedDownDirectory(at path: FilePath) throws -> Bool {
|
||||
return try path.withPlatformString {
|
||||
if system_mkdir($0, 0o700) == 0 {
|
||||
return true
|
||||
}
|
||||
let err = system_errno
|
||||
if err == Errno.fileExists.rawValue {
|
||||
return false
|
||||
} else {
|
||||
throw Errno(rawValue: err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a random string of base64 filename safe characters.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - length: The number of characters in the returned string.
|
||||
/// - Returns: A random string of length `length`.
|
||||
fileprivate func createRandomString(length: Int) -> String {
|
||||
return String(
|
||||
decoding: (0..<length).map{
|
||||
_ in base64[Int.random(in: 0..<64)]
|
||||
},
|
||||
as: UTF8.self
|
||||
)
|
||||
}
|
||||
|
||||
/// Given a base name, create a uniquely named temporary directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - basename: The base name for the new directory.
|
||||
/// - Returns: The path to the new directory.
|
||||
///
|
||||
/// Creates a directory in the system temporary directory whose name
|
||||
/// starts with `basename`, followed by a `.` and then a random
|
||||
/// string of characters.
|
||||
fileprivate func createUniqueTemporaryDirectory(
|
||||
basename: FilePath.Component
|
||||
) throws -> FilePath {
|
||||
var tempDir = try _getTemporaryDirectory()
|
||||
tempDir.append(basename)
|
||||
|
||||
while true {
|
||||
tempDir.extension = createRandomString(length: 16)
|
||||
|
||||
if try makeLockedDownDirectory(at: tempDir) {
|
||||
return tempDir
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
internal import CSystem // For the members of system_dirent
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// Get the path to the system temporary directory.
|
||||
internal func _getTemporaryDirectory() throws -> FilePath {
|
||||
guard let tmp = system_getenv("TMPDIR") else {
|
||||
return "/tmp"
|
||||
}
|
||||
|
||||
return FilePath(SystemString(platformString: tmp))
|
||||
}
|
||||
|
||||
/// Delete the entire contents of a directory, including its subdirectories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The directory to be deleted.
|
||||
///
|
||||
/// Removes a directory completely, including all of its contents.
|
||||
internal func _recursiveRemove(
|
||||
at path: FilePath
|
||||
) throws {
|
||||
let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory)
|
||||
defer {
|
||||
try? dirfd.close()
|
||||
}
|
||||
|
||||
let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0)
|
||||
try withUnsafeBytes(of: dot) {
|
||||
try recursiveRemove(
|
||||
in: dirfd.rawValue,
|
||||
name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress!
|
||||
)
|
||||
}
|
||||
|
||||
try path.withPlatformString {
|
||||
if system_rmdir($0) != 0 {
|
||||
throw Errno.current
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a directory by reference to its parent and name.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dirfd: An open file descriptor for the parent directory.
|
||||
/// - name: The name of the directory to open.
|
||||
/// - Returns: A pointer to a `DIR` structure.
|
||||
///
|
||||
/// This is like `opendir()`, but instead of taking a path, it uses a
|
||||
/// file descriptor pointing at the parent, thus avoiding path length
|
||||
/// limits.
|
||||
fileprivate func impl_opendirat(
|
||||
_ dirfd: CInt,
|
||||
_ name: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> system_DIRPtr? {
|
||||
let fd = system_openat(dirfd, name,
|
||||
FileDescriptor.AccessMode.readOnly.rawValue
|
||||
| FileDescriptor.OpenOptions.directory.rawValue)
|
||||
if fd < 0 {
|
||||
return nil
|
||||
}
|
||||
return system_fdopendir(fd)
|
||||
}
|
||||
|
||||
/// Invoke a closure for each file within a particular directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dirfd: The parent of the directory to be enumerated.
|
||||
/// - subdir: The subdirectory to be enumerated.
|
||||
/// - body: The closure that will be invoked.
|
||||
///
|
||||
/// We skip the `.` and `..` pseudo-entries.
|
||||
fileprivate func forEachFile(
|
||||
in dirfd: CInt,
|
||||
subdir: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ body: (system_dirent) throws -> ()
|
||||
) throws {
|
||||
guard let dir = impl_opendirat(dirfd, subdir) else {
|
||||
throw Errno.current
|
||||
}
|
||||
defer {
|
||||
_ = system_closedir(dir)
|
||||
}
|
||||
|
||||
while let dirent = system_readdir(dir) {
|
||||
// Skip . and ..
|
||||
if dirent.pointee.d_name.0 == 46
|
||||
&& (dirent.pointee.d_name.1 == 0
|
||||
|| (dirent.pointee.d_name.1 == 46
|
||||
&& dirent.pointee.d_name.2 == 0)) {
|
||||
continue
|
||||
}
|
||||
|
||||
try body(dirent.pointee)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the entire contents of a directory, including its subdirectories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dirfd: The parent of the directory to be removed.
|
||||
/// - name: The name of the directory to be removed.
|
||||
///
|
||||
/// Removes a directory completely, including all of its contents.
|
||||
fileprivate func recursiveRemove(
|
||||
in dirfd: CInt,
|
||||
name: UnsafePointer<CInterop.PlatformChar>
|
||||
) throws {
|
||||
// First, deal with subdirectories
|
||||
try forEachFile(in: dirfd, subdir: name) { dirent in
|
||||
if dirent.d_type == SYSTEM_DT_DIR {
|
||||
try withUnsafeBytes(of: dirent.d_name) {
|
||||
try recursiveRemove(
|
||||
in: dirfd,
|
||||
name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
.baseAddress!
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now delete the contents of this directory
|
||||
try forEachFile(in: dirfd, subdir: name) { dirent in
|
||||
let flag: CInt
|
||||
|
||||
if dirent.d_type == SYSTEM_DT_DIR {
|
||||
flag = SYSTEM_AT_REMOVE_DIR
|
||||
} else {
|
||||
flag = 0
|
||||
}
|
||||
|
||||
let result = withUnsafeBytes(of: dirent.d_name) {
|
||||
system_unlinkat(dirfd,
|
||||
$0.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
.baseAddress!,
|
||||
flag)
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
throw Errno.current
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !os(Windows)
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
import WinSDK
|
||||
|
||||
/// Get the path to the system temporary directory.
|
||||
internal func _getTemporaryDirectory() throws -> FilePath {
|
||||
return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self,
|
||||
capacity: Int(MAX_PATH) + 1) {
|
||||
buffer in
|
||||
|
||||
guard GetTempPathW(DWORD(buffer.count), buffer.baseAddress) != 0 else {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
|
||||
return FilePath(SystemString(platformString: buffer.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
/// Invoke a closure for each file within a particular directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path at which we should enumerate items.
|
||||
/// - body: The closure that will be invoked.
|
||||
///
|
||||
/// We skip the `.` and `..` pseudo-entries.
|
||||
fileprivate func forEachFile(
|
||||
at path: FilePath,
|
||||
_ body: (WIN32_FIND_DATAW) throws -> ()
|
||||
) rethrows {
|
||||
let searchPath = path.appending("\\*")
|
||||
|
||||
try searchPath.withPlatformString { szPath in
|
||||
var findData = WIN32_FIND_DATAW()
|
||||
let hFind = try szPath.withCanonicalPathRepresentation({ szPath in FindFirstFileW(szPath, &findData) })
|
||||
if hFind == INVALID_HANDLE_VALUE {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
defer {
|
||||
FindClose(hFind)
|
||||
}
|
||||
|
||||
repeat {
|
||||
// Skip . and ..
|
||||
if findData.cFileName.0 == 46
|
||||
&& (findData.cFileName.1 == 0
|
||||
|| (findData.cFileName.1 == 46
|
||||
&& findData.cFileName.2 == 0)) {
|
||||
continue
|
||||
}
|
||||
|
||||
try body(findData)
|
||||
} while FindNextFileW(hFind, &findData)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the entire contents of a directory, including its subdirectories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The directory to be deleted.
|
||||
///
|
||||
/// Removes a directory completely, including all of its contents.
|
||||
internal func _recursiveRemove(
|
||||
at path: FilePath
|
||||
) throws {
|
||||
// First, deal with subdirectories
|
||||
try forEachFile(at: path) { findData in
|
||||
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 {
|
||||
let name = withUnsafeBytes(of: findData.cFileName) {
|
||||
return SystemString(platformString: $0.assumingMemoryBound(
|
||||
to: CInterop.PlatformChar.self).baseAddress!)
|
||||
}
|
||||
let component = FilePath.Component(name)!
|
||||
let subpath = path.appending(component)
|
||||
|
||||
try _recursiveRemove(at: subpath)
|
||||
}
|
||||
}
|
||||
|
||||
// Now delete everything else
|
||||
try forEachFile(at: path) { findData in
|
||||
let name = withUnsafeBytes(of: findData.cFileName) {
|
||||
return SystemString(platformString: $0.assumingMemoryBound(
|
||||
to: CInterop.PlatformChar.self).baseAddress!)
|
||||
}
|
||||
let component = FilePath.Component(name)!
|
||||
let subpath = path.appending(component)
|
||||
|
||||
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 {
|
||||
try subpath.withPlatformString { subpath in
|
||||
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, delete the parent
|
||||
try path.withPlatformString {
|
||||
if try !$0.withCanonicalPathRepresentation({ RemoveDirectoryW($0) }) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // os(Windows)
|
||||
@@ -461,3 +461,78 @@ extension SystemString {
|
||||
return lexer.current
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Windows)
|
||||
import WinSDK
|
||||
|
||||
// FIXME: Rather than canonicalizing the path at every call site to a Win32 API,
|
||||
// we should consider always storing absolute paths with the \\?\ prefix applied,
|
||||
// for better performance.
|
||||
extension UnsafePointer where Pointee == CInterop.PlatformChar {
|
||||
/// Invokes `body` with a resolved and potentially `\\?\`-prefixed version of the pointee,
|
||||
/// to ensure long paths greater than MAX_PATH (260) characters are handled correctly.
|
||||
///
|
||||
/// - seealso: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
|
||||
internal func withCanonicalPathRepresentation<Result>(_ body: (Self) throws -> Result) throws -> Result {
|
||||
// 1. Normalize the path first.
|
||||
// Contrary to the documentation, this works on long paths independently
|
||||
// of the registry or process setting to enable long paths (but it will also
|
||||
// not add the \\?\ prefix required by other functions under these conditions).
|
||||
let dwLength: DWORD = GetFullPathNameW(self, 0, nil, nil)
|
||||
return try withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) { pwszFullPath in
|
||||
guard (1..<dwLength).contains(GetFullPathNameW(self, DWORD(pwszFullPath.count), pwszFullPath.baseAddress, nil)) else {
|
||||
throw Errno(rawValue: _mapWindowsErrorToErrno(GetLastError()))
|
||||
}
|
||||
|
||||
// 1.5 Leave \\.\ prefixed paths alone since device paths are already an exact representation and PathCchCanonicalizeEx will mangle these.
|
||||
if let base = pwszFullPath.baseAddress,
|
||||
base[0] == UInt8(ascii: "\\"),
|
||||
base[1] == UInt8(ascii: "\\"),
|
||||
base[2] == UInt8(ascii: "."),
|
||||
base[3] == UInt8(ascii: "\\") {
|
||||
return try body(base)
|
||||
}
|
||||
|
||||
// 2. Canonicalize the path.
|
||||
// This will add the \\?\ prefix if needed based on the path's length.
|
||||
var pwszCanonicalPath: LPWSTR?
|
||||
let flags: ULONG = numericCast(PATHCCH_ALLOW_LONG_PATHS.rawValue)
|
||||
let result = PathAllocCanonicalize(pwszFullPath.baseAddress, flags, &pwszCanonicalPath)
|
||||
if let pwszCanonicalPath {
|
||||
defer { LocalFree(pwszCanonicalPath) }
|
||||
if result == S_OK {
|
||||
// 3. Perform the operation on the normalized path.
|
||||
return try body(pwszCanonicalPath)
|
||||
}
|
||||
}
|
||||
throw Errno(rawValue: _mapWindowsErrorToErrno(WIN32_FROM_HRESULT(result)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func HRESULT_CODE(_ hr: HRESULT) -> DWORD {
|
||||
DWORD(hr) & 0xffff
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD {
|
||||
DWORD(hr >> 16) & 0x1fff
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func SUCCEEDED(_ hr: HRESULT) -> Bool {
|
||||
hr >= 0
|
||||
}
|
||||
|
||||
// This is a non-standard extension to the Windows SDK that allows us to convert
|
||||
// an HRESULT to a Win32 error code.
|
||||
@inline(__always)
|
||||
fileprivate func WIN32_FROM_HRESULT(_ hr: HRESULT) -> DWORD {
|
||||
if SUCCEEDED(hr) { return ERROR_SUCCESS }
|
||||
if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
|
||||
return HRESULT_CODE(hr)
|
||||
}
|
||||
return DWORD(hr)
|
||||
}
|
||||
#endif
|
||||
@@ -17,8 +17,8 @@
|
||||
/// let perms = FilePermissions(rawValue: 0o644)
|
||||
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
|
||||
@frozen
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C file permissions.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CModeT
|
||||
@@ -27,104 +27,103 @@ public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CModeT) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CModeT) { self.init(rawValue: raw) }
|
||||
|
||||
/// Indicates that other users have read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherRead: FilePermissions { FilePermissions(0o4) }
|
||||
public static var otherRead: FilePermissions { .init(rawValue: 0o4) }
|
||||
|
||||
/// Indicates that other users have write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherWrite: FilePermissions { FilePermissions(0o2) }
|
||||
public static var otherWrite: FilePermissions { .init(rawValue: 0o2) }
|
||||
|
||||
/// Indicates that other users have execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherExecute: FilePermissions { FilePermissions(0o1) }
|
||||
public static var otherExecute: FilePermissions { .init(rawValue: 0o1) }
|
||||
|
||||
/// Indicates that other users have read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadWrite: FilePermissions { FilePermissions(0o6) }
|
||||
public static var otherReadWrite: FilePermissions { .init(rawValue: 0o6) }
|
||||
|
||||
/// Indicates that other users have read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadExecute: FilePermissions { FilePermissions(0o5) }
|
||||
public static var otherReadExecute: FilePermissions { .init(rawValue: 0o5) }
|
||||
|
||||
/// Indicates that other users have write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) }
|
||||
public static var otherWriteExecute: FilePermissions { .init(rawValue: 0o3) }
|
||||
|
||||
/// Indicates that other users have read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) }
|
||||
public static var otherReadWriteExecute: FilePermissions { .init(rawValue: 0o7) }
|
||||
|
||||
/// Indicates that the group has read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupRead: FilePermissions { FilePermissions(0o40) }
|
||||
public static var groupRead: FilePermissions { .init(rawValue: 0o40) }
|
||||
|
||||
/// Indicates that the group has write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupWrite: FilePermissions { FilePermissions(0o20) }
|
||||
public static var groupWrite: FilePermissions { .init(rawValue: 0o20) }
|
||||
|
||||
/// Indicates that the group has execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupExecute: FilePermissions { FilePermissions(0o10) }
|
||||
public static var groupExecute: FilePermissions { .init(rawValue: 0o10) }
|
||||
|
||||
/// Indicates that the group has read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadWrite: FilePermissions { FilePermissions(0o60) }
|
||||
public static var groupReadWrite: FilePermissions { .init(rawValue: 0o60) }
|
||||
|
||||
/// Indicates that the group has read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadExecute: FilePermissions { FilePermissions(0o50) }
|
||||
public static var groupReadExecute: FilePermissions { .init(rawValue: 0o50) }
|
||||
|
||||
/// Indicates that the group has write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) }
|
||||
public static var groupWriteExecute: FilePermissions { .init(rawValue: 0o30) }
|
||||
|
||||
/// Indicates that the group has read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) }
|
||||
public static var groupReadWriteExecute: FilePermissions { .init(rawValue: 0o70) }
|
||||
|
||||
/// Indicates that the owner has read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerRead: FilePermissions { FilePermissions(0o400) }
|
||||
public static var ownerRead: FilePermissions { .init(rawValue: 0o400) }
|
||||
|
||||
/// Indicates that the owner has write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerWrite: FilePermissions { FilePermissions(0o200) }
|
||||
public static var ownerWrite: FilePermissions { .init(rawValue: 0o200) }
|
||||
|
||||
/// Indicates that the owner has execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerExecute: FilePermissions { FilePermissions(0o100) }
|
||||
public static var ownerExecute: FilePermissions { .init(rawValue: 0o100) }
|
||||
|
||||
/// Indicates that the owner has read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) }
|
||||
public static var ownerReadWrite: FilePermissions { .init(rawValue: 0o600) }
|
||||
|
||||
/// Indicates that the owner has read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) }
|
||||
public static var ownerReadExecute: FilePermissions { .init(rawValue: 0o500) }
|
||||
|
||||
/// Indicates that the owner has write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) }
|
||||
public static var ownerWriteExecute: FilePermissions { .init(rawValue: 0o300) }
|
||||
|
||||
/// Indicates that the owner has read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) }
|
||||
public static var ownerReadWriteExecute: FilePermissions { .init(rawValue: 0o700) }
|
||||
|
||||
/// Indicates that the file is executed as the owner.
|
||||
///
|
||||
/// For more information, see the `setuid(2)` man page.
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISUID` (the set-user-ID bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setUserID: FilePermissions { FilePermissions(0o4000) }
|
||||
public static var setUserID: FilePermissions { .init(rawValue: 0o4000) }
|
||||
|
||||
/// Indicates that the file is executed as the group.
|
||||
///
|
||||
/// For more information, see the `setgid(2)` man page.
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISGID` (the set-group-ID bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setGroupID: FilePermissions { FilePermissions(0o2000) }
|
||||
public static var setGroupID: FilePermissions { .init(rawValue: 0o2000) }
|
||||
|
||||
/// Indicates that executable's text segment
|
||||
/// should be kept in swap space even after it exits.
|
||||
@@ -132,10 +131,10 @@ public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISVTX` (the sticky bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var saveText: FilePermissions { FilePermissions(0o1000) }
|
||||
public static var saveText: FilePermissions { .init(rawValue: 0o1000) }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePermissions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -175,7 +174,3 @@ extension FilePermissions
|
||||
/// A textual representation of the file permissions, suitable for debugging.
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
extension FilePermissions: Sendable {}
|
||||
#endif
|
||||
@@ -0,0 +1,250 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// |------------------------|
|
||||
// | Swift API to C Mapping |
|
||||
// |------------------------------------------------------------------|
|
||||
// | FileFlags | Darwin | FreeBSD | OpenBSD |
|
||||
// |------------------|---------------|---------------|---------------|
|
||||
// | noDump | UF_NODUMP | UF_NODUMP | UF_NODUMP |
|
||||
// | userImmutable | UF_IMMUTABLE | UF_IMMUTABLE | UF_IMMUTABLE |
|
||||
// | userAppend | UF_APPEND | UF_APPEND | UF_APPEND |
|
||||
// | archived | SF_ARCHIVED | SF_ARCHIVED | SF_ARCHIVED |
|
||||
// | systemImmutable | SF_IMMUTABLE | SF_IMMUTABLE | SF_IMMUTABLE |
|
||||
// | systemAppend | SF_APPEND | SF_APPEND | SF_APPEND |
|
||||
// | opaque | UF_OPAQUE | UF_OPAQUE | N/A |
|
||||
// | hidden | UF_HIDDEN | UF_HIDDEN | N/A |
|
||||
// | systemNoUnlink | SF_NOUNLINK | SF_NOUNLINK | N/A |
|
||||
// | compressed | UF_COMPRESSED | N/A | N/A |
|
||||
// | tracked | UF_TRACKED | N/A | N/A |
|
||||
// | dataVault | UF_DATAVAULT | N/A | N/A |
|
||||
// | restricted | SF_RESTRICTED | N/A | N/A |
|
||||
// | firmlink | SF_FIRMLINK | N/A | N/A |
|
||||
// | dataless | SF_DATALESS | N/A | N/A |
|
||||
// | userNoUnlink | N/A | UF_NOUNLINK | N/A |
|
||||
// | offline | N/A | UF_OFFLINE | N/A |
|
||||
// | readOnly | N/A | UF_READONLY | N/A |
|
||||
// | reparse | N/A | UF_REPARSE | N/A |
|
||||
// | sparse | N/A | UF_SPARSE | N/A |
|
||||
// | system | N/A | UF_SYSTEM | N/A |
|
||||
// | snapshot | N/A | SF_SNAPSHOT | N/A |
|
||||
// |------------------|---------------|---------------|---------------|
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
|
||||
/// File-specific flags found in the `st_flags` property of a `stat` struct
|
||||
/// or used as input to `chflags()`.
|
||||
///
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.FileFlags
|
||||
|
||||
/// Creates a strongly-typed `FileFlags` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.FileFlags) { self.rawValue = rawValue }
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
/// Do not dump the file during backups.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NODUMP`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDump: FileFlags { FileFlags(rawValue: _UF_NODUMP) }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_IMMUTABLE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userImmutable: FileFlags { FileFlags(rawValue: _UF_IMMUTABLE) }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `UF_APPEND`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userAppend: FileFlags { FileFlags(rawValue: _UF_APPEND) }
|
||||
|
||||
/// File has been archived.
|
||||
///
|
||||
/// The corresponding C constant is `SF_ARCHIVED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var archived: FileFlags { FileFlags(rawValue: _SF_ARCHIVED) }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_IMMUTABLE`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var systemImmutable: FileFlags { FileFlags(rawValue: _SF_IMMUTABLE) }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `SF_APPEND`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var systemAppend: FileFlags { FileFlags(rawValue: _SF_APPEND) }
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Directory is opaque when viewed through a union mount.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OPAQUE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var opaque: FileFlags { FileFlags(rawValue: _UF_OPAQUE) }
|
||||
|
||||
/// File should not be displayed in a GUI.
|
||||
///
|
||||
/// The corresponding C constant is `UF_HIDDEN`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var hidden: FileFlags { FileFlags(rawValue: _UF_HIDDEN) }
|
||||
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_NOUNLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var systemNoUnlink: FileFlags { FileFlags(rawValue: _SF_NOUNLINK) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// File is compressed at the file system level.
|
||||
///
|
||||
/// The corresponding C constant is `UF_COMPRESSED`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var compressed: FileFlags { FileFlags(rawValue: _UF_COMPRESSED) }
|
||||
|
||||
/// File is tracked for the purpose of document IDs.
|
||||
///
|
||||
/// The corresponding C constant is `UF_TRACKED`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tracked: FileFlags { FileFlags(rawValue: _UF_TRACKED) }
|
||||
|
||||
/// File requires an entitlement for reading and writing.
|
||||
///
|
||||
/// The corresponding C constant is `UF_DATAVAULT`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataVault: FileFlags { FileFlags(rawValue: _UF_DATAVAULT) }
|
||||
|
||||
/// File requires an entitlement for writing.
|
||||
///
|
||||
/// The corresponding C constant is `SF_RESTRICTED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var restricted: FileFlags { FileFlags(rawValue: _SF_RESTRICTED) }
|
||||
|
||||
/// File is a firmlink.
|
||||
///
|
||||
/// Firmlinks are used by macOS to create transparent links between
|
||||
/// the read-only system volume and writable data volume. For example,
|
||||
/// the `/Applications` folder on the system volume is a firmlink to
|
||||
/// the `/Applications` folder on the data volume, allowing the user
|
||||
/// to see both system- and user-installed applications in a single folder.
|
||||
///
|
||||
/// The corresponding C constant is `SF_FIRMLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var firmlink: FileFlags { FileFlags(rawValue: _SF_FIRMLINK) }
|
||||
|
||||
/// File is a dataless placeholder (content is stored remotely).
|
||||
///
|
||||
/// The system will attempt to materialize the file when accessed according to
|
||||
/// the dataless file materialization policy of the accessing thread or process.
|
||||
/// See `getiopolicy_np(3)`.
|
||||
///
|
||||
/// The corresponding C constant is `SF_DATALESS`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataless: FileFlags { FileFlags(rawValue: _SF_DATALESS) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NOUNLINK`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userNoUnlink: FileFlags { FileFlags(rawValue: _UF_NOUNLINK) }
|
||||
|
||||
/// File has the Windows offline attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_OFFLINE` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OFFLINE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var offline: FileFlags { FileFlags(rawValue: _UF_OFFLINE) }
|
||||
|
||||
/// File is read-only.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_READONLY` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_READONLY`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var readOnly: FileFlags { FileFlags(rawValue: _UF_READONLY) }
|
||||
|
||||
/// File contains a Windows reparse point.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_REPARSE_POINT` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_REPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reparse: FileFlags { FileFlags(rawValue: _UF_REPARSE) }
|
||||
|
||||
/// File is sparse.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SPARSE_FILE` attribute,
|
||||
/// or to indicate a sparse file.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sparse: FileFlags { FileFlags(rawValue: _UF_SPARSE) }
|
||||
|
||||
/// File has the Windows system attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SYSTEM` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SYSTEM`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var system: FileFlags { FileFlags(rawValue: _UF_SYSTEM) }
|
||||
|
||||
/// File is a snapshot.
|
||||
///
|
||||
/// The corresponding C constant is `SF_SNAPSHOT`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var snapshot: FileFlags { FileFlags(rawValue: _SF_SNAPSHOT) }
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if !os(Windows)
|
||||
/// A strongly-typed file mode representing a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed `FileMode` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a `FileMode` from the given file type and permissions.
|
||||
///
|
||||
/// - Note: This initializer masks the inputs with their respective bit masks.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(type: FileType, permissions: FilePermissions) {
|
||||
self.rawValue = (type.rawValue & _MODE_FILETYPE_MASK) | (permissions.rawValue & _MODE_PERMISSIONS_MASK)
|
||||
}
|
||||
|
||||
/// The file's type, from the mode's file-type bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the file-type bit mask `S_IFMT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var type: FileType {
|
||||
get { FileType(rawValue: rawValue & _MODE_FILETYPE_MASK) }
|
||||
set { rawValue = (rawValue & ~_MODE_FILETYPE_MASK) | (newValue.rawValue & _MODE_FILETYPE_MASK) }
|
||||
}
|
||||
|
||||
/// The file's permissions, from the mode's permission bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the permissions bit mask `ALLPERMS`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var permissions: FilePermissions {
|
||||
get { FilePermissions(rawValue: rawValue & _MODE_PERMISSIONS_MASK) }
|
||||
set { rawValue = (rawValue & ~_MODE_PERMISSIONS_MASK) | (newValue.rawValue & _MODE_PERMISSIONS_MASK) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,108 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// |------------------------|
|
||||
// | Swift API to C Mapping |
|
||||
// |----------------------------------------|
|
||||
// | FileType | Unix-like Platforms |
|
||||
// |------------------|---------------------|
|
||||
// | directory | S_IFDIR |
|
||||
// | characterSpecial | S_IFCHR |
|
||||
// | blockSpecial | S_IFBLK |
|
||||
// | regular | S_IFREG |
|
||||
// | fifo | S_IFIFO |
|
||||
// | symbolicLink | S_IFLNK |
|
||||
// | socket | S_IFSOCK |
|
||||
// |------------------|---------------------|
|
||||
//
|
||||
// |------------------------------------------------------------------|
|
||||
// | FileType | Darwin | FreeBSD | Other Unix-like Platforms |
|
||||
// |------------------|---------|---------|---------------------------|
|
||||
// | whiteout | S_IFWHT | S_IFWHT | N/A |
|
||||
// |------------------|---------|---------|---------------------------|
|
||||
|
||||
#if !os(Windows)
|
||||
/// A file type matching those contained in a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw file-type bits from the C mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed file type from the raw C `mode_t`.
|
||||
///
|
||||
/// - Note: This initializer stores the `rawValue` directly and **does not**
|
||||
/// mask the value with `S_IFMT`. If the supplied `rawValue` contains bits
|
||||
/// outside of the `S_IFMT` mask, the resulting `FileType` will not compare
|
||||
/// equal to constants like `.directory` and `.symbolicLink`, which may
|
||||
/// be unexpected.
|
||||
///
|
||||
/// If you're unsure whether the `mode_t` contains bits outside of `S_IFMT`,
|
||||
/// you can use `FileMode(rawValue:)` instead to get a strongly-typed
|
||||
/// `FileMode`, then call `.type` to get the properly masked `FileType`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
/// Directory
|
||||
///
|
||||
/// The corresponding C constant is `S_IFDIR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: FileType { FileType(rawValue: _S_IFDIR) }
|
||||
|
||||
/// Character special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFCHR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var characterSpecial: FileType { FileType(rawValue: _S_IFCHR) }
|
||||
|
||||
/// Block special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFBLK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var blockSpecial: FileType { FileType(rawValue: _S_IFBLK) }
|
||||
|
||||
/// Regular file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFREG`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var regular: FileType { FileType(rawValue: _S_IFREG) }
|
||||
|
||||
/// FIFO (or named pipe)
|
||||
///
|
||||
/// The corresponding C constant is `S_IFIFO`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var fifo: FileType { FileType(rawValue: _S_IFIFO) }
|
||||
|
||||
/// Symbolic link
|
||||
///
|
||||
/// The corresponding C constant is `S_IFLNK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symbolicLink: FileType { FileType(rawValue: _S_IFLNK) }
|
||||
|
||||
/// Socket
|
||||
///
|
||||
/// The corresponding C constant is `S_IFSOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var socket: FileType { FileType(rawValue: _S_IFSOCK) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Whiteout file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFWHT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var whiteout: FileType { FileType(rawValue: _S_IFWHT) }
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,84 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if !os(Windows)
|
||||
/// A Swift wrapper of the C `uid_t` type.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `uid_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.UserID
|
||||
|
||||
/// Creates a strongly-typed `UserID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.UserID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `UserID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.UserID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
/// A Swift wrapper of the C `gid_t` type.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `gid_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.GroupID
|
||||
|
||||
/// Creates a strongly-typed `GroupID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.GroupID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `GroupID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.GroupID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
/// A Swift wrapper of the C `dev_t` type.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `dev_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.DeviceID
|
||||
|
||||
/// Creates a strongly-typed `DeviceID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.DeviceID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `DeviceID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.DeviceID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
/// A Swift wrapper of the C `ino_t` type.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `ino_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Inode
|
||||
|
||||
/// Creates a strongly-typed `Inode` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Inode) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `Inode` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.Inode) { self.rawValue = rawValue }
|
||||
}
|
||||
#endif // !os(Windows)
|
||||
@@ -0,0 +1,647 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if !os(Windows) && !os(WASI)
|
||||
|
||||
/// Flags describing a mounted file system.
|
||||
///
|
||||
/// These are the flags reported in the `f_flags` field of a `statfs` struct.
|
||||
/// Some reflect options employed when mounting the file system, while others,
|
||||
/// like `local` and `rootFileSystem`, describe state the kernel reports.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
///
|
||||
/// The corresponding C constants available on each platform:
|
||||
///
|
||||
/// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android |
|
||||
/// |----------------------------------|------------------------|-------------------|-------------------|------------------|------------------|
|
||||
/// | `readOnly` | `MNT_RDONLY` | `MNT_RDONLY` | `MNT_RDONLY` | `ST_RDONLY` | `ST_RDONLY` |
|
||||
/// | `synchronous` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `ST_SYNCHRONOUS` | `ST_SYNCHRONOUS` |
|
||||
/// | `noExecution` | `MNT_NOEXEC` | `MNT_NOEXEC` | `MNT_NOEXEC` | `ST_NOEXEC` | `ST_NOEXEC` |
|
||||
/// | `noSetUserID` | `MNT_NOSUID` | `MNT_NOSUID` | `MNT_NOSUID` | `ST_NOSUID` | `ST_NOSUID` |
|
||||
/// | `noAccessTime` | `MNT_NOATIME` | `MNT_NOATIME` | `MNT_NOATIME` | `ST_NOATIME` | `ST_NOATIME` |
|
||||
/// | `noDevices` | `MNT_NODEV` | N/A | `MNT_NODEV` | `ST_NODEV` | `ST_NODEV` |
|
||||
/// | `mandatoryLocking` | N/A | N/A | N/A | `ST_MANDLOCK` | `ST_MANDLOCK` |
|
||||
/// | `noDirectoryAccessTime` | N/A | N/A | N/A | `ST_NODIRATIME` | `ST_NODIRATIME` |
|
||||
/// | `relativeAccessTime` | N/A | N/A | N/A | `ST_RELATIME` | `ST_RELATIME` |
|
||||
/// | `noSymlinkFollowing` | N/A | `MNT_NOSYMFOLLOW` | N/A | `ST_NOSYMFOLLOW` | `ST_NOSYMFOLLOW` |
|
||||
/// | `asynchronous` | `MNT_ASYNC` | `MNT_ASYNC` | `MNT_ASYNC` | N/A | N/A |
|
||||
/// | `exported` | `MNT_EXPORTED` | `MNT_EXPORTED` | `MNT_EXPORTED` | N/A | N/A |
|
||||
/// | `local` | `MNT_LOCAL` | `MNT_LOCAL` | `MNT_LOCAL` | N/A | N/A |
|
||||
/// | `quotasEnabled` | `MNT_QUOTA` | `MNT_QUOTA` | `MNT_QUOTA` | N/A | N/A |
|
||||
/// | `rootFileSystem` | `MNT_ROOTFS` | `MNT_ROOTFS` | `MNT_ROOTFS` | N/A | N/A |
|
||||
/// | `union` | `MNT_UNION` | `MNT_UNION` | N/A | N/A | N/A |
|
||||
/// | `automounted` | `MNT_AUTOMOUNTED` | `MNT_AUTOMOUNTED` | N/A | N/A | N/A |
|
||||
/// | `multiLabel` | `MNT_MULTILABEL` | `MNT_MULTILABEL` | N/A | N/A | N/A |
|
||||
/// | `exportedReadOnly` | N/A | `MNT_EXRDONLY` | `MNT_EXRDONLY` | N/A | N/A |
|
||||
/// | `exportedByDefault` | N/A | `MNT_DEFEXPORTED` | `MNT_DEFEXPORTED` | N/A | N/A |
|
||||
/// | `exportedAnonymously` | N/A | `MNT_EXPORTANON` | `MNT_EXPORTANON` | N/A | N/A |
|
||||
/// | `softUpdates` | N/A | `MNT_SOFTDEP` | `MNT_SOFTDEP` | N/A | N/A |
|
||||
/// | `contentProtection` | `MNT_CPROTECT` | N/A | N/A | N/A | N/A |
|
||||
/// | `removable` | `MNT_REMOVABLE` | N/A | N/A | N/A | N/A |
|
||||
/// | `quarantined` | `MNT_QUARANTINE` | N/A | N/A | N/A | N/A |
|
||||
/// | `supportsVolfs` | `MNT_DOVOLFS` | N/A | N/A | N/A | N/A |
|
||||
/// | `noBrowsing` | `MNT_DONTBROWSE` | N/A | N/A | N/A | N/A |
|
||||
/// | `ignoresOwnership` | `MNT_IGNORE_OWNERSHIP` | N/A | N/A | N/A | N/A |
|
||||
/// | `journaled` | `MNT_JOURNALED` | N/A | N/A | N/A | N/A |
|
||||
/// | `noUserExtendedAttributes` | `MNT_NOUSERXATTR` | N/A | N/A | N/A | N/A |
|
||||
/// | `defersWrites` | `MNT_DEFWRITE` | N/A | N/A | N/A | N/A |
|
||||
/// | `noSymlinkFollowingAtMountPoint` | `MNT_NOFOLLOW` | N/A | N/A | N/A | N/A |
|
||||
/// | `snapshot` | `MNT_SNAPSHOT` | N/A | N/A | N/A | N/A |
|
||||
/// | `strictAccessTime` | `MNT_STRICTATIME` | N/A | N/A | N/A | N/A |
|
||||
/// | `exportedWithKerberos` | N/A | `MNT_EXKERB` | N/A | N/A | N/A |
|
||||
/// | `exportedPublicly` | N/A | `MNT_EXPUBLIC` | N/A | N/A | N/A |
|
||||
/// | `posixACLs` | N/A | `MNT_ACLS` | N/A | N/A | N/A |
|
||||
/// | `geomJournaled` | N/A | `MNT_GJOURNAL` | N/A | N/A | N/A |
|
||||
/// | `excludedFromDiskFreeReports` | N/A | `MNT_IGNORE` | N/A | N/A | N/A |
|
||||
/// | `nfs4ACLs` | N/A | `MNT_NFS4ACLS` | N/A | N/A | N/A |
|
||||
/// | `noClusteredReads` | N/A | `MNT_NOCLUSTERR` | N/A | N/A | N/A |
|
||||
/// | `noClusteredWrites` | N/A | `MNT_NOCLUSTERW` | N/A | N/A | N/A |
|
||||
/// | `setUserIDDirectories` | N/A | `MNT_SUIDDIR` | N/A | N/A | N/A |
|
||||
/// | `softUpdatesJournaling` | N/A | `MNT_SUJ` | N/A | N/A | N/A |
|
||||
/// | `untrusted` | N/A | `MNT_UNTRUSTED` | N/A | N/A | N/A |
|
||||
/// | `userMounted` | N/A | `MNT_USER` | N/A | N/A | N/A |
|
||||
/// | `verified` | N/A | `MNT_VERIFIED` | N/A | N/A | N/A |
|
||||
/// | `noPermissionChecks` | N/A | N/A | `MNT_NOPERM` | N/A | N/A |
|
||||
/// | `writeExecuteAllowed` | N/A | N/A | `MNT_WXALLOWED` | N/A | N/A |
|
||||
@frozen
|
||||
@available(System 1.9.0, *)
|
||||
public struct MountFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.MountFlags
|
||||
|
||||
/// Creates a strongly-typed `MountFlags` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.MountFlags) { self.rawValue = rawValue }
|
||||
|
||||
// MARK: Flags Available on All Platforms
|
||||
|
||||
/// The file system is mounted read-only, even for the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_RDONLY` on Darwin and BSD,
|
||||
/// or `ST_RDONLY` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var readOnly: MountFlags { MountFlags(rawValue: _MOUNT_RDONLY) }
|
||||
|
||||
/// The file system is written to synchronously.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SYNCHRONOUS` on Darwin and BSD,
|
||||
/// or `ST_SYNCHRONOUS` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var synchronous: MountFlags { MountFlags(rawValue: _MOUNT_SYNCHRONOUS) }
|
||||
|
||||
/// Programs may not be executed from the file system.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOEXEC` on Darwin and BSD,
|
||||
/// or `ST_NOEXEC` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noExecution: MountFlags { MountFlags(rawValue: _MOUNT_NOEXEC) }
|
||||
|
||||
/// Set-user-ID and set-group-ID (setuid and setgid) bits are not honored on
|
||||
/// the file system.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD,
|
||||
/// or `ST_NOSUID` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSetUserID: MountFlags { MountFlags(rawValue: _MOUNT_NOSUID) }
|
||||
|
||||
/// Access times are not updated on the file system.
|
||||
///
|
||||
/// - Note: On OpenBSD, access time may still be updated when the
|
||||
/// modification or status-change time is also being updated.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD,
|
||||
/// or `ST_NOATIME` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noAccessTime: MountFlags { MountFlags(rawValue: _MOUNT_NOATIME) }
|
||||
|
||||
// MARK: Flags Available on All Platforms Except FreeBSD
|
||||
|
||||
#if !os(FreeBSD)
|
||||
/// Special files may not be interpreted on the file system.
|
||||
///
|
||||
/// - Note: Not available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NODEV` on Darwin and OpenBSD,
|
||||
/// or `ST_NODEV` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDevices: MountFlags { MountFlags(rawValue: _MOUNT_NODEV) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Linux and Android
|
||||
|
||||
// Glibc and musl also define `ST_WRITE`, `ST_APPEND`, and `ST_IMMUTABLE`, but
|
||||
// Linux never reports them in `f_flags`, so they have no corresponding flag.
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
/// Mandatory file locking is enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on Linux and Android.
|
||||
/// - Note: Mandatory locking was deprecated and removed in Linux 5.15.
|
||||
///
|
||||
/// The corresponding C constant is `ST_MANDLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var mandatoryLocking: MountFlags { MountFlags(rawValue: _ST_MANDLOCK) }
|
||||
|
||||
/// Directory access times are not updated on the file system.
|
||||
///
|
||||
/// - Note: Only available on Linux and Android.
|
||||
///
|
||||
/// The corresponding C constant is `ST_NODIRATIME`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDirectoryAccessTime: MountFlags { MountFlags(rawValue: _ST_NODIRATIME) }
|
||||
|
||||
/// The access time is only updated if it's earlier than or equal to the file's
|
||||
/// last modification or status-change time, or if it's more than a day old.
|
||||
///
|
||||
/// - Note: Only available on Linux and Android.
|
||||
///
|
||||
/// The corresponding C constant is `ST_RELATIME`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var relativeAccessTime: MountFlags { MountFlags(rawValue: _ST_RELATIME) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Linux, Android, and FreeBSD
|
||||
|
||||
#if os(Linux) || os(Android) || os(FreeBSD)
|
||||
/// Symbolic links are not followed when resolving paths on the file system.
|
||||
///
|
||||
/// - Note: Only available on Linux, Android, and FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOSYMFOLLOW` on FreeBSD,
|
||||
/// or `ST_NOSYMFOLLOW` on Linux and Android.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSymlinkFollowing: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// The file system is written to asynchronously.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_ASYNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var asynchronous: MountFlags { MountFlags(rawValue: _MNT_ASYNC) }
|
||||
|
||||
/// The file system is exported for use over the network via NFS.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_EXPORTED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exported: MountFlags { MountFlags(rawValue: _MNT_EXPORTED) }
|
||||
|
||||
/// The file system is stored locally, rather than being accessed over a network.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_LOCAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var local: MountFlags { MountFlags(rawValue: _MNT_LOCAL) }
|
||||
|
||||
/// Quotas are enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_QUOTA`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var quotasEnabled: MountFlags { MountFlags(rawValue: _MNT_QUOTA) }
|
||||
|
||||
/// The file system is the root file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_ROOTFS`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var rootFileSystem: MountFlags { MountFlags(rawValue: _MNT_ROOTFS) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// The file system is unioned with the underlying file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_UNION`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var union: MountFlags { MountFlags(rawValue: _MNT_UNION) }
|
||||
|
||||
/// The file system was mounted by the automounter.
|
||||
///
|
||||
/// - Note: Only available on Darwin and FreeBSD. See `automount(8)`.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_AUTOMOUNTED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var automounted: MountFlags { MountFlags(rawValue: _MNT_AUTOMOUNTED) }
|
||||
|
||||
/// The file system maintains Mandatory Access Control (MAC) labels for
|
||||
/// individual objects.
|
||||
///
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_MULTILABEL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var multiLabel: MountFlags { MountFlags(rawValue: _MNT_MULTILABEL) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD and OpenBSD
|
||||
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
/// The file system is exported for reading only.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD and OpenBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_EXRDONLY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exportedReadOnly: MountFlags { MountFlags(rawValue: _MNT_EXRDONLY) }
|
||||
|
||||
/// The file system is exported to any host by default.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD and OpenBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DEFEXPORTED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exportedByDefault: MountFlags { MountFlags(rawValue: _MNT_DEFEXPORTED) }
|
||||
|
||||
/// The file system is exported with all remote users mapped to the
|
||||
/// anonymous user account.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD and OpenBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_EXPORTANON`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exportedAnonymously: MountFlags { MountFlags(rawValue: _MNT_EXPORTANON) }
|
||||
|
||||
/// Soft updates are enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD and OpenBSD. Accepted for compatibility
|
||||
/// on OpenBSD, but has no effect there.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SOFTDEP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var softUpdates: MountFlags { MountFlags(rawValue: _MNT_SOFTDEP) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin Only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Per-file encrypted data protection is enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_CPROTECT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var contentProtection: MountFlags { MountFlags(rawValue: _MNT_CPROTECT) }
|
||||
|
||||
/// The file system resides on removable media.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_REMOVABLE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var removable: MountFlags { MountFlags(rawValue: _MNT_REMOVABLE) }
|
||||
|
||||
/// The file system is quarantined.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_QUARANTINE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var quarantined: MountFlags { MountFlags(rawValue: _MNT_QUARANTINE) }
|
||||
|
||||
/// The file system supports volfs.
|
||||
///
|
||||
/// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DOVOLFS`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var supportsVolfs: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) }
|
||||
|
||||
/// The file system should not be presented to the user for browsing
|
||||
/// (e.g. hidden in Finder).
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DONTBROWSE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noBrowsing: MountFlags { MountFlags(rawValue: _MNT_DONTBROWSE) }
|
||||
|
||||
/// The file system ignores ownership information.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ignoresOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) }
|
||||
|
||||
/// The file system is journaled.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_JOURNALED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var journaled: MountFlags { MountFlags(rawValue: _MNT_JOURNALED) }
|
||||
|
||||
/// User extended attributes are not allowed on the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOUSERXATTR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noUserExtendedAttributes: MountFlags { MountFlags(rawValue: _MNT_NOUSERXATTR) }
|
||||
|
||||
/// The file system defers writes.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_DEFWRITE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var defersWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) }
|
||||
|
||||
/// Symbolic links are not followed when resolving the mount point.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOFOLLOW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSymlinkFollowingAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) }
|
||||
|
||||
/// The file system is a snapshot.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SNAPSHOT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var snapshot: MountFlags { MountFlags(rawValue: _MNT_SNAPSHOT) }
|
||||
|
||||
/// Access times are always updated when files are read. Without this flag,
|
||||
/// the file system may skip some access time updates for performance.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_STRICTATIME`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var strictAccessTime: MountFlags { MountFlags(rawValue: _MNT_STRICTATIME) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
/// The file system is exported with Kerberos user-ID mapping.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_EXKERB`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exportedWithKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) }
|
||||
|
||||
/// The file system is exported publicly for WebNFS clients.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_EXPUBLIC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exportedPublicly: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) }
|
||||
|
||||
/// POSIX.1e ACLs are enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_ACLS`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var posixACLs: MountFlags { MountFlags(rawValue: _MNT_ACLS) }
|
||||
|
||||
/// The file system is journaled by `gjournal`.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD. See `gjournal(8)`.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_GJOURNAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var geomJournaled: MountFlags { MountFlags(rawValue: _MNT_GJOURNAL) }
|
||||
|
||||
/// The file system is omitted from `df(1)` listings.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_IGNORE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var excludedFromDiskFreeReports: MountFlags { MountFlags(rawValue: _MNT_IGNORE) }
|
||||
|
||||
/// NFSv4 ACLs are enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NFS4ACLS`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nfs4ACLs: MountFlags { MountFlags(rawValue: _MNT_NFS4ACLS) }
|
||||
|
||||
/// Clustered reads are disabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOCLUSTERR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noClusteredReads: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) }
|
||||
|
||||
/// Clustered writes are disabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOCLUSTERW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noClusteredWrites: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) }
|
||||
|
||||
/// Newly created files in a directory with the set-user-ID bit set are owned
|
||||
/// by that directory's owner, rather than by the creating user.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SUIDDIR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setUserIDDirectories: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) }
|
||||
|
||||
/// Soft updates journaling is enabled on the file system.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_SUJ`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var softUpdatesJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) }
|
||||
|
||||
/// The file system is untrusted, as the integrity of its media is unknown.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_UNTRUSTED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var untrusted: MountFlags { MountFlags(rawValue: _MNT_UNTRUSTED) }
|
||||
|
||||
/// The file system was mounted by a non-root user.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_USER`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userMounted: MountFlags { MountFlags(rawValue: _MNT_USER) }
|
||||
|
||||
/// The file system is marked as verified, so per-file integrity checks are
|
||||
/// skipped on execution.
|
||||
///
|
||||
/// - Note: Only available on FreeBSD. See `mac_veriexec(4)`.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_VERIFIED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var verified: MountFlags { MountFlags(rawValue: _MNT_VERIFIED) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on OpenBSD Only
|
||||
|
||||
#if os(OpenBSD)
|
||||
/// File permissions are not checked on the file system (FFS only).
|
||||
///
|
||||
/// - Note: Only available on OpenBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_NOPERM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noPermissionChecks: MountFlags { MountFlags(rawValue: _MNT_NOPERM) }
|
||||
|
||||
/// Programs residing on the file system may create memory mappings that are
|
||||
/// both writable and executable.
|
||||
///
|
||||
/// By default, requesting such a mapping (via `mmap(2)` or `mprotect(2)`)
|
||||
/// kills the process. This flag lifts that restriction.
|
||||
///
|
||||
/// - Note: Only available on OpenBSD.
|
||||
///
|
||||
/// The corresponding C constant is `MNT_WXALLOWED`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var writeExecuteAllowed: MountFlags { MountFlags(rawValue: _MNT_WXALLOWED) }
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension MountFlags
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
/// A textual representation of the mount flags.
|
||||
@inline(never)
|
||||
public var description: String {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.readOnly, ".readOnly"),
|
||||
(.synchronous, ".synchronous"),
|
||||
(.noExecution, ".noExecution"),
|
||||
(.noSetUserID, ".noSetUserID"),
|
||||
(.noAccessTime, ".noAccessTime"),
|
||||
(.noDevices, ".noDevices"),
|
||||
(.asynchronous, ".asynchronous"),
|
||||
(.exported, ".exported"),
|
||||
(.local, ".local"),
|
||||
(.quotasEnabled, ".quotasEnabled"),
|
||||
(.rootFileSystem, ".rootFileSystem"),
|
||||
(.union, ".union"),
|
||||
(.automounted, ".automounted"),
|
||||
(.multiLabel, ".multiLabel"),
|
||||
(.contentProtection, ".contentProtection"),
|
||||
(.removable, ".removable"),
|
||||
(.quarantined, ".quarantined"),
|
||||
(.supportsVolfs, ".supportsVolfs"),
|
||||
(.noBrowsing, ".noBrowsing"),
|
||||
(.ignoresOwnership, ".ignoresOwnership"),
|
||||
(.journaled, ".journaled"),
|
||||
(.noUserExtendedAttributes, ".noUserExtendedAttributes"),
|
||||
(.defersWrites, ".defersWrites"),
|
||||
(.noSymlinkFollowingAtMountPoint, ".noSymlinkFollowingAtMountPoint"),
|
||||
(.snapshot, ".snapshot"),
|
||||
(.strictAccessTime, ".strictAccessTime"),
|
||||
]
|
||||
#elseif os(FreeBSD)
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.readOnly, ".readOnly"),
|
||||
(.synchronous, ".synchronous"),
|
||||
(.noExecution, ".noExecution"),
|
||||
(.noSetUserID, ".noSetUserID"),
|
||||
(.noAccessTime, ".noAccessTime"),
|
||||
(.noSymlinkFollowing, ".noSymlinkFollowing"),
|
||||
(.asynchronous, ".asynchronous"),
|
||||
(.exported, ".exported"),
|
||||
(.local, ".local"),
|
||||
(.quotasEnabled, ".quotasEnabled"),
|
||||
(.rootFileSystem, ".rootFileSystem"),
|
||||
(.union, ".union"),
|
||||
(.automounted, ".automounted"),
|
||||
(.multiLabel, ".multiLabel"),
|
||||
(.exportedReadOnly, ".exportedReadOnly"),
|
||||
(.exportedByDefault, ".exportedByDefault"),
|
||||
(.exportedAnonymously, ".exportedAnonymously"),
|
||||
(.softUpdates, ".softUpdates"),
|
||||
(.exportedWithKerberos, ".exportedWithKerberos"),
|
||||
(.exportedPublicly, ".exportedPublicly"),
|
||||
(.posixACLs, ".posixACLs"),
|
||||
(.geomJournaled, ".geomJournaled"),
|
||||
(.excludedFromDiskFreeReports, ".excludedFromDiskFreeReports"),
|
||||
(.nfs4ACLs, ".nfs4ACLs"),
|
||||
(.noClusteredReads, ".noClusteredReads"),
|
||||
(.noClusteredWrites, ".noClusteredWrites"),
|
||||
(.setUserIDDirectories, ".setUserIDDirectories"),
|
||||
(.softUpdatesJournaling, ".softUpdatesJournaling"),
|
||||
(.untrusted, ".untrusted"),
|
||||
(.userMounted, ".userMounted"),
|
||||
(.verified, ".verified"),
|
||||
]
|
||||
#elseif os(OpenBSD)
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.readOnly, ".readOnly"),
|
||||
(.synchronous, ".synchronous"),
|
||||
(.noExecution, ".noExecution"),
|
||||
(.noSetUserID, ".noSetUserID"),
|
||||
(.noAccessTime, ".noAccessTime"),
|
||||
(.noDevices, ".noDevices"),
|
||||
(.asynchronous, ".asynchronous"),
|
||||
(.exported, ".exported"),
|
||||
(.local, ".local"),
|
||||
(.quotasEnabled, ".quotasEnabled"),
|
||||
(.rootFileSystem, ".rootFileSystem"),
|
||||
(.exportedReadOnly, ".exportedReadOnly"),
|
||||
(.exportedByDefault, ".exportedByDefault"),
|
||||
(.exportedAnonymously, ".exportedAnonymously"),
|
||||
(.softUpdates, ".softUpdates"),
|
||||
(.noPermissionChecks, ".noPermissionChecks"),
|
||||
(.writeExecuteAllowed, ".writeExecuteAllowed"),
|
||||
]
|
||||
#elseif os(Linux) || os(Android)
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.readOnly, ".readOnly"),
|
||||
(.synchronous, ".synchronous"),
|
||||
(.noExecution, ".noExecution"),
|
||||
(.noSetUserID, ".noSetUserID"),
|
||||
(.noAccessTime, ".noAccessTime"),
|
||||
(.noDevices, ".noDevices"),
|
||||
(.mandatoryLocking, ".mandatoryLocking"),
|
||||
(.noDirectoryAccessTime, ".noDirectoryAccessTime"),
|
||||
(.relativeAccessTime, ".relativeAccessTime"),
|
||||
(.noSymlinkFollowing, ".noSymlinkFollowing"),
|
||||
]
|
||||
#endif
|
||||
|
||||
return _buildDescription(descriptions)
|
||||
}
|
||||
|
||||
/// A textual representation of the mount flags, suitable for debugging.
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
#endif // !os(Windows) && !os(WASI)
|
||||
@@ -0,0 +1,680 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
// Must import here to use C stat properties in @_alwaysEmitIntoClient APIs.
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Stat
|
||||
|
||||
/// A Swift wrapper of the C `stat` struct.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 1.7.0, *)
|
||||
public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C `stat` struct.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Stat
|
||||
|
||||
/// Creates a Swift `Stat` from the raw C struct.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Stat) { self.rawValue = rawValue }
|
||||
|
||||
// MARK: Stat.Flags
|
||||
|
||||
/// Flags representing those passed to `fstatat()`.
|
||||
@frozen
|
||||
public struct Flags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a strongly-typed `Stat.Flags` from raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlinkNoFollow: Flags { Flags(rawValue: _AT_SYMLINK_NOFOLLOW) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
/// If _any_ symbolic link is encountered during path resolution, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW_ANY`.
|
||||
/// - Note: Only available on Darwin.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlinkNoFollowAny: Flags { Flags(rawValue: _AT_SYMLINK_NOFOLLOW_ANY) }
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin, _version: 346) || os(FreeBSD)
|
||||
/// If the path does not reside in the hierarchy beneath the starting directory, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_RESOLVE_BENEATH`.
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var resolveBeneath: Flags { Flags(rawValue: _AT_RESOLVE_BENEATH) }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._stat(
|
||||
$0,
|
||||
followTargetSymlink: followTargetSymlink,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._stat(
|
||||
path,
|
||||
followTargetSymlink: followTargetSymlink,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _stat(
|
||||
_ ptr: UnsafePointer<CChar>,
|
||||
followTargetSymlink: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.Stat, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
if followTargetSymlink {
|
||||
system_stat(ptr, &result)
|
||||
} else {
|
||||
system_lstat(ptr, &result)
|
||||
}
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from a `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstat(
|
||||
fd,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _fstat(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.Stat, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstat(fd.rawValue, &result)
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._fstatat(
|
||||
$0,
|
||||
relativeTo: _AT_FDCWD,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._fstatat(
|
||||
$0,
|
||||
relativeTo: fd.rawValue,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstatat(
|
||||
path,
|
||||
relativeTo: _AT_FDCWD,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstatat(
|
||||
path,
|
||||
relativeTo: fd.rawValue,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _fstatat(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
relativeTo fd: FileDescriptor.RawValue,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.Stat, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstatat(fd, path, &result, flags.rawValue)
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// ID of device containing file
|
||||
///
|
||||
/// The corresponding C property is `st_dev`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var deviceID: DeviceID {
|
||||
get { DeviceID(rawValue: numericCast(rawValue.st_dev)) }
|
||||
set { rawValue.st_dev = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// Inode number
|
||||
///
|
||||
/// The corresponding C property is `st_ino`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var inode: Inode {
|
||||
get { Inode(rawValue: numericCast(rawValue.st_ino)) }
|
||||
set { rawValue.st_ino = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// File mode
|
||||
///
|
||||
/// The corresponding C property is `st_mode`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var mode: FileMode {
|
||||
get { FileMode(rawValue: numericCast(rawValue.st_mode)) }
|
||||
set { rawValue.st_mode = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// File type for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.type`. Modifying this
|
||||
/// property will update the underlying `st_mode` accordingly.
|
||||
@_alwaysEmitIntoClient
|
||||
public var type: FileType {
|
||||
get { mode.type }
|
||||
set {
|
||||
var newMode = mode
|
||||
newMode.type = newValue
|
||||
mode = newMode
|
||||
}
|
||||
}
|
||||
|
||||
/// File permissions for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.permissions`. Modifying
|
||||
/// this property will update the underlying `st_mode` accordingly.
|
||||
@_alwaysEmitIntoClient
|
||||
public var permissions: FilePermissions {
|
||||
get { mode.permissions }
|
||||
set {
|
||||
var newMode = mode
|
||||
newMode.permissions = newValue
|
||||
mode = newMode
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of hard links
|
||||
///
|
||||
/// The corresponding C property is `st_nlink`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var linkCount: Int {
|
||||
get { Int(rawValue.st_nlink) }
|
||||
set { rawValue.st_nlink = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// User ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_uid`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var userID: UserID {
|
||||
get { UserID(rawValue: rawValue.st_uid) }
|
||||
set { rawValue.st_uid = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// Group ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_gid`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var groupID: GroupID {
|
||||
get { GroupID(rawValue: rawValue.st_gid) }
|
||||
set { rawValue.st_gid = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// Device ID (if special file)
|
||||
///
|
||||
/// For character or block special files, the returned `DeviceID` may have
|
||||
/// meaningful major and minor values. For non-special files, this
|
||||
/// property is usually meaningless and often set to 0.
|
||||
///
|
||||
/// The corresponding C property is `st_rdev`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var specialDeviceID: DeviceID {
|
||||
get { DeviceID(rawValue: numericCast(rawValue.st_rdev)) }
|
||||
set { rawValue.st_rdev = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// Total size, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_size` field,
|
||||
/// which can have file-system–dependent behavior. For example, this property
|
||||
/// can return different values for a file's data fork and resource fork, and some
|
||||
/// file systems report logical size rather than actual disk usage for compressed
|
||||
/// or cloned files.
|
||||
///
|
||||
/// The corresponding C property is `st_size`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var size: Int64 {
|
||||
get { Int64(rawValue.st_size) }
|
||||
set { rawValue.st_size = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// Block size for file system I/O, in bytes
|
||||
///
|
||||
/// The corresponding C property is `st_blksize`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var preferredIOBlockSize: Int {
|
||||
get { Int(rawValue.st_blksize) }
|
||||
set { rawValue.st_blksize = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// Number of 512-byte blocks allocated
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file-system–dependent behavior.
|
||||
///
|
||||
/// The corresponding C property is `st_blocks`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var blocksAllocated: Int64 {
|
||||
get { Int64(rawValue.st_blocks) }
|
||||
set { rawValue.st_blocks = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// Total size allocated, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file-system–dependent behavior.
|
||||
///
|
||||
/// - Note: Calculated as `512 * blocksAllocated`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var sizeAllocated: Int64 {
|
||||
512 * blocksAllocated
|
||||
}
|
||||
|
||||
// NOTE: "st_" property names are used for the `timespec` properties so
|
||||
// we can reserve `accessTime`, `modificationTime`, etc. for potential
|
||||
// `UTCClock.Instant` properties in the future.
|
||||
|
||||
/// Time of last access, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin).
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_atim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_atimespec
|
||||
#else
|
||||
rawValue.st_atim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_atimespec = newValue
|
||||
#else
|
||||
rawValue.st_atim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Time of last modification, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin).
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_mtim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_mtimespec
|
||||
#else
|
||||
rawValue.st_mtim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_mtimespec = newValue
|
||||
#else
|
||||
rawValue.st_mtim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Time of last status (inode) change, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin).
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_ctim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_ctimespec
|
||||
#else
|
||||
rawValue.st_ctim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_ctimespec = newValue
|
||||
#else
|
||||
rawValue.st_ctim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Time of file creation, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin).
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_birthtim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_birthtimespec
|
||||
#else
|
||||
rawValue.st_birthtim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_birthtimespec = newValue
|
||||
#else
|
||||
rawValue.st_birthtim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// File flags
|
||||
///
|
||||
/// The corresponding C property is `st_flags`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var flags: FileFlags {
|
||||
get { FileFlags(rawValue: rawValue.st_flags) }
|
||||
set { rawValue.st_flags = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number may be used to distinguish between different
|
||||
/// files that have used the same inode over time.
|
||||
///
|
||||
/// The corresponding C property is `st_gen`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
|
||||
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var generationNumber: UInt64 {
|
||||
get { UInt64(rawValue.st_gen) }
|
||||
set { rawValue.st_gen = numericCast(newValue) }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
extension Stat: Equatable {
|
||||
/// Compares the meaningful file-metadata fields of two `Stat` values.
|
||||
///
|
||||
/// Alignment padding and platform reserved/"spare" fields are not compared.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
guard lhs.rawValue.st_dev == rhs.rawValue.st_dev,
|
||||
lhs.rawValue.st_ino == rhs.rawValue.st_ino,
|
||||
lhs.rawValue.st_mode == rhs.rawValue.st_mode,
|
||||
lhs.rawValue.st_nlink == rhs.rawValue.st_nlink,
|
||||
lhs.rawValue.st_uid == rhs.rawValue.st_uid,
|
||||
lhs.rawValue.st_gid == rhs.rawValue.st_gid,
|
||||
lhs.rawValue.st_rdev == rhs.rawValue.st_rdev,
|
||||
lhs.rawValue.st_size == rhs.rawValue.st_size,
|
||||
lhs.rawValue.st_blksize == rhs.rawValue.st_blksize,
|
||||
lhs.rawValue.st_blocks == rhs.rawValue.st_blocks,
|
||||
lhs.st_atim.tv_sec == rhs.st_atim.tv_sec,
|
||||
lhs.st_atim.tv_nsec == rhs.st_atim.tv_nsec,
|
||||
lhs.st_mtim.tv_sec == rhs.st_mtim.tv_sec,
|
||||
lhs.st_mtim.tv_nsec == rhs.st_mtim.tv_nsec,
|
||||
lhs.st_ctim.tv_sec == rhs.st_ctim.tv_sec,
|
||||
lhs.st_ctim.tv_nsec == rhs.st_ctim.tv_nsec else {
|
||||
return false
|
||||
}
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
guard lhs.st_birthtim.tv_sec == rhs.st_birthtim.tv_sec,
|
||||
lhs.st_birthtim.tv_nsec == rhs.st_birthtim.tv_nsec else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
guard lhs.rawValue.st_flags == rhs.rawValue.st_flags,
|
||||
lhs.rawValue.st_gen == rhs.rawValue.st_gen else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
extension Stat: Hashable {
|
||||
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
|
||||
///
|
||||
/// These are the same fields compared by `==`, fed in the same order.
|
||||
/// Alignment padding and platform reserved/"spare" fields are not hashed.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(rawValue.st_dev)
|
||||
hasher.combine(rawValue.st_ino)
|
||||
hasher.combine(rawValue.st_mode)
|
||||
hasher.combine(rawValue.st_nlink)
|
||||
hasher.combine(rawValue.st_uid)
|
||||
hasher.combine(rawValue.st_gid)
|
||||
hasher.combine(rawValue.st_rdev)
|
||||
hasher.combine(rawValue.st_size)
|
||||
hasher.combine(rawValue.st_blksize)
|
||||
hasher.combine(rawValue.st_blocks)
|
||||
hasher.combine(st_atim.tv_sec)
|
||||
hasher.combine(st_atim.tv_nsec)
|
||||
hasher.combine(st_mtim.tv_sec)
|
||||
hasher.combine(st_mtim.tv_nsec)
|
||||
hasher.combine(st_ctim.tv_sec)
|
||||
hasher.combine(st_ctim.tv_nsec)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
hasher.combine(st_birthtim.tv_sec)
|
||||
hasher.combine(st_birthtim.tv_nsec)
|
||||
#endif
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
hasher.combine(rawValue.st_flags)
|
||||
hasher.combine(rawValue.st_gen)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible and CustomDebugStringConvertible
|
||||
|
||||
// MARK: - FileDescriptor Extensions
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
extension FileDescriptor {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FilePath Extensions
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
extension FilePath {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, followTargetSymlink: followTargetSymlink, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, flags: flags, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, relativeTo: fd, flags: flags, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !os(Windows)
|
||||
@@ -0,0 +1,866 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
/// A Swift wrapper of the C `statfs` struct.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
@available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.")
|
||||
public struct StatFS {
|
||||
/// Creates a `StatFS` from a `FilePath`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
fatalError("StatFS is unavailable on Windows")
|
||||
}
|
||||
|
||||
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
fatalError("StatFS is unavailable on Windows")
|
||||
}
|
||||
|
||||
/// Creates a `StatFS` from a `FileDescriptor`.
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
fatalError("StatFS is unavailable on Windows")
|
||||
}
|
||||
}
|
||||
|
||||
#elseif os(WASI)
|
||||
|
||||
/// A Swift wrapper of the C `statfs` struct.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
@available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.")
|
||||
public struct StatFS {
|
||||
/// Creates a `StatFS` from a `FilePath`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
fatalError("StatFS is unavailable on WASI")
|
||||
}
|
||||
|
||||
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
fatalError("StatFS is unavailable on WASI")
|
||||
}
|
||||
|
||||
/// Creates a `StatFS` from a `FileDescriptor`.
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
fatalError("StatFS is unavailable on WASI")
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
// Must import here to use C statfs properties in @_alwaysEmitIntoClient APIs.
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
#if os(Linux)
|
||||
import CSystemStatFS
|
||||
#endif
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - FileSystemID
|
||||
|
||||
/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs`
|
||||
/// struct.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
@frozen
|
||||
@available(System 1.9.0, *)
|
||||
public struct FileSystemID: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C file system ID.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.FileSystemID
|
||||
|
||||
/// Creates a strongly-typed `FileSystemID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.FileSystemID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `FileSystemID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.FileSystemID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
// `CInterop.FileSystemID` is the C `fsid_t` struct (a fixed two-element
|
||||
// `int32_t` array), which provides no synthesized conformances.
|
||||
@available(System 1.9.0, *)
|
||||
extension FileSystemID {
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _words: (Int32, Int32) {
|
||||
#if os(Linux) || os(Android)
|
||||
rawValue.__val
|
||||
#else
|
||||
rawValue.val
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_words words: (Int32, Int32)) {
|
||||
#if os(Linux) || os(Android)
|
||||
self.init(rawValue: CInterop.FileSystemID(__val: words))
|
||||
#else
|
||||
self.init(rawValue: CInterop.FileSystemID(val: words))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension FileSystemID: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs._words.0 == rhs._words.0 && lhs._words.1 == rhs._words.1
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension FileSystemID: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_words.0)
|
||||
hasher.combine(_words.1)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension FileSystemID: Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.unkeyedContainer()
|
||||
try container.encode(_words.0)
|
||||
try container.encode(_words.1)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(from decoder: any Decoder) throws {
|
||||
var container = try decoder.unkeyedContainer()
|
||||
let val0 = try container.decode(Int32.self)
|
||||
let val1 = try container.decode(Int32.self)
|
||||
self.init(_words: (val0, val1))
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension FileSystemID: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the file system ID.
|
||||
@inline(never)
|
||||
public var description: String {
|
||||
"FileSystemID(\(_words.0), \(_words.1))"
|
||||
}
|
||||
|
||||
/// A textual representation of the file system ID, suitable for debugging.
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
// MARK: - FileSystemType
|
||||
|
||||
/// A Swift wrapper of the C `f_type` file system type found in a `statfs`
|
||||
/// struct.
|
||||
///
|
||||
/// - Note: Only available on Linux and Android.
|
||||
@frozen
|
||||
@available(System 1.9.0, *)
|
||||
public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C file system type.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: UInt32
|
||||
|
||||
/// Creates a strongly-typed `FileSystemType` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: UInt32) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `FileSystemType` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: UInt32) { self.rawValue = rawValue }
|
||||
}
|
||||
#endif // os(Linux) || os(Android)
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
// MARK: - FileSystemSubtype
|
||||
|
||||
/// A Swift wrapper of the C `f_fssubtype` file system subtype found in a
|
||||
/// `statfs` struct on Darwin.
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
@frozen
|
||||
@available(System 1.9.0, *)
|
||||
public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C file system subtype.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: UInt32
|
||||
|
||||
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: UInt32) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: UInt32) { self.rawValue = rawValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
// MARK: - FileSystemTypeName
|
||||
|
||||
/// A Swift wrapper of the C `f_fstypename` file system type name found in a
|
||||
/// `statfs` struct.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
@frozen
|
||||
@available(System 1.9.0, *)
|
||||
public struct FileSystemTypeName
|
||||
: RawRepresentable, Sendable, Hashable, Codable, ExpressibleByStringLiteral
|
||||
{
|
||||
|
||||
/// The raw file system type name.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: String
|
||||
|
||||
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: String) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: String) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a `FileSystemTypeName` from a string literal, such as `"apfs"`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(stringLiteral value: String) { self.rawValue = value }
|
||||
|
||||
// MARK: Type Names Available on Darwin Only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// The Apple File System (APFS).
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding `f_fstypename` value is `"apfs"`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var apfs: FileSystemTypeName { FileSystemTypeName(rawValue: "apfs") }
|
||||
|
||||
/// The Mac OS Extended file system (HFS Plus).
|
||||
///
|
||||
/// - Note: Only available on Darwin.
|
||||
///
|
||||
/// The corresponding `f_fstypename` value is `"hfs"`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var hfs: FileSystemTypeName { FileSystemTypeName(rawValue: "hfs") }
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension FileSystemTypeName: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// The file system type name, such as `apfs`.
|
||||
@inline(never)
|
||||
public var description: String { rawValue }
|
||||
|
||||
/// The file system type name as a quoted string, such as `"apfs"`.
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
#endif // SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
|
||||
// MARK: - StatFS
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
// Helpers for reading the fixed-size, NUL-terminated C character buffers
|
||||
// (`f_fstypename`, `f_mntonname`, `f_mntfromname`) in Darwin/BSD `statfs`.
|
||||
// If the buffer has no NUL (malformed), the entire buffer is used.
|
||||
@available(System 1.9.0, *)
|
||||
extension String {
|
||||
@usableFromInline
|
||||
internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) {
|
||||
let bytes = buffer.prefix { $0 != 0 }
|
||||
self = String(decoding: bytes, as: CInterop.PlatformUnicodeEncoding.self)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension FilePath {
|
||||
@usableFromInline
|
||||
internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) {
|
||||
let chars = buffer.bindMemory(to: CInterop.PlatformChar.self)
|
||||
guard let base = chars.baseAddress else {
|
||||
self = FilePath()
|
||||
return
|
||||
}
|
||||
self = if chars.firstIndex(of: 0) != nil {
|
||||
FilePath(platformString: base)
|
||||
} else {
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: CInterop.PlatformChar.self,
|
||||
capacity: chars.count + 1
|
||||
) { terminatedBuffer in
|
||||
terminatedBuffer.baseAddress!.initialize(from: base, count: chars.count)
|
||||
terminatedBuffer[chars.count] = 0
|
||||
return FilePath(platformString: terminatedBuffer.baseAddress!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// A Swift wrapper of the C `statfs` struct.
|
||||
///
|
||||
/// - Note: Not available on Windows or WASI.
|
||||
/// - Note: The numeric properties clamp when converting to or from the
|
||||
/// underlying C field. Use `rawValue` for exact, unclamped access.
|
||||
@frozen
|
||||
@available(System 1.9.0, *)
|
||||
public struct StatFS: RawRepresentable, Sendable, Hashable {
|
||||
|
||||
/// The raw C `statfs` struct.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.StatFS
|
||||
|
||||
/// Creates a Swift `StatFS` from the raw C struct.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.StatFS) { self.rawValue = rawValue }
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a `StatFS` from a `FilePath`.
|
||||
///
|
||||
/// The corresponding C function is `statfs()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._statfs($0, retryOnInterrupt: retryOnInterrupt)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
|
||||
///
|
||||
/// The corresponding C function is `statfs()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._statfs(
|
||||
path, retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _statfs(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.StatFS, Errno> {
|
||||
var result = CInterop.StatFS()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_statfs(path, &result)
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
/// Creates a `StatFS` from a `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstatfs()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstatfs(
|
||||
fd, retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _fstatfs(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.StatFS, Errno> {
|
||||
var result = CInterop.StatFS()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstatfs(fd.rawValue, &result)
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// File system block size, in bytes.
|
||||
///
|
||||
/// - Note: On Darwin and BSD, this is the fundamental size for block counts.
|
||||
/// Other platforms use `fragmentSize` (`f_frsize`) instead.
|
||||
///
|
||||
/// The corresponding C property is `f_bsize`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var blockSize: Int {
|
||||
get { Int(clamping: rawValue.f_bsize) }
|
||||
set { rawValue.f_bsize = .init(clamping: newValue) }
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// Block size for optimal data transfer, in bytes.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_iosize`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var preferredIOBlockSize: Int {
|
||||
get { Int(clamping: rawValue.f_iosize) }
|
||||
set { rawValue.f_iosize = .init(clamping: newValue) }
|
||||
}
|
||||
#else
|
||||
/// File system fragment size, in bytes.
|
||||
///
|
||||
/// - Note: On Linux and Android, this is the fundamental size for block
|
||||
/// counts. Not present on Darwin or BSD, which use `blockSize` instead.
|
||||
///
|
||||
/// The corresponding C property is `f_frsize`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var fragmentSize: Int {
|
||||
get { Int(clamping: rawValue.f_frsize) }
|
||||
set { rawValue.f_frsize = .init(clamping: newValue) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The fundamental block size used for space calculations, in bytes.
|
||||
///
|
||||
/// This is `blockSize` on Darwin and BSD, or `fragmentSize` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _fundamentalBlockSize: UInt64 {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
UInt64(clamping: rawValue.f_bsize)
|
||||
#else
|
||||
UInt64(clamping: rawValue.f_frsize)
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _saturatingSpace(_ blocks: UInt64) -> UInt64 {
|
||||
let (result, overflow) = blocks.multipliedReportingOverflow(by: _fundamentalBlockSize)
|
||||
return overflow ? .max : result
|
||||
}
|
||||
|
||||
/// Total number of blocks in the file system.
|
||||
///
|
||||
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
|
||||
/// otherwise.
|
||||
///
|
||||
/// The corresponding C property is `f_blocks`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var totalBlocks: UInt64 {
|
||||
get { UInt64(clamping: rawValue.f_blocks) }
|
||||
set { rawValue.f_blocks = .init(clamping: newValue) }
|
||||
}
|
||||
|
||||
/// Total size of the file system, in bytes.
|
||||
///
|
||||
/// - Note: Computed for convenience as `totalBlocks` times the fundamental
|
||||
/// block size (see `totalBlocks`). Saturates to `UInt64.max` on overflow.
|
||||
@_alwaysEmitIntoClient
|
||||
public var totalSpace: UInt64 { _saturatingSpace(totalBlocks) }
|
||||
|
||||
/// Number of free blocks in the file system.
|
||||
///
|
||||
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
|
||||
/// otherwise.
|
||||
///
|
||||
/// The corresponding C property is `f_bfree`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var freeBlocks: UInt64 {
|
||||
get { UInt64(clamping: rawValue.f_bfree) }
|
||||
set { rawValue.f_bfree = .init(clamping: newValue) }
|
||||
}
|
||||
|
||||
/// Free space in the file system, in bytes.
|
||||
///
|
||||
/// - Note: Computed for convenience as `freeBlocks` times the fundamental
|
||||
/// block size (see `freeBlocks`). Saturates to `UInt64.max` on overflow.
|
||||
@_alwaysEmitIntoClient
|
||||
public var freeSpace: UInt64 { _saturatingSpace(freeBlocks) }
|
||||
|
||||
/// Number of free blocks available to non-superuser.
|
||||
///
|
||||
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
|
||||
/// otherwise. On FreeBSD and OpenBSD, the underlying C property is
|
||||
/// signed; negative values are clamped to 0.
|
||||
///
|
||||
/// The corresponding C property is `f_bavail`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var availableBlocks: UInt64 {
|
||||
get { UInt64(clamping: rawValue.f_bavail) }
|
||||
set { rawValue.f_bavail = .init(clamping: newValue) }
|
||||
}
|
||||
|
||||
/// Available space in the file system for non-superuser, in bytes.
|
||||
///
|
||||
/// - Note: Computed for convenience as `availableBlocks` times the fundamental
|
||||
/// block size (see `availableBlocks`). Saturates to `UInt64.max` on overflow.
|
||||
@_alwaysEmitIntoClient
|
||||
public var availableSpace: UInt64 { _saturatingSpace(availableBlocks) }
|
||||
|
||||
/// Total number of inodes in the file system.
|
||||
///
|
||||
/// The corresponding C property is `f_files`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var totalInodes: UInt64 {
|
||||
get { UInt64(clamping: rawValue.f_files) }
|
||||
set { rawValue.f_files = .init(clamping: newValue) }
|
||||
}
|
||||
|
||||
/// Number of free inodes in the file system.
|
||||
///
|
||||
/// - Note: On FreeBSD, this reports the inodes available to a non-superuser
|
||||
/// rather than the total free count, and the underlying C field is signed
|
||||
/// (negative values are clamped to 0); on other platforms, it is the total
|
||||
/// number of free inodes.
|
||||
///
|
||||
/// The corresponding C property is `f_ffree`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var freeInodes: UInt64 {
|
||||
get { UInt64(clamping: rawValue.f_ffree) }
|
||||
set { rawValue.f_ffree = .init(clamping: newValue) }
|
||||
}
|
||||
|
||||
#if os(OpenBSD)
|
||||
/// Number of free inodes available to non-superuser.
|
||||
///
|
||||
/// - Note: Darwin, FreeBSD, Linux, and Android `statfs` do not report it.
|
||||
/// On OpenBSD, the underlying C property is signed; negative values are
|
||||
/// clamped to 0.
|
||||
///
|
||||
/// The corresponding C property is `f_favail`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var availableInodes: UInt64 {
|
||||
get { UInt64(clamping: rawValue.f_favail) }
|
||||
set { rawValue.f_favail = .init(clamping: newValue) }
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
/// Maximum length of a file name on the file system, in bytes.
|
||||
///
|
||||
/// - Note: Darwin's `statfs` does not report it.
|
||||
///
|
||||
/// The corresponding C property is `f_namelen` on Linux and Android, or
|
||||
/// `f_namemax` otherwise.
|
||||
@_alwaysEmitIntoClient
|
||||
public var maximumNameLength: Int {
|
||||
get {
|
||||
#if os(Linux) || os(Android)
|
||||
Int(clamping: rawValue.f_namelen)
|
||||
#else
|
||||
Int(clamping: rawValue.f_namemax)
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if os(Linux) || os(Android)
|
||||
rawValue.f_namelen = .init(clamping: newValue)
|
||||
#else
|
||||
rawValue.f_namemax = .init(clamping: newValue)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// File system ID.
|
||||
///
|
||||
/// The corresponding C property is `f_fsid`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var fileSystemID: FileSystemID {
|
||||
get { FileSystemID(rawValue: rawValue.f_fsid) }
|
||||
set { rawValue.f_fsid = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// Flags describing how the file system is mounted.
|
||||
///
|
||||
/// - Note: On Linux, the kernel also sets an `ST_VALID` bit in `f_flags`
|
||||
/// to mark the field as filled in. It isn't a mount flag, so this
|
||||
/// property omits it like glibc's `statvfs` and Bionic's `statfs` do.
|
||||
/// The setter preserves it.
|
||||
///
|
||||
/// The corresponding C property is `f_flags`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var mountFlags: MountFlags {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
MountFlags(rawValue: rawValue.f_flags)
|
||||
#elseif os(Linux) || os(Android)
|
||||
MountFlags(rawValue: CInterop.MountFlags(truncatingIfNeeded: rawValue.f_flags) & ~_ST_VALID_BIT)
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
rawValue.f_flags = newValue.rawValue
|
||||
#elseif os(Linux) || os(Android)
|
||||
let valid = CInterop.MountFlags(truncatingIfNeeded: rawValue.f_flags) & _ST_VALID_BIT
|
||||
rawValue.f_flags = .init(truncatingIfNeeded: newValue.rawValue | valid)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
/// File system type.
|
||||
///
|
||||
/// - Note: This is the file system's magic number, such as `0xEF53` for
|
||||
/// ext4. Only available on Linux and Android. On Darwin and BSD, use
|
||||
/// `typeName` to identify the file system.
|
||||
///
|
||||
/// The corresponding C property is `f_type`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var type: FileSystemType {
|
||||
get {
|
||||
// glibc's `f_type` is a signed `long` and can be negative.
|
||||
FileSystemType(rawValue: UInt32(truncatingIfNeeded: rawValue.f_type))
|
||||
}
|
||||
set {
|
||||
rawValue.f_type = .init(truncatingIfNeeded: newValue.rawValue)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// File system subtype.
|
||||
///
|
||||
/// - Note: This is a numeric value whose meaning depends on `typeName`,
|
||||
/// with no stable, public constants. Only available on Darwin.
|
||||
///
|
||||
/// The corresponding C property is `f_fssubtype`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var subtype: FileSystemSubtype {
|
||||
get { FileSystemSubtype(rawValue: rawValue.f_fssubtype) }
|
||||
set { rawValue.f_fssubtype = newValue.rawValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// User that mounted the file system.
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_owner`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var owner: UserID {
|
||||
get { UserID(rawValue: rawValue.f_owner) }
|
||||
set { rawValue.f_owner = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// File system type name, such as "apfs".
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_fstypename`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var typeName: FileSystemTypeName {
|
||||
FileSystemTypeName(rawValue: withUnsafeBytes(of: rawValue.f_fstypename) {
|
||||
String(_nullTerminatedBytes: $0)
|
||||
})
|
||||
}
|
||||
|
||||
/// Directory where the file system is mounted, such as "/System/Volumes/Data".
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_mntonname`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var mountPoint: FilePath {
|
||||
withUnsafeBytes(of: rawValue.f_mntonname) {
|
||||
FilePath(_nullTerminatedBytes: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The source of the mounted file system, such as "/dev/disk3s7".
|
||||
///
|
||||
/// - Note: Only available on Darwin and BSD.
|
||||
///
|
||||
/// The corresponding C property is `f_mntfromname`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var mountSource: FilePath {
|
||||
withUnsafeBytes(of: rawValue.f_mntfromname) {
|
||||
FilePath(_nullTerminatedBytes: $0)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - StatFS Equatable & Hashable
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
extension StatFS {
|
||||
/// Compares the file system metadata fields of two `StatFS` values,
|
||||
/// including fields not exposed as properties, such as `f_flags_ext` on
|
||||
/// Darwin.
|
||||
///
|
||||
/// Fields are compared by their raw C values. Reserved/"spare" fields and
|
||||
/// OpenBSD's `mount_info` union are not compared. Name buffers are compared
|
||||
/// only up to their NUL terminators.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
guard lhs.rawValue.f_bsize == rhs.rawValue.f_bsize,
|
||||
lhs.rawValue.f_blocks == rhs.rawValue.f_blocks,
|
||||
lhs.rawValue.f_bfree == rhs.rawValue.f_bfree,
|
||||
lhs.rawValue.f_bavail == rhs.rawValue.f_bavail,
|
||||
lhs.rawValue.f_files == rhs.rawValue.f_files,
|
||||
lhs.rawValue.f_ffree == rhs.rawValue.f_ffree,
|
||||
lhs.fileSystemID == rhs.fileSystemID else {
|
||||
return false
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
guard lhs.rawValue.f_iosize == rhs.rawValue.f_iosize,
|
||||
lhs.rawValue.f_flags == rhs.rawValue.f_flags,
|
||||
lhs.rawValue.f_owner == rhs.rawValue.f_owner,
|
||||
_nullTerminatedBytesEqual(lhs.rawValue.f_fstypename,
|
||||
rhs.rawValue.f_fstypename),
|
||||
_nullTerminatedBytesEqual(lhs.rawValue.f_mntonname,
|
||||
rhs.rawValue.f_mntonname),
|
||||
_nullTerminatedBytesEqual(lhs.rawValue.f_mntfromname,
|
||||
rhs.rawValue.f_mntfromname) else {
|
||||
return false
|
||||
}
|
||||
#elseif os(Linux) || os(Android)
|
||||
guard lhs.rawValue.f_type == rhs.rawValue.f_type,
|
||||
lhs.rawValue.f_frsize == rhs.rawValue.f_frsize,
|
||||
lhs.rawValue.f_flags == rhs.rawValue.f_flags,
|
||||
lhs.rawValue.f_namelen == rhs.rawValue.f_namelen else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
guard lhs.rawValue.f_type == rhs.rawValue.f_type,
|
||||
lhs.rawValue.f_fssubtype == rhs.rawValue.f_fssubtype,
|
||||
lhs.rawValue.f_flags_ext == rhs.rawValue.f_flags_ext else {
|
||||
return false
|
||||
}
|
||||
#elseif os(FreeBSD)
|
||||
guard lhs.rawValue.f_version == rhs.rawValue.f_version,
|
||||
lhs.rawValue.f_type == rhs.rawValue.f_type,
|
||||
lhs.rawValue.f_namemax == rhs.rawValue.f_namemax,
|
||||
lhs.rawValue.f_syncwrites == rhs.rawValue.f_syncwrites,
|
||||
lhs.rawValue.f_asyncwrites == rhs.rawValue.f_asyncwrites,
|
||||
lhs.rawValue.f_syncreads == rhs.rawValue.f_syncreads,
|
||||
lhs.rawValue.f_asyncreads == rhs.rawValue.f_asyncreads else {
|
||||
return false
|
||||
}
|
||||
#elseif os(OpenBSD)
|
||||
guard lhs.rawValue.f_favail == rhs.rawValue.f_favail,
|
||||
lhs.rawValue.f_namemax == rhs.rawValue.f_namemax,
|
||||
lhs.rawValue.f_syncwrites == rhs.rawValue.f_syncwrites,
|
||||
lhs.rawValue.f_syncreads == rhs.rawValue.f_syncreads,
|
||||
lhs.rawValue.f_asyncwrites == rhs.rawValue.f_asyncwrites,
|
||||
lhs.rawValue.f_asyncreads == rhs.rawValue.f_asyncreads,
|
||||
lhs.rawValue.f_ctime == rhs.rawValue.f_ctime,
|
||||
_nullTerminatedBytesEqual(lhs.rawValue.f_mntfromspec,
|
||||
rhs.rawValue.f_mntfromspec) else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/// Hashes the file system metadata fields of a `StatFS` struct.
|
||||
///
|
||||
/// These are the same fields compared by `==`. Reserved/"spare" fields are
|
||||
/// not hashed, and name buffers are hashed only up to their NUL terminators.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(rawValue.f_bsize)
|
||||
hasher.combine(rawValue.f_blocks)
|
||||
hasher.combine(rawValue.f_bfree)
|
||||
hasher.combine(rawValue.f_bavail)
|
||||
hasher.combine(rawValue.f_files)
|
||||
hasher.combine(rawValue.f_ffree)
|
||||
hasher.combine(fileSystemID)
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
hasher.combine(rawValue.f_iosize)
|
||||
hasher.combine(rawValue.f_flags)
|
||||
hasher.combine(rawValue.f_owner)
|
||||
Self._combineNullTerminatedBytes(rawValue.f_fstypename, into: &hasher)
|
||||
Self._combineNullTerminatedBytes(rawValue.f_mntonname, into: &hasher)
|
||||
Self._combineNullTerminatedBytes(rawValue.f_mntfromname, into: &hasher)
|
||||
#elseif os(Linux) || os(Android)
|
||||
hasher.combine(rawValue.f_type)
|
||||
hasher.combine(rawValue.f_frsize)
|
||||
hasher.combine(rawValue.f_flags)
|
||||
hasher.combine(rawValue.f_namelen)
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
hasher.combine(rawValue.f_type)
|
||||
hasher.combine(rawValue.f_fssubtype)
|
||||
hasher.combine(rawValue.f_flags_ext)
|
||||
#elseif os(FreeBSD)
|
||||
hasher.combine(rawValue.f_version)
|
||||
hasher.combine(rawValue.f_type)
|
||||
hasher.combine(rawValue.f_namemax)
|
||||
hasher.combine(rawValue.f_syncwrites)
|
||||
hasher.combine(rawValue.f_asyncwrites)
|
||||
hasher.combine(rawValue.f_syncreads)
|
||||
hasher.combine(rawValue.f_asyncreads)
|
||||
#elseif os(OpenBSD)
|
||||
hasher.combine(rawValue.f_favail)
|
||||
hasher.combine(rawValue.f_namemax)
|
||||
hasher.combine(rawValue.f_syncwrites)
|
||||
hasher.combine(rawValue.f_syncreads)
|
||||
hasher.combine(rawValue.f_asyncwrites)
|
||||
hasher.combine(rawValue.f_asyncreads)
|
||||
hasher.combine(rawValue.f_ctime)
|
||||
Self._combineNullTerminatedBytes(rawValue.f_mntfromspec, into: &hasher)
|
||||
#endif
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private static func _nullTerminatedBytesEqual<T>(_ lhs: T, _ rhs: T) -> Bool {
|
||||
withUnsafeBytes(of: lhs) { lhsBytes in
|
||||
withUnsafeBytes(of: rhs) { rhsBytes in
|
||||
lhsBytes.prefix { $0 != 0 }.elementsEqual(rhsBytes.prefix { $0 != 0 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds the length first so adjacent buffers can't run together.
|
||||
@inline(__always)
|
||||
private static func _combineNullTerminatedBytes<T>(
|
||||
_ value: T, into hasher: inout Hasher
|
||||
) {
|
||||
withUnsafeBytes(of: value) { buffer in
|
||||
let bytes = buffer.prefix { $0 != 0 }
|
||||
hasher.combine(bytes.count)
|
||||
hasher.combine(bytes: .init(rebasing: bytes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !os(Windows) && !os(WASI)
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
public import CSystemIOUring
|
||||
|
||||
public extension IORing {
|
||||
struct Completion: ~Copyable {
|
||||
@inlinable init(rawValue inRawValue: io_uring_cqe) {
|
||||
rawValue = inRawValue
|
||||
}
|
||||
@usableFromInline let rawValue: io_uring_cqe
|
||||
}
|
||||
}
|
||||
|
||||
public extension IORing.Completion {
|
||||
struct Flags: OptionSet, Hashable, Codable {
|
||||
public let rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
///`IORING_CQE_F_BUFFER` Indicates the buffer ID is stored in the upper 16 bits
|
||||
@inlinable public static var allocatedBuffer: Flags { Flags(rawValue: 1 << 0) }
|
||||
///`IORING_CQE_F_MORE` Indicates more completions will be generated from the request that generated this
|
||||
@inlinable public static var moreCompletions: Flags { Flags(rawValue: 1 << 1) }
|
||||
//`IORING_CQE_F_SOCK_NONEMPTY`, but currently unused
|
||||
//@inlinable public static var socketNotEmpty: Flags { Flags(rawValue: 1 << 2) }
|
||||
//`IORING_CQE_F_NOTIF`, but currently unused
|
||||
//@inlinable public static var isNotificationEvent: Flags { Flags(rawValue: 1 << 3) }
|
||||
//IORING_CQE_F_BUF_MORE will eventually be (1U << 4) if we add IOU_PBUF_RING_INC support
|
||||
}
|
||||
}
|
||||
|
||||
public extension IORing.Completion {
|
||||
@inlinable var context: UInt64 {
|
||||
get {
|
||||
rawValue.user_data
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var userPointer: UnsafeRawPointer? {
|
||||
get {
|
||||
UnsafeRawPointer(bitPattern: UInt(rawValue.user_data))
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of the completed operation.
|
||||
///
|
||||
/// A non-negative value is the operation's success result: a byte count
|
||||
/// for a read or a write, an event mask for a poll, and so on.
|
||||
///
|
||||
/// A negative value is an `errno` code multiplied by -1. Recover the error
|
||||
/// by negating it again: `Errno(rawValue: -completion.result)`, or use
|
||||
/// ``error``.
|
||||
@inlinable var result: Int32 {
|
||||
get {
|
||||
rawValue.res
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of the completed operation, or `nil` if the operation succeeded.
|
||||
@inlinable var error: Errno? {
|
||||
get {
|
||||
rawValue.res < 0 ? Errno(rawValue: -rawValue.res) : nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var flags: IORing.Completion.Flags {
|
||||
get {
|
||||
Flags(rawValue: rawValue.flags & 0x0000FFFF)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var bufferIndex: UInt16? {
|
||||
get {
|
||||
if self.flags.contains(.allocatedBuffer) {
|
||||
return UInt16(rawValue.flags >> 16)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,701 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
public import CSystemIOUring
|
||||
|
||||
@usableFromInline
|
||||
internal enum IORequestCore {
|
||||
case nop // nothing here
|
||||
case openat(
|
||||
atDirectory: FileDescriptor,
|
||||
path: FilePath,
|
||||
FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case openatSlot(
|
||||
atDirectory: FileDescriptor,
|
||||
path: FilePath,
|
||||
FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
intoSlot: IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case pollAdd(
|
||||
file: FileDescriptor,
|
||||
events: IORing.Request.PollEvents,
|
||||
isMultiShot: Bool = false,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case read(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case readUnregistered(
|
||||
file: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case readSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case readUnregisteredSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case write(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case writeUnregistered(
|
||||
file: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case writeSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case writeUnregisteredSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case close(
|
||||
FileDescriptor,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case closeSlot(
|
||||
IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case unlinkAt(
|
||||
atDirectory: FileDescriptor,
|
||||
path: FilePath,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case cancel(
|
||||
flags:UInt32
|
||||
)
|
||||
case cancelContext(
|
||||
flags: UInt32,
|
||||
targetContext: UInt64
|
||||
)
|
||||
case cancelFD(
|
||||
flags: UInt32,
|
||||
targetFD: FileDescriptor
|
||||
)
|
||||
case cancelFDSlot(
|
||||
flags: UInt32,
|
||||
target: IORing.RegisteredFile
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_registered(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.fileDescriptor = file
|
||||
request.buffer = buffer.unsafeBuffer
|
||||
request.rawValue.buf_index = UInt16(exactly: buffer.index)!
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_registered_slot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.rawValue.fd = Int32(exactly: file.index)!
|
||||
request.flags = .fixedFile
|
||||
request.buffer = buffer.unsafeBuffer
|
||||
request.rawValue.buf_index = UInt16(exactly: buffer.index)!
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_unregistered(
|
||||
file: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.fileDescriptor = file
|
||||
request.buffer = buffer
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_unregistered_slot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.rawValue.fd = Int32(exactly: file.index)!
|
||||
request.flags = .fixedFile
|
||||
request.buffer = buffer
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
extension IORing {
|
||||
public struct Request {
|
||||
@usableFromInline var core: IORequestCore
|
||||
|
||||
@inlinable internal init(core inCore: IORequestCore) {
|
||||
core = inCore
|
||||
}
|
||||
|
||||
@inlinable internal consuming func extractCore() -> IORequestCore {
|
||||
return core
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
extension IORing.Request {
|
||||
@inlinable public static func nop(context: UInt64 = 0) -> IORing.Request {
|
||||
.init(core: .nop)
|
||||
}
|
||||
|
||||
// Poll
|
||||
|
||||
/// Multishot poll: the poll handler continues to report CQEs on behalf
|
||||
/// of the same SQE, each flagged with
|
||||
/// ``IORing/Completion/Flags/moreCompletions``.
|
||||
///
|
||||
/// Corresponds to `IORING_POLL_ADD_MULTI`. Note that since
|
||||
/// `sqe->poll_events` is the event space, the command flags for
|
||||
/// `POLL_ADD` are stored in `sqe->len`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_POLL_ADD_MULTI: UInt32 { 1 << 0 }
|
||||
|
||||
/// Adds a poll operation to monitor a file descriptor for specific I/O
|
||||
/// events.
|
||||
///
|
||||
/// This method creates an `io_uring` poll operation that monitors the
|
||||
/// specified file descriptor for I/O readiness events. The operation
|
||||
/// completes when any of the requested events occur on the file
|
||||
/// descriptor, such as data becoming available for reading or the
|
||||
/// descriptor becoming ready for writing.
|
||||
///
|
||||
/// Poll operations are useful for implementing efficient I/O
|
||||
/// multiplexing, allowing you to monitor multiple file descriptors
|
||||
/// concurrently within a single `io_uring` instance. When used with
|
||||
/// multishot mode, a single poll operation can deliver multiple
|
||||
/// completion events without needing to be resubmitted.
|
||||
///
|
||||
/// Poll requests on a ring created with
|
||||
/// ``IORing/SetupFlags/pollCompletions`` fail with
|
||||
/// ``Errno/invalidArgument``.
|
||||
///
|
||||
/// ## Multishot Behavior
|
||||
///
|
||||
/// When `isMultiShot` is `true`, the poll operation automatically rearms
|
||||
/// after each completion event, continuing to monitor the file descriptor
|
||||
/// for subsequent events. This reduces submission overhead for long-lived
|
||||
/// monitoring operations. The poll stays armed until it's canceled or the
|
||||
/// kernel ends it; its last completion is the one without
|
||||
/// ``IORing/Completion/Flags/moreCompletions``. Neither a hangup nor
|
||||
/// closing the descriptor ends the poll, and the request keeps the file
|
||||
/// open until the poll ends.
|
||||
///
|
||||
/// When `isMultiShot` is `false`, the poll operation completes once after
|
||||
/// the first matching event occurs, requiring resubmission to continue
|
||||
/// monitoring.
|
||||
///
|
||||
/// ## Example Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// // Monitor a socket for incoming connections
|
||||
/// var ring = try IORing(queueDepth: 32)
|
||||
/// let pollRequest = IORing.Request.pollAdd(
|
||||
/// listenSocket,
|
||||
/// events: .readable,
|
||||
/// isMultiShot: true,
|
||||
/// context: 1
|
||||
/// )
|
||||
/// guard try ring.submit(linkedRequests: pollRequest) else {
|
||||
/// // The submission queue was full; retry or drain completions first.
|
||||
/// return
|
||||
/// }
|
||||
///
|
||||
/// // Process completions. A multishot poll stays armed while its
|
||||
/// // completions contain `.moreCompletions`.
|
||||
/// var armed = true
|
||||
/// while armed {
|
||||
/// let completion = try ring.blockingConsumeCompletion()
|
||||
/// guard completion.context == 1 else {
|
||||
/// // Handle completions for other requests.
|
||||
/// continue
|
||||
/// }
|
||||
/// armed = completion.flags.contains(.moreCompletions)
|
||||
/// if let error = completion.error {
|
||||
/// // The poll ended with an error, such as `.canceled`.
|
||||
/// throw error
|
||||
/// }
|
||||
/// // Handle incoming connection
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If the poll ends with an error, such as ``Errno/canceled``, its last
|
||||
/// completion carries that error in ``IORing/Completion/error`` and
|
||||
/// doesn't contain `.moreCompletions`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - file: The file descriptor to monitor for I/O events.
|
||||
/// - events: The I/O events to monitor on the file descriptor.
|
||||
/// - isMultiShot: If `true`, the poll operation automatically rearms
|
||||
/// after each event, continuing to monitor the file descriptor. If
|
||||
/// `false`, the operation completes after the first matching event.
|
||||
/// Defaults to `false`.
|
||||
/// - context: An application-specific value passed through to the
|
||||
/// completion event, allowing you to identify which operation
|
||||
/// completed. Defaults to `0`.
|
||||
///
|
||||
/// - Returns: An I/O ring request that monitors the file descriptor for
|
||||
/// the specified events.
|
||||
///
|
||||
/// ## See Also
|
||||
///
|
||||
/// - ``PollEvents``: The events that can be monitored.
|
||||
/// - ``IORing/Request/cancel(_:matching:)-(_,FileDescriptor)``:
|
||||
/// Canceling poll operations.
|
||||
@inlinable public static func pollAdd(
|
||||
_ file: FileDescriptor,
|
||||
events: PollEvents,
|
||||
isMultiShot: Bool = false,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .pollAdd(file: file, events: events, isMultiShot: isMultiShot, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: IORing.RegisteredFile,
|
||||
into buffer: IORing.RegisteredBuffer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: FileDescriptor,
|
||||
into buffer: IORing.RegisteredBuffer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .read(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: IORing.RegisteredFile,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: FileDescriptor,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func write(
|
||||
_ buffer: IORing.RegisteredBuffer,
|
||||
into file: IORing.RegisteredFile,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func write(
|
||||
_ buffer: IORing.RegisteredBuffer,
|
||||
into file: FileDescriptor,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .write(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use the overload accepting UnsafeRawBufferPointer instead.")
|
||||
@_disfavoredOverload
|
||||
@inlinable public static func write(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
into file: IORing.RegisteredFile,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .writeUnregisteredSlot(
|
||||
file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use the overload accepting UnsafeRawBufferPointer instead.")
|
||||
@_disfavoredOverload
|
||||
@inlinable public static func write(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
into file: FileDescriptor,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(
|
||||
core: .writeUnregistered(file: file, buffer: buffer, offset: offset, context: context)
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a request to write an unregistered buffer to a registered file.
|
||||
///
|
||||
/// The request does not copy the buffer's contents. Keep its storage alive
|
||||
/// and unchanged until the operation completes. The write only reads from
|
||||
/// the buffer; it does not modify its contents.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The bytes to write.
|
||||
/// - file: The registered file to write to.
|
||||
/// - offset: The byte offset in the file at which to begin writing.
|
||||
/// Ignored for non-seekable files. Defaults to `0`.
|
||||
/// - context: An application-specific value passed through to the
|
||||
/// completion event. Defaults to `0`.
|
||||
/// - Returns: An I/O ring write request. A successful completion's result
|
||||
/// is the number of bytes written, which may be less than the buffer's count.
|
||||
@inlinable public static func write(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
into file: IORing.RegisteredFile,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
// The shared request encoder uses a mutable pointer, but writes only read the buffer.
|
||||
.init(core: .writeUnregisteredSlot(
|
||||
file: file, buffer: UnsafeMutableRawBufferPointer(mutating: buffer), offset: offset, context: context
|
||||
))
|
||||
}
|
||||
|
||||
/// Creates a request to write an unregistered buffer to a file descriptor.
|
||||
///
|
||||
/// The request does not copy the buffer's contents. Keep its storage alive
|
||||
/// and unchanged until the operation completes. The write only reads from
|
||||
/// the buffer; it does not modify its contents.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The bytes to write.
|
||||
/// - file: The file descriptor to write to.
|
||||
/// - offset: The byte offset in the file at which to begin writing.
|
||||
/// Ignored for non-seekable files. Defaults to `0`.
|
||||
/// - context: An application-specific value passed through to the
|
||||
/// completion event. Defaults to `0`.
|
||||
/// - Returns: An I/O ring write request. A successful completion's result
|
||||
/// is the number of bytes written, which may be less than the buffer's count.
|
||||
@inlinable public static func write(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
into file: FileDescriptor,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
// The shared request encoder uses a mutable pointer, but writes only read the buffer.
|
||||
.init(core: .writeUnregistered(
|
||||
file: file, buffer: UnsafeMutableRawBufferPointer(mutating: buffer), offset: offset, context: context
|
||||
))
|
||||
}
|
||||
|
||||
@inlinable public static func close(
|
||||
_ file: FileDescriptor,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .close(file, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func close(
|
||||
_ file: IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .closeSlot(file, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func open(
|
||||
_ path: FilePath,
|
||||
in directory: FileDescriptor,
|
||||
into slot: IORing.RegisteredFile,
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(
|
||||
core: .openatSlot(
|
||||
atDirectory: directory, path: path, mode, options: options,
|
||||
permissions: permissions, intoSlot: slot, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func open(
|
||||
_ path: FilePath,
|
||||
in directory: FileDescriptor,
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(
|
||||
core: .openat(
|
||||
atDirectory: directory, path: path, mode, options: options,
|
||||
permissions: permissions, context: context
|
||||
))
|
||||
}
|
||||
|
||||
@inlinable public static func unlink(
|
||||
_ path: FilePath,
|
||||
in directory: FileDescriptor,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .unlinkAt(atDirectory: directory, path: path, context: context))
|
||||
}
|
||||
|
||||
// Cancel
|
||||
|
||||
/// Cancel every request matching the given key.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_ALL`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 }
|
||||
|
||||
/// Cancel any request matching the given file descriptor.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_FD`. Cannot be combined with
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_ANY``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 }
|
||||
|
||||
/// Cancel any matching request, disregarding every other key.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_ANY`. Cannot be combined with
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_FD`` or ``SWIFT_IORING_ASYNC_CANCEL_OP``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 }
|
||||
|
||||
/// Cancel any request matching a registered file.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_FD_FIXED`, and accompanies
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_FD``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 }
|
||||
|
||||
/// Cancel requests matching the `user_data`. This is the default when no other
|
||||
/// key is given.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_USERDATA`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 }
|
||||
|
||||
/// Cancel requests matching the operation.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_OP`. Cannot be combined with
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_ANY``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 }
|
||||
|
||||
public enum CancellationMatch {
|
||||
case all
|
||||
case first
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
matchingContext: UInt64
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext))
|
||||
case .first:
|
||||
.init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
matching: FileDescriptor
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching))
|
||||
case .first:
|
||||
.init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
matching: IORing.RegisteredFile
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching))
|
||||
case .first:
|
||||
.init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ALL))
|
||||
case .first:
|
||||
.init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ANY))
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal consuming func makeRawRequest(
|
||||
pathBuffers: PendingPathBuffers
|
||||
) -> RawIORequest {
|
||||
var request = RawIORequest()
|
||||
switch extractCore() {
|
||||
case .nop:
|
||||
request.operation = .nop
|
||||
case .openatSlot(
|
||||
let atDirectory, let path, let mode, let options, let permissions, let fileSlot,
|
||||
let context):
|
||||
// TODO: use rawValue less
|
||||
request.operation = .openAt
|
||||
request.fileDescriptor = atDirectory
|
||||
request.rawValue.addr = UInt64(
|
||||
UInt(bitPattern: pathBuffers.pin(path)))
|
||||
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
|
||||
request.rawValue.len = permissions?.rawValue ?? 0
|
||||
request.rawValue.file_index = UInt32(fileSlot.index + 1)
|
||||
request.rawValue.user_data = context
|
||||
case .openat(
|
||||
let atDirectory, let path, let mode, let options, let permissions, let context):
|
||||
request.operation = .openAt
|
||||
request.fileDescriptor = atDirectory
|
||||
request.rawValue.addr = UInt64(
|
||||
UInt(bitPattern: pathBuffers.pin(path)))
|
||||
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
|
||||
request.rawValue.len = permissions?.rawValue ?? 0
|
||||
request.rawValue.user_data = context
|
||||
case .write(let file, let buffer, let offset, let context):
|
||||
request.operation = .writeFixed
|
||||
return makeRawRequest_readWrite_registered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .writeSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .writeFixed
|
||||
return makeRawRequest_readWrite_registered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .writeUnregistered(let file, let buffer, let offset, let context):
|
||||
request.operation = .write
|
||||
return makeRawRequest_readWrite_unregistered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .writeUnregisteredSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .write
|
||||
return makeRawRequest_readWrite_unregistered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .read(let file, let buffer, let offset, let context):
|
||||
request.operation = .readFixed
|
||||
return makeRawRequest_readWrite_registered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .readSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .readFixed
|
||||
return makeRawRequest_readWrite_registered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .readUnregistered(let file, let buffer, let offset, let context):
|
||||
request.operation = .read
|
||||
return makeRawRequest_readWrite_unregistered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .readUnregisteredSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .read
|
||||
return makeRawRequest_readWrite_unregistered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .close(let file, let context):
|
||||
request.operation = .close
|
||||
request.fileDescriptor = file
|
||||
request.rawValue.user_data = context
|
||||
case .closeSlot(let file, let context):
|
||||
request.operation = .close
|
||||
request.rawValue.file_index = UInt32(file.index + 1)
|
||||
request.rawValue.user_data = context
|
||||
case .unlinkAt(let atDirectory, let path, let context):
|
||||
request.operation = .unlinkAt
|
||||
request.fileDescriptor = atDirectory
|
||||
request.rawValue.addr = UInt64(
|
||||
UInt(bitPattern: pathBuffers.pin(path)))
|
||||
request.rawValue.user_data = context
|
||||
case .cancelContext(let flags, let targetContext):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
request.addr = targetContext
|
||||
case .cancelFD(let flags, let targetFD):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
request.fileDescriptor = targetFD
|
||||
case .cancelFDSlot(let flags, let target):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
request.rawValue.fd = Int32(target.index)
|
||||
case .cancel(let flags):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
case .pollAdd(let file, let events, let isMultiShot, let context):
|
||||
request.operation = .pollAdd
|
||||
request.fileDescriptor = file
|
||||
request.rawValue.user_data = context
|
||||
if isMultiShot {
|
||||
request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI
|
||||
}
|
||||
request.pollEvents = events
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
internal import CSystem
|
||||
public import CSystemIOUring
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// Throwing wrapper around the `csystem_io_uring_enter2` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result (the number of SQEs
|
||||
/// consumed by the kernel). On failure, reads `errno` and throws the matching
|
||||
/// `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringEnter2(
|
||||
ringDescriptor: Int32,
|
||||
toSubmit: UInt32,
|
||||
minComplete: UInt32,
|
||||
flags: UInt32,
|
||||
args: UnsafeMutablePointer<swift_io_uring_getevents_arg>?,
|
||||
argsSize: Int
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
csystem_io_uring_enter2(
|
||||
ringDescriptor, toSubmit, minComplete, flags, args, argsSize
|
||||
)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `csystem_io_uring_enter` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result (the number of SQEs
|
||||
/// consumed by the kernel). On failure, reads `errno` and throws the matching
|
||||
/// `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringEnter(
|
||||
ringDescriptor: Int32,
|
||||
toSubmit: UInt32,
|
||||
minComplete: UInt32,
|
||||
flags: UInt32,
|
||||
sig: UnsafeMutablePointer<sigset_t>?
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
csystem_io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `csystem_io_uring_register` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result. On failure, reads
|
||||
/// `errno` and throws the matching `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringRegister(
|
||||
ringDescriptor: Int32,
|
||||
opcode: UInt32,
|
||||
arg: UnsafeMutableRawPointer?,
|
||||
nrArgs: UInt32
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
csystem_io_uring_register(ringDescriptor, opcode, arg, nrArgs)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,970 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
internal import CSystem
|
||||
public import CSystemIOUring
|
||||
// needed for mmap
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
import Synchronization
|
||||
|
||||
private var ioringSupported: Bool {
|
||||
__SWIFT_IORING_SUPPORTED != 0
|
||||
}
|
||||
|
||||
//This was #defines in older headers, so we redeclare it to get a consistent import
|
||||
internal enum RegistrationOps: UInt32 {
|
||||
case registerBuffers = 0
|
||||
case unregisterBuffers = 1
|
||||
case registerFiles = 2
|
||||
case unregisterFiles = 3
|
||||
case registerEventFD = 4
|
||||
case unregisterEventFD = 5
|
||||
case registerFilesUpdate = 6
|
||||
case registerEventFDAsync = 7
|
||||
case registerProbe = 8
|
||||
case registerPersonality = 9
|
||||
case unregisterPersonality = 10
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawPointer {
|
||||
func advanced(by offset: UInt32) -> UnsafeMutableRawPointer {
|
||||
return advanced(by: Int(offset))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer {
|
||||
func to_iovec() -> iovec {
|
||||
iovec(iov_base: baseAddress, iov_len: count)
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the FilePaths whose interior pointers have been written into pending
|
||||
/// SQEs. The kernel copies SQE-referenced data out during `io_uring_enter` (due to
|
||||
/// `IORING_FEAT_SUBMIT_STABLE`), so the paths only need to live across the prepare->submit gap
|
||||
/// This is a class purely to avoid making methods calling `pin` mutating, which would be an API break
|
||||
@usableFromInline
|
||||
internal final class PendingPathBuffers {
|
||||
@usableFromInline
|
||||
var paths: [FilePath] = []
|
||||
|
||||
init(reservedCapacity: Int) {
|
||||
paths.reserveCapacity(reservedCapacity)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func pin(_ path: FilePath) -> UnsafePointer<CInterop.PlatformChar> {
|
||||
paths.append(path)
|
||||
// Safe to escape: `paths` keeps the FilePath (and its underlying
|
||||
// [SystemChar] buffer) alive until clear() or class deinit.
|
||||
return paths.last!.withPlatformString { $0 }
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func clear() {
|
||||
paths.removeAll(keepingCapacity: true)
|
||||
}
|
||||
}
|
||||
|
||||
// all pointers in this struct reference kernel-visible memory
|
||||
@usableFromInline struct SQRing: ~Copyable {
|
||||
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
|
||||
@usableFromInline let kernelTail: UnsafePointer<Atomic<UInt32>>
|
||||
@usableFromInline var userTail: UInt32
|
||||
|
||||
// from liburing: the kernel should never change these
|
||||
// might change in the future with resizable rings?
|
||||
@usableFromInline let ringMask: UInt32
|
||||
// let ringEntries: UInt32 - absorbed into array.count
|
||||
|
||||
// ring flags bitfield
|
||||
// currently used by the kernel only in SQPOLL mode to indicate
|
||||
// when the polling thread needs to be woken up
|
||||
@usableFromInline let flags: UnsafePointer<Atomic<UInt32>>
|
||||
|
||||
// ring array
|
||||
// maps indexes between the actual ring and the submissionQueueEntries list,
|
||||
// allowing the latter to be used as a kind of freelist with enough work?
|
||||
// currently, just 1:1 mapping (0..<n)
|
||||
@usableFromInline let array: UnsafeMutableBufferPointer<UInt32>
|
||||
}
|
||||
|
||||
@usableFromInline struct CQRing: ~Copyable {
|
||||
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
|
||||
@usableFromInline let kernelTail: UnsafePointer<Atomic<UInt32>>
|
||||
|
||||
@usableFromInline let ringMask: UInt32
|
||||
|
||||
@usableFromInline let cqes: UnsafeBufferPointer<io_uring_cqe>
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func _tryWriteRequest(
|
||||
_ request: __owned RawIORequest, ring: inout SQRing,
|
||||
submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
if let entry = _getSubmissionEntry(
|
||||
ring: &ring, submissionQueueEntries: submissionQueueEntries) {
|
||||
entry.pointee = request.rawValue
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//TODO: omitting signal mask for now
|
||||
//Tell the kernel that we've submitted requests and/or are waiting for completions
|
||||
@inlinable
|
||||
internal func _enter(
|
||||
ring: borrowing SQRing,
|
||||
ringDescriptor: Int32,
|
||||
numEvents: UInt32,
|
||||
minCompletions: UInt32,
|
||||
flags: UInt32
|
||||
) throws(Errno) -> Int32 {
|
||||
// Ring always needs enter right now;
|
||||
// TODO: support SQPOLL here
|
||||
while true {
|
||||
do {
|
||||
let ret = try _ioUringEnter(
|
||||
ringDescriptor: ringDescriptor,
|
||||
toSubmit: numEvents,
|
||||
minComplete: minCompletions,
|
||||
flags: flags,
|
||||
sig: nil
|
||||
)
|
||||
if _getSubmissionQueueCount(ring: ring) > 0 {
|
||||
// See https://github.com/axboe/liburing/issues/309,
|
||||
// in some cases not all pending requests are submitted
|
||||
continue
|
||||
}
|
||||
return ret
|
||||
// error handling:
|
||||
// EAGAIN (try again),
|
||||
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
|
||||
// (failure in ring lifetime management, fatal),
|
||||
// EINVAL (bad constant flag?, fatal),
|
||||
// EFAULT (bad address for argument from library, fatal)
|
||||
} catch Errno.resourceTemporarilyUnavailable {
|
||||
//TODO: should we wait a bit on AGAIN?
|
||||
//alternatively we could treat EAGAIN the same as EINTR in the wrapper
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(Errno) {
|
||||
let flushedEvents = _flushQueue(ring: ring)
|
||||
_ = try _enter(
|
||||
ring: ring, ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getSubmissionQueueCount(ring: borrowing SQRing) -> UInt32 {
|
||||
return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getRemainingSubmissionQueueCapacity(ring: borrowing SQRing) -> UInt32 {
|
||||
return UInt32(truncatingIfNeeded: ring.array.count) - _getSubmissionQueueCount(ring: ring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getUnconsumedCompletionCount(ring: borrowing CQRing) -> UInt32 {
|
||||
return ring.kernelTail.pointee.load(ordering: .acquiring)
|
||||
- ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _flushQueue(ring: borrowing SQRing) -> UInt32 {
|
||||
ring.kernelTail.pointee.store(
|
||||
ring.userTail, ordering: .releasing
|
||||
)
|
||||
return _getSubmissionQueueCount(ring: ring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getSubmissionEntry(
|
||||
ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
|
||||
) -> UnsafeMutablePointer<
|
||||
swift_io_uring_sqe
|
||||
>? {
|
||||
let next = ring.userTail &+ 1 //this is expected to wrap
|
||||
|
||||
let kernelHead: UInt32 = ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
|
||||
// FEAT: 128-bit event support (not in MVP)
|
||||
if next - kernelHead <= ring.array.count {
|
||||
// let sqe = &sq->sqes[(sq->sqe_tail & sq->ring_mask) << shift];
|
||||
let sqeIndex = Int(
|
||||
ring.userTail & ring.ringMask
|
||||
)
|
||||
|
||||
let sqe = submissionQueueEntries
|
||||
.baseAddress.unsafelyUnwrapped
|
||||
.advanced(by: sqeIndex)
|
||||
|
||||
ring.userTail = next
|
||||
return sqe
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func setUpRing(
|
||||
queueDepth: UInt32, flags: IORing.SetupFlags
|
||||
) throws(Errno) ->
|
||||
(params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer?, ringSize: Int, submissionRingPtr: UnsafeMutableRawPointer?, submissionRingSize: Int, completionRingPtr: UnsafeMutableRawPointer?, completionRingSize: Int, sqes: UnsafeMutableRawPointer) {
|
||||
var params = io_uring_params()
|
||||
params.flags = flags.rawValue
|
||||
|
||||
var err: Errno? = nil
|
||||
let ringDescriptor = withUnsafeMutablePointer(to: ¶ms) {
|
||||
let result = csystem_io_uring_setup(queueDepth, $0)
|
||||
if result < 0 {
|
||||
err = Errno.current
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
if let err {
|
||||
throw err
|
||||
}
|
||||
|
||||
// We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced
|
||||
// pathnames (and other inline data) out of userspace before io_uring_enter
|
||||
// returns; the path-buffer side store on IORing relies on this to free
|
||||
// path buffers as soon as a submission completes.
|
||||
let requiredFeatures =
|
||||
IORing.Features.nonDroppingCompletions.rawValue
|
||||
| IORing.Features.stableSubmissions.rawValue
|
||||
if params.features & requiredFeatures != requiredFeatures
|
||||
{
|
||||
close(ringDescriptor)
|
||||
throw Errno.invalidArgument
|
||||
}
|
||||
|
||||
let submitRingSize =
|
||||
params.sq_off.array
|
||||
+ params.sq_entries * UInt32(MemoryLayout<UInt32>.size)
|
||||
|
||||
let completionRingSize =
|
||||
params.cq_off.cqes
|
||||
+ params.cq_entries * UInt32(MemoryLayout<io_uring_cqe>.size)
|
||||
|
||||
let ringSize = Int(max(submitRingSize, completionRingSize))
|
||||
|
||||
var ringPtr: UnsafeMutableRawPointer!
|
||||
var sqPtr: UnsafeMutableRawPointer!
|
||||
var cqPtr: UnsafeMutableRawPointer!
|
||||
|
||||
if params.features & IORING_FEAT_SINGLE_MMAP != 0{
|
||||
ringPtr = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ ringSize,
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_SQ_RING)
|
||||
)
|
||||
|
||||
if ringPtr == MAP_FAILED {
|
||||
let errno = Errno.current
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
} else {
|
||||
sqPtr = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ Int(submitRingSize),
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_SQ_RING)
|
||||
)
|
||||
|
||||
if sqPtr == MAP_FAILED {
|
||||
let errno = Errno.current
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
|
||||
cqPtr = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ Int(completionRingSize),
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_CQ_RING)
|
||||
)
|
||||
|
||||
if cqPtr == MAP_FAILED {
|
||||
let errno: Errno = Errno.current
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
}
|
||||
|
||||
// map the submission queue
|
||||
let sqes = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ Int(params.sq_entries) * MemoryLayout<swift_io_uring_sqe>.size,
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_SQES)
|
||||
)
|
||||
|
||||
if sqes == MAP_FAILED {
|
||||
let errno = Errno.current
|
||||
if ringPtr != nil {
|
||||
munmap(ringPtr, ringSize)
|
||||
} else {
|
||||
if sqPtr != nil {
|
||||
munmap(sqPtr, Int(submitRingSize))
|
||||
}
|
||||
if cqPtr != nil {
|
||||
munmap(cqPtr, Int(completionRingSize))
|
||||
}
|
||||
}
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
|
||||
return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr, ringSize: ringSize, submissionRingPtr: sqPtr, submissionRingSize: Int(submitRingSize), completionRingPtr: cqPtr, completionRingSize: Int(completionRingSize), sqes: sqes!)
|
||||
}
|
||||
|
||||
///IORing provides facilities for
|
||||
/// * Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file IOdescriptors that improves their efficiency
|
||||
/// * Registering and unregistering eventfds, which allow asynchronous waiting for completions
|
||||
/// * Enqueueing IO requests
|
||||
/// * Dequeueing IO completions
|
||||
public struct IORing: ~Copyable {
|
||||
let ringFlags: UInt32
|
||||
@usableFromInline let ringDescriptor: Int32
|
||||
|
||||
@usableFromInline var submissionRing: SQRing
|
||||
// FEAT: set this eventually
|
||||
let submissionPolling: Bool = false
|
||||
|
||||
@usableFromInline let completionRing: CQRing
|
||||
|
||||
@usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
|
||||
|
||||
// kept around for unmap / cleanup. TODO: we can save a few words of memory by figuring out how to handle cleanup for non-IORING_FEAT_SINGLE_MMAP better
|
||||
let ringSize: Int
|
||||
let ringPtr: UnsafeMutableRawPointer?
|
||||
let submissionRingSize: Int
|
||||
let submissionRingPtr: UnsafeMutableRawPointer?
|
||||
let completionRingSize: Int
|
||||
let completionRingPtr: UnsafeMutableRawPointer?
|
||||
|
||||
@usableFromInline var _registeredFiles: [UInt32]
|
||||
@usableFromInline var _registeredBuffers: [iovec]
|
||||
|
||||
@usableFromInline let _pendingPathBuffers: PendingPathBuffers
|
||||
|
||||
var features = Features(rawValue: 0)
|
||||
|
||||
/// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them.
|
||||
public struct RegisteredResource<T> {
|
||||
public typealias Resource = T
|
||||
@usableFromInline let resource: T
|
||||
public let index: Int
|
||||
|
||||
@inlinable internal init(
|
||||
resource: T,
|
||||
index: Int
|
||||
) {
|
||||
self.resource = resource
|
||||
self.index = index
|
||||
}
|
||||
}
|
||||
|
||||
public typealias RegisteredFile = RegisteredResource<UInt32>
|
||||
public typealias RegisteredBuffer = RegisteredResource<iovec>
|
||||
|
||||
/// SetupFlags represents configuration options to an IORing as it's being created
|
||||
public struct SetupFlags: OptionSet, RawRepresentable, Hashable {
|
||||
public var rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
@inlinable public static var pollCompletions: SetupFlags { .init(rawValue: UInt32(1) << 0) } //IORING_SETUP_IOPOLL
|
||||
@inlinable public static var pollSubmissions: SetupFlags { .init(rawValue: UInt32(1) << 1) } //IORING_SETUP_SQPOLL
|
||||
//TODO: figure out how to expose IORING_SETUP_SQ_AFF, IORING_SETUP_CQSIZE, IORING_SETUP_ATTACH_WQ
|
||||
@inlinable public static var clampMaxEntries: SetupFlags { .init(rawValue: UInt32(1) << 4) } //IORING_SETUP_CLAMP
|
||||
@inlinable public static var startDisabled: SetupFlags { .init(rawValue: UInt32(1) << 6) } //IORING_SETUP_R_DISABLED
|
||||
@inlinable public static var continueSubmittingOnError: SetupFlags { .init(rawValue: UInt32(1) << 7) } //IORING_SETUP_SUBMIT_ALL
|
||||
//TODO: do we want to expose IORING_SETUP_COOP_TASKRUN and IORING_SETUP_TASKRUN_FLAG?
|
||||
//public static var runTasksCooperatively: SetupFlags { .init(rawValue: UInt32(1) << 8) } //IORING_SETUP_COOP_TASKRUN
|
||||
//TODO: can we even do different size sqe/cqe? It requires a kernel feature, but how do we convince swift to let the types be different sizes?
|
||||
//internal static var use128ByteSQEs: SetupFlags { .init(rawValue: UInt32(1) << 10) } //IORING_SETUP_SQE128
|
||||
//internal static var use32ByteCQEs: SetupFlags { .init(rawValue: UInt32(1) << 11) } //IORING_SETUP_CQE32
|
||||
@inlinable public static var singleSubmissionThread: SetupFlags { .init(rawValue: UInt32(1) << 12) } //IORING_SETUP_SINGLE_ISSUER
|
||||
@inlinable public static var deferRunningTasks: SetupFlags { .init(rawValue: UInt32(1) << 13) } //IORING_SETUP_DEFER_TASKRUN
|
||||
//pretty sure we don't want to expose IORING_SETUP_NO_MMAP or IORING_SETUP_REGISTERED_FD_ONLY currently
|
||||
//TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it?
|
||||
}
|
||||
|
||||
/// Initializes an IORing with enough space for `queueDepth` prepared requests and completed operations
|
||||
public init(queueDepth: UInt32, flags: SetupFlags = []) throws(Errno) {
|
||||
guard ioringSupported else {
|
||||
throw Errno.notSupported
|
||||
}
|
||||
|
||||
let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, tmpSQPtr, tmpSQSize, tmpCQPtr, tmpCQSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags)
|
||||
// All throws need to be before initializing ivars here to avoid
|
||||
// "error: conditional initialization or destruction of noncopyable types is not supported;
|
||||
// this variable must be consistently in an initialized or uninitialized state through every code path"
|
||||
|
||||
// Pre-compute values to avoid accessing partially initialized state
|
||||
let ringBasePtr = tmpRingPtr ?? tmpSQPtr!
|
||||
let completionBasePtr = tmpRingPtr ?? tmpCQPtr!
|
||||
|
||||
let submissionRing = SQRing(
|
||||
kernelHead: UnsafePointer<Atomic<UInt32>>(
|
||||
ringBasePtr.advanced(by: params.sq_off.head)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
kernelTail: UnsafePointer<Atomic<UInt32>>(
|
||||
ringBasePtr.advanced(by: params.sq_off.tail)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
userTail: 0, // no requests yet
|
||||
ringMask: ringBasePtr.advanced(by: params.sq_off.ring_mask)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee,
|
||||
flags: UnsafePointer<Atomic<UInt32>>(
|
||||
ringBasePtr.advanced(by: params.sq_off.flags)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
array: UnsafeMutableBufferPointer(
|
||||
start: ringBasePtr.advanced(by: params.sq_off.array)
|
||||
.assumingMemoryBound(to: UInt32.self),
|
||||
count: Int(
|
||||
ringBasePtr.advanced(by: params.sq_off.ring_entries)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee)
|
||||
)
|
||||
)
|
||||
|
||||
let completionRing = CQRing(
|
||||
kernelHead: UnsafePointer<Atomic<UInt32>>(
|
||||
completionBasePtr.advanced(by: params.cq_off.head)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
kernelTail: UnsafePointer<Atomic<UInt32>>(
|
||||
completionBasePtr.advanced(by: params.cq_off.tail)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
ringMask: completionBasePtr.advanced(by: params.cq_off.ring_mask)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee,
|
||||
cqes: UnsafeBufferPointer(
|
||||
start: completionBasePtr.advanced(by: params.cq_off.cqes)
|
||||
.assumingMemoryBound(to: io_uring_cqe.self),
|
||||
count: Int(
|
||||
completionBasePtr.advanced(by: params.cq_off.ring_entries)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee)
|
||||
)
|
||||
)
|
||||
|
||||
let submissionQueueEntries = UnsafeMutableBufferPointer(
|
||||
start: sqes.assumingMemoryBound(to: swift_io_uring_sqe.self),
|
||||
count: Int(params.sq_entries)
|
||||
)
|
||||
|
||||
// Now initialize all stored properties
|
||||
self.features = Features(rawValue: params.features)
|
||||
self.ringDescriptor = tmpRingDescriptor
|
||||
self.ringPtr = tmpRingPtr
|
||||
self.ringSize = tmpRingSize
|
||||
self.submissionRingPtr = tmpSQPtr
|
||||
self.submissionRingSize = tmpSQSize
|
||||
self.completionRingPtr = tmpCQPtr
|
||||
self.completionRingSize = tmpCQSize
|
||||
self._registeredFiles = []
|
||||
self._registeredBuffers = []
|
||||
self._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries))
|
||||
self.submissionRing = submissionRing
|
||||
self.completionRing = completionRing
|
||||
self.submissionQueueEntries = submissionQueueEntries
|
||||
self.ringFlags = params.flags
|
||||
|
||||
// fill submission ring array with 1:1 map to underlying SQEs
|
||||
// (happens after all properties are initialized)
|
||||
for i in 0 ..< self.submissionRing.array.count {
|
||||
self.submissionRing.array[i] = UInt32(i)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _blockingConsumeCompletionGuts<Err: Error>(
|
||||
minimumCount: UInt32,
|
||||
maximumCount: UInt32,
|
||||
extraArgs: UnsafeMutablePointer<swift_io_uring_getevents_arg>? = nil,
|
||||
consumer: (consuming IORing.Completion?, Errno?, Bool) throws(Err) -> Void
|
||||
) throws(Err) {
|
||||
var count = 0
|
||||
while let completion = _tryConsumeCompletion(ring: completionRing) {
|
||||
count += 1
|
||||
// We still return the completion for a failed operation so that the
|
||||
// caller can tell which request failed through its `context`.
|
||||
let error = completion.error
|
||||
try consumer(completion, error, false)
|
||||
if count == maximumCount {
|
||||
try consumer(nil, nil, true)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if count < minimumCount {
|
||||
while count < minimumCount {
|
||||
var sz = 0
|
||||
var flags = IORING_ENTER_GETEVENTS
|
||||
if extraArgs != nil {
|
||||
sz = MemoryLayout<swift_io_uring_getevents_arg>.size
|
||||
flags |= IORING_ENTER_EXT_ARG
|
||||
}
|
||||
do {
|
||||
_ = try _ioUringEnter2(
|
||||
ringDescriptor: ringDescriptor,
|
||||
toSubmit: 0,
|
||||
minComplete: minimumCount,
|
||||
flags: flags,
|
||||
args: extraArgs,
|
||||
argsSize: sz
|
||||
)
|
||||
break
|
||||
// error handling:
|
||||
// EAGAIN (try again),
|
||||
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
|
||||
// (failure in ring lifetime management, fatal),
|
||||
// EINVAL (bad constant flag?, fatal),
|
||||
// EFAULT (bad address for argument from library, fatal)
|
||||
// EBUSY (not enough space for events; implies events filled
|
||||
// by kernel between kernelTail load and now)
|
||||
// ETIME (timeout from extraArgs.ts elapsed before
|
||||
// minimumCount completions arrived)
|
||||
} catch Errno.resourceBusy {
|
||||
break
|
||||
} catch Errno.resourceTemporarilyUnavailable {
|
||||
continue
|
||||
} catch Errno.timeout {
|
||||
try consumer(nil, .timeout, true)
|
||||
return
|
||||
} catch {
|
||||
fatalError(
|
||||
"fatal error in receiving requests: "
|
||||
+ error.debugDescription
|
||||
)
|
||||
}
|
||||
}
|
||||
var count = 0
|
||||
while let completion = _tryConsumeCompletion(ring: completionRing) {
|
||||
count += 1
|
||||
let error = completion.error
|
||||
try consumer(completion, error, false)
|
||||
if count == maximumCount {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
try consumer(nil, nil, true)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _blockingConsumeOneCompletion(
|
||||
extraArgs: UnsafeMutablePointer<swift_io_uring_getevents_arg>? = nil
|
||||
) throws(Errno) -> Completion {
|
||||
var result: Completion? = nil
|
||||
try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) {
|
||||
(completion: consuming Completion?, error, done) throws(Errno) in
|
||||
if let completion {
|
||||
result = consume completion
|
||||
} else if let error {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return result.take()!
|
||||
}
|
||||
|
||||
/// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified)
|
||||
///
|
||||
/// The completion is returned even if its operation failed. Check
|
||||
/// ``IORing/Completion/error`` to find out whether it did, and
|
||||
/// ``IORing/Completion/context`` to find out which request it belongs to.
|
||||
///
|
||||
/// - Throws: An error of the ring itself, such as ``Errno/timeout`` when
|
||||
/// no operation completed within `timeout`.
|
||||
@inlinable
|
||||
public func blockingConsumeCompletion(
|
||||
timeout: Duration? = nil
|
||||
) throws(Errno) -> Completion {
|
||||
if let timeout {
|
||||
var ts = timespec(
|
||||
tv_sec: Int(timeout.components.seconds),
|
||||
tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> Completion in
|
||||
var args = swift_io_uring_getevents_arg(
|
||||
sigmask: 0,
|
||||
sigmask_sz: 0,
|
||||
min_wait_usec: 0,
|
||||
ts: UInt64(UInt(bitPattern: tsPtr))
|
||||
)
|
||||
return try _blockingConsumeOneCompletion(extraArgs: &args)
|
||||
}
|
||||
} else {
|
||||
return try _blockingConsumeOneCompletion()
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout`
|
||||
/// (or forever if not specified). For each completed operation found, `consumer` is called to handle
|
||||
/// processing it.
|
||||
///
|
||||
/// `consumer` receives a completion, an error, and whether consuming is done:
|
||||
/// - For each completed operation, it receives the completion. If the
|
||||
/// operation failed, it receives the operation's error alongside the
|
||||
/// completion.
|
||||
/// - If the ring itself fails, such as with ``Errno/timeout``, it receives
|
||||
/// the error without a completion.
|
||||
/// - Once consuming is done, it is called a final time with `done` set to `true`.
|
||||
@inlinable
|
||||
public func blockingConsumeCompletions<Err: Error>(
|
||||
minimumCount: UInt32 = 1,
|
||||
timeout: Duration? = nil,
|
||||
consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void
|
||||
) throws(Err) {
|
||||
if let timeout {
|
||||
var ts = timespec(
|
||||
tv_sec: Int(timeout.components.seconds),
|
||||
tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
try withUnsafePointer(to: &ts) { (tsPtr) throws(Err) in
|
||||
var args = swift_io_uring_getevents_arg(
|
||||
sigmask: 0,
|
||||
sigmask_sz: 0,
|
||||
min_wait_usec: 0,
|
||||
ts: UInt64(UInt(bitPattern: tsPtr))
|
||||
)
|
||||
try _blockingConsumeCompletionGuts(
|
||||
minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args,
|
||||
consumer: consumer)
|
||||
}
|
||||
} else {
|
||||
try _blockingConsumeCompletionGuts(
|
||||
minimumCount: minimumCount, maximumCount: UInt32.max, consumer: consumer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes a completed operation from the ring and returns it, if one is ready. Otherwise, returns nil.
|
||||
@inlinable
|
||||
public func tryConsumeCompletion() -> Completion? {
|
||||
return _tryConsumeCompletion(ring: completionRing)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func _tryConsumeCompletion(ring: borrowing CQRing) -> Completion? {
|
||||
let tail = ring.kernelTail.pointee.load(ordering: .acquiring)
|
||||
let head = ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
|
||||
if tail != head {
|
||||
// 32 byte copy - oh well
|
||||
let res = ring.cqes[Int(head & ring.ringMask)]
|
||||
ring.kernelHead.pointee.store(head &+ 1, ordering: .releasing)
|
||||
return Completion(rawValue: res)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information.
|
||||
public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) {
|
||||
var rawfd = descriptor.rawValue
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.registerEventFD.rawValue,
|
||||
arg: &rawfd,
|
||||
nrArgs: 1
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes a registered event file descriptor from the ring
|
||||
public mutating func unregisterEventFD() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterEventFD.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
}
|
||||
|
||||
/// Registers `count` files with the ring for later use in IO operations
|
||||
public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources<RegisteredFile.Resource> {
|
||||
precondition(_registeredFiles.isEmpty)
|
||||
precondition(count < UInt32.max)
|
||||
let files = [UInt32](repeating: UInt32.max, count: count)
|
||||
|
||||
try files.withUnsafeBufferPointer { bPtr throws(Errno) in
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.registerFiles.rawValue,
|
||||
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
|
||||
nrArgs: UInt32(truncatingIfNeeded: count)
|
||||
)
|
||||
}
|
||||
|
||||
_registeredFiles = files
|
||||
return registeredFileSlots
|
||||
}
|
||||
|
||||
/// Removes registered files from the ring
|
||||
public func unregisterFiles() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterFiles.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
}
|
||||
|
||||
/// Allows access to registered files by index
|
||||
@inlinable
|
||||
public var registeredFileSlots: RegisteredResources<RegisteredFile.Resource> {
|
||||
RegisteredResources(resources: _registeredFiles)
|
||||
}
|
||||
|
||||
/// Registers buffers with the ring for later use in IO operations
|
||||
public mutating func registerBuffers(_ buffers: some Collection<UnsafeMutableRawBufferPointer>) throws(Errno)
|
||||
-> RegisteredResources<RegisteredBuffer.Resource>
|
||||
{
|
||||
precondition(buffers.count < UInt32.max)
|
||||
precondition(_registeredBuffers.isEmpty)
|
||||
let iovecs = buffers.map { $0.to_iovec() }
|
||||
try iovecs.withUnsafeBufferPointer { bPtr throws(Errno) in
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.registerBuffers.rawValue,
|
||||
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
|
||||
nrArgs: UInt32(truncatingIfNeeded: buffers.count)
|
||||
)
|
||||
}
|
||||
|
||||
_registeredBuffers = iovecs
|
||||
return registeredBuffers
|
||||
}
|
||||
|
||||
/// Registers buffers with the ring for later use in IO operations
|
||||
@inlinable
|
||||
public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno)
|
||||
-> RegisteredResources<RegisteredBuffer.Resource>
|
||||
{
|
||||
try registerBuffers(buffers)
|
||||
}
|
||||
|
||||
/// A view of the registered files or buffers in a ring
|
||||
public struct RegisteredResources<T>: RandomAccessCollection {
|
||||
@usableFromInline let resources: [T]
|
||||
|
||||
@inlinable public var startIndex: Int { 0 }
|
||||
@inlinable public var endIndex: Int { resources.endIndex }
|
||||
@inlinable init(resources: [T]) {
|
||||
self.resources = resources
|
||||
}
|
||||
@inlinable public subscript(position: Int) -> RegisteredResource<T> {
|
||||
RegisteredResource(resource: resources[position], index: position)
|
||||
}
|
||||
@inlinable public subscript(position: UInt16) -> RegisteredResource<T> {
|
||||
RegisteredResource(resource: resources[Int(position)], index: Int(position))
|
||||
}
|
||||
}
|
||||
|
||||
/// Allows access to registered files by index
|
||||
@inlinable
|
||||
public var registeredBuffers: RegisteredResources<RegisteredBuffer.Resource> {
|
||||
RegisteredResources(resources: _registeredBuffers)
|
||||
}
|
||||
|
||||
public func unregisterBuffers() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterBuffers.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
}
|
||||
|
||||
/// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring.
|
||||
@inlinable
|
||||
public func submitPreparedRequests() throws(Errno) {
|
||||
try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor)
|
||||
// IORING_FEAT_SUBMIT_STABLE guarantees the kernel has copied any
|
||||
// SQE-referenced data (e.g. openat/unlinkAt pathnames) before
|
||||
// io_uring_enter returns; safe to release path storage now.
|
||||
_pendingPathBuffers.clear()
|
||||
}
|
||||
|
||||
/// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available.
|
||||
///
|
||||
/// `consumer` receives a completion, an error, and whether consuming is done:
|
||||
/// - For each completed operation, it receives the completion. If the
|
||||
/// operation failed, it receives the operation's error alongside the
|
||||
/// completion.
|
||||
/// - If submitting the requests or waiting for completions fails, such as
|
||||
/// with ``Errno/timeout``, it receives the error without a completion.
|
||||
/// - Once consuming is done, it is called a final time with `done` set to `true`.
|
||||
@inlinable
|
||||
public func submitPreparedRequestsAndConsumeCompletions<Err: Error>(
|
||||
minimumCount: UInt32 = 1,
|
||||
timeout: Duration? = nil,
|
||||
consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void
|
||||
) throws(Err) {
|
||||
//TODO: optimize this to one uring_enter
|
||||
do {
|
||||
try submitPreparedRequests()
|
||||
} catch (let e) {
|
||||
try consumer(nil, e, true)
|
||||
}
|
||||
try blockingConsumeCompletions(
|
||||
minimumCount: minimumCount,
|
||||
timeout: timeout,
|
||||
consumer: consumer
|
||||
)
|
||||
}
|
||||
|
||||
/// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request
|
||||
@inlinable
|
||||
public mutating func prepare(request: __owned Request) -> Bool {
|
||||
guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else {
|
||||
return false
|
||||
}
|
||||
var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers)
|
||||
let ok = _tryWriteRequest(
|
||||
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
|
||||
assert(ok)
|
||||
return ok
|
||||
}
|
||||
|
||||
/// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order.
|
||||
@inlinable
|
||||
mutating func prepare(linkedRequests: some BidirectionalCollection<Request>) -> Bool {
|
||||
guard linkedRequests.count > 0 else {
|
||||
return true
|
||||
}
|
||||
let freeSQECount = _getRemainingSubmissionQueueCapacity(ring: submissionRing)
|
||||
guard freeSQECount >= linkedRequests.count else {
|
||||
return false
|
||||
}
|
||||
let last = linkedRequests.last!
|
||||
var allAdded = true
|
||||
for req in linkedRequests.dropLast() {
|
||||
var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers)
|
||||
raw.linkToNextRequest()
|
||||
let successfullyAdded = _tryWriteRequest(
|
||||
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
|
||||
assert(successfullyAdded)
|
||||
allAdded = allAdded && successfullyAdded
|
||||
}
|
||||
let successfullyAdded = _tryWriteRequest(
|
||||
last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing,
|
||||
submissionQueueEntries: submissionQueueEntries)
|
||||
assert(successfullyAdded)
|
||||
return allAdded && successfullyAdded
|
||||
}
|
||||
|
||||
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
|
||||
@inlinable
|
||||
public mutating func prepare(linkedRequests: Request...) -> Bool {
|
||||
prepare(linkedRequests: linkedRequests)
|
||||
}
|
||||
|
||||
/// Prepares and submits a sequence of requests to the ring. Returns false if the submission queue doesn't have enough available space.
|
||||
@inlinable
|
||||
public mutating func submit(linkedRequests: Request...) throws(Errno) -> Bool {
|
||||
if !prepare(linkedRequests: linkedRequests) {
|
||||
return false
|
||||
}
|
||||
try submitPreparedRequests()
|
||||
return true
|
||||
}
|
||||
|
||||
/// Describes which `io_uring` features are supported by the kernel this program is running on
|
||||
public struct Features: OptionSet, RawRepresentable, Hashable {
|
||||
public let rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
//IORING_FEAT_SINGLE_MMAP is handled internally
|
||||
@inlinable public static var nonDroppingCompletions: Features { .init(rawValue: UInt32(1) << 1) } //IORING_FEAT_NODROP
|
||||
@inlinable public static var stableSubmissions: Features { .init(rawValue: UInt32(1) << 2) } //IORING_FEAT_SUBMIT_STABLE
|
||||
@inlinable public static var currentFilePosition: Features { .init(rawValue: UInt32(1) << 3) } //IORING_FEAT_RW_CUR_POS
|
||||
@inlinable public static var assumingTaskCredentials: Features { .init(rawValue: UInt32(1) << 4) } //IORING_FEAT_CUR_PERSONALITY
|
||||
@inlinable public static var fastPolling: Features { .init(rawValue: UInt32(1) << 5) } //IORING_FEAT_FAST_POLL
|
||||
@inlinable public static var epoll32BitFlags: Features { .init(rawValue: UInt32(1) << 6) } //IORING_FEAT_POLL_32BITS
|
||||
@inlinable public static var pollNonFixedFiles: Features { .init(rawValue: UInt32(1) << 7) } //IORING_FEAT_SQPOLL_NONFIXED
|
||||
@inlinable public static var extendedArguments: Features { .init(rawValue: UInt32(1) << 8) } //IORING_FEAT_EXT_ARG
|
||||
@inlinable public static var nativeWorkers: Features { .init(rawValue: UInt32(1) << 9) } //IORING_FEAT_NATIVE_WORKERS
|
||||
@inlinable public static var resourceTags: Features { .init(rawValue: UInt32(1) << 10) } //IORING_FEAT_RSRC_TAGS
|
||||
@inlinable public static var allowsSkippingSuccessfulCompletions: Features { .init(rawValue: UInt32(1) << 11) } //IORING_FEAT_CQE_SKIP
|
||||
@inlinable public static var improvedLinkedFiles: Features { .init(rawValue: UInt32(1) << 12) } //IORING_FEAT_LINKED_FILE
|
||||
@inlinable public static var registerRegisteredRings: Features { .init(rawValue: UInt32(1) << 13) } //IORING_FEAT_REG_REG_RING
|
||||
@inlinable public static var minimumTimeout: Features { .init(rawValue: UInt32(1) << 15) } //IORING_FEAT_MIN_TIMEOUT
|
||||
@inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE
|
||||
}
|
||||
|
||||
/// Describes which `io_uring` features are supported by the kernel this program is running on
|
||||
public var supportedFeatures: Features {
|
||||
return features
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let ringPtr {
|
||||
munmap(ringPtr, ringSize)
|
||||
} else if let submissionRingPtr, let completionRingPtr {
|
||||
munmap(submissionRingPtr, submissionRingSize)
|
||||
munmap(completionRingPtr, completionRingSize)
|
||||
}
|
||||
munmap(
|
||||
UnsafeMutableRawPointer(submissionQueueEntries.baseAddress!),
|
||||
submissionQueueEntries.count * MemoryLayout<swift_io_uring_sqe>.size
|
||||
)
|
||||
close(ringDescriptor)
|
||||
}
|
||||
}
|
||||
|
||||
extension IORing.RegisteredBuffer {
|
||||
@unsafe @inlinable public var unsafeBuffer: UnsafeMutableRawBufferPointer {
|
||||
return .init(start: resource.iov_base, count: resource.iov_len)
|
||||
}
|
||||
|
||||
@inlinable public var mutableBytes: MutableRawSpan {
|
||||
@_lifetime(&self)
|
||||
mutating get {
|
||||
let span = MutableRawSpan(_unsafeBytes: unsafeBuffer)
|
||||
return unsafe _overrideLifetime(span, mutating: &self)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public var bytes: RawSpan {
|
||||
let span = RawSpan(_unsafeBytes: UnsafeRawBufferPointer(unsafeBuffer))
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
extension IORing.Request {
|
||||
/// A set of I/O events that can be monitored on a file descriptor.
|
||||
///
|
||||
/// `PollEvents` represents the event mask used with `io_uring` poll
|
||||
/// operations to specify which I/O conditions to monitor on a file
|
||||
/// descriptor. These events correspond to the standard POSIX poll events
|
||||
/// defined in the kernel's `poll.h` header.
|
||||
///
|
||||
/// Use `PollEvents` with
|
||||
/// ``IORing/Request/pollAdd(_:events:isMultiShot:context:)`` to
|
||||
/// register interest in specific I/O events. The poll operation completes
|
||||
/// when any of the specified events become active on the file descriptor.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// // Monitor a socket for incoming data
|
||||
/// let request = IORing.Request.pollAdd(
|
||||
/// socketFD,
|
||||
/// events: .readable,
|
||||
/// isMultiShot: true
|
||||
/// )
|
||||
/// ```
|
||||
public struct PollEvents: OptionSet, Hashable, Codable {
|
||||
public let rawValue: UInt32
|
||||
|
||||
@inlinable
|
||||
public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
init(_ event: Event) {
|
||||
self.rawValue = event.rawValue
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum Event: UInt32, RawRepresentable, Hashable, CaseIterable {
|
||||
case readable = 0x0001
|
||||
case priorityData = 0x0002
|
||||
case writable = 0x0004
|
||||
case error = 0x0008
|
||||
case hangUp = 0x0010
|
||||
case invalidDescriptor = 0x0020
|
||||
case peerClosed = 0x2000
|
||||
}
|
||||
|
||||
/// An event indicating data is available for reading.
|
||||
///
|
||||
/// This event becomes active when data arrives on the file descriptor
|
||||
/// and can be read without blocking. For sockets, this includes when
|
||||
/// a new connection is available on a listening socket. Corresponds
|
||||
/// to the POSIX `POLLIN` event flag.
|
||||
@inlinable
|
||||
public static var readable: PollEvents { PollEvents(.readable) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "readable")
|
||||
public static var POLLIN: PollEvents { readable }
|
||||
|
||||
/// An event indicating out-of-band data is available for reading.
|
||||
///
|
||||
/// For sockets this signals urgent data; it is also used to report
|
||||
/// exceptional conditions on descriptors that have no other way to
|
||||
/// signal them, such as a `sysfs` attribute that has changed value.
|
||||
/// Corresponds to the POSIX `POLLPRI` event flag.
|
||||
@inlinable
|
||||
public static var priorityData: PollEvents { PollEvents(.priorityData) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "priorityData")
|
||||
public static var POLLPRI: PollEvents { priorityData }
|
||||
|
||||
/// An event indicating the file descriptor is ready for writing.
|
||||
///
|
||||
/// This event becomes active when writing to the file descriptor will
|
||||
/// not block. For sockets, this indicates that send buffer space is
|
||||
/// available. Corresponds to the POSIX `POLLOUT` event flag.
|
||||
@inlinable
|
||||
public static var writable: PollEvents { PollEvents(.writable) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "writable")
|
||||
public static var POLLOUT: PollEvents { writable }
|
||||
|
||||
/// An event indicating an error condition on the file descriptor.
|
||||
///
|
||||
/// The kernel reports this event whether or not it was requested, so
|
||||
/// it can appear in a completion's result mask even when the poll
|
||||
/// asked only for ``readable`` or ``writable``. Requesting it
|
||||
/// explicitly has no effect. Corresponds to the POSIX `POLLERR` event
|
||||
/// flag.
|
||||
@inlinable
|
||||
public static var error: PollEvents { PollEvents(.error) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "error")
|
||||
public static var POLLERR: PollEvents { error }
|
||||
|
||||
/// An event indicating the peer closed its end of the channel.
|
||||
///
|
||||
/// For a pipe this means the writing end was closed; for a socket, that
|
||||
/// the connection was shut down.
|
||||
///
|
||||
/// The kernel reports this event whether or not it was requested, and
|
||||
/// requesting it explicitly has no effect. Corresponds to the POSIX
|
||||
/// `POLLHUP` event flag.
|
||||
@inlinable
|
||||
public static var hangUp: PollEvents { PollEvents(.hangUp) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "hangUp")
|
||||
public static var POLLHUP: PollEvents { hangUp }
|
||||
|
||||
/// An event indicating that the object a descriptor refers to is no
|
||||
/// longer valid.
|
||||
///
|
||||
/// This arises when the descriptor itself resolves, but the thing it
|
||||
/// refers to has since become invalid. For example, the disconnection
|
||||
/// of a sound device could cause this event.
|
||||
///
|
||||
/// A descriptor that doesn't resolve at all would make the request
|
||||
/// fail with ``Errno/badFileDescriptor`` instead.
|
||||
///
|
||||
/// The kernel reports this event whether or not it was requested, and
|
||||
/// requesting it explicitly has no effect. Corresponds to the POSIX
|
||||
/// `POLLNVAL` event flag.
|
||||
@inlinable
|
||||
public static var invalidDescriptor: PollEvents {
|
||||
PollEvents(.invalidDescriptor)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "invalidDescriptor")
|
||||
public static var POLLNVAL: PollEvents { invalidDescriptor }
|
||||
|
||||
/// An event indicating the peer closed its writing end of a stream
|
||||
/// socket, or shut it down for writing.
|
||||
///
|
||||
/// Unlike ``hangUp``, this event can arrive while the connection is
|
||||
/// still half-open: data already in flight can still be read, and the
|
||||
/// local end can still write. Once both directions are shut down,
|
||||
/// ``hangUp`` is reported alongside this event.
|
||||
///
|
||||
/// Unlike `poll(2)`, `io_uring` reports this event whether or not it
|
||||
/// was requested, and requesting it explicitly has no effect.
|
||||
/// Corresponds to the Linux `POLLRDHUP` event flag.
|
||||
@inlinable
|
||||
public static var peerClosed: PollEvents { PollEvents(.peerClosed) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "peerClosed")
|
||||
public static var POLLRDHUP: PollEvents { peerClosed }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,239 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
public import CSystemIOUring
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
internal struct RawIORequest: ~Copyable {
|
||||
// swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where
|
||||
// IORing is supported (currently requires kernel version >= 5.15).
|
||||
@usableFromInline var rawValue: swift_io_uring_sqe
|
||||
|
||||
@inlinable public init() {
|
||||
self.rawValue = swift_io_uring_sqe()
|
||||
}
|
||||
}
|
||||
|
||||
extension RawIORequest {
|
||||
@usableFromInline
|
||||
enum Operation: UInt8 {
|
||||
case nop = 0
|
||||
case readv = 1
|
||||
case writev = 2
|
||||
case fsync = 3
|
||||
case readFixed = 4
|
||||
case writeFixed = 5
|
||||
case pollAdd = 6
|
||||
case pollRemove = 7
|
||||
case syncFileRange = 8
|
||||
case sendMessage = 9
|
||||
case receiveMessage = 10
|
||||
// ...
|
||||
case asyncCancel = 14
|
||||
case link_timeout = 15
|
||||
// ...
|
||||
case openAt = 18
|
||||
case close = 19
|
||||
case filesUpdate = 20
|
||||
case statx = 21
|
||||
case read = 22
|
||||
case write = 23
|
||||
// ...
|
||||
case openAt2 = 28
|
||||
// ...
|
||||
case unlinkAt = 36
|
||||
}
|
||||
|
||||
public struct Flags: OptionSet, Hashable, Codable {
|
||||
public let rawValue: UInt8
|
||||
|
||||
@inlinable public init(rawValue: UInt8) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@inlinable public static var fixedFile: RawIORequest.Flags { Flags(rawValue: 1 << 0) }
|
||||
@inlinable public static var drainQueue: RawIORequest.Flags { Flags(rawValue: 1 << 1) }
|
||||
@inlinable public static var linkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 2) }
|
||||
@inlinable public static var hardlinkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 3) }
|
||||
@inlinable public static var asynchronous: RawIORequest.Flags { Flags(rawValue: 1 << 4) }
|
||||
@inlinable public static var selectBuffer: RawIORequest.Flags { Flags(rawValue: 1 << 5) }
|
||||
@inlinable public static var skipSuccess: RawIORequest.Flags { Flags(rawValue: 1 << 6) }
|
||||
}
|
||||
|
||||
@inlinable var operation: Operation {
|
||||
get { Operation(rawValue: rawValue.opcode)! }
|
||||
set { rawValue.opcode = newValue.rawValue }
|
||||
}
|
||||
|
||||
@inlinable var cancel_flags: UInt32 {
|
||||
get { rawValue.cancel_flags }
|
||||
set { rawValue.cancel_flags = newValue }
|
||||
}
|
||||
|
||||
@inlinable var addr: UInt64 {
|
||||
get { rawValue.addr }
|
||||
set { rawValue.addr = newValue }
|
||||
}
|
||||
|
||||
/// The poll event mask, stored in `sqe->poll32_events`.
|
||||
///
|
||||
/// Big-endian kernels swap the halfwords of this field before reading it.
|
||||
/// Equivalent to liburing's `__io_uring_prep_poll_mask`.
|
||||
@_alwaysEmitIntoClient var pollEvents: IORing.Request.PollEvents {
|
||||
get { .init(rawValue: Self._applyPollMask(rawValue.poll32_events)) }
|
||||
set { rawValue.poll32_events = Self._applyPollMask(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// Converts a poll event mask between its in-memory and `sqe` encodings.
|
||||
///
|
||||
/// This is a halfword rotate (`swahw32` from `<linux/swab.h>`), which keeps
|
||||
/// the byte order within each half.
|
||||
@_alwaysEmitIntoClient static func _applyPollMask(_ mask: UInt32) -> UInt32 {
|
||||
#if _endian(big)
|
||||
return (mask &<< 16) | (mask &>> 16)
|
||||
#else
|
||||
return mask
|
||||
#endif
|
||||
}
|
||||
|
||||
@inlinable public var flags: Flags {
|
||||
get { Flags(rawValue: rawValue.flags) }
|
||||
set { rawValue.flags = newValue.rawValue }
|
||||
}
|
||||
|
||||
@inlinable public mutating func linkToNextRequest() {
|
||||
flags = Flags(rawValue: flags.rawValue | Flags.linkRequest.rawValue)
|
||||
}
|
||||
|
||||
@inlinable public var fileDescriptor: FileDescriptor {
|
||||
get { FileDescriptor(rawValue: rawValue.fd) }
|
||||
set { rawValue.fd = newValue.rawValue }
|
||||
}
|
||||
|
||||
@inlinable public var offset: UInt64? {
|
||||
get {
|
||||
if (rawValue.off == UInt64.max) {
|
||||
return nil
|
||||
} else {
|
||||
return rawValue.off
|
||||
}
|
||||
}
|
||||
set {
|
||||
if let val = newValue {
|
||||
rawValue.off = val
|
||||
} else {
|
||||
rawValue.off = UInt64.max
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public var buffer: UnsafeMutableRawBufferPointer {
|
||||
get {
|
||||
let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!)
|
||||
return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len))
|
||||
}
|
||||
|
||||
set {
|
||||
rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!))
|
||||
rawValue.len = UInt32(exactly: newValue.count)!
|
||||
}
|
||||
}
|
||||
|
||||
public enum RequestFlags {
|
||||
case readWriteFlags(ReadWriteFlags)
|
||||
// case fsyncFlags(FsyncFlags?)
|
||||
// poll_events
|
||||
// poll32_events
|
||||
// sync_range_flags
|
||||
// msg_flags
|
||||
case timeoutFlags(TimeOutFlags)
|
||||
// accept_flags
|
||||
// cancel_flags
|
||||
case openFlags(FileDescriptor.OpenOptions)
|
||||
// statx_flags
|
||||
// fadvise_advice
|
||||
// splice_flags
|
||||
}
|
||||
|
||||
public struct ReadWriteFlags: OptionSet, Hashable, Codable {
|
||||
public var rawValue: UInt32
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@inlinable public static var highPriority: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 0) }
|
||||
|
||||
// sync with only data integrity
|
||||
@inlinable public static var dataSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 1) }
|
||||
|
||||
// sync with full data + file integrity
|
||||
@inlinable public static var fileSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 2) }
|
||||
|
||||
// return -EAGAIN if operation blocks
|
||||
@inlinable public static var noWait: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 3) }
|
||||
|
||||
// append to end of the file
|
||||
@inlinable public static var append: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 4) }
|
||||
}
|
||||
|
||||
public struct TimeOutFlags: OptionSet, Hashable, Codable {
|
||||
public var rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@inlinable public static var relativeTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 0) }
|
||||
@inlinable public static var absoluteTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 1 << 0) }
|
||||
}
|
||||
}
|
||||
|
||||
extension RawIORequest {
|
||||
@inlinable
|
||||
static func nop() -> RawIORequest {
|
||||
var req: RawIORequest = RawIORequest()
|
||||
req.operation = .nop
|
||||
return req
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func withTimeoutRequest<R, E: Error>(
|
||||
linkedTo opEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
in timeoutEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
duration: Duration,
|
||||
flags: TimeOutFlags,
|
||||
work: () throws(E) -> R) throws(E) -> R {
|
||||
|
||||
opEntry.pointee.flags |= Flags.linkRequest.rawValue
|
||||
opEntry.pointee.off = 1
|
||||
var ts = timespec(
|
||||
tv_sec: Int(duration.components.seconds),
|
||||
tv_nsec: Int(duration.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
return try withUnsafePointer(to: &ts) { tsPtr throws(E) -> R in
|
||||
var req: RawIORequest = RawIORequest()
|
||||
req.operation = .link_timeout
|
||||
req.rawValue.timeout_flags = flags.rawValue
|
||||
req.rawValue.len = 1
|
||||
req.rawValue.addr = UInt64(UInt(bitPattern: tsPtr))
|
||||
timeoutEntry.pointee = req.rawValue
|
||||
return try work()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -1,20 +1,29 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
#if os(Linux)
|
||||
// SwiftGlibc doesn't export `struct statfs`, so re-export it for clients who
|
||||
// need to use the fields of a `CInterop.StatFS`.
|
||||
@_exported import CSystemStatFS
|
||||
#endif
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -29,13 +38,19 @@ import ucrt
|
||||
public typealias CModeT = CInt
|
||||
#else
|
||||
/// The C `mode_t` type.
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
public typealias CModeT = mode_t
|
||||
#endif
|
||||
|
||||
/// A namespace for C and platform types
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
public enum CInterop {
|
||||
#if os(Windows)
|
||||
public typealias Mode = CInt
|
||||
#else
|
||||
public typealias Mode = mode_t
|
||||
#endif
|
||||
|
||||
/// The C `char` type
|
||||
public typealias Char = CChar
|
||||
|
||||
@@ -65,3 +80,59 @@ public enum CInterop {
|
||||
public typealias PlatformUnicodeEncoding = UTF8
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(System 0.0.2, *) // Original availability of CInterop
|
||||
extension CInterop {
|
||||
/// The C `stat` struct.
|
||||
public typealias Stat = stat
|
||||
|
||||
/// Calls the C `stat()` function.
|
||||
///
|
||||
/// This is a direct wrapper around the C `stat()` system call.
|
||||
/// For a more ergonomic Swift API, use `Stat` instead.
|
||||
///
|
||||
/// - Warning: This API is primarily intended for migration purposes when
|
||||
/// supporting older deployment targets. If your deployment target supports
|
||||
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
|
||||
/// type-safe, ergonomic access to file metadata in Swift.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: A null-terminated C string representing the file path.
|
||||
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
|
||||
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
|
||||
@_alwaysEmitIntoClient
|
||||
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
system_stat(path, &s)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
extension CInterop {
|
||||
public typealias DeviceID = dev_t
|
||||
public typealias Inode = ino_t
|
||||
public typealias UserID = uid_t
|
||||
public typealias GroupID = gid_t
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
public typealias FileFlags = UInt32
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@available(System 1.9.0, *)
|
||||
extension CInterop {
|
||||
/// The C `statfs` struct.
|
||||
public typealias StatFS = statfs
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(OpenBSD)
|
||||
public typealias MountFlags = UInt32
|
||||
#elseif os(FreeBSD)
|
||||
public typealias MountFlags = UInt64
|
||||
#else
|
||||
public typealias MountFlags = CUnsignedLong
|
||||
#endif
|
||||
|
||||
public typealias FileSystemID = fsid_t
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,29 +1,40 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
*/
|
||||
|
||||
// For platform constants redefined in Swift. We define them here so that
|
||||
// they can be used anywhere without imports and without confusion to
|
||||
// unavailable local decls.
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
import WinSDK
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - errno
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// Some WASI constants come from CSystem and are inlined into clients.
|
||||
#if os(WASI)
|
||||
public import CSystem
|
||||
#endif
|
||||
|
||||
// MARK: errno
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERRNO_NOT_USED: CInt { 0 }
|
||||
#endif
|
||||
@@ -70,7 +81,7 @@ internal var _EACCES: CInt { EACCES }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFAULT: CInt { EFAULT }
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(Windows) && !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTBLK: CInt { ENOTBLK }
|
||||
#endif
|
||||
@@ -138,7 +149,13 @@ internal var _ERANGE: CInt { ERANGE }
|
||||
internal var _EAGAIN: CInt { EAGAIN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EWOULDBLOCK: CInt { EWOULDBLOCK }
|
||||
internal var _EWOULDBLOCK: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_EWOULDBLOCK()
|
||||
#else
|
||||
EWOULDBLOCK
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINPROGRESS: CInt { EINPROGRESS }
|
||||
@@ -164,6 +181,7 @@ internal var _ENOPROTOOPT: CInt { ENOPROTOOPT }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTONOSUPPORT: CInt { EPROTONOSUPPORT }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESOCKTNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
@@ -172,6 +190,7 @@ internal var _ESOCKTNOSUPPORT: CInt {
|
||||
return ESOCKTNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSUP: CInt {
|
||||
@@ -182,6 +201,7 @@ internal var _ENOTSUP: CInt {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPFNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
@@ -190,6 +210,7 @@ internal var _EPFNOSUPPORT: CInt {
|
||||
return EPFNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT }
|
||||
@@ -224,6 +245,7 @@ internal var _EISCONN: CInt { EISCONN }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCONN: CInt { ENOTCONN }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHUTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
@@ -241,6 +263,7 @@ internal var _ETOOMANYREFS: CInt {
|
||||
return ETOOMANYREFS
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIMEDOUT: CInt { ETIMEDOUT }
|
||||
@@ -254,6 +277,7 @@ internal var _ELOOP: CInt { ELOOP }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAMETOOLONG: CInt { ENAMETOOLONG }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
@@ -262,6 +286,7 @@ internal var _EHOSTDOWN: CInt {
|
||||
return EHOSTDOWN
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
|
||||
@@ -269,11 +294,12 @@ internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTEMPTY: CInt { ENOTEMPTY }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROCLIM: CInt { EPROCLIM }
|
||||
#endif
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUSERS: CInt {
|
||||
#if os(Windows)
|
||||
@@ -282,6 +308,7 @@ internal var _EUSERS: CInt {
|
||||
return EUSERS
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDQUOT: CInt {
|
||||
@@ -301,6 +328,7 @@ internal var _ESTALE: CInt {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTE: CInt {
|
||||
#if os(Windows)
|
||||
@@ -309,8 +337,9 @@ internal var _EREMOTE: CInt {
|
||||
return EREMOTE
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADRPC: CInt { EBADRPC }
|
||||
|
||||
@@ -333,7 +362,7 @@ internal var _ENOLCK: CInt { ENOLCK }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSYS: CInt { ENOSYS }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFTYPE: CInt { EFTYPE }
|
||||
|
||||
@@ -342,7 +371,9 @@ internal var _EAUTH: CInt { EAUTH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENEEDAUTH: CInt { ENEEDAUTH }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPWROFF: CInt { EPWROFF }
|
||||
|
||||
@@ -355,7 +386,7 @@ internal var _EDEVERR: CInt { EDEVERR }
|
||||
internal var _EOVERFLOW: CInt { EOVERFLOW }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADEXEC: CInt { EBADEXEC }
|
||||
|
||||
@@ -383,7 +414,7 @@ internal var _ENOMSG: CInt { ENOMSG }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EILSEQ: CInt { EILSEQ }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOATTR: CInt { ENOATTR }
|
||||
#endif
|
||||
@@ -396,32 +427,43 @@ internal var _EBADMSG: CInt { EBADMSG }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMULTIHOP: CInt { EMULTIHOP }
|
||||
|
||||
#if !os(WASI) && !os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODATA: CInt { ENODATA }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLINK: CInt { ENOLINK }
|
||||
|
||||
#if !os(WASI) && !os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSR: CInt { ENOSR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSTR: CInt { ENOSTR }
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTO: CInt { EPROTO }
|
||||
|
||||
#if !os(OpenBSD)
|
||||
#if !os(OpenBSD) && !os(WASI) && !os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIME: CInt { ETIME }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_EOPNOTSUPP()
|
||||
#else
|
||||
EOPNOTSUPP
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPOLICY: CInt { ENOPOLICY }
|
||||
#endif
|
||||
@@ -434,15 +476,28 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
|
||||
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCAPABLE: CInt { ENOTCAPABLE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECAPMODE: CInt { ECAPMODE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINTEGRITY: CInt { EINTEGRITY }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EQFULL: CInt { EQFULL }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELAST: CInt { ELAST }
|
||||
#endif
|
||||
|
||||
// MARK: - File Operations
|
||||
// MARK: File Operations
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDONLY: CInt { O_RDONLY }
|
||||
@@ -454,18 +509,40 @@ internal var _O_WRONLY: CInt { O_WRONLY }
|
||||
internal var _O_RDWR: CInt { O_RDWR }
|
||||
|
||||
#if !os(Windows)
|
||||
#if canImport(Musl)
|
||||
internal var _O_ACCMODE: CInt { 0x03|O_SEARCH }
|
||||
#else
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ACCMODE: CInt { O_ACCMODE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
|
||||
internal var _O_ACCMODE: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_ACCMODE()
|
||||
#else
|
||||
O_ACCMODE
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt { O_APPEND }
|
||||
internal var _O_NONBLOCK: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_NONBLOCK()
|
||||
#else
|
||||
O_NONBLOCK
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_APPEND()
|
||||
#else
|
||||
O_APPEND
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SHLOCK: CInt { O_SHLOCK }
|
||||
|
||||
@@ -474,24 +551,52 @@ internal var _O_EXLOCK: CInt { O_EXLOCK }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(WASI)
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ASYNC: CInt { O_ASYNC }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOFOLLOW: CInt { O_NOFOLLOW }
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CREAT: CInt { O_CREAT }
|
||||
internal var _O_FSYNC: CInt { O_FSYNC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt { O_TRUNC }
|
||||
internal var _O_SYNC: CInt { O_SYNC }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt { O_EXCL }
|
||||
internal var _O_CREAT: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_CREAT()
|
||||
#else
|
||||
O_CREAT
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_TRUNC()
|
||||
#else
|
||||
O_TRUNC
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_EXCL()
|
||||
#else
|
||||
O_EXCL
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EVTONLY: CInt { O_EVTONLY }
|
||||
#endif
|
||||
@@ -502,17 +607,40 @@ internal var _O_EVTONLY: CInt { O_EVTONLY }
|
||||
internal var _O_NOCTTY: CInt { O_NOCTTY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECTORY: CInt { O_DIRECTORY }
|
||||
internal var _O_DIRECTORY: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_DIRECTORY()
|
||||
#else
|
||||
O_DIRECTORY
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SYMLINK: CInt { O_SYMLINK }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt {
|
||||
#if os(Windows)
|
||||
O_NOINHERIT
|
||||
#else
|
||||
O_CLOEXEC
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt { O_CLOEXEC }
|
||||
internal var _O_CLOFORK: CInt {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
0x0800_0000 // O_CLOFORK, which SDKs before macOS 27 and older FreeBSD lack
|
||||
#elseif !os(WASI) && !os(Linux) && !os(Android)
|
||||
O_CLOFORK
|
||||
#else
|
||||
0
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -524,7 +652,7 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_END: CInt { SEEK_END }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
|
||||
|
||||
@@ -532,3 +660,481 @@ internal var _SEEK_HOLE: CInt { SEEK_HOLE }
|
||||
internal var _SEEK_DATA: CInt { SEEK_DATA }
|
||||
#endif
|
||||
|
||||
// MARK: - File System
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_FDCWD: CInt { AT_FDCWD }
|
||||
|
||||
// MARK: - fstatat Flags
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_SYMLINK_NOFOLLOW: CInt { AT_SYMLINK_NOFOLLOW }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_SYMLINK_NOFOLLOW_ANY: CInt { AT_SYMLINK_NOFOLLOW_ANY }
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin, _version: 346) || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_RESOLVE_BENEATH: CInt { AT_RESOLVE_BENEATH }
|
||||
#endif
|
||||
|
||||
// MARK: - File Mode / File Type
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MODE_FILETYPE_MASK: mode_t { S_IFMT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MODE_PERMISSIONS_MASK: mode_t { 0o7777 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFDIR: mode_t { S_IFDIR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFCHR: mode_t { S_IFCHR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFBLK: mode_t { S_IFBLK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFREG: mode_t { S_IFREG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFIFO: mode_t { S_IFIFO }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFLNK: mode_t { S_IFLNK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFSOCK: mode_t { S_IFSOCK }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
// `S_IFWHT` is `Int32` on FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFWHT: mode_t { .init(S_IFWHT) }
|
||||
#endif
|
||||
|
||||
// MARK: - stat/chflags File Flags
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_NODUMP: UInt32 { UInt32(bitPattern: UF_NODUMP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_IMMUTABLE: UInt32 { UInt32(bitPattern: UF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_APPEND: UInt32 { UInt32(bitPattern: UF_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_ARCHIVED: UInt32 { UInt32(bitPattern: SF_ARCHIVED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_IMMUTABLE: UInt32 { UInt32(bitPattern: SF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_APPEND: UInt32 { UInt32(bitPattern: SF_APPEND) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_OPAQUE: UInt32 { UInt32(bitPattern: UF_OPAQUE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_HIDDEN: UInt32 { UInt32(bitPattern: UF_HIDDEN) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_NOUNLINK: UInt32 { UInt32(bitPattern: SF_NOUNLINK) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin Only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_COMPRESSED: UInt32 { UInt32(bitPattern: UF_COMPRESSED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_TRACKED: UInt32 { UInt32(bitPattern: UF_TRACKED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_DATAVAULT: UInt32 { UInt32(bitPattern: UF_DATAVAULT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_RESTRICTED: UInt32 { UInt32(bitPattern: SF_RESTRICTED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_FIRMLINK: UInt32 { UInt32(bitPattern: SF_FIRMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_DATALESS: UInt32 { UInt32(bitPattern: SF_DATALESS) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_NOUNLINK: UInt32 { UInt32(bitPattern: UF_NOUNLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_OFFLINE: UInt32 { UInt32(bitPattern: UF_OFFLINE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_READONLY: UInt32 { UInt32(bitPattern: UF_READONLY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_REPARSE: UInt32 { UInt32(bitPattern: UF_REPARSE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_SPARSE: UInt32 { UInt32(bitPattern: UF_SPARSE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_SYSTEM: UInt32 { UInt32(bitPattern: UF_SYSTEM) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) }
|
||||
#endif
|
||||
|
||||
// MARK: - statfs Mount Flags
|
||||
|
||||
// `_MOUNT_*` is `MNT_*` on Darwin and BSD, or `ST_*` on Linux and Android.
|
||||
|
||||
#if !os(WASI)
|
||||
|
||||
// MARK: ST_* bits on Linux and Android
|
||||
|
||||
// Literal bits to keep our `@_alwaysEmitIntoClient` semantics. Calling
|
||||
// CSystem's `_system_get_ST_*` getters would put a CSystem symbol in every
|
||||
// client, block constant folding, and require a public `import CSystem`.
|
||||
// `StatFSTests.mountFlagBitsMatchLibc` checks the literals against libc.
|
||||
#if os(Linux) || os(Android)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_RDONLY_BIT: CInterop.MountFlags { 0x0001 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NOSUID_BIT: CInterop.MountFlags { 0x0002 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NODEV_BIT: CInterop.MountFlags { 0x0004 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NOEXEC_BIT: CInterop.MountFlags { 0x0008 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_SYNCHRONOUS_BIT: CInterop.MountFlags { 0x0010 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_MANDLOCK_BIT: CInterop.MountFlags { 0x0040 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NOATIME_BIT: CInterop.MountFlags { 0x0400 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NODIRATIME_BIT: CInterop.MountFlags { 0x0800 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_RELATIME_BIT: CInterop.MountFlags { 0x1000 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NOSYMFOLLOW_BIT: CInterop.MountFlags { 0x2000 }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_VALID_BIT: CInterop.MountFlags { 0x0020 }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on All Platforms
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_RDONLY: CInterop.MountFlags {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_RDONLY)
|
||||
#elseif os(Linux) || os(Android)
|
||||
_ST_RDONLY_BIT
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_SYNCHRONOUS: CInterop.MountFlags {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_SYNCHRONOUS)
|
||||
#elseif os(Linux) || os(Android)
|
||||
_ST_SYNCHRONOUS_BIT
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_NOEXEC: CInterop.MountFlags {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_NOEXEC)
|
||||
#elseif os(Linux) || os(Android)
|
||||
_ST_NOEXEC_BIT
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_NOSUID: CInterop.MountFlags {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_NOSUID)
|
||||
#elseif os(Linux) || os(Android)
|
||||
_ST_NOSUID_BIT
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_NOATIME: CInterop.MountFlags {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_NOATIME)
|
||||
#elseif os(Linux) || os(Android)
|
||||
_ST_NOATIME_BIT
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Flags Available on All Platforms Except FreeBSD
|
||||
|
||||
#if !os(FreeBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_NODEV: CInterop.MountFlags {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(OpenBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_NODEV)
|
||||
#elseif os(Linux) || os(Android)
|
||||
_ST_NODEV_BIT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Linux and Android
|
||||
|
||||
#if os(Linux) || os(Android)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_MANDLOCK: CInterop.MountFlags { _ST_MANDLOCK_BIT }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_NODIRATIME: CInterop.MountFlags { _ST_NODIRATIME_BIT }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ST_RELATIME: CInterop.MountFlags { _ST_RELATIME_BIT }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Linux, Android, and FreeBSD
|
||||
|
||||
#if os(Linux) || os(Android) || os(FreeBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MOUNT_NOSYMFOLLOW: CInterop.MountFlags {
|
||||
#if os(FreeBSD)
|
||||
CInterop.MountFlags(truncatingIfNeeded: MNT_NOSYMFOLLOW)
|
||||
#else
|
||||
_ST_NOSYMFOLLOW_BIT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_ASYNC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ASYNC) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_EXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTED) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_LOCAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_LOCAL) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_QUOTA: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUOTA) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_ROOTFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ROOTFS) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_UNION: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNION) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_AUTOMOUNTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_AUTOMOUNTED) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_MULTILABEL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_MULTILABEL) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD and OpenBSD
|
||||
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_EXRDONLY: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXRDONLY) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_DEFEXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFEXPORTED) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_EXPORTANON: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTANON) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_SOFTDEP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SOFTDEP) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin Only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_CPROTECT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_CPROTECT) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_REMOVABLE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_REMOVABLE) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_QUARANTINE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUARANTINE) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_DOVOLFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DOVOLFS) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_DONTBROWSE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DONTBROWSE) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_IGNORE_OWNERSHIP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE_OWNERSHIP) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_JOURNALED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_JOURNALED) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_NOUSERXATTR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOUSERXATTR) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_DEFWRITE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFWRITE) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_NOFOLLOW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOFOLLOW) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_SNAPSHOT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SNAPSHOT) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_STRICTATIME: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_STRICTATIME) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_EXKERB: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXKERB) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_EXPUBLIC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPUBLIC) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ACLS) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_GJOURNAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_GJOURNAL) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_IGNORE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_NFS4ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NFS4ACLS) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_NOCLUSTERR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERR) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_NOCLUSTERW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERW) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_SUIDDIR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUIDDIR) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_SUJ: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUJ) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_UNTRUSTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNTRUSTED) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_USER: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_USER) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_VERIFIED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_VERIFIED) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on OpenBSD Only
|
||||
|
||||
#if os(OpenBSD)
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_NOPERM: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOPERM) }
|
||||
|
||||
@available(System 1.9.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MNT_WXALLOWED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_WXALLOWED) }
|
||||
#endif
|
||||
|
||||
#endif // !os(WASI)
|
||||
|
||||
#endif // !os(Windows)
|
||||
@@ -1,25 +1,31 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
*/
|
||||
|
||||
// Internal wrappers and typedefs which help reduce #if littering in System's
|
||||
// code base.
|
||||
|
||||
// TODO: Should CSystem just include all the header files we need?
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
import WinSDK
|
||||
#elseif canImport(Glibc)
|
||||
#if os(Linux)
|
||||
import CSystemStatFS
|
||||
#endif
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -28,7 +34,7 @@ internal typealias _COffT = off_t
|
||||
|
||||
// MARK: syscalls and variables
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
internal var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
@@ -45,21 +51,32 @@ internal var system_errno: CInt {
|
||||
_ = ucrt._set_errno(newValue)
|
||||
}
|
||||
}
|
||||
#else
|
||||
#elseif canImport(Glibc)
|
||||
internal var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Musl)
|
||||
internal var system_errno: CInt {
|
||||
get { Musl.errno }
|
||||
set { Musl.errno = newValue }
|
||||
}
|
||||
#elseif canImport(WASILibc)
|
||||
internal var system_errno: CInt {
|
||||
get { WASILibc.errno }
|
||||
set { WASILibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Android)
|
||||
internal var system_errno: CInt {
|
||||
get { Android.errno }
|
||||
set { Android.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: C stdlib decls
|
||||
|
||||
// Convention: `system_foo` is system's wrapper for `foo`.
|
||||
|
||||
internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
@@ -67,6 +84,37 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(System 0.0.2, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
stat(p, &s)
|
||||
}
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_lstat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
lstat(p, &s)
|
||||
}
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
|
||||
fstat(fd, &s)
|
||||
}
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 {
|
||||
fstatat(fd, p, &s, flags)
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@available(System 1.9.0, *)
|
||||
internal func system_statfs(_ p: UnsafePointer<CChar>, _ s: inout CInterop.StatFS) -> Int32 {
|
||||
statfs(p, &s)
|
||||
}
|
||||
@available(System 1.9.0, *)
|
||||
internal func system_fstatfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 {
|
||||
fstatfs(fd, &s)
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Convention: `system_platform_foo` is a
|
||||
// platform-representation-abstracted wrapper around `foo`-like functionality.
|
||||
// Type and layout differences such as the `char` vs `wchar` are abstracted.
|
||||
@@ -117,7 +165,7 @@ extension String {
|
||||
return
|
||||
|
||||
#else
|
||||
self.init(validatingUTF8: platformString)
|
||||
self.init(validatingCString: platformString)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -141,6 +189,25 @@ extension String {
|
||||
// TLS
|
||||
#if os(Windows)
|
||||
internal typealias _PlatformTLSKey = DWORD
|
||||
#elseif os(WASI) && !_runtime(_multithreaded)
|
||||
// Mock TLS storage for single-threaded WASI.
|
||||
// Carries no state of its own, and only used to index `sharedTLSStorage`.
|
||||
internal final class _PlatformTLSKey: @unchecked Sendable {
|
||||
fileprivate init() {}
|
||||
}
|
||||
private final class TLSStorage: @unchecked Sendable {
|
||||
var storage = [ObjectIdentifier: UnsafeMutableRawPointer]()
|
||||
}
|
||||
private let sharedTLSStorage = TLSStorage()
|
||||
|
||||
func pthread_setspecific(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) -> Int {
|
||||
sharedTLSStorage.storage[ObjectIdentifier(key)] = p
|
||||
return 0
|
||||
}
|
||||
|
||||
func pthread_getspecific(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
|
||||
sharedTLSStorage.storage[ObjectIdentifier(key)]
|
||||
}
|
||||
#else
|
||||
internal typealias _PlatformTLSKey = pthread_key_t
|
||||
#endif
|
||||
@@ -152,6 +219,8 @@ internal func makeTLSKey() -> _PlatformTLSKey {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#elseif os(WASI) && !_runtime(_multithreaded)
|
||||
return _PlatformTLSKey()
|
||||
#else
|
||||
var raw = pthread_key_t()
|
||||
guard 0 == pthread_key_create(&raw, nil) else {
|
||||
|
||||
@@ -63,7 +63,7 @@ internal class MockingDriver {
|
||||
|
||||
// Whether we should pretend to be Windows for syntactic operations
|
||||
// inside FilePath
|
||||
fileprivate var forceWindowsSyntaxForPaths = false
|
||||
fileprivate var forceWindowsSyntaxForPaths: Bool? = nil
|
||||
}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
@@ -110,8 +110,8 @@ private var contextualMockingEnabled: Bool {
|
||||
extension MockingDriver {
|
||||
internal static var enabled: Bool { mockingEnabled }
|
||||
|
||||
internal static var forceWindowsPaths: Bool {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
|
||||
internal static var forceWindowsPaths: Bool? {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,9 +128,9 @@ internal var mockingEnabled: Bool {
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var forceWindowsPaths: Bool {
|
||||
internal var forceWindowsPaths: Bool? {
|
||||
#if !ENABLE_MOCKING
|
||||
return false
|
||||
return nil
|
||||
#else
|
||||
return MockingDriver.forceWindowsPaths
|
||||
#endif
|
||||
@@ -193,25 +193,14 @@ internal func _mockOffT(
|
||||
) -> _COffT {
|
||||
_COffT(mockImpl(name: name, path: path, args))
|
||||
}
|
||||
|
||||
internal func _mockModeT(
|
||||
name: String = #function, _ args: AnyHashable...
|
||||
) -> CInterop.Mode {
|
||||
CInterop.Mode(mockImpl(name: name, path: nil, args))
|
||||
}
|
||||
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
// Force paths to be treated as Windows syntactically if `enabled` is
|
||||
// true.
|
||||
// true, and as POSIX syntactically if not.
|
||||
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
|
||||
#if ENABLE_MOCKING
|
||||
guard enabled else {
|
||||
body()
|
||||
return
|
||||
}
|
||||
MockingDriver.withMockingEnabled { driver in
|
||||
driver.forceWindowsSyntaxForPaths = true
|
||||
driver.forceWindowsSyntaxForPaths = enabled
|
||||
body()
|
||||
}
|
||||
#else
|
||||
|
||||
@@ -80,7 +80,13 @@ extension _RawBuffer {
|
||||
internal static func create(minimumCapacity: Int) -> Storage {
|
||||
Storage.create(
|
||||
minimumCapacity: minimumCapacity,
|
||||
makingHeaderWith: { $0.capacity }
|
||||
makingHeaderWith: {
|
||||
#if os(OpenBSD)
|
||||
minimumCapacity
|
||||
#else
|
||||
$0.capacity
|
||||
#endif
|
||||
}
|
||||
) as! Storage
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
internal import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -20,6 +27,16 @@ import ucrt
|
||||
// Interacting with the mocking system, tracing, etc., is a potentially significant
|
||||
// amount of code size, so we hand outline that code for every syscall
|
||||
|
||||
// strerror(3) isn't guaranteed to be thread-safe: for an unknown error number,
|
||||
// it may format the message into a buffer shared by all threads. This wrapper
|
||||
// uses a caller-provided buffer instead (strerror_r(3), or strerror_s on
|
||||
// Windows). It isn't a syscall, so it isn't mocked.
|
||||
internal func system_strerror_r(
|
||||
_ errnum: CInt, _ buffer: UnsafeMutablePointer<CChar>, _ length: Int
|
||||
) -> CInt {
|
||||
csystem_strerror_r(errnum, buffer, length)
|
||||
}
|
||||
|
||||
// open
|
||||
internal func system_open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
|
||||
@@ -69,7 +86,15 @@ internal func system_pread(
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
|
||||
#endif
|
||||
#if os(Android)
|
||||
var zero = UInt8.zero
|
||||
return withUnsafeMutablePointer(to: &zero) {
|
||||
// this pread has a non-nullable `buf` pointer
|
||||
pread(fd, buf ?? UnsafeMutableRawPointer($0), nbyte, offset)
|
||||
}
|
||||
#else
|
||||
return pread(fd, buf, nbyte, offset)
|
||||
#endif
|
||||
}
|
||||
|
||||
// lseek
|
||||
@@ -99,9 +124,18 @@ internal func system_pwrite(
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
|
||||
#endif
|
||||
#if os(Android)
|
||||
var zero = UInt8.zero
|
||||
return withUnsafeMutablePointer(to: &zero) {
|
||||
// this pwrite has a non-nullable `buf` pointer
|
||||
pwrite(fd, buf ?? UnsafeRawPointer($0), nbyte, offset)
|
||||
}
|
||||
#else
|
||||
return pwrite(fd, buf, nbyte, offset)
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
internal func system_dup(_ fd: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
@@ -116,20 +150,148 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
return dup2(fd, fd2)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
internal func system_dup3(_ fd: Int32, _ fd2: Int32, _ oflag: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, fd2, oflag) }
|
||||
#endif
|
||||
return csystem_posix_dup3(fd, fd2, oflag)
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
|
||||
#if !os(WASI)
|
||||
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fds) }
|
||||
#endif
|
||||
return pipe(fds)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
internal func system_pipe2(_ fds: UnsafeMutablePointer<Int32>, _ oflag: Int32) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fds, oflag) }
|
||||
#endif
|
||||
return csystem_posix_pipe2(fds, oflag)
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
|
||||
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, length) }
|
||||
#endif
|
||||
return ftruncate(fd, length)
|
||||
}
|
||||
|
||||
internal func system_mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path: path, mode) }
|
||||
#endif
|
||||
return mkdir(path, mode)
|
||||
}
|
||||
|
||||
internal func system_rmdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path: path) }
|
||||
#endif
|
||||
return rmdir(path)
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
internal let SYSTEM_CS_DARWIN_USER_TEMP_DIR = _CS_DARWIN_USER_TEMP_DIR
|
||||
|
||||
internal func system_confstr(
|
||||
_ name: CInt,
|
||||
_ buf: UnsafeMutablePointer<CInterop.PlatformChar>,
|
||||
_ len: Int
|
||||
) -> Int {
|
||||
return confstr(name, buf, len)
|
||||
}
|
||||
#endif // SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
#if !os(Windows)
|
||||
internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR
|
||||
#if os(WASI)
|
||||
internal let SYSTEM_DT_DIR = _getConst_DT_DIR()
|
||||
internal typealias system_dirent = _system_dirent
|
||||
#else
|
||||
internal let SYSTEM_DT_DIR = DT_DIR
|
||||
internal typealias system_dirent = dirent
|
||||
#endif
|
||||
#if os(Linux) || os(Android) || os(FreeBSD) || os(OpenBSD) || os(WASI)
|
||||
internal typealias system_DIRPtr = OpaquePointer
|
||||
#else
|
||||
internal typealias system_DIRPtr = UnsafeMutablePointer<DIR>
|
||||
#endif
|
||||
|
||||
internal func system_unlinkat(
|
||||
_ fd: CInt,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flag: CInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, flag) }
|
||||
#endif
|
||||
return unlinkat(fd, path, flag)
|
||||
}
|
||||
|
||||
internal func system_fdopendir(
|
||||
_ fd: CInt
|
||||
) -> system_DIRPtr? {
|
||||
return fdopendir(fd)
|
||||
}
|
||||
|
||||
internal func system_readdir(
|
||||
_ dir: system_DIRPtr
|
||||
) -> UnsafeMutablePointer<system_dirent>? {
|
||||
#if os(WASI)
|
||||
return _system_dirent_from_wasi_dirent(readdir(dir))
|
||||
#else
|
||||
return readdir(dir)
|
||||
#endif
|
||||
}
|
||||
|
||||
internal func system_rewinddir(
|
||||
_ dir: system_DIRPtr
|
||||
) {
|
||||
return rewinddir(dir)
|
||||
}
|
||||
|
||||
internal func system_closedir(
|
||||
_ dir: system_DIRPtr
|
||||
) -> CInt {
|
||||
return closedir(dir)
|
||||
}
|
||||
|
||||
internal func system_openat(
|
||||
_ fd: CInt,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ oflag: Int32
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
return openat(fd, path, oflag)
|
||||
}
|
||||
#endif // !os(Windows)
|
||||
|
||||
#if !os(WASI) // WASI has no umask
|
||||
internal func system_umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
return umask(mode)
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
|
||||
internal func system_getenv(
|
||||
_ name: UnsafePointer<CChar>
|
||||
) -> UnsafeMutablePointer<CChar>? {
|
||||
return getenv(name)
|
||||
}
|
||||
@@ -11,14 +11,45 @@
|
||||
|
||||
import ucrt
|
||||
import WinSDK
|
||||
import Synchronization
|
||||
|
||||
private let _umask = Atomic<CInterop.Mode>(0o22)
|
||||
|
||||
@inline(__always)
|
||||
func umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
_umask.exchange(mode, ordering: .relaxed)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
|
||||
) -> CInt {
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
let decodedFlags = DecodedOpenFlags(oflag)
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: nil,
|
||||
bInheritHandle: decodedFlags.bInheritHandle
|
||||
)
|
||||
|
||||
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
|
||||
CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE,
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
nil)
|
||||
}), hFile != INVALID_HANDLE_VALUE else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -26,10 +57,41 @@ internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
// TODO(compnerd): Apply read/write permissions
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
let actualMode = mode & ~_umask.load(ordering: .relaxed)
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
defer {
|
||||
pSD.deallocate()
|
||||
}
|
||||
|
||||
let decodedFlags = DecodedOpenFlags(oflag)
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: pSD,
|
||||
bInheritHandle: decodedFlags.bInheritHandle
|
||||
)
|
||||
|
||||
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
|
||||
CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE,
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
nil)
|
||||
}), hFile != INVALID_HANDLE_VALUE else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -72,7 +134,11 @@ internal func dup(_ fd: Int32) -> Int32 {
|
||||
|
||||
@inline(__always)
|
||||
internal func dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
_dup2(fd, fd2)
|
||||
// _dup2 returns 0 to indicate success.
|
||||
if _dup2(fd, fd2) == 0 {
|
||||
return fd2
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -80,7 +146,13 @@ internal func pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
|
||||
|
||||
// Windows ReadFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
|
||||
if nbyte > Int(DWORD.max) {
|
||||
ucrt._set_errno(EINVAL)
|
||||
return -1
|
||||
}
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
@@ -91,8 +163,7 @@ internal func pread(
|
||||
|
||||
var nNumberOfBytesRead: DWORD = 0
|
||||
if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesRead)
|
||||
@@ -103,7 +174,13 @@ internal func pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
|
||||
|
||||
// Windows WriteFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
|
||||
if nbyte > Int(DWORD.max) {
|
||||
ucrt._set_errno(EINVAL)
|
||||
return -1
|
||||
}
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
@@ -115,11 +192,489 @@ internal func pwrite(
|
||||
var nNumberOfBytesWritten: DWORD = 0
|
||||
if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten,
|
||||
&ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesWritten)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func pipe(
|
||||
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0
|
||||
) -> CInt {
|
||||
return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func csystem_posix_pipe2(
|
||||
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0, _ oflag: Int32
|
||||
) -> CInt {
|
||||
return _pipe(fds, bytesReserved, _O_BINARY | oflag)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
let liDesiredLength = LARGE_INTEGER(QuadPart: LONGLONG(length))
|
||||
var liCurrentOffset = LARGE_INTEGER(QuadPart: 0)
|
||||
|
||||
// Save the current position and restore it when we're done
|
||||
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
|
||||
FILE_CURRENT) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
defer {
|
||||
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN);
|
||||
}
|
||||
|
||||
// Truncate (or extend) the file
|
||||
if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN)
|
||||
|| !SetEndOfFile(hFile) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
let actualMode = mode & ~_umask.load(ordering: .relaxed)
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode,
|
||||
for: .directory) else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
defer {
|
||||
pSD.deallocate()
|
||||
}
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: pSD,
|
||||
bInheritHandle: false
|
||||
)
|
||||
|
||||
guard (try? path.withCanonicalPathRepresentation({ path in CreateDirectoryW(path, &saAttrs) })) == true else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func rmdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
guard (try? path.withCanonicalPathRepresentation({ path in RemoveDirectoryW(path) })) == true else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
|
||||
switch errorCode {
|
||||
case ERROR_SUCCESS:
|
||||
return 0
|
||||
case ERROR_INVALID_FUNCTION,
|
||||
ERROR_INVALID_ACCESS,
|
||||
ERROR_INVALID_DATA,
|
||||
ERROR_INVALID_PARAMETER,
|
||||
ERROR_NEGATIVE_SEEK:
|
||||
return EINVAL
|
||||
case ERROR_FILE_NOT_FOUND,
|
||||
ERROR_PATH_NOT_FOUND,
|
||||
ERROR_INVALID_DRIVE,
|
||||
ERROR_NO_MORE_FILES,
|
||||
ERROR_BAD_NETPATH,
|
||||
ERROR_BAD_NET_NAME,
|
||||
ERROR_BAD_PATHNAME,
|
||||
ERROR_FILENAME_EXCED_RANGE:
|
||||
return ENOENT
|
||||
case ERROR_TOO_MANY_OPEN_FILES:
|
||||
return EMFILE
|
||||
case ERROR_ACCESS_DENIED,
|
||||
ERROR_CURRENT_DIRECTORY,
|
||||
ERROR_LOCK_VIOLATION,
|
||||
ERROR_NETWORK_ACCESS_DENIED,
|
||||
ERROR_CANNOT_MAKE,
|
||||
ERROR_FAIL_I24,
|
||||
ERROR_DRIVE_LOCKED,
|
||||
ERROR_SEEK_ON_DEVICE,
|
||||
ERROR_NOT_LOCKED,
|
||||
ERROR_LOCK_FAILED,
|
||||
ERROR_WRITE_PROTECT...ERROR_SHARING_BUFFER_EXCEEDED:
|
||||
return EACCES
|
||||
case ERROR_INVALID_HANDLE,
|
||||
ERROR_INVALID_TARGET_HANDLE,
|
||||
ERROR_DIRECT_ACCESS_HANDLE:
|
||||
return EBADF
|
||||
case ERROR_ARENA_TRASHED,
|
||||
ERROR_NOT_ENOUGH_MEMORY,
|
||||
ERROR_INVALID_BLOCK,
|
||||
ERROR_NOT_ENOUGH_QUOTA:
|
||||
return ENOMEM
|
||||
case ERROR_BAD_ENVIRONMENT:
|
||||
return E2BIG
|
||||
case ERROR_BAD_FORMAT,
|
||||
ERROR_INVALID_STARTING_CODESEG...ERROR_INFLOOP_IN_RELOC_CHAIN:
|
||||
return ENOEXEC
|
||||
case ERROR_NOT_SAME_DEVICE:
|
||||
return EXDEV
|
||||
case ERROR_FILE_EXISTS,
|
||||
ERROR_ALREADY_EXISTS:
|
||||
return EEXIST
|
||||
case ERROR_NO_PROC_SLOTS,
|
||||
ERROR_MAX_THRDS_REACHED,
|
||||
ERROR_NESTING_NOT_ALLOWED:
|
||||
return EAGAIN
|
||||
case ERROR_BROKEN_PIPE:
|
||||
return EPIPE
|
||||
case ERROR_DISK_FULL:
|
||||
return ENOSPC
|
||||
case ERROR_WAIT_NO_CHILDREN,
|
||||
ERROR_CHILD_NOT_COMPLETE:
|
||||
return ECHILD
|
||||
case ERROR_DIR_NOT_EMPTY:
|
||||
return ENOTEMPTY
|
||||
case ERROR_NO_UNICODE_TRANSLATION:
|
||||
return EILSEQ
|
||||
default:
|
||||
return EINVAL
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func rightsFromModeBits(
|
||||
_ bits: Int,
|
||||
sticky: Bool = false,
|
||||
for fileOrDirectory: _FileOrDirectory
|
||||
) -> DWORD {
|
||||
var rights: DWORD = 0
|
||||
|
||||
if (bits & 0o4) != 0 {
|
||||
rights |= (FILE_READ_ATTRIBUTES
|
||||
| FILE_READ_DATA
|
||||
| FILE_READ_EA
|
||||
| STANDARD_RIGHTS_READ
|
||||
| SYNCHRONIZE)
|
||||
}
|
||||
if (bits & 0o2) != 0 {
|
||||
rights |= (FILE_APPEND_DATA
|
||||
| FILE_WRITE_ATTRIBUTES
|
||||
| FILE_WRITE_DATA
|
||||
| FILE_WRITE_EA
|
||||
| STANDARD_RIGHTS_WRITE
|
||||
| SYNCHRONIZE)
|
||||
if fileOrDirectory == .directory && !sticky {
|
||||
rights |= FILE_DELETE_CHILD
|
||||
}
|
||||
}
|
||||
if (bits & 0o1) != 0 {
|
||||
rights |= (FILE_EXECUTE
|
||||
| FILE_READ_ATTRIBUTES
|
||||
| STANDARD_RIGHTS_EXECUTE
|
||||
| SYNCHRONIZE)
|
||||
}
|
||||
|
||||
return rights
|
||||
}
|
||||
|
||||
fileprivate func getTokenInformation<T>(
|
||||
of: T.Type,
|
||||
hToken: HANDLE,
|
||||
ticTokenClass: TOKEN_INFORMATION_CLASS
|
||||
) -> UnsafePointer<T>? {
|
||||
var capacity = 1024
|
||||
for _ in 0..<2 {
|
||||
let buffer = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: capacity,
|
||||
alignment: MemoryLayout<T>.alignment
|
||||
)
|
||||
|
||||
var dwLength = DWORD(0)
|
||||
|
||||
if GetTokenInformation(hToken,
|
||||
ticTokenClass,
|
||||
buffer,
|
||||
DWORD(capacity),
|
||||
&dwLength) {
|
||||
return UnsafePointer(buffer.assumingMemoryBound(to: T.self))
|
||||
}
|
||||
|
||||
buffer.deallocate()
|
||||
|
||||
capacity = Int(dwLength)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
internal enum _FileOrDirectory {
|
||||
case file
|
||||
case directory
|
||||
}
|
||||
|
||||
/// Build a SECURITY_DESCRIPTOR from UNIX-style "mode" bits. This only
|
||||
/// takes account of the rwx and sticky bits; there's really nothing that
|
||||
/// we can do about setuid/setgid.
|
||||
internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
for fileOrDirectory: _FileOrDirectory)
|
||||
-> PSECURITY_DESCRIPTOR? {
|
||||
let ownerPerm = (Int(mode) >> 6) & 0o7
|
||||
let groupPerm = (Int(mode) >> 3) & 0o7
|
||||
let otherPerm = Int(mode) & 0o7
|
||||
|
||||
let ownerRights = rightsFromModeBits(ownerPerm, for: fileOrDirectory)
|
||||
let groupRights = rightsFromModeBits(groupPerm,
|
||||
sticky: (mode & 0o1000) != 0,
|
||||
for: fileOrDirectory)
|
||||
let otherRights = rightsFromModeBits(otherPerm,
|
||||
sticky: (mode & 0o1000) != 0,
|
||||
for: fileOrDirectory)
|
||||
|
||||
// If group or other permissions are *more* permissive, then we need
|
||||
// some DENY ACEs as well to implement the expected semantics
|
||||
let ownerDenyRights = ((ownerRights ^ groupRights) & groupRights) |
|
||||
((ownerRights ^ otherRights) & otherRights)
|
||||
let groupDenyRights = (groupRights ^ otherRights) & otherRights
|
||||
|
||||
var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1))
|
||||
var everyone: PSID? = nil
|
||||
|
||||
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
|
||||
SECURITY_WORLD_RID,
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
&everyone) else {
|
||||
return nil
|
||||
}
|
||||
guard let everyone = everyone else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
FreeSid(everyone)
|
||||
}
|
||||
|
||||
let hToken = GetCurrentThreadEffectiveToken()!
|
||||
|
||||
guard let pTokenUser = getTokenInformation(of: TOKEN_USER.self,
|
||||
hToken: hToken,
|
||||
ticTokenClass: TokenUser) else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
pTokenUser.deallocate()
|
||||
}
|
||||
|
||||
guard let pTokenPrimaryGroup = getTokenInformation(
|
||||
of: TOKEN_PRIMARY_GROUP.self,
|
||||
hToken: hToken,
|
||||
ticTokenClass: TokenPrimaryGroup
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
pTokenPrimaryGroup.deallocate()
|
||||
}
|
||||
|
||||
let user = pTokenUser.pointee.User.Sid!
|
||||
let group = pTokenPrimaryGroup.pointee.PrimaryGroup!
|
||||
|
||||
var eas = [
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: ownerRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_USER,
|
||||
ptstrName:
|
||||
user.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
),
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: groupRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
group.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
),
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: otherRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
everyone.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
)
|
||||
]
|
||||
|
||||
if ownerDenyRights != 0 {
|
||||
eas.append(
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: ownerDenyRights,
|
||||
grfAccessMode: DENY_ACCESS,
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_USER,
|
||||
ptstrName:
|
||||
user.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
if groupDenyRights != 0 {
|
||||
eas.append(
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: groupDenyRights,
|
||||
grfAccessMode: DENY_ACCESS,
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
group.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var pACL: PACL? = nil
|
||||
guard SetEntriesInAclW(ULONG(eas.count),
|
||||
&eas,
|
||||
nil,
|
||||
&pACL) == ERROR_SUCCESS else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
LocalFree(pACL)
|
||||
}
|
||||
|
||||
// Create the security descriptor, making sure that inherited ACEs don't
|
||||
// take effect, since that wouldn't match the behaviour of mode bits.
|
||||
var descriptor = SECURITY_DESCRIPTOR()
|
||||
|
||||
guard InitializeSecurityDescriptor(&descriptor,
|
||||
SECURITY_DESCRIPTOR_REVISION) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard SetSecurityDescriptorControl(&descriptor,
|
||||
SE_DACL_PROTECTED,
|
||||
SE_DACL_PROTECTED)
|
||||
&& SetSecurityDescriptorOwner(&descriptor, user, false)
|
||||
&& SetSecurityDescriptorGroup(&descriptor, group, false)
|
||||
&& SetSecurityDescriptorDacl(&descriptor,
|
||||
true,
|
||||
pACL,
|
||||
false) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Make it self-contained (up to this point it uses pointers)
|
||||
var dwRelativeSize = DWORD(0)
|
||||
|
||||
guard !MakeSelfRelativeSD(&descriptor, nil, &dwRelativeSize)
|
||||
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let pDescriptor = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: Int(dwRelativeSize),
|
||||
alignment: MemoryLayout<SECURITY_DESCRIPTOR>.alignment
|
||||
).assumingMemoryBound(to: SECURITY_DESCRIPTOR.self)
|
||||
|
||||
guard MakeSelfRelativeSD(&descriptor, pDescriptor, &dwRelativeSize) else {
|
||||
pDescriptor.deallocate()
|
||||
return nil
|
||||
}
|
||||
|
||||
return UnsafeMutableRawPointer(pDescriptor)
|
||||
}
|
||||
|
||||
fileprivate struct DecodedOpenFlags {
|
||||
var dwDesiredAccess: DWORD
|
||||
var dwCreationDisposition: DWORD
|
||||
var bInheritHandle: WindowsBool
|
||||
var dwFlagsAndAttributes: DWORD
|
||||
|
||||
init(_ oflag: Int32) {
|
||||
switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) {
|
||||
case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC:
|
||||
dwCreationDisposition = CREATE_NEW
|
||||
case _O_CREAT:
|
||||
dwCreationDisposition = OPEN_ALWAYS
|
||||
case _O_CREAT | _O_TRUNC:
|
||||
dwCreationDisposition = CREATE_ALWAYS
|
||||
case _O_TRUNC:
|
||||
dwCreationDisposition = TRUNCATE_EXISTING
|
||||
default:
|
||||
dwCreationDisposition = OPEN_EXISTING
|
||||
}
|
||||
|
||||
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
|
||||
// on Windows; in particular, _O_RDONLY is zero, which means we can't
|
||||
// test for it by AND-ing.
|
||||
dwDesiredAccess = 0
|
||||
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
|
||||
case _O_RDONLY:
|
||||
dwDesiredAccess |= GENERIC_READ
|
||||
case _O_WRONLY:
|
||||
dwDesiredAccess |= GENERIC_WRITE
|
||||
case _O_RDWR:
|
||||
dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
bInheritHandle = WindowsBool((oflag & _O_NOINHERIT) == 0)
|
||||
|
||||
dwFlagsAndAttributes = 0
|
||||
if (oflag & _O_SEQUENTIAL) != 0 {
|
||||
dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN
|
||||
}
|
||||
if (oflag & _O_RANDOM) != 0 {
|
||||
dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS
|
||||
}
|
||||
if (oflag & _O_TEMPORARY) != 0 {
|
||||
dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE
|
||||
}
|
||||
|
||||
if (oflag & _O_SHORT_LIVED) != 0 {
|
||||
dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY
|
||||
} else {
|
||||
dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,18 +1,24 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2022 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2022 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if false && swift(>=5.8) && $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
#if canImport(Darwin, _version: 310)
|
||||
import Darwin.Mach
|
||||
#else
|
||||
@preconcurrency import Darwin.Mach
|
||||
#endif
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
public protocol MachPortRight {}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
@inlinable
|
||||
internal func _machPrecondition(
|
||||
file: StaticString = #file,
|
||||
@@ -24,9 +30,10 @@ internal func _machPrecondition(
|
||||
precondition(kr == expected, file: file, line: line)
|
||||
}
|
||||
|
||||
@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@available(System 1.4.0, *)
|
||||
@frozen
|
||||
public enum Mach {
|
||||
@available(System 1.4.0, *)
|
||||
public struct Port<RightType: MachPortRight>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _name: mach_port_name_t
|
||||
@@ -48,11 +55,15 @@ public enum Mach {
|
||||
///
|
||||
/// This initializer makes a syscall to guard the right.
|
||||
public init(name: mach_port_name_t) {
|
||||
precondition(name != mach_port_name_t(MACH_PORT_NULL), "Mach.Port cannot be initialized with MACH_PORT_NULL")
|
||||
precondition(name != mach_port_name_t(MACH_PORT_NULL),
|
||||
"Mach.Port cannot be initialized with MACH_PORT_NULL")
|
||||
self._name = name
|
||||
|
||||
if RightType.self == ReceiveRight.self {
|
||||
precondition(name != 0xFFFFFFFF /* MACH_PORT_DEAD */, "Receive rights cannot be dead names")
|
||||
precondition(
|
||||
_name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */,
|
||||
"Receive rights cannot be dead names"
|
||||
)
|
||||
|
||||
let secret = mach_port_context_t(arc4random())
|
||||
_machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0))
|
||||
@@ -81,17 +92,20 @@ public enum Mach {
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _name == 0xFFFFFFFF /* MACH_PORT_DEAD */ {
|
||||
precondition(RightType.self != ReceiveRight.self, "Receive rights cannot be dead names")
|
||||
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_DEAD_NAME, -1))
|
||||
if RightType.self == ReceiveRight.self {
|
||||
precondition(
|
||||
_name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */,
|
||||
"Receive rights cannot be dead names"
|
||||
)
|
||||
_machPrecondition(
|
||||
mach_port_destruct(mach_task_self_, _name, 0, _context)
|
||||
)
|
||||
} else {
|
||||
if RightType.self == ReceiveRight.self {
|
||||
_machPrecondition(mach_port_destruct(mach_task_self_, _name, -1, _context))
|
||||
} else if RightType.self == SendRight.self {
|
||||
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND, -1))
|
||||
} else if RightType.self == SendOnceRight.self {
|
||||
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND_ONCE, -1))
|
||||
}
|
||||
assert(
|
||||
RightType.self == SendRight.self ||
|
||||
RightType.self == SendOnceRight.self
|
||||
)
|
||||
_machPrecondition(mach_port_deallocate(mach_task_self_, _name))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,6 +137,7 @@ public enum Mach {
|
||||
public struct SendOnceRight: MachPortRight {}
|
||||
}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// Transfer ownership of an existing, unmanaged, but already guarded,
|
||||
/// Mach port right into a Mach.Port by name.
|
||||
@@ -134,7 +149,10 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
///
|
||||
/// The underlying port right will be automatically deallocated when
|
||||
/// the Mach.Port object is destroyed.
|
||||
@available(System 1.4.0, *)
|
||||
public init(name: mach_port_name_t, context: mach_port_context_t) {
|
||||
precondition(name != mach_port_name_t(MACH_PORT_NULL),
|
||||
"Mach.Port cannot be initialized with MACH_PORT_NULL")
|
||||
self._name = name
|
||||
self._context = context
|
||||
}
|
||||
@@ -145,11 +163,12 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// This initializer will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public init() {
|
||||
var storage: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
|
||||
withUnsafeMutablePointer(to: &storage) { storage in
|
||||
_machPrecondition(mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage))
|
||||
}
|
||||
_machPrecondition(
|
||||
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &storage)
|
||||
)
|
||||
|
||||
// name-only init will guard ReceiveRights
|
||||
self.init(name: storage)
|
||||
@@ -166,10 +185,12 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
@inlinable
|
||||
public __consuming func relinquish(
|
||||
@available(System 1.4.0, *)
|
||||
public consuming func relinquish(
|
||||
) -> (name: mach_port_name_t, context: mach_port_context_t) {
|
||||
return (name: _name, context: _context)
|
||||
let destructured = (name: _name, context: _context)
|
||||
discard self
|
||||
return destructured
|
||||
}
|
||||
|
||||
/// Remove guard and transfer ownership of the underlying port right to
|
||||
@@ -187,9 +208,11 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract
|
||||
/// the context value along with the port name.
|
||||
@inlinable
|
||||
public __consuming func unguardAndRelinquish() -> mach_port_name_t {
|
||||
_machPrecondition(mach_port_unguard(mach_task_self_, _name, _context))
|
||||
return _name
|
||||
@available(System 1.4.0, *)
|
||||
public consuming func unguardAndRelinquish() -> mach_port_name_t {
|
||||
let (name, context) = self.relinquish()
|
||||
_machPrecondition(mach_port_unguard(mach_task_self_, name, context))
|
||||
return name
|
||||
}
|
||||
|
||||
/// Borrow access to the port name in a block that can perform
|
||||
@@ -202,6 +225,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// The body block may optionally return something, which will then be
|
||||
/// returned to the caller of withBorrowedName.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func withBorrowedName<ReturnType>(
|
||||
body: (mach_port_name_t, mach_port_context_t) -> ReturnType
|
||||
) -> ReturnType {
|
||||
@@ -215,22 +239,21 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// This function will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func makeSendOnceRight() -> Mach.Port<Mach.SendOnceRight> {
|
||||
// send once rights do not coalesce
|
||||
var newRight: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
|
||||
var newRightType: mach_port_type_t = MACH_PORT_TYPE_NONE
|
||||
|
||||
withUnsafeMutablePointer(to: &newRight) { newRight in
|
||||
withUnsafeMutablePointer(to: &newRightType) { newRightType in
|
||||
_machPrecondition(
|
||||
mach_port_extract_right(mach_task_self_,
|
||||
_name,
|
||||
mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE),
|
||||
newRight,
|
||||
newRightType)
|
||||
)
|
||||
}
|
||||
}
|
||||
_machPrecondition(
|
||||
mach_port_extract_right(
|
||||
mach_task_self_,
|
||||
_name,
|
||||
mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE),
|
||||
&newRight,
|
||||
&newRightType
|
||||
)
|
||||
)
|
||||
|
||||
// The value of newRight is validated by the Mach.Port initializer
|
||||
precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE)
|
||||
@@ -245,11 +268,16 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// This function will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func makeSendRight() -> Mach.Port<Mach.SendRight> {
|
||||
let how = MACH_MSG_TYPE_MAKE_SEND
|
||||
|
||||
// name is the same because send and recv rights are coalesced
|
||||
_machPrecondition(mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how)))
|
||||
_machPrecondition(
|
||||
mach_port_insert_right(
|
||||
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
|
||||
)
|
||||
)
|
||||
|
||||
return Mach.Port(name: _name)
|
||||
}
|
||||
@@ -258,14 +286,24 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
///
|
||||
/// Each get/set of this property makes a syscall.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public var makeSendCount: mach_port_mscount_t {
|
||||
get {
|
||||
var status: mach_port_status = mach_port_status()
|
||||
var size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout<mach_port_status>.size / MemoryLayout<natural_t>.size)
|
||||
withUnsafeMutablePointer(to: &size) { size in
|
||||
withUnsafeMutablePointer(to: &status) { status in
|
||||
let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1)
|
||||
_machPrecondition(mach_port_get_attributes(mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, size))
|
||||
var size = mach_msg_type_number_t(
|
||||
MemoryLayout<mach_port_status>.size / MemoryLayout<natural_t>.size
|
||||
)
|
||||
|
||||
withUnsafeMutablePointer(to: &status) {
|
||||
[ _name = self._name ] in
|
||||
let status = UnsafeMutableBufferPointer(start: $0, count: 1)
|
||||
status.withMemoryRebound(to: integer_t.self) {
|
||||
let info = $0.baseAddress
|
||||
_machPrecondition(
|
||||
mach_port_get_attributes(
|
||||
mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, &size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return status.mps_mscount
|
||||
@@ -277,6 +315,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
extension Mach.Port where RightType == Mach.SendRight {
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
@@ -287,9 +326,11 @@ extension Mach.Port where RightType == Mach.SendRight {
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
@inlinable
|
||||
public __consuming func relinquish() -> mach_port_name_t {
|
||||
return _name
|
||||
@available(System 1.4.0, *)
|
||||
public consuming func relinquish() -> mach_port_name_t {
|
||||
let name = _name
|
||||
discard self
|
||||
return name
|
||||
}
|
||||
|
||||
/// Create another send right from a given send right.
|
||||
@@ -300,12 +341,15 @@ extension Mach.Port where RightType == Mach.SendRight {
|
||||
/// receiving side has been deallocated, then copySendRight() will throw
|
||||
/// a Mach.PortRightError.deadName error.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func copySendRight() throws -> Mach.Port<Mach.SendRight> {
|
||||
let how = MACH_MSG_TYPE_COPY_SEND
|
||||
|
||||
// name is the same because send rights are coalesced
|
||||
let kr = mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how))
|
||||
if kr == KERN_INVALID_CAPABILITY {
|
||||
let kr = mach_port_insert_right(
|
||||
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
|
||||
)
|
||||
if kr == KERN_INVALID_NAME || kr == KERN_INVALID_CAPABILITY {
|
||||
throw Mach.PortRightError.deadName
|
||||
}
|
||||
_machPrecondition(kr)
|
||||
@@ -314,7 +358,7 @@ extension Mach.Port where RightType == Mach.SendRight {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
extension Mach.Port where RightType == Mach.SendOnceRight {
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
@@ -325,9 +369,11 @@ extension Mach.Port where RightType == Mach.SendOnceRight {
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
@inlinable
|
||||
public __consuming func relinquish() -> mach_port_name_t {
|
||||
return _name
|
||||
@available(System 1.4.0, *)
|
||||
public consuming func relinquish() -> mach_port_name_t {
|
||||
let name = _name
|
||||
discard self
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
@@ -20,6 +20,7 @@ extension String {
|
||||
/// This means that, depending on the semantics of the specific platform,
|
||||
/// conversion to a string and back might result in a value that's different
|
||||
/// from the original platform string.
|
||||
@_disfavoredOverload
|
||||
public init(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_errorCorrectingPlatformString: platformString)
|
||||
}
|
||||
@@ -164,7 +165,7 @@ extension String {
|
||||
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension CInterop.PlatformChar {
|
||||
internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
#if os(Windows)
|
||||
@@ -175,7 +176,7 @@ extension CInterop.PlatformChar {
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
@available(System 0.0.2, *)
|
||||
extension CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
internal var _platformChar: CInterop.PlatformChar {
|
||||
#if os(Windows)
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
extension CInterop {
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// The C `int` type
|
||||
public typealias Signal = CInt
|
||||
#endif
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// hangup
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGHUP: CInterop.Signal { SIGHUP }
|
||||
/// interrupt
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGINT: CInterop.Signal { SIGINT }
|
||||
/// quit
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGQUIT: CInterop.Signal { SIGQUIT }
|
||||
/// illegal instruction (not reset when caught)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGILL: CInterop.Signal { SIGILL }
|
||||
/// trace trap (not reset when caught)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGTRAP: CInterop.Signal { SIGTRAP }
|
||||
/// abort()
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGABRT: CInterop.Signal { SIGABRT }
|
||||
#if false
|
||||
/// pollable event
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGPOLL: CInterop.Signal { SIGPOLL }
|
||||
#endif
|
||||
/// compatibility
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGIOT: CInterop.Signal { SIGIOT }
|
||||
/// EMT instruction
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGEMT: CInterop.Signal { SIGEMT }
|
||||
/// floating point exception
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGFPE: CInterop.Signal { SIGFPE }
|
||||
/// kill (cannot be caught or ignored)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGKILL: CInterop.Signal { SIGKILL }
|
||||
/// bus error
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGBUS: CInterop.Signal { SIGBUS }
|
||||
/// segmentation violation
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGSEGV: CInterop.Signal { SIGSEGV }
|
||||
/// bad argument to system call
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGSYS: CInterop.Signal { SIGSYS }
|
||||
/// write on a pipe with no one to read it
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGPIPE: CInterop.Signal { SIGPIPE }
|
||||
/// alarm clock
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGALRM: CInterop.Signal { SIGALRM }
|
||||
/// software termination signal from kill
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGTERM: CInterop.Signal { SIGTERM }
|
||||
/// urgent condition on IO channel
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGURG: CInterop.Signal { SIGURG }
|
||||
/// sendable stop signal not from tty
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGSTOP: CInterop.Signal { SIGSTOP }
|
||||
/// stop signal from tty
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGTSTP: CInterop.Signal { SIGTSTP }
|
||||
/// continue a stopped process
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGCONT: CInterop.Signal { SIGCONT }
|
||||
/// to parent on child stop or exit
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGCHLD: CInterop.Signal { SIGCHLD }
|
||||
/// to readers pgrp upon background tty read
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGTTIN: CInterop.Signal { SIGTTIN }
|
||||
/// like TTIN for output if (tp->t_local<OSTOP)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGTTOU: CInterop.Signal { SIGTTOU }
|
||||
/// input/output possible signal
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGIO: CInterop.Signal { SIGIO }
|
||||
/// exceeded CPU time limit
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGXCPU: CInterop.Signal { SIGXCPU }
|
||||
/// exceeded file size limit
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGXFSZ: CInterop.Signal { SIGXFSZ }
|
||||
/// virtual time alarm
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGVTALRM: CInterop.Signal { SIGVTALRM }
|
||||
/// profiling time alarm
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGPROF: CInterop.Signal { SIGPROF }
|
||||
/// window size changes
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGWINCH: CInterop.Signal { SIGWINCH }
|
||||
/// information request
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGINFO: CInterop.Signal { SIGINFO }
|
||||
/// user defined signal 1
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGUSR1: CInterop.Signal { SIGUSR1 }
|
||||
/// user defined signal 2
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SIGUSR2: CInterop.Signal { SIGUSR2 }
|
||||
#endif
|
||||
@@ -1,296 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
public struct Signal: RawRepresentable {
|
||||
/// The raw C signal value.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.Signal
|
||||
|
||||
/// Creates a strongly typed signal from a raw C signal value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Signal) { self.rawValue = rawValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
extension Signal {
|
||||
/// The corresponding C signal is `SIGHUP`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var hangup: Self { Self(rawValue: _SIGHUP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "hangup")
|
||||
internal static var SIGHUP: Self { hangup }
|
||||
|
||||
/// The corresponding C signal is `SIGINT`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var interrupt: Self { Self(rawValue: _SIGINT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "interrupt")
|
||||
internal static var SIGINT: Self { interrupt }
|
||||
|
||||
/// The corresponding C signal is `SIGQUIT`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var quit: Self { Self(rawValue: _SIGQUIT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "quit")
|
||||
internal static var SIGQUIT: Self { quit }
|
||||
|
||||
/// The corresponding C signal is `SIGILL`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var illegalInstruction: Self { Self(rawValue: _SIGILL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "illegalInstruction")
|
||||
internal static var SIGILL: Self { illegalInstruction }
|
||||
|
||||
/// The corresponding C signal is `SIGTRAP`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var trap: Self { Self(rawValue: _SIGTRAP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "trap")
|
||||
internal static var SIGTRAP: Self { trap }
|
||||
|
||||
/// The corresponding C signal is `SIGABRT`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var abort: Self { Self(rawValue: _SIGABRT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "abort")
|
||||
internal static var SIGABRT: Self { abort }
|
||||
|
||||
#if false
|
||||
/// The corresponding C signal is `SIGPOLL`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var pollableEvent: Self { Self(rawValue: _SIGPOLL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "pollableEvent")
|
||||
internal static var SIGPOLL: Self { pollableEvent }
|
||||
#endif
|
||||
|
||||
/// The corresponding C signal is `SIGIOT`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, renamed: "abort")
|
||||
internal static var inputOutputTrap: Self { Self(rawValue: _SIGIOT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated)
|
||||
@available(*, unavailable, renamed: "inputOutputTrap")
|
||||
internal static var SIGIOT: Self { inputOutputTrap }
|
||||
|
||||
/// The corresponding C signal is `SIGEMT`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var emulatorTrap: Self { Self(rawValue: _SIGEMT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "emulatorTrap")
|
||||
internal static var SIGEMT: Self { emulatorTrap }
|
||||
|
||||
/// The corresponding C signal is `SIGFPE`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var floatingPointException: Self { Self(rawValue: _SIGFPE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "floatingPointException")
|
||||
internal static var SIGFPE: Self { floatingPointException }
|
||||
|
||||
/// The corresponding C signal is `SIGKILL`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var kill: Self { Self(rawValue: _SIGKILL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "kill")
|
||||
internal static var SIGKILL: Self { kill }
|
||||
|
||||
/// The corresponding C signal is `SIGBUS`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var busError: Self { Self(rawValue: _SIGBUS) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "busError")
|
||||
internal static var SIGBUS: Self { busError }
|
||||
|
||||
/// The corresponding C signal is `SIGSEGV`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var segmentationViolation: Self { Self(rawValue: _SIGSEGV) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "segmentationViolation")
|
||||
internal static var SIGSEGV: Self { segmentationViolation }
|
||||
|
||||
/// The corresponding C signal is `SIGSYS`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var badSystemCall: Self { Self(rawValue: _SIGSYS) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "badSystemCall")
|
||||
internal static var SIGSYS: Self { badSystemCall }
|
||||
|
||||
/// The corresponding C signal is `SIGPIPE`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var brokenPipe: Self { Self(rawValue: _SIGPIPE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "brokenPipe")
|
||||
internal static var SIGPIPE: Self { brokenPipe }
|
||||
|
||||
/// The corresponding C signal is `SIGALRM`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var alarm: Self { Self(rawValue: _SIGALRM) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "alarm")
|
||||
internal static var SIGALRM: Self { alarm }
|
||||
|
||||
/// The corresponding C signal is `SIGTERM`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var terminationRequest: Self { Self(rawValue: _SIGTERM) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "terminationRequest")
|
||||
internal static var SIGTERM: Self { terminationRequest }
|
||||
|
||||
/// The corresponding C signal is `SIGURG`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var urgentInputOutput: Self { Self(rawValue: _SIGURG) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "urgentInputOutput")
|
||||
internal static var SIGURG: Self { urgentInputOutput }
|
||||
|
||||
/// The corresponding C signal is `SIGSTOP`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var stop: Self { Self(rawValue: _SIGSTOP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "stop")
|
||||
internal static var SIGSTOP: Self { stop }
|
||||
|
||||
/// The corresponding C signal is `SIGTSTP`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var interactiveStop: Self { Self(rawValue: _SIGTSTP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "interactiveStop")
|
||||
internal static var SIGTSTP: Self { interactiveStop }
|
||||
|
||||
/// The corresponding C signal is `SIGCONT`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var `continue`: Self { Self(rawValue: _SIGCONT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "continue")
|
||||
internal static var SIGCONT: Self { `continue` }
|
||||
|
||||
/// The corresponding C signal is `SIGCHLD`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var childStopOrExit: Self { Self(rawValue: _SIGCHLD) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "childStopOrExit")
|
||||
internal static var SIGCHLD: Self { childStopOrExit }
|
||||
|
||||
/// The corresponding C signal is `SIGTTIN`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var backgroundRead: Self { Self(rawValue: _SIGTTIN) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "backgroundRead")
|
||||
internal static var SIGTTIN: Self { backgroundRead }
|
||||
|
||||
/// The corresponding C signal is `SIGTTOU`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var backgroundWrite: Self { Self(rawValue: _SIGTTOU) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "backgroundWrite")
|
||||
internal static var SIGTTOU: Self { backgroundWrite }
|
||||
|
||||
/// The corresponding C signal is `SIGIO`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var possibleInputOutput: Self { Self(rawValue: _SIGIO) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "possibleInputOutput")
|
||||
internal static var SIGIO: Self { possibleInputOutput }
|
||||
|
||||
/// The corresponding C signal is `SIGXCPU`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var exceededCPUTimeLimit: Self { Self(rawValue: _SIGXCPU) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exceededCPUTimeLimit")
|
||||
internal static var SIGXCPU: Self { exceededCPUTimeLimit }
|
||||
|
||||
/// The corresponding C signal is `SIGXFSZ`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var exceededFileSizeLimit: Self { Self(rawValue: _SIGXFSZ) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exceededFileSizeLimit")
|
||||
internal static var SIGXFSZ: Self { exceededFileSizeLimit }
|
||||
|
||||
/// The corresponding C signal is `SIGVTALRM`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var virtualAlarm: Self { Self(rawValue: _SIGVTALRM) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "virtualAlarm")
|
||||
internal static var SIGVTALRM: Self { virtualAlarm }
|
||||
|
||||
/// The corresponding C signal is `SIGPROF`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var profilingAlarm: Self { Self(rawValue: _SIGPROF) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "profilingAlarm")
|
||||
internal static var SIGPROF: Self { profilingAlarm }
|
||||
|
||||
/// The corresponding C signal is `SIGWINCH`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var windowSizeChange: Self { Self(rawValue: _SIGWINCH) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "windowSizeChange")
|
||||
internal static var SIGWINCH: Self { windowSizeChange }
|
||||
|
||||
/// The corresponding C signal is `SIGINFO`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var informationRequest: Self { Self(rawValue: _SIGINFO) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "informationRequest")
|
||||
internal static var SIGINFO: Self { informationRequest }
|
||||
|
||||
/// The corresponding C signal is `SIGUSR1`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var userDefined1: Self { Self(rawValue: _SIGUSR1) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "userDefined1")
|
||||
internal static var SIGUSR1: Self { userDefined1 }
|
||||
|
||||
/// The corresponding C signal is `SIGUSR2`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var userDefined2: Self { Self(rawValue: _SIGUSR2) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "userDefined2")
|
||||
internal static var SIGUSR2: Self { userDefined2 }
|
||||
}
|
||||
#endif
|
||||
@@ -1,18 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
public struct SignalSet {
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// File.swift
|
||||
//
|
||||
//
|
||||
// Created by Rauhul Varma on 6/16/23.
|
||||
//
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// FIXME: this is wrong and should be done with wrapping fcntrl
|
||||
// FIXME: go through and figure out the right way to express `at` methods
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileDescriptor {
|
||||
public struct ControlFlags {
|
||||
let rawValue: Int32
|
||||
// Test stub
|
||||
public static var none: ControlFlags = ControlFlags(rawValue: 0)
|
||||
// Out of scope of this sketch
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,234 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
|
||||
// FIXME: Document
|
||||
@frozen
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
public struct FileFlags: OptionSet, Hashable, Codable {
|
||||
/// The raw C file flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.FileFlags
|
||||
|
||||
/// Create a strongly-typed file flags from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.FileFlags) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInterop.FileFlags) { self.init(rawValue: raw) }
|
||||
|
||||
/// Do not dump the file. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NODUMP`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDump: FileFlags { FileFlags(_UF_NODUMP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "noDump")
|
||||
public static var UF_NODUMP: FileFlags { noDump }
|
||||
|
||||
/// The file may not be changed. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_IMMUTABLE`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var immutable: FileFlags { FileFlags(_UF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "immutable")
|
||||
public static var UF_IMMUTABLE: FileFlags { immutable }
|
||||
|
||||
/// The file may only be appended to. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_APPEND`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var appendOnly: FileFlags { FileFlags(_UF_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "appendOnly")
|
||||
public static var UF_APPEND: FileFlags { appendOnly }
|
||||
|
||||
/// The directory is opaque when viewed through a union stack. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OPAQUE`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var opaque: FileFlags { FileFlags(_UF_OPAQUE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "opaque")
|
||||
public static var UF_OPAQUE: FileFlags { opaque }
|
||||
|
||||
// #if os(FreeBSD)
|
||||
// /// The file may not be removed or renamed. Modifiable by file owner or super-user.
|
||||
// ///
|
||||
// /// The corresponding C constant is `UF_NOUNLINK`
|
||||
// @_alwaysEmitIntoClient
|
||||
// public static var noUnlink: FileFlags { FileFlags(_UF_NOUNLINK) }
|
||||
//
|
||||
// @_alwaysEmitIntoClient
|
||||
// @available(*, unavailable, renamed: "noUnlink")
|
||||
// public static var UF_NOUNLINK: FileFlags { noUnlink }
|
||||
// #endif
|
||||
|
||||
/// The file is compressed (some file-systems). Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_COMPRESSED`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var compressed: FileFlags { FileFlags(_UF_COMPRESSED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "compressed")
|
||||
public static var UF_COMPRESSED: FileFlags { compressed }
|
||||
|
||||
/// No notifications will be issued for deletes or renames. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_TRACKED`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tracked: FileFlags { FileFlags(_UF_TRACKED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "tracked")
|
||||
public static var UF_TRACKED: FileFlags { tracked }
|
||||
|
||||
/// The file requires entitlement required for reading and writing. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_DATAVAULT`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataVault: FileFlags { FileFlags(_UF_DATAVAULT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "dataVault")
|
||||
public static var UF_DATAVAULT: FileFlags { dataVault }
|
||||
|
||||
/// The file or directory is not intended to be displayed to the user. Modifiable by file owner or super-user.
|
||||
///
|
||||
/// The corresponding C constant is `UF_HIDDEN`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var hidden: FileFlags { FileFlags(_UF_HIDDEN) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "hidden")
|
||||
public static var UF_HIDDEN: FileFlags { hidden }
|
||||
|
||||
/// The file has been archived. Only modifiable by the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `SF_ARCHIVED`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var superUserArchived: FileFlags { FileFlags(_SF_ARCHIVED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "superUserArchived")
|
||||
public static var SF_ARCHIVED: FileFlags { superUserArchived }
|
||||
|
||||
/// The file may not be changed. Only modifiable by the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `SF_IMMUTABLE`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var superUserImmutable: FileFlags { FileFlags(_SF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "superUserImmutable")
|
||||
public static var SF_IMMUTABLE: FileFlags { superUserImmutable }
|
||||
|
||||
/// The file may only be appended to. Only modifiable by the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `SF_APPEND`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var superUserAppend: FileFlags { FileFlags(_SF_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "superUserAppend")
|
||||
public static var SF_APPEND: FileFlags { superUserAppend }
|
||||
|
||||
/// The file requires entitlement required for reading and writing. Only modifiable by the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `SF_RESTRICTED`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var superUserRestricted: FileFlags { FileFlags(_SF_RESTRICTED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "superUserRestricted")
|
||||
public static var SF_RESTRICTED: FileFlags { superUserRestricted }
|
||||
|
||||
/// The file may not be removed, renamed or mounted on. Only modifiable by the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `SF_NOUNLINK`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var superUserNoUnlink: FileFlags { FileFlags(_SF_NOUNLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "superUserNoUnlink")
|
||||
public static var SF_NOUNLINK: FileFlags { superUserNoUnlink }
|
||||
|
||||
// #if os(FreeBSD)
|
||||
// /// The file is a snapshot file. Only modifiable by the super-user.
|
||||
// ///
|
||||
// /// The corresponding C constant is `SF_SNAPSHOT`
|
||||
// @_alwaysEmitIntoClient
|
||||
// public static var superUserSnapshot: FileFlags { FileFlags(_SF_SNAPSHOT) }
|
||||
//
|
||||
// @_alwaysEmitIntoClient
|
||||
// @available(*, unavailable, renamed: "superUserSnapshot")
|
||||
// public static var SF_SNAPSHOT: FileFlags { superUserSnapshot }
|
||||
// #endif
|
||||
|
||||
/// The file is a firmlink. Only modifiable by the super-user.
|
||||
///
|
||||
/// The corresponding C constant is `SF_FIRMLINK`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var superUserFirmlink: FileFlags { FileFlags(_SF_FIRMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "superUserFirmlink")
|
||||
public static var SF_FIRMLINK: FileFlags { superUserFirmlink }
|
||||
|
||||
/// The file is a dataless placeholder. The system will attempt to materialize it when accessed according to the dataless file materialization policy of the accessing thread or process. Cannot be modified in user-space.
|
||||
///
|
||||
/// The corresponding C constant is `SF_DATALESS`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var kernelDataless: FileFlags { FileFlags(_SF_DATALESS) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "kernelDataless")
|
||||
public static var SF_DATALESS: FileFlags { kernelDataless }
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileFlags
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
/// A textual representation of the file permissions.
|
||||
@inline(never)
|
||||
public var description: String {
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.noDump, ".noDump"),
|
||||
(.immutable, ".immutable"),
|
||||
(.appendOnly, ".appendOnly"),
|
||||
(.opaque, ".opaque"),
|
||||
(.compressed, ".compressed"),
|
||||
(.tracked, ".tracked"),
|
||||
(.dataVault, ".dataVault"),
|
||||
(.hidden, ".hidden"),
|
||||
(.superUserArchived, ".superUserArchived"),
|
||||
(.superUserImmutable, ".superUserImmutable"),
|
||||
(.superUserAppend, ".superUserAppend"),
|
||||
(.superUserRestricted, ".superUserRestricted"),
|
||||
(.superUserNoUnlink, ".superUserNoUnlink"),
|
||||
(.superUserFirmlink, ".superUserFirmlink"),
|
||||
(.kernelDataless, ".kernelDataless"),
|
||||
]
|
||||
|
||||
return _buildDescription(descriptions)
|
||||
}
|
||||
|
||||
/// A textual representation of the file permissions, suitable for debugging.
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
|
||||
// FIXME: should the subtypes of Mode mask their rawValues to only allow their bits to be changed?
|
||||
|
||||
/// The superset of access permissions and type for a file.
|
||||
///
|
||||
/// The following example creates an instance of the `FileMode` structure
|
||||
/// from a raw octal literal and reads the file type from it:
|
||||
///
|
||||
/// let mode = FileMode(rawValue: 0o140000)
|
||||
/// mode.type == .socket // true
|
||||
@frozen
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
public struct FileMode: RawRepresentable {
|
||||
/// The raw C file mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Create a strongly-typed file mode from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
/// Subset of mode for accessing and modifying file permissions.
|
||||
@_alwaysEmitIntoClient
|
||||
public var permissions: FilePermissions {
|
||||
get { FilePermissions(rawValue: rawValue & _MODE_PERMISSIONS) }
|
||||
set { rawValue = (rawValue & ~_MODE_PERMISSIONS) | (newValue.rawValue & _MODE_PERMISSIONS ) }
|
||||
}
|
||||
|
||||
/// Subset of mode for accessing and modifying file type.
|
||||
@_alwaysEmitIntoClient
|
||||
public var type: FileType {
|
||||
get { FileType(rawValue: rawValue & _MODE_TYPE) }
|
||||
set { rawValue = (rawValue & ~_MODE_TYPE) | (newValue.rawValue & _MODE_TYPE ) }
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
|
||||
// FIXME: Document
|
||||
@frozen
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
public struct FileStatus: RawRepresentable {
|
||||
/// The raw C file status.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.Stat
|
||||
|
||||
/// Create a strongly-typed file status from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Stat) { self.rawValue = rawValue }
|
||||
|
||||
// FIXME: replace with swift type DeviceID that splits out major/minor
|
||||
/// ID of device containing file.
|
||||
@_alwaysEmitIntoClient
|
||||
public var deviceID: CInterop.DeviceID { rawValue.st_dev }
|
||||
|
||||
/// Mode of file.
|
||||
@_alwaysEmitIntoClient
|
||||
public var mode: FileMode { FileMode(rawValue: rawValue.st_mode) }
|
||||
|
||||
/// Number of hard links.
|
||||
@_alwaysEmitIntoClient
|
||||
public var hardLinkCount: CInterop.NumberOfLinks { rawValue.st_nlink }
|
||||
|
||||
/// File serial number.
|
||||
@_alwaysEmitIntoClient
|
||||
public var inodeNumber: CInterop.INodeNumber { rawValue.st_ino }
|
||||
|
||||
/// User ID of the file.
|
||||
@_alwaysEmitIntoClient
|
||||
public var userID: CInterop.UserID { rawValue.st_uid }
|
||||
|
||||
/// Group ID of the file.
|
||||
@_alwaysEmitIntoClient
|
||||
public var groupID: CInterop.GroupID { rawValue.st_gid }
|
||||
|
||||
/// Device ID.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rDeviceID: CInterop.DeviceID { rawValue.st_rdev }
|
||||
|
||||
/// Time of last access.
|
||||
@_alwaysEmitIntoClient
|
||||
public var accessTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_atimespec) }
|
||||
|
||||
/// Time of last data modification.
|
||||
@_alwaysEmitIntoClient
|
||||
public var modifyTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_mtimespec) }
|
||||
|
||||
/// Time of last status change.
|
||||
@_alwaysEmitIntoClient
|
||||
public var statusChangeTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_ctimespec) }
|
||||
|
||||
/// Time of file creation.
|
||||
@_alwaysEmitIntoClient
|
||||
public var creationTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_birthtimespec) }
|
||||
|
||||
/// File size, in bytes.
|
||||
@_alwaysEmitIntoClient
|
||||
public var fileSize: CInterop.Offset { rawValue.st_size }
|
||||
|
||||
/// Blocks allocated for file.
|
||||
@_alwaysEmitIntoClient
|
||||
public var blockCount: CInterop.BlockCount { rawValue.st_blocks }
|
||||
|
||||
/// Optimal block size for I/O.
|
||||
@_alwaysEmitIntoClient
|
||||
public var blockSize: CInterop.BlockSize { rawValue.st_blksize }
|
||||
|
||||
/// User defined flags for file.
|
||||
@_alwaysEmitIntoClient
|
||||
public var fileFlags: FileFlags { FileFlags(rawValue: rawValue.st_flags) }
|
||||
|
||||
/// File generation number.
|
||||
@_alwaysEmitIntoClient
|
||||
public var generationID: CInterop.GenerationID { rawValue.st_gen }
|
||||
}
|
||||
#endif
|
||||
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
|
||||
// FIXME: Document
|
||||
@frozen
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
public struct FileType: RawRepresentable {
|
||||
/// The raw C file type.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Create a strongly-typed file type from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
|
||||
|
||||
/// Named pipe (fifo)
|
||||
///
|
||||
/// The corresponding C constant is `S_IFIFO`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var fifo: FileType { FileType(_S_IFIFO) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "fifo")
|
||||
public static var S_IFIFO: FileType { fifo }
|
||||
|
||||
/// Character special
|
||||
///
|
||||
/// The corresponding C constant is `S_IFCHR`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var characterDevice: FileType { FileType(_S_IFCHR) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "characterDevice")
|
||||
public static var S_IFCHR: FileType { characterDevice }
|
||||
|
||||
/// Directory
|
||||
///
|
||||
/// The corresponding C constant is `S_IFDIR`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: FileType { FileType(_S_IFDIR) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "directory")
|
||||
public static var S_IFDIR: FileType { directory }
|
||||
|
||||
/// Block special
|
||||
///
|
||||
/// The corresponding C constant is `S_IFBLK`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var blockDevice: FileType { FileType(_S_IFBLK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "blockDevice")
|
||||
public static var S_IFBLK: FileType { blockDevice }
|
||||
|
||||
/// Regular
|
||||
///
|
||||
/// The corresponding C constant is `S_IFREG`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var regular: FileType { FileType(_S_IFREG) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "regular")
|
||||
public static var S_IFREG: FileType { regular }
|
||||
|
||||
/// Symbolic link
|
||||
///
|
||||
/// The corresponding C constant is `S_IFLNK`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symbolicLink: FileType { FileType(_S_IFLNK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "symbolicLink")
|
||||
public static var S_IFLNK: FileType { symbolicLink }
|
||||
|
||||
/// Socket
|
||||
///
|
||||
/// The corresponding C constant is `S_IFSOCK`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var socket: FileType { FileType(_S_IFSOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "socket")
|
||||
public static var S_IFSOCK: FileType { socket }
|
||||
|
||||
/// Whiteout
|
||||
///
|
||||
/// The corresponding C constant is `S_IFWHT`
|
||||
@_alwaysEmitIntoClient
|
||||
// FIXME: rename with inclusive language
|
||||
public static var whiteout: FileType { FileType(_S_IFWHT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "whiteout")
|
||||
public static var S_IFWHT: FileType { whiteout }
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,162 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - stat
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileDescriptor {
|
||||
/// Obtain information about the file pointed to by the FileDescriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: A `FileStatus` for the file pointed to by `self`.
|
||||
///
|
||||
/// The corresponding C function is `fstat`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getFileStatus(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileStatus {
|
||||
try _getFileStatus(
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getFileStatus(
|
||||
retryOnInterrupt: Bool = true
|
||||
) -> Result<FileStatus, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstat(self.rawValue, &result)
|
||||
}.map { FileStatus(rawValue: result) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - chmod
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileMode(
|
||||
to mode: FileMode,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileMode(
|
||||
to: mode,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileMode(
|
||||
to mode: FileMode,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fchmod(self.rawValue, mode.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - chown
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileOwner(
|
||||
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileOwner(
|
||||
to: owner,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileOwner(
|
||||
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fchown(self.rawValue, owner.userID, owner.groupID)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - chflags
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
internal func changeFileFlags(
|
||||
to flags: FileFlags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileFlags(
|
||||
to: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileFlags(
|
||||
to flags: FileFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fchflags(self.rawValue, flags.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - utimens
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileTimes(
|
||||
to times: (access: TimeSpecification, modification: TimeSpecification)?,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileTimes(
|
||||
to: times,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileTimes(
|
||||
to times: (access: TimeSpecification, modification: TimeSpecification)?,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
if let times = times {
|
||||
return withUnsafePointer(to: times) { tuplePtr in
|
||||
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
|
||||
timespecPtr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_futimens(self.rawValue, timespecPtr)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_futimens(self.rawValue, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,24 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - umask
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FileMode {
|
||||
@_alwaysEmitIntoClient
|
||||
func updateProcessMask() -> Self {
|
||||
_updateProcessMask()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func _updateProcessMask() -> Self {
|
||||
Self(rawValue: system_umask(self.rawValue))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,544 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - stat
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
/// Obtain information about the file pointed to by the FilePath.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - followSymlinks: Whether to follow symlinks.
|
||||
/// The default is `true`.
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: A `FileStatus` for the file pointed to by `self`.
|
||||
///
|
||||
/// Read, write or execute permission of the pointed to file is not required,
|
||||
/// but all intermediate directories must be searchable.
|
||||
///
|
||||
/// The corresponding C functions are `stat` and `lstat`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getFileStatus(
|
||||
followSymlinks: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileStatus {
|
||||
try _getFileStatus(
|
||||
followSymlinks: followSymlinks,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getFileStatus(
|
||||
followSymlinks: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileStatus, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
let fn = followSymlinks ? system_lstat : system_stat
|
||||
return withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
fn(ptr, &result)
|
||||
}.map { FileStatus(rawValue: result) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtain information about the file pointed to by the FilePath relative to
|
||||
/// the provided FileDescriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - relativeTo: if `self` is relative, treat it as relative to this file descriptor
|
||||
/// rather than relative to the current working directory.
|
||||
/// - followSymlinks: Whether to follow symlinks.
|
||||
/// The default is `true`.
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: A `FileStatus` for the file pointed to by `self`.
|
||||
///
|
||||
/// Read, write or execute permission of the pointed to file is not required,
|
||||
/// but all intermediate directories must be searchable.
|
||||
///
|
||||
/// The corresponding C function is `fstatat`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getFileStatus(
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileStatus {
|
||||
try _getFileStatus(
|
||||
relativeTo: fd,
|
||||
fcntrl: fcntrl,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getFileStatus(
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileStatus, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstatat(fd.rawValue, ptr, &result, fcntrl.rawValue)
|
||||
}.map { FileStatus(rawValue: result) }
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - chmod
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileMode(
|
||||
to mode: FileMode,
|
||||
followSymlinks: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileMode(
|
||||
to: mode,
|
||||
followSymlinks: followSymlinks,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileMode(
|
||||
to mode: FileMode,
|
||||
followSymlinks: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
let fn = followSymlinks ? system_lchmod : system_chmod
|
||||
return withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
fn(ptr, mode.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// valid flags: AT_SYMLINK_NOFOLLOW | AT_REALDEV | AT_FDONLY
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileMode(
|
||||
to mode: FileMode,
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileMode(
|
||||
to: mode,
|
||||
relativeTo: fd,
|
||||
fcntrl: fcntrl,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileMode(
|
||||
to mode: FileMode,
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
self.withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fchmodat(fd.rawValue, ptr, mode.rawValue, fcntrl.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - chown
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeOwner(
|
||||
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
|
||||
followSymlinks: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeOwner(
|
||||
to: owner,
|
||||
followSymlinks: followSymlinks,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeOwner(
|
||||
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
|
||||
followSymlinks: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
let fn = followSymlinks ? system_lchown : system_chown
|
||||
return withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
fn(ptr, owner.userID, owner.groupID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeOwner(
|
||||
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeOwner(
|
||||
to: owner,
|
||||
relativeTo: fd,
|
||||
fcntrl: fcntrl,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeOwner(
|
||||
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
self.withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fchownat(
|
||||
fd.rawValue, ptr, owner.userID, owner.groupID, fcntrl.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - chflags
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileFlags(
|
||||
to flags: FileFlags,
|
||||
followSymlinks: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileFlags(
|
||||
to: flags,
|
||||
followSymlinks: followSymlinks,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileFlags(
|
||||
to flags: FileFlags,
|
||||
followSymlinks: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
let fn = followSymlinks ? system_lchflags : system_chflags
|
||||
return withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
fn(ptr, flags.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileFlags(
|
||||
to flags: FileFlags,
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileFlags(
|
||||
to: flags,
|
||||
relativeTo: fd,
|
||||
fcntrl: fcntrl,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileFlags(
|
||||
to flags: FileFlags,
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
return withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_chflagsat(fd.rawValue, ptr, flags.rawValue, fcntrl.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - mkfifo
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
@_alwaysEmitIntoClient
|
||||
public func makeFIFO(
|
||||
withMode mode: FileMode,
|
||||
retryOnInterrupt: Bool = true) throws {
|
||||
try _makeFIFO(
|
||||
withMode: mode,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _makeFIFO(
|
||||
withMode mode: FileMode,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_mkfifo(ptr, mode.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func makeFIFO(
|
||||
withMode mode: FileMode,
|
||||
relativeTo fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true) throws {
|
||||
try _makeFIFO(
|
||||
withMode: mode,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
@usableFromInline
|
||||
internal func _makeFIFO(
|
||||
withMode mode: FileMode,
|
||||
relativeTo fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_mkfifoat(fd.rawValue, ptr, mode.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - mknod
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
@_alwaysEmitIntoClient
|
||||
public func makeNode(
|
||||
withMode mode: FileMode,
|
||||
andDeviceID deviceID: CInterop.DeviceID,
|
||||
retryOnInterrupt: Bool = true) throws {
|
||||
try _makeNode(
|
||||
withMode: mode,
|
||||
andDeviceID: deviceID,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _makeNode(
|
||||
withMode mode: FileMode,
|
||||
andDeviceID deviceID: CInterop.DeviceID,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_mknod(ptr, mode.rawValue, deviceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func makeNode(
|
||||
withMode mode: FileMode,
|
||||
andDeviceID deviceID: CInterop.DeviceID,
|
||||
relativeTo fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true) throws {
|
||||
try _makeNode(
|
||||
withMode: mode,
|
||||
andDeviceID: deviceID,
|
||||
relativeTo: fd,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
@usableFromInline
|
||||
internal func _makeNode(
|
||||
withMode mode: FileMode,
|
||||
andDeviceID deviceID: CInterop.DeviceID,
|
||||
relativeTo fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_mknodat(fd.rawValue, ptr, mode.rawValue, deviceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - mkdir
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
@_alwaysEmitIntoClient
|
||||
public func makeDirectory(
|
||||
withMode mode: FileMode,
|
||||
retryOnInterrupt: Bool = true) throws {
|
||||
try _makeDirectory(
|
||||
withMode: mode,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _makeDirectory(
|
||||
withMode mode: FileMode,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_mkdir(ptr, mode.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func makeDirectory(
|
||||
withMode mode: FileMode,
|
||||
relativeTo fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true) throws {
|
||||
try _makeDirectory(
|
||||
withMode: mode,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
@usableFromInline
|
||||
internal func _makeDirectory(
|
||||
withMode mode: FileMode,
|
||||
relativeTo fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
withPlatformString { ptr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_mkdirat(fd.rawValue, ptr, mode.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// MARK: - mkdir
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
extension FilePath {
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileTimes(
|
||||
to times: (access: TimeSpecification, modification: TimeSpecification)?,
|
||||
followSymlinks: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileTimes(
|
||||
to: times,
|
||||
followSymlinks: followSymlinks,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileTimes(
|
||||
to times: (access: TimeSpecification, modification: TimeSpecification)?,
|
||||
followSymlinks: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
let fn = followSymlinks ? system_utimens : system_lutimens
|
||||
return withPlatformString { ptr in
|
||||
if let times = times {
|
||||
return withUnsafePointer(to: times) { tuplePtr in
|
||||
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
|
||||
timespecPtr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
fn(ptr, timespecPtr)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
fn(ptr, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func changeFileTimes(
|
||||
to times: (access: TimeSpecification, modification: TimeSpecification)?,
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _changeFileTimes(
|
||||
to: times,
|
||||
relativeTo: fd,
|
||||
fcntrl: fcntrl,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _changeFileTimes(
|
||||
to times: (access: TimeSpecification, modification: TimeSpecification)?,
|
||||
relativeTo fd: FileDescriptor,
|
||||
fcntrl: FileDescriptor.ControlFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Void, Errno> {
|
||||
self.withPlatformString { ptr in
|
||||
if let times = times {
|
||||
return withUnsafePointer(to: times) { tuplePtr in
|
||||
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
|
||||
timespecPtr in
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_utimensat(fd.rawValue, ptr, timespecPtr, fcntrl.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_utimensat(fd.rawValue, ptr, nil, fcntrl.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#endif
|
||||
|
||||
extension CInterop {
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// The C `stat` type.
|
||||
public typealias Stat = stat
|
||||
/// The C `mode_t` type.
|
||||
public typealias Mode = mode_t
|
||||
/// The C `uid_t` type.
|
||||
public typealias UserID = uid_t
|
||||
/// The C `gid_t` type.
|
||||
public typealias GroupID = gid_t
|
||||
/// The C `dev_t` type.
|
||||
public typealias DeviceID = dev_t
|
||||
/// The C `nlink_t` type.
|
||||
public typealias NumberOfLinks = nlink_t
|
||||
/// The C `ino_t` type.
|
||||
public typealias INodeNumber = ino_t
|
||||
/// The C `timespec` type.
|
||||
public typealias TimeSpec = timespec
|
||||
/// The C `off_t` type.
|
||||
public typealias Offset = off_t
|
||||
/// The C `blkcnt_t` type.
|
||||
public typealias BlockCount = blkcnt_t
|
||||
/// The C `blksize_t` type.
|
||||
public typealias BlockSize = blksize_t
|
||||
/// The C `UInt32` type.
|
||||
public typealias GenerationID = UInt32
|
||||
/// The C `UInt32` type.
|
||||
public typealias FileFlags = UInt32
|
||||
#endif
|
||||
|
||||
#if os(Windows)
|
||||
public typealias Mode = CInt
|
||||
#endif
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
// MARK: - Mode Masks
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// mode_t: type ugs rwx rwx rwx
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MODE_PERMISSIONS: CInterop.Mode { 0b0000_111_111_111_111 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MODE_TYPE: CInterop.Mode { 0b1111_000_000_000_000 }
|
||||
#endif
|
||||
|
||||
// MARK: - File Type
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFIFO: CInterop.Mode { S_IFIFO }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFCHR: CInterop.Mode { S_IFCHR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFDIR: CInterop.Mode { S_IFDIR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFBLK: CInterop.Mode { S_IFBLK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFREG: CInterop.Mode { S_IFREG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFLNK: CInterop.Mode { S_IFLNK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFSOCK: CInterop.Mode { S_IFSOCK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFWHT: CInterop.Mode { S_IFWHT }
|
||||
#endif
|
||||
|
||||
// MARK: - File Flags
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_NODUMP: CInterop.FileFlags { UInt32(bitPattern: UF_NODUMP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_IMMUTABLE: CInterop.FileFlags { UInt32(bitPattern: UF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_APPEND: CInterop.FileFlags { UInt32(bitPattern: UF_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_OPAQUE: CInterop.FileFlags { UInt32(bitPattern: UF_OPAQUE) }
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_NOUNLINK: CInterop.FileFlags { UInt32(bitPattern: UF_NOUNLINK) }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_COMPRESSED: CInterop.FileFlags { UInt32(bitPattern: UF_COMPRESSED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_TRACKED: CInterop.FileFlags { UInt32(bitPattern: UF_TRACKED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_DATAVAULT: CInterop.FileFlags { UInt32(bitPattern: UF_DATAVAULT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_HIDDEN: CInterop.FileFlags { UInt32(bitPattern: UF_HIDDEN) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_ARCHIVED: CInterop.FileFlags { UInt32(bitPattern: SF_ARCHIVED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_IMMUTABLE: CInterop.FileFlags { UInt32(bitPattern: SF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_APPEND: CInterop.FileFlags { UInt32(bitPattern: SF_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_RESTRICTED: CInterop.FileFlags { UInt32(bitPattern: SF_RESTRICTED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_NOUNLINK: CInterop.FileFlags { UInt32(bitPattern: SF_NOUNLINK) }
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_SNAPSHOT: CInterop.FileFlags { UInt32(bitPattern: SF_SNAPSHOT) }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_FIRMLINK: CInterop.FileFlags { UInt32(bitPattern: SF_FIRMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_DATALESS: CInterop.FileFlags { UInt32(bitPattern: SF_DATALESS) }
|
||||
#endif
|
||||
|
||||
// MARK: - Time Specification
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UTIME_NOW: Int { Int(UTIME_NOW) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UTIME_OMIT: Int { Int(UTIME_OMIT) }
|
||||
#endif
|
||||
@@ -1,296 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
internal func system_stat(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ buf: UnsafeMutablePointer<stat>
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, buf) }
|
||||
#endif
|
||||
return stat(path, buf)
|
||||
}
|
||||
|
||||
internal func system_lstat(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ buf: UnsafeMutablePointer<stat>
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, buf) }
|
||||
#endif
|
||||
return lstat(path, buf)
|
||||
}
|
||||
|
||||
internal func system_fstat(
|
||||
_ fd: Int32,
|
||||
_ buf: UnsafeMutablePointer<stat>
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, buf) }
|
||||
#endif
|
||||
return fstat(fd, buf)
|
||||
}
|
||||
|
||||
internal func system_fstatat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ buf: UnsafeMutablePointer<stat>,
|
||||
_ flag: Int32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, buf, flag) }
|
||||
#endif
|
||||
return fstatat(fd, path, buf, flag)
|
||||
}
|
||||
|
||||
internal func system_chmod(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode) }
|
||||
#endif
|
||||
return chmod(path, mode)
|
||||
}
|
||||
|
||||
internal func system_lchmod(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode) }
|
||||
#endif
|
||||
return lchmod(path, mode)
|
||||
}
|
||||
|
||||
internal func system_fchmod(
|
||||
_ fd: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, mode) }
|
||||
#endif
|
||||
return fchmod(fd, mode)
|
||||
}
|
||||
|
||||
internal func system_fchmodat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode,
|
||||
_ flag: Int32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, mode, flag) }
|
||||
#endif
|
||||
return fchmodat(fd, path, mode, flag)
|
||||
}
|
||||
|
||||
internal func system_chown(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ userID: CInterop.UserID,
|
||||
_ groupID: CInterop.GroupID
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, userID, groupID) }
|
||||
#endif
|
||||
return chown(path, userID, groupID)
|
||||
}
|
||||
|
||||
internal func system_lchown(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ userID: CInterop.UserID,
|
||||
_ groupID: CInterop.GroupID
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, userID, groupID) }
|
||||
#endif
|
||||
return lchown(path, userID, groupID)
|
||||
}
|
||||
|
||||
internal func system_fchown(
|
||||
_ fd: Int32,
|
||||
_ userID: CInterop.UserID,
|
||||
_ groupID: CInterop.GroupID
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, userID, groupID) }
|
||||
#endif
|
||||
return fchown(fd, userID, groupID)
|
||||
}
|
||||
|
||||
internal func system_fchownat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ userID: CInterop.UserID,
|
||||
_ groupID: CInterop.GroupID,
|
||||
_ flag: Int32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, userID, groupID, flag) }
|
||||
#endif
|
||||
return fchownat(fd, path, userID, groupID, flag)
|
||||
}
|
||||
|
||||
internal func system_chflags(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flag: UInt32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, flag) }
|
||||
#endif
|
||||
return chflags(path, flag)
|
||||
}
|
||||
|
||||
internal func system_lchflags(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flag: UInt32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, flag) }
|
||||
#endif
|
||||
return lchflags(path, flag)
|
||||
}
|
||||
|
||||
internal func system_fchflags(
|
||||
_ fd: Int32,
|
||||
_ flag: UInt32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, flag) }
|
||||
#endif
|
||||
return fchflags(fd, flag)
|
||||
}
|
||||
|
||||
internal func system_umask(
|
||||
_ cmask: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockModeT(cmask) }
|
||||
#endif
|
||||
return umask(cmask)
|
||||
}
|
||||
|
||||
internal func system_mkfifo(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode) }
|
||||
#endif
|
||||
return mkfifo(path, mode)
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
internal func system_mkfifoat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode) }
|
||||
#endif
|
||||
return mkfifoat(fd, path, mode)
|
||||
}
|
||||
|
||||
internal func system_mknod(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode,
|
||||
_ deviceID: CInterop.DeviceID
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode, deviceID) }
|
||||
#endif
|
||||
return mknod(path, mode, deviceID)
|
||||
}
|
||||
|
||||
@available(macOS 13.0, *)
|
||||
internal func system_mknodat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode,
|
||||
_ deviceID: CInterop.DeviceID
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode, deviceID) }
|
||||
#endif
|
||||
return mknodat(fd, path, mode, deviceID)
|
||||
}
|
||||
|
||||
internal func system_mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, mode) }
|
||||
#endif
|
||||
return mkdir(path, mode)
|
||||
}
|
||||
|
||||
internal func system_mkdirat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, mode) }
|
||||
#endif
|
||||
return mkdirat(fd, path, mode)
|
||||
}
|
||||
|
||||
#if os(FreeBSD)
|
||||
internal func system_utimens(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ times: UnsafePointer<timespec>?
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, times) }
|
||||
#endif
|
||||
return utimens(path, times)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD)
|
||||
internal func system_lutimens(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ times: UnsafePointer<timespec>?
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path, times) }
|
||||
#endif
|
||||
return lutimens(path, times)
|
||||
}
|
||||
#endif
|
||||
|
||||
internal func system_utimensat(
|
||||
_ fd: Int32,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ times: UnsafePointer<timespec>?,
|
||||
_ flag: Int32
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, times, flag) }
|
||||
#endif
|
||||
return utimensat(fd, path, times, flag)
|
||||
}
|
||||
|
||||
internal func system_futimens(
|
||||
_ fd: Int32,
|
||||
_ times: UnsafePointer<timespec>?
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, times) }
|
||||
#endif
|
||||
return futimens(fd, times)
|
||||
}
|
||||
#endif
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// MARK: - stat
|
||||
// int stat(const char *, struct stat *)
|
||||
// int lstat(const char *, struct stat *)
|
||||
// FilePath.getFileStatus(followSymlinks:) throws Errno -> FileStatus
|
||||
|
||||
// int fstatat(int, const char *, struct stat *, int)
|
||||
// FilePath.getFileStatus(relativeTo:controlFlags:) throws Errno -> FileStatus
|
||||
|
||||
// int fstat(int, struct stat *)
|
||||
// FileDescriptor.getFileStatus() throws Errno -> FileStatus
|
||||
|
||||
|
||||
// MARK: - chmod
|
||||
// int chmod(const char *, mode_t)
|
||||
// int lchmod(const char *, mode_t)
|
||||
// FilePath.changeFileMode(to:followSymlinks) throws Errno -> Void
|
||||
|
||||
// int fchmodat(int, const char *, mode_t, int)
|
||||
// FilePath.changeFileMode(to:relativeTo:controlFlags:) throws Errno -> Void
|
||||
|
||||
// int fchmod(int, mode_t)
|
||||
// FileDescriptor.changeFileMode(to:) throws Errno -> Void
|
||||
|
||||
|
||||
// MARK: - chown
|
||||
// int chown(const char *, uid_t, gid_t)
|
||||
// int lchown(const char *, uid_t, gid_t)
|
||||
// FilePath.changeFileOwner(to:followSymlinks:) throws Errno -> Void
|
||||
|
||||
// int fchownat(int, const char *, uid_t, gid_t, int)
|
||||
// FilePath.changeFileOwner(to:relativeTo:controlFlags:) throws Errno -> Void
|
||||
|
||||
// int fchown(int, uid_t, gid_t)
|
||||
// FileDescriptor.changeFileOwner(to:) throws Errno -> Void
|
||||
|
||||
|
||||
// MARK: - chflags
|
||||
// int chflags(const char *, uint32_t)
|
||||
// int lchflags(const char *, uint32_t)
|
||||
// FilePath.changeFileFlags(to:followSymlinks:) throws Errno -> Void
|
||||
|
||||
// int chflagsat(int, const char *, uint32_t, int) (FreeBSD)
|
||||
// FilePath.changeFileFlags(to:relativeTo:controlFlags:) throws Errno -> Void
|
||||
|
||||
// int fchflags(int, uint32_t)
|
||||
// FileDescriptor.changeFileFlags(to:) throws Errno -> Void
|
||||
|
||||
|
||||
// MARK: - umask
|
||||
// mode_t umask(mode_t)
|
||||
// FileMode.updateProcessMask() -> FileMode
|
||||
|
||||
|
||||
// MARK: - mkfifo
|
||||
// int mkfifo(const char *, mode_t)
|
||||
// FilePath.makeFIFO(withMode:) throws Errno -> Void
|
||||
|
||||
// int mkfifoat(int, const char *, mode_t)
|
||||
// FilePath.makeFIFO(withMode:relativeTo:) throws Errno -> Void
|
||||
|
||||
|
||||
// MARK: - mknod
|
||||
// int mknod(const char *, mode_t, dev_t)
|
||||
// FilePath.makeNode(withMode:andDeviceID:) throws Errno -> Void
|
||||
|
||||
// int mknodat(int, const char *, mode_t, dev_t)
|
||||
// FilePath.makeNode(withMode:andDeviceID:relativeTo:) throws Errno -> Void
|
||||
|
||||
|
||||
// MARK: - mkdir
|
||||
// int mkdir(const char *, mode_t)
|
||||
// FilePath.makeDirectory(withMode:) throws Errno -> Void
|
||||
|
||||
// int mkdirat(int, const char *, mode_t)
|
||||
// FilePath.makeDirectory(withMode:relativeTo:) throws Errno -> Void
|
||||
|
||||
|
||||
// MARK: - utimens
|
||||
// int utimens(const char *, const struct timespec[2])
|
||||
// int lutimens(const char *, const struct timespec[2])
|
||||
// FilePath.changeFileTimes(to:followSymlinks:) throws Errno -> Void
|
||||
|
||||
// int utimensat(int, const char *, const struct timespec[2], int)
|
||||
// FilePath.changeFileTimes(to:relativeTo:controlFlags:) throws Errno -> Void
|
||||
|
||||
// int futimens(int, const struct timespec[2])
|
||||
// FileDescriptor.changeFileTimes(to:) throws Errno -> Void
|
||||
@@ -1,14 +1,15 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// A platform-native character representation, currently used for file paths
|
||||
internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable {
|
||||
internal struct SystemChar:
|
||||
RawRepresentable, Sendable, Comparable, Hashable, Codable {
|
||||
internal typealias RawValue = CInterop.PlatformChar
|
||||
|
||||
internal var rawValue: RawValue
|
||||
@@ -61,7 +62,7 @@ extension SystemChar {
|
||||
// A platform-native string representation, currently for file paths
|
||||
//
|
||||
// Always null-terminated.
|
||||
internal struct SystemString {
|
||||
internal struct SystemString: Sendable {
|
||||
internal typealias Storage = [SystemChar]
|
||||
internal var nullTerminatedStorage: Storage
|
||||
}
|
||||
@@ -95,10 +96,18 @@ extension SystemString {
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
fileprivate func _invariantsSatisfied() -> Bool {
|
||||
guard !nullTerminatedStorage.isEmpty else { return false }
|
||||
guard nullTerminatedStorage.last! == .null else { return false }
|
||||
guard nullTerminatedStorage.firstIndex(of: .null) == length else {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fileprivate func _invariantCheck() {
|
||||
#if DEBUG
|
||||
precondition(nullTerminatedStorage.last! == .null)
|
||||
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
|
||||
precondition(_invariantsSatisfied())
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
@@ -141,44 +150,67 @@ extension SystemString: RangeReplaceableCollection {
|
||||
nullTerminatedStorage.reserveCapacity(1 + n)
|
||||
}
|
||||
|
||||
// TODO: Below include null terminator, is this desired?
|
||||
|
||||
internal func withContiguousStorageIfAvailable<R>(
|
||||
_ body: (UnsafeBufferPointer<SystemChar>) throws -> R
|
||||
) rethrows -> R? {
|
||||
try nullTerminatedStorage.withContiguousStorageIfAvailable(body)
|
||||
// Do not include the null terminator, it is outside the Collection
|
||||
try nullTerminatedStorage.withContiguousStorageIfAvailable {
|
||||
try body(.init(start: $0.baseAddress, count: $0.count-1))
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func withContiguousMutableStorageIfAvailable<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
|
||||
) rethrows -> R? {
|
||||
defer { _invariantCheck() }
|
||||
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
|
||||
// Do not include the null terminator, it is outside the Collection
|
||||
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable {
|
||||
var buffer = UnsafeMutableBufferPointer<SystemChar>(
|
||||
start: $0.baseAddress, count: $0.count-1
|
||||
)
|
||||
return try body(&buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString: Hashable, Codable {}
|
||||
extension SystemString: Hashable, Codable {
|
||||
// Encoder is synthesized; it probably should have been explicit and used
|
||||
// a single-value container, but making that change now is somewhat risky.
|
||||
|
||||
// Decoder is written explicitly to ensure that we validate invariants on
|
||||
// untrusted input.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.nullTerminatedStorage = try container.decode(
|
||||
Storage.self, forKey: .nullTerminatedStorage
|
||||
)
|
||||
guard _invariantsSatisfied() else {
|
||||
throw DecodingError.dataCorruptedError(
|
||||
forKey: .nullTerminatedStorage,
|
||||
in: container,
|
||||
debugDescription:
|
||||
"Encoding does not satisfy the invariants of SystemString"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
// TODO: Below include null terminator, is this desired?
|
||||
|
||||
internal func withSystemChars<T>(
|
||||
internal func withNullTerminatedSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withContiguousStorageIfAvailable(f)!
|
||||
try nullTerminatedStorage.withUnsafeBufferPointer(f)
|
||||
}
|
||||
|
||||
// withCodeUnits does not include the null terminator
|
||||
internal func withCodeUnits<T>(
|
||||
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
let count = length / MemoryLayout<CInterop.PlatformUnicodeEncoding.CodeUnit>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformUnicodeEncoding.CodeUnit.self,
|
||||
capacity: count
|
||||
) { pointer in
|
||||
try f(UnsafeBufferPointer(start: pointer, count: count))
|
||||
try withNullTerminatedSystemChars {
|
||||
try $0.withMemoryRebound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self) {
|
||||
assert($0.last == .zero)
|
||||
return try f(.init(start: $0.baseAddress, count: $0.count&-1))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,7 +226,9 @@ extension Slice where Base == SystemString {
|
||||
}
|
||||
|
||||
internal var string: String {
|
||||
withCodeUnits { String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) }
|
||||
withCodeUnits {
|
||||
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
|
||||
}
|
||||
}
|
||||
|
||||
internal func withPlatformString<T>(
|
||||
@@ -236,7 +270,11 @@ extension SystemString: ExpressibleByStringLiteral {
|
||||
}
|
||||
|
||||
extension SystemString: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
internal var string: String { String(decoding: self) }
|
||||
internal var string: String {
|
||||
self.withCodeUnits {
|
||||
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
|
||||
}
|
||||
}
|
||||
|
||||
internal var description: String { string }
|
||||
internal var debugDescription: String { description.debugDescription }
|
||||
@@ -275,7 +313,7 @@ extension SystemString {
|
||||
internal func withPlatformString<T>(
|
||||
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars { chars in
|
||||
try withNullTerminatedSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformChar.self,
|
||||
@@ -288,11 +326,6 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
extension SystemChar: Sendable {}
|
||||
extension SystemString: Sendable {}
|
||||
#endif
|
||||
|
||||
// TODO: SystemString should use a COW-interchangable storage form rather
|
||||
// than array, so you could "borrow" the storage from a non-bridged String
|
||||
// or Data or whatever
|
||||
@@ -1,140 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Specification:
|
||||
// - POSIX.1-2017
|
||||
// - IEEE Std 1003.1™-2017
|
||||
// - The Open Group Technical Standard Base Specifications, Issue 7
|
||||
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
|
||||
// sys/time.h
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// A system provided timer which can be configured to run after an initial
|
||||
/// delay and subsequent interval.
|
||||
///
|
||||
/// The corresponding C type is `int`.
|
||||
@frozen
|
||||
public struct IntervalTimer: RawRepresentable {
|
||||
public typealias RawValue = CInterop.IntervalTimer
|
||||
|
||||
/// The raw C ITIMER value.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: RawValue
|
||||
|
||||
/// Create a strongly-typed interval timer from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: RawValue) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
extension IntervalTimer {
|
||||
/// A timer which decrements in real time.
|
||||
///
|
||||
/// A `SIGALRM` signal is delivered when this timer expires.
|
||||
///
|
||||
/// The corresponding C timer is `ITIMER_REAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var real: Self { Self(rawValue: _ITIMER_REAL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "real")
|
||||
public static var ITIMER_REAL: Self { real }
|
||||
|
||||
/// A timer which decrements in process virtual time.
|
||||
///
|
||||
/// The timer runs only while the process is executing. A `SIGVTALRM` signal
|
||||
/// is delivered when this timer expires.
|
||||
///
|
||||
/// The corresponding C timer is `ITIMER_VIRTUAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var virtual: Self { Self(rawValue: _ITIMER_VIRTUAL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "virtual")
|
||||
public static var ITIMER_VIRTUAL: Self { virtual }
|
||||
|
||||
/// A timer which decrements both in process virtual time and when the system
|
||||
/// is running on behalf of the process.
|
||||
///
|
||||
/// This timer is designed to be used by interpreters when statistically
|
||||
/// profiling the execution of interpreted programs. A `SIGPROF` signal
|
||||
/// is delivered when this timer expires. Because this signal may interrupt
|
||||
/// in-progress system calls, programs using this timer must be prepared to
|
||||
/// restart interrupted system calls.
|
||||
///
|
||||
/// The corresponding C timer is `ITIMER_PROF`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var profile: Self { Self(rawValue: _ITIMER_PROF) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "profile")
|
||||
public static var ITIMER_PROF: Self { profile }
|
||||
}
|
||||
|
||||
extension IntervalTimer {
|
||||
/// Returns the current value for the timer.
|
||||
///
|
||||
/// - Returns: The current value of the timer.
|
||||
///
|
||||
/// The corresponding C function is `getitimer`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func get() throws -> IntervalTimerValue {
|
||||
try _get().get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _get() -> Result<IntervalTimerValue, Errno> {
|
||||
var currentValue = itimerval()
|
||||
return nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getitimer(self.rawValue, ¤tValue)
|
||||
}
|
||||
.map {
|
||||
IntervalTimerValue(rawValue: currentValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a timer to run on specified value.
|
||||
///
|
||||
/// If the initial delay is non-zero, it indicates the time to the next timer
|
||||
/// expiration. If the interval is non-zero, it specifies a value to be used
|
||||
/// in reloading initial delay when the timer expires.
|
||||
///
|
||||
/// Setting the initial delay to `0` disables the timer.
|
||||
/// Setting the interval to `0` causes a timer to be disabled after its next
|
||||
/// expiration, assuming initial delay is non-zero.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newValue: The new interval to run the timer.
|
||||
/// - Returns: The previous value of the timer.
|
||||
///
|
||||
/// The corresponding C function is `setitimer`.
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func set(newValue: IntervalTimerValue) throws -> IntervalTimerValue {
|
||||
try _set(newValue: newValue).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _set(
|
||||
newValue: IntervalTimerValue
|
||||
) -> Result<IntervalTimerValue, Errno> {
|
||||
var newValue = newValue.rawValue
|
||||
var oldValue = itimerval()
|
||||
return nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_setitimer(self.rawValue, &newValue, &oldValue)
|
||||
}
|
||||
.map {
|
||||
IntervalTimerValue(rawValue: oldValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Specification:
|
||||
// - POSIX.1-2017
|
||||
// - IEEE Std 1003.1™-2017
|
||||
// - The Open Group Technical Standard Base Specifications, Issue 7
|
||||
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
|
||||
// sys/time.h
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// The value an interval timer is configured to run on.
|
||||
///
|
||||
/// The corresponding C type is `itimerval`.
|
||||
@frozen
|
||||
public struct IntervalTimerValue: RawRepresentable {
|
||||
public typealias RawValue = CInterop.IntervalTimerValue
|
||||
|
||||
/// The raw C itimerval type.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: RawValue
|
||||
|
||||
/// Create a strongly-typed internal timer value from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: RawValue) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
extension IntervalTimerValue {
|
||||
/// The initial delay before running the timer.
|
||||
///
|
||||
/// Setting the initial delay to `0` disables the timer.
|
||||
///
|
||||
/// The corresponding C property is `it_value`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var initialDelay: TimeValue {
|
||||
get { TimeValue(rawValue: rawValue.it_value) }
|
||||
set { rawValue.it_value = newValue.rawValue }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "initialDelay")
|
||||
public var it_value: TimeValue { initialDelay }
|
||||
|
||||
/// The subsequent delay after the initial delay before running the timer.
|
||||
///
|
||||
/// Setting the interval to `0` causes a timer to be disabled after its next
|
||||
/// expiration, assuming initial delay is non-zero.
|
||||
///
|
||||
/// The corresponding C property is `it_interval`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var interval: TimeValue {
|
||||
get { TimeValue(rawValue: rawValue.it_interval) }
|
||||
set { rawValue.it_interval = newValue.rawValue }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "interval")
|
||||
public var it_interval: TimeValue { interval }
|
||||
}
|
||||
#endif
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
extension CInterop {
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// The C `time_t` type
|
||||
public typealias Time = time_t
|
||||
/// The C `suseconds_t` type
|
||||
public typealias Microseconds = suseconds_t
|
||||
/// The C `long` type
|
||||
public typealias Nanoseconds = CLong
|
||||
/// The C `timeval` type
|
||||
public typealias TimeValue = timeval
|
||||
/// The C `timespec` type
|
||||
public typealias TimeSpecification = timespec
|
||||
/// The C `itimerval` type
|
||||
public typealias IntervalTimerValue = itimerval
|
||||
/// The C type of `ITIMER` values
|
||||
public typealias IntervalTimer = CInt
|
||||
#endif
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ITIMER_REAL: CInterop.IntervalTimer { ITIMER_REAL }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ITIMER_VIRTUAL: CInterop.IntervalTimer { ITIMER_VIRTUAL }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ITIMER_PROF: CInterop.IntervalTimer { ITIMER_PROF }
|
||||
#endif
|
||||
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// getitimer
|
||||
internal func system_getitimer(
|
||||
_ timer: CInt,
|
||||
_ currentValue: UnsafeMutablePointer<itimerval>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(timer, currentValue) }
|
||||
#endif
|
||||
return getitimer(timer, currentValue)
|
||||
}
|
||||
|
||||
// setitimer
|
||||
internal func system_setitimer(
|
||||
_ timer: CInt,
|
||||
_ newValue: UnsafePointer<itimerval>,
|
||||
_ oldValue: UnsafeMutablePointer<itimerval>?
|
||||
) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(timer, newValue, oldValue) }
|
||||
#endif
|
||||
return setitimer(timer, newValue, oldValue)
|
||||
}
|
||||
#endif
|
||||
@@ -1,164 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Specification:
|
||||
// - POSIX.1-2017
|
||||
// - IEEE Std 1003.1™-2017
|
||||
// - The Open Group Technical Standard Base Specifications, Issue 7
|
||||
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
|
||||
// time.h
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// Represents an elapsed time since a reference point.
|
||||
///
|
||||
/// The corresponding C type is `timeval`.
|
||||
@frozen
|
||||
public struct TimeSpecification: RawRepresentable {
|
||||
public typealias RawValue = CInterop.TimeSpecification
|
||||
|
||||
/// The raw C timeval type.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: RawValue
|
||||
|
||||
/// Create a strongly-typed time value from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: RawValue) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
extension TimeSpecification {
|
||||
/// The elapsed time in seconds.
|
||||
///
|
||||
/// The corresponding C property is `tv_sec`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var seconds: CInterop.Time {
|
||||
get { rawValue.tv_sec }
|
||||
set { rawValue.tv_sec = newValue }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "seconds")
|
||||
public var tv_sec: CInterop.Time { seconds }
|
||||
|
||||
/// The remaining elapsed time in nanoseconds.
|
||||
///
|
||||
/// This value must always be in the range [0, 999999999].
|
||||
///
|
||||
/// The corresponding C property is `tv_nsec`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var nanoseconds: CInterop.Nanoseconds {
|
||||
get { rawValue.tv_nsec }
|
||||
set { rawValue.tv_nsec = newValue }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "nanoseconds")
|
||||
public var tv_nsec: CInterop.Nanoseconds { nanoseconds }
|
||||
}
|
||||
|
||||
extension TimeSpecification {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
private static let attosecondsPerNanoseconds: Int64 = 1_000_000_000
|
||||
|
||||
/// Creates a new value, rounded to the closest possible representation.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public init(_ duration: Duration) {
|
||||
let (seconds, attoseconds) = duration.components
|
||||
let nanoseconds = attoseconds / Self.attosecondsPerNanoseconds
|
||||
self.rawValue = .init(
|
||||
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
|
||||
tv_nsec: CInterop.Nanoseconds(nanoseconds))
|
||||
}
|
||||
|
||||
/// Creates a new value, if the given duration can be represented exactly.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public init?(exactly duration: Duration) {
|
||||
let (seconds, attoseconds) = duration.components
|
||||
guard
|
||||
let seconds = CInterop.Time(exactly: seconds),
|
||||
attoseconds.isMultiple(of: Self.attosecondsPerNanoseconds)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
let nanoseconds = attoseconds / Self.attosecondsPerNanoseconds
|
||||
self.rawValue = .init(
|
||||
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
|
||||
tv_nsec: CInterop.Nanoseconds(nanoseconds))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public var duration: Duration {
|
||||
let seconds = Int64(self.seconds)
|
||||
let attoseconds = Int64(self.nanoseconds) *
|
||||
Self.attosecondsPerNanoseconds
|
||||
return .init(
|
||||
secondsComponent: seconds,
|
||||
attosecondsComponent: attoseconds)
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeSpecification: AdditiveArithmetic {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
private static let nanosecondsPerSecond: CInterop.Nanoseconds = 1_000_000_000
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static var zero: Self {
|
||||
Self(rawValue: .init(tv_sec: 0, tv_nsec: 0))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static func + (lhs: Self, rhs: Self) -> Self {
|
||||
var newValue = TimeSpecification.zero
|
||||
newValue.seconds = lhs.seconds + rhs.seconds
|
||||
newValue.nanoseconds = lhs.nanoseconds + rhs.nanoseconds
|
||||
if (newValue.nanoseconds >= Self.nanosecondsPerSecond) {
|
||||
newValue.seconds += 1
|
||||
newValue.nanoseconds -= Self.nanosecondsPerSecond
|
||||
}
|
||||
return newValue
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static func - (lhs: Self, rhs: Self) -> Self {
|
||||
var newValue = TimeSpecification.zero
|
||||
newValue.seconds = lhs.seconds - rhs.seconds;
|
||||
newValue.nanoseconds = lhs.nanoseconds - rhs.nanoseconds
|
||||
if (newValue.nanoseconds < 0) {
|
||||
newValue.seconds -= 1
|
||||
newValue.nanoseconds += Self.nanosecondsPerSecond
|
||||
}
|
||||
return newValue
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeSpecification: Comparable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
guard lhs.seconds == rhs.seconds else {
|
||||
return lhs.seconds < rhs.seconds
|
||||
}
|
||||
return lhs.nanoseconds < rhs.nanoseconds
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeSpecification: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.seconds == rhs.seconds && lhs.nanoseconds == rhs.nanoseconds
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,164 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Specification:
|
||||
// - POSIX.1-2017
|
||||
// - IEEE Std 1003.1™-2017
|
||||
// - The Open Group Technical Standard Base Specifications, Issue 7
|
||||
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
|
||||
// sys/time.h
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// Represents an elapsed time since a reference point.
|
||||
///
|
||||
/// The corresponding C type is `timeval`.
|
||||
@frozen
|
||||
public struct TimeValue: RawRepresentable {
|
||||
public typealias RawValue = CInterop.TimeValue
|
||||
|
||||
/// The raw C timeval type.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: RawValue
|
||||
|
||||
/// Create a strongly-typed time value from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: RawValue) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
extension TimeValue {
|
||||
/// The elapsed time in seconds.
|
||||
///
|
||||
/// The corresponding C property is `tv_sec`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var seconds: CInterop.Time {
|
||||
get { rawValue.tv_sec }
|
||||
set { rawValue.tv_sec = newValue }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "seconds")
|
||||
public var tv_sec: CInterop.Time { seconds }
|
||||
|
||||
/// The remaining elapsed time in microseconds.
|
||||
///
|
||||
/// This value must always be in the range [0, 999999].
|
||||
///
|
||||
/// The corresponding C property is `tv_usec`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var microseconds: CInterop.Microseconds {
|
||||
get { rawValue.tv_usec }
|
||||
set { rawValue.tv_usec = newValue }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "microseconds")
|
||||
public var tv_usec: CInterop.Microseconds { microseconds }
|
||||
}
|
||||
|
||||
extension TimeValue {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
private static let attosecondsPerMicrosecond: Int64 = 1_000_000_000_000
|
||||
|
||||
/// Creates a new value, rounded to the closest possible representation.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public init(_ duration: Duration) {
|
||||
let (seconds, attoseconds) = duration.components
|
||||
let microseconds = attoseconds / Self.attosecondsPerMicrosecond
|
||||
self.rawValue = .init(
|
||||
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
|
||||
tv_usec: CInterop.Microseconds(microseconds))
|
||||
}
|
||||
|
||||
/// Creates a new value, if the given duration can be represented exactly.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public init?(exactly duration: Duration) {
|
||||
let (seconds, attoseconds) = duration.components
|
||||
guard
|
||||
let seconds = CInterop.Time(exactly: seconds),
|
||||
attoseconds.isMultiple(of: Self.attosecondsPerMicrosecond)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
let microseconds = attoseconds / Self.attosecondsPerMicrosecond
|
||||
self.rawValue = .init(
|
||||
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
|
||||
tv_usec: CInterop.Microseconds(microseconds))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public var duration: Duration {
|
||||
let seconds = Int64(self.seconds)
|
||||
let attoseconds = Int64(self.microseconds) *
|
||||
Self.attosecondsPerMicrosecond
|
||||
return .init(
|
||||
secondsComponent: seconds,
|
||||
attosecondsComponent: attoseconds)
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeValue: AdditiveArithmetic {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
private static let microsecondsPerSecond: CInterop.Microseconds = 1_000_000
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static var zero: TimeValue {
|
||||
Self(rawValue: .init(tv_sec: 0, tv_usec: 0))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static func + (lhs: Self, rhs: Self) -> Self {
|
||||
var newValue = TimeValue.zero
|
||||
newValue.seconds = lhs.seconds + rhs.seconds
|
||||
newValue.microseconds = lhs.microseconds + rhs.microseconds
|
||||
if (newValue.microseconds >= Self.microsecondsPerSecond) {
|
||||
newValue.seconds += 1
|
||||
newValue.microseconds -= Self.microsecondsPerSecond
|
||||
}
|
||||
return newValue
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public static func - (lhs: Self, rhs: Self) -> Self {
|
||||
var newValue = TimeValue.zero
|
||||
newValue.seconds = lhs.seconds - rhs.seconds;
|
||||
newValue.microseconds = lhs.microseconds - rhs.microseconds
|
||||
if (newValue.microseconds < 0) {
|
||||
newValue.seconds -= 1
|
||||
newValue.microseconds += Self.microsecondsPerSecond
|
||||
}
|
||||
return newValue
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeValue: Comparable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
guard lhs.seconds == rhs.seconds else {
|
||||
return lhs.seconds < rhs.seconds
|
||||
}
|
||||
return lhs.microseconds < rhs.microseconds
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeValue: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.seconds == rhs.seconds && lhs.microseconds == rhs.microseconds
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -8,21 +8,21 @@
|
||||
*/
|
||||
|
||||
// Results in errno if i == -1
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
private func valueOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<I, Errno> {
|
||||
i == -1 ? .failure(Errno.current) : .success(i)
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
private func nothingOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(i).map { _ in () }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<I, Errno> {
|
||||
@@ -36,7 +36,7 @@ internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
} while true
|
||||
}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
internal func nothingOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<(), Errno> {
|
||||
|
||||
@@ -52,13 +52,13 @@ extension Slice where Element: Equatable {
|
||||
return self[...idx]
|
||||
}
|
||||
|
||||
// If `e` is present, eat up to first occurence of `e`
|
||||
// If `e` is present, eat up to first occurrence of `e`
|
||||
internal mutating func _eatUntil(_ e: Element) -> Slice? {
|
||||
guard let idx = self.firstIndex(of: e) else { return nil }
|
||||
return _eatUntil(idx)
|
||||
}
|
||||
|
||||
// If `e` is present, eat up to and through first occurence of `e`
|
||||
// If `e` is present, eat up to and through first occurrence of `e`
|
||||
internal mutating func _eatThrough(_ e: Element) -> Slice? {
|
||||
guard let idx = self.firstIndex(of: e) else { return nil }
|
||||
return _eatThrough(idx)
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
import WinSDK
|
||||
|
||||
@_transparent
|
||||
internal var CREATE_ALWAYS: DWORD {
|
||||
DWORD(WinSDK.CREATE_ALWAYS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var CREATE_NEW: DWORD {
|
||||
DWORD(WinSDK.CREATE_NEW)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_ACCESS_DENIED: DWORD {
|
||||
DWORD(WinSDK.ERROR_ACCESS_DENIED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_ALREADY_EXISTS: DWORD {
|
||||
DWORD(WinSDK.ERROR_ALREADY_EXISTS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_ARENA_TRASHED: DWORD {
|
||||
DWORD(WinSDK.ERROR_ARENA_TRASHED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_ENVIRONMENT: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_ENVIRONMENT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_FORMAT: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_FORMAT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_NET_NAME: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_NET_NAME)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_NETPATH: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_NETPATH)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_PATHNAME: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_PATHNAME)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BROKEN_PIPE: DWORD {
|
||||
DWORD(WinSDK.ERROR_BROKEN_PIPE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_CANNOT_MAKE: DWORD {
|
||||
DWORD(WinSDK.ERROR_CANNOT_MAKE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_CHILD_NOT_COMPLETE: DWORD {
|
||||
DWORD(WinSDK.ERROR_CHILD_NOT_COMPLETE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_CURRENT_DIRECTORY: DWORD {
|
||||
DWORD(WinSDK.ERROR_CURRENT_DIRECTORY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DIR_NOT_EMPTY: DWORD {
|
||||
DWORD(WinSDK.ERROR_DIR_NOT_EMPTY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DISK_FULL: DWORD {
|
||||
DWORD(WinSDK.ERROR_DISK_FULL)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DRIVE_LOCKED: DWORD {
|
||||
DWORD(WinSDK.ERROR_DRIVE_LOCKED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DIRECT_ACCESS_HANDLE: DWORD {
|
||||
DWORD(WinSDK.ERROR_DIRECT_ACCESS_HANDLE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FILE_EXISTS: DWORD {
|
||||
DWORD(WinSDK.ERROR_FILE_EXISTS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FILE_NOT_FOUND: DWORD {
|
||||
DWORD(WinSDK.ERROR_FILE_NOT_FOUND)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FAIL_I24: DWORD {
|
||||
DWORD(WinSDK.ERROR_FAIL_I24)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FILENAME_EXCED_RANGE: DWORD {
|
||||
DWORD(WinSDK.ERROR_FILENAME_EXCED_RANGE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NEGATIVE_SEEK: DWORD {
|
||||
DWORD(WinSDK.ERROR_NEGATIVE_SEEK)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NO_MORE_FILES: DWORD {
|
||||
DWORD(WinSDK.ERROR_NO_MORE_FILES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NO_UNICODE_TRANSLATION: DWORD {
|
||||
DWORD(WinSDK.ERROR_NO_UNICODE_TRANSLATION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_ENOUGH_MEMORY: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_ENOUGH_MEMORY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_ACCESS: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_ACCESS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_BLOCK: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_BLOCK)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_DATA: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_DRIVE: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_DRIVE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_FUNCTION: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_FUNCTION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_HANDLE: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_HANDLE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD {
|
||||
DWORD(WinSDK.ERROR_INFLOOP_IN_RELOC_CHAIN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_PARAMETER: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_PARAMETER)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_STARTING_CODESEG: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_STARTING_CODESEG)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_TARGET_HANDLE: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_TARGET_HANDLE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_LOCK_FAILED: DWORD {
|
||||
DWORD(WinSDK.ERROR_LOCK_FAILED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_LOCK_VIOLATION: DWORD {
|
||||
DWORD(WinSDK.ERROR_LOCK_VIOLATION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_MAX_THRDS_REACHED: DWORD {
|
||||
DWORD(WinSDK.ERROR_MAX_THRDS_REACHED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NESTING_NOT_ALLOWED: DWORD {
|
||||
DWORD(WinSDK.ERROR_NESTING_NOT_ALLOWED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NETWORK_ACCESS_DENIED: DWORD {
|
||||
DWORD(WinSDK.ERROR_NETWORK_ACCESS_DENIED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NO_PROC_SLOTS: DWORD {
|
||||
DWORD(WinSDK.ERROR_NO_PROC_SLOTS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_ENOUGH_QUOTA: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_ENOUGH_QUOTA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_LOCKED: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_LOCKED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_SAME_DEVICE: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_SAME_DEVICE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_PATH_NOT_FOUND: DWORD {
|
||||
DWORD(WinSDK.ERROR_PATH_NOT_FOUND)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_SEEK_ON_DEVICE: DWORD {
|
||||
DWORD(WinSDK.ERROR_SEEK_ON_DEVICE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_SHARING_BUFFER_EXCEEDED: DWORD {
|
||||
DWORD(WinSDK.ERROR_SHARING_BUFFER_EXCEEDED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_SUCCESS: DWORD {
|
||||
DWORD(WinSDK.ERROR_SUCCESS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_WAIT_NO_CHILDREN: DWORD {
|
||||
DWORD(WinSDK.ERROR_WAIT_NO_CHILDREN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_WRITE_PROTECT: DWORD {
|
||||
DWORD(WinSDK.ERROR_WRITE_PROTECT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_TOO_MANY_OPEN_FILES: DWORD {
|
||||
DWORD(WinSDK.ERROR_TOO_MANY_OPEN_FILES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_APPEND_DATA: DWORD {
|
||||
DWORD(WinSDK.FILE_APPEND_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_ATTRIBUTE_DIRECTORY: DWORD {
|
||||
DWORD(WinSDK.FILE_ATTRIBUTE_DIRECTORY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_ATTRIBUTE_NORMAL: DWORD {
|
||||
DWORD(WinSDK.FILE_ATTRIBUTE_NORMAL)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_ATTRIBUTE_TEMPORARY: DWORD {
|
||||
DWORD(WinSDK.FILE_ATTRIBUTE_TEMPORARY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_BEGIN: DWORD {
|
||||
DWORD(WinSDK.FILE_BEGIN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_CURRENT: DWORD {
|
||||
DWORD(WinSDK.FILE_CURRENT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_DELETE_CHILD: DWORD {
|
||||
DWORD(WinSDK.FILE_DELETE_CHILD)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
package var FILE_EXECUTE: DWORD {
|
||||
DWORD(WinSDK.FILE_EXECUTE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_FLAG_DELETE_ON_CLOSE: DWORD {
|
||||
DWORD(WinSDK.FILE_FLAG_DELETE_ON_CLOSE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_FLAG_RANDOM_ACCESS: DWORD {
|
||||
DWORD(WinSDK.FILE_FLAG_RANDOM_ACCESS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_FLAG_SEQUENTIAL_SCAN: DWORD {
|
||||
DWORD(WinSDK.FILE_FLAG_SEQUENTIAL_SCAN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
package var FILE_READ_ATTRIBUTES: DWORD {
|
||||
DWORD(WinSDK.FILE_READ_ATTRIBUTES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_READ_DATA: DWORD {
|
||||
DWORD(WinSDK.FILE_READ_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_READ_EA: DWORD {
|
||||
DWORD(WinSDK.FILE_READ_EA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_SHARE_DELETE: DWORD {
|
||||
DWORD(WinSDK.FILE_SHARE_DELETE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_SHARE_READ: DWORD {
|
||||
DWORD(WinSDK.FILE_SHARE_READ)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_SHARE_WRITE: DWORD {
|
||||
DWORD(WinSDK.FILE_SHARE_WRITE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
package var FILE_WRITE_ATTRIBUTES: DWORD {
|
||||
DWORD(WinSDK.FILE_WRITE_ATTRIBUTES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_WRITE_DATA: DWORD {
|
||||
DWORD(WinSDK.FILE_WRITE_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_WRITE_EA: DWORD {
|
||||
DWORD(WinSDK.FILE_WRITE_EA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var GENERIC_READ: DWORD {
|
||||
DWORD(WinSDK.GENERIC_READ)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var GENERIC_WRITE: DWORD {
|
||||
DWORD(WinSDK.GENERIC_WRITE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var NO_INHERITANCE: DWORD {
|
||||
DWORD(WinSDK.NO_INHERITANCE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var OPEN_ALWAYS: DWORD {
|
||||
DWORD(WinSDK.OPEN_ALWAYS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var OPEN_EXISTING: DWORD {
|
||||
DWORD(WinSDK.OPEN_EXISTING)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SE_DACL_PROTECTED: SECURITY_DESCRIPTOR_CONTROL {
|
||||
SECURITY_DESCRIPTOR_CONTROL(WinSDK.SE_DACL_PROTECTED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SECURITY_DESCRIPTOR_REVISION: DWORD {
|
||||
DWORD(WinSDK.SECURITY_DESCRIPTOR_REVISION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SECURITY_WORLD_RID: DWORD {
|
||||
DWORD(WinSDK.SECURITY_WORLD_RID)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var STANDARD_RIGHTS_READ: DWORD {
|
||||
DWORD(WinSDK.STANDARD_RIGHTS_READ)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var STANDARD_RIGHTS_EXECUTE: DWORD {
|
||||
DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var STANDARD_RIGHTS_WRITE: DWORD {
|
||||
DWORD(WinSDK.STANDARD_RIGHTS_WRITE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SYNCHRONIZE: DWORD {
|
||||
DWORD(WinSDK.SYNCHRONIZE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var TRUNCATE_EXISTING: DWORD {
|
||||
DWORD(WinSDK.TRUNCATE_EXISTING)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,8 +0,0 @@
|
||||
import XCTest
|
||||
|
||||
import SystemTests
|
||||
|
||||
var tests = [XCTestCaseEntry]()
|
||||
tests += SystemTests.__allTests()
|
||||
|
||||
XCTMain(tests)
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Compile-only canary for MemberImportVisibility regressions: this file fails
|
||||
// to build if a C member of a type SystemPackage vends is attributed to the
|
||||
// private CSystem module.
|
||||
//
|
||||
// For new type wrappers introduced to System, access their C members here:
|
||||
// - Import the platform overlay (Glibc/Musl/Android), as consumers do.
|
||||
// - Access raw C members of vended types (e.g. CInterop.Stat) as a downstream
|
||||
// consumer would. Don't go through the Swift (e.g. Stat) wrapper since its
|
||||
// accesses happen inside System, where importing CSystem is fine.
|
||||
// - Touch every direct member the public API exposes, and the members of C
|
||||
// types it exposes through them (e.g. timespec). One field is not always a
|
||||
// safe proxy for the rest.
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#endif
|
||||
import SystemPackage
|
||||
|
||||
func _mivProbe(_ s: CInterop.Stat) {
|
||||
_ = s.st_dev
|
||||
_ = s.st_ino
|
||||
_ = s.st_mode
|
||||
_ = s.st_nlink
|
||||
_ = s.st_uid
|
||||
_ = s.st_gid
|
||||
_ = s.st_rdev
|
||||
_ = s.st_size
|
||||
_ = s.st_blksize
|
||||
_ = s.st_blocks
|
||||
_ = s.st_atim
|
||||
_ = s.st_mtim
|
||||
_ = s.st_ctim
|
||||
_ = s.st_atim.tv_sec
|
||||
_ = s.st_atim.tv_nsec
|
||||
}
|
||||
|
||||
// These are the Linux and Android field names. FreeBSD's libc module is also
|
||||
// named Glibc, but its `statfs` and `fsid_t` use the BSD names.
|
||||
#if os(Linux) || os(Android)
|
||||
func _mivProbe(_ s: CInterop.StatFS) {
|
||||
_ = s.f_type
|
||||
_ = s.f_bsize
|
||||
_ = s.f_blocks
|
||||
_ = s.f_bfree
|
||||
_ = s.f_bavail
|
||||
_ = s.f_files
|
||||
_ = s.f_ffree
|
||||
_ = s.f_fsid
|
||||
_ = s.f_namelen
|
||||
_ = s.f_frsize
|
||||
_ = s.f_flags
|
||||
}
|
||||
|
||||
func _mivProbe(_ id: CInterop.FileSystemID) {
|
||||
_ = id.__val
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user