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
use std::sync::Mutex;
use std::process;
#[cfg(target_os = "linux")]
use std::{fs, env};
#[cfg(target_os = "windows")]
use winapi::um::debugapi;
#[cfg(target_os = "windows")]
use std::{path, thread};
#[cfg(target_os = "windows")]
use std::time::Duration;
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
compile_error!("debug-here: this crate currently only builds on linux, macos, and windows");
fn already_entered() -> bool {
lazy_static! {
static ref GUARD: Mutex<bool> = Mutex::new(false);
}
let mut entered = GUARD.lock().unwrap();
let ret = *entered;
*entered = true;
return ret;
}
#[cfg(not(target_os = "windows"))]
pub fn debug_here_unixy_impl(debugger: Option<&str>) {
if already_entered() {
return;
}
#[cfg(target_os = "linux")]
let sane_env = linux_check();
#[cfg(target_os = "macos")]
let sane_env = macos_check();
if let Err(e) = sane_env {
eprintln!("debug-here: {}", e);
return
}
#[cfg(target_os = "linux")]
let debugger = debugger.unwrap_or("rust-gdb");
#[cfg(target_os = "macos")]
let debugger = debugger.unwrap_or("rust-lldb");
if which::which(debugger).is_err() {
eprintln!("debug-here: can't find {} on your path. Bailing.", debugger);
return;
}
if which::which("debug-here-gdb-wrapper").is_err() {
eprintln!(r#"debug-here:
Can't find debug-here-gdb-wrapper on your path. To get it
you can run `cargo install debug-here-gdb-wrapper`
"#);
return;
}
let looping = true;
#[cfg(target_os = "linux")]
let launch_stat = linux_launch_term(debugger);
#[cfg(target_os = "macos")]
let launch_stat = macos_launch_term(debugger);
if let Err(e) = launch_stat {
eprintln!("debug-here: {}", e);
return;
}
while looping {}
}
#[cfg(target_os = "windows")]
pub fn debug_here_win_impl() {
if already_entered() {
return;
}
let jitdbg_exe = r#"c:\windows\system32\vsjitdebugger.exe"#;
if !path::Path::new(jitdbg_exe).exists() {
eprintln!("debug-here: could not find '{}'.", jitdbg_exe);
return;
}
let pid = process::id();
let mut cmd = process::Command::new(jitdbg_exe);
cmd.stdin(process::Stdio::null())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null());
cmd.arg("-p").arg(pid.to_string());
if let Err(e) = cmd.spawn() {
eprintln!("debug-here: failed to launch '{}': {}", jitdbg_exe, e);
return;
}
while unsafe { debugapi::IsDebuggerPresent() } == 0 {
thread::sleep(Duration::from_millis(100));
}
unsafe { debugapi::DebugBreak(); }
}
#[cfg(not(target_os = "windows"))]
fn debugger_args(debugger: &str) -> Vec<String> {
if debugger == "rust-lldb" {
vec!["-p".to_string(),
process::id().to_string(),
"-o".to_string(),
"expression looping = 0".to_string(),
"-o".to_string(),
"finish".to_string()]
} else if debugger == "rust-gdb" {
vec!["-pid".to_string(),
process::id().to_string(),
"-ex".to_string(),
"set variable looping = 0".to_string(),
"-ex".to_string(),
"finish".to_string()]
} else {
panic!("unknown debugger: {}", debugger);
}
}
#[cfg(target_os = "linux")]
fn linux_check() -> Result<(), String> {
let the_kids_are_ok =
fs::read("/proc/sys/kernel/yama/ptrace_scope")
.map(|contents|
std::str::from_utf8(&contents[..1]).unwrap_or("1") == "0")
.unwrap_or(false);
if !the_kids_are_ok {
return Err(format!(r#"
ptrace_scope must be set to 0 for debug-here to work.
This will allow any process with a given uid to rummage around
in the memory of any other process with the same uid, so there
are some security risks. To set ptrace_scope for just this
session you can do:
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
Giving up on debugging for now.
"#));
}
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_launch_term(debugger: &str) -> Result<(), String> {
if debugger == "rust-gdb" {
env::set_var("RUST_DEBUG_HERE_LIFELINE",
format!("1,{}", process::id()));
} else {
env::set_var("RUST_DEBUG_HERE_LIFELINE",
format!("2,{},{}", process::id(), debugger));
}
let term = match which::which("alacritty").or(which::which("xterm")) {
Ok(t) => t,
Err(_) => {
return Err(format!(r#"
can't find alacritty or xterm on your path. Those are the
only terminal emulators currently supported on linux.
"#));
}
};
let term_cmd = term.clone();
let mut cmd = process::Command::new(term_cmd);
cmd.stdin(process::Stdio::null())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null());
if term.ends_with("alacritty") {
cmd.arg("-e");
cmd.arg(debugger);
cmd.args(debugger_args(debugger));
} else {
cmd.arg("debug-here-gdb-wrapper");
}
match cmd.spawn() {
Ok(_) => Ok(()),
Err(e) => Err(
format!("failed to launch rust-gdb in {:?}: {}", term, e))
}
}
#[cfg(target_os = "macos")]
fn macos_check() -> Result<(), String> {
if which::which("osascript").is_err() {
return Err(format!("debug-here: can't find osascript. Bailing."));
}
Ok(())
}
#[cfg(target_os = "macos")]
fn macos_launch_term(debugger: &str) -> Result<(), String> {
let launch_script =
format!(r#"tell app "Terminal"
do script "exec {} {}"
end tell"#, debugger,
debugger_args(debugger).into_iter()
.map(|a| if a.contains(" ") { format!("'{}'", a) } else { a } )
.collect::<Vec<_>>().join(" "));
let mut cmd = process::Command::new("osascript");
cmd.arg("-e")
.arg(launch_script)
.stdin(process::Stdio::null())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null());
match cmd.spawn() {
Ok(_) => Ok(()),
Err(e) => Err(
format!("failed to launch {} in Terminal.app: {}", debugger, e))
}
}