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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Tracing another thread: `ptrace`.
//!
//! A *tracer* stops a thread (the *tracee*) at the events it asked for,
//! looks at its registers and its memory while it is stopped, changes
//! them, and lets it go on. This is what a debugger, a system call tracer
//! and some sandboxes are made of. The functions here are the requests of
//! the one `ptrace` system call, each with the arguments it takes; what
//! they mean is the kernel's (`ptrace(2)`), which this module does not
//! hide: it is thin.
//!
//! # Becoming a tracer
//!
//! - Of a child, from its first instruction:
//! [`ConfineExt::trace_me`](super::ConfineExt::trace_me). The program
//! stops as it starts, with `SIGTRAP` ([`Stop::Signal`]), and waits for
//! the caller.
//! - Of a thread that runs: [`seize`], which does not stop it
//! ([`interrupt`] does), or the older [`attach`], which sends it
//! `SIGSTOP`. The system may forbid it: see [`seize`].
//!
//! # The loop
//!
//! A tracer waits for its tracee to stop ([`wait`](super::wait), with
//! [`WaitFlags::STOPPED`](super::WaitFlags::STOPPED) and
//! [`ALL_CHILDREN`](super::WaitFlags::ALL_CHILDREN)), which gives a
//! [`Stop`]; while the tracee is stopped it reads and writes
//! ([`registers`], [`peek`], [`syscall_info`]...); then it restarts it:
//! [`cont`] until the next event, [`syscall`] until the next system call
//! as well, [`single_step`] for one instruction. Each takes the signal to
//! deliver to the tracee as it restarts: 0 for none, or the one a
//! [`Stop::Signal`] reported, which is otherwise swallowed.
//!
//! ```no_run
//! # #[cfg(all(feature = "alloc", any(target_os = "linux", target_os = "fullrust")))] {
//! use oscall::process::Command;
//! use oscall::process::linux::ptrace::{self, Options, Stop, SyscallStop};
//! use oscall::process::linux::{self, ConfineExt as _, WaitEvent, WaitFlags, WaitFor};
//!
//! // Prints the system calls of a program.
//! let child = Command::new("/bin/true").trace_me().spawn()?;
//! let pid = child.id();
//! let flags = WaitFlags::EXITED | WaitFlags::STOPPED | WaitFlags::ALL_CHILDREN;
//! let mut first = true;
//! while let Some(waited) = linux::wait(WaitFor::Process(pid), flags)? {
//! let signal = match waited.event {
//! WaitEvent::Trapped(Stop::Signal(_)) if first => {
//! // The stop of a program that starts.
//! first = false;
//! ptrace::set_options(pid, Options::TRACE_SYSGOOD | Options::EXIT_KILL)?;
//! 0
//! }
//! WaitEvent::Trapped(Stop::Syscall) => {
//! if let SyscallStop::Entry { number, .. } = ptrace::syscall_info(pid)?.stop {
//! println!("{number}");
//! }
//! 0
//! }
//! WaitEvent::Trapped(Stop::Signal(signal)) => signal,
//! WaitEvent::Trapped(_) => 0,
//! // It ended.
//! _ => break,
//! };
//! ptrace::syscall(pid, signal)?;
//! }
//! # }
//! # Ok::<(), oscall::Error>(())
//! ```
//!
//! # A thread traces a thread
//!
//! The tracee is one thread, named by its thread identifier (that of a
//! process is its first thread's), and the tracer is the **thread** that
//! attached, or that spawned the child: a request made by another thread
//! of the same process fails with
//! [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess), as does a request
//! that needs the tracee stopped when it is not. Waiting is not so
//! strict: any thread of the tracer's process may wait for the tracee.
//!
//! A tracee that is not a child of its tracer is waited for like one, and
//! goes back to its parent when the tracer [`detach`]es or ends. A tracer
//! that ends leaves its tracees running, unless [`Options::EXIT_KILL`].
//!
//! # With a system call filter
//!
//! A [`seccomp`](super::seccomp) filter that answers
//! [`Action::Trace`](super::seccomp::Action::Trace) stops the thread
//! before the call for a tracer that asked for it
//! ([`Options::TRACE_SECCOMP`]): [`Stop::Seccomp`], with the number the
//! filter gave as [`event_message`]. The tracer may change the call (its
//! number and arguments are registers), skip it, or let it be. Without a
//! tracer that asked, the call fails with `ENOSYS`.
//!
//! # What is needed of the system
//!
//! `ptrace` is in every kernel. qemu-user has none of it
//! ([`Unsupported`](crate::ErrorKind::Unsupported)), and the default
//! system call filter of an older container runtime refuses it
//! ([`PermissionDenied`](crate::ErrorKind::PermissionDenied)). What may
//! be traced is restricted by the system: see [`seize`].
use crate::;
crateflags!
/// Why a traced thread stopped: what the status of a wait says of it
/// ([`WaitEvent::Trapped`](super::WaitEvent::Trapped)).
/// The general registers of a thread of the target architecture: what
/// [`registers`] reads (the `NT_PRSTATUS` register set, the kernel's
/// `struct user_regs_struct`).
/// The general registers of a thread of the target architecture: what
/// [`registers`] reads (the `NT_PRSTATUS` register set, the kernel's
/// `struct user_regs_struct`).
/// The general registers of a thread of the target architecture: what
/// [`registers`] reads (the `NT_PRSTATUS` register set, the kernel's
/// `struct user_pt_regs`).
/// The general registers of a thread of the target architecture: what
/// [`registers`] reads (the `NT_PRSTATUS` register set, the kernel's
/// `struct pt_regs`).
/// The general registers of a thread of the target architecture: what
/// [`registers`] reads (the `NT_PRSTATUS` register set, the kernel's
/// `struct user_regs_struct`). Each is 64 bits on riscv64, 32 on riscv32.
const _: = assert!;
/// The register set of the general registers (`NT_PRSTATUS`): what
/// [`Registers`] is. For [`get_regset`] and [`set_regset`].
pub const REGSET_GENERAL: u32 = NT_PRSTATUS;
/// The register set of the floating-point registers (`NT_PRFPREG`), whose
/// layout is the architecture's (`struct user_fpregs_struct`,
/// `user_fpsimd_state`, `__riscv_d_ext_state`...).
pub const REGSET_FLOATING_POINT: u32 = NT_PRFPREG;
/// What the kernel says of the signal a tracee stopped for, or of the
/// event that stopped it: what [`signal_info`] reads (`siginfo_t`).
/// Where in a system call a tracee is stopped: part of [`SyscallInfo`].
/// The system call a tracee is stopped at: what [`syscall_info`] reads
/// (`struct ptrace_syscall_info`).
/// Makes the calling **thread** a tracee of its parent:
/// `ptrace(PTRACE_TRACEME)`. Nothing stops yet: the thread stops, for its
/// parent to see, at every signal it is sent from then on, and with a
/// `SIGTRAP` when it runs a program.
///
/// This is for a child that will run a program, between `fork` and
/// `execve`. [`ConfineExt::trace_me`](super::ConfineExt::trace_me) does it
/// in the child of a [`Command`](crate::process::Command).
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) for a thread
/// that is traced already, and where a security module forbids it.
/// Makes the calling thread the tracer of the thread `pid`, without
/// stopping it: `ptrace(PTRACE_SEIZE)` (Linux 3.4). [`interrupt`] stops
/// it. `options` are set at once, with no moment at which the tracee runs
/// without them.
///
/// A thread that was seized reports the stops of its process as
/// [`Stop::GroupStop`], can be [`interrupt`]ed and [`listen`]ed to, and
/// gets no `SIGTRAP` when it runs a program: this is the attachment to
/// use.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) when the
/// caller may not trace that thread. It must have the same user and
/// groups and no fewer capabilities, or `CAP_SYS_PTRACE`; the target must
/// be dumpable ([`set_dumpable`](super::set_dumpable)); and a security
/// module may ask for more: Yama, in its usual setting
/// (`kernel.yama.ptrace_scope` 1), only lets a process trace its
/// descendants. Also for a thread that is traced already.
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess) for no such thread.
/// Makes the calling thread the tracer of the thread `pid` and sends it
/// `SIGSTOP`: `ptrace(PTRACE_ATTACH)`. The stop that follows is a
/// [`Stop::Signal`] of `SIGSTOP`, which must be waited for before
/// anything else, and which cannot be told from a `SIGSTOP` someone else
/// sent meanwhile: [`seize`] has no such flaw.
///
/// # Errors
///
/// As [`seize`].
/// Stops the tracee `pid`, which was [`seize`]d:
/// `ptrace(PTRACE_INTERRUPT)`. It reports [`Stop::Interrupted`], or
/// whatever else stopped it first.
///
/// # Errors
///
/// `EIO` for a tracee that was attached another way.
/// Restarts the tracee `pid`, which is in a [`Stop::GroupStop`], without
/// letting it run: `ptrace(PTRACE_LISTEN)`. It stays stopped as the
/// signal that stopped its process wants, and its tracer is told when
/// that changes (`SIGCONT`, a new stop, a signal that kills). For a
/// tracee that was [`seize`]d.
/// Stops tracing the thread `pid`, which goes on running:
/// `ptrace(PTRACE_DETACH)`. `signal` is delivered to it as it restarts; 0
/// for none. The tracee must be stopped.
/// Restarts the stopped tracee `pid` until its next event:
/// `ptrace(PTRACE_CONT)`. `signal` is delivered to it as it restarts; 0
/// for none.
///
/// # Errors
///
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess) for a thread the
/// caller does not trace, one that is not stopped, and one that was
/// killed meanwhile; `EIO` for a number that is no signal.
/// Restarts the stopped tracee `pid` as [`cont`] does, until it next
/// enters or leaves a system call: `ptrace(PTRACE_SYSCALL)`. The two
/// stops of a call alternate; [`syscall_info`] says which one it is.
/// Restarts the stopped tracee `pid` for one instruction:
/// `ptrace(PTRACE_SINGLESTEP)`. It then stops with a `SIGTRAP`
/// ([`Stop::Signal`]).
///
/// # Errors
///
/// `EIO` on a kernel that cannot do it: those of 32-bit ARM and of
/// RISC-V, of 32 and 64 bits, have no such request (a debugger there
/// puts a breakpoint after the instruction). It is the kernel that
/// counts: a 32-bit ARM program on an aarch64 kernel is stepped.
/// Replaces the options of the stopped tracee `pid`:
/// `ptrace(PTRACE_SETOPTIONS)`.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for an option the
/// kernel does not have.
/// The number that goes with the event the tracee `pid` is stopped at:
/// `ptrace(PTRACE_GETEVENTMSG)`. The identifier of the new process or
/// thread for [`Stop::Fork`], [`Stop::Vfork`] and [`Stop::Clone`]; the
/// exit status, as `wait4` would encode it, for [`Stop::Exit`]; what the
/// filter gave for [`Stop::Seccomp`]; 1 or 2 at the entry or the exit of
/// a system call (Linux 5.3).
/// Reads a set of registers of the stopped tracee `pid` into `buf`, and
/// returns how many bytes of it were written:
/// `ptrace(PTRACE_GETREGSET)`. `kind` names the set: [`REGSET_GENERAL`],
/// [`REGSET_FLOATING_POINT`], or one of the `NT_*` numbers the
/// architecture has (`elf.h`). A set longer than `buf` is cut.
///
/// [`registers`] is this for the general registers, as a structure.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a set the
/// architecture, or this processor, does not have.
/// Writes a set of registers of the stopped tracee `pid`:
/// `ptrace(PTRACE_SETREGSET)`. `data` is the set, or the beginning of it,
/// as [`get_regset`] read it.
/// The general registers of the stopped tracee `pid`:
/// `ptrace(PTRACE_GETREGSET)` with `NT_PRSTATUS`.
///
/// # Errors
///
/// [`Other`](crate::ErrorKind::Other) for a tracee of another
/// architecture than the caller (a 32-bit program traced by a 64-bit
/// one), whose registers are not this structure: [`get_regset`] reads
/// them as bytes.
/// Replaces the general registers of the stopped tracee `pid`:
/// `ptrace(PTRACE_SETREGSET)` with `NT_PRSTATUS`. The kernel keeps what a
/// program may not change (the privileged bits of the flags, the segment
/// registers it does not allow).
/// Reads one word of the memory of the stopped tracee `pid`, at
/// `address`: `ptrace(PTRACE_PEEKDATA)`. The address need not be aligned.
///
/// [`read_memory`](super::read_memory) reads any length in one call, and
/// does not need the target stopped, nor traced.
///
/// # Errors
///
/// `EIO` or `EFAULT` for an address the tracee has nothing readable at.
/// Writes one word to the memory of the stopped tracee `pid`, at
/// `address`: `ptrace(PTRACE_POKEDATA)`. Unlike
/// [`write_memory`](super::write_memory), this writes to memory the
/// tracee itself may not write: its code, for a breakpoint. A page of a
/// file mapped privately is copied first, as if the tracee had written.
/// What the kernel says of the signal the tracee `pid` is stopped for:
/// `ptrace(PTRACE_GETSIGINFO)`.
///
/// For a stop that is an event and no signal, a tracee that was
/// [`seize`]d answers with the status of the stop as
/// [`code`](SignalInfo::code) (measured for a [`Stop::GroupStop`]).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for the stop of its
/// process by a stop signal, of a tracee that was [`attach`]ed: that stop
/// reports as a [`Stop::Signal`] like the signal before it, and this
/// error is how the two are told apart.
/// The system call the tracee `pid` is stopped at:
/// `ptrace(PTRACE_GET_SYSCALL_INFO)` (Linux 5.3). The same on every
/// architecture, where [`registers`] needs to know which register is
/// what.