rucc_driver/lib.rs
1//! The driver: command line parsing, the phase graph, job scheduling and the linker
2//! invocation.
3//!
4//! Design: `spec/04-driver-and-cli.md`. Layer rank 13, see `spec/18-package-layout.md`.
5//!
6//! This is the only crate that is allowed to know the process exists. It reads the command
7//! line, touches the file system, spawns the linker and writes to the terminal, and it hands
8//! everything below it a [`Session`]. The binary crate is a `main` that calls
9//! [`run`] and nothing else, so that the whole driver is reachable from a test.
10//!
11//! # Status
12//!
13//! `--help`, `--version` and `--print-config` are real, which is the `M0` exit criterion in
14//! `spec/17-milestones.md`. The phase graph is real and `-###` prints it, and the scheduler
15//! that will run it is real and tested.
16//!
17//! Two phases run. `-E` reads the file, runs phase 4 over it and writes the result, to `-o` or
18//! to standard output. `--emit=tast` carries on through phase 7, the parse and the checking,
19//! and writes the typed tree. The flags those two read are real with them, which is `-D`, `-U`,
20//! `-I`, `-I-`, `-iquote`, `-isystem`, `-idirafter`, `-iprefix`, `-iwithprefix`,
21//! `-iwithprefixbefore`, `-include`, `-imacros`, `--sysroot=`, `-isysroot`, `-P`, `-std=`,
22//! `-fgnuc-version=`, `-ansi`, `-ffreestanding`, `-fno-builtin`, `-fno-builtin-<name>`,
23//! `-fgnu89-inline`, `-pedantic` and `-Werror`.
24//! The phases after them still say they are not implemented.
25//!
26//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
27//! explicitly unstable and will change without a major version bump.
28
29#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.26")]
30
31pub mod cache;
32pub mod compile;
33pub mod deps;
34pub mod fetch;
35pub mod install;
36pub mod library;
37pub mod link;
38mod map;
39pub mod phase;
40pub mod preprocess;
41pub mod schedule;
42
43use std::fmt::Write as _;
44use std::io::Write as _;
45use std::path::PathBuf;
46
47use rucc_codegen::coverage::{self, Fired};
48use rucc_codegen::pressure::Pressure;
49use rucc_pp::Dependency;
50use rucc_session::{
51 Compress, Control, Dumps, EmitKind, Hook, Options, Pic, PrefixMap, Preinclude, Protector,
52 SaveTemps, Session, Std, Wrapping, runtime,
53};
54use rucc_sysroot::{Manifest, Sysroot};
55use rucc_target::{ObjectFormat, Triple};
56
57use crate::link::LinkOptions;
58
59pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
60pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan};
61pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
62pub use crate::schedule::Jobs;
63
64/// The compiler's version, taken from the workspace manifest.
65pub const VERSION: &str = env!("CARGO_PKG_VERSION");
66
67/// What the command line asked for.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum Action {
70 /// Print usage and exit successfully.
71 Help,
72 /// Print the version and exit successfully.
73 Version,
74 /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
75 ///
76 /// A build system asks these before it compiles anything, and what it does with the answer
77 /// is paste it into a path or into another command line, so each one is a single line with
78 /// no decoration around it.
79 Print(String),
80 /// Print the resolved configuration and exit successfully.
81 PrintConfig(Box<Options>),
82 /// Print the passes the level will run and exit successfully.
83 PrintPipeline(Box<Options>),
84 /// Print the phase plan and the link line and exit successfully, which is `-###`.
85 PrintPlan {
86 /// The resolved options, which is what says what the link line is for.
87 opts: Box<Options>,
88 /// What to do to each input, and in what order.
89 plan: Box<Plan>,
90 /// What the command line said about linking.
91 link: Box<LinkOptions>,
92 },
93 /// Compile the given inputs.
94 Compile {
95 /// The resolved options.
96 opts: Box<Options>,
97 /// What to do to each input, and in what order.
98 plan: Box<Plan>,
99 /// What the command line said about linking.
100 link: Box<LinkOptions>,
101 /// How many translation units to compile at once.
102 jobs: Jobs,
103 /// Whether `-v` asked for the plan to be printed while it runs.
104 verbose: bool,
105 },
106}
107
108/// Why a command line was rejected.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct CliError {
111 /// The message, lowercase and without a trailing period, in the same shape as any other
112 /// diagnostic.
113 pub message: String,
114}
115
116impl std::fmt::Display for CliError {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.write_str(&self.message)
119 }
120}
121
122impl std::error::Error for CliError {}
123
124fn err(message: impl Into<String>) -> CliError {
125 CliError { message: message.into() }
126}
127
128/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
129///
130/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
131/// the only one that lets a directory whose name contains an `=` be the old half. It also means
132/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
133/// trap until you notice the alternative traps the far more common case.
134fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
135 let rest = &arg[flag.len()..];
136 PrefixMap::split(rest).ok_or_else(|| {
137 let flag = flag.trim_end_matches('=');
138 err(format!(
139 "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
140 ))
141 })
142}
143
144/// A question the command line asked instead of asking for a compilation.
145///
146/// These are answered after the loop rather than where they are read, because every one of them
147/// is about the target or about the library search and the last word on both is the end of the
148/// command line.
149enum Query {
150 /// `-dumpmachine`, the triple.
151 Machine,
152 /// `-dumpversion` and `-dumpfullversion`, which are the same three numbers here.
153 Version,
154 /// `-print-multiarch`, the directory name a distribution files this target under.
155 Multiarch,
156 /// `-print-search-dirs`, in the three lines GCC prints.
157 SearchDirs,
158 /// `-print-sysroot`, the root the headers and the libraries are read under.
159 Sysroot,
160 /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
161 SysrootProvenance,
162 /// `-print-sysroot-digest`, the one number that names all of it.
163 SysrootDigest,
164 /// `-print-file-name=<name>`, the full path of a library file.
165 FileName(String),
166 /// `-print-prog-name=<name>`, the full path of a program.
167 ProgName(String),
168 /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
169 Libgcc,
170}
171
172/// Usage text.
173///
174/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
175/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
176pub const USAGE: &str = "\
177rucc, an optimizing C compiler
178
179usage: rucc [options] file...
180
181options:
182 -c compile and assemble, do not link
183 -S compile only, emit assembly
184 -E preprocess only
185 -o <file> write output to <file>, or to standard output for -
186 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
187 -I <dir> add <dir> to the include search path
188 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
189 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
190 -include <file>, -imacros <file> read <file> first, the second for its macros only
191 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
192 -P, -dM with -E: leave out the markers, or dump the macros
193 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
194 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
195 -std=<dialect> c89 through c23, and the gnu spellings
196 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
197 -x <lang> treat later inputs as <lang>, or none to stop
198 -O<level> optimize: 0, 1, 2, 3, s, z
199 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
200 -f[no-]sanitize=<what> the negative is taken, the positive is refused by name
201 -f[no-]safety-subobject a write has to stay inside the member it names
202 -f[no-]safety-restrict two restrict pointers of one block may not meet
203 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
204 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
205 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
206 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
207 -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf compress debug sections, one file not two
208 -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects read, and not done yet
209 -fprofile-use[=<path>] -fprofile-dir=<dir> read too, where -fprofile-generate is refused
210 -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
211 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
212 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
213 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
214 -fPIC -fpic -fPIE -fpie, -fno-common, -pipe what it does anyway
215 -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks what it assumes anyway
216 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
217 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
218 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
219 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
220 -pg -p, -mfentry -mno-fentry call a profiler on the way in, and where that call goes
221 -fpatchable-function-entry=<n>[,<m>] room at the top of every function to patch later
222 -fwrapv, -fwrapv-pointer, -fno-strict-overflow signed or pointer overflow wraps
223 -ftrapv signed overflow stops the program instead
224 -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums change the ABI
225 -ffp-contract=<how> fuse a multiply and an addition: fast, on or off
226 -fexcess-precision=<how>, -f[no-]rounding-math, -f[no-]trapping-math what may be folded
227 -ffile-prefix-map=<old>=<new> rewrite that front of every path we put in the output
228 -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map= the same, one output each
229 -pthread build for more than one thread, and link the library for it
230 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
231 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
232 -print-sysroot the root the headers and the libraries are read under
233 -print-sysroot-provenance every input under it, where it came from and its licence
234 -print-sysroot-digest the sha256 of that record, which names the whole sysroot in one line
235 -j[n] compile n translation units at once, default all
236 -v, -### print each phase as it runs, or without running any
237 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
238 --target=<triple> generate code for <triple>
239 --emit=<kind> exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
240 safety-summary, type-granules
241 --print-config, --print-pipeline print the configuration or the pipeline, and exit
242 --version print the version and exit
243 -h, --help print this message and exit
244
245See spec/04-driver-and-cli.md for the full flag reference.
246";
247
248/// The argument of a flag that may be joined to it or may be the next word.
249///
250/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
251fn joined_or_next(
252 arg: &str,
253 at: usize,
254 args: &[String],
255 i: &mut usize,
256) -> Result<String, CliError> {
257 if arg.len() > at {
258 return Ok(arg[at..].to_owned());
259 }
260 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
261 *i += 1;
262 Ok(next.clone())
263}
264
265/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
266/// own.
267///
268/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
269/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
270/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
271/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
272/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
273/// because none of them is implemented.
274///
275/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
276/// those two spellings is read rather than by being on this list.
277const SANITIZERS: [&str; 34] = [
278 "address",
279 "kernel-address",
280 "hwaddress",
281 "kernel-hwaddress",
282 "pointer-compare",
283 "pointer-subtract",
284 "thread",
285 "leak",
286 "undefined",
287 "shift",
288 "shift-base",
289 "shift-exponent",
290 "integer-divide-by-zero",
291 "unreachable",
292 "vla-bound",
293 "null",
294 "return",
295 "signed-integer-overflow",
296 "bounds",
297 "bounds-strict",
298 "alignment",
299 "object-size",
300 "float-divide-by-zero",
301 "float-cast-overflow",
302 "nonnull-attribute",
303 "returns-nonnull-attribute",
304 "bool",
305 "enum",
306 "vptr",
307 "pointer-overflow",
308 "builtin",
309 "alias",
310 "restrict",
311 "memory",
312];
313
314/// Parses a command line, without the program name.
315///
316/// # Errors
317///
318/// Returns the message to print when the arguments do not name a compilation this compiler
319/// can attempt.
320pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
321 let host = Triple::host()
322 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
323 let mut opts = Options::new(host);
324 let mut inputs: Vec<Input> = Vec::new();
325 let mut print_config = false;
326 let mut print_pipeline = false;
327 let mut print_plan = false;
328 let mut verbose = false;
329 let mut jobs = Jobs::default();
330 let mut nostdinc = false;
331 let mut sysroot: Option<PathBuf> = None;
332 // The whole ten field target, kept beside the three field one because `--target=` can pin a
333 // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
334 // else today, and `None` is a command line that named no target, which is this machine.
335 let mut pinned: Option<rucc_tuple::TargetTuple> = None;
336 let mut output = None;
337 let mut link = LinkOptions::default();
338 let mut query: Option<Query> = None;
339 let mut threads = false;
340 // Which sanitizers are still asked for by the end of the command line. Accumulated across the
341 // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
342 // build that asks for a check and then takes it back has asked for nothing. What happens to a
343 // set that is not empty is decided after the loop.
344 let mut sanitizers: Vec<&str> = Vec::new();
345 // `-x` applies to inputs that come after it and stays in effect until the next one, which
346 // is why it is tracked across the loop rather than attached to a single argument.
347 let mut forced: Option<InputKind> = None;
348 // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
349 // the flags after it and not the ones before, so a command line may set it more than once.
350 // GCC's default is its own installed header directory with the last component taken off,
351 // which is a path a cross compiler's build system knows and passes; there is no equivalent
352 // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
353 // outright.
354 let mut iprefix = String::new();
355
356 let mut i = 0;
357 while i < args.len() {
358 let arg = args[i].as_str();
359 i += 1;
360 match arg {
361 "-h" | "--help" => return Ok(Action::Help),
362 "--version" => return Ok(Action::Version),
363 "--print-config" => print_config = true,
364 "--print-pipeline" => print_pipeline = true,
365 "-###" => print_plan = true,
366 "-v" => verbose = true,
367 // The files a compilation goes through, kept rather than thrown away. The bare
368 // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
369 // gcc 16 does; `SaveTemps::Object` carries the measurement.
370 "-save-temps" => opts.save_temps = SaveTemps::Object,
371 _ if arg.starts_with("-save-temps=") => {
372 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
373 }
374 // How long each step took. A misspelling of this is worth rejecting rather than
375 // ignoring, since a run that says nothing looks like a compilation that took no time.
376 "-time" => opts.time = true,
377 "-c" => opts.emit = EmitKind::Object,
378 "-S" => opts.emit = EmitKind::Asm,
379 "-E" => opts.emit = EmitKind::Preprocessed,
380 "-g" => opts.debug_info = true,
381 // GCC's own levels of how much debug information to write. Zero is none and every
382 // other number is some, and this compiler has one amount, so the numbers above zero
383 // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
384 // debugger on the machine prefers, which is what we emit anyway.
385 "-g0" => opts.debug_info = false,
386 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
387 opts.debug_info = true;
388 }
389 // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
390 // asks for another version is told rather than handed a file it cannot read.
391 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
392 _ if arg.starts_with("-gdwarf-") => {
393 return Err(err(format!(
394 "{arg}: this compiler writes DWARF 5 and no other version, see \
395 spec/11-debug-info.md"
396 )));
397 }
398 // Whether the debug information goes in a file of its own beside the object. gcc
399 // writes that `.dwo` whether or not it found anything to put in it, which means a
400 // build system that declares the file as an output gets one and a make rule that
401 // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
402 // flag that changes nothing and refuses one that changes what is produced, and a file
403 // that does not appear is the plainest change of that kind there is. The negative
404 // spelling is taken, because putting it all in the object is what happens anyway.
405 "-gno-split-dwarf" => {}
406 "-gsplit-dwarf" => {
407 return Err(err(format!(
408 "{arg}: this compiler writes no separate `.dwo` file, and a build that \
409 expects one beside each object would wait for a file that never arrives, \
410 see spec/11-debug-info.md"
411 )));
412 }
413 // How the debug sections are compressed. There are none yet, so every answer produces
414 // the same bytes and taking the flag promises nothing that is not kept. The value is
415 // still checked, because a typo in a distribution's flags is worth finding when the
416 // compiler reads it rather than when somebody later wonders why nothing got smaller.
417 // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
418 "-gz" => opts.compress = Compress::Zlib,
419 _ if arg.starts_with("-gz=") => {
420 let how = &arg["-gz=".len()..];
421 opts.compress = how.parse().map_err(|()| {
422 err(format!(
423 "`{how}` is not a way to compress debug sections, which is none, zlib, \
424 zlib-gnu or zstd"
425 ))
426 })?;
427 }
428 "-Werror" => opts.warnings_are_errors = true,
429 // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
430 // through rather than here, so that a warning `-w` dropped is not counted either.
431 "-w" => opts.warnings = false,
432 "-pedantic-errors" => {
433 opts.pedantic = true;
434 opts.warnings_are_errors = true;
435 }
436 "-P" => opts.line_markers = false,
437 // The dependency family, which section 4.4 calls required because every build system
438 // that generates its own makefiles asks for it. The two that end in `D` write a file
439 // beside the object and let the compilation happen, and the two that do not write to
440 // standard output and stop after it. Nothing here turns the system headers back on
441 // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
442 // `-MM`: the flag asking for fewer of them is the one with something to say.
443 "-M" => {
444 opts.deps.emit = true;
445 opts.deps.instead_of_compiling = true;
446 }
447 "-MM" => {
448 opts.deps.emit = true;
449 opts.deps.instead_of_compiling = true;
450 opts.deps.system_headers = false;
451 }
452 "-MD" => opts.deps.emit = true,
453 "-MMD" => {
454 opts.deps.emit = true;
455 opts.deps.system_headers = false;
456 }
457 "-MP" => opts.deps.phony = true,
458 // These three take a word and only in the separated form, which is how GCC spells
459 // them and how every build system writes them.
460 "-MF" | "-MT" | "-MQ" => {
461 let value =
462 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
463 i += 1;
464 match arg {
465 "-MF" => opts.deps.file = Some(value.clone()),
466 // The whole of the difference between the two. `-MT` is for a build that has
467 // already escaped what it is passing, and `-MQ` is for one that has a name
468 // and wants it to arrive as that name.
469 "-MT" => opts.deps.targets.push(value.clone()),
470 _ => opts.deps.targets.push(deps::escaped(value)),
471 }
472 }
473 // The questions a build system asks before it compiles anything. Answered after the
474 // loop, because each one is about the target or the library search and the command
475 // line has not finished saying what those are.
476 "-dumpmachine" => query = Some(Query::Machine),
477 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
478 "-print-multiarch" => query = Some(Query::Multiarch),
479 "-print-search-dirs" => query = Some(Query::SearchDirs),
480 "-print-sysroot" => query = Some(Query::Sysroot),
481 // Both spellings, because this one is ours rather than GCC's and our own documents
482 // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
483 // two dashes like the other flags we invented, and document 12's table gives it one
484 // like the `-print-` family it sits in. A person who reads either and types what it
485 // says is right, so neither is refused.
486 "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
487 query = Some(Query::SysrootProvenance);
488 }
489 "-print-sysroot-digest" | "--print-sysroot-digest" => {
490 query = Some(Query::SysrootDigest);
491 }
492 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
493 _ if arg.starts_with("-print-file-name=") => {
494 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
495 }
496 _ if arg.starts_with("-print-prog-name=") => {
497 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
498 }
499 // A program built to run in more than one thread. On every platform this compiler
500 // targets that is a macro the library's headers read and one more library on the
501 // link line, and the library is added after the loop so that it lands after the
502 // objects that refer to it.
503 "-pthread" | "-pthreads" => {
504 opts.defines.push("_REENTRANT".to_owned());
505 threads = true;
506 }
507 "-ansi" => {
508 opts.std = Std::C89;
509 opts.gnu_extensions = false;
510 }
511 // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
512 // the spelling a build system that groups its warning flags tends to write.
513 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
514 // Both directions, because a build that needs this for one directory turns it back
515 // off for the next one rather than leaving it on for the whole tree.
516 "-fpermissive" => opts.permissive = true,
517 "-fno-permissive" => opts.permissive = false,
518 "-ffreestanding" => opts.hosted = false,
519 "-fhosted" => opts.hosted = true,
520 "-fno-builtin" => opts.builtins = false,
521 "-fbuiltin" => opts.builtins = true,
522 // The C89 dialects are under GNU's reading whatever this says, so turning it off
523 // there is turning off something the dialect asked for, which is accepted and does
524 // nothing. gcc refuses that command line, and there is nothing it could have meant.
525 "-fgnu89-inline" => opts.gnu89_inline = true,
526 "-fno-gnu89-inline" => opts.gnu89_inline = false,
527 // Both directions of each, because a build system that wants one of these usually
528 // writes it beside the flag that turns it back off for one directory.
529 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
530 "-fomit-frame-pointer" => opts.frame_pointer = false,
531 "-mno-red-zone" => opts.red_zone = false,
532 "-mred-zone" => opts.red_zone = true,
533 // Four flags rather than one with an argument, which is how gcc spells them and how
534 // every build line writes them. Last one wins, because a package build puts
535 // `-fstack-protector-strong` in its global flags and a directory that cannot have one
536 // turns it back off on the line after.
537 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
538 opts.protector = Protector::None;
539 }
540 "-fstack-protector" => opts.protector = Protector::Buffers,
541 "-fstack-protector-strong" => opts.protector = Protector::Strong,
542 "-fstack-protector-all" => opts.protector = Protector::All,
543 // The other half of what a hardened build asks for, and it is a question about the
544 // frame rather than about the function, so it is a switch rather than a level.
545 "-fstack-clash-protection" => opts.stack_clash = true,
546 "-fno-stack-clash-protection" => opts.stack_clash = false,
547 // The third of them, and the one that is a question with an argument rather than a
548 // family of spellings, because what it asks about is which of the two edges of a
549 // control flow transfer is checked. Bare is both of them, which is what gcc does.
550 "-fcf-protection" => opts.control = Control::Full,
551 "-fno-cf-protection" => opts.control = Control::None,
552 // Two spellings of the same request, which is what gcc has as well. `-p` was the older
553 // profiler and `-pg` the one that also recorded who called whom, and on every platform
554 // this compiler targets there is now one hook and both ask for it.
555 "-pg" | "-p" => {
556 opts.profile = true;
557 link.profile = true;
558 }
559 // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
560 // say where the call goes and a command line that asked for no call has nowhere to put
561 // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
562 // directory is a build system that would otherwise fail on every other directory.
563 "-mfentry" => opts.hook = Hook::Early,
564 "-mno-fentry" => opts.hook = Hook::Late,
565 // GCC drops its own include directory along with the system ones, because its
566 // headers are half of a pair with the library's and half a pair is worse than
567 // none. A build that passes this is supplying the whole set itself.
568 "-nostdinc" => nostdinc = true,
569 "-o" => {
570 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
571 i += 1;
572 }
573 // The flags that take a directory only in the separated form. GCC spells them
574 // this way and nothing writes `-iquotedir`, so accepting the joined form would
575 // mean guessing at a path that starts with the flag's own letters.
576 // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
577 // two mean the same thing here: the configured directories are under there rather
578 // than under the root.
579 "-isysroot" => {
580 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
581 i += 1;
582 sysroot = Some(PathBuf::from(dir));
583 }
584 "-iquote" | "-isystem" | "-idirafter" => {
585 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
586 i += 1;
587 match arg {
588 "-iquote" => opts.search.push_quote(dir.clone()),
589 "-isystem" => opts.search.push_system(dir.clone()),
590 _ => opts.search.push_after(dir.clone()),
591 }
592 }
593 "-iprefix" => {
594 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
595 i += 1;
596 }
597 // Where GCC puts these is not where its manual says it puts them, and this is the
598 // measured answer rather than the documented one: `-iwithprefix` lands in the
599 // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
600 // the `-I` slot. A cross build that uses them is relying on the behaviour, since
601 // that is the compiler it was developed against.
602 "-iwithprefix" | "-iwithprefixbefore" => {
603 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
604 i += 1;
605 let dir = format!("{iprefix}{dir}");
606 if arg == "-iwithprefix" {
607 opts.search.push_system(dir);
608 } else {
609 opts.search.push_bracket(dir);
610 }
611 }
612 "-include" | "-imacros" => {
613 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
614 i += 1;
615 opts.preincludes
616 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
617 }
618 // The flag `-iquote` was introduced to replace, still passed by build systems old
619 // enough to predate the replacement. It is not a directory: it says that every `-I`
620 // so far is for quoted includes only, and that a quoted include stops looking next
621 // to the file that wrote it.
622 "-I-" => opts.search.split_quote_chain(),
623 "-x" => {
624 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
625 i += 1;
626 forced = if lang == "none" {
627 None
628 } else {
629 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
630 };
631 }
632 // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
633 // translation units in one process rather than making the build system fork, and
634 // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
635 // to exist and has to be spelled the way `make` spells it.
636 // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
637 // and a build system may produce either, so both are read here rather than
638 // being normalised by whatever generated the command line.
639 _ if arg.starts_with("-D") => {
640 let value = joined_or_next(arg, 2, args, &mut i)?;
641 opts.defines.push(value);
642 }
643 _ if arg.starts_with("-U") => {
644 let value = joined_or_next(arg, 2, args, &mut i)?;
645 opts.undefines.push(value);
646 }
647 _ if arg.starts_with("-I") => {
648 let dir = joined_or_next(arg, 2, args, &mut i)?;
649 opts.search.push_bracket(dir);
650 }
651 _ if arg.starts_with("-std=") => {
652 let name = &arg["-std=".len()..];
653 let (std, gnu) = Std::from_flag(name)
654 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
655 opts.std = std;
656 opts.gnu_extensions = gnu;
657 }
658 // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
659 // handed, so a differential run that does not set it is comparing two compilers
660 // that believe they are different compilers.
661 // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
662 // that we have not written yet are accepted and ignored, because a dump is a
663 // debugging aid and a build that asks for one should still compile. A letter
664 // outside the family falls through to the unknown option error, which is what
665 // keeps `-dumpversion` from being read as a dump of nothing.
666 _ if Dumps::is_family(arg) => {
667 opts.dumps.add(&arg[2..]);
668 }
669 // One name at a time, which is what a build that means its own `memcpy` and the
670 // library's everything else writes. The name is not checked against a list, because
671 // the flag is about what the program means by a name and a program is allowed to mean
672 // something by a name this compiler has never heard of.
673 _ if arg.starts_with("-fno-builtin-") => {
674 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
675 }
676 _ if arg.starts_with("-fgnuc-version=") => {
677 let v = &arg["-fgnuc-version=".len()..];
678 opts.gnuc = v.parse().map_err(err)?;
679 }
680 // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
681 // than the unknown option one, because a build reaching for it is asking for a feature
682 // and deserves to be told it is not coming rather than told the spelling is wrong.
683 // The negative form is what this compiler does anyway, so it is taken and dropped.
684 "-fnested-functions" => {
685 return Err(err(
686 "nested functions are not supported: a call to one goes through a trampoline \
687 written on the stack, which no target that enforces an unexecutable stack \
688 allows",
689 ));
690 }
691 "-fno-nested-functions" => {}
692 // Which of the two links the output is for, which is a real difference and not a
693 // description of what happens anyway. Everything here is position independent either
694 // way, and what these decide is whether a name may be one another object defines or
695 // replaces, because a link that produces an executable puts every name in the same
696 // program and a link that produces a shared library does not.
697 //
698 // It matters that they are accepted at all, whatever they then do. Every autoconf and
699 // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
700 // be the `CC` of a project that has a configure script, whatever else it can do. That
701 // is how this was found: building SQLite's test fixture stopped on it.
702 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
703 // Not a synonym of the pair above, which is what they were treated as until #756. The
704 // library is the expensive answer and gcc makes it the one that has to be asked for,
705 // so this is also what nothing at all means.
706 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
707 // A different question from the pair above, and the one every distribution build of a
708 // shared library answers. `-fPIC` decides how an address is reached, and this decides
709 // whether the optimizer may believe a body it can see, because an exported name is one
710 // the dynamic linker may find another definition of first. On by default, which is
711 // gcc's arrangement and is the honest answer, and off is a promise the build makes and
712 // nothing checks.
713 "-fsemantic-interposition" => opts.interposition = true,
714 "-fno-semantic-interposition" => opts.interposition = false,
715 // Two requests rather than one, and the same table answers both, so what decides is
716 // whether either of them is standing. gcc arranges it the same way: the asynchronous
717 // one is the default here and it implies the other, and a line that asks for a table
718 // and against an asynchronous one gets a table.
719 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
720 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
721 "-funwind-tables" => opts.unwind_tables = true,
722 "-fno-unwind-tables" => opts.unwind_tables = false,
723 // The other direction is a request, not a description, and it is one this compiler
724 // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
725 // option error. Answering it by carrying on would be answering a different question:
726 // the code would still be position independent, which is correct everywhere an
727 // ordinary program runs and is wrong in a kernel, where the flag is written precisely
728 // because there is no loader to fill a global offset table in.
729 "-fno-pic" | "-fno-pie" => {
730 return Err(err(
731 "position dependent code is not supported: an address that may be in another \
732 object is loaded out of the global offset table, and nothing here emits the \
733 absolute form this asks for. Use -no-pie if what you meant was how to link",
734 ));
735 }
736 // A section per function and a section per variable, which is what makes
737 // `--gc-sections` able to drop anything: a linker can leave out a section nothing
738 // reaches and cannot leave out half of one. Both directions are taken, and the off
739 // one is the default rather than a refusal, since a build that writes it is asking
740 // for what happens anyway.
741 "-ffunction-sections" => opts.function_sections = true,
742 "-fno-function-sections" => opts.function_sections = false,
743 "-fdata-sections" => opts.data_sections = true,
744 "-fno-data-sections" => opts.data_sections = false,
745 // Another description of what this compiler does. A file scope declaration with no
746 // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
747 // linker as a common one for it to merge, which is what `-fno-common` asks for and what
748 // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
749 // at all.
750 "-fno-common" => {}
751 // What overflows rather than being undefined. Every one of these takes something away
752 // from the optimizer rather than asking it to do anything, which is why the negative
753 // spellings are the interesting ones and the positive spellings are the default.
754 //
755 // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
756 // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
757 // written here as the pair rather than kept as a third thing to test everywhere.
758 //
759 // `-ftrapv` is the exception and is the one that asks for something. It is the other
760 // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
761 // the other, which makes the last one on the command line the one that counts. That is
762 // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
763 // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
764 // question is left alone by both, because neither has anything to say about it.
765 "-fwrapv" => {
766 opts.wrapping.signed = true;
767 opts.wrapping.trap = false;
768 }
769 "-fno-wrapv" => opts.wrapping.signed = false,
770 "-fwrapv-pointer" => opts.wrapping.pointer = true,
771 "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
772 "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
773 // Which does not clear the checked one, because gcc does not: `-ftrapv
774 // -fstrict-overflow` still emits the calls. It says what is assumed and not what
775 // happens.
776 "-fstrict-overflow" => {
777 opts.wrapping.signed = false;
778 opts.wrapping.pointer = false;
779 }
780 "-ftrapv" => {
781 opts.wrapping.trap = true;
782 opts.wrapping.signed = false;
783 }
784 "-fno-trapv" => opts.wrapping.trap = false,
785 // The two flags that say what a plain `char` is, which is one question with two
786 // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
787 // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
788 // answers and the last one written wins. Nothing is set until one of them is given,
789 // because the target's own ABI is the answer otherwise and it is not the same answer
790 // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
791 "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
792 "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
793 // And the size of an enumeration, which is the other thing in this group that changes
794 // the ABI rather than the code.
795 "-fshort-enums" => opts.short_enums = true,
796 "-fno-short-enums" => opts.short_enums = false,
797 // And the request, which is the one that cannot be granted. It is a real difference and
798 // not a preference: two files each writing `int g;` link under `-fcommon` and are a
799 // duplicate definition without it, which is the whole reason the flag survives.
800 "-fcommon" => {
801 return Err(err(
802 "a tentative definition is written into .bss as its own symbol here, and \
803 nothing emits the common symbol this asks the linker to merge. Give the \
804 variable a definition in one file and declare it extern in the others",
805 ));
806 }
807 // Both directions of this one are recorded, and what they decide is whether lowering
808 // names the type each access goes through. Turning it off is the front end leaving the
809 // name off rather than a pass being told to ignore one it can see, which is one
810 // condition in one place, and it is the reading that survives link time optimization:
811 // a unit built with the flag off keeps its own answer when its bodies end up in a
812 // module beside bodies that were not.
813 //
814 // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
815 // and is tested, and no pass at any level asks the alias analysis anything today, so
816 // no program compiles differently for having passed this. The flag is wired anyway,
817 // because the change that makes a pass ask is not the change anybody will remember to
818 // wire it in, and a flag that is taken and dropped once the names mean something is
819 // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
820 // words.
821 "-fstrict-aliasing" => opts.strict_aliasing = true,
822 "-fno-strict-aliasing" => opts.strict_aliasing = false,
823 // The same shape of answer for the same reason, and the flag the kernel writes beside
824 // the one above it.
825 //
826 // Nothing here concludes that a pointer is not null from the fact that it was
827 // dereferenced. There is no such conclusion to draw from, because no pass records one:
828 // a load says where it read and nothing else, and a comparison against null is an
829 // ordinary comparison of two values the optimizer has no fact about. So a function
830 // that reads through a pointer and then tests it keeps the test, which is what the
831 // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
832 // to be asked for because it draws the conclusion by default.
833 //
834 // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
835 // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
836 // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
837 "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
838 // The floating point group, which goes the same way and for the same reason, and which
839 // is worth writing out because the reason is easy to get backwards.
840 //
841 // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
842 // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
843 // changed and that an exception raised by an operation may be looked at, so an
844 // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
845 // whose exception the program does not get. Nothing here folds any floating point
846 // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
847 // that runs, at every level. So both of those describe what already happens.
848 //
849 // The permissive ones are the other half, and they are licences rather than requests
850 // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
851 // `-fno-trapping-math` says nothing looks at the exceptions, which together are
852 // permission to fold. Not folding is the conservative side of that permission and is
853 // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
854 // speed and not correctness, which is the test section 4.1 puts a licence through.
855 "-frounding-math" | "-fno-rounding-math" => {}
856 // `-fno-trapping-math` is the one of the four that is kept, because there is one
857 // conversion this compiler does not fold and gcc folds under it, and the two answers
858 // differ. Converting a constant floating value to an integer type it does not fit in
859 // is undefined behaviour rather than a value: left to the hardware it is one
860 // instruction and the answer is the integer indefinite value, and folded it is the
861 // nearest end of the integer's range. Both compilers leave it to the instruction by
862 // default and gcc folds it under this flag, so a program built with it and compiled
863 // without it gets a different number rather than a slower one. `-ftrapping-math` is
864 // gcc's default, so a build spelling it out is asking for what it already has.
865 "-ftrapping-math" => opts.trapping_math = true,
866 "-fno-trapping-math" => opts.trapping_math = false,
867 // About temporary files rather than about code. There is nothing between the phases of
868 // one compilation here to write to a file in the first place.
869 "-pipe" => {}
870 // Nothing here writes colour, so all of these are the same answer, and it is the answer
871 // that costs nothing: the diagnostics come out plain either way and no build depends on
872 // an escape sequence being there. Taken rather than refused because cmake writes
873 // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
874 // makes this the second most common flag after `-fPIC` to stop a build over a question
875 // about how the text looks.
876 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
877 _ if arg.starts_with("-fdiagnostics-color=") => {}
878 // The link flags. None of them changes the compilation, which is why they are
879 // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
880 // error: it is a thing said to a linker that is not going to run.
881 "-static" => link.is_static = true,
882 "-shared" => link.shared = true,
883 "-pie" => link.pie = Some(true),
884 "-no-pie" | "-nopie" => link.pie = Some(false),
885 "-nostdlib" => link.no_stdlib = true,
886 "-nostartfiles" => link.no_startfiles = true,
887 "-nodefaultlibs" => link.no_defaultlibs = true,
888 "-fno-builtins-lib" => link.no_builtins_lib = true,
889 "-fbuiltins-lib" => link.no_builtins_lib = false,
890 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
891 "-s" => link.strip = true,
892 "-Xlinker" => {
893 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
894 i += 1;
895 link.passthrough.push(next.clone());
896 }
897 _ if arg.starts_with("-Wl,") => {
898 // Commas separate arguments rather than being part of one, which is what makes
899 // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
900 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
901 }
902 _ if arg.starts_with("-fuse-ld=") => {
903 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
904 }
905 _ if arg.starts_with("-l") && arg.len() > 2 => {
906 inputs.push(Input::library(&arg[2..]));
907 }
908 "-l" => {
909 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
910 i += 1;
911 inputs.push(Input::library(next));
912 }
913 _ if arg.starts_with("-L") => {
914 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
915 }
916 _ if arg.starts_with("-B") => {
917 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
918 }
919 _ if arg.starts_with("-j") => {
920 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
921 }
922 _ if arg.starts_with("--sysroot=") => {
923 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
924 }
925 _ if arg.starts_with("--target=") => {
926 let t = &arg["--target=".len()..];
927 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
928 // The same string again, as the model that has room for a libc version. A spelling
929 // the three field parser took and this one does not is not an error, because the
930 // one that decides what is compiled has already accepted it and the only thing
931 // lost is a version nobody asked for.
932 pinned = t.parse().ok();
933 }
934 _ if arg.starts_with("--emit=") => {
935 let k = &arg["--emit=".len()..];
936 opts.emit = k
937 .parse()
938 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
939 }
940 // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
941 // to write. `-Og` is GCC's level for a build somebody is going to step through, and
942 // it is `-O1` with the transformations that move code around left out; this compiler
943 // has no such level yet, so it is the nearest one and `--print-pipeline` says what
944 // that came to rather than the flag pretending otherwise.
945 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
946 // The union of `-O3` and `-ffast-math`, and the second half of that changes what
947 // floating point arithmetic means. Refused rather than taken as `-O3`, because a
948 // build that asks for fast math and is quietly given ordinary arithmetic gets a
949 // slower program than it asked for and a build that is given fast math it did not
950 // ask for gets a wrong one.
951 "-Ofast" => {
952 return Err(err(
953 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
954 spec/04-driver-and-cli.md section 4.6",
955 ));
956 }
957 _ if arg.starts_with("-O") => {
958 opts.opt_level = arg[2..]
959 .parse()
960 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
961 }
962 // How far a multiply and an addition may be fused into one rounding. Before the
963 // optimizer's `-f` family below for the reason the ones under it are, and kept rather
964 // than dropped because it is the one flag in its group this compiler could act on: it
965 // rides into the IR as an attribute on each function with a body, so the day the code
966 // generator forms an `fma` it already knows which functions were given permission.
967 // Nothing forms one today, under any value of this and under any `-march=`.
968 _ if arg.starts_with("-ffp-contract=") => {
969 let how = &arg["-ffp-contract=".len()..];
970 opts.fp_contract = how.parse().map_err(|()| {
971 err(format!("`{how}` is not a contraction, which is fast, on or off"))
972 })?;
973 }
974 // How much of an expression may be computed wider than it was written. The values are
975 // gcc's and so is the refusal of anything else, and none of the three changes anything
976 // here: an operation is computed in the type C says it is on every target this compiler
977 // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
978 // happens. `fast` and `16` are permission to be wider, which is a licence this takes
979 // and does not use, the same way the two above are. The flag is worth taking because
980 // glibc's headers and a good deal of configure output write it, and because the answer
981 // it asks about is one this compiler can state rather than guess at: there is no x87
982 // target here, which is the machine the whole question was invented for.
983 _ if arg.starts_with("-fexcess-precision=") => {
984 let how = &arg["-fexcess-precision=".len()..];
985 if !matches!(how, "16" | "fast" | "standard") {
986 return Err(err(format!(
987 "`{how}` is not an excess precision, which is 16, fast or standard"
988 )));
989 }
990 }
991 // Which front of a path is rewritten before it reaches the output, which is how a
992 // build gets the same bytes out of two different directories. The four spellings are
993 // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
994 // once. Only the macro list does anything today, because `__FILE__` is the only place
995 // a path reaches the output: there is no DWARF and no profile data yet, so the other
996 // two are recorded for the work that will read them. The argument splits at the last
997 // `=` rather than the first, which is gcc's rule and is what lets a directory with an
998 // `=` in its name be the old half.
999 _ if arg.starts_with("-fmacro-prefix-map=") => {
1000 let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1001 opts.prefix_map.macros.push(old, new);
1002 }
1003 _ if arg.starts_with("-fdebug-prefix-map=") => {
1004 let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1005 opts.prefix_map.debug.push(old, new);
1006 }
1007 _ if arg.starts_with("-fprofile-prefix-map=") => {
1008 let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1009 opts.prefix_map.profile.push(old, new);
1010 }
1011 _ if arg.starts_with("-ffile-prefix-map=") => {
1012 let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1013 opts.prefix_map.macros.push(old, new);
1014 opts.prefix_map.debug.push(old, new);
1015 opts.prefix_map.profile.push(old, new);
1016 }
1017 // A whole optimization rather than a flag, and the family is taken rather than
1018 // refused because of what ignoring it does. There is none of it here yet, so a build
1019 // that asks for it gets a program that is correct and slower than it could have been,
1020 // which is what section 4.1 means by a hint about speed and what every compilation at
1021 // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1022 // holds the bytecode and no machine code at all, and every object here holds the code,
1023 // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1024 // to this compiler gets objects that are more usable than the ones it asked for rather
1025 // than different ones. Every value is still checked against gcc's, because somebody
1026 // who wrote `-flto=thin` meant clang and had better hear about it here.
1027 "-flto" => opts.lto.requested = true,
1028 "-fno-lto" => opts.lto.requested = false,
1029 _ if arg.starts_with("-flto=") => {
1030 let how = &arg["-flto=".len()..];
1031 opts.lto.jobs = how.parse().map_err(|()| {
1032 err(format!(
1033 "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1034 count above zero"
1035 ))
1036 })?;
1037 opts.lto.requested = true;
1038 }
1039 _ if arg.starts_with("-flto-partition=") => {
1040 let how = &arg["-flto-partition=".len()..];
1041 opts.lto.partition = how.parse().map_err(|()| {
1042 err(format!(
1043 "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1044 or none"
1045 ))
1046 })?;
1047 }
1048 _ if arg.starts_with("-flto-compression-level=") => {
1049 let how = &arg["-flto-compression-level=".len()..];
1050 let level =
1051 how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1052 err(format!("`{how}` is not a compression level, 0 to 19"))
1053 })?;
1054 opts.lto.compression = Some(level);
1055 }
1056 // Whether the object keeps its machine code as well as the bytecode. It always does
1057 // here, so the first of these describes what happens and the second asks for an object
1058 // with less in it, which is a smaller file and not a different program, so both are
1059 // taken.
1060 "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1061 // Whether the linker is handed a plugin that does the link time work. The design in
1062 // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1063 // plugin into anybody, so neither answer is a question it has to hold.
1064 "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1065 // Reading a profile back. Taken for the reason the family above it is: nothing here
1066 // reads one, so a build that asks gets the program it would have got anyway, and gcc
1067 // itself produces a byte for byte identical object from `-fprofile-use` when there are
1068 // no counts beside the file. The path is recorded for the pass that will read it. The
1069 // warning gcc prints when it looked and found nothing is deliberately not copied,
1070 // because nothing here looks, and a warning about a file that was never opened would
1071 // fire on the builds that have a perfectly good profile as well as on the ones that
1072 // do not.
1073 "-fprofile-use" => opts.profile_data.requested = true,
1074 "-fno-profile-use" => opts.profile_data.requested = false,
1075 _ if arg.starts_with("-fprofile-use=") => {
1076 opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1077 opts.profile_data.requested = true;
1078 }
1079 _ if arg.starts_with("-fprofile-dir=") => {
1080 opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1081 }
1082 "-fprofile-abs-path" => opts.profile_data.absolute = true,
1083 "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1084 "-fprofile-correction" => opts.profile_data.correction = true,
1085 "-fno-profile-correction" => opts.profile_data.correction = false,
1086 "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1087 "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1088 // Writing the counts rather than reading them, which is refused rather than taken and
1089 // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1090 // file a build declared as an output never appears: the instrumented program writes a
1091 // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1092 // two stage build that got neither would go on to optimize against no counts at all
1093 // and report coverage of nothing, with nothing along the way saying so. The objects
1094 // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1095 // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1096 // this is a flag that changes the output rather than a hint about speed.
1097 "-fprofile-arcs"
1098 | "--coverage"
1099 | "-fcondition-coverage"
1100 | "-fpath-coverage"
1101 | "-fprofile-generate" => {
1102 return Err(err(format!(
1103 "{arg}: this compiler does not instrument for profiling, and a build that \
1104 expects the counts a run of the instrumented program writes would optimize \
1105 against nothing on its second pass, see spec/04-driver-and-cli.md"
1106 )));
1107 }
1108 _ if arg.starts_with("-fprofile-generate=") => {
1109 return Err(err(format!(
1110 "{arg}: this compiler does not instrument for profiling, and a build that \
1111 expects the counts a run of the instrumented program writes would optimize \
1112 against nothing on its second pass, see spec/04-driver-and-cli.md"
1113 )));
1114 }
1115 "-ftest-coverage" => {
1116 return Err(err(format!(
1117 "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1118 that expects one would wait for a file that never arrives, see \
1119 spec/04-driver-and-cli.md"
1120 )));
1121 }
1122 // The rest of the family describes instrumentation that is refused above, so what is
1123 // left to do with them is check them and drop them. They are checked because a
1124 // misspelling in a distribution's flags is worth finding here rather than on the day
1125 // the instrumentation lands, and dropped because there is nothing for an answer about
1126 // how a counter is written to be an answer about.
1127 _ if arg.starts_with("-fprofile-update=") => {
1128 let how = &arg["-fprofile-update=".len()..];
1129 if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1130 return Err(err(format!(
1131 "`{how}` is not a profile update method, which is single, atomic or \
1132 prefer-atomic"
1133 )));
1134 }
1135 }
1136 _ if arg.starts_with("-fprofile-reproducible=") => {
1137 let how = &arg["-fprofile-reproducible=".len()..];
1138 if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1139 return Err(err(format!(
1140 "`{how}` is not a profile reproducibility method, which is serial, \
1141 parallel-runs or multithreaded"
1142 )));
1143 }
1144 }
1145 "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1146 "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1147 _ if arg.starts_with("-fprofile-filter-files=")
1148 || arg.starts_with("-fprofile-exclude-files=")
1149 || arg.starts_with("-fprofile-note=") => {}
1150 // What every name gets when nothing in the source said, which the attribute in the
1151 // source overrides rather than the other way round. Before the optimizer's `-f`
1152 // family below for the reason the tier below it is.
1153 _ if arg.starts_with("-fvisibility=") => {
1154 let seen = &arg["-fvisibility=".len()..];
1155 opts.visibility = seen.parse().map_err(|()| {
1156 err(format!(
1157 "`{seen}` is not a visibility, which is default, hidden, internal or \
1158 protected"
1159 ))
1160 })?;
1161 }
1162 // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1163 // family below for the reason the two above it are, and last of the three so that the
1164 // bare spelling and the negative one are matched exactly rather than by this.
1165 _ if arg.starts_with("-fcf-protection=") => {
1166 let edges = &arg["-fcf-protection=".len()..];
1167 opts.control = edges.parse().map_err(|()| {
1168 err(format!(
1169 "`{edges}` is not a control flow protection, which is full, branch, \
1170 return, none or check"
1171 ))
1172 })?;
1173 }
1174 // How much room every function opens with for something to be written over later.
1175 // Before the optimizer's `-f` family below for the reason the ones above it are.
1176 _ if arg.starts_with("-fpatchable-function-entry=") => {
1177 let room = &arg["-fpatchable-function-entry=".len()..];
1178 opts.patchable = room.parse().map_err(|()| {
1179 err(format!(
1180 "`{room}` is not an amount of room to reserve, which is a number of bytes and then, after a comma, how many of them go in front of the function's own label"
1181 ))
1182 })?;
1183 }
1184 // The memory safety monitor, from section 15.4 of
1185 // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1186 // because a pass that took the name `safety=detect` would otherwise be handed the
1187 // flag, and the tier is not a pass.
1188 _ if arg.starts_with("-fsafety=") => {
1189 let tier = &arg["-fsafety=".len()..];
1190 opts.safety = tier.parse().map_err(|()| {
1191 err(format!(
1192 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1193 ))
1194 })?;
1195 }
1196 // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1197 // than folded into the tier because it is a departure somebody who has read that
1198 // section makes, and the two defaults it describes are a property of what is being
1199 // built rather than of how much checking is wanted.
1200 _ if arg.starts_with("-fsafety-init=") => {
1201 let mode = &arg["-fsafety-init=".len()..];
1202 opts.padding = mode.parse().map_err(|()| {
1203 err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1204 })?;
1205 }
1206 // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1207 // strict form of that section needs a member id the front end does not name yet and
1208 // accepting the spelling for it would be accepting a promise this build cannot keep.
1209 // Before `-fno-` is looked at below, for the reason the tier is.
1210 "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1211 "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1212 _ if arg.starts_with("-fsafety-subobject=") => {
1213 let form = &arg["-fsafety-subobject=".len()..];
1214 return Err(err(format!(
1215 "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1216 the strict form of section 9.4 is tamnd/rucc#967"
1217 )));
1218 }
1219 // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1220 // the one above has none: there is one form of this check and a spelling that suggested
1221 // otherwise would be promising something. Before `-fno-` is looked at below, the same
1222 // way.
1223 "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1224 "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1225 _ if arg.starts_with("-fsafety-restrict=") => {
1226 let form = &arg["-fsafety-restrict=".len()..];
1227 return Err(err(format!(
1228 "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1229 )));
1230 }
1231 // Section 9.5's races, which take a value because the section gives them three modes
1232 // and the difference between two of them is which classes get reported rather than how
1233 // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1234 // reason the two above spell theirs out.
1235 _ if arg.starts_with("-fsafety-races=") => {
1236 let mode = &arg["-fsafety-races=".len()..];
1237 opts.races = mode.parse().map_err(|()| {
1238 err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1239 })?;
1240 }
1241 "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1242 // The sanitizers of document 12, which are checks at run time rather than a way of
1243 // generating the same program. Each name is held to gcc 16's list, and what is still
1244 // asked for by the end of the line is answered after the loop, so that a command line
1245 // which turns one on and then off again is a command line that asked for nothing.
1246 //
1247 // Before the optimizer's `-f` family below, for the reason the tier above it is.
1248 _ if arg.starts_with("-fsanitize=") => {
1249 for one in arg["-fsanitize=".len()..].split(',') {
1250 if one == "all" {
1251 // gcc takes `all` only in the negative, because turning every check on at
1252 // once includes checks that contradict each other.
1253 return Err(err(
1254 "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1255 ));
1256 }
1257 if !SANITIZERS.contains(&one) {
1258 return Err(err(format!(
1259 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1260 )));
1261 }
1262 if !sanitizers.contains(&one) {
1263 sanitizers.push(one);
1264 }
1265 }
1266 }
1267 _ if arg.starts_with("-fno-sanitize=") => {
1268 for one in arg["-fno-sanitize=".len()..].split(',') {
1269 if one == "all" {
1270 sanitizers.clear();
1271 continue;
1272 }
1273 if !SANITIZERS.contains(&one) {
1274 return Err(err(format!(
1275 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1276 )));
1277 }
1278 sanitizers.retain(|asked| *asked != one);
1279 }
1280 }
1281 // What a check does when it fires, and where the records about the checked objects go.
1282 // Each of them is an answer about the sanitizers refused after the loop, so there is
1283 // nothing left for them to change here. The names are still held to the list, because
1284 // a misspelling in a build's flags is worth finding when the compiler reads it.
1285 _ if arg.starts_with("-fsanitize-recover=")
1286 || arg.starts_with("-fno-sanitize-recover=")
1287 || arg.starts_with("-fsanitize-trap=")
1288 || arg.starts_with("-fno-sanitize-trap=") =>
1289 {
1290 // The guard above matched on a spelling that has an `=` in it, so the tail is
1291 // whatever follows the first one.
1292 let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1293 for one in how.split(',') {
1294 if one != "all" && !SANITIZERS.contains(&one) {
1295 return Err(err(format!(
1296 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1297 )));
1298 }
1299 }
1300 }
1301 "-fsanitize-undefined-trap-on-error"
1302 | "-fsanitize-address-use-after-scope"
1303 | "-fno-sanitize-address-use-after-scope" => {}
1304 _ if arg.starts_with("-fsanitize-sections=") => {}
1305 // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1306 // keeping. Refused rather than dropped, because a fuzzer whose calls into
1307 // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1308 // and there is no point in the campaign where that announces itself.
1309 _ if arg.starts_with("-fsanitize-coverage=") => {
1310 let how = &arg["-fsanitize-coverage=".len()..];
1311 for one in how.split(',') {
1312 if !matches!(one, "trace-pc" | "trace-cmp") {
1313 return Err(err(format!(
1314 "`{one}` is not a coverage instrumentation, which is trace-pc or \
1315 trace-cmp"
1316 )));
1317 }
1318 }
1319 return Err(err(format!(
1320 "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1321 with it would run without any feedback at all, see \
1322 spec/04-driver-and-cli.md section 4.7"
1323 )));
1324 }
1325 // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1326 // after every `-f` the rest of the compiler answers to, so a pass can never take a
1327 // name that already means something else on the command line.
1328 _ if arg.starts_with("-fpass-fuel=") => {
1329 let (name, count) = arg["-fpass-fuel=".len()..]
1330 .split_once('=')
1331 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1332 if rucc_opt::pass::find(name).is_none() {
1333 return Err(err(format!(
1334 "`{name}` is not a pass this compiler has, see --print-pipeline"
1335 )));
1336 }
1337 let count: u32 = count
1338 .parse()
1339 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1340 opts.pass_fuel.push((name.to_owned(), count));
1341 }
1342 _ if arg.starts_with("-fpass-fuel-global=") => {
1343 let count = &arg["-fpass-fuel-global=".len()..];
1344 let count: u32 = count
1345 .parse()
1346 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1347 opts.pass_fuel_global = Some(count);
1348 }
1349 // Everything from `-fopt-info` to the end of the argument, which is optional
1350 // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1351 // where the remarks are printed, because by then the compilation somebody wanted
1352 // to hear about is over.
1353 _ if arg == "-fopt-info"
1354 || arg.starts_with("-fopt-info=")
1355 || arg.starts_with("-fopt-info-") =>
1356 {
1357 let rest = &arg["-fopt-info".len()..];
1358 let (kinds, file) = match rest.split_once('=') {
1359 Some((kinds, file)) => (kinds, Some(file)),
1360 None => (rest, None),
1361 };
1362 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1363 rucc_opt::Wants::none().add(kinds).map_err(err)?;
1364 opts.opt_info.push(kinds.to_owned());
1365 if let Some(file) = file {
1366 if file.is_empty() {
1367 return Err(err("-fopt-info= was given no file to write to"));
1368 }
1369 opts.opt_info_file = Some(file.to_owned());
1370 }
1371 }
1372 _ if arg.starts_with("-fdump-ir=") => {
1373 // Checked here rather than where the dumps are taken, because the compilation
1374 // that would have been dumped is over by then.
1375 let spec = &arg["-fdump-ir=".len()..];
1376 rucc_opt::Dumps::default().add(spec).map_err(err)?;
1377 opts.dump_ir.push(spec.to_owned());
1378 }
1379 // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1380 // otherwise take the flag away from the gate. Checked here rather than where the
1381 // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1382 // name that quietly gated nothing looks exactly like a pass that is not the guilty
1383 // one, and a bisection would carry on past the thing it was looking for.
1384 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1385 let on = arg.starts_with("-fenable-");
1386 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1387 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1388 opts.pass_gates.push((on, spec.to_owned()));
1389 }
1390 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1391 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1392 }
1393 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1394 opts.passes.push((arg["-f".len()..].to_owned(), true));
1395 }
1396 // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1397 // program reduced from a miscompilation usually names the pass that miscompiled it on
1398 // its `dg-options` line, and they arrive from hand written build files for the same
1399 // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1400 // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1401 // for a compiler that does not exist here, and the program it is attached to is a
1402 // correctness test that passes either way. Turning on a pass we do not have costs
1403 // speed, turning off a pass we do not have costs nothing, and neither changes what the
1404 // program computes.
1405 //
1406 // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1407 // compiler has rather than landing here, and the day one of these names becomes a pass
1408 // here it stops being taken and dropped without anybody editing this list.
1409 //
1410 // Two of them are prefixes rather than names, which is the one place this file takes a
1411 // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1412 // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1413 // nothing else, and there is no member of either that changes the meaning of a program
1414 // that was already correct. The rest are written out one at a time, because they live
1415 // in the flat `-f` namespace where the neighbours do change meanings.
1416 _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1417 _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1418 "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1419 "-fmodulo-sched" | "-fno-modulo-sched" => {}
1420 "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1421 _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1422 }
1423 "-fearly-inlining" | "-fno-early-inlining" => {}
1424 "-finline"
1425 | "-fno-inline"
1426 | "-finline-functions"
1427 | "-fno-inline-functions"
1428 | "-finline-small-functions"
1429 | "-fno-inline-small-functions"
1430 | "-finline-functions-called-once"
1431 | "-fno-inline-functions-called-once" => {}
1432 "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1433 "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1434 // The charset flags are not in that pile, because an encoding is a statement about
1435 // what the bytes of the source mean rather than about how fast the output is. The
1436 // preprocessor reads UTF-8 and has no converter, so the one name that describes what
1437 // already happens is taken and every other name is refused. Spelled without regard to
1438 // case and with both of the spellings iconv answers to, since a build writes whichever
1439 // one its author typed.
1440 _ if arg.starts_with("-finput-charset=") => {
1441 let name = &arg["-finput-charset=".len()..];
1442 if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
1443 return Err(err(format!(
1444 "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
1445 converter, so a file in another encoding would be read as though it were \
1446 UTF-8 rather than converted",
1447 )));
1448 }
1449 }
1450 // The three that come in on the same `dg-options` lines and are the other half of
1451 // section 4.1's rule, because each of them changes what the program does and not how
1452 // fast it does it. The negative form of each is what this compiler does anyway, so it
1453 // is taken and dropped, which is the shape `-fnested-functions` has above.
1454 "-ffast-math" => {
1455 return Err(err(
1456 "-ffast-math is a licence to answer a floating point arithmetic differently \
1457 from the way the source wrote it, and it is not one flag: it defines \
1458 __FAST_MATH__, which a library header reads, and gcc links a startup file \
1459 that puts the hardware in flush to zero mode for the whole process. Taking it \
1460 and dropping it would change what other objects in the same program answer. \
1461 -ffp-contract= and -fexcess-precision= are the parts of it this compiler has",
1462 ));
1463 }
1464 "-fno-fast-math" => {}
1465 "-fnon-call-exceptions" => {
1466 return Err(err(
1467 "-fnon-call-exceptions is a promise that an instruction which is not a call \
1468 can raise an exception the unwinder finds a handler for, and nothing here \
1469 produces a landing pad for a trapping instruction. A program built without it \
1470 would unwind past the handler it wrote",
1471 ));
1472 }
1473 "-fno-non-call-exceptions" => {}
1474 "-finstrument-functions" => {
1475 return Err(err(
1476 "-finstrument-functions calls __cyg_profile_func_enter on entry to every \
1477 function and __cyg_profile_func_exit on the way out, and nothing here emits \
1478 either call. A program that asks for them usually counts them, so taking the \
1479 flag and dropping it would turn a program that fails loudly into one that \
1480 fails quietly",
1481 ));
1482 }
1483 "-fno-instrument-functions" => {}
1484 // The unstable options, spelled the way rustc spells them and carrying the same
1485 // promise, which is none: one of these may change or go away in any release. They are
1486 // measurements and debugging aids rather than things a build asks for, which is why
1487 // none of them is in the usage text and all of them are in section 4.11 of
1488 // `spec/04-driver-and-cli.md`.
1489 "-Zverify-each" => opts.verify_each = true,
1490 _ if arg.starts_with("-Zrule-coverage=") => {
1491 let file = &arg["-Zrule-coverage=".len()..];
1492 if file.is_empty() {
1493 return Err(err("-Zrule-coverage= needs a file to write to"));
1494 }
1495 opts.rule_coverage = Some(file.to_owned());
1496 }
1497 _ if arg.starts_with("-Zregister-pressure=") => {
1498 let file = &arg["-Zregister-pressure=".len()..];
1499 if file.is_empty() {
1500 return Err(err("-Zregister-pressure= needs a file to write to"));
1501 }
1502 opts.register_pressure = Some(file.to_owned());
1503 }
1504 _ if arg.starts_with("-Z") => {
1505 return Err(err(format!(
1506 "`{arg}` is not an unstable option this compiler has, see \
1507 spec/04-driver-and-cli.md section 4.11 for the ones it does"
1508 )));
1509 }
1510 // The word size, which is a statement about the target and is taken as one. A build
1511 // that says the size the target already has is saying nothing, and one that says the
1512 // other size is asking for a target this compiler does not have, which it is told
1513 // rather than being given the wrong one.
1514 "-m64" | "-m32" | "-mx32" => {
1515 let want: u32 = match arg {
1516 "-m64" => 64,
1517 _ => 32,
1518 };
1519 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
1520 if have != want {
1521 return Err(err(format!(
1522 "{arg} asks for a {want} bit target and {} is {have} bit, use \
1523 --target= to name the one you mean",
1524 opts.target
1525 )));
1526 }
1527 }
1528 // Which processor in the family to generate for. This compiler emits the base
1529 // instruction set of the architecture and nothing above it, so a program built with
1530 // any of these runs on the machine that was named; it is a program that could have
1531 // been faster rather than a program that is wrong, which is what makes these safe to
1532 // take and ignore where a flag that changed the meaning of the code would not be.
1533 _ if arg.starts_with("-march=")
1534 || arg.starts_with("-mtune=")
1535 || arg.starts_with("-mcpu=") => {}
1536 // The calling convention, which is not safe to ignore. Taken when it names the one
1537 // the target already uses and refused otherwise.
1538 _ if arg.starts_with("-mabi=") => {
1539 let want = &arg["-mabi=".len()..];
1540 let have = match opts.target.arch {
1541 rucc_target::Arch::X86_64 => "sysv",
1542 rucc_target::Arch::Aarch64 => "lp64",
1543 rucc_target::Arch::Riscv64 => "lp64d",
1544 };
1545 if want != have {
1546 return Err(err(format!(
1547 "{arg}: {} uses the {have} convention and this compiler has no other",
1548 opts.target
1549 )));
1550 }
1551 }
1552 // How far apart the pieces of the program may be. The small model is what we emit and
1553 // it is every hosted program's default; the kernel model is a different one and a
1554 // build that asks for it and does not get it links and then does not run.
1555 "-mcmodel=small" => {}
1556 _ if arg.starts_with("-mcmodel=") => {
1557 return Err(err(format!(
1558 "{arg}: this compiler emits the small code model and no other, see \
1559 spec/12-targets.md"
1560 )));
1561 }
1562 // GCC's own scripting language for how the driver builds a command line.
1563 // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
1564 // build reaching for it is told which flags do the same job.
1565 _ if arg.starts_with("-specs=") => {
1566 return Err(err(
1567 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
1568 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
1569 section 4.4",
1570 ));
1571 }
1572 // Arguments meant for a separate assembler or preprocessor, which this compiler does
1573 // not have: both are inside it and neither reads a command line. Refused rather than
1574 // dropped, because every one of these says something about the output and a build
1575 // that asked for `-Wa,--noexecstack` and was silently given an executable stack got
1576 // the opposite of what it asked for.
1577 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
1578 return Err(err(format!(
1579 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
1580 are inside this compiler rather than programs it runs"
1581 )));
1582 }
1583 "-Xassembler" | "-Xpreprocessor" => {
1584 return Err(err(format!(
1585 "{arg} hands an argument to a separate assembler or preprocessor, and both \
1586 are inside this compiler rather than programs it runs"
1587 )));
1588 }
1589 // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
1590 // this one as a rule about build systems rather than about warnings: autoconf finds
1591 // out whether a warning flag exists by passing it and looking at the exit status, so
1592 // a compiler that refuses one it has not heard of fails a configure script written
1593 // for a GCC newer than itself. The names are not checked against a list because this
1594 // compiler has no warning groups for a list to be of, which #485 is about.
1595 _ if arg.starts_with("-W") => {}
1596 // Flags that name something this compiler does not do and would not do differently
1597 // if it did. `-fno-ident` is about a comment in the output that we do not write
1598 // either way, and the others are about a way of ordering the compilation that has
1599 // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
1600 // and for adding to it to be deliberate, which is why it is written out here.
1601 "-fno-ident"
1602 | "-fident"
1603 | "-funit-at-a-time"
1604 | "-fno-unit-at-a-time"
1605 | "-shared-libgcc"
1606 | "-static-libgcc" => {}
1607 _ if arg.starts_with('-') && arg.len() > 1 => {
1608 // Silently ignoring an unknown flag is how a build ends up not doing what
1609 // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
1610 // for the flags that change code generation, and the safe default until the
1611 // flag table is populated is to reject everything we do not know.
1612 return Err(err(format!("unknown option `{arg}`")));
1613 }
1614 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
1615 }
1616 }
1617
1618 // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
1619 // order: a directory the user names outranks the compiler's own, and the compiler's own
1620 // outranks the library's. It is pushed after the loop rather than before it because
1621 // `SearchPath` appends within a group and the position is what the order is.
1622 // The same directory the headers were looked for under, because a sysroot is a statement
1623 // about a whole installation and not about half of one.
1624 // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
1625 // command line that turns a check on and off again has asked for nothing. What is left is
1626 // refused rather than dropped, and it is the one place in this parser where the reason is not
1627 // that the output would differ. A sanitizer is a promise that the program is watched while it
1628 // runs, so a build that asks for one and is quietly given a program with no checks in it does
1629 // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
1630 // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
1631 // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
1632 // options.
1633 if let Some(first) = sanitizers.first() {
1634 return Err(err(format!(
1635 "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
1636 asked for one and got none would run its tests unchecked, see \
1637 spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
1638 compiler does have"
1639 )));
1640 }
1641 link.sysroot = sysroot.clone();
1642 // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
1643 // inside the link line, because a link line that read the environment could only be tested on a
1644 // machine whose environment said the right thing, and the link line is the last thing that
1645 // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
1646 link.cache = Some(cache::dir());
1647 // And the ten field spelling of the target, because the release on it decides two things the
1648 // three field one cannot say: whether a target that is this architecture is still a cross
1649 // compile, and which directory under the cache it is against. After the loop because the last
1650 // `--target=` on the command line is the one that counts.
1651 link.pinned = pinned;
1652 // After the loop rather than where `-pthread` was read, so that it lands after the objects
1653 // that refer to it. A static link takes the definitions it needs from a library when it
1654 // reaches it and not afterwards, so a library before the objects is a library that answers
1655 // nothing.
1656 if threads {
1657 inputs.push(Input::library("pthread"));
1658 }
1659 if let Some(query) = query {
1660 return Ok(Action::Print(answer(&query, &opts, &link)?));
1661 }
1662 // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
1663 // else the command line asked for. Read here rather than where the flag was, because a `-c`
1664 // written after it has to lose and the loop cannot know that until it has ended. The output
1665 // file is where the rule goes rather than where an object would have gone, and the last
1666 // phase being the preprocessor is what makes that true without a second rule for it.
1667 if opts.deps.instead_of_compiling {
1668 opts.emit = EmitKind::Preprocessed;
1669 }
1670 if !nostdinc {
1671 opts.search.push_system(runtime::DIR);
1672 // And the library's after ours, which is the other half of the same order. They go on
1673 // here rather than at the point `--target=` or `--sysroot=` was read because either
1674 // one changes the answer and the last word on both is the end of the loop.
1675 //
1676 // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
1677 // that the headers and the libraries come from the same place. A target that is this
1678 // machine reads this machine's headers, and a target that is not reads the ones in the
1679 // sysroot for it rather than the ones next door.
1680 let cross = link::cross_sysroot(opts.target, &link);
1681 let kernel = link::cross_kernel(opts.target, &link);
1682 // And the version of those headers, which only the bundled tree has an answer for. A host
1683 // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
1684 // and a second definition with a different value is a warning on every file, so the
1685 // condition is the same one that chose the directories.
1686 if cross.is_some() {
1687 let target = pinned.unwrap_or_else(|| opts.target.tuple());
1688 opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
1689 err(format!(
1690 "{skew}; pin a release the tree has, or name a tree that has that one \
1691 with --sysroot"
1692 ))
1693 })?;
1694 }
1695 for dir in
1696 library::header_dirs(opts.target, sysroot.as_deref(), cross.as_ref(), kernel.as_ref())
1697 {
1698 opts.search.push_system(dir);
1699 }
1700 }
1701 // Once, here, rather than as each directory is pushed. A `-I` that names a system
1702 // directory has to lose to the system entry and the system entry is added last, so the
1703 // question cannot be answered until the whole path is known.
1704 opts.search.remove_duplicates();
1705
1706 // The target has to be resolved before the configuration is printed, so this check comes
1707 // after the loop rather than at the point `--print-config` was seen.
1708 if print_config {
1709 return Ok(Action::PrintConfig(Box::new(opts)));
1710 }
1711 if print_pipeline {
1712 return Ok(Action::PrintPipeline(Box::new(opts)));
1713 }
1714 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
1715 if print_plan {
1716 return Ok(Action::PrintPlan {
1717 opts: Box::new(opts),
1718 plan: Box::new(plan),
1719 link: Box::new(link),
1720 });
1721 }
1722 Ok(Action::Compile {
1723 opts: Box::new(opts),
1724 plan: Box::new(plan),
1725 link: Box::new(link),
1726 jobs,
1727 verbose,
1728 })
1729}
1730
1731/// What one of the `-dump` and `-print` flags prints.
1732///
1733/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
1734/// which is what makes the answer safe to paste into a link line whether or not the file is
1735/// there, and this does the same.
1736fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
1737 let found = |name: &str| {
1738 link::find_in_search(link, opts.target, name)
1739 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
1740 };
1741 Ok(match query {
1742 Query::Machine => opts.target.to_string(),
1743 Query::Version => VERSION.to_owned(),
1744 Query::Multiarch => link::multiarch(opts.target),
1745 // The three lines GCC prints, in its order and with its punctuation, because what reads
1746 // them is a script written against that shape. There is no installation directory to
1747 // report: this compiler is one binary that works wherever it is copied, and the headers
1748 // it ships are inside it, so `install` is where the binary is and nothing is under it.
1749 Query::SearchDirs => {
1750 let here = std::env::current_exe()
1751 .ok()
1752 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1753 .unwrap_or_default();
1754 let list = |dirs: &[PathBuf]| {
1755 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1756 };
1757 let libraries = link::search_dirs(link, opts.target);
1758 format!(
1759 "install: {}\nprograms: ={}\nlibraries: ={}",
1760 here.display(),
1761 list(&link.prefixes),
1762 list(&libraries)
1763 )
1764 }
1765 // The root the rest of the answers are under, which a build system asks for when it wants
1766 // to find a file itself rather than ask for one by name, and which is the first thing to
1767 // look at when a cross build read a header nobody expected. A native compile has no
1768 // sysroot and the answer is the empty line, which is what GCC prints when it was
1769 // configured without one. `--sysroot` wins over ours because it wins everywhere else.
1770 Query::Sysroot => {
1771 sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
1772 }
1773 // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
1774 // compiler's own code, what it is, where it was got, its hash, its licence and whether it
1775 // was bundled, generated or fetched. What is printed is the manifest the sysroot already
1776 // carries rather than a second format saying the same things, because the three uses 13.5
1777 // gives for this are a licence notice, a reproducibility check and a security audit, and all
1778 // three are somebody else parsing it. One format is one parser to write.
1779 // Read and rendered rather than copied out, so that what comes back is the format this
1780 // build understands. The last newline comes off because whatever prints an answer adds
1781 // one, the way it does for every other query here. Keeping it would put a blank line at
1782 // the end of the one answer that is a file somebody diffs against the file it came from.
1783 Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
1784 Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
1785 None => String::new(),
1786 },
1787 // Section 13.2 of the same document, which asks for the hash of a cache directory's
1788 // contents in the directory's name. A name cannot carry one, because the path has to be
1789 // computable before anything has been read, by the producer about to write the files and by
1790 // the compiler about to read them, and neither has the contents when it asks. So the number
1791 // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
1792 // which means `sha256sum` over the manifest answers the same thing.
1793 Query::SysrootDigest => match sysroot_manifest(opts, link)? {
1794 Some(manifest) => manifest.digest(),
1795 None => String::new(),
1796 },
1797 Query::FileName(name) => found(name),
1798 // The name GCC gives the library of routines a compiler's output calls that the C
1799 // library does not have. Ours is built in and there is no file, so the answer is the
1800 // name itself, which is what GCC prints when it cannot find one either.
1801 Query::Libgcc => found("libgcc.a"),
1802 // A program rather than a library: the linker and the archiver are the ones a build asks
1803 // about, and this compiler finds them on the path or under `-B` rather than shipping
1804 // them, so the name back is the honest answer unless a `-B` prefix holds one.
1805 Query::ProgName(name) => link
1806 .prefixes
1807 .iter()
1808 .map(|dir| dir.join(name))
1809 .find(|path| path.is_file())
1810 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1811 })
1812}
1813
1814/// The root every sysroot answer is about.
1815///
1816/// One function rather than a copy in each, because the other flags exist to say what is inside the
1817/// tree this one names, and two answers that disagreed about which tree that is would be a
1818/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
1819/// else.
1820fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
1821 link.sysroot
1822 .clone()
1823 .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
1824}
1825
1826/// The record of the sysroot this command line reads, when there is one to read.
1827///
1828/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
1829/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
1830/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
1831/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
1832/// inputs in it because that one still has its header lines.
1833///
1834/// # Errors
1835///
1836/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
1837/// record we could not read on to whoever asked would make their parser the one that finds the
1838/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
1839/// output.
1840fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
1841 let Some(root) = sysroot_root(opts, link) else {
1842 return Ok(None);
1843 };
1844 let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
1845 match std::fs::read_to_string(&path) {
1846 Ok(text) => Manifest::parse(&text)
1847 .map(Some)
1848 .map_err(|why| err(format!("{}: {why}", path.display()))),
1849 Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
1850 Err(why) => Err(err(format!("{}: {why}", path.display()))),
1851 }
1852}
1853
1854/// Renders the passes this level will run, in order, with what each one does.
1855///
1856/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
1857/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
1858/// emerges from which flags happen to be set, and this is how that list is read.
1859#[must_use]
1860pub fn print_pipeline(opts: &Options) -> String {
1861 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1862 settings.toggles.clone_from(&opts.passes);
1863 settings.global_fuel = opts.pass_fuel_global;
1864 for (on, spec) in &opts.pass_gates {
1865 // Every spelling was checked while the arguments were parsed, so there is nothing here
1866 // this can refuse, and a listing is not the place to report it if there were.
1867 let _ = settings.gates.add(*on, spec);
1868 }
1869 rucc_opt::pipeline::print(&settings)
1870}
1871
1872/// Renders the resolved configuration.
1873///
1874/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
1875/// this output is diffed across hosts in CI and a reordering would read as a change.
1876#[must_use]
1877pub fn print_config(opts: &Options) -> String {
1878 let sess = Session::new(opts.clone());
1879 let t = &sess.target;
1880 let mut out = String::new();
1881 let _ = writeln!(out, "version: {VERSION}");
1882 // The three field triple the driver was given rather than the ten field tuple it widens to,
1883 // because this output is what a build system reads to find out what it asked for. The tuple is
1884 // the compiler's model of the machine and this line is a receipt for a command line.
1885 let _ = writeln!(out, "target: {}", opts.target);
1886 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1887 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1888 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1889 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1890 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1891 let _ = writeln!(out, "long-width: {}", t.long_width);
1892 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1893 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1894 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1895 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1896 // The register file as a count per class, which is enough to tell a target whose registers
1897 // are described from one whose are not without printing sixteen names nobody asked for.
1898 let regs: Vec<String> = t
1899 .regs
1900 .classes()
1901 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1902 .collect();
1903 let _ = writeln!(
1904 out,
1905 "registers: {}",
1906 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1907 );
1908 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1909 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1910 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1911 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1912 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1913 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1914 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1915 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
1916 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
1917 let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
1918 let _ = writeln!(out, "profile: {}", sess.opts.profile);
1919 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
1920 // Last because it is the one key with more than one line under it, and the only one
1921 // whose value is a property of the machine rather than of the command line.
1922 for dir in sess.opts.search.dirs() {
1923 let system = if dir.is_system { " (system)" } else { "" };
1924 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1925 }
1926 out
1927}
1928
1929/// The output name the make target is taken from, which is the `-o` argument or nothing.
1930///
1931/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
1932/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
1933/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
1934/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
1935/// `-S` on the argument does name what the rule builds, and it is used as written.
1936fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1937 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1938}
1939
1940/// Writes to a path the command line named rather than one the plan derived, where `-` is
1941/// standard output.
1942fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1943 if path == "-" {
1944 return write_out(&Output::Stdout, bytes);
1945 }
1946 write_out(&Output::File(path.to_owned()), bytes)
1947}
1948
1949/// Writes the make rule for one input, and reports whether it got there.
1950///
1951/// A rule with no file of its own goes where the compilation it replaced would have written,
1952/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
1953/// `$@`, and the same line with the `-o` left off puts it on standard output.
1954fn write_deps(
1955 opts: &Options,
1956 plan: &Plan,
1957 job: &Job,
1958 found: &[Dependency],
1959 stderr: &mut impl std::io::Write,
1960) -> bool {
1961 let targets = if opts.deps.targets.is_empty() {
1962 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1963 } else {
1964 opts.deps.targets.clone()
1965 };
1966 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1967 // The file, on the other hand, is named after the `-o` in every mode that still has one to
1968 // spend, which is every mode except the two that spend it on the rule.
1969 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1970 // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
1971 // named empty rather than absent, because a makefile that named it as a target of its
1972 // own is a makefile that will look for it.
1973 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1974 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1975 }),
1976 None => write_out(&job.output, rule.as_bytes()),
1977 };
1978 if let Err(e) = wrote {
1979 let _ = writeln!(stderr, "rucc: error: {e}");
1980 return false;
1981 }
1982 true
1983}
1984
1985/// Runs phase 4 over every input that has one, and writes what came out.
1986///
1987/// One input that fails does not stop the others. A build that reports every file it could
1988/// not preprocess in one run is worth more than one that stops at the first, and the exit
1989/// status is still a failure either way.
1990fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1991 let fs = OsFileSystem::new();
1992 let mut stderr = std::io::stderr().lock();
1993 let mut failed = false;
1994 for job in &plan.jobs {
1995 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1996 // An input that is already preprocessed, or an object file. GCC passes these
1997 // through untouched, and the plan has already said so in its notes.
1998 continue;
1999 }
2000 let started = std::time::Instant::now();
2001 let result = preprocess(opts, &job.input, &fs);
2002 if opts.time {
2003 say_time(&job.input, started.elapsed(), &mut stderr);
2004 }
2005 for message in &result.messages {
2006 let _ = writeln!(stderr, "{message}");
2007 }
2008 if result.failed() {
2009 failed = true;
2010 continue;
2011 }
2012 if opts.deps.emit {
2013 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2014 // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
2015 // to write. The other two asked for both and fall through to the text below.
2016 if opts.deps.instead_of_compiling {
2017 continue;
2018 }
2019 }
2020 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
2021 let _ = writeln!(stderr, "rucc: error: {e}");
2022 failed = true;
2023 }
2024 }
2025 i32::from(failed)
2026}
2027
2028/// Runs the front end over every input that has a compile phase, and writes what came out.
2029///
2030/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
2031/// exit status is a failure either way. An input that is already assembly or an object has no
2032/// compile phase and is passed over here, which the plan has already said in its notes.
2033fn compile_all(opts: &Options, plan: &Plan) -> i32 {
2034 let fs = OsFileSystem::new();
2035 let mut stderr = std::io::stderr().lock();
2036 let mut failed = false;
2037 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2038 failed |= !ok;
2039 let mut fired = Fired::new();
2040 let mut pressure = Pressure::new();
2041 for job in &plan.jobs {
2042 if !job.phases.contains(&Phase::Compile) {
2043 continue;
2044 }
2045 // An input of IR is read back rather than compiled, since the C it came from is not
2046 // here any more. Everything after this is the same, so the two paths meet again at the
2047 // messages and the file the result is written to.
2048 let started = std::time::Instant::now();
2049 let result = if job.kind == InputKind::Ir {
2050 compile_ir(opts, &job.input, &fs)
2051 } else {
2052 compile(opts, &job.input, &fs)
2053 };
2054 if opts.time {
2055 say_time(&job.input, started.elapsed(), &mut stderr);
2056 }
2057 fired.merge(&result.fired);
2058 pressure.merge(&result.pressure);
2059 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2060 failed |= !remarks.write(&result.remarks, &mut stderr);
2061 for message in &result.messages {
2062 let _ = writeln!(stderr, "{message}");
2063 }
2064 // Before the failure below, because a compilation that stopped in the back end is exactly
2065 // the one whose preprocessed source somebody wants to look at.
2066 failed |= !write_temps(job, &result.temps, &mut stderr);
2067 if result.failed() {
2068 failed = true;
2069 continue;
2070 }
2071 // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
2072 // this is the one path where both files come out of the same run. An input of IR has no
2073 // dependencies to report and produces an empty list, which produces a rule naming only
2074 // itself, and that is the honest answer rather than a missing file.
2075 if opts.deps.emit {
2076 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2077 }
2078 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
2079 let _ = writeln!(stderr, "rucc: error: {e}");
2080 failed = true;
2081 }
2082 }
2083 failed |= !write_coverage(opts, &fired, &mut stderr);
2084 failed |= !write_pressure(opts, &pressure, &mut stderr);
2085 i32::from(failed)
2086}
2087
2088/// A directory for the object files only the link step ever sees, removed when it goes away.
2089///
2090/// `-c` writes its object where the user can see it and linking does not, which is the whole of
2091/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
2092/// every other compiler. Removing them on drop rather than at the end of a function is so that a
2093/// link that failed leaves nothing behind either.
2094struct Scratch {
2095 /// Where the objects go.
2096 dir: PathBuf,
2097}
2098
2099impl Scratch {
2100 /// Makes one, under whatever the platform calls its temporary directory.
2101 ///
2102 /// The name carries the process id so that two compilers running at once do not share a
2103 /// directory, which they would otherwise do the moment two of them compiled a file of the
2104 /// same name.
2105 fn new() -> Result<Scratch, String> {
2106 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
2107 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
2108 Ok(Scratch { dir })
2109 }
2110}
2111
2112impl Drop for Scratch {
2113 fn drop(&mut self) {
2114 let _ = std::fs::remove_dir_all(&self.dir);
2115 }
2116}
2117
2118/// The link line the plan describes, for `-###`.
2119///
2120/// The names in it are the hints the plan carries rather than the temporaries a real compilation
2121/// would choose, because `-###` prints the line without having compiled anything and so has
2122/// nothing to point at. That also makes the printed line readable rather than naming a directory
2123/// that only exists while a compilation is running.
2124fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
2125 let linker = link::find(opts.target, link)?;
2126 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
2127 Ok(link::render(&linker, &args))
2128}
2129
2130/// Compiles everything, then links it.
2131///
2132/// The objects go in a directory that is removed afterwards, which is why this is not
2133/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
2134/// and does not say where, because where is a question that only has an answer once something is
2135/// running.
2136fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
2137 let Some(job) = &plan.link else {
2138 // Every path into here comes from a plan whose last phase is the link, and such a plan
2139 // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
2140 let mut stderr = std::io::stderr().lock();
2141 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
2142 return 1;
2143 };
2144 // Before anything is compiled, because a linker that is not on the machine is worth knowing
2145 // about in the second it takes to look rather than after the compilation.
2146 // And before that, whether this link has a line at all and whether what it reads is on the
2147 // machine. Both are answerable now, and a target whose sysroot has not been built is worth
2148 // saying so about before the compilation rather than after it.
2149 if let Err(why) = link::preflight(opts.target, link) {
2150 return complain(why);
2151 }
2152 let linker = match link::find(opts.target, link) {
2153 Ok(linker) => linker,
2154 Err(why) => return complain(why),
2155 };
2156
2157 let scratch = match Scratch::new() {
2158 Ok(scratch) => scratch,
2159 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
2160 };
2161
2162 let fs = OsFileSystem::new();
2163 let mut failed = false;
2164 // One per job, in job order, which is what lets the link line below be rebuilt with the real
2165 // paths in it: every job contributes exactly one file to the line and does so in this order.
2166 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
2167 let mut fired = Fired::new();
2168 let mut pressure = Pressure::new();
2169 {
2170 let mut stderr = std::io::stderr().lock();
2171 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2172 failed |= !ok;
2173 for (at, job) in plan.jobs.iter().enumerate() {
2174 let out = match &job.output {
2175 Output::Temporary(hint) => {
2176 // The index because two inputs in different directories can have the same
2177 // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
2178 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
2179 }
2180 Output::File(path) => path.clone(),
2181 // A job feeding the linker never writes to standard output, since the plan gives
2182 // it a temporary. This is here so that the match is total rather than a panic.
2183 Output::Stdout => continue,
2184 };
2185 produced.push(out.clone());
2186 if !job.phases.contains(&Phase::Compile) {
2187 continue;
2188 }
2189 let started = std::time::Instant::now();
2190 let result = if job.kind == InputKind::Ir {
2191 compile_ir(opts, &job.input, &fs)
2192 } else {
2193 compile(opts, &job.input, &fs)
2194 };
2195 if opts.time {
2196 say_time(&job.input, started.elapsed(), &mut stderr);
2197 }
2198 fired.merge(&result.fired);
2199 pressure.merge(&result.pressure);
2200 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2201 failed |= !remarks.write(&result.remarks, &mut stderr);
2202 for message in &result.messages {
2203 let _ = writeln!(stderr, "{message}");
2204 }
2205 failed |= !write_temps(job, &result.temps, &mut stderr);
2206 if result.failed() {
2207 failed = true;
2208 continue;
2209 }
2210 // A `-MD` on a command line that links writes the rule next to the executable and
2211 // names the executable as its target, since that is the file this source builds
2212 // here. The object it went through is in a temporary directory and is gone by the
2213 // time `make` reads any of this.
2214 if opts.deps.emit {
2215 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2216 }
2217 if !matches!(result.artifact, Artifact::Object { .. }) {
2218 // Worth saying rather than writing whatever it is and letting the linker read it.
2219 // An empty file is a valid empty linker script, so a link handed one gets as far
2220 // as reporting every symbol of this file undefined, which is a page of messages
2221 // about something that went wrong here.
2222 let _ = writeln!(
2223 stderr,
2224 "rucc: internal error: {}: no object file was produced for the link",
2225 job.input
2226 );
2227 failed = true;
2228 continue;
2229 }
2230 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
2231 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
2232 failed = true;
2233 }
2234 }
2235 failed |= !write_coverage(opts, &fired, &mut stderr);
2236 failed |= !write_pressure(opts, &pressure, &mut stderr);
2237 }
2238 if failed {
2239 // Nothing is linked from a compilation that did not finish. A linker run over the objects
2240 // that did compile would report every function of the file that did not as undefined,
2241 // which is a page of messages about a mistake already reported once.
2242 return 1;
2243 }
2244
2245 // The items in command line order with the temporaries filled in. A library contributes no
2246 // job and passes through, and every file item takes the next job's real output, which is
2247 // what keeps a library that was written between two objects between them here.
2248 let mut outputs = produced.into_iter();
2249 let mut items = Vec::with_capacity(job.inputs.len());
2250 for item in &job.inputs {
2251 match item {
2252 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
2253 link::Item::File(_) => match outputs.next() {
2254 Some(path) => items.push(link::Item::File(path)),
2255 None => return complain("the plan asks the linker for a file nothing produced"),
2256 },
2257 }
2258 }
2259
2260 let args = match link::line(opts.target, link, &items, &job.output) {
2261 Ok(args) => args,
2262 Err(why) => return complain(why),
2263 };
2264 if verbose {
2265 let mut stderr = std::io::stderr().lock();
2266 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
2267 }
2268 let started = std::time::Instant::now();
2269 let ran = link::run(&linker, &args);
2270 if opts.time {
2271 // The one step of a compilation that really is another program, so this line is the same
2272 // measurement gcc's is and names the linker the way gcc names `collect2`.
2273 let mut stderr = std::io::stderr().lock();
2274 say_time(&linker.name, started.elapsed(), &mut stderr);
2275 }
2276 match ran {
2277 Ok(()) => 0,
2278 // The linker has already said what was wrong on its own error output, and repeating that
2279 // linking failed would only push its message further up the screen.
2280 Err(link::Error::Refused { .. }) => 1,
2281 Err(why) => complain(why),
2282 }
2283}
2284
2285/// Compiles everything and writes the objects into one static library.
2286///
2287/// No temporary directory and no second program. The objects never reach the file system at all:
2288/// they go from the compiler into the archive writer, which is both faster than writing a directory
2289/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
2290/// member's index entries are the names the object writer says it wrote, and the only thing that
2291/// knows those is the run that wrote it.
2292///
2293/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
2294/// person can find, and they are written there as well as put in the archive.
2295fn archive_all(opts: &Options, plan: &Plan) -> i32 {
2296 let Some(job) = &plan.archive else {
2297 // Every path into here comes from a plan whose last phase is the archive, and such a plan
2298 // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
2299 return complain("there is nothing to put in an archive");
2300 };
2301 // Before anything is compiled, because a format this has no container for is worth knowing
2302 // about in the second it takes to look rather than after the whole compilation.
2303 let flavour = match opts.target.os.object_format() {
2304 ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
2305 ObjectFormat::Coff => rucc_archive::Flavour::Coff,
2306 // Mach-O wants the BSD flavour, whose index is a different member under a different name,
2307 // and wasm has no archives of its own at all. Neither has an object writer either, so a
2308 // command line reaching this would have failed in the next step regardless.
2309 format @ (ObjectFormat::MachO | ObjectFormat::Wasm) => {
2310 return complain(format!(
2311 "there is no archive format for {} objects in this compiler yet",
2312 format.as_str()
2313 ));
2314 }
2315 };
2316
2317 let fs = OsFileSystem::new();
2318 let mut failed = false;
2319 let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
2320 let mut names = job.members.iter();
2321 let mut fired = Fired::new();
2322 let mut pressure = Pressure::new();
2323 {
2324 let mut stderr = std::io::stderr().lock();
2325 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2326 failed |= !ok;
2327 for plan_job in &plan.jobs {
2328 // What the plan called this member. The two lists are walked together rather than the
2329 // name being worked out again here, so that what `-###` printed and what goes in the
2330 // file cannot come apart.
2331 let Some(member) = names.next() else {
2332 return complain("the plan asks the archive for a member nothing produced");
2333 };
2334 if !plan_job.phases.contains(&Phase::Compile) {
2335 // Assembly, which enters the pipeline after the compile phase. There is no
2336 // assembler for a file of text in this compiler, so there is no object to put in,
2337 // and an archive quietly missing one is worse than a message about it.
2338 let _ = writeln!(
2339 &mut stderr,
2340 "rucc: error: {}: this compiler has no assembler for a file of assembly yet, \
2341 so it cannot go into an archive",
2342 plan_job.input
2343 );
2344 failed = true;
2345 continue;
2346 }
2347 let started = std::time::Instant::now();
2348 let result = if plan_job.kind == InputKind::Ir {
2349 compile_ir(opts, &plan_job.input, &fs)
2350 } else {
2351 compile(opts, &plan_job.input, &fs)
2352 };
2353 if opts.time {
2354 say_time(&plan_job.input, started.elapsed(), &mut stderr);
2355 }
2356 fired.merge(&result.fired);
2357 pressure.merge(&result.pressure);
2358 failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
2359 failed |= !remarks.write(&result.remarks, &mut stderr);
2360 for message in &result.messages {
2361 let _ = writeln!(stderr, "{message}");
2362 }
2363 failed |= !write_temps(plan_job, &result.temps, &mut stderr);
2364 if result.failed() {
2365 failed = true;
2366 continue;
2367 }
2368 if opts.deps.emit {
2369 failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
2370 }
2371 let Artifact::Object { bytes, defines } = result.artifact else {
2372 let _ = writeln!(
2373 stderr,
2374 "rucc: internal error: {}: no object file was produced for the archive",
2375 plan_job.input
2376 );
2377 failed = true;
2378 continue;
2379 };
2380 // Under `-save-temps` the plan gave the object a name a person can find, so it is
2381 // written there too. Otherwise it is only ever a member and never a file.
2382 if let Output::File(path) = &plan_job.output {
2383 if let Err(e) = std::fs::write(path, &bytes) {
2384 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2385 failed = true;
2386 }
2387 }
2388 members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
2389 }
2390 failed |= !write_coverage(opts, &fired, &mut stderr);
2391 failed |= !write_pressure(opts, &pressure, &mut stderr);
2392 }
2393 if failed {
2394 // Nothing is written from a compilation that did not finish, for the reason the link gives:
2395 // an archive missing the file that failed is one a link reports every name of as undefined,
2396 // which is a page of messages about a mistake already reported once.
2397 return 1;
2398 }
2399
2400 let bytes = match rucc_archive::write(flavour, &members) {
2401 Ok(bytes) => bytes,
2402 // Every one of these is a bug here rather than a program's mistake: the names came from the
2403 // object writer and the bodies came from this process.
2404 Err(why) => return complain(format!("the archive could not be written: {why}")),
2405 };
2406 match std::fs::write(&job.output, &bytes) {
2407 Ok(()) => 0,
2408 Err(e) => complain(format!("{}: {e}", job.output)),
2409 }
2410}
2411
2412/// Prints one driver level message and gives back the exit status that goes with it.
2413fn complain(why: impl std::fmt::Display) -> i32 {
2414 let mut stderr = std::io::stderr().lock();
2415 let _ = writeln!(stderr, "rucc: error: {why}");
2416 1
2417}
2418
2419/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
2420///
2421/// Once for the whole command line rather than once per input, because the question is which
2422/// lowering rules this run of the compiler reached and a file per input would leave the reader
2423/// unioning files to find out something one process already knew.
2424///
2425/// A file that could not be written is a failure and not a warning. What asks for this is a
2426/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
2427fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
2428 let Some(path) = &opts.rule_coverage else { return true };
2429 let Some(table) = coverage::table(opts.target.arch) else {
2430 let _ = writeln!(
2431 stderr,
2432 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
2433 to report",
2434 opts.target
2435 );
2436 return false;
2437 };
2438 match std::fs::write(path, fired.listing(table)) {
2439 Ok(()) => true,
2440 Err(e) => {
2441 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2442 false
2443 }
2444 }
2445}
2446
2447/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
2448///
2449/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
2450/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
2451/// rule table here, since every target this compiles for has an allocator, and a run that reached
2452/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
2453/// produced no code is still an answer and it is the honest one.
2454fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
2455 let Some(path) = &opts.register_pressure else { return true };
2456 match std::fs::write(path, pressure.listing()) {
2457 Ok(()) => true,
2458 Err(e) => {
2459 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2460 false
2461 }
2462 }
2463}
2464
2465/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
2466///
2467/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
2468/// A file rather than the diagnostic stream is what a harness wants: the corpus in
2469/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
2470/// a few thousand remarks mixed into that would bury it.
2471struct Remarks {
2472 /// The file, if there is one.
2473 file: Option<String>,
2474 /// Whether anything has been written to it yet, which decides between truncating and
2475 /// appending. One file holds the whole run rather than the last input in it.
2476 started: bool,
2477}
2478
2479impl Remarks {
2480 /// Prepares the destination, emptying the file if there is one.
2481 ///
2482 /// Emptied here rather than at the first remark, because a run where no pass had anything to
2483 /// say should leave an empty file and not yesterday's. An absent file and an empty one are
2484 /// different facts and something reading this will act on the difference.
2485 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
2486 let mut ok = true;
2487 if let Some(path) = file {
2488 if let Err(e) = std::fs::write(path, "") {
2489 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2490 ok = false;
2491 }
2492 }
2493 (Self { file: file.cloned(), started: false }, ok)
2494 }
2495
2496 /// Writes one input's remarks, and says whether that worked.
2497 ///
2498 /// A file that cannot be written is a failure and not a warning, for the reason
2499 /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
2500 /// where nothing happened.
2501 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
2502 if text.is_empty() {
2503 return true;
2504 }
2505 let Some(path) = &self.file else {
2506 let _ = write!(stderr, "{text}");
2507 return true;
2508 };
2509 let opened = std::fs::OpenOptions::new()
2510 .write(true)
2511 .append(self.started)
2512 .truncate(!self.started)
2513 .create(true)
2514 .open(path);
2515 self.started = true;
2516 let result =
2517 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
2518 if let Err(e) = result {
2519 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2520 return false;
2521 }
2522 true
2523 }
2524}
2525
2526/// Writes what `-fdump-ir=` asked to see, one file per dump.
2527///
2528/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
2529/// after a run is the passes in the order they ran, per input. They go in the working directory
2530/// rather than beside the output, because a dump is something a person asked for at a prompt and
2531/// the working directory is where that person is.
2532///
2533/// A file that could not be written is a failure and not a warning, for the reason
2534/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
2535/// quietly did not happen looks exactly like a pass that did not run.
2536fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
2537 let stem = std::path::Path::new(input)
2538 .file_name()
2539 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
2540 let mut ok = true;
2541 for dump in dumps {
2542 let path = format!("{stem}.{}.ir", dump.name);
2543 if let Err(e) = std::fs::write(&path, &dump.text) {
2544 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2545 ok = false;
2546 }
2547 }
2548 ok
2549}
2550
2551/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
2552///
2553/// A file that could not be written is a failure rather than a warning, for the reason
2554/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
2555/// looks like a compilation that never went through that step.
2556fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
2557 let mut ok = true;
2558 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
2559 for (path, text) in kept {
2560 // A step the compilation did not reach has nothing to keep, and a job that is not keeping
2561 // that step has nowhere to put it. Either way there is no file here.
2562 let (Some(path), Some(text)) = (path, text) else { continue };
2563 if let Err(e) = std::fs::write(&path, text) {
2564 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2565 ok = false;
2566 }
2567 }
2568 ok
2569}
2570
2571/// One line of `-time`, which is what a step was called and how long it took.
2572///
2573/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
2574/// no subprocess for anything but the link, so what is measured here is the wall clock of the
2575/// step and the second column is always zero. The shape of the line is kept because a person
2576/// reading it next to gcc's should not have to work out which column is which.
2577fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
2578 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
2579}
2580
2581/// Writes one job's result where the plan said it goes.
2582///
2583/// # Errors
2584///
2585/// Returns the message to print, which names the file when there is one, because "permission
2586/// denied" on its own does not say which file was refused.
2587fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
2588 match output {
2589 Output::Stdout => {
2590 let mut stdout = std::io::stdout().lock();
2591 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
2592 }
2593 Output::File(path) | Output::Temporary(path) => {
2594 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
2595 }
2596 }
2597}
2598
2599/// Runs the driver and returns the process exit code.
2600///
2601/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
2602/// is the one place in the compiler that is true.
2603pub fn run(args: &[String]) -> i32 {
2604 match parse_args(args) {
2605 Ok(Action::Help) => {
2606 print!("{USAGE}");
2607 0
2608 }
2609 Ok(Action::Version) => {
2610 println!("rucc {VERSION}");
2611 0
2612 }
2613 Ok(Action::Print(line)) => {
2614 println!("{line}");
2615 0
2616 }
2617 Ok(Action::PrintConfig(opts)) => {
2618 print!("{}", print_config(&opts));
2619 0
2620 }
2621 Ok(Action::PrintPipeline(opts)) => {
2622 print!("{}", print_pipeline(&opts));
2623 0
2624 }
2625 Ok(Action::PrintPlan { opts, plan, link }) => {
2626 print!("{}", plan.render());
2627 // The line as it would be typed, which is the half of `-###` that section 4.3 says
2628 // arrives with the link. It is printed even when the linker is not on this machine,
2629 // because what a build wants from `-###` is what the compiler would do.
2630 if let Some(job) = &plan.link {
2631 match link_line(&opts, &link, job) {
2632 Ok(line) => println!("{line}"),
2633 Err(why) => {
2634 let mut stderr = std::io::stderr().lock();
2635 let _ = writeln!(stderr, "rucc: error: {why}");
2636 return 1;
2637 }
2638 }
2639 }
2640 0
2641 }
2642 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
2643 {
2644 let mut stderr = std::io::stderr().lock();
2645 if verbose {
2646 let _ = write!(stderr, "{}", plan.render());
2647 let _ = writeln!(stderr, "workers: {}", jobs.count());
2648 }
2649 }
2650 if opts.emit == EmitKind::Preprocessed {
2651 return preprocess_all(&opts, &plan);
2652 }
2653 if opts.emit == EmitKind::Archive {
2654 return archive_all(&opts, &plan);
2655 }
2656 if opts.emit != EmitKind::Executable {
2657 return compile_all(&opts, &plan);
2658 }
2659 link_all(&opts, &plan, &link, verbose)
2660 }
2661 Err(e) => {
2662 let mut stderr = std::io::stderr().lock();
2663 let _ = writeln!(stderr, "rucc: error: {e}");
2664 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
2665 1
2666 }
2667 }
2668}
2669
2670#[cfg(test)]
2671mod tests {
2672 use rucc_session::{
2673 Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
2674 };
2675
2676 use super::*;
2677
2678 fn args(s: &[&str]) -> Vec<String> {
2679 s.iter().map(|x| (*x).to_owned()).collect()
2680 }
2681
2682 #[test]
2683 fn help_and_version_win_over_everything_else() {
2684 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
2685 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
2686 }
2687
2688 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
2689 match parse_args(&args(s)).expect("expected a compilation") {
2690 Action::Compile { opts, plan, .. } => (opts, plan),
2691 other => panic!("expected a compilation, got {other:?}"),
2692 }
2693 }
2694
2695 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
2696 match parse_args(&args(s)).expect("expected a compilation") {
2697 Action::Compile { link, plan, .. } => (link, plan),
2698 other => panic!("expected a compilation, got {other:?}"),
2699 }
2700 }
2701
2702 #[test]
2703 fn collects_inputs_and_flags() {
2704 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
2705 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2706 assert_eq!(paths, vec!["a.c", "b.c"]);
2707 assert_eq!(opts.opt_level, OptLevel::O2);
2708 assert_eq!(opts.emit, EmitKind::Object);
2709 assert!(opts.debug_info);
2710 }
2711
2712 /// The unstable options, which are spelled apart from everything else on purpose: what is
2713 /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
2714 #[test]
2715 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
2716 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
2717 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
2718
2719 let (plain, _) = compile(&["-c", "a.c"]);
2720 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
2721
2722 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
2723 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
2724 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
2725 }
2726
2727 /// The other measurement written to a file, which reads the same way and fails the same way.
2728 #[test]
2729 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
2730 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
2731 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
2732
2733 let (plain, _) = compile(&["-c", "a.c"]);
2734 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
2735
2736 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
2737 }
2738
2739 #[test]
2740 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
2741 let (opts, _) = compile(&["-O", "a.c"]);
2742 assert_eq!(opts.opt_level, OptLevel::O1);
2743 }
2744
2745 #[test]
2746 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
2747 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
2748 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
2749 assert_eq!(plan.jobs[1].kind, InputKind::C);
2750 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
2751 }
2752
2753 #[test]
2754 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
2755 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
2756 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
2757 other => panic!("expected a compilation, got {other:?}"),
2758 };
2759 assert_eq!(jobs.count(), 4);
2760
2761 let default = match parse_args(&args(&["a.c"])).unwrap() {
2762 Action::Compile { jobs, .. } => jobs,
2763 other => panic!("expected a compilation, got {other:?}"),
2764 };
2765 assert_eq!(default, Jobs::available());
2766 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
2767 }
2768
2769 #[test]
2770 fn triple_hash_prints_the_plan_and_runs_nothing() {
2771 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
2772 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
2773 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
2774 }
2775
2776 #[test]
2777 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
2778 // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
2779 // this, and following the compiler is what makes a build that reads either of them find
2780 // the files where they are.
2781 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
2782 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
2783 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
2784 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
2785 // The last one on the line decides, the way it does for every other flag with an
2786 // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
2787 // nothing and said nothing looks exactly like one where the files were not produced.
2788 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
2789 assert_eq!(opts.save_temps, SaveTemps::Cwd);
2790 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
2791 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
2792 }
2793
2794 #[test]
2795 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
2796 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
2797 let (plain, without) = compile(&["-c", "a.c"]);
2798 assert!(opts.time);
2799 assert!(!plain.time);
2800 // Against the same line without the flag rather than against a spelling of the object's
2801 // name, since what the object is called is the host's business and this is not about that.
2802 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
2803 }
2804
2805 #[test]
2806 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
2807 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
2808 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
2809 }
2810
2811 #[test]
2812 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
2813 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
2814 assert!(e.message.contains("unknown option"), "{}", e.message);
2815 }
2816
2817 /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
2818 /// one directory needs the older rules and the rest of the tree does not.
2819 #[test]
2820 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
2821 let (opts, _) = compile(&["-c", "a.c"]);
2822 assert!(!opts.permissive, "off unless it is asked for");
2823
2824 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
2825 assert!(opts.permissive);
2826
2827 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
2828 assert!(!opts.permissive);
2829 }
2830
2831 #[test]
2832 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
2833 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
2834 assert!(e.message.contains("trampoline"), "{}", e.message);
2835 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
2836 }
2837
2838 #[test]
2839 fn the_flag_every_configure_script_writes_is_taken() {
2840 // All four spellings, because a build writes whichever one its macros picked and a
2841 // compiler that takes three of them is a compiler that fails on the fourth.
2842 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
2843 let (opts, _) = compile(&["-c", flag, "a.c"]);
2844 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2845 }
2846 }
2847
2848 #[test]
2849 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
2850 let (opts, _) = compile(&["-c", "a.c"]);
2851 assert!(opts.unwinds(), "the default is off");
2852 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
2853 assert!(!opts.unwinds(), "the build was not taken at its word");
2854 let (opts, _) = compile(&[
2855 "-c",
2856 "-fno-asynchronous-unwind-tables",
2857 "-fasynchronous-unwind-tables",
2858 "a.c",
2859 ]);
2860 assert!(opts.unwinds(), "the last flag did not win");
2861 // The weaker request, which the same table answers, so a line that asks for a table and
2862 // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
2863 // build turns the asynchronous one off globally and a directory asks for a table back.
2864 let (opts, _) =
2865 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
2866 assert!(opts.unwinds(), "the weaker request was dropped");
2867 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
2868 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
2869 let (opts, _) =
2870 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
2871 assert!(!opts.unwinds(), "both were turned off and one stayed on");
2872 }
2873
2874 #[test]
2875 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
2876 // Every one of these is on a real build line somewhere and every one of them was an
2877 // unknown option. What they have in common is that the answer rucc gives is the answer
2878 // they ask for, so there is nothing to implement and nothing to refuse.
2879 for flag in [
2880 "-fno-common",
2881 "-fstrict-aliasing",
2882 "-fno-strict-aliasing",
2883 "-fdelete-null-pointer-checks",
2884 "-fno-delete-null-pointer-checks",
2885 "-frounding-math",
2886 "-fno-rounding-math",
2887 "-fexcess-precision=standard",
2888 "-fexcess-precision=fast",
2889 "-fexcess-precision=16",
2890 "-pipe",
2891 "-fdiagnostics-color",
2892 "-fno-diagnostics-color",
2893 "-fdiagnostics-color=always",
2894 "-fdiagnostics-color=never",
2895 "-fdiagnostics-color=auto",
2896 ] {
2897 let (opts, _) = compile(&["-c", flag, "a.c"]);
2898 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2899 }
2900 }
2901
2902 #[test]
2903 fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
2904 let (opts, _) = compile(&["-c", "a.c"]);
2905 assert!(opts.trapping_math, "the default was not gcc's");
2906 let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
2907 assert!(!opts.trapping_math);
2908 let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
2909 assert!(opts.trapping_math, "spelling out the default turned it off");
2910 // The last one written wins, which is how a build line that inherits a flag from one
2911 // place and overrides it in another is read.
2912 let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
2913 assert!(opts.trapping_math);
2914 }
2915
2916 /// The flags a torture program writes on its own `dg-options` line, which is where most of
2917 /// these come from: a program reduced from a miscompilation names the pass that miscompiled
2918 /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
2919 /// tamnd/rucc#1019 is the list.
2920 #[test]
2921 fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
2922 for flag in [
2923 "-fno-tree-ccp",
2924 "-fno-tree-dominator-opts",
2925 "-fno-tree-vrp",
2926 "-fno-tree-bit-ccp",
2927 "-fno-tree-coalesce-vars",
2928 "-ftree-vectorize",
2929 "-ftree-loop-distribution",
2930 "-fno-ipa-cp",
2931 "-fipa-pta",
2932 "-fmodulo-sched",
2933 "-fno-vect-cost-model",
2934 "-fvect-cost-model=unlimited",
2935 "-fsimd-cost-model=cheap",
2936 "-fexpensive-optimizations",
2937 "-fno-early-inlining",
2938 "-fno-inline",
2939 "-finline-functions",
2940 "-foptimize-strlen",
2941 "-fno-ira-share-spill-slots",
2942 ] {
2943 let (opts, _) = compile(&["-c", flag, "a.c"]);
2944 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2945 assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
2946 }
2947 }
2948
2949 /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
2950 /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
2951 #[test]
2952 fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
2953 for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
2954 let (opts, _) = compile(&["-c", flag, "a.c"]);
2955 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2956 }
2957 }
2958
2959 /// A pass this compiler has keeps its flag, since the arms that read the registry are above
2960 /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
2961 /// is the program that writes it.
2962 #[test]
2963 fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
2964 let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
2965 assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
2966 }
2967
2968 /// The encoding of the source is not a question about speed, so the one name that describes
2969 /// what the preprocessor does is taken and every other name is refused.
2970 #[test]
2971 fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
2972 for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
2973 let (opts, _) = compile(&["-c", flag, "a.c"]);
2974 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2975 }
2976
2977 let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
2978 assert!(e.message.contains("latin1"), "{}", e.message);
2979 assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
2980 }
2981
2982 /// The other half of the same rule. Each of these changes what the program does rather than
2983 /// how fast it does it, so each is refused with the reason, and the negative of each is what
2984 /// happens anyway and is taken.
2985 #[test]
2986 fn the_three_that_change_the_answer_are_refused_and_their_negatives_are_taken() {
2987 for (flag, word) in [
2988 ("-ffast-math", "__FAST_MATH__"),
2989 ("-fnon-call-exceptions", "landing pad"),
2990 ("-finstrument-functions", "__cyg_profile_func_enter"),
2991 ] {
2992 let e = parse_args(&args(&["-c", flag, "a.c"])).unwrap_err();
2993 assert!(e.message.contains(word), "{flag}: {}", e.message);
2994 assert!(!e.message.contains("unknown option"), "{flag} deserves a reason");
2995
2996 let off = format!("-fno-{}", flag.trim_start_matches("-f"));
2997 let (opts, _) = compile(&["-c", &off, "a.c"]);
2998 assert_eq!(opts.emit, EmitKind::Object, "{off}");
2999 }
3000 }
3001
3002 #[test]
3003 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
3004 // The one of that family that is a request rather than a description, and it is a real
3005 // difference: two files each writing `int g;` link under it and do not without it.
3006 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
3007 assert!(e.message.contains(".bss"), "{}", e.message);
3008 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
3009 }
3010
3011 #[test]
3012 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
3013 for flag in ["-fno-pic", "-fno-pie"] {
3014 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
3015 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
3016 // The one it may have meant, since the two are a letter apart and one of them is
3017 // about linking and is taken.
3018 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
3019 }
3020 }
3021
3022 #[test]
3023 fn an_unsupported_target_names_itself() {
3024 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
3025 assert!(e.message.contains("sparc64"), "{}", e.message);
3026 }
3027
3028 #[test]
3029 fn no_inputs_is_an_error_but_print_config_needs_none() {
3030 assert!(parse_args(&args(&[])).is_err());
3031 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
3032 }
3033
3034 #[test]
3035 fn print_config_reports_the_target_it_was_given_not_the_host() {
3036 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
3037 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
3038 let text = print_config(&opts);
3039 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
3040 assert!(text.contains("char-signed: false"), "{text}");
3041 assert!(text.contains("object-format: elf"), "{text}");
3042 assert!(text.contains("va-list: void-pointer"), "{text}");
3043 // RISC-V has a register file and this compiler has not written it down yet, and the
3044 // dump says which of those two it is rather than leaving the line out.
3045 assert!(text.contains("registers: none"), "{text}");
3046 }
3047
3048 #[test]
3049 fn print_config_has_one_key_per_line_and_a_fixed_order() {
3050 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
3051 let text = print_config(&opts);
3052 let keys: Vec<&str> =
3053 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
3054 assert_eq!(keys[0], "version");
3055 assert_eq!(keys[1], "target");
3056 assert_eq!(keys.len(), 25);
3057 assert!(text.ends_with('\n'));
3058 }
3059
3060 #[test]
3061 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
3062 let (opts, _) = compile(&["a.c"]);
3063 assert_eq!(opts.safety, rucc_session::Safety::Off);
3064
3065 for (flag, tier) in [
3066 ("-fsafety=detect", rucc_session::Safety::Detect),
3067 ("-fsafety=enforce", rucc_session::Safety::Enforce),
3068 ("-fsafety=kernel", rucc_session::Safety::Kernel),
3069 ("-fsafety=off", rucc_session::Safety::Off),
3070 ] {
3071 let (opts, _) = compile(&[flag, "a.c"]);
3072 assert_eq!(opts.safety, tier, "{flag}");
3073 }
3074
3075 // The last one wins, the way every other repeated flag on this command line does.
3076 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
3077 assert_eq!(opts.safety, rucc_session::Safety::Off);
3078
3079 // A misspelled tier is refused rather than ignored. Silently compiling without the
3080 // monitor a build asked for is the one failure mode this feature cannot have.
3081 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
3082 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
3083 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
3084 }
3085
3086 #[test]
3087 fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
3088 // The default is the one section 9.3 of document 09 gives library code, which is that
3089 // padding does not participate, so a record filled a member at a time is not reported.
3090 let (opts, _) = compile(&["a.c"]);
3091 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
3092
3093 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
3094 assert_eq!(opts.padding, rucc_session::Padding::Tracked);
3095
3096 let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
3097 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
3098
3099 // The tier is still a tier. A flag whose name starts the same way must not be eaten by
3100 // the one above it, which is the thing worth pinning about a pair of names like these.
3101 let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
3102 assert_eq!(opts.safety, rucc_session::Safety::Off);
3103
3104 let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
3105 assert!(e.message.contains("is not a padding mode"), "{}", e.message);
3106 }
3107
3108 #[test]
3109 fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
3110 // Off by default, because a store to allocated storage sets its effective type and C 6.5
3111 // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
3112 let (opts, _) = compile(&["a.c"]);
3113 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
3114
3115 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
3116 assert_eq!(opts.subobject, rucc_session::Subobject::Members);
3117
3118 let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
3119 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
3120
3121 // It takes no value. The form that would take one is the strict reading of section 9.4,
3122 // which is not written yet, so say so rather than accept a spelling that does nothing.
3123 let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
3124 assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
3125 }
3126
3127 #[test]
3128 fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
3129 // Off by default, because the record a block keeps is the union of what each pointer
3130 // reached, so two pointers striding through one array without landing on the same byte are
3131 // reported and by the letter of the standard those are different objects. Row Y8 is a build
3132 // deciding it would rather know.
3133 let (opts, _) = compile(&["a.c"]);
3134 assert_eq!(opts.promise, rucc_session::Promise::Off);
3135
3136 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
3137 assert_eq!(opts.promise, rucc_session::Promise::Blocks);
3138
3139 let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
3140 assert_eq!(opts.promise, rucc_session::Promise::Off);
3141
3142 // The tier is still a tier, which is the thing worth pinning about a pair of names where
3143 // one is the front of the other.
3144 let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
3145 assert_eq!(opts.safety, rucc_session::Safety::Off);
3146
3147 let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
3148 assert!(e.message.contains("takes no value"), "{}", e.message);
3149 }
3150
3151 #[test]
3152 fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
3153 // Three modes rather than a bare flag, because section 9.5 gives two answers that record
3154 // the same thing and report different classes, so a flag with no value could not say which
3155 // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
3156 // argument: this is the one plane where an edge nobody interposed costs a false report.
3157 let (opts, _) = compile(&["a.c"]);
3158 assert_eq!(opts.races, rucc_session::Races::Off);
3159
3160 let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
3161 assert_eq!(opts.races, rucc_session::Races::Metadata);
3162
3163 let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
3164 assert_eq!(opts.races, rucc_session::Races::Pointer);
3165
3166 // Last one wins, as it does for every other mode flag here.
3167 let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
3168 assert_eq!(opts.races, rucc_session::Races::Off);
3169
3170 let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
3171 assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
3172 }
3173
3174 #[test]
3175 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
3176 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
3177 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3178 let text = print_pipeline(&opts);
3179 assert!(text.starts_with("level: -O2\n"), "{text}");
3180 assert!(text.contains("fold"), "{text}");
3181
3182 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
3183 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3184 // One pass runs at `-O0` and it is the one that removes code nothing reaches, which is
3185 // not an optimization. See issue 359.
3186 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
3187
3188 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
3189 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3190 // And with that one turned off there is nothing left, which the dump says rather than
3191 // printing an empty list.
3192 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
3193 }
3194
3195 #[test]
3196 fn print_pipeline_takes_the_toggles_into_account() {
3197 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
3198 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3199 let text = print_pipeline(&opts);
3200 // The one that was named is gone and the rest of the level is not, which is the whole
3201 // of what a toggle promises.
3202 assert!(!text.contains("fold"), "{text}");
3203 assert!(text.contains("dce"), "{text}");
3204
3205 // Every pass the compiler has, named off. Built from the registry rather than written
3206 // out, so a pass added later is turned off here too and this keeps testing the thing it
3207 // is about, which is that the toggles can empty a level.
3208 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
3209 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
3210 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
3211 let a = parse_args(&args(&spelled)).unwrap();
3212 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3213 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
3214 }
3215
3216 #[test]
3217 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
3218 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
3219 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3220 assert!(!print_pipeline(&opts).contains("global fuel"));
3221
3222 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
3223 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3224 let text = print_pipeline(&opts);
3225 // Because the listing is the answer to what this compilation will do, and a run that
3226 // stops after four rewrites is not doing what the level says it does.
3227 assert!(text.contains("global fuel: 4"), "{text}");
3228 }
3229
3230 /// A pass is turned on and off by its own name, and the order the flags were given in is
3231 /// kept, because the last spelling of a name is the one that decides.
3232 #[test]
3233 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
3234 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
3235 assert_eq!(
3236 opts.passes,
3237 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
3238 );
3239
3240 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
3241 assert!(e.message.contains("unknown option"), "{}", e.message);
3242 }
3243
3244 #[test]
3245 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
3246 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
3247 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
3248
3249 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
3250 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
3251 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
3252 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
3253 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
3254 assert!(e.message.contains("not a number"), "{}", e.message);
3255 }
3256
3257 #[test]
3258 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
3259 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
3260 assert_eq!(opts.pass_fuel_global, None);
3261
3262 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
3263 assert_eq!(opts.pass_fuel_global, Some(12));
3264 // And it is not the per pass flag with a longer name, so neither spelling swallows the
3265 // other.
3266 assert!(opts.pass_fuel.is_empty());
3267
3268 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
3269 assert!(e.message.contains("not a number"), "{}", e.message);
3270 }
3271
3272 #[test]
3273 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
3274 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
3275 assert_eq!(
3276 opts.pass_gates,
3277 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
3278 "the order is what decides, so it has to survive the parse"
3279 );
3280
3281 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
3282 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
3283 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
3284 assert!(e.message.contains("ends before it starts"), "{}", e.message);
3285 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
3286 assert!(e.message.contains("is empty"), "{}", e.message);
3287 }
3288
3289 #[test]
3290 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
3291 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
3292 let text = print_pipeline(&opts);
3293 assert!(text.contains("fold, "), "{text}");
3294 assert!(text.contains("[off for main]"), "{text}");
3295 }
3296
3297 /// The spelling is checked while the arguments are read, because a dump that names a pass
3298 /// this compiler does not have is a typo, and a typo found after the compilation has run is
3299 /// found too late to be any use.
3300 #[test]
3301 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
3302 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
3303 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
3304
3305 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
3306 assert!(e.message.contains("nosuch"), "{}", e.message);
3307 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
3308 }
3309
3310 /// Every spelling `-fopt-info` takes, and the one it does not.
3311 ///
3312 /// The keywords are checked here for the same reason a dump's pass name is: a person who
3313 /// misspelled one gets no output, and no output is also what a compilation where nothing
3314 /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
3315 #[test]
3316 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
3317 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
3318 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
3319 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
3320
3321 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
3322 assert_eq!(opts.opt_info, ["missed-note"]);
3323
3324 // Two flags add up rather than the second replacing the first, and the file is the last
3325 // one that named a file, which is how GCC treats both.
3326 let (opts, _) =
3327 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
3328 assert_eq!(opts.opt_info, ["missed", "all"]);
3329 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
3330
3331 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
3332 assert!(e.message.contains("vectorized"), "{}", e.message);
3333 assert!(e.message.contains("`missed`"), "{}", e.message);
3334 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
3335 assert!(e.message.contains("no file"), "{}", e.message);
3336 }
3337
3338 #[test]
3339 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
3340 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
3341 assert!(opts.verify_each);
3342 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
3343 }
3344
3345 #[test]
3346 fn dash_o_needs_an_argument() {
3347 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
3348 assert_eq!(e.message, "-o requires an argument");
3349 }
3350
3351 #[test]
3352 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
3353 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
3354 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
3355 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
3356 }
3357
3358 #[test]
3359 fn the_include_flags_land_on_the_chain_each_one_names() {
3360 // A sysroot with nothing under it, so that the library's own directories are the
3361 // same on every machine this test runs on, which is none of them.
3362 let (opts, _) = compile(&[
3363 "-Ii",
3364 "-iquote",
3365 "q",
3366 "-isystem",
3367 "sys",
3368 "-idirafter",
3369 "after",
3370 "--sysroot=/nowhere-at-all",
3371 "a.c",
3372 ]);
3373 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
3374 // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
3375 // which is where GCC puts its own: a directory the user named outranks ours.
3376 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
3377 assert!(!opts.search.dirs()[1].is_system);
3378 assert!(opts.search.dirs()[2].is_system);
3379 }
3380
3381 #[test]
3382 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
3383 // Which machine this runs on decides what is on the path, so the test is about the
3384 // order rather than about the names: ours is on it, the library's follow it, and
3385 // `-nostdinc` is the one flag that takes both halves of the pair off at once.
3386 let (opts, _) = compile(&["a.c"]);
3387 let dirs = opts.search.dirs();
3388 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
3389 assert_eq!(ours, Some(0), "{dirs:?}");
3390 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
3391 let (bare, _) = compile(&["-nostdinc", "a.c"]);
3392 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
3393 }
3394
3395 #[test]
3396 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
3397 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
3398 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
3399 assert_eq!(dirs, ["sys", runtime::DIR]);
3400 }
3401
3402 #[test]
3403 fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
3404 // The target is not the machine this test runs on wherever it runs, so the answer is the
3405 // same on all of them: the libc's two include directories for that target, the kernel's
3406 // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
3407 // program that builds on the build machine and is wrong everywhere else.
3408 let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
3409 let dirs: Vec<&std::path::Path> =
3410 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
3411 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
3412 let kernel = cache::dir().join("kernel-headers");
3413 assert_eq!(dirs.len(), 5, "{dirs:?}");
3414 assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
3415 assert_eq!(dirs[1], root.join("include").join("riscv64"));
3416 assert_eq!(dirs[2], root.join("include").join("generic"));
3417 // The kernel's, which are beside the sysroots rather than inside one, because every target
3418 // that shares an architecture reads the same files.
3419 assert_eq!(dirs[3], kernel.join("riscv"));
3420 assert_eq!(dirs[4], kernel.join("generic"));
3421 }
3422
3423 #[test]
3424 fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
3425 // The other side of the same answer. Windows has its own system headers and no `linux/` at
3426 // all, so the list is the libc's two and the question never arises, which is the `None` that
3427 // `link::cross_kernel` returns rather than a directory nothing would be found in.
3428 let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
3429 let dirs: Vec<&std::path::Path> =
3430 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
3431 assert_eq!(dirs.len(), 3, "{dirs:?}");
3432 assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
3433 }
3434
3435 #[test]
3436 fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
3437 // One tree serves every glibc release, so the release is what the target supplies, and the
3438 // condition is the same one that chose the directories. A host glibc and a tree somebody
3439 // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
3440 // different values is a warning on every compilation of every file.
3441 //
3442 // The architecture is chosen against this machine's rather than written down, because the
3443 // bundled tree is only in effect for a target that is not this machine. The first version of
3444 // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
3445 // Linux runner, so it passed here and failed there.
3446 let gnu = format!("--target={}-linux-gnu", cross_arch());
3447 let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
3448 assert_eq!(bundled.glibc_minor, Some(44));
3449 let pin = format!("{gnu}.2.28");
3450 let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
3451 assert_eq!(pinned.glibc_minor, Some(28));
3452
3453 let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3454 assert_eq!(named.glibc_minor, None);
3455 let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
3456 assert_eq!(none.glibc_minor, None);
3457 let musl = format!("--target={}-linux-musl", cross_arch());
3458 let (musl, _) = compile(&[&musl, "-c", "a.c"]);
3459 assert_eq!(musl.glibc_minor, None);
3460
3461 // And this machine's own target gets nothing, whatever this machine is, because its headers
3462 // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
3463 // that is the case this test had backwards; on a mac it is true for the other reason, which
3464 // is that Darwin is not a glibc target at all.
3465 if let Some(host) = Triple::host() {
3466 let native = format!("--target={}", host.tuple());
3467 let (native, _) = compile(&[&native, "-c", "a.c"]);
3468 assert_eq!(native.glibc_minor, None);
3469 }
3470 }
3471
3472 #[test]
3473 fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
3474 // The end to end half of the answer in `link::cross_for`. A release named for this machine's
3475 // own target is a cross compile, so the headers are the bundled tree's and the macro says
3476 // what was asked for rather than what this machine has.
3477 //
3478 // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
3479 // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
3480 // where the case lives.
3481 let Some(host) = Triple::host() else { return };
3482 if host.env != rucc_target::Env::Gnu {
3483 return;
3484 }
3485 let pin = format!("--target={}.2.28", host.tuple());
3486 let (opts, _) = compile(&[&pin, "-c", "a.c"]);
3487 assert_eq!(opts.glibc_minor, Some(28));
3488 let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
3489 let dirs: Vec<&std::path::Path> =
3490 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
3491 assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
3492 // And nothing of this machine's, which is the failure this was: a program compiled against
3493 // 2.44 declarations and told it was 2.28.
3494 assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
3495 }
3496
3497 /// An architecture that is not this machine's, out of the three the driver has targets for.
3498 ///
3499 /// A test about the bundled sysroot has to name a target that is not the host, because a target
3500 /// that is the host reads the host's own headers and libraries. Asking which machine this is
3501 /// beats picking a row and hoping, and it is two lines.
3502 fn cross_arch() -> &'static str {
3503 match Triple::host().map(|host| host.arch) {
3504 Some(rucc_target::Arch::X86_64) => "aarch64",
3505 _ => "x86_64",
3506 }
3507 }
3508
3509 #[test]
3510 fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
3511 // Both versions in the message, because the two things a person can do about it are pin a
3512 // release the tree has and name a sysroot that has the one they asked for, and neither is a
3513 // choice they can make without knowing which release the tree is.
3514 //
3515 // Not this machine's architecture, for the reason the test above gives: the refusal is about
3516 // the bundled tree, and the bundled tree is not what a target that is this machine reads.
3517 let target = format!("--target={}-linux-gnu.2.99", cross_arch());
3518 let message = refused(&[&target, "-c", "a.c"]);
3519 assert!(message.contains("asked for glibc 2.99"), "{message}");
3520 assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
3521 assert!(message.contains("--sysroot"), "{message}");
3522 }
3523
3524 #[test]
3525 fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
3526 // The tree somebody assembled beats the one we would build, on the headers as on the
3527 // libraries. It is empty here, which is why the list comes out short: the directories under
3528 // it are checked for rather than assumed, and a tree that is not there offers nothing.
3529 let (opts, _) =
3530 compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3531 let dirs: Vec<&std::path::Path> =
3532 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
3533 assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
3534 }
3535
3536 #[test]
3537 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
3538 let (opts, _) =
3539 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
3540 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
3541 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
3542 // An angled include sees only what came after the flag.
3543 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
3544 assert!(!opts.search.searches_current_dir());
3545 }
3546
3547 #[test]
3548 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
3549 let (opts, _) = compile(&[
3550 "-iprefix",
3551 "/tools/",
3552 "-iwithprefix",
3553 "late",
3554 "-iwithprefixbefore",
3555 "early",
3556 "-iprefix",
3557 "/other/",
3558 "-iwithprefix",
3559 "last",
3560 "-nostdinc",
3561 "a.c",
3562 ]);
3563 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
3564 // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
3565 // puts them rather than where its manual says it does.
3566 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
3567 assert!(!opts.search.dirs()[0].is_system);
3568 assert!(opts.search.dirs()[1].is_system);
3569 }
3570
3571 #[test]
3572 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
3573 let (opts, _) =
3574 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
3575 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
3576 assert_eq!(names, ["one.h", "two.h", "3.h"]);
3577 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
3578 }
3579
3580 #[test]
3581 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
3582 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
3583 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
3584 assert_eq!(dirs, ["i"]);
3585 }
3586
3587 #[test]
3588 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
3589 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
3590 assert_eq!(opts.std, Std::C11);
3591 assert!(opts.gnu_extensions);
3592
3593 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
3594 assert_eq!(opts.std, Std::C99);
3595 assert!(!opts.gnu_extensions);
3596
3597 let (opts, _) = compile(&["-ansi", "a.c"]);
3598 assert_eq!(opts.std, Std::C89);
3599 assert!(!opts.gnu_extensions);
3600
3601 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
3602 assert!(e.message.contains("unknown dialect"), "{}", e.message);
3603 }
3604
3605 #[test]
3606 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
3607 let (opts, _) = compile(&["-dM", "a.c"]);
3608 assert!(opts.dumps.macros);
3609
3610 // Packed, the way GCC takes them, and a letter in the family we have not written yet
3611 // is accepted and does nothing rather than failing a build.
3612 let (opts, _) = compile(&["-dDM", "a.c"]);
3613 assert!(opts.dumps.macros);
3614 let (opts, _) = compile(&["-dD", "a.c"]);
3615 assert!(!opts.dumps.macros);
3616
3617 let (opts, _) = compile(&["a.c"]);
3618 assert!(!opts.dumps.any());
3619
3620 // `-dumpversion` is a different flag that happens to start the same way, and it is read
3621 // as itself rather than as a dump of nothing.
3622 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
3623 }
3624
3625 #[test]
3626 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
3627 let (opts, _) = compile(&["a.c"]);
3628 assert_eq!(
3629 opts.gnuc,
3630 GnucVersion { major: 7, minor: 0, patch: 0 },
3631 "the lowest claim a modern glibc gives its own declarations to"
3632 );
3633
3634 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
3635 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
3636
3637 // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
3638 // patchlevel and a harness that pastes that back has to be understood.
3639 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
3640 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
3641
3642 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
3643 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
3644
3645 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
3646 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
3647
3648 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
3649 assert!(e.message.contains("more than three"), "{}", e.message);
3650 }
3651
3652 #[test]
3653 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
3654 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
3655 assert!(opts.pedantic);
3656 assert_eq!(opts.std, Std::C17);
3657
3658 // The `-W` family's name for it, which is what a build that groups its warning flags
3659 // tends to write.
3660 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
3661 assert!(opts.pedantic);
3662
3663 let (opts, _) = compile(&["-std=c17", "a.c"]);
3664 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
3665 }
3666
3667 #[test]
3668 fn dash_p_and_dash_ffreestanding_reach_the_options() {
3669 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
3670 assert!(!opts.line_markers);
3671 assert!(!opts.hosted);
3672 assert_eq!(opts.emit, EmitKind::Preprocessed);
3673 }
3674
3675 /// The two ways a build says it means its own function by a name the C library also has.
3676 ///
3677 /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
3678 /// build writes when it means its own `memcpy` and the library's everything else. The name is
3679 /// kept as it was written and not checked against anything, because a program is allowed to
3680 /// mean something by a name this compiler has never heard of.
3681 #[test]
3682 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
3683 let (opts, _) = compile(&["-c", "a.c"]);
3684 assert!(opts.builtins, "a library name means the library function by default");
3685 assert!(opts.no_builtin.is_empty());
3686
3687 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
3688 assert!(!opts.builtins);
3689
3690 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
3691 assert!(opts.builtins, "the last mention decides");
3692
3693 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
3694 assert!(opts.builtins, "one name is not the family");
3695 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
3696 }
3697
3698 /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
3699 /// and which was refused as an unknown option until now.
3700 ///
3701 /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
3702 /// the address across a component boundary, and nothing derives anything from that promise
3703 /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
3704 /// over a distinction this compiler does not make.
3705 #[test]
3706 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
3707 let (opts, _) = compile(&["-c", "a.c"]);
3708 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
3709
3710 for (written, wanted) in [
3711 ("default", Visibility::Default),
3712 ("hidden", Visibility::Hidden),
3713 ("internal", Visibility::Hidden),
3714 ("protected", Visibility::Protected),
3715 ] {
3716 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
3717 assert_eq!(opts.visibility, wanted, "{written}");
3718 }
3719
3720 // The last mention decides, which is what every other flag of this shape does and what a
3721 // build that turns something off for one directory relies on.
3722 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
3723 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
3724
3725 // A spelling gcc does not take is refused rather than read as the default, because a
3726 // build that meant hidden and got exported is a library with the wrong interface and
3727 // nothing said about it anywhere.
3728 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
3729 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
3730 }
3731
3732 /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
3733 /// described, and the values are gcc 16's three.
3734 #[test]
3735 fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
3736 let (opts, _) = compile(&["-c", "a.c"]);
3737 assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
3738
3739 for (written, wanted) in
3740 [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
3741 {
3742 let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
3743 assert_eq!(opts.fp_contract, wanted, "{written}");
3744 }
3745
3746 let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
3747 assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
3748
3749 // Refused rather than read as one of the three, because a build that asked for no fusing
3750 // and was given the default would be one whose numbers change and whose command line says
3751 // they should not. gcc refuses the same spellings and names the same three in its message.
3752 for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
3753 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
3754 assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
3755 }
3756
3757 // And the other one that takes a value, which is taken and kept nowhere: every operation
3758 // here is computed in the type it was written in, so `standard` is what happens and the
3759 // other two are permission to do something this does not do.
3760 let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
3761 assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
3762 }
3763
3764 /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
3765 /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
3766 /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
3767 #[test]
3768 fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
3769 let (opts, _) = compile(&["-c", "a.c"]);
3770 assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
3771 assert!(opts.prefix_map.debug.is_empty(), "nor here");
3772 assert!(opts.prefix_map.profile.is_empty(), "nor here");
3773
3774 let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
3775 assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
3776 assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
3777
3778 let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
3779 assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
3780 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
3781
3782 let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
3783 assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
3784 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
3785
3786 let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
3787 for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
3788 assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
3789 }
3790
3791 // Every mention is kept and the last one that matches wins, unlike the flags above whose
3792 // last mention replaces the earlier ones. A build writes one of these per source root and
3793 // expects all of them to be in force, which is the whole point of a list.
3794 let (opts, _) =
3795 compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
3796 assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
3797 assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
3798
3799 // An argument with no `=` is refused rather than ignored, because a build whose paths were
3800 // meant to be rewritten and were not is one that ships the build directory's name and says
3801 // nothing about it. gcc refuses the same thing.
3802 for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
3803 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
3804 assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
3805 }
3806 }
3807
3808 /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
3809 /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
3810 /// one. A kernel and an embedded image are both linked that way.
3811 ///
3812 /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
3813 /// the other is a build that measured something: splitting the code is nearly free at link time
3814 /// and splitting the data can defeat the linker's ordering of what is next to what.
3815 #[test]
3816 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
3817 let (opts, _) = compile(&["-c", "a.c"]);
3818 assert!(!opts.function_sections, "one text section unless something says otherwise");
3819 assert!(!opts.data_sections);
3820
3821 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
3822 assert!(opts.function_sections);
3823 assert!(!opts.data_sections, "one flag is not the other");
3824
3825 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
3826 assert!(opts.data_sections);
3827 assert!(!opts.function_sections);
3828
3829 // Both directions taken, and the off one is what happens anyway rather than a refusal,
3830 // since a build that writes it is asking for the default.
3831 let (opts, _) = compile(&[
3832 "-c",
3833 "-ffunction-sections",
3834 "-fno-function-sections",
3835 "-fdata-sections",
3836 "-fno-data-sections",
3837 "a.c",
3838 ]);
3839 assert!(!opts.function_sections, "the last mention decides");
3840 assert!(!opts.data_sections, "the last mention decides");
3841 }
3842
3843 /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
3844 /// line, since the dialect asks for GNU's reading further in rather than through this.
3845 #[test]
3846 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
3847 let (opts, _) = compile(&["-c", "a.c"]);
3848 assert!(!opts.gnu89_inline, "C's reading of inline by default");
3849
3850 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
3851 assert!(opts.gnu89_inline);
3852
3853 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
3854 assert!(!opts.gnu89_inline, "the last mention decides");
3855
3856 // The C89 dialects are under GNU's reading whether this was written or not, so the flag
3857 // stays off there and the dialect is what the checker and the macro set both ask. That is
3858 // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
3859 // dialect already has. gcc refuses that command line, which is measured in the issue.
3860 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
3861 assert!(!opts.gnu89_inline);
3862 }
3863
3864 /// Both spellings of both frame flags, since a build that wants one usually writes the
3865 /// other beside it for the one file that has to be compiled the ordinary way.
3866 #[test]
3867 fn the_two_frame_flags_are_read_in_both_directions() {
3868 let (opts, _) = compile(&["-c", "a.c"]);
3869 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
3870 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
3871
3872 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
3873 assert!(opts.frame_pointer);
3874 assert!(!opts.red_zone);
3875
3876 let (opts, _) = compile(&[
3877 "-c",
3878 "-fno-omit-frame-pointer",
3879 "-fomit-frame-pointer",
3880 "-mno-red-zone",
3881 "-mred-zone",
3882 "a.c",
3883 ]);
3884 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
3885 assert!(opts.red_zone);
3886 }
3887
3888 /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
3889 /// spelled three ways because a build that turns one off writes whichever it turned on.
3890 #[test]
3891 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
3892 let (opts, _) = compile(&["-c", "a.c"]);
3893 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
3894
3895 for (flag, want) in [
3896 ("-fstack-protector", Protector::Buffers),
3897 ("-fstack-protector-strong", Protector::Strong),
3898 ("-fstack-protector-all", Protector::All),
3899 ] {
3900 let (opts, _) = compile(&["-c", flag, "a.c"]);
3901 assert_eq!(opts.protector, want, "{flag}");
3902 }
3903
3904 // What a package build does: the strong one in the global flags and one directory that
3905 // cannot have a protector turning it off on the line after.
3906 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
3907 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
3908 assert_eq!(opts.protector, Protector::None, "{off}");
3909 }
3910 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
3911 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
3912 }
3913
3914 /// A switch rather than a level, because how a frame is taken is one question and which
3915 /// functions get a canary is another, and gcc spells it that way for the same reason.
3916 #[test]
3917 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
3918 let (opts, _) = compile(&["-c", "a.c"]);
3919 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
3920
3921 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
3922 assert!(opts.stack_clash);
3923
3924 // The same shape a package build uses for the protector: on in the global flags and off
3925 // for the one directory that cannot have it.
3926 let (opts, _) =
3927 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
3928 assert!(!opts.stack_clash);
3929 let (opts, _) =
3930 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
3931 assert!(opts.stack_clash, "the last one wins either way round");
3932
3933 // The two are independent, since one is about the frame and the other about the function.
3934 let (opts, _) =
3935 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
3936 assert!(opts.stack_clash);
3937 assert_eq!(opts.protector, Protector::Strong);
3938 }
3939
3940 /// One flag with an argument rather than a family of spellings, because what it asks about is
3941 /// which of the two edges of a control flow transfer is checked and the two are not separate
3942 /// questions to the hardware.
3943 #[test]
3944 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
3945 let (opts, _) = compile(&["-c", "a.c"]);
3946 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
3947
3948 for (arg, want) in [
3949 ("-fcf-protection", Control::Full),
3950 ("-fcf-protection=full", Control::Full),
3951 ("-fcf-protection=branch", Control::Branch),
3952 ("-fcf-protection=return", Control::Return),
3953 ("-fcf-protection=none", Control::None),
3954 ("-fcf-protection=check", Control::Check),
3955 ] {
3956 let (opts, _) = compile(&["-c", arg, "a.c"]);
3957 assert_eq!(opts.control, want, "{arg}");
3958 }
3959
3960 // The shape a package build uses: on in the global flags and off for the one directory
3961 // that cannot have it, whichever of the two spellings of off it reaches for.
3962 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
3963 assert_eq!(opts.control, Control::None);
3964 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
3965 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
3966 }
3967
3968 /// The profiler is asked for by two spellings, and where its hook goes by two more.
3969 ///
3970 /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
3971 /// asks for no call, which is what gcc does with it, and a build system that sets it globally
3972 /// and asks for the profile per directory needs that to be true rather than an error.
3973 ///
3974 /// The link is asserted alongside, because the flag changes it too and a build that compiled
3975 /// with it and linked without it is a program that calls the hook everywhere and never writes a
3976 /// profile.
3977 #[test]
3978 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
3979 let (opts, _) = compile(&["-c", "a.c"]);
3980 assert!(!opts.profile);
3981 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
3982
3983 for arg in ["-pg", "-p"] {
3984 let (opts, _) = compile(&["-c", arg, "a.c"]);
3985 assert!(opts.profile, "{arg}");
3986 let (link, _) = linking(&[arg, "a.c"]);
3987 assert!(link.profile, "{arg} changes the link as well");
3988 }
3989
3990 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
3991 let (opts, _) = compile(&["-c", arg, "a.c"]);
3992 assert_eq!(opts.hook, want, "{arg}");
3993 assert!(!opts.profile, "{arg} asks for no call of its own");
3994 }
3995
3996 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
3997 assert_eq!(opts.hook, Hook::Late, "the last one wins");
3998 assert!(opts.profile);
3999 }
4000
4001 /// How much room a patcher is promised, which is one number or two.
4002 ///
4003 /// A command line that did not ask is asserted alongside, because the flag has to be written to
4004 /// mean anything and a build that reserved room nobody asked for would grow every function in
4005 /// it for nothing.
4006 #[test]
4007 fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
4008 let (opts, _) = compile(&["-c", "a.c"]);
4009 assert_eq!(opts.patchable, Patchable::default());
4010 assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
4011
4012 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
4013 assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
4014
4015 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
4016 assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
4017 assert_eq!(opts.patchable.after(), 2);
4018
4019 // The last one wins, which is what every other flag of this shape does and what a build
4020 // that adds one to a command line it did not write is relying on.
4021 let (opts, _) = compile(&[
4022 "-c",
4023 "-fpatchable-function-entry=5,3",
4024 "-fpatchable-function-entry=2",
4025 "a.c",
4026 ]);
4027 assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
4028 }
4029
4030 /// And a request nothing could satisfy is refused rather than rounded into one that can be.
4031 #[test]
4032 fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
4033 for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
4034 let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
4035 assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
4036 }
4037 }
4038
4039 /// What wraps rather than being undefined, which is two questions and three flags.
4040 ///
4041 /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
4042 /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
4043 /// only what it asked for.
4044 #[test]
4045 fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
4046 let (opts, _) = compile(&["-c", "a.c"]);
4047 assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
4048
4049 let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
4050 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
4051
4052 let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
4053 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
4054
4055 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
4056 assert_eq!(opts.wrapping, Wrapping::ALL);
4057
4058 // And the last one wins, in both directions. A build that turns one of these on globally
4059 // and off for one directory is relying on that, and so is one that writes the pair and
4060 // then takes half of it back.
4061 let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
4062 assert_eq!(opts.wrapping, Wrapping::NONE);
4063
4064 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
4065 assert_eq!(opts.wrapping, Wrapping::NONE);
4066
4067 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
4068 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
4069 }
4070
4071 /// And the other answer to the signed question cannot be held at the same time as the first.
4072 ///
4073 /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
4074 /// resolves it by letting the last one win rather than by reporting anything. That was measured
4075 /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
4076 /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
4077 #[test]
4078 fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
4079 let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
4080 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
4081
4082 let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
4083 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
4084
4085 let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
4086 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
4087
4088 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
4089 assert_eq!(opts.wrapping, Wrapping::ALL);
4090
4091 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
4092 assert_eq!(opts.wrapping, Wrapping::NONE);
4093
4094 // And the flag that says what may be assumed says nothing about what happens, so it leaves
4095 // this alone where it takes the wrapping away. gcc does the same.
4096 let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
4097 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
4098 }
4099
4100 /// What a plain `char` is, which is four spellings of two answers and nothing by default.
4101 ///
4102 /// Nothing is the target's own answer and has to stay distinct from both of the others, since
4103 /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
4104 /// The negative spellings are the other flag rather than a way of asking for the default, which
4105 /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
4106 /// `-fno-unsigned-char` does not.
4107 #[test]
4108 fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
4109 let (opts, _) = compile(&["-c", "a.c"]);
4110 assert_eq!(opts.char_signed, None);
4111
4112 for flag in ["-fsigned-char", "-fno-unsigned-char"] {
4113 let (opts, _) = compile(&["-c", flag, "a.c"]);
4114 assert_eq!(opts.char_signed, Some(true), "{flag}");
4115 }
4116
4117 for flag in ["-funsigned-char", "-fno-signed-char"] {
4118 let (opts, _) = compile(&["-c", flag, "a.c"]);
4119 assert_eq!(opts.char_signed, Some(false), "{flag}");
4120 }
4121
4122 // And the last one wins, which is what a build that sets one globally and the other for a
4123 // directory relies on.
4124 let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
4125 assert_eq!(opts.char_signed, Some(true));
4126
4127 // And what is asked for reaches the target, because that is what every other part of the
4128 // compiler asks. The triple is one whose own answer is the opposite, so a session that
4129 // ignored the flag would still read as signed here.
4130 let (opts, _) =
4131 compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
4132 assert!(Session::new(*opts).target.char_is_signed);
4133 let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
4134 assert!(!Session::new(*opts).target.char_is_signed);
4135 }
4136
4137 /// And the size of an enumeration, which is one question with two spellings.
4138 #[test]
4139 fn the_smallest_enumeration_is_asked_for_and_taken_back() {
4140 let (opts, _) = compile(&["-c", "a.c"]);
4141 assert!(!opts.short_enums);
4142
4143 let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
4144 assert!(opts.short_enums);
4145
4146 let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
4147 assert!(!opts.short_enums);
4148
4149 let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
4150 assert!(opts.short_enums);
4151 }
4152
4153 /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
4154 ///
4155 /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
4156 /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
4157 /// family would report it as an unknown pass. Neither is the news the build wants.
4158 #[test]
4159 fn a_control_flow_protection_nothing_means_is_refused() {
4160 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
4161 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
4162 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
4163 }
4164
4165 #[test]
4166 fn the_link_flags_are_collected_apart_from_the_compilation() {
4167 let (link, _) = linking(&[
4168 "-static",
4169 "-nostartfiles",
4170 "-rdynamic",
4171 "-s",
4172 "-fuse-ld=mold",
4173 "-L/opt/lib",
4174 "-B",
4175 "/opt/tools",
4176 "a.c",
4177 ]);
4178 assert!(link.is_static);
4179 assert!(link.no_startfiles);
4180 assert!(link.export_dynamic);
4181 assert!(link.strip);
4182 assert_eq!(link.use_ld.as_deref(), Some("mold"));
4183 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
4184 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
4185 }
4186
4187 #[test]
4188 fn a_comma_in_dash_wl_separates_two_arguments() {
4189 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
4190 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
4191 }
4192
4193 #[test]
4194 fn a_library_keeps_its_place_between_the_objects() {
4195 // Link order is semantic: `-lm` written between two files resolves for the one before
4196 // it and not for the one after, so a library cannot be collected into a list of its own.
4197 // The target is named because the suffix of an object is the target's and this asserts
4198 // on the names: the same command line on a Windows host plans two `.obj` files.
4199 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
4200 let link = plan.link.expect("expected a link step");
4201 assert_eq!(
4202 link.inputs,
4203 vec![
4204 link::Item::File("a.o".into()),
4205 link::Item::Library("m".into()),
4206 link::Item::File("b.o".into()),
4207 ]
4208 );
4209 // And it is not a job, because there is nothing to compile in a library.
4210 assert_eq!(plan.jobs.len(), 2);
4211 }
4212
4213 #[test]
4214 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
4215 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
4216 assert!(plan.link.is_none());
4217 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
4218 }
4219
4220 #[test]
4221 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
4222 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
4223 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
4224 }
4225
4226 fn printed(s: &[&str]) -> String {
4227 match parse_args(&args(s)).expect("expected an answer") {
4228 Action::Print(line) => line,
4229 other => panic!("expected an answer, got {other:?}"),
4230 }
4231 }
4232
4233 fn refused(s: &[&str]) -> String {
4234 parse_args(&args(s)).expect_err("expected a refusal").message
4235 }
4236
4237 #[test]
4238 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
4239 // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
4240 // out whether a warning flag exists by passing it and looking at the exit status, so a
4241 // compiler that refuses one it does not know fails a script written for a newer GCC.
4242 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
4243 assert!(!opts.warnings_are_errors);
4244 assert!(opts.warnings);
4245 // The two spellings that do mean something are still read.
4246 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
4247 assert!(opts.warnings_are_errors);
4248 let (opts, _) = compile(&["-w", "-c", "a.c"]);
4249 assert!(!opts.warnings);
4250 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
4251 assert!(opts.pedantic && opts.warnings_are_errors);
4252 }
4253
4254 #[test]
4255 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
4256 // Every one of these says something about the output, so the wrong answer is silence.
4257 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
4258 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
4259 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
4260 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
4261 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
4262 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
4263 // The word size the target does not have, which is a target this compiler was not asked
4264 // for rather than a flag it does not know.
4265 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
4266 assert!(no32.contains("32 bit target"), "{no32}");
4267 }
4268
4269 /// `-gz` and the two spellings of the split, which are the two questions about the shape of
4270 /// the debug output rather than about how much of it there is.
4271 ///
4272 /// Both answers here are about what happens when there is debug information to shape, and
4273 /// there is none yet, so what is being asserted is that the flags are read and remembered
4274 /// rather than that anything changed in the output. That is the whole of what taking them
4275 /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
4276 /// it comes to find out what the command line said.
4277 #[test]
4278 fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
4279 let (opts, _) = compile(&["-c", "a.c"]);
4280 assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
4281
4282 // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
4283 // which describes the flag without ever saying which algorithm it picks.
4284 assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
4285 for (spelling, want) in [
4286 ("none", Compress::None),
4287 ("zlib", Compress::Zlib),
4288 ("zlib-gnu", Compress::ZlibGnu),
4289 ("zstd", Compress::Zstd),
4290 ] {
4291 let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
4292 assert_eq!(opts.compress, want, "{spelling}");
4293 }
4294
4295 // A value nothing here has heard of is refused rather than rounded to the nearest one,
4296 // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
4297 // reader may not understand and would have no way of finding out.
4298 for bad in ["-gz=gzip", "-gz="] {
4299 let failed = refused(&[bad, "-c", "a.c"]);
4300 assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
4301 }
4302
4303 // The split is refused in the direction that would have written a file and taken in the
4304 // direction that describes what happens. A build system that names the `.dwo` as an
4305 // output has to hear about it now rather than at the point the file is missing.
4306 let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
4307 assert!(opts.debug_info, "the negative spelling says nothing about how much");
4308 let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
4309 assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
4310 }
4311
4312 /// The `-flto` family, which is the whole of an optimization this compiler does not do.
4313 ///
4314 /// Taken rather than refused because ignoring it gives a correct program that is slower than
4315 /// it could have been, which is section 4.1's hint about speed. The values are still held to
4316 /// gcc's, so a command line written for clang is told rather than quietly taken.
4317 #[test]
4318 fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
4319 let (opts, _) = compile(&["-c", "a.c"]);
4320 assert!(!opts.lto.requested, "nothing asks unless the command line does");
4321
4322 let (opts, _) = compile(&["-flto", "-c", "a.c"]);
4323 assert!(opts.lto.requested);
4324 assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
4325
4326 // The last of the two directions wins, the same as every other pair of `-f` spellings.
4327 assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
4328 assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
4329
4330 // A count is a count, and asking for one implies asking for the optimization.
4331 for (spelling, want) in [
4332 ("auto", LtoJobs::Auto),
4333 ("jobserver", LtoJobs::Jobserver),
4334 ("1", LtoJobs::One),
4335 ("8", LtoJobs::Count(8)),
4336 ] {
4337 let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
4338 assert_eq!(opts.lto.jobs, want, "{spelling}");
4339 assert!(opts.lto.requested, "{spelling} asks for it too");
4340 }
4341
4342 // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
4343 // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
4344 // different compiler and gets told so here rather than getting a serial link.
4345 for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
4346 let failed = refused(&[bad, "-c", "a.c"]);
4347 assert!(failed.contains("link time jobs"), "{bad}: {failed}");
4348 }
4349
4350 // How the program is cut up before the work is spread over it.
4351 assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
4352 for (spelling, want) in [
4353 ("balanced", Partition::Balanced),
4354 ("1to1", Partition::OneToOne),
4355 ("one", Partition::One),
4356 ("max", Partition::Max),
4357 ("none", Partition::None),
4358 ] {
4359 let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
4360 assert_eq!(opts.lto.partition, want, "{spelling}");
4361 }
4362 assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
4363
4364 // And how hard the bytecode is compressed on its way into the object, which is zstd's
4365 // range of levels and is the range gcc checks an argument against.
4366 assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
4367 assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
4368 let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
4369 assert_eq!(opts.lto.compression, Some(19));
4370 for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
4371 let failed = refused(&[bad, "-c", "a.c"]);
4372 assert!(failed.contains("compression level"), "{bad}: {failed}");
4373 }
4374
4375 // The two pairs that describe an arrangement rather than ask for one. Every object here
4376 // holds its machine code, so the fat spelling is what already happens and the other is a
4377 // smaller file rather than a different program, and the plugin pair is about a tool the
4378 // design in `spec/09-optimizer.md` never loads.
4379 for taken in [
4380 "-ffat-lto-objects",
4381 "-fno-fat-lto-objects",
4382 "-fuse-linker-plugin",
4383 "-fno-use-linker-plugin",
4384 ] {
4385 let (opts, _) = compile(&[taken, "-c", "a.c"]);
4386 assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
4387 }
4388 }
4389
4390 /// The profile family, which is the only one here that splits down the middle.
4391 ///
4392 /// Reading a profile is taken and writing one is refused, and the line between them is the one
4393 /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
4394 /// slower than it could have been, and ignoring a request to write them means a file the build
4395 /// declared as an output never appears.
4396 #[test]
4397 fn reading_a_profile_is_taken_and_writing_one_is_refused() {
4398 let (opts, _) = compile(&["-c", "a.c"]);
4399 assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
4400 assert_eq!(opts.profile_data.path, None);
4401
4402 let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
4403 assert!(opts.profile_data.requested);
4404 assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
4405
4406 let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
4407 assert!(opts.profile_data.requested, "naming a path asks for it too");
4408 assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
4409
4410 // The last of the two directions wins, the same as every other pair of `-f` spellings.
4411 assert!(
4412 !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
4413 );
4414 assert!(
4415 compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
4416 );
4417
4418 // The rest of the reading half, which is where the files are and three answers about what
4419 // to make of what is in them.
4420 let (opts, _) = compile(&[
4421 "-fprofile-dir=/build/profiles",
4422 "-fprofile-abs-path",
4423 "-fprofile-correction",
4424 "-fprofile-partial-training",
4425 "-c",
4426 "a.c",
4427 ]);
4428 assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
4429 assert!(opts.profile_data.absolute);
4430 assert!(opts.profile_data.correction);
4431 assert!(opts.profile_data.partial_training);
4432
4433 // Writing one, which is refused by name. The first four instrument the program and the
4434 // last writes a file beside the object, and a build that got neither and no message would
4435 // go on to optimize against counts that were never gathered.
4436 for writing in [
4437 "-fprofile-generate",
4438 "-fprofile-generate=/build/profiles",
4439 "-fprofile-arcs",
4440 "--coverage",
4441 "-fcondition-coverage",
4442 "-fpath-coverage",
4443 ] {
4444 let failed = refused(&[writing, "-c", "a.c"]);
4445 assert!(failed.contains("instrument"), "{writing}: {failed}");
4446 }
4447 assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
4448
4449 // The negative spellings of the refused half are what already happens, so they are taken.
4450 for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
4451 let (opts, _) = compile(&[taken, "-c", "a.c"]);
4452 assert!(!opts.profile_data.requested, "{taken} asks for nothing");
4453 }
4454
4455 // And the flags that describe the instrumentation that is refused above, which are checked
4456 // and dropped. Checked because a typo is worth finding here rather than on the day the
4457 // instrumentation lands.
4458 for taken in [
4459 "-fprofile-update=single",
4460 "-fprofile-update=atomic",
4461 "-fprofile-update=prefer-atomic",
4462 "-fprofile-reproducible=serial",
4463 "-fprofile-reproducible=parallel-runs",
4464 "-fprofile-reproducible=multithreaded",
4465 "-fprofile-values",
4466 "-fno-profile-values",
4467 "-fprofile-info-section",
4468 "-fprofile-filter-files=a.c",
4469 "-fprofile-exclude-files=b.c",
4470 "-fprofile-note=a.gcno",
4471 ] {
4472 let (opts, _) = compile(&[taken, "-c", "a.c"]);
4473 assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
4474 }
4475 assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
4476 assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
4477 }
4478
4479 /// The sanitizers, which are refused by name and are the one family refused for a reason that
4480 /// is not about the bytes.
4481 ///
4482 /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
4483 /// for one and was quietly given a program with no checks in it gets a test suite that passes
4484 /// for the wrong reason rather than a slower program.
4485 #[test]
4486 fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
4487 for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
4488 let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
4489 assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
4490 assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
4491 }
4492
4493 // A list is every name in it, and the first one still standing is the one named.
4494 let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
4495 assert!(failed.contains("address"), "{failed}");
4496
4497 // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
4498 // with a typo in it has a different problem from somebody who wrote a real one.
4499 for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
4500 let failed = refused(&[bad, "-c", "a.c"]);
4501 assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
4502 }
4503
4504 // gcc takes `all` only in the negative, and so does this.
4505 assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
4506
4507 // Asking and then taking it back is asking for nothing, which is why the answer waits for
4508 // the end of the line. A build whose shared flags turn a check on and whose rule for one
4509 // file turns it off again compiles that file here.
4510 for pair in [
4511 ["-fsanitize=address", "-fno-sanitize=address"],
4512 ["-fsanitize=address,undefined", "-fno-sanitize=all"],
4513 ["-fsanitize=undefined", "-fno-sanitize=undefined"],
4514 ] {
4515 let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
4516 assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
4517 }
4518 // And the other order still asks, because the last word is the one that counts.
4519 assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
4520
4521 // What a check does when it fires is an answer about checks that are refused, so there is
4522 // nothing left for it to change and it is taken.
4523 for taken in [
4524 "-fsanitize-recover=undefined",
4525 "-fno-sanitize-recover=all",
4526 "-fsanitize-trap=undefined",
4527 "-fno-sanitize-trap=all",
4528 "-fsanitize-undefined-trap-on-error",
4529 "-fsanitize-address-use-after-scope",
4530 "-fno-sanitize-address-use-after-scope",
4531 "-fsanitize-sections=.data",
4532 ] {
4533 let (opts, _) = compile(&[taken, "-c", "a.c"]);
4534 assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
4535 }
4536 assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
4537
4538 // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
4539 // feedback runs blind and never says so.
4540 let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
4541 assert!(failed.contains("feedback"), "{failed}");
4542 let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
4543 assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
4544 }
4545
4546 #[test]
4547 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
4548 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
4549 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
4550 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
4551 }
4552
4553 #[test]
4554 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
4555 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
4556 let (opts, _) =
4557 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
4558 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
4559 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
4560 assert!(wrong.contains("sysv convention"), "{wrong}");
4561 }
4562
4563 #[test]
4564 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
4565 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
4566 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
4567 // After the input, because a static link takes what it needs from a library when it
4568 // reaches it and not afterwards.
4569 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
4570 assert_eq!(names, vec!["a.c"]);
4571 }
4572
4573 #[test]
4574 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
4575 let target = "--target=x86_64-unknown-linux-gnu";
4576 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
4577 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
4578 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
4579 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
4580 // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
4581 // answer safe to paste into a link line whether or not the file is there.
4582 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
4583 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
4584 let dirs = printed(&[target, "-print-search-dirs"]);
4585 assert!(dirs.starts_with("install: "), "{dirs}");
4586 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
4587 }
4588
4589 #[test]
4590 fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
4591 // A tree the user named is the answer whatever the target is, because it is the answer to
4592 // every other question too.
4593 assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
4594
4595 // A target that is no machine this suite runs on is read under the cache, and the answer is
4596 // the root rather than one of the directories under it, since what asks is looking for a
4597 // file of its own.
4598 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
4599 assert_eq!(
4600 printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
4601 root.display().to_string()
4602 );
4603
4604 // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
4605 // was configured without one rather than a `/` that would be a claim about the filesystem.
4606 let host = Triple::host().expect("a host this compiler knows");
4607 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot"]), "");
4608 }
4609
4610 #[test]
4611 fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
4612 // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
4613 // is the record that already has them, so the flag prints that rather than a second format.
4614 let manifest = "rucc sysroot manifest 3\n\
4615 target\tx86_64-linux-musl\n\
4616 kernel\t6.12\n\
4617 include/generic/stdio.h\tmusl-1.2.5\t\
4618 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
4619 0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
4620 bundled\n\
4621 lib/libc.so\tmusl-1.2.5\t\
4622 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
4623 1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
4624 generated\n";
4625 let tree = TempTree::new("provenance", &[("manifest", manifest)]);
4626 let sysroot = format!("--sysroot={}", tree.0.display());
4627 // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
4628 // the flag parses the record and renders it again rather than picking fields out of it. That
4629 // is the reason it prints a manifest and not a format of its own.
4630 //
4631 // The answer is the file without its last newline, because whatever prints it adds one. The
4632 // file is what somebody diffs the output against, so the two have to be the same bytes.
4633 assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
4634
4635 // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
4636 // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
4637 // tell it from a manifest with no inputs because that one still has its two header lines.
4638 let bare = TempTree::new("provenance-bare", &[]);
4639 assert_eq!(
4640 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
4641 ""
4642 );
4643
4644 // And a compile for this machine has no sysroot at all, which is the same empty answer
4645 // `-print-sysroot` gives for it.
4646 let host = Triple::host().expect("a host this compiler knows");
4647 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
4648
4649 // And the other spelling, which section 13.5 is the document that writes.
4650 assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
4651
4652 // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
4653 // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
4654 // the bytes it is over are the bytes of the file. The number here is that hash of the
4655 // fixture above, computed by `sha256sum` rather than by this compiler.
4656 assert_eq!(
4657 printed(&[&sysroot, "-print-sysroot-digest"]),
4658 "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
4659 );
4660 assert_eq!(
4661 printed(&[&sysroot, "--print-sysroot-digest"]),
4662 printed(&[&sysroot, "-print-sysroot-digest"])
4663 );
4664
4665 // And the two empty answers are empty here too, because a digest of nothing would read as a
4666 // claim about a sysroot rather than as the absence of one.
4667 assert_eq!(
4668 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
4669 ""
4670 );
4671 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
4672 }
4673
4674 #[test]
4675 fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
4676 // Passing a file we could not parse to whoever asked would make their parser the one that
4677 // finds the problem, and the three uses section 13.5 gives for this are all somebody else
4678 // parsing it.
4679 let tree = TempTree::new(
4680 "provenance-bad",
4681 &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
4682 );
4683 let message =
4684 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
4685 assert!(message.contains("manifest"), "{message}");
4686 assert!(message.contains("1 fields where an input has six"), "{message}");
4687
4688 // The digest is refused for the same file and for a stronger reason: a hash of bytes this
4689 // build cannot read would be a number that names a record nobody can act on.
4690 let digest =
4691 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
4692 assert_eq!(digest, message);
4693 }
4694
4695 #[test]
4696 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
4697 let (opts, _) = compile(&["-M", "a.c"]);
4698 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
4699 assert!(opts.deps.system_headers, "plain -M lists them");
4700 assert_eq!(opts.emit, EmitKind::Preprocessed);
4701
4702 // Even where a later flag asked for something else, because the family is a mode and
4703 // the mode is what the run is for.
4704 let (opts, _) = compile(&["-M", "-c", "a.c"]);
4705 assert_eq!(opts.emit, EmitKind::Preprocessed);
4706
4707 let (opts, _) = compile(&["-MM", "a.c"]);
4708 assert!(!opts.deps.system_headers);
4709 }
4710
4711 #[test]
4712 fn the_two_that_end_in_d_leave_the_compilation_alone() {
4713 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
4714 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
4715 assert!(opts.deps.system_headers);
4716 assert_eq!(opts.emit, EmitKind::Object);
4717
4718 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
4719 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
4720 assert!(!opts.deps.system_headers);
4721 }
4722
4723 #[test]
4724 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
4725 // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
4726 // the answer, because the other one never asked the question.
4727 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
4728 assert!(!opts.deps.system_headers);
4729 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
4730 assert!(!opts.deps.system_headers);
4731 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
4732 assert!(!opts.deps.system_headers);
4733 }
4734
4735 #[test]
4736 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
4737 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
4738 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
4739 }
4740
4741 #[test]
4742 fn the_rest_of_the_family_is_a_file_and_a_switch() {
4743 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
4744 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
4745 assert!(opts.deps.phony);
4746
4747 for flag in ["-MF", "-MT", "-MQ"] {
4748 let e = parse_args(&args(&[flag])).unwrap_err();
4749 assert!(e.message.contains("requires an argument"), "{}", e.message);
4750 }
4751 }
4752
4753 /// A directory of sources for one test, removed when the test is done with it.
4754 struct TempTree(PathBuf);
4755
4756 impl Drop for TempTree {
4757 fn drop(&mut self) {
4758 let _ = std::fs::remove_dir_all(&self.0);
4759 }
4760 }
4761
4762 impl TempTree {
4763 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
4764 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
4765 let _ = std::fs::remove_dir_all(&dir);
4766 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
4767 for (path, text) in files {
4768 let at = dir.join(path);
4769 if let Some(parent) = at.parent() {
4770 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
4771 }
4772 std::fs::write(&at, text).expect("writing a temporary file should work");
4773 }
4774 TempTree(dir)
4775 }
4776
4777 fn path(&self, name: &str) -> String {
4778 self.0.join(name).to_string_lossy().into_owned()
4779 }
4780 }
4781
4782 #[test]
4783 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
4784 // End to end, because the list comes from the preprocessor and the format comes from
4785 // somewhere else, and a test of either half on its own would pass with the two of them
4786 // wired up backwards.
4787 let tree = TempTree::new(
4788 "found",
4789 &[
4790 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
4791 ("one.h", "#define X 0\n"),
4792 ("two.h", "#include \"one.h\"\n"),
4793 ],
4794 );
4795 let out = tree.path("dep.d");
4796 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
4797 assert_eq!(code, 0);
4798
4799 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
4800 let names: Vec<&str> = text.split_whitespace().collect();
4801 // The target, the source, and each header once however many times it was reached.
4802 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
4803 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
4804 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
4805 // And the `-o` went to the file the rule replaced, which is left empty rather than
4806 // absent because a makefile that named it as a target will look for it.
4807 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
4808 }
4809
4810 #[test]
4811 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
4812 // The multiple-include optimization means the second reach never opens the file. It is
4813 // still a file this translation unit was built from, so it is still in the rule.
4814 let tree = TempTree::new(
4815 "guarded",
4816 &[
4817 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
4818 ("g.h", "#ifndef G\n#define G\n#endif\n"),
4819 ],
4820 );
4821 let out = tree.path("dep.d");
4822 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
4823 assert_eq!(code, 0);
4824 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
4825 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
4826 }
4827
4828 #[test]
4829 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
4830 // Measured against GCC rather than read: the two flags the other way round produce the
4831 // same output byte for byte, so the command line order between the two families does not
4832 // decide anything and the order within one does. The `-include` file here can only see
4833 // the definition if the `-imacros` file that was written after it ran first.
4834 let tree = TempTree::new(
4835 "preinclude",
4836 &[
4837 ("a.c", "int main(void) { return 0; }\n"),
4838 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
4839 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
4840 ],
4841 );
4842 let out = tree.path("a.i");
4843 let code = run(&args(&[
4844 "-E",
4845 "-include",
4846 &tree.path("i.h"),
4847 "-imacros",
4848 &tree.path("m.h"),
4849 "-o",
4850 &out,
4851 &tree.path("a.c"),
4852 ]));
4853 assert_eq!(code, 0);
4854 let text = std::fs::read_to_string(&out).expect("the output should have been written");
4855 assert!(text.contains("saw_it"), "{text}");
4856 // And the text of the `-imacros` file is thrown away, which is the whole difference
4857 // between the two flags.
4858 assert!(!text.contains("macros_text"), "{text}");
4859 }
4860
4861 #[test]
4862 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
4863 let tree = TempTree::new(
4864 "preinclude-deps",
4865 &[
4866 ("a.c", "int main(void) { return 0; }\n"),
4867 ("i.h", "int from_include;\n"),
4868 ("m.h", "#define M 1\n"),
4869 ],
4870 );
4871 let out = tree.path("dep.d");
4872 let code = run(&args(&[
4873 "-MM",
4874 "-MF",
4875 &out,
4876 "-include",
4877 &tree.path("i.h"),
4878 "-imacros",
4879 &tree.path("m.h"),
4880 "-o",
4881 &tree.path("a.i"),
4882 &tree.path("a.c"),
4883 ]));
4884 assert_eq!(code, 0);
4885 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
4886 assert!(text.contains("i.h"), "{text}");
4887 assert!(text.contains("m.h"), "{text}");
4888 }
4889
4890 #[test]
4891 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
4892 // Including the directory of the source file, which is not on the path for these: the
4893 // command line was not written there, so a name in it is relative to where the compiler
4894 // was run rather than to where the source sits.
4895 let tree = TempTree::new(
4896 "preinclude-missing",
4897 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
4898 );
4899 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
4900 assert_eq!(code, 1);
4901 }
4902
4903 #[test]
4904 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
4905 // The object a link goes through is in a temporary directory and is gone before `make`
4906 // reads any of this, so the rule that named it would be a rule for a file that is never
4907 // there. The target and the file are both the `-o`, which is the executable.
4908 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
4909 assert_eq!(plan.output.as_deref(), Some("prog"));
4910 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
4911 assert_eq!(
4912 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
4913 Some("prog.d")
4914 );
4915 }
4916
4917 #[test]
4918 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
4919 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
4920 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
4921 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
4922 assert_eq!(plan.output, None);
4923 }
4924
4925 #[test]
4926 fn usage_fits_on_a_screen() {
4927 // Not a style preference. A help text that scrolls is one nobody reads, and this is
4928 // the cheapest way to keep it honest as flags accumulate. The number goes up only when
4929 // a family of flags arrives that has nowhere to share a line, which the two pass gates
4930 // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
4931 // the lines that family took. The four it went up by last are the flags a build system
4932 // passes without being asked to: how much to say, what machine to generate for, threads,
4933 // and the questions `configure` asks before it compiles anything. The one it went up by
4934 // last is the second line of `--emit`, whose kinds are a family that has now outgrown
4935 // one line and has nowhere else to go. The two it went up by last are the dependency
4936 // family, which is eight flags that share nothing with anything above them. The one it
4937 // went up by last is the four spellings of position independent code, which every
4938 // configure script writes and which could only have shared the link line, and that line
4939 // is already four characters short of the limit. The two it went up by last are the rest
4940 // of the include family, which is six more flags that change where a header is looked for
4941 // and two that name a header outright. The one it went up by last is the pair that keeps
4942 // the intermediate files and times the steps, which belong next to the two flags above
4943 // them that are also about watching a compilation rather than changing one. The two it
4944 // went up by last are the section flags and the visibility flag, which are what a build
4945 // that cares about the size of what it ships and about which names it exports writes, and
4946 // the second of them was already taken and only missing from here. The one it went up by
4947 // last is the stack protector, which is four spellings of one question and which every
4948 // distribution puts on every command line it issues, so a build that reads this list
4949 // looking for it and does not find it has to go and read the specification instead. The one
4950 // it went up by last is the profiler, which is two spellings of the request and two of
4951 // where the call goes, and which is about watching a program run rather than about what is
4952 // generated, so it shares its subject with nothing above it. The one it went up by last is
4953 // the room a function opens with for something to be written over it later, which takes an
4954 // argument of its own shape and is what a kernel build asks for, so it fits beside the
4955 // profiler and nothing else. The one it went up by last is what overflows rather than being
4956 // undefined, which is three spellings of two questions and which a kernel build and a great
4957 // deal of code written before the standard settled both pass. The one it went up by last is
4958 // the other answer to the first of those questions, which could not share the line because
4959 // what it asks for is the opposite of what the flags on that line ask for. The one it went
4960 // up by last is the split of the line that lists what this compiler does anyway into that
4961 // and what it assumes anyway, which are two different claims that were sharing a line until
4962 // the second of them got a second flag and the line stopped fitting. The one it went up by
4963 // last is the three flags that change the ABI rather than the code, which have to be given
4964 // to every file in a program or none of them and which therefore belong somewhere a person
4965 // reading this list will see them. The one it went up by last is the floating point group,
4966 // which is two lines rather than one because the first of them is a choice this compiler
4967 // records and the rest are claims about what it does anyway, and putting a real setting on
4968 // the same line as three flags that change nothing would be misleading about both. The one
4969 // it went up by last is the flag that says a write has to stay inside the member it names,
4970 // which is a setting rather than a claim and so cannot share the line above it, that being
4971 // the one that picks a tier. The two it went up by last are the prefix mapping family,
4972 // which is four flags whose whole job is to keep a build's output the same from two
4973 // different directories, and which a person chasing a reproducible build comes here
4974 // looking for by name. The one it went up by last is how the debug sections are compressed
4975 // and whether they go in a file of their own, which are two questions about the shape of
4976 // the debug output, where the line above them is about how much of it there is. The one it
4977 // went up by last is the `restrict` contract, which is a setting for the same reason the
4978 // flag that keeps a write inside its member is and which is the check a person who has been
4979 // bitten by a vectorizer comes here looking for. The one it went up by last is link time
4980 // optimization, which is a whole optimization rather than a flag and which says so on its
4981 // own line, because a build that passes it and reads this looking for what it got is
4982 // asking a question no other line here answers. The one it went up by last is the sysroot,
4983 // which is the question somebody asks when a cross build read a file nobody expected, and
4984 // which has no room on the line above it because the answers there are a path each and this
4985 // one is the root all of them are under. The one it went up by last is what is inside that
4986 // root and where each of it came from, which is a question about a whole tree rather than
4987 // about a path and which is long enough on its own that it could not have shared a line with
4988 // anything. The one it went up by last is the profile family, which splits down the middle
4989 // where no other family here does, so the line has to name the half that is taken and the
4990 // half that is refused or it would be read as taking both. The one it went up by last is
4991 // the sanitizers, which are what somebody reaching for a checked build writes first and
4992 // which belong beside the tier that is the nearest thing here to what they asked for. The
4993 // one it went up by last is the digest of that record, which is the same tree as one number
4994 // and could not share the line above it because that line prints a few hundred lines and
4995 // this one prints sixty four characters, and a reader who wants the short answer is looking
4996 // for it by name rather than reading the long one.
4997 assert!(USAGE.lines().count() < 70, "usage text has grown past one screen");
4998 }
4999}