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