|
| 1 | +// |
| 2 | +// Copyright (c) 2026 Basil Crow |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | +// |
| 16 | + |
| 17 | +//! Test helper that modifies its environment at runtime via `set_var`. |
| 18 | +//! |
| 19 | +//! Used by integration tests to verify that `penv` and `pargs -e` reflect |
| 20 | +//! runtime environment changes (read from the `environ` symbol) rather than |
| 21 | +//! the static `/proc/pid/environ` snapshot. |
| 22 | +
|
| 23 | +use std::env; |
| 24 | +use std::fs::File; |
| 25 | +use std::thread; |
| 26 | +use std::time::Duration; |
| 27 | + |
| 28 | +fn allow_ptrace_for_tests() { |
| 29 | + // On Linux with Yama ptrace_scope=1 (the Ubuntu default), only a |
| 30 | + // process's descendants may ptrace it. Since the test harness spawns |
| 31 | + // this process and the ptool as siblings, we opt in to tracing by any |
| 32 | + // process so the tests work without elevated privileges. |
| 33 | + unsafe { |
| 34 | + nix::libc::prctl( |
| 35 | + nix::libc::PR_SET_PTRACER, |
| 36 | + nix::libc::PR_SET_PTRACER_ANY, |
| 37 | + 0, |
| 38 | + 0, |
| 39 | + 0, |
| 40 | + ); |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +fn main() { |
| 45 | + allow_ptrace_for_tests(); |
| 46 | + |
| 47 | + // Add a new environment variable at runtime. This will only be visible |
| 48 | + // via the `environ` symbol (process_vm_readv), not via /proc/pid/environ. |
| 49 | + env::set_var("PTOOLS_TEST_SETENV_VAR", "runtime_value"); |
| 50 | + |
| 51 | + // Also overwrite an existing variable to verify updates are reflected. |
| 52 | + env::set_var("PTOOLS_TEST_OVERWRITE_VAR", "after"); |
| 53 | + |
| 54 | + let signal_path = |
| 55 | + env::var("PTOOLS_TEST_READY_FILE").expect("PTOOLS_TEST_READY_FILE must be set"); |
| 56 | + |
| 57 | + // Signal parent process (the test process) that this process is ready to be observed by the |
| 58 | + // ptool being tested. |
| 59 | + File::create(signal_path).unwrap(); |
| 60 | + |
| 61 | + // Wait for the parent to finish running the ptool and then kill us. |
| 62 | + loop { |
| 63 | + thread::sleep(Duration::from_millis(100)); |
| 64 | + } |
| 65 | +} |
0 commit comments