miri/shims/unix/
sync.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
use std::sync::atomic::{AtomicBool, Ordering};

use rustc_abi::Size;

use crate::concurrency::sync::LAZY_INIT_COOKIE;
use crate::*;

/// Do a bytewise comparison of the two places, using relaxed atomic reads. This is used to check if
/// a synchronization primitive matches its static initializer value.
///
/// The reads happen in chunks of 4, so all racing accesses must also use that access size.
fn bytewise_equal_atomic_relaxed<'tcx>(
    ecx: &MiriInterpCx<'tcx>,
    left: &MPlaceTy<'tcx>,
    right: &MPlaceTy<'tcx>,
) -> InterpResult<'tcx, bool> {
    let size = left.layout.size;
    assert_eq!(size, right.layout.size);

    // We do this in chunks of 4, so that we are okay to race with (sufficiently aligned)
    // 4-byte atomic accesses.
    assert!(size.bytes() % 4 == 0);
    for i in 0..(size.bytes() / 4) {
        let offset = Size::from_bytes(i.strict_mul(4));
        let load = |place: &MPlaceTy<'tcx>| {
            let byte = place.offset(offset, ecx.machine.layouts.u32, ecx)?;
            ecx.read_scalar_atomic(&byte, AtomicReadOrd::Relaxed)?.to_u32()
        };
        let left = load(left)?;
        let right = load(right)?;
        if left != right {
            return interp_ok(false);
        }
    }

    interp_ok(true)
}

// # pthread_mutexattr_t
// We store some data directly inside the type, ignoring the platform layout:
// - kind: i32

#[inline]
fn mutexattr_kind_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, u64> {
    interp_ok(match &*ecx.tcx.sess.target.os {
        "linux" | "illumos" | "solaris" | "macos" | "freebsd" | "android" => 0,
        os => throw_unsup_format!("`pthread_mutexattr` is not supported on {os}"),
    })
}

fn mutexattr_get_kind<'tcx>(
    ecx: &MiriInterpCx<'tcx>,
    attr_ptr: &OpTy<'tcx>,
) -> InterpResult<'tcx, i32> {
    ecx.deref_pointer_and_read(
        attr_ptr,
        mutexattr_kind_offset(ecx)?,
        ecx.libc_ty_layout("pthread_mutexattr_t"),
        ecx.machine.layouts.i32,
    )?
    .to_i32()
}

fn mutexattr_set_kind<'tcx>(
    ecx: &mut MiriInterpCx<'tcx>,
    attr_ptr: &OpTy<'tcx>,
    kind: i32,
) -> InterpResult<'tcx, ()> {
    ecx.deref_pointer_and_write(
        attr_ptr,
        mutexattr_kind_offset(ecx)?,
        Scalar::from_i32(kind),
        ecx.libc_ty_layout("pthread_mutexattr_t"),
        ecx.machine.layouts.i32,
    )
}

/// To differentiate "the mutex kind has not been changed" from
/// "the mutex kind has been set to PTHREAD_MUTEX_DEFAULT and that is
/// equal to some other mutex kind", we make the default value of this
/// field *not* PTHREAD_MUTEX_DEFAULT but this special flag.
const PTHREAD_MUTEX_KIND_UNCHANGED: i32 = 0x8000000;

/// Translates the mutex kind from what is stored in pthread_mutexattr_t to our enum.
fn mutexattr_translate_kind<'tcx>(
    ecx: &MiriInterpCx<'tcx>,
    kind: i32,
) -> InterpResult<'tcx, MutexKind> {
    interp_ok(if kind == (ecx.eval_libc_i32("PTHREAD_MUTEX_NORMAL")) {
        MutexKind::Normal
    } else if kind == ecx.eval_libc_i32("PTHREAD_MUTEX_ERRORCHECK") {
        MutexKind::ErrorCheck
    } else if kind == ecx.eval_libc_i32("PTHREAD_MUTEX_RECURSIVE") {
        MutexKind::Recursive
    } else if kind == ecx.eval_libc_i32("PTHREAD_MUTEX_DEFAULT")
        || kind == PTHREAD_MUTEX_KIND_UNCHANGED
    {
        // We check this *last* since PTHREAD_MUTEX_DEFAULT may be numerically equal to one of the
        // others, and we want an explicit `mutexattr_settype` to work as expected.
        MutexKind::Default
    } else {
        throw_unsup_format!("unsupported type of mutex: {kind}");
    })
}

