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
//! `pthread_create` interposition: the last step to telemetry a program does not
//! have to know about.
//!
//! A thread has to be seen once before it can be described, and everything else
//! in this crate arranges for that to happen on the first call into it. This
//! module removes even that requirement by defining `pthread_create` itself.
//! Because a symbol in the executable takes precedence over the one in the C
//! library, every thread the process creates — including those created by
//! libraries that have never heard of `stackler`, and by `std::thread::spawn`,
//! which goes through the same call — runs a small trampoline that attaches the
//! thread first.
//!
//! Unix only: on other platforms the feature compiles to nothing at all, so that
//! enabling every feature of every crate in a workspace still builds.
//!
//! ## What this costs, and when not to do it
//!
//! - The crate defines a public `pthread_create` symbol. That is a process-wide
//! decision, which is why the feature is off by default and why it belongs in a
//! binary rather than in a library that others depend on.
//! - The real `pthread_create` is resolved with `dlsym(RTLD_NEXT, ..)` on first
//! use. This needs a dynamically linked libc; a fully static link will instead
//! fail at link time with a duplicate symbol, which is a better outcome than
//! failing at runtime.
//! - Each intercepted thread costs one small allocation for the trampoline's
//! payload, plus whatever attaching costs — with the `watermark` feature, that
//! includes painting the new thread's stack.
use ;
use AtomicPtr;
/// The signature of a thread's entry point.
type StartRoutine = unsafe extern "C" fn ;
/// The signature of `pthread_create` itself.
type PthreadCreate = unsafe extern "C" fn ;
/// The libc `pthread_create`, cached after the first lookup.
static REAL: = new;
/// What the trampoline needs to know to call the thread's real entry point.
/// Resolves the `pthread_create` that would have been called if this module did
/// not exist.
/// Attaches the new thread, then hands control to the entry point the caller of
/// `pthread_create` asked for.
unsafe extern "C"
/// Creates a thread, registering it with `stackler` before it runs.
///
/// This replaces the C library's `pthread_create` for the whole process; it
/// forwards every argument unchanged and returns what the real implementation
/// returns, except that it fails with `EAGAIN` if the real implementation could
/// not be found at all.
///
/// # Safety
///
/// Same contract as the `pthread_create` it replaces.
pub unsafe extern "C"