forked from facebookexperimental/hermit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello_race.rs
102 lines (86 loc) · 2.49 KB
/
hello_race.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/*! One of the simplest possible race conditions.
Exits with a nonzero code under one order, and not the other.
However, we complicate things a bit by having an rdtsc and a branch right before
the critical event, to make it easier to recognize in the raw schedule recordings,
as when manually checking the results of this test.
```cargo
[dependencies]
core = "1.6.0"
```
*/
use core::arch::x86_64::_rdtsc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
#[inline(always)]
fn rdtsc() -> u64 {
unsafe { _rdtsc() }
}
const WORK_AMT: usize = 100;
#[inline(never)]
fn do_work(iters: usize) -> u64 {
let mut max = 0;
for _i in 0..iters {
let new = rdtsc();
max = std::cmp::max(max, new);
}
max
}
#[inline(never)]
fn thread1(var: Arc<AtomicUsize>) {
do_work(4 * WORK_AMT);
// Provide a little extra context so we can judge the accuracy of the pinpointing result.
let fin = rdtsc(); // last intercepted instruction
if fin % 2 == 0
// last branch before critical event
{
var.store(1, SeqCst); // critical event
} else {
var.store(11, SeqCst); // critical event
}
do_work(4 * WORK_AMT);
}
#[inline(never)]
fn thread2(var: Arc<AtomicUsize>) {
do_work(4 * WORK_AMT);
// Provide a little extra context so we can judge the accuracy of the pinpointing result.
let fin = rdtsc(); // last intercepted instruction
if fin % 2 == 0
// last branch before critical event
{
var.store(2, SeqCst); // critical event
} else {
var.store(22, SeqCst); // critical event
}
do_work(4 * WORK_AMT);
}
#[test]
fn unit_test() {
run_test();
}
fn run_test() {
let d = Arc::new(AtomicUsize::new(1));
let d1 = Arc::clone(&d);
let d2 = Arc::clone(&d);
let h1 = std::thread::spawn(move || thread1(d1));
let h2 = std::thread::spawn(move || thread2(d2));
h1.join().unwrap();
h2.join().unwrap();
let val = Arc::try_unwrap(d).unwrap().into_inner();
println!("Final value: {}", val);
if val == 1 || val == 11 {
println!("Antagonistic schedule reached, failing.");
std::process::exit(1);
}
println!("Did not find antagonistic schedule. Succeeding.");
}
fn main() {
run_test();
}