miri/shims/unix/
foreign_items.rs

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
use std::ffi::OsStr;
use std::str;

use rustc_abi::Size;
use rustc_middle::ty::Ty;
use rustc_middle::ty::layout::LayoutOf;
use rustc_span::Symbol;
use rustc_target::callconv::{Conv, FnAbi};

use self::shims::unix::android::foreign_items as android;
use self::shims::unix::freebsd::foreign_items as freebsd;
use self::shims::unix::linux::foreign_items as linux;
use self::shims::unix::macos::foreign_items as macos;
use self::shims::unix::solarish::foreign_items as solarish;
use crate::concurrency::cpu_affinity::CpuAffinityMask;
use crate::shims::alloc::EvalContextExt as _;
use crate::shims::unix::*;
use crate::*;

pub fn is_dyn_sym(name: &str, target_os: &str) -> bool {
    match name {
        // Used for tests.
        "isatty" => true,
        // `signal` is set up as a weak symbol in `init_extern_statics` (on Android) so we might as
        // well allow it in `dlsym`.
        "signal" => true,
        // needed at least on macOS to avoid file-based fallback in getrandom
        "getentropy" | "getrandom" => true,
        // Give specific OSes a chance to allow their symbols.
        _ =>
            match target_os {
                "android" => android::is_dyn_sym(name),
                "freebsd" => freebsd::is_dyn_sym(name),
                "linux" => linux::is_dyn_sym(name),
                "macos" => macos::is_dyn_sym(name),
                "solaris" | "illumos" => solarish::is_dyn_sym(name),
                _ => false,
            },
    }
}

impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
    // Querying system information
    fn sysconf(&mut self, val: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let name = this.read_scalar(val)?.to_i32()?;
        // FIXME: Which of these are POSIX, and which are GNU/Linux?
        // At least the names seem to all also exist on macOS.
        let sysconfs: &[(&str, fn(&MiriInterpCx<'_>) -> Scalar)] = &[
            ("_SC_PAGESIZE", |this| Scalar::from_int(this.machine.page_size, this.pointer_size())),
            ("_SC_PAGE_SIZE", |this| Scalar::from_int(this.machine.page_size, this.pointer_size())),
            ("_SC_NPROCESSORS_CONF", |this| {
                Scalar::from_int(this.machine.num_cpus, this.pointer_size())
            }),
            ("_SC_NPROCESSORS_ONLN", |this| {
                Scalar::from_int(this.machine.num_cpus, this.pointer_size())
            }),
            // 512 seems to be a reasonable default. The value is not critical, in
            // the sense that getpwuid_r takes and checks the buffer length.
            ("_SC_GETPW_R_SIZE_MAX", |this| Scalar::from_int(512, this.pointer_size())),
            // Miri doesn't have a fixed limit on FDs, but we may be limited in terms of how
            // many *host* FDs we can open. Just use some arbitrary, pretty big value;
            // this can be adjusted if it causes problems.
            // The spec imposes a minimum of `_POSIX_OPEN_MAX` (20).
            ("_SC_OPEN_MAX", |this| Scalar::from_int(2_i32.pow(16), this.pointer_size())),
        ];
        for &(sysconf_name, value) in sysconfs {
            let sysconf_name = this.eval_libc_i32(sysconf_name);
            if sysconf_name == name {
                return interp_ok(value(this));
            }
        }
        throw_unsup_format!("unimplemented sysconf name: {}", name)
    }

    fn strerror_r(
        &mut self,
        errnum: &OpTy<'tcx>,
        buf: &OpTy<'tcx>,
        buflen: &OpTy<'tcx>,
    ) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let errnum = this.read_scalar(errnum)?;
        let buf = this.read_pointer(buf)?;
        let buflen = this.read_target_usize(buflen)?;
        let error = this.try_errnum_to_io_error(errnum)?;
        let formatted = match error {
            Some(err) => format!("{err}"),
            None => format!("<unknown errnum in strerror_r: {errnum}>"),
        };
        let (complete, _) = this.write_os_str_to_c_str(OsStr::new(&formatted), buf, buflen)?;
        if complete {
            interp_ok(Scalar::from_i32(0))
        } else {
            interp_ok(Scalar::from_i32(this.eval_libc_i32("ERANGE")))
        }
    }

    fn emulate_foreign_item_inner(
        &mut self,
        link_name: Symbol,
        abi: &FnAbi<'tcx, Ty<'tcx>>,
        args: &[OpTy<'tcx>],
        dest: &MPlaceTy<'tcx>,
    ) -> InterpResult<'tcx, EmulateItemResult> {
        let this = self.eval_context_mut();

        // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern.
        #[rustfmt::skip]
        match link_name.as_str() {
            // Environment related shims
            "getenv" => {
                let [name] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.getenv(name)?;
                this.write_pointer(result, dest)?;
            }
            "unsetenv" => {
                let [name] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.unsetenv(name)?;
                this.write_scalar(result, dest)?;
            }
            "setenv" => {
                let [name, value, overwrite] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.read_scalar(overwrite)?.to_i32()?;
                let result = this.setenv(name, value)?;
                this.write_scalar(result, dest)?;
            }
            "getcwd" => {
                let [buf, size] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.getcwd(buf, size)?;
                this.write_pointer(result, dest)?;
            }
            "chdir" => {
                let [path] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.chdir(path)?;
                this.write_scalar(result, dest)?;
            }
            "getpid" => {
                let [] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.getpid()?;
                this.write_scalar(result, dest)?;
            }
            "sysconf" => {
                let [val] =
                    this.check_shim(abi, Conv::C, link_name, args)?;
                let result = this.sysconf(val)?;
                this.write_scalar(result, dest)?;
            }
            // File descriptors
            "read" => {
                let [fd, buf, count] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let buf = this.read_pointer(buf)?;
                let count = this.read_target_usize(count)?;
                this.read(fd, buf, count, None, dest)?;
            }
            "write" => {
                let [fd, buf, n] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let buf = this.read_pointer(buf)?;
                let count = this.read_target_usize(n)?;
                trace!("Called write({:?}, {:?}, {:?})", fd, buf, count);
                this.write(fd, buf, count, None, dest)?;
            }
            "pread" => {
                let [fd, buf, count, offset] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let buf = this.read_pointer(buf)?;
                let count = this.read_target_usize(count)?;
                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
                this.read(fd, buf, count, Some(offset), dest)?;
            }
            "pwrite" => {
                let [fd, buf, n, offset] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let buf = this.read_pointer(buf)?;
                let count = this.read_target_usize(n)?;
                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
                trace!("Called pwrite({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
                this.write(fd, buf, count, Some(offset), dest)?;
            }
            "pread64" => {
                let [fd, buf, count, offset] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let buf = this.read_pointer(buf)?;
                let count = this.read_target_usize(count)?;
                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off64_t").size)?;
                this.read(fd, buf, count, Some(offset), dest)?;
            }
            "pwrite64" => {
                let [fd, buf, n, offset] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let buf = this.read_pointer(buf)?;
                let count = this.read_target_usize(n)?;
                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off64_t").size)?;
                trace!("Called pwrite64({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
                this.write(fd, buf, count, Some(offset), dest)?;
            }
            "close" => {
                let [fd] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.close(fd)?;
                this.write_scalar(result, dest)?;
            }
            "fcntl" => {
                // `fcntl` is variadic. The argument count is checked based on the first argument
                // in `this.fcntl()`, so we do not use `check_shim` here.
                this.check_abi_and_shim_symbol_clash(abi, Conv::C , link_name)?;
                let result = this.fcntl(args)?;
                this.write_scalar(result, dest)?;
            }
            "dup" => {
                let [old_fd] = this.check_shim(abi, Conv::C , link_name, args)?;
                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
                let new_fd = this.dup(old_fd)?;
                this.write_scalar(new_fd, dest)?;
            }
            "dup2" => {
                let [old_fd, new_fd] = this.check_shim(abi, Conv::C , link_name, args)?;
                let old_fd = this.read_scalar(old_fd)?.to_i32()?;
                let new_fd = this.read_scalar(new_fd)?.to_i32()?;
                let result = this.dup2(old_fd, new_fd)?;
                this.write_scalar(result, dest)?;
            }
            "flock" => {
                let [fd, op] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let op = this.read_scalar(op)?.to_i32()?;
                let result = this.flock(fd, op)?;
                this.write_scalar(result, dest)?;
            }

            // File and file system access
            "open" | "open64" => {
                // `open` is variadic, the third argument is only present when the second argument has O_CREAT (or on linux O_TMPFILE, but miri doesn't support that) set
                this.check_abi_and_shim_symbol_clash(abi, Conv::C , link_name)?;
                let result = this.open(args)?;
                this.write_scalar(result, dest)?;
            }
            "unlink" => {
                let [path] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.unlink(path)?;
                this.write_scalar(result, dest)?;
            }
            "symlink" => {
                let [target, linkpath] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.symlink(target, linkpath)?;
                this.write_scalar(result, dest)?;
            }
            "rename" => {
                let [oldpath, newpath] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.rename(oldpath, newpath)?;
                this.write_scalar(result, dest)?;
            }
            "mkdir" => {
                let [path, mode] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.mkdir(path, mode)?;
                this.write_scalar(result, dest)?;
            }
            "rmdir" => {
                let [path] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.rmdir(path)?;
                this.write_scalar(result, dest)?;
            }
            "opendir" => {
                let [name] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.opendir(name)?;
                this.write_scalar(result, dest)?;
            }
            "closedir" => {
                let [dirp] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.closedir(dirp)?;
                this.write_scalar(result, dest)?;
            }
            "lseek64" => {
                let [fd, offset, whence] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let offset = this.read_scalar(offset)?.to_i64()?;
                let whence = this.read_scalar(whence)?.to_i32()?;
                let result = this.lseek64(fd, offset.into(), whence)?;
                this.write_scalar(result, dest)?;
            }
            "lseek" => {
                let [fd, offset, whence] = this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
                let whence = this.read_scalar(whence)?.to_i32()?;
                let result = this.lseek64(fd, offset, whence)?;
                this.write_scalar(result, dest)?;
            }
            "ftruncate64" => {
                let [fd, length] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let length = this.read_scalar(length)?.to_i64()?;
                let result = this.ftruncate64(fd, length.into())?;
                this.write_scalar(result, dest)?;
            }
            "ftruncate" => {
                let [fd, length] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let fd = this.read_scalar(fd)?.to_i32()?;
                let length = this.read_scalar(length)?.to_int(this.libc_ty_layout("off_t").size)?;
                let result = this.ftruncate64(fd, length)?;
                this.write_scalar(result, dest)?;
            }
            "fsync" => {
                let [fd] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.fsync(fd)?;
                this.write_scalar(result, dest)?;
            }
            "fdatasync" => {
                let [fd] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.fdatasync(fd)?;
                this.write_scalar(result, dest)?;
            }
            "readlink" => {
                let [pathname, buf, bufsize] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.readlink(pathname, buf, bufsize)?;
                this.write_scalar(Scalar::from_target_isize(result, this), dest)?;
            }
            "posix_fadvise" => {
                let [fd, offset, len, advice] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                this.read_scalar(fd)?.to_i32()?;
                this.read_target_isize(offset)?;
                this.read_target_isize(len)?;
                this.read_scalar(advice)?.to_i32()?;
                // fadvise is only informational, we can ignore it.
                this.write_null(dest)?;
            }
            "realpath" => {
                let [path, resolved_path] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.realpath(path, resolved_path)?;
                this.write_scalar(result, dest)?;
            }
            "mkstemp" => {
                let [template] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.mkstemp(template)?;
                this.write_scalar(result, dest)?;
            }

            // Unnamed sockets and pipes
            "socketpair" => {
                let [domain, type_, protocol, sv] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.socketpair(domain, type_, protocol, sv)?;
                this.write_scalar(result, dest)?;
            }
            "pipe" => {
                let [pipefd] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pipe2(pipefd, /*flags*/ None)?;
                this.write_scalar(result, dest)?;
            }
            "pipe2" => {
                // Currently this function does not exist on all Unixes, e.g. on macOS.
                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "solaris" | "illumos") {
                    throw_unsup_format!(
                        "`pipe2` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }
                let [pipefd, flags] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pipe2(pipefd, Some(flags))?;
                this.write_scalar(result, dest)?;
            }

            // Time
            "gettimeofday" => {
                let [tv, tz] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.gettimeofday(tv, tz)?;
                this.write_scalar(result, dest)?;
            }
            "localtime_r" => {
                let [timep, result_op] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.localtime_r(timep, result_op)?;
                this.write_pointer(result, dest)?;
            }
            "clock_gettime" => {
                let [clk_id, tp] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.clock_gettime(clk_id, tp)?;
                this.write_scalar(result, dest)?;
            }

            // Allocation
            "posix_memalign" => {
                let [memptr, align, size] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.posix_memalign(memptr, align, size)?;
                this.write_scalar(result, dest)?;
            }

            "mmap" => {
                let [addr, length, prot, flags, fd, offset] = this.check_shim(abi, Conv::C , link_name, args)?;
                let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?;
                let ptr = this.mmap(addr, length, prot, flags, fd, offset)?;
                this.write_scalar(ptr, dest)?;
            }
            "munmap" => {
                let [addr, length] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.munmap(addr, length)?;
                this.write_scalar(result, dest)?;
            }

            "reallocarray" => {
                // Currently this function does not exist on all Unixes, e.g. on macOS.
                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "android") {
                    throw_unsup_format!(
                        "`reallocarray` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }
                let [ptr, nmemb, size] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let ptr = this.read_pointer(ptr)?;
                let nmemb = this.read_target_usize(nmemb)?;
                let size = this.read_target_usize(size)?;
                // reallocarray checks a possible overflow and returns ENOMEM
                // if that happens.
                //
                // Linux: https://www.unix.com/man-page/linux/3/reallocarray/
                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=reallocarray
                match this.compute_size_in_bytes(Size::from_bytes(size), nmemb) {
                    None => {
                        this.set_last_error(LibcError("ENOMEM"))?;
                        this.write_null(dest)?;
                    }
                    Some(len) => {
                        let res = this.realloc(ptr, len.bytes())?;
                        this.write_pointer(res, dest)?;
                    }
                }
            }
            "aligned_alloc" => {
                // This is a C11 function, we assume all Unixes have it.
                // (MSVC explicitly does not support this.)
                let [align, size] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let res = this.aligned_alloc(align, size)?;
                this.write_pointer(res, dest)?;
            }

            // Dynamic symbol loading
            "dlsym" => {
                let [handle, symbol] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.read_target_usize(handle)?;
                let symbol = this.read_pointer(symbol)?;
                let name = this.read_c_str(symbol)?;
                if let Ok(name) = str::from_utf8(name) && is_dyn_sym(name, &this.tcx.sess.target.os) {
                    let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str(name)));
                    this.write_pointer(ptr, dest)?;
                } else {
                    this.write_null(dest)?;
                }
            }

            // Thread-local storage
            "pthread_key_create" => {
                let [key, dtor] = this.check_shim(abi, Conv::C , link_name, args)?;
                let key_place = this.deref_pointer_as(key, this.libc_ty_layout("pthread_key_t"))?;
                let dtor = this.read_pointer(dtor)?;

                // Extract the function type out of the signature (that seems easier than constructing it ourselves).
                let dtor = if !this.ptr_is_null(dtor)? {
                    Some(this.get_ptr_fn(dtor)?.as_instance()?)
                } else {
                    None
                };

                // Figure out how large a pthread TLS key actually is.
                // To this end, deref the argument type. This is `libc::pthread_key_t`.
                let key_type = key.layout.ty
                    .builtin_deref(true)
                    .ok_or_else(|| err_ub_format!(
                        "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
                    ))?;
                let key_layout = this.layout_of(key_type)?;

                // Create key and write it into the memory where `key_ptr` wants it.
                let key = this.machine.tls.create_tls_key(dtor, key_layout.size)?;
                this.write_scalar(Scalar::from_uint(key, key_layout.size), &key_place)?;

                // Return success (`0`).
                this.write_null(dest)?;
            }
            "pthread_key_delete" => {
                let [key] = this.check_shim(abi, Conv::C , link_name, args)?;
                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
                this.machine.tls.delete_tls_key(key)?;
                // Return success (0)
                this.write_null(dest)?;
            }
            "pthread_getspecific" => {
                let [key] = this.check_shim(abi, Conv::C , link_name, args)?;
                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
                let active_thread = this.active_thread();
                let ptr = this.machine.tls.load_tls(key, active_thread, this)?;
                this.write_scalar(ptr, dest)?;
            }
            "pthread_setspecific" => {
                let [key, new_ptr] = this.check_shim(abi, Conv::C , link_name, args)?;
                let key = this.read_scalar(key)?.to_bits(key.layout.size)?;
                let active_thread = this.active_thread();
                let new_data = this.read_scalar(new_ptr)?;
                this.machine.tls.store_tls(key, active_thread, new_data, &*this.tcx)?;

                // Return success (`0`).
                this.write_null(dest)?;
            }

            // Synchronization primitives
            "pthread_mutexattr_init" => {
                let [attr] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_mutexattr_init(attr)?;
                this.write_null(dest)?;
            }
            "pthread_mutexattr_settype" => {
                let [attr, kind] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pthread_mutexattr_settype(attr, kind)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_mutexattr_destroy" => {
                let [attr] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_mutexattr_destroy(attr)?;
                this.write_null(dest)?;
            }
            "pthread_mutex_init" => {
                let [mutex, attr] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_mutex_init(mutex, attr)?;
                this.write_null(dest)?;
            }
            "pthread_mutex_lock" => {
                let [mutex] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_mutex_lock(mutex, dest)?;
            }
            "pthread_mutex_trylock" => {
                let [mutex] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pthread_mutex_trylock(mutex)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_mutex_unlock" => {
                let [mutex] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pthread_mutex_unlock(mutex)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_mutex_destroy" => {
                let [mutex] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_mutex_destroy(mutex)?;
                this.write_int(0, dest)?;
            }
            "pthread_rwlock_rdlock" => {
                let [rwlock] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_rwlock_rdlock(rwlock, dest)?;
            }
            "pthread_rwlock_tryrdlock" => {
                let [rwlock] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pthread_rwlock_tryrdlock(rwlock)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_rwlock_wrlock" => {
                let [rwlock] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_rwlock_wrlock(rwlock, dest)?;
            }
            "pthread_rwlock_trywrlock" => {
                let [rwlock] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pthread_rwlock_trywrlock(rwlock)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_rwlock_unlock" => {
                let [rwlock] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_rwlock_unlock(rwlock)?;
                this.write_null(dest)?;
            }
            "pthread_rwlock_destroy" => {
                let [rwlock] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_rwlock_destroy(rwlock)?;
                this.write_null(dest)?;
            }
            "pthread_condattr_init" => {
                let [attr] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_condattr_init(attr)?;
                this.write_null(dest)?;
            }
            "pthread_condattr_setclock" => {
                let [attr, clock_id] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.pthread_condattr_setclock(attr, clock_id)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_condattr_getclock" => {
                let [attr, clock_id] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_condattr_getclock(attr, clock_id)?;
                this.write_null(dest)?;
            }
            "pthread_condattr_destroy" => {
                let [attr] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_condattr_destroy(attr)?;
                this.write_null(dest)?;
            }
            "pthread_cond_init" => {
                let [cond, attr] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_cond_init(cond, attr)?;
                this.write_null(dest)?;
            }
            "pthread_cond_signal" => {
                let [cond] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_cond_signal(cond)?;
                this.write_null(dest)?;
            }
            "pthread_cond_broadcast" => {
                let [cond] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_cond_broadcast(cond)?;
                this.write_null(dest)?;
            }
            "pthread_cond_wait" => {
                let [cond, mutex] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_cond_wait(cond, mutex, dest)?;
            }
            "pthread_cond_timedwait" => {
                let [cond, mutex, abstime] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_cond_timedwait(cond, mutex, abstime, dest)?;
            }
            "pthread_cond_destroy" => {
                let [cond] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_cond_destroy(cond)?;
                this.write_null(dest)?;
            }

            // Threading
            "pthread_create" => {
                let [thread, attr, start, arg] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.pthread_create(thread, attr, start, arg)?;
                this.write_null(dest)?;
            }
            "pthread_join" => {
                let [thread, retval] = this.check_shim(abi, Conv::C , link_name, args)?;
                let res = this.pthread_join(thread, retval)?;
                this.write_scalar(res, dest)?;
            }
            "pthread_detach" => {
                let [thread] = this.check_shim(abi, Conv::C , link_name, args)?;
                let res = this.pthread_detach(thread)?;
                this.write_scalar(res, dest)?;
            }
            "pthread_self" => {
                let [] = this.check_shim(abi, Conv::C , link_name, args)?;
                let res = this.pthread_self()?;
                this.write_scalar(res, dest)?;
            }
            "sched_yield" => {
                let [] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.sched_yield()?;
                this.write_null(dest)?;
            }
            "nanosleep" => {
                let [req, rem] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.nanosleep(req, rem)?;
                this.write_scalar(result, dest)?;
            }
            "sched_getaffinity" => {
                // Currently this function does not exist on all Unixes, e.g. on macOS.
                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "android") {
                    throw_unsup_format!(
                        "`sched_getaffinity` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }

                let [pid, cpusetsize, mask] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let pid = this.read_scalar(pid)?.to_u32()?;
                let cpusetsize = this.read_target_usize(cpusetsize)?;
                let mask = this.read_pointer(mask)?;

                // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid
                let thread_id = match pid {
                    0 => this.active_thread(),
                    _ => throw_unsup_format!("`sched_getaffinity` is only supported with a pid of 0 (indicating the current thread)"),
                };

                // The mask is stored in chunks, and the size must be a whole number of chunks.
                let chunk_size = CpuAffinityMask::chunk_size(this);

                if this.ptr_is_null(mask)? {
                    this.set_last_error_and_return(LibcError("EFAULT"), dest)?;
                } else if cpusetsize == 0 || cpusetsize.checked_rem(chunk_size).unwrap() != 0 {
                    // we only copy whole chunks of size_of::<c_ulong>()
                    this.set_last_error_and_return(LibcError("EINVAL"), dest)?;
                } else if let Some(cpuset) = this.machine.thread_cpu_affinity.get(&thread_id) {
                    let cpuset = cpuset.clone();
                    // we only copy whole chunks of size_of::<c_ulong>()
                    let byte_count = Ord::min(cpuset.as_slice().len(), cpusetsize.try_into().unwrap());
                    this.write_bytes_ptr(mask, cpuset.as_slice()[..byte_count].iter().copied())?;
                    this.write_null(dest)?;
                } else {
                    // The thread whose ID is pid could not be found
                    this.set_last_error_and_return(LibcError("ESRCH"), dest)?;
                }
            }
            "sched_setaffinity" => {
                // Currently this function does not exist on all Unixes, e.g. on macOS.
                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "android") {
                    throw_unsup_format!(
                        "`sched_setaffinity` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }

                let [pid, cpusetsize, mask] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let pid = this.read_scalar(pid)?.to_u32()?;
                let cpusetsize = this.read_target_usize(cpusetsize)?;
                let mask = this.read_pointer(mask)?;

                // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid
                let thread_id = match pid {
                    0 => this.active_thread(),
                    _ => throw_unsup_format!("`sched_setaffinity` is only supported with a pid of 0 (indicating the current thread)"),
                };

                if this.ptr_is_null(mask)? {
                    this.set_last_error_and_return(LibcError("EFAULT"), dest)?;
                } else {
                    // NOTE: cpusetsize might be smaller than `CpuAffinityMask::CPU_MASK_BYTES`.
                    // Any unspecified bytes are treated as zero here (none of the CPUs are configured).
                    // This is not exactly documented, so we assume that this is the behavior in practice.
                    let bits_slice = this.read_bytes_ptr_strip_provenance(mask, Size::from_bytes(cpusetsize))?;
                    // This ignores the bytes beyond `CpuAffinityMask::CPU_MASK_BYTES`
                    let bits_array: [u8; CpuAffinityMask::CPU_MASK_BYTES] =
                        std::array::from_fn(|i| bits_slice.get(i).copied().unwrap_or(0));
                    match CpuAffinityMask::from_array(this, this.machine.num_cpus, bits_array) {
                        Some(cpuset) => {
                            this.machine.thread_cpu_affinity.insert(thread_id, cpuset);
                            this.write_null(dest)?;
                        }
                        None => {
                            // The intersection between the mask and the available CPUs was empty.
                            this.set_last_error_and_return(LibcError("EINVAL"), dest)?;
                        }
                    }
                }
            }

            // Miscellaneous
            "isatty" => {
                let [fd] = this.check_shim(abi, Conv::C , link_name, args)?;
                let result = this.isatty(fd)?;
                this.write_scalar(result, dest)?;
            }
            "pthread_atfork" => {
                let [prepare, parent, child] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.read_pointer(prepare)?;
                this.read_pointer(parent)?;
                this.read_pointer(child)?;
                // We do not support forking, so there is nothing to do here.
                this.write_null(dest)?;
            }
            "getentropy" => {
                // This function is non-standard but exists with the same signature and behavior on
                // Linux, macOS, FreeBSD and Solaris/Illumos.
                if !matches!(&*this.tcx.sess.target.os, "linux" | "macos" | "freebsd" | "illumos" | "solaris" | "android") {
                    throw_unsup_format!(
                        "`getentropy` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }

                let [buf, bufsize] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let buf = this.read_pointer(buf)?;
                let bufsize = this.read_target_usize(bufsize)?;

                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
                // Linux: https://man7.org/linux/man-pages/man3/getentropy.3.html
                // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html
                // Solaris/Illumos: https://illumos.org/man/3C/getentropy
                if bufsize > 256 {
                    this.set_last_error_and_return(LibcError("EIO"), dest)?;
                } else {
                    this.gen_random(buf, bufsize)?;
                    this.write_null(dest)?;
                }
            }

            "strerror_r" => {
                let [errnum, buf, buflen] =
                    this.check_shim(abi, Conv::C, link_name, args)?;
                let result = this.strerror_r(errnum, buf, buflen)?;
                this.write_scalar(result, dest)?;
            }

            "getrandom" => {
                // This function is non-standard but exists with the same signature and behavior on
                // Linux, FreeBSD and Solaris/Illumos.
                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "illumos" | "solaris" | "android") {
                    throw_unsup_format!(
                        "`getrandom` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }
                let [ptr, len, flags] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let ptr = this.read_pointer(ptr)?;
                let len = this.read_target_usize(len)?;
                let _flags = this.read_scalar(flags)?.to_i32()?;
                // We ignore the flags, just always use the same PRNG / host RNG.
                this.gen_random(ptr, len)?;
                this.write_scalar(Scalar::from_target_usize(len, this), dest)?;
            }
            "arc4random_buf" => {
                // This function is non-standard but exists with the same signature and
                // same behavior (eg never fails) on FreeBSD and Solaris/Illumos.
                if !matches!(&*this.tcx.sess.target.os, "freebsd" | "illumos" | "solaris") {
                    throw_unsup_format!(
                        "`arc4random_buf` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }
                let [ptr, len] = this.check_shim(abi, Conv::C , link_name, args)?;
                let ptr = this.read_pointer(ptr)?;
                let len = this.read_target_usize(len)?;
                this.gen_random(ptr, len)?;
            }
            "_Unwind_RaiseException" => {
                // This is not formally part of POSIX, but it is very wide-spread on POSIX systems.
                // It was originally specified as part of the Itanium C++ ABI:
                // https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html#base-throw.
                // On Linux it is
                // documented as part of the LSB:
                // https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/baselib--unwind-raiseexception.html
                // Basically every other UNIX uses the exact same api though. Arm also references
                // back to the Itanium C++ ABI for the definition of `_Unwind_RaiseException` for
                // arm64:
                // https://github.com/ARM-software/abi-aa/blob/main/cppabi64/cppabi64.rst#toc-entry-35
                // For arm32 they did something custom, but similar enough that the same
                // `_Unwind_RaiseException` impl in miri should work:
                // https://github.com/ARM-software/abi-aa/blob/main/ehabi32/ehabi32.rst
                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "illumos" | "solaris" | "android" | "macos") {
                    throw_unsup_format!(
                        "`_Unwind_RaiseException` is not supported on {}",
                        this.tcx.sess.target.os
                    );
                }
                // This function looks and behaves excatly like miri_start_unwind.
                let [payload] = this.check_shim(abi, Conv::C, link_name, args)?;
                this.handle_miri_start_unwind(payload)?;
                return interp_ok(EmulateItemResult::NeedsUnwind);
            }
            "getuid" => {
                let [] = this.check_shim(abi, Conv::C , link_name, args)?;
                // For now, just pretend we always have this fixed UID.
                this.write_int(UID, dest)?;
            }

            // Incomplete shims that we "stub out" just to get pre-main initialization code to work.
            // These shims are enabled only when the caller is in the standard library.
            "pthread_attr_getguardsize"
            if this.frame_in_std() => {
                let [_attr, guard_size] = this.check_shim(abi, Conv::C , link_name, args)?;
                let guard_size = this.deref_pointer(guard_size)?;
                let guard_size_layout = this.libc_ty_layout("size_t");
                this.write_scalar(Scalar::from_uint(this.machine.page_size, guard_size_layout.size), &guard_size)?;

                // Return success (`0`).
                this.write_null(dest)?;
            }

            | "pthread_attr_init"
            | "pthread_attr_destroy"
            if this.frame_in_std() => {
                let [_] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.write_null(dest)?;
            }
            | "pthread_attr_setstacksize"
            if this.frame_in_std() => {
                let [_, _] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.write_null(dest)?;
            }

            "pthread_attr_getstack"
            if this.frame_in_std() => {
                // We don't support "pthread_attr_setstack", so we just pretend all stacks have the same values here.
                // Hence we can mostly ignore the input `attr_place`.
                let [attr_place, addr_place, size_place] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                let _attr_place = this.deref_pointer_as(attr_place, this.libc_ty_layout("pthread_attr_t"))?;
                let addr_place = this.deref_pointer(addr_place)?;
                let size_place = this.deref_pointer(size_place)?;

                this.write_scalar(
                    Scalar::from_uint(this.machine.stack_addr, this.pointer_size()),
                    &addr_place,
                )?;
                this.write_scalar(
                    Scalar::from_uint(this.machine.stack_size, this.pointer_size()),
                    &size_place,
                )?;

                // Return success (`0`).
                this.write_null(dest)?;
            }

            | "signal"
            | "sigaltstack"
            if this.frame_in_std() => {
                let [_, _] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.write_null(dest)?;
            }
            | "sigaction"
            | "mprotect"
            if this.frame_in_std() => {
                let [_, _, _] = this.check_shim(abi, Conv::C , link_name, args)?;
                this.write_null(dest)?;
            }

            "getpwuid_r" | "__posix_getpwuid_r"
            if this.frame_in_std() => {
                // getpwuid_r is the standard name, __posix_getpwuid_r is used on solarish
                let [uid, pwd, buf, buflen, result] =
                    this.check_shim(abi, Conv::C , link_name, args)?;
                this.check_no_isolation("`getpwuid_r`")?;

                let uid = this.read_scalar(uid)?.to_u32()?;
                let pwd = this.deref_pointer_as(pwd, this.libc_ty_layout("passwd"))?;
                let buf = this.read_pointer(buf)?;
                let buflen = this.read_target_usize(buflen)?;
                let result = this.deref_pointer(result)?;

                // Must be for "us".
                if uid != UID {
                    throw_unsup_format!("`getpwuid_r` on other users is not supported");
                }

                // Reset all fields to `uninit` to make sure nobody reads them.
                // (This is a std-only shim so we are okay with such hacks.)
                this.write_uninit(&pwd)?;

                // We only set the home_dir field.
                #[allow(deprecated)]
                let home_dir = std::env::home_dir().unwrap();
                let (written, _) = this.write_path_to_c_str(&home_dir, buf, buflen)?;
                let pw_dir = this.project_field_named(&pwd, "pw_dir")?;
                this.write_pointer(buf, &pw_dir)?;

                if written {
                    this.write_pointer(pwd.ptr(), &result)?;
                    this.write_null(dest)?;
                } else {
                    this.write_null(&result)?;
                    this.write_scalar(this.eval_libc("ERANGE"), dest)?;
                }
            }

            // Platform-specific shims
            _ => {
                let target_os = &*this.tcx.sess.target.os;
                return match target_os {
                    "android" => android::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest),
                    "freebsd" => freebsd::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest),
                    "linux" => linux::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest),
                    "macos" => macos::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest),
                    "solaris" | "illumos" => solarish::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest),
                    _ => interp_ok(EmulateItemResult::NotSupported),
                };
            }
        };

        interp_ok(EmulateItemResult::NeedsReturn)
    }
}