Repository navigation
Expand file tree
/
Copy pathprocess.cpp
More file actions
1580 lines (1472 loc) · 74 KB
/
Copy pathprocess.cpp
File metadata and controls
1580 lines (1472 loc) · 74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "sys.h"
#include "handle.h"
#include "rights.h"
// This system's sandbox, which its library supplies and no C library in this
// ecosystem defines (port/libSystem.tbd); and the parts of its `fork' a
// confined start duplicates with (space.cpp).
extern "C" int sandbox_init_with_parameters(const char* profile, unsigned long long flags,
const char* const parameters[], char** error);
namespace okm {
int resource_preference();
void fork_prepare();
void fork_parent();
void fork_child();
}
#include <openkal/process.h>
#include <openkal/memory.h>
#include <openkal/task.h>
#include <openkal/time.h>
namespace okm { extern bool g_pipe_ignored_here; }
// A program image that has been started.
//
// This system has no operation that starts a program relative to a directory,
// so the directory is entered by the duplicate before it replaces itself --- a
// duplicate that exists for the length of two calls, is not a resource the
// caller receives, and is exactly what openkal declines to offer for that
// reason. The caller's own working directory is not touched, which is the
// property the interface requires and which an implementation that entered the
// directory before duplicating would not have.
namespace {
bool units_observable(); // defined beside the unit's reference (clause 7.18)
// --- confinement (0.23): this system's sandbox ---------------------------------
//
// THE RULES ARE THIS SYSTEM'S PROFILE LANGUAGE, applied to the started program
// before it is replaced (`sandbox_init_with_parameters'), and kept across the
// replacement. Everything is allowed but reading a file's content outside the
// grants and this system's own libraries, and writing outside the grants that
// are not read-only and the devices a program writes to. Asking whether a name
// exists, and what it is, is not refused: it reveals what the name is, which
// the rule above already allows a program to learn by trying.
//
// THE RULES ARE AS LONG AS THE GRANTS MAKE THEM (0.22.1). A fixed 16 KiB was
// exceeded by sixteen long grants, and the start was refused with
// kal_err_invalid, which says the request was malformed. The capacity is now
// the bound of what `build' can write --- the fixed rules, the program's name
// quoted, and each grant's name quoted in both rules --- and memory for it is
// obtained before the start. A start whose rules cannot be held fails with
// kal_err_no_memory; one whose rules outgrow the bound, which the bound
// excludes, with kal_err_no_space.
struct profile {
static constexpr okm_uptr kFixed = 1024; // the literal rules, with room
static constexpr okm_uptr kName = 1024; // F_GETPATH's MAXPATHLEN
static constexpr okm_uptr kGrant = 2 * (16 + 2 * kName + 2);
char* text = nullptr;
okm_uptr cap = 0;
okm_uptr n = 0;
profile() = default;
profile(const profile&) = delete;
profile& operator=(const profile&) = delete;
~profile() { if (text) kal_free(text, cap, 1); }
bool reserve(kal_uintptr grants, const char* program) {
okm_uptr p = 0;
while (program[p]) ++p;
cap = kFixed + 2 * p + 4 + grants * kGrant;
text = static_cast<char*>(kal_alloc(cap, 1));
return text != nullptr;
}
bool put(const char* s) { while (*s) { if (n + 1 >= cap) return false; text[n++] = *s++; } text[n] = '\0'; return true; }
bool quoted(const char* s) {
if (!put("\"")) return false;
for (; *s; ++s) {
if (n + 3 >= cap) return false;
if (*s == '"' || *s == '\\') text[n++] = '\\';
text[n++] = *s;
}
text[n] = '\0';
return put("\"");
}
int build(const okm_long* grants, const okm_u32* rights, kal_uintptr g, const char* program) {
if (!reserve(g, program)) return kal_err_no_memory;
char path[kName];
bool ok = put("(version 1)\n(allow default)\n(deny file-write* (require-not (require-any"
" (literal \"/dev/null\") (literal \"/dev/tty\") (literal \"/dev/dtracehelper\")");
for (kal_uintptr i = 0; ok && i < g; ++i) {
if (rights[i] & okm::rights::read_only) continue;
if (okm::failed(okm::sys(okm::nr_fcntl, grants[i], okm::f_getpath, reinterpret_cast<okm_long>(path)))) continue;
ok = put(" (subpath ") && quoted(path) && put(")");
}
// WHAT A PROGRAM OF THIS SYSTEM READS BEFORE ITS FIRST INSTRUCTION:
// its libraries, in /System, /usr/lib and the system's cryptex
// (/private/preboot/Cryptexes), the loader's caches, and the root
// directory itself, which the system's start reads --- refused it, a
// program is ended there (measured on macOS 15: SIGABRT, termination
// namespace 35, `deny file-read-data /'). The root's entries are names,
// which every program may learn by trying them.
ok = ok && put(")))\n(deny file-read-data (require-not (require-any"
" (literal \"/\") (subpath \"/System\") (subpath \"/usr/lib\") (subpath \"/usr/share\")"
" (subpath \"/private/var/db/dyld\") (subpath \"/private/preboot/Cryptexes\")"
" (subpath \"/Library/Apple\") (subpath \"/dev\")"
" (literal ") && quoted(program) && put(")");
for (kal_uintptr i = 0; ok && i < g; ++i) {
if (okm::failed(okm::sys(okm::nr_fcntl, grants[i], okm::f_getpath, reinterpret_cast<okm_long>(path)))) continue;
ok = put(" (subpath ") && quoted(path) && put(")");
}
return ok && put(")))\n") ? kal_ok : kal_err_no_space;
}
};
constexpr char kPreopens[] = "KAL_PREOPENS=";
constexpr okm_uptr kPreopensLen = sizeof kPreopens - 1;
constexpr okm_uptr kPidDigits = 10;
// THE TWO VARIABLES 0.23 WRITES BESIDE IT: what each grant carries
// (`KAL_GRANT_RIGHTS', read in fs.cpp) and the started program's resource
// preference (`KAL_RESOURCES', read in env.cpp). A value of either the caller
// supplied is left out.
constexpr char kRights[] = "KAL_GRANT_RIGHTS=";
constexpr okm_uptr kRightsLen = sizeof kRights - 1;
constexpr char kResources[] = "KAL_RESOURCES=";
constexpr okm_uptr kResourcesLen = sizeof kResources - 1;
bool starts_with(const char* s, kal_uintptr n, const char* key, okm_uptr klen) {
if (n < klen) return false;
for (okm_uptr i = 0; i < klen; ++i) if (s[i] != key[i]) return false;
return true;
}
// What one start conveys beside the grants' names.
struct conveyance {
char rights[4096];
okm_uptr rights_len = 0;
bool any_rights = false;
okm_long record_src[16];
kal_uintptr records = 0;
const char* resources = nullptr;
};
bool names_preopens(const char* s, kal_uintptr n) {
if (n < kPreopensLen) return false;
for (okm_uptr i = 0; i < kPreopensLen; ++i)
if (s[i] != kPreopens[i]) return false;
return true;
}
okm_uptr digits(okm_uptr v) {
okm_uptr n = 1;
while (v >= 10) { v /= 10; ++n; }
return n;
}
char* put_decimal(char* o, okm_uptr v) {
char b[24]; int i = 0;
do { b[i++] = static_cast<char>('0' + v % 10); v /= 10; } while (v);
while (i) *o++ = b[--i];
return o;
}
// Every descriptor from `from' upward is marked to close when the image is
// replaced. This kernel has no `close_range'. What it has is `/dev/fd', which
// lists the descriptors of the process reading it, so exactly those are marked;
// where it cannot be read, every number below the descriptor limit is tried,
// and an unlimited limit is taken as OPEN_MAX, which is the bound this system's
// own C library applies in the same case.
void close_on_exec_from(okm_long from) {
const okm_long dir = okm::sys(okm::nr_openat, okm::at_fdcwd,
reinterpret_cast<okm_long>("/dev/fd"),
okm::o_rdonly | okm::o_directory | okm::o_cloexec, 0);
if (!okm::failed(dir)) {
alignas(8) char buf[4096];
okm_i64 position = 0;
for (;;) {
const okm_long n = okm::sys(okm::nr_getdirentries64, dir,
reinterpret_cast<okm_long>(buf),
static_cast<okm_long>(sizeof buf),
reinterpret_cast<okm_long>(&position));
if (okm::interrupted(n)) continue;
if (okm::failed(n) || n == 0) break;
for (okm_long at = 0; at < n; ) {
const auto* d = reinterpret_cast<const okm::kdirent64*>(buf + at);
okm_long fd = 0; bool number = d->namlen > 0;
for (unsigned short c = 0; c < d->namlen; ++c) {
if (d->name[c] < '0' || d->name[c] > '9') { number = false; break; }
fd = fd * 10 + (d->name[c] - '0');
}
if (number && fd >= from && fd != dir)
okm::sys(okm::nr_fcntl, fd, okm::f_setfd, okm::fd_cloexec);
if (d->reclen == 0) break;
at += d->reclen;
}
}
okm::sys(okm::nr_close, dir);
return;
}
okm_u64 lim[2] = { 256, 256 };
okm::sys(okm::nr_getrlimit, okm::rlimit_nofile, reinterpret_cast<okm_long>(lim));
const okm_u64 bound = lim[0] > static_cast<okm_u64>(okm::open_max)
? static_cast<okm_u64>(okm::open_max) : lim[0];
for (okm_long fd = from; static_cast<okm_u64>(fd) < bound; ++fd)
okm::sys(okm::nr_fcntl, fd, okm::f_setfd, okm::fd_cloexec);
}
// The counted arrays the interface takes become the terminated arrays this
// kernel takes. Every allocation happens before the program is duplicated, so
// that the duplicate performs nothing but a few calls: a duplicate of a program
// that has more than one execution context may hold a lock no context in it
// will release.
struct vector {
char** slots = nullptr;
char* bytes = nullptr;
okm_uptr slots_bytes = 0;
okm_uptr bytes_bytes = 0;
bool ok = true;
bool build(const char** items, const kal_uintptr* lens, kal_uintptr n) {
okm_uptr total = 0;
for (kal_uintptr i = 0; i < n; ++i) total += lens[i] + 1;
slots_bytes = (n + 1) * sizeof(char*);
bytes_bytes = total == 0 ? 1 : total;
slots = static_cast<char**>(kal_alloc(slots_bytes, alignof(char*)));
bytes = static_cast<char*>(kal_alloc(bytes_bytes, 1));
if (!slots || !bytes) { ok = false; return false; }
okm_uptr at = 0;
for (kal_uintptr i = 0; i < n; ++i) {
okm::copy(bytes + at, items[i], lens[i]);
bytes[at + lens[i]] = '\0';
slots[i] = bytes + at;
at += lens[i] + 1;
}
slots[n] = nullptr;
return true;
}
// THE ENVIRONMENT, WHICH CARRIES THE NAMES OF THE GRANTED DIRECTORIES.
//
// A granted directory reaches the started program as a descriptor, and a
// descriptor carries no name. The names travel in one variable,
//
// KAL_PREOPENS=<pid>{;<fd>,<len>,<name>}
//
// which the started program reads when it first enumerates its preopens
// (`table' in fs.cpp). The arrangement and its spelling are openkal-linux's,
// which takes them from systemd's LISTEN_FDS, LISTEN_FDNAMES and LISTEN_PID;
// one spelling on both kernels is what lets a program read its grants
// without knowing which implementation started it. It is bound to the
// process it was written for in the same way: `<pid>' is ten digits written
// by the duplicate once it knows its own number, so a value inherited
// through a program that does not read it, a shell for example, names no
// one when it arrives one generation further down.
//
// Every variable of that name the caller supplied is left out, so a value
// is never forwarded; one is added only when the caller asked for grants,
// and asking for none (a count of zero) is a value with no entries.
char* pid_digits = nullptr;
char* rights_pid_digits = nullptr;
bool build_env(const char** items, const kal_uintptr* lens, kal_uintptr n,
const kal_preopen* grants, kal_uintptr g, const conveyance& c) {
auto left_out = [&](const char* s, kal_uintptr l) {
return names_preopens(s, l) || starts_with(s, l, kRights, kRightsLen)
|| starts_with(s, l, kResources, kResourcesLen);
};
kal_uintptr kept = 0;
okm_uptr total = 0;
for (kal_uintptr i = 0; i < n; ++i) {
if (left_out(items[i], lens[i])) continue;
++kept; total += lens[i] + 1;
}
okm_uptr extra = 0;
if (grants) {
extra = kPreopensLen + kPidDigits + 1;
for (kal_uintptr i = 0; i < g; ++i)
extra += 3 + digits(3 + i) + digits(grants[i].len) + grants[i].len;
}
if (c.any_rights) extra += kRightsLen + kPidDigits + c.rights_len + 1;
const okm_uptr res_len = c.resources ? okm::length(c.resources) : 0;
if (c.resources) extra += kResourcesLen + res_len + 1;
slots_bytes = (kept + (grants ? 1 : 0) + (c.any_rights ? 1 : 0) + (c.resources ? 1 : 0) + 1)
* sizeof(char*);
bytes_bytes = total + extra == 0 ? 1 : total + extra;
slots = static_cast<char**>(kal_alloc(slots_bytes, alignof(char*)));
bytes = static_cast<char*>(kal_alloc(bytes_bytes, 1));
if (!slots || !bytes) { ok = false; return false; }
okm_uptr at = 0, k = 0;
for (kal_uintptr i = 0; i < n; ++i) {
if (left_out(items[i], lens[i])) continue;
okm::copy(bytes + at, items[i], lens[i]);
bytes[at + lens[i]] = '\0';
slots[k++] = bytes + at;
at += lens[i] + 1;
}
if (grants) {
char* o = bytes + at;
slots[k++] = o;
okm::copy(o, kPreopens, kPreopensLen); o += kPreopensLen;
pid_digits = o;
okm::fill(o, '0', kPidDigits); o += kPidDigits;
for (kal_uintptr i = 0; i < g; ++i) {
*o++ = ';'; o = put_decimal(o, 3 + i);
*o++ = ','; o = put_decimal(o, grants[i].len);
*o++ = ',';
okm::copy(o, grants[i].name, grants[i].len); o += grants[i].len;
}
*o = '\0';
at = static_cast<okm_uptr>(o + 1 - bytes);
}
if (c.any_rights) {
char* o = bytes + at;
slots[k++] = o;
okm::copy(o, kRights, kRightsLen); o += kRightsLen;
rights_pid_digits = o;
okm::fill(o, '0', kPidDigits); o += kPidDigits;
okm::copy(o, c.rights, c.rights_len); o += c.rights_len;
*o = '\0';
at = static_cast<okm_uptr>(o + 1 - bytes);
}
if (c.resources) {
char* o = bytes + at;
slots[k++] = o;
okm::copy(o, kResources, kResourcesLen); o += kResourcesLen;
okm::copy(o, c.resources, res_len); o += res_len;
*o = '\0';
at = static_cast<okm_uptr>(o + 1 - bytes);
}
slots[k] = nullptr;
return true;
}
// In the duplicate, which is the first point at which the number is known.
void stamp(okm_long pid) const {
char* const where[2] = { pid_digits, rights_pid_digits };
for (char* d : where) {
if (!d) continue;
okm_long v = pid;
for (int i = static_cast<int>(kPidDigits) - 1; i >= 0; --i) {
d[i] = static_cast<char>('0' + v % 10);
v /= 10;
}
}
}
~vector() {
if (slots) kal_free(slots, slots_bytes, alignof(char*));
if (bytes) kal_free(bytes, bytes_bytes, 1);
}
};
constexpr okm_long nr_fchdir = 13;
// openkal 0.11: the unit a started program joins.
constexpr okm_long nr_setpgid = 82;
// --- reporting a replacement that failed -----------------------------------
//
// THE REPLACEMENT HAPPENS IN THE DUPLICATE, SO ITS FAILURE WAS REPORTED TO
// NOBODY. Version 0.13.
//
// A program is started here by duplicating this image and replacing the
// duplicate. The replacement is the part that can fail --- the name is absent,
// or is a directory, or is not a program, or may not be executed --- and it
// failed inside an image the caller does not have. This implementation ended
// that image with 127 and answered kal_ok with a handle, so a caller learned
// something was wrong only by waiting and reading 127, which is exactly what a
// program that RAN and exited 127 reports. openkal SPEC.md clause 11 entry 16.
//
// The arrangement is openkal-linux's: a pipe whose ends close when the image
// is replaced. Nothing arrives, the replacement happened; a value arrives, it
// did not, and the value says why.
struct exec_report {
int fd[2] = { -1, -1 };
bool armed = false;
// THE PIPE MUST NOT SIT WHERE THE DUPLICATE IS ABOUT TO PLACE SOMETHING.
// The duplicate places streams at 0, 1 and 2 and granted directories at 3
// and upwards, so a pipe that happened to hold one of those numbers would
// be closed by the very placement whose failure it exists to report --- and
// the parent would then read end-of-input and call that success.
//
// F_DUPFD_CLOEXEC answers the lowest FREE descriptor at or above a bound,
// atomically. There is no pipe2 on this kernel, so each end is marked
// close-on-exec separately before being lifted; a caller that spawns from
// one context, which is what this operation is used from, is not affected
// by the two steps not being atomic with each other.
bool open(kal_uintptr placements) {
okm_long w = -1;
const okm_long r = okm::pipe_pair(w);
if (okm::failed(r)) return false;
fd[0] = static_cast<int>(r);
fd[1] = static_cast<int>(w);
okm::sys(okm::nr_fcntl, fd[0], okm::f_setfd, okm::fd_cloexec);
okm::sys(okm::nr_fcntl, fd[1], okm::f_setfd, okm::fd_cloexec);
const okm_long floor = 3 + static_cast<okm_long>(placements);
armed = lift(fd[0], floor) && lift(fd[1], floor);
if (!armed) close_both();
return armed;
}
void close_both() {
if (fd[0] >= 0) okm::sys(okm::nr_close, fd[0]);
if (fd[1] >= 0) okm::sys(okm::nr_close, fd[1]);
fd[0] = fd[1] = -1;
}
// In the duplicate, once the replacement has returned --- which it does
// only when it did not happen.
void say(okm_long failure) const {
if (!armed) return;
okm_long value = failure;
okm::sys(okm::nr_write, fd[1],
reinterpret_cast<okm_long>(&value), sizeof value);
}
// In this image. Zero when the replacement happened, otherwise the
// kernel's own negative value for why it did not.
okm_long heard() {
if (!armed) return 0;
okm::sys(okm::nr_close, fd[1]);
fd[1] = -1;
okm_long value = 0;
okm_long n;
// A transfer this short is not divided, but it can be interrupted.
do {
n = okm::sys(okm::nr_read, fd[0],
reinterpret_cast<okm_long>(&value), sizeof value);
} while (n == -okm::e_intr);
okm::sys(okm::nr_close, fd[0]);
fd[0] = -1;
return (n == static_cast<okm_long>(sizeof value)) ? value : 0;
}
private:
static bool lift(int& f, okm_long floor) {
const okm_long n = okm::sys(okm::nr_fcntl, f, okm::f_dupfd_cloexec, floor);
if (okm::failed(n)) return false;
okm::sys(okm::nr_close, f);
f = static_cast<int>(n);
return true;
}
};
// A duplicate that could not be replaced is ended, and this image waits for it
// so that nothing is left for a caller to meet later. It is the one wait this
// implementation performs that a caller did not ask for, and it is bounded:
// the duplicate has already reached `exit'.
inline void reap(okm_long child) {
int status = 0;
okm_long r;
do {
r = okm::sys(okm::nr_wait4, child,
reinterpret_cast<okm_long>(&status), 0, 0);
} while (r == -okm::e_intr);
}
} // namespace
extern "C" {
// Starting a program. One function since openkal 0.11, where three declarations
// became one and their modifiers became positions in `kal_spawn'.
//
// AND THIS IMPLEMENTATION IS WHERE THE MISSING MODIFIER WAS ALREADY VISIBLE,
// which is worth recording rather than quietly fixing.
//
// This kernel has no `execveat', so a program named relative to a directory has
// always been started by entering that directory first --- the `fchdir(base)'
// below used to be the whole story. So a started program's working directory WAS
// `base' here, and on the other kernel it was whatever that implementation
// happened to be in. Same openkal calls, two different observable answers,
// and neither was wrong because the specification said nothing.
//
// ⇒ 0.11 gives the caller a second directory, and both implementations now enter
// the one the caller named. The divergence is gone because the thing that caused
// it --- a property nobody had declared --- is declared.
} // extern "C" (reopened below)
// --- the handles of this interface (0.17) ------------------------------------
//
// A started program's handle is its identifier. Since 0.17 two more kinds are
// told apart by the top byte: this program itself, and a program found by its
// identifier. This kernel has no descriptor for a program, so the second
// carries, above the identifier, twenty-four bits of the moment the program
// started --- what tells the program found apart from a later one given the
// same number (process.h: "records started_ns at the open").
namespace {
constexpr unsigned kind_child = 0, kind_self = 1, kind_opened = 2;
inline unsigned handle_kind(kal_process h) { return static_cast<unsigned>(h.h >> 56); }
inline okm_long handle_pid(kal_process h) { return static_cast<okm_long>(h.h & 0xffffffffu); }
// `proc_bsdinfo', as `proc_info' (PROC_PIDTBSDINFO) writes it.
struct bsdinfo {
okm_u32 flags, status, xstatus, pid, ppid, uid, gid, ruid, rgid, svuid, svgid, rfu;
char comm[16]; char name[32];
okm_u32 nfiles, pgid, pjobc, tdev, tpgid; int nice;
okm_u64 start_sec, start_usec;
};
static_assert(sizeof(bsdinfo) == 136, "proc_bsdinfo");
bool bsd(okm_long pid, bsdinfo& out) {
const okm_long r = okm::sys(okm::nr_proc_info, 2 /* PROC_INFO_CALL_PIDINFO */, pid,
3 /* PROC_PIDTBSDINFO */, 0, reinterpret_cast<okm_long>(&out),
sizeof out);
return !okm::failed(r) && r == static_cast<okm_long>(sizeof out);
}
okm_u32 start_mark(const bsdinfo& b) {
const okm_u64 us = b.start_sec * 1000000ull + b.start_usec;
return static_cast<okm_u32>((us ^ (us >> 24) ^ (us >> 48)) & 0xffffffu);
}
bool cpu_ns(okm_long pid, okm_u64& out) {
alignas(8) unsigned char ri[400] = {}; // rusage_info_v0 and some
const okm_long r = okm::sys(okm::nr_proc_info, 9 /* PROC_INFO_CALL_PIDRUSAGE */, pid,
0 /* RUSAGE_INFO_V0 */, 0, reinterpret_cast<okm_long>(ri), 0);
if (okm::failed(r)) return false;
okm_u64 user = 0, sys = 0;
okm::copy(reinterpret_cast<char*>(&user), reinterpret_cast<const char*>(ri + 16), 8);
okm::copy(reinterpret_cast<char*>(&sys), reinterpret_cast<const char*>(ri + 24), 8);
okm_u32 n = 1, d = 1;
okm::timebase(n, d);
out = (user + sys) / d * n + (user + sys) % d * n / d;
return true;
}
bool has_ended(kal_process h) {
if (handle_kind(h) == kind_self) return false;
bsdinfo b{};
if (handle_kind(h) == kind_opened) {
if (!bsd(handle_pid(h), b)) return true;
if (b.status == 5 /* SZOMB */) return true;
return start_mark(b) != static_cast<okm_u32>((h.h >> 32) & 0xffffffu);
}
alignas(8) unsigned char info[128] = {};
const okm_long r = okm::sys(okm::nr_waitid, 1 /* P_PID */, handle_pid(h),
reinterpret_cast<okm_long>(info),
0x4 | 0x1 | 0x20 /* WEXITED | WNOHANG | WNOWAIT */);
if (r == -10 /* ECHILD */) return true;
if (okm::failed(r)) return false;
int si_pid = 0;
okm::copy(reinterpret_cast<char*>(&si_pid), reinterpret_cast<const char*>(info + 8), sizeof si_pid);
return si_pid != 0;
}
// --- what a program and a unit use, and a limit on a unit (openkal 0.20) ----
//
// A PROGRAM'S MEMORY is its footprint as this kernel accounts it
// (`proc_pid_rusage', RUSAGE_INFO_V4: `ri_phys_footprint' now and
// `ri_lifetime_max_phys_footprint' at most), which is what the system's own
// tools report for a program. The kernel keeps the record of an ended program
// until it is collected, so `kal_process_wait' waits without collecting
// (WNOWAIT) and `kal_process_close' collects (0.18): what a program used remains
// readable while its handle is held.
//
// A UNIT IS A PROCESS GROUP, and this kernel lists a group's members
// (`proc_listpgrppids'): a unit's use is the sum of its members' footprints.
//
// A LIMIT IS SUPERVISED: a context started with the first limit observes the
// limited units and ends one it sees over its limit, every 500 ms below half
// the limit, 200 ms below four fifths and 100 ms above. This kernel has no
// ceiling upon a set of programs to delegate the limit to.
bool footprint(okm_long pid, okm_u64& now, okm_u64& peak) {
alignas(8) unsigned char ri[296] = {}; // rusage_info_v4
const okm_long r = okm::sys(okm::nr_proc_info, 9 /* PROC_INFO_CALL_PIDRUSAGE */, pid,
4 /* RUSAGE_INFO_V4 */, 0, reinterpret_cast<okm_long>(ri), 0);
if (okm::failed(r)) return false;
okm::copy(reinterpret_cast<char*>(&now), reinterpret_cast<const char*>(ri + 72), 8);
okm::copy(reinterpret_cast<char*>(&peak), reinterpret_cast<const char*>(ri + 240), 8);
if (peak < now) peak = now;
return true;
}
// The members of process group `unit', at most `cap' of them, into `out'.
okm_long group_members(okm_long unit, int* out, okm_long cap) {
const okm_long r = okm::sys(okm::nr_proc_info, 1 /* PROC_INFO_CALL_LISTPIDS */,
2 /* PROC_PGRP_ONLY */, unit, 0, reinterpret_cast<okm_long>(out),
cap * static_cast<okm_long>(sizeof(int)));
if (okm::failed(r)) return 0;
okm_long n = r / static_cast<okm_long>(sizeof(int));
if (n > cap) n = cap;
okm_long live = 0;
for (okm_long i = 0; i < n; ++i) if (out[i] > 0) out[live++] = out[i];
return live;
}
kal_u32 unit_use(okm_long unit, okm_u64& memory) {
int pids[1024];
const okm_long n = group_members(unit, pids, 1024);
memory = 0;
kal_u32 count = 0;
for (okm_long i = 0; i < n; ++i) {
okm_u64 now = 0, peak = 0;
if (!footprint(pids[i], now, peak)) continue;
memory += now;
++count;
}
return count;
}
// A unit this program limited. `killed' names the programs the supervisor
// ended for the limit: an ended program's group is not something this kernel
// reports reliably once it has ended, so the programs are recorded as they are
// ended.
struct limited { okm_long unit; okm_u64 limit; int ended; int count; int killed[64]; };
constexpr int kLimited = 64;
limited g_limited[kLimited];
volatile int g_limited_lock = 0;
int g_supervising = 0;
void lock_limited() { while (__atomic_exchange_n(&g_limited_lock, 1, __ATOMIC_ACQUIRE)) { } }
void unlock_limited() { __atomic_store_n(&g_limited_lock, 0, __ATOMIC_RELEASE); }
limited* row_of(okm_long unit) {
for (auto& r : g_limited) if (r.unit == unit) return &r;
return nullptr;
}
void supervise(void*) {
for (;;) {
okm_u64 worst = 0;
bool any = false;
for (int i = 0; i < kLimited; ++i) {
lock_limited();
const limited r = g_limited[i];
unlock_limited();
if (r.unit == 0 || r.limit == 0 || r.ended) continue;
any = true;
int pids[1024];
const okm_long n = group_members(r.unit, pids, 1024);
okm_u64 memory = 0;
for (okm_long k = 0; k < n; ++k) {
okm_u64 now = 0, peak = 0;
if (footprint(pids[k], now, peak)) memory += now;
}
if (n == 0) continue;
if (memory > r.limit) {
// Recorded before they are ended, so that a wait that returns
// because of the end already finds why.
lock_limited();
if (g_limited[i].unit == r.unit) {
g_limited[i].ended = 1;
for (okm_long k = 0; k < n && g_limited[i].count < 64; ++k)
g_limited[i].killed[g_limited[i].count++] = pids[k];
}
unlock_limited();
okm::sys(okm::nr_kill, -r.unit, 9 /* SIGKILL */);
continue;
}
const okm_u64 share = memory * 1000 / r.limit;
if (share > worst) worst = share;
}
if (!any) {
__atomic_store_n(&g_supervising, 0, __ATOMIC_RELEASE);
lock_limited();
bool again = false;
for (const auto& r : g_limited) if (r.unit && r.limit && !r.ended) again = true;
unlock_limited();
if (!again || __atomic_exchange_n(&g_supervising, 1, __ATOMIC_ACQ_REL)) return;
continue;
}
kal_time_sleep((worst < 500 ? 500u : worst < 800 ? 200u : 100u) * 1000u * 1000u);
}
}
// Whether a program ended on SIGKILL was ended by its unit's limit: one the
// supervisor recorded as it ended it.
bool ended_by_limit(okm_long pid) {
bool found = false;
lock_limited();
for (const auto& r : g_limited)
for (int k = 0; r.unit && k < r.count && !found; ++k) found = r.killed[k] == pid;
unlock_limited();
return found;
}
} // namespace
namespace okm {
// How a started program ended, read without collecting it; `block' waits for
// it. Shared with openkal.timeout. This kernel's `siginfo_t' places the code at
// 8, the identifier at 12 and the status at 20.
int child_outcome(okm_long pid, bool block, int* status, int* terminated, bool& ended) {
alignas(8) unsigned char info[128] = {};
okm_long r;
do r = okm::sys(okm::nr_waitid, 1 /* P_PID */, pid, reinterpret_cast<okm_long>(info),
0x4 | 0x20 | (block ? 0 : 0x1) /* WEXITED | WNOWAIT [| WNOHANG] */);
while (okm::interrupted(r));
ended = false;
if (okm::failed(r)) return okm::translate(r);
int si_code = 0, si_pid = 0, si_status = 0;
okm::copy(reinterpret_cast<char*>(&si_code), reinterpret_cast<const char*>(info + 8), sizeof si_code);
okm::copy(reinterpret_cast<char*>(&si_pid), reinterpret_cast<const char*>(info + 12), sizeof si_pid);
okm::copy(reinterpret_cast<char*>(&si_status), reinterpret_cast<const char*>(info + 20), sizeof si_status);
if (si_pid == 0 && si_code == 0) return kal_ok; // not yet
ended = true;
if (si_code == 1 /* CLD_EXITED */) {
if (status) *status = si_status & 0xff;
if (terminated) *terminated = 0;
} else {
if (status) *status = si_status;
if (terminated) *terminated = (si_status == 9 && ended_by_limit(pid)) ? KAL_TERMINATED_LIMIT : 1;
}
return kal_ok;
}
} // namespace okm
namespace {
// EVERY ENVIRONMENT ENTRY IS `NAME=value' (0.17, process.h).
bool entries_well_formed(const char** envp, const kal_uintptr* lens, kal_uintptr n) {
for (kal_uintptr i = 0; i < n; ++i) {
if (envp[i] == nullptr) return false;
kal_uintptr eq = 0;
while (eq < lens[i] && envp[i][eq] != '=') ++eq;
if (eq == 0 || eq == lens[i]) return false;
}
return true;
}
} // namespace
extern "C" {
int kal_process_self(kal_process* out) {
if (out == nullptr) return kal_err_invalid;
*out = kal_process{ (static_cast<kal_uintptr>(kind_self) << 56)
| static_cast<kal_uintptr>(okm::sys(okm::nr_getpid)) };
return kal_ok;
}
int kal_process_open_id(kal_u64 id, kal_process* out) {
if (out == nullptr || id == 0) return kal_err_invalid;
if (id > 0x7fffffffu) return kal_err_not_found;
bsdinfo b{};
if (!bsd(static_cast<okm_long>(id), b)) {
const okm_long probe = okm::sys(okm::nr_kill, static_cast<okm_long>(id), 0);
return probe == -1 /* EPERM */ ? kal_err_permission : kal_err_not_found;
}
if (b.status == 5 /* SZOMB */) return kal_err_not_found;
*out = kal_process{ (static_cast<kal_uintptr>(kind_opened) << 56)
| (static_cast<kal_uintptr>(start_mark(b)) << 32)
| static_cast<kal_uintptr>(id) };
return kal_ok;
}
int kal_process_info(kal_process p, kal_u32 wanted, kal_program_info* out) {
if (out == nullptr || p.h == 0 || out->self_size < 8) return kal_err_invalid;
const kal_u32 self = out->self_size;
kal_program_info v{};
v.self_size = self;
const okm_long pid = handle_pid(p);
v.id = static_cast<kal_u64>(pid);
v.present = KAL_PINFO_ID | KAL_PINFO_ENDED;
const bool ended = has_ended(p);
v.ended = ended ? 1u : 0u;
bsdinfo b{};
if (!ended && (wanted & KAL_PINFO_STARTED) && bsd(pid, b)) {
v.started_ns = b.start_sec * 1000000000ull + b.start_usec * 1000ull;
v.present |= KAL_PINFO_STARTED;
}
// CPU (0.21): of a started program that has ended, from the record the
// kernel keeps until it is collected, as its peak memory below.
okm_u64 c = 0;
if ((wanted & KAL_PINFO_CPU) && (!ended || handle_kind(p) == kind_child) && cpu_ns(pid, c)) {
v.cpu_ns = c;
v.present |= KAL_PINFO_CPU;
}
// MEMORY (openkal 0.20): the footprint now and at most; of a started
// program that has ended, the peak from the record the kernel keeps until it
// is collected. Only where the structure has room for the fields.
// Where the caller's structure reaches the fields: one built for 0.22 ends
// with them, and is answered as it was.
constexpr kal_u32 memory_end = static_cast<kal_u32>(__builtin_offsetof(kal_program_info, memory_peak_bytes) + 8);
constexpr kal_u32 faults_end = static_cast<kal_u32>(__builtin_offsetof(kal_program_info, faults_major) + 8);
if ((wanted & KAL_PINFO_MEMORY) && self >= memory_end
&& (!ended || handle_kind(p) == kind_child)) {
okm_u64 now = 0, peak = 0;
if (footprint(handle_kind(p) == kind_self ? okm::sys(okm::nr_getpid) : pid, now, peak)) {
v.memory_bytes = ended ? 0 : now;
v.memory_peak_bytes = peak;
v.present |= KAL_PINFO_MEMORY;
}
}
// PAGE FAULTS (0.23): this program's from the kernel's account of it
// (`getrusage'), a running one's from its task (PROC_PIDTASKINFO: every
// fault, and those that read a page in). Of an ended program this kernel
// keeps no count of faults, and none is reported.
if ((wanted & (KAL_PINFO_FAULTS | KAL_PINFO_MAJOR)) && self >= faults_end && !ended) {
okm_u64 minor = 0, major = 0;
bool ok = false;
if (handle_kind(p) == kind_self) {
okm_long ru[18] = {};
ok = !okm::failed(okm::sys(okm::nr_getrusage, 0 /* RUSAGE_SELF */, reinterpret_cast<okm_long>(ru)));
minor = static_cast<okm_u64>(ru[8]); major = static_cast<okm_u64>(ru[9]);
} else {
alignas(8) unsigned char ti[96] = {};
const okm_long r = okm::sys(okm::nr_proc_info, 2 /* PROC_INFO_CALL_PIDINFO */, pid,
4 /* PROC_PIDTASKINFO */, 0, reinterpret_cast<okm_long>(ti), sizeof ti);
if (!okm::failed(r) && r >= 64) {
int faults = 0, pageins = 0;
okm::copy(&faults, ti + 52, 4);
okm::copy(&pageins, ti + 56, 4);
major = static_cast<okm_u64>(pageins);
minor = faults > pageins ? static_cast<okm_u64>(faults - pageins) : 0;
ok = true;
}
}
if (ok) { v.faults_minor = minor; v.faults_major = major; v.present |= KAL_PINFO_FAULTS | KAL_PINFO_MAJOR; }
}
const kal_u32 n = self < sizeof v ? self : static_cast<kal_u32>(sizeof v);
okm::copy(reinterpret_cast<char*>(out), reinterpret_cast<const char*>(&v), n);
return kal_ok;
}
int kal_process_spawn(const kal_spawn* how,
const char* path, kal_uintptr path_len,
const char** argv, const kal_uintptr* argv_lens, kal_uintptr argc,
const char** envp, const kal_uintptr* envp_lens, kal_uintptr envc,
const kal_spawn_streams* streams,
kal_process* out) {
if (how == nullptr || out == nullptr) return kal_err_invalid;
const int b = okm::unpack(how->base.h);
const int w = okm::unpack(how->work.h);
if (b < 0 || w < 0) return kal_err_invalid;
if (!okm::acceptable(path, path_len)) return kal_err_invalid;
if (how->grant_count > 0 && how->grants == nullptr) return kal_err_invalid;
// A LIFETIME THIS KERNEL CANNOT BIND IS REFUSED BEFORE ANYTHING STARTS.
// The reason is unchanged from 0.10 and is stated at kal_process_props: the
// binding must hold however the caller ends, including when it is killed
// outright, and what this system offers instead is a WATCH, which needs a
// live context to notice. Composing it would move the defect from "refused"
// to "works except when it matters".
constexpr kal_uintptr nulls = KAL_SPAWN_NULL_IN | KAL_SPAWN_NULL_OUT | KAL_SPAWN_NULL_ERR;
constexpr kal_uintptr preferences = KAL_SPAWN_RESOURCES_BALANCED | KAL_SPAWN_RESOURCES_PERFORMANCE
| KAL_SPAWN_RESOURCES_ECONOMY;
if (how->flags & ~(nulls | preferences | KAL_SPAWN_CONFINE)) return kal_err_not_supported;
// ONE PREFERENCE (0.23).
const kal_uintptr preference = how->flags & preferences;
if ((preference & (preference - 1)) != 0) return kal_err_invalid;
const bool confine = (how->flags & KAL_SPAWN_CONFINE) != 0;
// THE NULL DEVICE BESIDE A STREAM AT ONE POSITION is two answers to one
// question (openkal 0.22, clause 7.15).
if (streams != nullptr
&& (((how->flags & KAL_SPAWN_NULL_IN) && streams->in.h != 0)
|| ((how->flags & KAL_SPAWN_NULL_OUT) && streams->out.h != 0)
|| ((how->flags & KAL_SPAWN_NULL_ERR) && streams->err.h != 0)))
return kal_err_invalid;
if (envc > 0 && (envp == nullptr || envp_lens == nullptr)) return kal_err_invalid;
if (!entries_well_formed(envp, envp_lens, envc)) return kal_err_invalid;
okm::terminated p(path, path_len);
if (!p.ok) return kal_err_invalid;
// Resolved before the duplication, because a failure after it would leave a
// duplicate to be reaped and a caller with an error it cannot act upon. A
// name travels in the environment, which cannot carry a zero byte.
constexpr kal_uintptr max_grants = 16;
if (how->grant_count > max_grants) return kal_err_invalid;
okm_long granted[max_grants];
for (kal_uintptr i = 0; i < how->grant_count; ++i) {
const kal_preopen& g = how->grants[i];
const int fd = okm::unpack(g.dir.h);
if (fd < 0) return kal_err_invalid;
if (g.len > okm::max_name || (g.len > 0 && g.name == nullptr)) return kal_err_invalid;
for (kal_uintptr c = 0; c < g.len; ++c)
if (g.name[c] == '\0') return kal_err_invalid;
granted[i] = fd;
}
// WHAT EACH GRANT CARRIES, AND THE PREFERENCE (0.23).
conveyance carry;
okm_u32 grant_rights[max_grants] = {};
for (kal_uintptr i = 0; i < how->grant_count; ++i) {
okm_u32 flags = 0; int record = -1; const char* prefix = ""; okm_uptr plen = 0;
if (!okm::rights::conveyed(static_cast<int>(granted[i]), &flags, &record, &prefix, &plen)) continue;
grant_rights[i] = flags;
long dest = -1;
if (record >= 0 && carry.records < 16) {
dest = static_cast<long>(3 + how->grant_count + carry.records);
carry.record_src[carry.records++] = record;
}
char entry[64];
char* o = entry;
*o++ = ';'; o = put_decimal(o, i);
*o++ = ','; o = put_decimal(o, flags);
*o++ = ',';
if (dest < 0) { *o++ = '-'; *o++ = '1'; } else o = put_decimal(o, static_cast<okm_uptr>(dest));
*o++ = ','; o = put_decimal(o, plen);
*o++ = ',';
const okm_uptr head = static_cast<okm_uptr>(o - entry);
if (carry.rights_len + head + plen >= sizeof carry.rights) return kal_err_invalid;
okm::copy(carry.rights + carry.rights_len, entry, head); carry.rights_len += head;
okm::copy(carry.rights + carry.rights_len, prefix, plen); carry.rights_len += plen;
carry.any_rights = true;
}
{
const int own = okm::resource_preference();
const int asked = preference == KAL_SPAWN_RESOURCES_PERFORMANCE ? 1
: preference == KAL_SPAWN_RESOURCES_ECONOMY ? 2
: preference == KAL_SPAWN_RESOURCES_BALANCED ? 0 : own;
carry.resources = asked == 1 ? "performance" : asked == 2 ? "economy"
: preference != 0 ? "balanced" : nullptr;
}
vector args, envs;
if (!args.build(argv, argv_lens, argc)) return kal_err_no_memory;
if (!envs.build_env(envp, envp_lens, envc, how->grants, how->grant_count, carry))
return kal_err_no_memory;
// THE PROGRAM'S NAME IS MADE ABSOLUTE BEFORE THE DIRECTORY MOVES, because
// with no `execveat' the two things `base' and `work' now mean cannot both be
// served by one `fchdir'. `F_GETPATH' answers the path of an open directory,
// which src/fs.cpp already relies on for the same reason: this kernel has no
// call that reports a working directory, so a path is obtained from the
// descriptor that names it.
char whole[1024];
kal_uintptr n = 0;
if (p.buf[0] == '/') {
while (p.buf[n] && n < sizeof whole - 1) { whole[n] = p.buf[n]; ++n; }
} else {
const okm_long r = okm::sys(okm::nr_fcntl, b, okm::f_getpath,
reinterpret_cast<okm_long>(whole));
if (okm::failed(r)) return okm::translate(r);
while (whole[n] && n < sizeof whole - 1) ++n;
if (n && whole[n - 1] != '/' && n < sizeof whole - 1) whole[n++] = '/';
for (kal_uintptr i = 0; p.buf[i] && n < sizeof whole - 1; ++i) whole[n++] = p.buf[i];
}
if (n >= sizeof whole - 1) return kal_err_invalid;
whole[n] = '\0';
// CONFINED (0.23): the rules are written here, before the duplication, and
// applied in the duplicate before it is replaced.
profile rules;
if (confine) {
const int built = rules.build(granted, grant_rights, how->grant_count, whole);
if (built != kal_ok) return built;
}
const okm_long in = streams ? static_cast<okm_long>(streams->in.h) : 0;
const okm_long ou = streams ? static_cast<okm_long>(streams->out.h) : 0;
const okm_long er = streams ? static_cast<okm_long>(streams->err.h) : 0;
// The unit, named here by a process group --- which is to say by whichever
// program formed it first. Zero for the first member; a later one is given
// the number to join.
const okm_long join = how->job ? static_cast<okm_long>(how->job->h) : 0;
const bool unit = how->job != nullptr;
// The bound is 3 + grant_count, because the placements below reach that
// far. A caller that cannot arm the report is not refused for it: `heard'
// then answers zero and this operation behaves as it did before 0.13,
// which is the same fallback openkal-linux takes.
exec_report report;
report.open(how->grant_count + carry.records);
// A CONFINED START DUPLICATES AS THIS SYSTEM'S `fork' DOES (space.cpp):
// the duplicate calls into this system's library to apply the rules, and the
// library's locks must be consistent there. Any other start calls nothing
// there, and duplicates without the protocol, as before.
bool is_duplicate = false;
if (confine) okm::fork_prepare();
const okm_long child = okm::duplicate(is_duplicate);
if (confine && !is_duplicate) okm::fork_parent();
if (okm::failed(child)) { report.close_both(); return okm::translate(child); }
// The duplicate is distinguished by the second value the call returns and
// not by the first: both images receive the same first value here. The
// reason, and what happens to an implementation that tests the first alone,
// are in src/sys.h beside the call.
if (is_duplicate) {
if (confine) okm::fork_child();
// WHAT THE STARTED PROGRAM RECEIVES IS THE THREE STREAMS AND THE GRANTED
// DIRECTORIES, AND NOTHING ELSE (SPEC.md clause 7.13).
//
// Every source is first moved above the positions being filled, because
// placing one source on its position must not overwrite another that
// still has to be read: a granted directory, a stream or the working
// directory may each occupy a number between 0 and 3+n. Placing them one
// at a time where they stood let one grant arrive as a copy of another,
// and let a placement overwrite the directory the program was to run
// in. A source that is moved has its own descriptor flag; `dup2' onto a
// different number clears it on the copy it places, including where the
// source happened to be the position itself --- which `dup2' left
// untouched, still marked to close, so that the grant never arrived.
const okm_long top = static_cast<okm_long>(3 + how->grant_count + carry.records);
auto lift = [&](okm_long fd) -> okm_long {
const okm_long r = okm::sys(okm::nr_fcntl, fd, okm::f_dupfd_cloexec, top);
if (okm::failed(r)) {
report.say(r);
okm::sys(okm::nr_exit, 127);
for (;;) { }
}
return r;
};
// THE NULL DEVICE (openkal 0.22), opened in the duplicate, so that the
// caller holds no descriptor for it; it is placed as any other source
// is, and its own descriptor is marked to close.
okm_long device = 0;
if (how->flags & nulls) {