File: thread-local-static-ref-use-after-free.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (46 lines) | stat: -rw-r--r-- 843 bytes parent folder | download | duplicates (5)
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
//@ check-pass
//@ known-bug: #49682
//@ edition:2021

// Should fail. Keeping references to thread local statics can result in a
// use-after-free.

#![feature(thread_local)]

use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

#[allow(dead_code)]
#[thread_local]
static FOO: AtomicUsize = AtomicUsize::new(0);

#[allow(dead_code)]
async fn bar() {}

#[allow(dead_code)]
async fn foo() {
    let r = &FOO;
    bar().await;
    r.load(Ordering::SeqCst);
}

fn main() {
    // &FOO = 0x7fd1e9cbf6d0
    _ = thread::spawn(|| {
        let g = foo();
        println!("&FOO = {:p}", &FOO);
        g
    })
    .join()
    .unwrap();

    // &FOO = 0x7fd1e9cc0f50
    println!("&FOO = {:p}", &FOO);

    // &FOO = 0x7fd1e9cbf6d0
    thread::spawn(move || {
        println!("&FOO = {:p}", &FOO);
    })
    .join()
    .unwrap();
}