// # pthread_mutex_t
// We store some data directly inside the type, ignoring the platform layout:
// - init: u32

/// The mutex kind.
#[derive(Debug, Clone, Copy)]
enum MutexKind {
    Normal,
    Default,
    Recursive,
    ErrorCheck,
}

#[derive(Debug, Clone, Copy)]
struct PthreadMutex {
    id: MutexId,
    kind: MutexKind,
}

/// To ensure an initialized mutex that was moved somewhere else can be distinguished from
/// a statically initialized mutex that is used the first time, we pick some offset within
/// `pthread_mutex_t` and use it as an "initialized" flag.
fn mutex_init_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, Size> {
    let offset = match &*ecx.tcx.sess.target.os {
        "linux" | "illumos" | "solaris" | "freebsd" | "android" => 0,
        // macOS stores a signature in the first bytes, so we move to offset 4.
        "macos" => 4,
        os => throw_unsup_format!("`pthread_mutex` is not supported on {os}"),
    };
    let offset = Size::from_bytes(offset);

    // Sanity-check this against PTHREAD_MUTEX_INITIALIZER (but only once):
    // the `init` field must start out not equal to INIT_COOKIE.
    static SANITY: AtomicBool = AtomicBool::new(false);
    if !SANITY.swap(true, Ordering::Relaxed) {
        let check_static_initializer = |name| {
            let static_initializer = ecx.eval_path(&["libc", name]);
            let init_field =
                static_initializer.offset(offset, ecx.machine.layouts.u32, ecx).unwrap();
            let init = ecx.read_scalar(&init_field).unwrap().to_u32().unwrap();
            assert_ne!(
                init, LAZY_INIT_COOKIE,
                "{name} is incompatible with our initialization cookie"
            );
        };

        check_static_initializer("PTHREAD_MUTEX_INITIALIZER");
        // Check non-standard initializers.
        match &*ecx.tcx.sess.target.os {
            "linux" => {
                check_static_initializer("PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP");
                check_static_initializer("PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP");
                check_static_initializer("PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP");
            }
            "illumos" | "solaris" | "macos" | "freebsd" | "android" => {
                // No non-standard initializers.
            }
            os => throw_unsup_format!("`pthread_mutex` is not supported on {os}"),
        }
    }

    interp_ok(offset)
}

/// Eagerly create and initialize a new mutex.
fn mutex_create<'tcx>(
    ecx: &mut MiriInterpCx<'tcx>,
    mutex_ptr: &OpTy<'tcx>,
    kind: MutexKind,
) -> InterpResult<'tcx, PthreadMutex> {
    let mutex = ecx.deref_pointer(mutex_ptr)?;
    let id = ecx.machine.sync.mutex_create();
    let data = PthreadMutex { id, kind };
    ecx.lazy_sync_init(&mutex, mutex_init_offset(ecx)?, data)?;
    interp_ok(data)
}

/// Returns the `MutexId` of the mutex stored at `mutex_op`.
///
/// `mutex_get_id` will also check if the mutex has been moved since its first use and
/// return an error if it has.
fn mutex_get_data<'tcx, 'a>(
    ecx: &'a mut MiriInterpCx<'tcx>,
    mutex_ptr: &OpTy<'tcx>,
) -> InterpResult<'tcx, PthreadMutex> {
    let mutex = ecx.deref_pointer(mutex_ptr)?;
    ecx.lazy_sync_get_data(
        &mutex,
        mutex_init_offset(ecx)?,
        || throw_ub_format!("`pthread_mutex_t` can't be moved after first use"),
        |ecx| {
            let kind = mutex_kind_from_static_initializer(ecx, &mutex)?;
            let id = ecx.machine.sync.mutex_create();
            interp_ok(PthreadMutex { id, kind })
        },
    )
}

