Debian Codegraph @

src/common/validation.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore execveat fexecve memfd prefixcat rsplit testcat atexit profraw Cprofile
7
8 use std::ffi::{OsStr, OsString};
9 use std::io::{Write, stderr};
10 use std::path::{Path, PathBuf};
11 use std::process;
12
13 use uucore::Args;
14 use uucore::display::Quotable;
15 use uucore::locale;
16
17 // The instrumented binary built by `util/build-pgo.sh` (`--cfg pgo_training`)
18 // has to flush its own profile counters on Windows. Every exit below goes
19 // through `std::process::exit`, which is `libc::exit` on Unix but
20 // `ExitProcess` on Windows; the latter skips the `atexit` handler the LLVM
21 // profiling runtime writes the counters from, so the training runs would
22 // leave nothing but empty `.profraw` files behind.
23 #[cfg(all(pgo_training, windows))]
24 unsafe extern "C" {
25 fn __llvm_profile_write_file() -> i32;
26 }
27
28 /// Terminates the process with `code`, flushing the PGO counters when the
29 /// binary was built for profile training on Windows.
30 pub fn exit(code: i32) -> ! {
31 #[cfg(all(pgo_training, windows))]
32 // SAFETY: `__llvm_profile_write_file` is provided by the LLVM profiling
33 // runtime, which is linked in whenever this cfg is set (the same build
34 // passes `-Cprofile-generate`). It takes no arguments and only writes the
35 // counter file named by `LLVM_PROFILE_FILE`.
36 unsafe {
37 __llvm_profile_write_file();
38 }
39 process::exit(code)
40 }
41
42 /// Gets all available utilities including "coreutils"
43 #[allow(clippy::type_complexity)]
44 pub fn get_all_utilities<T: Args>(
45 util_map: &phf::OrderedMap<&'static str, (fn(T) -> i32, fn() -> clap::Command)>,
46 ) -> Vec<&'static str> {
47 std::iter::once("coreutils")
48 .chain(util_map.keys().copied())
49 .collect()
50 }
51
52 /// Prints a "utility not found" error and exits
53 pub fn not_found(util: &OsStr) -> ! {
54 let _ = writeln!(
55 stderr(),
56 "coreutils: unknown program '{}'",
57 util.maybe_quote()
58 );
59 exit(1);
60 }
61
62 /// Prints an "unrecognized option" error and exits
63 pub fn unrecognized_option(binary_name: &str, option: &OsStr) -> ! {
64 let _ = writeln!(
65 stderr(),
66 "{binary_name}: unrecognized option '{}'",
67 option.to_string_lossy()
68 );
69 exit(1);
70 }
71
72 /// Sets up localization for a utility with proper error handling
73 pub fn setup_localization_or_exit(util_name: &str) {
74 let util_name = get_canonical_util_name(util_name);
75 locale::setup_localization(util_name).unwrap_or_else(|err| {
76 match err {
77 locale::LocalizationError::ParseResource {
78 error: err_msg,
79 snippet,
80 } => eprintln!("Localization parse error at {snippet}: {err_msg}"),
81 other => eprintln!("Could not init the localization system: {other}"),
82 }
83 exit(99)
84 });
85 }
86
87 /// Gets the canonical utility name, resolving aliases
88 fn get_canonical_util_name(util_name: &str) -> &str {
89 match util_name {
90 // uu_test aliases - '[' is an alias for test
91 "[" => "test",
92 "dir" | "vdir" => "ls", // aliases for ls
93
94 // Default case - return the util name as is
95 _ => util_name,
96 }
97 }
98
99 /// Gets the binary path from command line arguments
100 /// Panics if the binary path cannot be determined
101 #[cfg(any(
102 not(any(
103 target_os = "linux",
104 all(target_os = "android", target_pointer_width = "64")
105 )),
106 target_env = "musl"
107 ))]
108 pub fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
109 PathBuf::from(args.next().unwrap())
110 // no fallback for empty args. current_exe() (/proc/self/exe) is valid only for hardlinks
111 }
112 /// Get actual binary path from kernel, not argv0, to prevent `env -a` from bypassing
113 /// AppArmor, SELinux policies on hard-linked binaries
114 #[cfg(all(
115 any(
116 target_os = "linux",
117 all(target_os = "android", target_pointer_width = "64")
118 ),
119 not(target_env = "musl")
120 ))]
121 pub fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
122 use std::fs::File;
123 use std::io::Read;
124 use std::os::unix::ffi::OsStrExt;
125 let execfn = rustix::param::linux_execfn();
126 let execfn_bytes = execfn.to_bytes();
127 let exec_path = Path::new(OsStr::from_bytes(execfn_bytes));
128 let argv0 = args.next().unwrap();
129 let mut shebang_buf = [0u8; 2];
130 // exec_path is wrong when called from a shebang, or via fexecve/execveat:
131 // the kernel reports /dev/fd/* and memfd_create/glibc's fallback /proc/self/fd/*
132 // argv0 is not full-path when called from PATH
133 if execfn_bytes.rsplit(|&b| b == b'/').next() == argv0.as_bytes().rsplit(|&b| b == b'/').next()
134 || execfn_bytes.starts_with(b"/proc/")
135 || execfn_bytes.starts_with(b"/dev/fd/")
136 || (File::open(Path::new(exec_path))
137 .and_then(|mut f| f.read_exact(&mut shebang_buf))
138 .is_ok()
139 && &shebang_buf == b"#!")
140 {
141 argv0.into()
142 } else {
143 exec_path.into()
144 }
145 }
146 /// Extracts the binary name from a path
147 pub fn name(binary_path: &Path) -> Option<&str> {
148 binary_path.file_stem()?.to_str()
149 }
150
151 #[cfg(test)]
152 mod tests {
153 use super::*;
154
155 #[test]
156 fn test_get_canonical_util_name() {
157 // Test a few key aliases
158 assert_eq!(get_canonical_util_name("["), "test");
159 assert_eq!(get_canonical_util_name("dir"), "ls");
160
161 // Test passthrough case
162 assert_eq!(get_canonical_util_name("cat"), "cat");
163 }
164
165 #[test]
166 fn test_name() {
167 // Test normal executable name
168 assert_eq!(name(Path::new("/usr/bin/ls")), Some("ls"));
169 assert_eq!(name(Path::new("cat")), Some("cat"));
170 assert_eq!(
171 name(Path::new("./target/debug/coreutils")),
172 Some("coreutils")
173 );
174
175 // Test with extensions
176 assert_eq!(name(Path::new("program.exe")), Some("program"));
177 assert_eq!(name(Path::new("/path/to/utility.bin")), Some("utility"));
178
179 // Test edge cases
180 assert_eq!(name(Path::new("")), None);
181 assert_eq!(name(Path::new("/")), None);
182 }
183 }