-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathforkipc.c
More file actions
1879 lines (1679 loc) · 73.5 KB
/
Copy pathforkipc.c
File metadata and controls
1879 lines (1679 loc) · 73.5 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
/* Fork/clone IPC
*
* Copyright 2026 elfuse contributors
* Copyright 2025 Moritz Angermann, zw3rk pte. ltd.
* SPDX-License-Identifier: Apache-2.0
*
* Implements clone via posix_spawn + IPC state transfer. macOS HVF allows only
* one VM per process, so fork spawns a new elfuse process and serializes the
* full VM state (registers, memory, FDs) over a socketpair.
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <spawn.h>
#include <sys/spawn.h> /* POSIX_SPAWN_CLOEXEC_DEFAULT (macOS extension) */
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <dirent.h> /* fdopendir, for DIR* reconstruction in child */
#include <sys/wait.h>
#include <sys/clonefile.h> /* fclonefileat for CoW shm snapshots */
#include <mach-o/dyld.h>
#include "hvutil.h"
#include "utils.h"
#include "core/shim-globals.h"
#include "runtime/forkipc.h"
#include "runtime/fork-state.h"
#include "runtime/futex.h"
#include "syscall/abi.h"
#include "syscall/internal.h"
#include "syscall/mem.h"
#include "syscall/net.h" /* absock namespace IPC state */
#include "syscall/poll.h" /* wakeup_pipe_signal */
#include "syscall/proc.h"
#include "syscall/proc-pidfd.h"
#include "syscall/signal.h"
#include "debug/log.h"
#include "debug/syscall-hist.h"
/* Linux clone flags. Shared by the fork-child TID-sync emulation below and
* sys_clone further down.
*/
#define LINUX_CLONE_VM 0x00000100
#define LINUX_CLONE_VFORK 0x00004000
#define LINUX_CLONE_THREAD 0x00010000
#define LINUX_CLONE_SETTLS 0x00080000
#define LINUX_CLONE_PARENT_SETTID 0x00100000
#define LINUX_CLONE_CHILD_CLEARTID 0x00200000
#define LINUX_CLONE_CHILD_SETTID 0x01000000
/* LINUX_SIGCHLD defined in syscall_signal.h (included above) */
/* fork_child_main. */
static int fork_child_vfork_notify_fd = -1;
void fork_notify_vfork_exec(void)
{
if (fork_child_vfork_notify_fd < 0)
return;
char byte = 'X';
ssize_t n;
do {
n = write(fork_child_vfork_notify_fd, &byte, 1);
} while (n < 0 && errno == EINTR);
close(fork_child_vfork_notify_fd);
fork_child_vfork_notify_fd = -1;
}
int fork_child_main(int ipc_fd,
int vfork_notify_fd,
bool verbose,
int timeout_sec)
{
/* Reinitialize logging after posix_spawn (mutex state is undefined). */
log_init();
if (verbose)
log_set_level(LOG_DEBUG);
/* The startup syscall histogram captures dynamic-linker bring-up of the
* top-level guest only; the child resumes from the parent's snapshot, so
* its first syscalls would be steady-state traffic that confuses the dump.
* Disable before any guest syscall is dispatched.
*/
syscall_hist_disable();
/* Reset static process/thread/futex state before receiving the parent
* snapshot so the incoming metadata survives child restore.
*/
proc_init();
fork_child_vfork_notify_fd = vfork_notify_fd;
/* The header fixes the IPC protocol version and the guest identity before
* any variable-length state is trusted.
*/
ipc_header_t hdr;
if (fork_ipc_read_all(ipc_fd, &hdr, sizeof(hdr)) < 0) {
log_error("fork-child: failed to read header");
return 1;
}
if (hdr.magic != IPC_MAGIC_HEADER) {
log_error("fork-child: bad magic 0x%x", hdr.magic);
return 1;
}
if (hdr.version != IPC_VERSION) {
log_error(
"fork-child: IPC version mismatch "
"(got %u, expected %u)",
hdr.version, IPC_VERSION);
return 1;
}
log_debug("fork-child: pid=%lld ppid=%lld", (long long) hdr.child_pid,
(long long) hdr.parent_pid);
/* Static process identity lives in syscall/proc.c; use its accessor so the
* child sees the parent-assigned guest PID/PPID.
*/
proc_set_identity(hdr.child_pid, hdr.parent_pid);
proc_set_ids(hdr.uid, hdr.euid, hdr.suid, hdr.gid, hdr.egid, hdr.sgid);
proc_set_nice(hdr.nice);
absock_set_namespace_id(hdr.absock_namespace_id);
proc_set_session(hdr.sid, hdr.pgid);
/* Validate header layout fields before any size-derived arithmetic.
* guest_init / guest_init_from_shm derive interp_base, mmap_limit, and the
* high-IPA infra reserve from these inputs; underflow on tiny or malformed
* values would place pt_pool_base and friends near UINT64_MAX, which then
* feeds unchecked host-buffer offsets in pt_alloc_page and pt_at. Reject
* impossible layouts up front.
*
* Lower bound: guest_size must leave room for both mmap_limit (size - 8
* GiB) and interp_base (size - 4 GiB) plus the 16 MiB infra reserve below
* it. 8 GiB satisfies all three with margin. Upper bound: guest_size must
* fit in the negotiated IPA width. IPA bits: 36 (M1/M2) and 40 (M3+) for
* native aarch64; 48 for Rosetta guests, which need the wider Stage-2 width
* for high VAs (image at 128 TiB) even though their primary slab stays
* under 40-bit. Reject anything outside [36, 48].
*/
if (hdr.ipa_bits < 36 || hdr.ipa_bits > 48) {
log_error("fork-child: invalid ipa_bits %u", (unsigned) hdr.ipa_bits);
close(ipc_fd);
return 1;
}
if (hdr.guest_size < 0x200000000ULL ||
hdr.guest_size > (1ULL << hdr.ipa_bits)) {
log_error("fork-child: invalid guest_size 0x%llx (ipa_bits=%u)",
(unsigned long long) hdr.guest_size, (unsigned) hdr.ipa_bits);
close(ipc_fd);
return 1;
}
/* Create guest memory before receiving state so all incoming offsets can be
* bounds-checked against the negotiated guest size.
*/
guest_t g;
if (hdr.has_shm) {
/* CoW fork: receive shm fd via SCM_RIGHTS, then map MAP_PRIVATE. This
* gives the child an instant copy-on-write snapshot of the parent's
* entire guest memory, with no region enumeration or byte copying.
*/
int shm_fd = -1, shm_count = 0;
if (fork_ipc_recv_fds(ipc_fd, &shm_fd, 1, &shm_count) < 0 ||
shm_count != 1) {
log_error("fork-child: failed to receive shm fd");
close(ipc_fd);
return 1;
}
if (guest_init_from_shm(&g, shm_fd, hdr.guest_size, hdr.ipa_bits,
hdr.shm_is_clone != 0) < 0) {
log_error("fork-child: guest_init_from_shm failed");
close(ipc_fd);
return 1;
}
log_debug("fork-child: CoW fork via shm fd");
} else {
/* Legacy fork copies selected guest memory regions over IPC. */
if (guest_init(&g, hdr.guest_size, hdr.ipa_bits) < 0) {
log_error("fork-child: failed to init guest");
close(ipc_fd);
return 1;
}
}
/* Restore allocator/page-table cursors before mmap/brk can run in child.
* Validate pt_pool_next and ttbr0 against the child's own page-table pool,
* which the child just computed from hdr.guest_size + hdr.ipa_bits via
* compute_infra_layout.
*
* Range alone is not enough: pt_alloc_page advances pt_pool_next in
* GUEST_PAGE_SIZE quanta, and pt_at converts page-table GPAs straight into
* host-buffer pointers. An unaligned value passes the [base, end) gate but
* then misaligns the walker. Require:
* - pt_pool_next page-aligned relative to pt_pool_base
* - ttbr0 strictly inside the in-use pool [pt_pool_base, pt_pool_next)
* (parent must have allocated the L0 page) and page-aligned.
*/
if (hdr.pt_pool_next < g.pt_pool_base || hdr.pt_pool_next > g.pt_pool_end ||
((hdr.pt_pool_next - g.pt_pool_base) % GUEST_PAGE_SIZE) != 0) {
log_error("fork-child: invalid pt_pool_next 0x%llx",
(unsigned long long) hdr.pt_pool_next);
guest_destroy(&g);
close(ipc_fd);
return 1;
}
uint64_t ttbr0_off = hdr.ttbr0 - g.ipa_base;
if (ttbr0_off < g.pt_pool_base || ttbr0_off >= hdr.pt_pool_next ||
((ttbr0_off - g.pt_pool_base) % GUEST_PAGE_SIZE) != 0) {
log_error("fork-child: invalid ttbr0 0x%llx",
(unsigned long long) hdr.ttbr0);
guest_destroy(&g);
close(ipc_fd);
return 1;
}
g.brk_base = hdr.brk_base;
g.brk_current = hdr.brk_current;
g.elf_load_min = hdr.elf_load_min;
g.stack_base = hdr.stack_base;
g.stack_top = hdr.stack_top;
g.mmap_next = hdr.mmap_next;
g.mmap_end = hdr.mmap_end;
g.pt_pool_next = hdr.pt_pool_next;
g.ttbr0 = hdr.ttbr0;
g.mmap_rx_next = hdr.mmap_rx_next;
g.mmap_rx_end = hdr.mmap_rx_end;
/* Restore rosetta placement so the non-identity page-table entries that
* came across in the memory transfer continue to resolve. ttbr1 points at
* the L0 page the parent's PT pool emitted; that page sits inside the
* primary buffer and is copied by the region transfer below, so the child
* can reuse it without rebuilding the tree.
*/
g.is_rosetta = (hdr.is_rosetta != 0);
proc_set_rosetta_active(g.is_rosetta);
g.rosetta_guest_base = hdr.rosetta_guest_base;
g.rosetta_va_base = hdr.rosetta_va_base;
g.rosetta_size = hdr.rosetta_size;
g.rosetta_entry = hdr.rosetta_entry;
g.kbuf_gpa = hdr.kbuf_gpa;
g.ttbr1 = hdr.ttbr1;
if (g.is_rosetta && g.kbuf_gpa)
g.kbuf_base = (uint8_t *) g.host_base + g.kbuf_gpa;
/* Register state is the fork return frame captured from the parent vCPU. */
ipc_registers_t regs;
if (fork_ipc_read_all(ipc_fd, ®s, sizeof(regs)) < 0) {
log_error("fork-child: failed to read registers");
guest_destroy(&g);
return 1;
}
if (fork_ipc_recv_memory_regions(ipc_fd, &g) < 0) {
log_error("fork-child: failed to receive memory regions");
guest_destroy(&g);
return 1;
}
if (fork_ipc_recv_fd_table(ipc_fd, &g) < 0) {
log_error("fork-child: failed to receive fd table");
guest_destroy(&g);
return 1;
}
/* Must follow fork_ipc_recv_fd_table: the keepalive recv resolves each
* payload guest_fd to its (now installed) child-side host master fd.
*/
if (fork_ipc_recv_pty_keepalives(ipc_fd) < 0) {
log_error("fork-child: failed to receive pty keepalives");
guest_destroy(&g);
return 1;
}
signal_state_t sig;
if (fork_ipc_recv_process_state(ipc_fd, &g, &sig) < 0) {
log_error("fork-child: failed to receive process state");
guest_destroy(&g);
return 1;
}
/* POSIX: "Signals pending to the parent shall not be pending to the child."
* Clear pending bitmask and RT queue before applying state.
* signal_set_state() is deferred until after thread_register_main() so that
* current_thread is non-NULL and per-thread state (blocked mask, altstack)
* is properly restored.
*/
sig.pending = 0;
memset(sig.rt_queue, 0, sizeof(sig.rt_queue));
memset(sig.rt_head, 0, sizeof(sig.rt_head));
memset(sig.rt_info, 0, sizeof(sig.rt_info));
/* execve in the child needs the shim bytes after guest_reset clears memory.
*/
/* Close IPC socket */
close(ipc_fd);
/* Create the child vCPU only after all inherited state is available. */
hv_vcpu_t vcpu;
hv_vcpu_exit_t *vexit;
HV_CHECK(hv_vcpu_create(&vcpu, &vexit, NULL));
g.vcpu = vcpu;
g.exit = vexit;
/* Restore system registers. For fork children, the child enables the MMU
* directly via hv_vcpu_set_sys_reg (rather than going through the shim
* entry point) because:
* 1. The page tables are already set up (copied from parent via IPC)
* 2. The shim entry zeros ALL GPRs before ERET, which would destroy
* callee-saved registers (X19-X28, FP, LR) that the guest expects
* preserved across the clone() syscall
* 3. The child can restore the exact parent GPR state and only set X0=0
*/
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_VBAR_EL1, regs.vbar_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_MAIR_EL1, regs.mair_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TCR_EL1, regs.tcr_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TTBR0_EL1, regs.ttbr0_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TTBR1_EL1, regs.ttbr1_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_CPACR_EL1, regs.cpacr_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SP_EL0, regs.sp_el0));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SP_EL1, regs.sp_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TPIDR_EL0, regs.tpidr_el0));
/* TPIDR_EL1 is set by the host (never inherited from the parent's register
* snapshot) because it must point at the child's own shim_globals base in
* the child's IPA; shim_data_base happens to be the same value in both
* processes (layout derives from guest_size + ipa_bits which match across
* fork), but installing it explicitly keeps the child consistent with the
* bootstrap path. CONTEXTIDR_EL1 holds the per-vCPU tid (== child pid for
* the single-threaded child at this point).
*/
if (shim_globals_install_per_vcpu(vcpu, &g, hdr.child_pid) < 0) {
guest_destroy(&g);
return 1;
}
/* Enable MMU directly (page tables already in guest memory from IPC). SCTLR
* must include MMU-enable (M), caches (C, I), RES1 bits, and EL0 cache
* maintenance access (UCI, UCT) for JIT translators.
*/
uint64_t sctlr_with_mmu = SCTLR_RES1 | SCTLR_M | SCTLR_C | SCTLR_I |
SCTLR_DZE | SCTLR_UCT | SCTLR_UCI;
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SCTLR_EL1, sctlr_with_mmu));
/* Restore all 31 GPRs from parent state, then override X0=0 (child clone
* return value). This preserves X1-X30 exactly as they were when the parent
* called clone(), which is required by the Linux syscall ABI (especially
* callee-saved X19-X28, FP=X29, LR=X30).
*/
vcpu_restore_gprs(vcpu, regs.x);
vcpu_set_gpr(vcpu, 0, 0); /* Child gets 0 from clone */
vcpu_restore_simd(vcpu, ®s.simd_state);
/* Start at the clone return point in EL0 (not the shim entry). ELR_EL1
* points to the guest's clone return site. SPSR_EL1 has the saved EL0
* state. The child sets PC/CPSR for EL0t execution.
*/
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_ELR_EL1, regs.elr_el1));
HV_CHECK(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SPSR_EL1, regs.spsr_el1));
HV_CHECK(hv_vcpu_set_reg(vcpu, HV_REG_PC, regs.elr_el1));
HV_CHECK(hv_vcpu_set_reg(vcpu, HV_REG_CPSR, 0)); /* EL0t */
/* Register the fork child's main thread in the thread table. Without this,
* current_thread is NULL and any syscall handler that accesses per-thread
* state (signal masks, ptrace, CLONE_THREAD) will dereference NULL.
*/
thread_register_main(vcpu, vexit, hdr.child_pid, regs.sp_el1);
/* Emulate CLONE_CHILD_SETTID for the fork child. glibc's fork wrapper
* passes CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID so the child's TCB
* caches its own TID; without the SETTID write the child keeps the parent's
* cached TID and modern glibc trips stack-canary / TLS checks ("stack
* smashing detected"). The write goes through guest memory, valid for both
* the CoW and region-copy paths. A faulting ctid_gva is the guest's own bad
* pointer: warn and continue, matching how the kernel ignores a
* child_tidptr fault.
*
* CLONE_CHILD_CLEARTID is deliberately not honored here. The clear-and-wake
* on exit only matters to an in-process joiner waiting on the futex (that
* is how the worker-thread exit path serves pthread_join). A fork child is
* a separate process with its own address space, so its ctid lives in
* memory no other process can observe -- the parent reaps it via
* wait4/SIGCHLD, not a cross-process futex. Registering clear_child_tid
* would be inert.
*/
if (hdr.clone_flags & LINUX_CLONE_CHILD_SETTID) {
int32_t tid32 = (int32_t) hdr.child_pid;
if (guest_write_small(&g, hdr.ctid_gva, &tid32, sizeof(tid32)) < 0)
log_warn("fork-child: CHILD_SETTID write to 0x%llx failed",
(unsigned long long) hdr.ctid_gva);
}
/* Re-publish identity into the child's shim-globals cache: the CoW / region
* copy inherits the parent's pid/uid values, and the shim's identity fast
* path would otherwise return the parent's pid to the child. Identity is
* now committed via the same path the bootstrap uses.
*/
shim_globals_init(&g);
shim_globals_publish_stats_gate(&g);
shim_globals_set_trace_enabled(&g, verbose);
shim_globals_publish_pid(&g, hdr.child_pid, hdr.parent_pid);
shim_globals_publish_creds(&g, hdr.uid, hdr.euid, hdr.gid, hdr.egid);
/* proc_set_session above committed hdr.pgid/sid into proc-identity; mirror
* into the shim cache so the child's getpgid(0)/getsid(0) fast paths see
* the inherited session state from the first syscall. Publish via
* proc-identity to keep parity with the syscall-time session_lock ordering
* even though no sibling vCPU exists at this point.
*/
proc_publish_pgsid_snapshot(&g);
/* Fresh entropy for the child. Linux's vDSO getrandom epoch-bumps across
* fork; this path re-fills the ring from arc4random_buf which seeds from
* the host kernel's RNG, so parent and child do not share future urandom
* output.
*/
shim_globals_refill_urandom_ring(&g);
/* Register the singleton for the child's signal.c so its attention setters
* know which guest to update.
*/
signal_set_shim_globals_guest(&g);
/* Same for the fd-table hooks. Must precede any fd_alloc the child performs
* (the fd-table-restore step has already run above, but those slots are
* populated via direct memcpy of the parent's entries; subsequent
* open/dup/close in the child rely on this registration to keep the bitmap
* in sync).
*/
shim_globals_set_singleton(&g);
/* shim_globals_init above zeroed the urandom bitmap. Walk the inherited fd
* table and re-mark every readable FD_URANDOM slot so the shim's read fast
* path sees the correct state from the first syscall onward.
*/
shim_globals_rebuild_urandom_bitmap();
/* Now that current_thread is set, apply signal state. This must happen
* after thread_register_main() so the per-thread blocked mask and altstack
* are properly restored to the thread entry.
*/
signal_set_state(&sig);
log_debug("fork-child: entering vCPU loop");
/* The child resumes from the captured fork frame and returns 0 to EL0. */
int exit_code = vcpu_run_loop(vcpu, vexit, &g, verbose, timeout_sec);
guest_destroy(&g);
return exit_code;
}
/* sys_clone. */
/* Namespace flags. elfuse implements no namespace isolation. Both sys_clone and
* sys_clone3 reject them.
*/
#define LINUX_CLONE_NEWTIME 0x00000080
#define LINUX_CLONE_NEWNS 0x00020000
#define LINUX_CLONE_NEWCGROUP 0x02000000
#define LINUX_CLONE_NEWUTS 0x04000000
#define LINUX_CLONE_NEWIPC 0x08000000
#define LINUX_CLONE_NEWUSER 0x10000000
#define LINUX_CLONE_NEWPID 0x20000000
#define LINUX_CLONE_NEWNET 0x40000000
#define LINUX_CLONE3_NS_FLAGS \
(LINUX_CLONE_NEWNS | LINUX_CLONE_NEWCGROUP | LINUX_CLONE_NEWUTS | \
LINUX_CLONE_NEWIPC | LINUX_CLONE_NEWUSER | LINUX_CLONE_NEWPID | \
LINUX_CLONE_NEWNET | LINUX_CLONE_NEWTIME)
/* CLONE_THREAD: create a new guest thread in the same VM. */
/* Arguments passed to the worker pthread. Allocated by sys_clone_thread, freed
* by the worker after vCPU creation and register setup.
*/
typedef struct {
pthread_mutex_t lock;
pthread_cond_t cond;
bool ready;
int startup_rc;
} thread_startup_t;
typedef struct {
thread_entry_t *thread;
guest_t *guest;
thread_startup_t *startup;
bool verbose;
uint64_t child_stack, flags, tls;
/* Parent system regs to copy into the new vCPU */
uint64_t elr, spsr, vbar, ttbr0, sctlr, tcr, mair, cpacr;
uint64_t tpidr;
uint64_t gprs[31];
uint64_t sp_el1;
vcpu_simd_state_t simd_state;
} thread_create_args_t;
static void resolve_clone_stack_range(const guest_t *g,
uint64_t child_stack,
uint64_t *start_out,
uint64_t *end_out)
{
if (start_out)
*start_out = 0;
if (end_out)
*end_out = 0;
if (!g || !child_stack || child_stack <= g->ipa_base)
return;
uint64_t sp_off = child_stack - g->ipa_base;
if (sp_off == 0 || sp_off > g->guest_size)
return;
const guest_region_t *r = guest_region_find(g, sp_off - 1);
if (!r)
return;
if (start_out)
*start_out = r->start;
if (end_out)
*end_out = r->end;
}
/* Forward declaration: worker entry runs after sys_clone_thread */
static void *thread_create_and_run(void *arg);
static int64_t sys_clone_thread(hv_vcpu_t parent_vcpu,
guest_t *g,
uint64_t flags,
uint64_t child_stack,
uint64_t stack_map_start,
uint64_t stack_map_end,
uint64_t ptid_gva,
uint64_t tls,
uint64_t ctid_gva,
bool verbose)
{
thread_startup_t startup = {
.lock = PTHREAD_MUTEX_INITIALIZER,
.cond = PTHREAD_COND_INITIALIZER,
};
/* Allocate guest TID */
int64_t child_tid = proc_alloc_pid();
/* Allocate thread table slot */
if (stack_map_start >= stack_map_end)
resolve_clone_stack_range(g, child_stack, &stack_map_start,
&stack_map_end);
thread_entry_t *t = thread_alloc(child_tid, stack_map_start, stack_map_end);
if (!t) {
log_error("clone_thread: thread table full");
return -LINUX_EAGAIN;
}
/* Inherit parent's signal mask (POSIX: clone inherits blocked mask) */
if (current_thread)
t->blocked = current_thread->blocked;
/* Allocate per-thread EL1 stack (records both sp and slot in t). */
uint64_t child_sp_el1 = thread_alloc_sp_el1(g, t);
if (child_sp_el1 == 0) {
thread_deactivate(t);
return -LINUX_ENOMEM;
}
/* Capture parent register state before spawning worker. HVF binds vCPU to
* the creating thread, so the worker must call hv_vcpu_create itself. The
* parent passes all parent state via the args.
*/
uint64_t parent_elr, parent_spsr, parent_vbar, parent_ttbr0;
uint64_t parent_sctlr, parent_tcr, parent_mair, parent_cpacr;
uint64_t parent_tpidr;
parent_elr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_ELR_EL1);
parent_spsr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_SPSR_EL1);
parent_vbar = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_VBAR_EL1);
parent_ttbr0 = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_TTBR0_EL1);
parent_sctlr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_SCTLR_EL1);
parent_tcr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_TCR_EL1);
parent_mair = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_MAIR_EL1);
parent_cpacr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_CPACR_EL1);
parent_tpidr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_TPIDR_EL0);
uint64_t parent_gprs[31];
vcpu_snapshot_gprs(parent_vcpu, parent_gprs);
thread_create_args_t *tca = calloc(1, sizeof(thread_create_args_t));
if (!tca) {
thread_deactivate(t);
pthread_cond_destroy(&startup.cond);
pthread_mutex_destroy(&startup.lock);
return -LINUX_ENOMEM;
}
tca->thread = t;
tca->guest = g;
tca->startup = &startup;
tca->verbose = verbose;
tca->child_stack = child_stack;
tca->flags = flags;
tca->tls = tls;
tca->elr = parent_elr;
tca->spsr = parent_spsr;
tca->vbar = parent_vbar;
tca->ttbr0 = parent_ttbr0;
tca->sctlr = parent_sctlr;
tca->tcr = parent_tcr;
tca->mair = parent_mair;
tca->cpacr = parent_cpacr;
tca->tpidr = parent_tpidr;
memcpy(tca->gprs, parent_gprs, sizeof(parent_gprs));
tca->sp_el1 = child_sp_el1;
vcpu_snapshot_simd(parent_vcpu, &tca->simd_state);
/* CLONE_PARENT_SETTID: write child TID to parent's ptid address */
if (flags & LINUX_CLONE_PARENT_SETTID) {
int32_t tid32 = (int32_t) child_tid;
if (guest_write_small(g, ptid_gva, &tid32, sizeof(tid32)) < 0) {
free(tca);
thread_deactivate(t);
pthread_cond_destroy(&startup.cond);
pthread_mutex_destroy(&startup.lock);
return -LINUX_EFAULT;
}
}
/* CLONE_CHILD_CLEARTID: store the address for cleanup on exit */
if (flags & LINUX_CLONE_CHILD_CLEARTID) {
t->clear_child_tid = ctid_gva;
}
/* CLONE_CHILD_SETTID: write child TID to the child's ctid address. This
* writes into shared guest memory (visible to child thread).
*/
if (flags & LINUX_CLONE_CHILD_SETTID) {
int32_t tid32 = (int32_t) child_tid;
if (guest_write_small(g, ctid_gva, &tid32, sizeof(tid32)) < 0) {
free(tca);
thread_deactivate(t);
pthread_cond_destroy(&startup.cond);
pthread_mutex_destroy(&startup.lock);
return -LINUX_EFAULT;
}
}
/* Create the host pthread (joinable; exit_group joins all workers via
* thread_join_workers_cb before process exit). Threads clean up their TID
* address via CLONE_CHILD_CLEARTID + futex wake.
*/
pthread_t host_thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
int err = pthread_create(&host_thread, &attr, thread_create_and_run, tca);
pthread_attr_destroy(&attr);
if (err != 0) {
log_error("clone_thread: pthread_create failed: %s", strerror(err));
free(tca);
thread_deactivate(t);
pthread_cond_destroy(&startup.cond);
pthread_mutex_destroy(&startup.lock);
/* Roll back any SETTID writes done before pthread_create. Same
* rationale as the post-handshake failure path: clone(2) does not leave
* live-looking TIDs behind for a thread that never started.
*/
if (flags & LINUX_CLONE_PARENT_SETTID) {
int32_t zero = 0;
(void) guest_write_small(g, ptid_gva, &zero, sizeof(zero));
}
if (flags & LINUX_CLONE_CHILD_SETTID) {
int32_t zero = 0;
(void) guest_write_small(g, ctid_gva, &zero, sizeof(zero));
}
return -LINUX_EAGAIN;
}
t->host_thread = host_thread;
pthread_mutex_lock(&startup.lock);
while (!startup.ready)
pthread_cond_wait(&startup.cond, &startup.lock);
pthread_mutex_unlock(&startup.lock);
pthread_cond_destroy(&startup.cond);
pthread_mutex_destroy(&startup.lock);
if (startup.startup_rc < 0) {
/* Worker failed during HVF bring-up after the SETTID writes had already
* populated the guest TID slots. Linux clone(2) does not leave a
* live-looking TID behind for a thread that never started, so zero the
* slots before the parent sees the error.
*/
pthread_join(host_thread, NULL);
if (flags & LINUX_CLONE_PARENT_SETTID) {
int32_t zero = 0;
(void) guest_write_small(g, ptid_gva, &zero, sizeof(zero));
}
if (flags & LINUX_CLONE_CHILD_SETTID) {
int32_t zero = 0;
(void) guest_write_small(g, ctid_gva, &zero, sizeof(zero));
}
return startup.startup_rc;
}
log_debug("clone_thread: child tid=%lld created", (long long) child_tid);
return child_tid;
}
/* Worker pthread entry: creates the HVF vCPU on this thread (required by Apple
* HVF, since the vCPU is bound to the creating thread), configures all
* registers from parent state, then enters the run loop. On exit, performs
* CLONE_CHILD_CLEARTID cleanup (write 0 + FUTEX_WAKE).
*/
static void *thread_create_and_run(void *arg)
{
thread_create_args_t *tca = (thread_create_args_t *) arg;
thread_entry_t *t = tca->thread;
guest_t *g = tca->guest;
thread_startup_t *startup = tca->startup;
/* Create vCPU on THIS thread (HVF requirement) */
hv_vcpu_t vcpu;
hv_vcpu_exit_t *vexit;
hv_return_t r = hv_vcpu_create(&vcpu, &vexit, NULL);
if (r != HV_SUCCESS) {
log_error("thread tid=%lld: hv_vcpu_create failed: %d",
(long long) t->guest_tid, (int) r);
pthread_mutex_lock(&startup->lock);
startup->startup_rc = -LINUX_EIO;
startup->ready = true;
pthread_cond_broadcast(&startup->cond);
pthread_mutex_unlock(&startup->lock);
free(tca);
thread_deactivate(t);
return NULL;
}
t->vcpu = vcpu;
t->vexit = vexit;
/* Sysreg setup uses checked calls instead of HV_CHECK so the parent's
* startup handshake can roll back cleanly rather than tearing down the
* whole process on a transient HVF failure here.
*/
#define WORKER_HV(call) \
do { \
hv_return_t _r = (call); \
if (_r != HV_SUCCESS) { \
log_error("thread tid=%lld: %s failed: %d", \
(long long) t->guest_tid, #call, (int) _r); \
goto startup_failed; \
} \
} while (0)
/* Copy system registers from parent (shared page tables, same MMU config)
*/
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_VBAR_EL1, tca->vbar));
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_MAIR_EL1, tca->mair));
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TCR_EL1, tca->tcr));
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TTBR0_EL1, tca->ttbr0));
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_CPACR_EL1, tca->cpacr));
/* All worker vCPUs in the process share the same shim_globals base (one VM
* per process); a fresh TPIDR_EL1 set is still required because HVF created
* this vCPU empty. CONTEXTIDR_EL1 holds the per-thread tid that the gettid
* shim fast path returns.
*/
if (shim_globals_install_per_vcpu(vcpu, tca->guest, t->guest_tid) < 0)
goto startup_failed;
/* MMU already on, so set SCTLR with M=1 directly (page tables exist) */
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SCTLR_EL1, tca->sctlr));
/* Per-thread SP_EL1 (each vCPU needs its own EL1 exception stack) */
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SP_EL1, tca->sp_el1));
/* SP_EL0 = child_stack (provided by clone caller) */
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SP_EL0, tca->child_stack));
/* TPIDR_EL0 = thread-local storage pointer (if CLONE_SETTLS) */
if (tca->flags & LINUX_CLONE_SETTLS) {
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TPIDR_EL0, tca->tls));
} else {
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_TPIDR_EL0, tca->tpidr));
}
/* ELR_EL1 = clone return point (same as parent) */
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_ELR_EL1, tca->elr));
WORKER_HV(hv_vcpu_set_sys_reg(vcpu, HV_SYS_REG_SPSR_EL1, tca->spsr));
/* Copy all 31 GPRs from parent, then set X0=0 (child clone return). The
* vcpu_restore_gprs / vcpu_restore_simd helpers in hvutil.h abort the whole
* process on failure via HV_CHECK, which would defeat the handshake
* rollback. Open-code the restore here so transient HVF failures fall into
* the same startup_failed path as the sysreg writes.
*/
for (unsigned i = 0; i < 31; i++)
WORKER_HV(hv_vcpu_set_reg(vcpu, HV_REG_X0 + i, tca->gprs[i]));
WORKER_HV(hv_vcpu_set_reg(vcpu, HV_REG_X0, 0));
for (int i = 0; i < 32; i++)
WORKER_HV(hv_vcpu_set_simd_fp_reg(vcpu, HV_SIMD_FP_REG_Q0 + i,
tca->simd_state.v[i]));
WORKER_HV(hv_vcpu_set_reg(vcpu, HV_REG_FPSR, tca->simd_state.fpsr));
WORKER_HV(hv_vcpu_set_reg(vcpu, HV_REG_FPCR, tca->simd_state.fpcr));
/* Start at clone return point in EL0 (not shim entry) */
WORKER_HV(hv_vcpu_set_reg(vcpu, HV_REG_PC, tca->elr));
WORKER_HV(hv_vcpu_set_reg(vcpu, HV_REG_CPSR, 0)); /* EL0t */
#undef WORKER_HV
bool verbose = tca->verbose;
free(tca);
/* Set per-thread TLS pointer and enter worker run loop */
current_thread = t;
pthread_mutex_lock(&startup->lock);
startup->startup_rc = 0;
startup->ready = true;
pthread_cond_broadcast(&startup->cond);
pthread_mutex_unlock(&startup->lock);
goto startup_ok;
startup_failed:
/* HVF sysreg/GPR setup failed after vCPU creation. Drop the thread slot
* before tearing the vCPU down: thread_interrupt_all() scans the active set
* and calls hv_vcpus_exit() on each t->vcpu without a null check, so
* clearing t->vcpu while the slot is still active would let a concurrent
* exit_group hand a zero handle to HVF. Deactivating first removes the slot
* from iteration. Then destroy the vCPU on its owning thread (the only
* thread allowed to do so), free args, and finally signal the parent so it
* observes a fully torn-down state.
*/
thread_deactivate(t);
hv_vcpu_destroy(vcpu);
free(tca);
pthread_mutex_lock(&startup->lock);
startup->startup_rc = -LINUX_EIO;
startup->ready = true;
pthread_cond_broadcast(&startup->cond);
pthread_mutex_unlock(&startup->lock);
return NULL;
startup_ok:;
log_debug("thread tid=%lld starting on vCPU", (long long) t->guest_tid);
vcpu_run_loop(vcpu, vexit, g, verbose, 0);
/* Robust futex cleanup: walk the robust list and set FUTEX_OWNER_DIED on
* each held lock, then wake one waiter. Must happen before CLEARTID so
* waiters see the died bit.
*/
if (t->robust_list_head != 0)
robust_list_walk(g, t);
/* CLONE_CHILD_CLEARTID: write 0 to the address and wake one waiter. This is
* how pthread_join works in musl: the joining thread does FUTEX_WAIT on
* this address until it becomes 0.
*
* Drain any deferred munmap of this thread's stack before waking the
* joiner: the parent may reuse the freed VA as soon as it returns from
* pthread_join, and reuse must not race with the deferred unmap.
*/
bool wake_ctid = false;
if (t->clear_child_tid != 0) {
uint32_t zero = 0;
if (guest_write_small(g, t->clear_child_tid, &zero, sizeof(zero)) ==
0) {
wake_ctid = true;
} else {
log_warn(
"thread tid=%lld clear_child_tid "
"write failed (gva=0x%llx)",
(long long) t->guest_tid,
(unsigned long long) t->clear_child_tid);
}
}
mem_cleanup_deferred_stack_unmaps(g, t);
if (wake_ctid)
futex_wake_one(g, t->clear_child_tid);
log_debug("thread tid=%lld exiting", (long long) t->guest_tid);
hv_vcpu_destroy(vcpu);
thread_deactivate(t);
/* When all CLONE_THREAD workers have exited and only the main thread
* remains, interrupt its futex_wait. In real Linux, child exit delivers
* SIGCHLD which interrupts futex_wait with -EINTR. elfuse simulates this
* through the futex interrupt API.
*/
if (thread_active_count() == 1) {
log_debug(
"last worker exited, interrupting "
"main thread futex_wait/poll");
futex_interrupt_request();
wakeup_pipe_signal();
thread_interrupt_all();
}
return NULL;
}
/* CLONE_VM creates a thread sharing guest memory and waitable via wait4. */
/* Worker entry for vm-clone child threads. Nearly identical to
* thread_create_and_run but sets vm-clone exit semantics.
*/
static void *vm_clone_thread_run(void *arg);
static int64_t sys_clone_vm(hv_vcpu_t parent_vcpu,
guest_t *g,
uint64_t flags,
uint64_t child_stack,
uint64_t stack_map_start,
uint64_t stack_map_end,
uint64_t ptid_gva,
uint64_t tls,
uint64_t ctid_gva,
bool verbose)
{
/* Allocate guest TID */
int64_t child_tid = proc_alloc_pid();
/* Allocate thread table slot */
if (stack_map_start >= stack_map_end)
resolve_clone_stack_range(g, child_stack, &stack_map_start,
&stack_map_end);
thread_entry_t *t = thread_alloc(child_tid, stack_map_start, stack_map_end);
if (!t) {
log_error("clone_vm: thread table full");
return -LINUX_EAGAIN;
}
/* Mark as VM-clone child (waitable via wait4, not CLONE_THREAD) */
t->is_vm_clone = true;
t->parent_tid = current_thread ? current_thread->guest_tid : 0;
t->exit_signal = (int) (flags & 0xFF); /* Low byte = exit signal */
if (t->exit_signal == 0)
t->exit_signal = LINUX_SIGCHLD;
/* Inherit parent's signal mask */
if (current_thread)
t->blocked = current_thread->blocked;
/* Allocate per-thread EL1 stack (records both sp and slot in t). */
uint64_t child_sp_el1 = thread_alloc_sp_el1(g, t);
if (child_sp_el1 == 0) {
thread_deactivate(t);
return -LINUX_ENOMEM;
}
/* Capture parent register state */
uint64_t parent_elr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_ELR_EL1);
uint64_t parent_spsr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_SPSR_EL1);
uint64_t parent_vbar = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_VBAR_EL1);
uint64_t parent_ttbr0 = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_TTBR0_EL1);
uint64_t parent_sctlr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_SCTLR_EL1);
uint64_t parent_tcr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_TCR_EL1);
uint64_t parent_mair = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_MAIR_EL1);
uint64_t parent_cpacr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_CPACR_EL1);
uint64_t parent_tpidr = vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_TPIDR_EL0);
uint64_t parent_gprs[31];
vcpu_snapshot_gprs(parent_vcpu, parent_gprs);
thread_create_args_t *tca = calloc(1, sizeof(thread_create_args_t));
if (!tca) {
thread_deactivate(t);
return -LINUX_ENOMEM;
}
tca->thread = t;
tca->guest = g;
tca->verbose = verbose;
tca->child_stack = child_stack
? child_stack
: vcpu_get_sysreg(parent_vcpu, HV_SYS_REG_SP_EL0);
tca->flags = flags;
tca->tls = tls;
tca->elr = parent_elr;
tca->spsr = parent_spsr;
tca->vbar = parent_vbar;
tca->ttbr0 = parent_ttbr0;
tca->sctlr = parent_sctlr;
tca->tcr = parent_tcr;
tca->mair = parent_mair;
tca->cpacr = parent_cpacr;
tca->tpidr = parent_tpidr;
memcpy(tca->gprs, parent_gprs, sizeof(parent_gprs));