/// Returns the kind of a static initializer.
fn mutex_kind_from_static_initializer<'tcx>(
    ecx: &MiriInterpCx<'tcx>,
    mutex: &MPlaceTy<'tcx>,
) -> InterpResult<'tcx, MutexKind> {
    // All the static initializers recognized here *must* be checked in `mutex_init_offset`!
    let is_initializer =
        |name| bytewise_equal_atomic_relaxed(ecx, mutex, &ecx.eval_path(&["libc", name]));

    // PTHREAD_MUTEX_INITIALIZER is recognized on all targets.
    if is_initializer("PTHREAD_MUTEX_INITIALIZER")? {
        return interp_ok(MutexKind::Default);
    }
    // Support additional platform-specific initializers.
    match &*ecx.tcx.sess.target.os {
        "linux" =>
            if is_initializer("PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP")? {
                return interp_ok(MutexKind::Recursive);
            } else if is_initializer("PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP")? {
                return interp_ok(MutexKind::ErrorCheck);
            },
        _ => {}
    }
    throw_unsup_format!("unsupported static initializer used for `pthread_mutex_t`");
}

// # pthread_rwlock_t
// We store some data directly inside the type, ignoring the platform layout:
// - init: u32

#[derive(Debug, Copy, Clone)]
struct PthreadRwLock {
    id: RwLockId,
}

fn rwlock_init_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, Size> {
    let offset = match &*ecx.tcx.sess.target.os {
        "linux" | "illumos" | "solaris" | "freebsd" | "android" => 0,
        // macOS stores a signature in the first bytes, so we move to offset 4.
        "macos" => 4,
        os => throw_unsup_format!("`pthread_rwlock` is not supported on {os}"),
    };
    let offset = Size::from_bytes(offset);

    // Sanity-check this against PTHREAD_RWLOCK_INITIALIZER (but only once):
    // the `init` field must start out not equal to LAZY_INIT_COOKIE.
    static SANITY: AtomicBool = AtomicBool::new(false);
    if !SANITY.swap(true, Ordering::Relaxed) {
        let static_initializer = ecx.eval_path(&["libc", "PTHREAD_RWLOCK_INITIALIZER"]);
        let init_field = static_initializer.offset(offset, ecx.machine.layouts.u32, ecx).unwrap();
        let init = ecx.read_scalar(&init_field).unwrap().to_u32().unwrap();
        assert_ne!(
            init, LAZY_INIT_COOKIE,
            "PTHREAD_RWLOCK_INITIALIZER is incompatible with our initialization cookie"
        );
    }

    interp_ok(offset)
}

fn rwlock_get_data<'tcx>(
    ecx: &mut MiriInterpCx<'tcx>,
    rwlock_ptr: &OpTy<'tcx>,
) -> InterpResult<'tcx, PthreadRwLock> {
    let rwlock = ecx.deref_pointer(rwlock_ptr)?;
    ecx.lazy_sync_get_data(
        &rwlock,
        rwlock_init_offset(ecx)?,
        || throw_ub_format!("`pthread_rwlock_t` can't be moved after first use"),
        |ecx| {
            if !bytewise_equal_atomic_relaxed(
                ecx,
                &rwlock,
                &ecx.eval_path(&["libc", "PTHREAD_RWLOCK_INITIALIZER"]),
            )? {
                throw_unsup_format!("unsupported static initializer used for `pthread_rwlock_t`");
            }
            let id = ecx.machine.sync.rwlock_create();
            interp_ok(PthreadRwLock { id })
        },
    )
}

// # pthread_condattr_t
// We store some data directly inside the type, ignoring the platform layout:
// - clock: i32

#[inline]
fn condattr_clock_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, u64> {
    interp_ok(match &*ecx.tcx.sess.target.os {
        "linux" | "illumos" | "solaris" | "freebsd" | "android" => 0,
        // macOS does not have a clock attribute.
        os => throw_unsup_format!("`pthread_condattr` clock field is not supported on {os}"),
    })
}

