Skip to content

Commit 925facd

Browse files
committed
Ctrl-C: the npm strobe command waits for strobe to stop, and a stop that ends strobe at once still ends and reports what strobe launched
1 parent 5112c6e commit 925facd

6 files changed

Lines changed: 145 additions & 24 deletions

File tree

‎sdk/bench/bin/strobe.js‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env node
22
// Runs this platform's strobe binary, from the @hona/strobe-<platform>-<arch> package npm installed beside this
33
// one (an optional dependency: each machine installs only its own). STROBE_BINARY points at another build.
4-
import { spawnSync } from "node:child_process"
4+
import { spawn } from "node:child_process"
55
import { createRequire } from "node:module"
66
import { dirname, join } from "node:path"
77

@@ -17,10 +17,25 @@ if (!exe) {
1717
process.exit(1)
1818
}
1919
}
20-
const r = spawnSync(exe, process.argv.slice(2), { stdio: "inherit" })
21-
if (r.error) {
22-
console.error(`strobe: ${r.error.message}`)
23-
process.exit(1)
20+
const child = spawn(exe, process.argv.slice(2), { stdio: "inherit" })
21+
// A stop (Ctrl-C, SIGINT, SIGTERM) is strobe's to carry out: it ends what it launched and says what it
22+
// left before it exits, so this waits for it rather than handing the shell back while it still stops.
23+
// A terminal's Ctrl-C or `timeout` reaches strobe directly; one sent to this process alone is passed on
24+
// (on Unix: strobe takes a repeat within 300 ms as the same stop). Windows' console sends Ctrl-C to
25+
// every process on it, and Node would end the child rather than signal it, so nothing is passed there.
26+
for (const sig of ["SIGINT", "SIGTERM"]) {
27+
process.on(sig, () => {
28+
if (process.platform !== "win32") child.kill(sig)
29+
})
2430
}
25-
if (r.signal) process.kill(process.pid, r.signal)
26-
process.exit(r.status ?? 1)
31+
child.on("error", (e) => {
32+
console.error(`strobe: ${e.message}`)
33+
process.exit(1)
34+
})
35+
child.on("exit", (code, signal) => {
36+
if (signal) {
37+
process.removeAllListeners(signal)
38+
process.kill(process.pid, signal)
39+
}
40+
process.exit(code ?? 1)
41+
})

‎src/host/cgroup.rs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,13 @@ fn populated(dir: &Path) -> bool {
200200

201201
/// Kills what runs in a cgroup and below it, waits (2 s at most) for it to end, and removes the
202202
/// cgroups, deepest first. Before Linux 5.14 (no `cgroup.kill`) each process listed is sent SIGKILL
203-
/// until none is left (one forked meanwhile is listed in the next round).
203+
/// until none is left (one forked meanwhile is listed in the next round). What is still in it after
204+
/// the wait is said (`spawn::leave`): strobe ended it, and it did not go. A cgroup already removed
205+
/// (ended by a stop, `end_all`) is nothing to end.
204206
fn end(dir: &Path) {
207+
if !dir.exists() {
208+
return;
209+
}
205210
let killed = std::fs::write(dir.join("cgroup.kill"), "1").is_ok();
206211
let until = Instant::now() + Duration::from_secs(2);
207212
while populated(dir) && Instant::now() < until {
@@ -214,9 +219,28 @@ fn end(dir: &Path) {
214219
}
215220
std::thread::sleep(Duration::from_millis(5));
216221
}
222+
if populated(dir) {
223+
for pid in pids(dir).unwrap_or_default() {
224+
super::spawn::leave(Some(pid), "a process in the cgroup of a launch strobe ended", "it was still running 2 s after strobe ended the cgroup's processes");
225+
}
226+
}
217227
remove(dir);
218228
}
219229

230+
/// Ends every launch cgroup this strobe still has (`end`), for a stop that exits at once: a process
231+
/// that left its launch's tree and group (a crash reporter's handler, a daemon) is still in it, and
232+
/// the cgroup strobe made is the proof that it is the launch's. All are killed first, then each waited
233+
/// for.
234+
pub fn end_all() {
235+
let all: Vec<PathBuf> = std::mem::take(&mut *LAUNCHES.lock().unwrap_or_else(|e| e.into_inner())).into_iter().map(|(_, _, p)| p).collect();
236+
for dir in &all {
237+
let _ = std::fs::write(dir.join("cgroup.kill"), "1");
238+
}
239+
for dir in &all {
240+
end(dir);
241+
}
242+
}
243+
220244
/// Whether process `pid` is in cgroup `dir` or one below it now (`/proc/<pid>/cgroup`'s v2 line).
221245
fn in_cgroup(pid: u32, dir: &Path) -> bool {
222246
let Ok(rel) = dir.strip_prefix(ROOT) else { return false };

‎src/host/kill.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
//! | 1 | `kill_launch(pid, start)` | root, its tree, `-pid` | at the spawn (`Owned::start`); tree members from the walk's snapshot | strobe's own child, unreaped (Unix) or handle held (Windows); with `start`, nothing once it names another process; each member by its start, re-read (Linux: through a pidfd) right before |
4848
//! | 2 | `kill_opened(pid, start)` | root, its tree (macOS: what is responsible to it by pid and start); never a group | the caller's (see each row) | root only at `start`, read again after the walk's list (a root that exited during it lends no children; macOS still ends what is responsible to it by pid and start); each member by its snapshot start, re-read right before; a reused root's tree left alone |
4949
//! | 3 | `win::kill_tree` | `TerminateProcess` per tree member | the snapshot's creation time | the creation time read through the handle it terminates with; with a start, the root must have it |
50-
//! | 4 | `spawn::end_launches` (a stop) | child: `kill_launch` + `-pgid`; opened app: `kill_opened` | child: at the spawn; opened app: `macos::launched` at the launch | child unreaped; opened app only with its launch-time start (an unadopted one has pid 0 and nothing is signalled) |
50+
//! | 4 | `spawn::end_launches` (a stop) | child: `kill_launch` + `-pgid`; opened app: `kill_opened`; then every launch cgroup (`cgroup::end_all`, rows 14-15) or job (`TerminateJobObject`); `isolate::end_on_stop` then ends what carries each launch's stamp (`end_roots`) and says what is still running 2 s on | child: at the spawn; opened app: `macos::launched` at the launch | child unreaped; opened app only with its launch-time start (an unadopted one has pid 0 and nothing is signalled); a cgroup or job strobe made; a stamp re-read with the start time right before |
5151
//! | 5 | `Owned::end_group` | as 4, then `TerminateJobObject`, `Child::kill` | as 4 | under the `LIVE` lock, before the reap |
5252
//! | 6 | `close_job`, a job's last handle (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`), `tty` Windows | every process of the job | - | a job strobe made, by its handle |
5353
//! | 7 | `Owned::run_to_exit` watchdog | `-pid` at the deadline | - | the child is unreaped until `wait4`; on a wait error the watchdog is joined and the group forgotten before returning |
@@ -63,7 +63,7 @@
6363
//! | 17 | `tty` Unix: the pty master dropped (SIGHUP), `TIOCSWINSZ` (SIGWINCH) | the pty's foreground group | - | a pty strobe opened for its own child; the kernel signals only that terminal's group |
6464
//! | 18 | `probe::sample::Capture::{stop, drop}` (macOS) | SIGINT, `Child::kill` | - | its own `sample` child while `try_wait` says it is not reaped |
6565
//! | 19 | `Child::kill` (`engine`, `ffmpeg`, `track` alert shell, `macos::unregister`, `macos::ls_registered`, `spawn`) | own child | - | std signals none it reaped; each is waited for after |
66-
//! | 20 | `unix_ctrl_c` (a second SIGINT or SIGTERM) | strobe itself (`raise`) | - | itself |
66+
//! | 20 | `unix_ctrl_c` (a third SIGINT or SIGTERM, 300 ms or more after the second; a repeat within 300 ms is the same stop, and the second is a stop now: `spawn::stop_launches`, row 4, then exit 130) | strobe itself (`raise`) | - | itself |
6767
//! | 21 | `probe::suspend` (Windows x64): stack sampling | `SuspendThread`, `ResumeThread`, memory reads | the look's snapshot (the set walked from the launch's root): each process's and thread's creation time | each process handle kept only while its creation time is the look's (`open_process`), each thread handle only while it is a thread of that pid created at the look's time (`open_thread`), both checked on the handle; else closed and counted unopened. A job's new process is opened by its parent's handle and creation time (`open_child`) |
6868
//! | 22 | `android_chrome` (`adb shell am force-stop`) | a Chrome channel on a phone | - | never the stable channel; only a channel strobe started or one opted in with no tabs of the person's |
6969
//! | 23 | `helper` (`schtasks /end`) | strobe's ETW helper task | - | the task name carries the user's RID; strobe's own |

‎src/host/mod.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2297,9 +2297,30 @@ pub fn start_now() -> Option<u64> {
22972297
pub fn unix_ctrl_c(flag: &'static std::sync::atomic::AtomicBool) {
22982298
use std::sync::atomic::{AtomicPtr, Ordering};
22992299
static TARGET: AtomicPtr<std::sync::atomic::AtomicBool> = AtomicPtr::new(std::ptr::null_mut());
2300+
// When the first stop came (`now_ns`): the same stop can arrive twice at once, once to strobe's
2301+
// process group (a terminal's Ctrl-C, `timeout`) and once passed on by a wrapper that got it too
2302+
// (the npm package's `bin/strobe.js`). A repeat within 300 ms is that stop; a later one ends strobe.
2303+
static FIRST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2304+
// A second stop asks for one now: the `strobe-stop-now` thread ends what strobe launched (by proof, waited
2305+
// for, what is left said) and exits 130, rather than the signal ending strobe with its launches
2306+
// still running (a browser is in a process group of its own). Only a third, 300 ms or more after the
2307+
// second, ends strobe at once (should that end hang).
2308+
static NOW: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2309+
static NOW_AT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
23002310
extern "C" fn handler(sig: libc::c_int) {
23012311
let flag = TARGET.load(Ordering::SeqCst);
23022312
if !flag.is_null() && !unsafe { (*flag).swap(true, Ordering::SeqCst) } {
2313+
FIRST.store(now_ns(), Ordering::SeqCst);
2314+
return;
2315+
}
2316+
if now_ns().saturating_sub(FIRST.load(Ordering::SeqCst)) < 300_000_000 {
2317+
return;
2318+
}
2319+
if !flag.is_null() && !NOW.swap(true, Ordering::SeqCst) {
2320+
NOW_AT.store(now_ns(), Ordering::SeqCst);
2321+
return;
2322+
}
2323+
if now_ns().saturating_sub(NOW_AT.load(Ordering::SeqCst)) < 300_000_000 {
23032324
return;
23042325
}
23052326
unsafe {
@@ -2312,6 +2333,17 @@ pub fn unix_ctrl_c(flag: &'static std::sync::atomic::AtomicBool) {
23122333
libc::signal(libc::SIGINT, handler as *const () as libc::sighandler_t);
23132334
libc::signal(libc::SIGTERM, handler as *const () as libc::sighandler_t);
23142335
}
2336+
let _ = std::thread::Builder::new().name("strobe-stop-now".into()).spawn(|| {
2337+
while !NOW.load(Ordering::SeqCst) {
2338+
std::thread::sleep(std::time::Duration::from_millis(50));
2339+
}
2340+
spawn::stop_launches();
2341+
let left = spawn::left_alone();
2342+
if !left.is_empty() {
2343+
eprint!("{}", spawn::left_alone_text(&left));
2344+
}
2345+
std::process::exit(130);
2346+
});
23152347
}
23162348
}
23172349

‎src/host/spawn.rs‎

Lines changed: 56 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
//! launched for, which whatever it starts inherits: what left the group (a detached service, a
66
//! double-forked daemon) still carries the stamp.
77
8-
use std::path::Path;
8+
use std::path::{Path, PathBuf};
99
use std::process::{Child, Command};
1010

1111
/// Every process strobe launches (an isolated app, a browser, a command target) carries the folder it
@@ -310,11 +310,13 @@ struct Group {
310310
/// One launch `end_launches` would end: its root's pid and start time, and whether the root is
311311
/// strobe's own child (never reaped before its end, so its pid and its process group stay its own) or
312312
/// an app launchd started for strobe (`open_owned`), reaped by launchd as it exits.
313-
#[derive(Clone, Copy, Debug)]
313+
#[derive(Clone, Debug)]
314314
struct Live {
315315
pid: u32,
316316
start: Option<u64>,
317317
child: bool,
318+
/// The folder the launch was for (its stamp): what left its tree and group still carries it.
319+
home: Option<PathBuf>,
318320
}
319321

320322
/// Every `Owned` launch not yet ended: what `end_launches` ends on a stop. A child launch registers
@@ -491,13 +493,19 @@ pub fn left_alone_text(left: &[LeftAlone]) -> String {
491493
s
492494
}
493495

494-
/// Ends every launch this strobe still owns (each one's tree, then a child's group; Windows ends the
495-
/// jobs itself when strobe exits): for a stop of a command that then exits (`isolate::end_on_stop`).
496-
/// An app launchd started for strobe is ended only as far as `kill_opened` proves it the launch's,
497-
/// and never by a process group: strobe made none. The launches stay ended: their `end` only reaps them.
498-
pub fn end_launches() {
496+
/// Ends every launch this strobe still owns (each one's tree, then a child's group), and then what
497+
/// left them that is still the launches' by proof: on Linux everything in the launch cgroups strobe
498+
/// made (`cgroup::end_all`, which says what did not go), on Windows everything in their jobs (which
499+
/// the OS would end only once strobe has exited): for a stop of a command that then exits
500+
/// (`isolate::end_on_stop`), where no launch's own end runs. An app launchd started for strobe is
501+
/// ended only as far as `kill_opened` proves it the launch's, and never by a process group: strobe
502+
/// made none. Returns the folders the launches were for, whose stamped processes the caller ends and
503+
/// waits for. The launches stay ended: their `end` only reaps them.
504+
pub fn end_launches() -> Vec<PathBuf> {
499505
let mut live = LIVE.lock().unwrap_or_else(|e| e.into_inner());
506+
let mut homes = Vec::new();
500507
for l in live.drain(..) {
508+
homes.extend(l.home.clone());
501509
if !l.child {
502510
if let Some(start) = l.start {
503511
super::kill_opened(l.pid, start);
@@ -513,6 +521,43 @@ pub fn end_launches() {
513521
libc::kill(-(l.pid as i32), libc::SIGKILL);
514522
}
515523
}
524+
drop(live);
525+
#[cfg(target_os = "linux")]
526+
super::cgroup::end_all();
527+
#[cfg(windows)]
528+
for (_, _, job) in std::mem::take(&mut *JOBS.lock().unwrap_or_else(|e| e.into_inner())) {
529+
unsafe { windows_sys::Win32::System::JobObjects::TerminateJobObject(job as _, 1) };
530+
}
531+
homes.sort();
532+
homes.dedup();
533+
homes
534+
}
535+
536+
/// A stop's end of everything strobe launched, for a stop that exits at once (`isolate::end_on_stop`,
537+
/// a second Ctrl-C): every launch (`end_launches`), then what carries a launch's stamp and is still
538+
/// that process (its stamp and start time read again right before; a browser's crash reporter on a
539+
/// session of its own), then up to 2 s for those to go. What is still there then is said (`leave`):
540+
/// a stop ends sooner, never by leaving that unsaid.
541+
pub fn stop_launches() {
542+
let homes = end_launches();
543+
let ours = |h: &Path| {
544+
let k = home_key(h);
545+
stamped().into_iter().filter(move |s| s.stamp.home == k && super::start_time(s.pid) == Some(s.start) && stamp_of(s.pid).as_ref() == Some(&s.stamp))
546+
};
547+
for h in &homes {
548+
for s in ours(h) {
549+
super::kill_opened(s.pid, s.start);
550+
}
551+
}
552+
let until = std::time::Instant::now() + std::time::Duration::from_secs(2);
553+
let mut left: Vec<Stamped> = homes.iter().flat_map(|h| ours(h)).collect();
554+
while !left.is_empty() && std::time::Instant::now() < until {
555+
std::thread::sleep(std::time::Duration::from_millis(20));
556+
left = homes.iter().flat_map(|h| ours(h)).collect();
557+
}
558+
for s in left {
559+
leave(Some(s.pid), "a process launched for a launch strobe ended at a stop (it carries the launch's stamp)", "it was still running 2 s after strobe ended it");
560+
}
516561
}
517562

518563
/// Whether a launch's pid names another process now: one started at another time than the launch
@@ -589,7 +634,7 @@ pub fn close_job(job: isize) {
589634
/// found by `group_pids` for `home`. Taken back by `unlist_launch` before it is ended.
590635
#[cfg(windows)]
591636
pub fn list_launch(pid: u32, job: Option<isize>, home: Option<&Path>) {
592-
LIVE.lock().unwrap_or_else(|e| e.into_inner()).push(Live { pid, start: None, child: true });
637+
LIVE.lock().unwrap_or_else(|e| e.into_inner()).push(Live { pid, start: None, child: true, home: home.map(Path::to_path_buf) });
593638
if let Some(j) = job {
594639
JOBS.lock().unwrap_or_else(|e| e.into_inner()).push((pid, home.map(home_key), j));
595640
}
@@ -1282,7 +1327,7 @@ pub fn spawn_owned(cmd: &mut Command, cpus: Option<u64>, flags: u32, home: Optio
12821327
// Held from before the spawn until the launch is listed: a stop in between ends it too.
12831328
let mut live = LIVE.lock().unwrap_or_else(|e| e.into_inner());
12841329
let owned = spawn_group(cmd, cpus, flags, home)?;
1285-
live.push(Live { pid: owned.pid(), start: owned.start, child: true });
1330+
live.push(Live { pid: owned.pid(), start: owned.start, child: true, home: home.map(Path::to_path_buf) });
12861331
Ok(owned)
12871332
}
12881333

@@ -1478,7 +1523,7 @@ pub fn spawn_owned_terminal(cmd: &mut Command, cpus: Option<u64>, home: Option<&
14781523
let released_ns = before_ns;
14791524
let pgid = child.id();
14801525
let start = super::start_time(pgid);
1481-
live.push(Live { pid: pgid, start, child: true });
1526+
live.push(Live { pid: pgid, start, child: true, home: home.map(Path::to_path_buf) });
14821527
Ok(Owned {
14831528
process: Proc::Child(child),
14841529
group: Some(Group { pgid }),
@@ -1514,7 +1559,7 @@ pub fn open_owned(bundle: &super::macos::Bundle, args: &[String], env: &[(String
15141559
let start = opened.start;
15151560
let pid = if start.is_some() { opened.pid } else { 0 };
15161561
match start {
1517-
Some(start) => LIVE.lock().unwrap_or_else(|e| e.into_inner()).push(Live { pid, start: Some(start), child: false }),
1562+
Some(start) => LIVE.lock().unwrap_or_else(|e| e.into_inner()).push(Live { pid, start: Some(start), child: false, home: Some(home.to_path_buf()) }),
15181563
None => leave(
15191564
Some(opened.pid),
15201565
"the process Launch Services answered strobe's launch with",

‎src/target/isolate.rs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,10 +1240,12 @@ pub fn release_home(home: &Path) {
12401240

12411241
/// While alive, a stop of strobe (Ctrl-C, SIGINT, SIGTERM) waits for a Launch Services launch under
12421242
/// way to end what it started (macOS, `macos::opening`, 2.5 s at most), ends every launch it owns (each one's tree
1243-
/// and group or job: `spawn::end_launches`), then what still runs from `home` (stamped with it),
1243+
/// and group, its Linux cgroup or Windows job: `spawn::end_launches`) and what carries a launch's stamp
1244+
/// (a browser's crash reporter on a session of its own), waits up to 2 s for those to go and says what
1245+
/// did not (`spawn::leave`), then what still runs from `home` (stamped with it),
12441246
/// removes that home when `prepare_home` made it now, and exits 130: for a command with no stop
12451247
/// points of its own (`look`), which leaves nothing running for the next strobe to reap. A browser's
1246-
/// profile goes with the next strobe's `reap_dead_owners`. Dropped (before the command closes what
1248+
/// profile folder goes with the next strobe's `reap_dead_owners`. Dropped (before the command closes what
12471249
/// it launched), the watcher has ended: a stop that came first finished its work and exited.
12481250
pub struct EndOnStop {
12491251
done: std::sync::Arc<std::sync::Mutex<bool>>,
@@ -1274,7 +1276,10 @@ pub fn end_on_stop(home: Option<&Home>) -> EndOnStop {
12741276
std::thread::sleep(std::time::Duration::from_millis(10));
12751277
}
12761278
}
1277-
host::spawn::end_launches();
1279+
// Each launch's tree and group, its cgroup or job, then what left them with its
1280+
// stamp (a browser's crash reporter, on its own session), waited for: what is still
1281+
// there 2 s on is said below, never left unsaid for speed.
1282+
host::spawn::stop_launches();
12781283
if let Some((dir, fresh)) = &home {
12791284
release_home(dir);
12801285
if *fresh {

0 commit comments

Comments
 (0)