fn condattr_get_clock_id<'tcx>(
    ecx: &MiriInterpCx<'tcx>,
    attr_ptr: &OpTy<'tcx>,
) -> InterpResult<'tcx, i32> {
    ecx.deref_pointer_and_read(
        attr_ptr,
        condattr_clock_offset(ecx)?,
        ecx.libc_ty_layout("pthread_condattr_t"),
        ecx.machine.layouts.i32,
    )?
    .to_i32()
}

fn condattr_set_clock_id<'tcx>(
    ecx: &mut MiriInterpCx<'tcx>,
    attr_ptr: &OpTy<'tcx>,
    clock_id: i32,
) -> InterpResult<'tcx, ()> {
    ecx.deref_pointer_and_write(
        attr_ptr,
        condattr_clock_offset(ecx)?,
        Scalar::from_i32(clock_id),
        ecx.libc_ty_layout("pthread_condattr_t"),
        ecx.machine.layouts.i32,
    )
}

/// Translates the clock from what is stored in pthread_condattr_t to our enum.
fn condattr_translate_clock_id<'tcx>(
    ecx: &MiriInterpCx<'tcx>,
    raw_id: i32,
) -> InterpResult<'tcx, ClockId> {
    interp_ok(if raw_id == ecx.eval_libc_i32("CLOCK_REALTIME") {
        ClockId::Realtime
    } else if raw_id == ecx.eval_libc_i32("CLOCK_MONOTONIC") {
        ClockId::Monotonic
    } else {
        throw_unsup_format!("unsupported clock id: {raw_id}");
    })
}

// # pthread_cond_t
// We store some data directly inside the type, ignoring the platform layout:
// - init: u32

fn cond_init_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, Size> {
    let offset = match &*ecx.tcx.sess.target.os {
        "linux" | "illumos" | "solaris" | "freebsd" | "android" => 0,
        // macOS stores a signature in the first bytes, so we move to offset 4.
        "macos" => 4,
        os => throw_unsup_format!("`pthread_cond` is not supported on {os}"),
    };
    let offset = Size::from_bytes(offset);

    // Sanity-check this against PTHREAD_COND_INITIALIZER (but only once):
    // the `init` field must start out not equal to LAZY_INIT_COOKIE.
    static SANITY: AtomicBool = AtomicBool::new(false);
    if !SANITY.swap(true, Ordering::Relaxed) {
        let static_initializer = ecx.eval_path(&["libc", "PTHREAD_COND_INITIALIZER"]);
        let init_field = static_initializer.offset(offset, ecx.machine.layouts.u32, ecx).unwrap();
        let init = ecx.read_scalar(&init_field).unwrap().to_u32().unwrap();
        assert_ne!(
            init, LAZY_INIT_COOKIE,
            "PTHREAD_COND_INITIALIZER is incompatible with our initialization cookie"
        );
    }

    interp_ok(offset)
}

#[derive(Debug, Clone, Copy)]
enum ClockId {
    Realtime,
    Monotonic,
}

#[derive(Debug, Copy, Clone)]
struct PthreadCondvar {
    id: CondvarId,
    clock: ClockId,
}

fn cond_create<'tcx>(
    ecx: &mut MiriInterpCx<'tcx>,
    cond_ptr: &OpTy<'tcx>,
    clock: ClockId,
) -> InterpResult<'tcx, PthreadCondvar> {
    let cond = ecx.deref_pointer(cond_ptr)?;
    let id = ecx.machine.sync.condvar_create();
    let data = PthreadCondvar { id, clock };
    ecx.lazy_sync_init(&cond, cond_init_offset(ecx)?, data)?;
    interp_ok(data)
}

fn cond_get_data<'tcx>(
    ecx: &mut MiriInterpCx<'tcx>,
    cond_ptr: &OpTy<'tcx>,
) -> InterpResult<'tcx, PthreadCondvar> {
    let cond = ecx.deref_pointer(cond_ptr)?;
    ecx.lazy_sync_get_data(
        &cond,
        cond_init_offset(ecx)?,
        || throw_ub_format!("`pthread_cond_t` can't be moved after first use"),
        |ecx| {
            if !bytewise_equal_atomic_relaxed(
                ecx,
                &cond,
                &ecx.eval_path(&["libc", "PTHREAD_COND_INITIALIZER"]),
            )? {
                throw_unsup_format!("unsupported static initializer used for `pthread_cond_t`");
            }
            // This used the static initializer. The clock there is always CLOCK_REALTIME.
            let id = ecx.machine.sync.condvar_create();
            interp_ok(PthreadCondvar { id, clock: ClockId::Realtime })
        },
    )
}

impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
    fn pthread_mutexattr_init(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        mutexattr_set_kind(this, attr_op, PTHREAD_MUTEX_KIND_UNCHANGED)?;

        interp_ok(())
    }

    fn pthread_mutexattr_settype(
        &mut self,
        attr_op: &OpTy<'tcx>,
        kind_op: &OpTy<'tcx>,
    ) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let kind = this.read_scalar(kind_op)?.to_i32()?;
        if kind == this.eval_libc_i32("PTHREAD_MUTEX_NORMAL")
            || kind == this.eval_libc_i32("PTHREAD_MUTEX_DEFAULT")
            || kind == this.eval_libc_i32("PTHREAD_MUTEX_ERRORCHECK")
            || kind == this.eval_libc_i32("PTHREAD_MUTEX_RECURSIVE")
        {
            // Make sure we do not mix this up with the "unchanged" kind.
            assert_ne!(kind, PTHREAD_MUTEX_KIND_UNCHANGED);
            mutexattr_set_kind(this, attr_op, kind)?;
        } else {
            let einval = this.eval_libc_i32("EINVAL");
            return interp_ok(Scalar::from_i32(einval));
        }

        interp_ok(Scalar::from_i32(0))
    }

    fn pthread_mutexattr_destroy(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        // Destroying an uninit pthread_mutexattr is UB, so check to make sure it's not uninit.
        mutexattr_get_kind(this, attr_op)?;

        // To catch double-destroys, we de-initialize the mutexattr.
        // This is technically not right and might lead to false positives. For example, the below
        // code is *likely* sound, even assuming uninit numbers are UB, but Miri complains.
        //
        // let mut x: MaybeUninit<libc::pthread_mutexattr_t> = MaybeUninit::zeroed();
        // libc::pthread_mutexattr_init(x.as_mut_ptr());
        // libc::pthread_mutexattr_destroy(x.as_mut_ptr());
        // x.assume_init();
        //
        // However, the way libstd uses the pthread APIs works in our favor here, so we can get away with this.
        // This can always be revisited to have some external state to catch double-destroys
        // but not complain about the above code. See https://github.com/rust-lang/miri/pull/1933
        this.write_uninit(
            &this.deref_pointer_as(attr_op, this.libc_ty_layout("pthread_mutexattr_t"))?,
        )?;

        interp_ok(())
    }

    fn pthread_mutex_init(
        &mut self,
        mutex_op: &OpTy<'tcx>,
        attr_op: &OpTy<'tcx>,
    ) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        let attr = this.read_pointer(attr_op)?;
        let kind = if this.ptr_is_null(attr)? {
            MutexKind::Default
        } else {
            mutexattr_translate_kind(this, mutexattr_get_kind(this, attr_op)?)?
        };

        mutex_create(this, mutex_op, kind)?;

        interp_ok(())
    }

    fn pthread_mutex_lock(
        &mut self,
        mutex_op: &OpTy<'tcx>,
        dest: &MPlaceTy<'tcx>,
    ) -> InterpResult<'tcx> {
        let this = self.eval_context_mut();

        let mutex = mutex_get_data(this, mutex_op)?;

        let ret = if this.mutex_is_locked(mutex.id) {
            let owner_thread = this.mutex_get_owner(mutex.id);
            if owner_thread != this.active_thread() {
                this.mutex_enqueue_and_block(mutex.id, Some((Scalar::from_i32(0), dest.clone())));
                return interp_ok(());
            } else {
                // Trying to acquire the same mutex again.
                match mutex.kind {
                    MutexKind::Default =>
                        throw_ub_format!(
                            "trying to acquire default mutex already locked by the current thread"
                        ),
                    MutexKind::Normal => throw_machine_stop!(TerminationInfo::Deadlock),
                    MutexKind::ErrorCheck => this.eval_libc_i32("EDEADLK"),
                    MutexKind::Recursive => {
                        this.mutex_lock(mutex.id);
                        0
                    }
                }
            }
        } else {
            // The mutex is unlocked. Let's lock it.
            this.mutex_lock(mutex.id);
            0
        };
        this.write_scalar(Scalar::from_i32(ret), dest)?;
        interp_ok(())
    }

    fn pthread_mutex_trylock(&mut self, mutex_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let mutex = mutex_get_data(this, mutex_op)?;

        interp_ok(Scalar::from_i32(if this.mutex_is_locked(mutex.id) {
            let owner_thread = this.mutex_get_owner(mutex.id);
            if owner_thread != this.active_thread() {
                this.eval_libc_i32("EBUSY")
            } else {
                match mutex.kind {
                    MutexKind::Default | MutexKind::Normal | MutexKind::ErrorCheck =>
                        this.eval_libc_i32("EBUSY"),
                    MutexKind::Recursive => {
                        this.mutex_lock(mutex.id);
                        0
                    }
                }
            }
        } else {
            // The mutex is unlocked. Let's lock it.
            this.mutex_lock(mutex.id);
            0
        }))
    }

    fn pthread_mutex_unlock(&mut self, mutex_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let mutex = mutex_get_data(this, mutex_op)?;

        if let Some(_old_locked_count) = this.mutex_unlock(mutex.id)? {
            // The mutex was locked by the current thread.
            interp_ok(Scalar::from_i32(0))
        } else {
            // The mutex was locked by another thread or not locked at all. See
            // the “Unlock When Not Owner” column in
            // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_unlock.html.
            match mutex.kind {
                MutexKind::Default =>
                    throw_ub_format!(
                        "unlocked a default mutex that was not locked by the current thread"
                    ),
                MutexKind::Normal =>
                    throw_ub_format!(
                        "unlocked a PTHREAD_MUTEX_NORMAL mutex that was not locked by the current thread"
                    ),
                MutexKind::ErrorCheck | MutexKind::Recursive =>
                    interp_ok(Scalar::from_i32(this.eval_libc_i32("EPERM"))),
            }
        }
    }

    fn pthread_mutex_destroy(&mut self, mutex_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        // Reading the field also has the side-effect that we detect double-`destroy`
        // since we make the field unint below.
        let mutex = mutex_get_data(this, mutex_op)?;

        if this.mutex_is_locked(mutex.id) {
            throw_ub_format!("destroyed a locked mutex");
        }

        // This might lead to false positives, see comment in pthread_mutexattr_destroy
        this.write_uninit(
            &this.deref_pointer_as(mutex_op, this.libc_ty_layout("pthread_mutex_t"))?,
        )?;
        // FIXME: delete interpreter state associated with this mutex.

        interp_ok(())
    }

    fn pthread_rwlock_rdlock(
        &mut self,
        rwlock_op: &OpTy<'tcx>,
        dest: &MPlaceTy<'tcx>,
    ) -> InterpResult<'tcx> {
        let this = self.eval_context_mut();

        let id = rwlock_get_data(this, rwlock_op)?.id;

        if this.rwlock_is_write_locked(id) {
            this.rwlock_enqueue_and_block_reader(id, Scalar::from_i32(0), dest.clone());
        } else {
            this.rwlock_reader_lock(id);
            this.write_null(dest)?;
        }

        interp_ok(())
    }

    fn pthread_rwlock_tryrdlock(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let id = rwlock_get_data(this, rwlock_op)?.id;

        if this.rwlock_is_write_locked(id) {
            interp_ok(Scalar::from_i32(this.eval_libc_i32("EBUSY")))
        } else {
            this.rwlock_reader_lock(id);
            interp_ok(Scalar::from_i32(0))
        }
    }

    fn pthread_rwlock_wrlock(
        &mut self,
        rwlock_op: &OpTy<'tcx>,
        dest: &MPlaceTy<'tcx>,
    ) -> InterpResult<'tcx> {
        let this = self.eval_context_mut();

        let id = rwlock_get_data(this, rwlock_op)?.id;

        if this.rwlock_is_locked(id) {
            // Note: this will deadlock if the lock is already locked by this
            // thread in any way.
            //
            // Relevant documentation:
            // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_rwlock_wrlock.html
            // An in-depth discussion on this topic:
            // https://github.com/rust-lang/rust/issues/53127
            //
            // FIXME: Detect and report the deadlock proactively. (We currently
            // report the deadlock only when no thread can continue execution,
            // but we could detect that this lock is already locked and report
            // an error.)
            this.rwlock_enqueue_and_block_writer(id, Scalar::from_i32(0), dest.clone());
        } else {
            this.rwlock_writer_lock(id);
            this.write_null(dest)?;
        }

        interp_ok(())
    }

    fn pthread_rwlock_trywrlock(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let id = rwlock_get_data(this, rwlock_op)?.id;

        if this.rwlock_is_locked(id) {
            interp_ok(Scalar::from_i32(this.eval_libc_i32("EBUSY")))
        } else {
            this.rwlock_writer_lock(id);
            interp_ok(Scalar::from_i32(0))
        }
    }

    fn pthread_rwlock_unlock(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        let id = rwlock_get_data(this, rwlock_op)?.id;

        if this.rwlock_reader_unlock(id)? || this.rwlock_writer_unlock(id)? {
            interp_ok(())
        } else {
            throw_ub_format!("unlocked an rwlock that was not locked by the active thread");
        }
    }

    fn pthread_rwlock_destroy(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        // Reading the field also has the side-effect that we detect double-`destroy`
        // since we make the field unint below.
        let id = rwlock_get_data(this, rwlock_op)?.id;

        if this.rwlock_is_locked(id) {
            throw_ub_format!("destroyed a locked rwlock");
        }

        // This might lead to false positives, see comment in pthread_mutexattr_destroy
        this.write_uninit(
            &this.deref_pointer_as(rwlock_op, this.libc_ty_layout("pthread_rwlock_t"))?,
        )?;
        // FIXME: delete interpreter state associated with this rwlock.

        interp_ok(())
    }

    fn pthread_condattr_init(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        // no clock attribute on macOS
        if this.tcx.sess.target.os != "macos" {
            // The default value of the clock attribute shall refer to the system
            // clock.
            // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_condattr_setclock.html
            let default_clock_id = this.eval_libc_i32("CLOCK_REALTIME");
            condattr_set_clock_id(this, attr_op, default_clock_id)?;
        }

        interp_ok(())
    }

    fn pthread_condattr_setclock(
        &mut self,
        attr_op: &OpTy<'tcx>,
        clock_id_op: &OpTy<'tcx>,
    ) -> InterpResult<'tcx, Scalar> {
        let this = self.eval_context_mut();

        let clock_id = this.read_scalar(clock_id_op)?.to_i32()?;
        if clock_id == this.eval_libc_i32("CLOCK_REALTIME")
            || clock_id == this.eval_libc_i32("CLOCK_MONOTONIC")
        {
            condattr_set_clock_id(this, attr_op, clock_id)?;
        } else {
            let einval = this.eval_libc_i32("EINVAL");
            return interp_ok(Scalar::from_i32(einval));
        }

        interp_ok(Scalar::from_i32(0))
    }

    fn pthread_condattr_getclock(
        &mut self,
        attr_op: &OpTy<'tcx>,
        clk_id_op: &OpTy<'tcx>,
    ) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        let clock_id = condattr_get_clock_id(this, attr_op)?;
        this.write_scalar(Scalar::from_i32(clock_id), &this.deref_pointer(clk_id_op)?)?;

        interp_ok(())
    }

    fn pthread_condattr_destroy(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        // Destroying an uninit pthread_condattr is UB, so check to make sure it's not uninit.
        // There's no clock attribute on macOS.
        if this.tcx.sess.target.os != "macos" {
            condattr_get_clock_id(this, attr_op)?;
        }

        // De-init the entire thing.
        // This might lead to false positives, see comment in pthread_mutexattr_destroy
        this.write_uninit(
            &this.deref_pointer_as(attr_op, this.libc_ty_layout("pthread_condattr_t"))?,
        )?;

        interp_ok(())
    }

    fn pthread_cond_init(
        &mut self,
        cond_op: &OpTy<'tcx>,
        attr_op: &OpTy<'tcx>,
    ) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        let attr = this.read_pointer(attr_op)?;
        // Default clock if `attr` is null, and on macOS where there is no clock attribute.
        let clock_id = if this.ptr_is_null(attr)? || this.tcx.sess.target.os == "macos" {
            this.eval_libc_i32("CLOCK_REALTIME")
        } else {
            condattr_get_clock_id(this, attr_op)?
        };
        let clock_id = condattr_translate_clock_id(this, clock_id)?;

        cond_create(this, cond_op, clock_id)?;

        interp_ok(())
    }

    fn pthread_cond_signal(&mut self, cond_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();
        let id = cond_get_data(this, cond_op)?.id;
        this.condvar_signal(id)?;
        interp_ok(())
    }

    fn pthread_cond_broadcast(&mut self, cond_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();
        let id = cond_get_data(this, cond_op)?.id;
        while this.condvar_signal(id)? {}
        interp_ok(())
    }

    fn pthread_cond_wait(
        &mut self,
        cond_op: &OpTy<'tcx>,
        mutex_op: &OpTy<'tcx>,
        dest: &MPlaceTy<'tcx>,
    ) -> InterpResult<'tcx> {
        let this = self.eval_context_mut();

        let data = cond_get_data(this, cond_op)?;
        let mutex_id = mutex_get_data(this, mutex_op)?.id;

        this.condvar_wait(
            data.id,
            mutex_id,
            None, // no timeout
            Scalar::from_i32(0),
            Scalar::from_i32(0), // retval_timeout -- unused
            dest.clone(),
        )?;

        interp_ok(())
    }

    fn pthread_cond_timedwait(
        &mut self,
        cond_op: &OpTy<'tcx>,
        mutex_op: &OpTy<'tcx>,
        abstime_op: &OpTy<'tcx>,
        dest: &MPlaceTy<'tcx>,
    ) -> InterpResult<'tcx> {
        let this = self.eval_context_mut();

        let data = cond_get_data(this, cond_op)?;
        let mutex_id = mutex_get_data(this, mutex_op)?.id;

        // Extract the timeout.
        let duration = match this
            .read_timespec(&this.deref_pointer_as(abstime_op, this.libc_ty_layout("timespec"))?)?
        {
            Some(duration) => duration,
            None => {
                let einval = this.eval_libc("EINVAL");
                this.write_scalar(einval, dest)?;
                return interp_ok(());
            }
        };
        let timeout_clock = match data.clock {
            ClockId::Realtime => {
                this.check_no_isolation("`pthread_cond_timedwait` with `CLOCK_REALTIME`")?;
                TimeoutClock::RealTime
            }
            ClockId::Monotonic => TimeoutClock::Monotonic,
        };

        this.condvar_wait(
            data.id,
            mutex_id,
            Some((timeout_clock, TimeoutAnchor::Absolute, duration)),
            Scalar::from_i32(0),
            this.eval_libc("ETIMEDOUT"), // retval_timeout
            dest.clone(),
        )?;

        interp_ok(())
    }

    fn pthread_cond_destroy(&mut self, cond_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> {
        let this = self.eval_context_mut();

        // Reading the field also has the side-effect that we detect double-`destroy`
        // since we make the field unint below.
        let id = cond_get_data(this, cond_op)?.id;
        if this.condvar_is_awaited(id) {
            throw_ub_format!("destroying an awaited conditional variable");
        }

        // This might lead to false positives, see comment in pthread_mutexattr_destroy
        this.write_uninit(&this.deref_pointer_as(cond_op, this.libc_ty_layout("pthread_cond_t"))?)?;
        // FIXME: delete interpreter state associated with this condvar.

        interp_ok(())
    }
}