Debian Codegraph @

debian/rust-vendor/cc/src/flags.rs

raw
1 use crate::target::TargetInfo;
2 use crate::{Build, Error, ErrorKind, Tool, ToolFamily};
3 use std::borrow::Cow;
4 use std::ffi::OsString;
5
6 #[derive(Debug, PartialEq, Default)]
7 pub(crate) struct RustcCodegenFlags<'a> {
8 branch_protection: Option<&'a str>,
9 code_model: Option<&'a str>,
10 no_vectorize_loops: bool,
11 no_vectorize_slp: bool,
12 profile_generate: Option<&'a str>,
13 profile_use: Option<&'a str>,
14 control_flow_guard: Option<&'a str>,
15 lto: Option<&'a str>,
16 relocation_model: Option<&'a str>,
17 embed_bitcode: Option<bool>,
18 force_frame_pointers: Option<bool>,
19 no_redzone: Option<bool>,
20 soft_float: Option<bool>,
21 dwarf_version: Option<u32>,
22 stack_protector: Option<&'a str>,
23 linker_plugin_lto: Option<bool>,
24 }
25
26 impl<'this> RustcCodegenFlags<'this> {
27 // Parse flags obtained from CARGO_ENCODED_RUSTFLAGS
28 pub(crate) fn parse(rustflags_env: &'this str) -> Result<Self, Error> {
29 fn is_flag_prefix(flag: &str) -> bool {
30 [
31 "-Z",
32 "-C",
33 "--codegen",
34 "-L",
35 "-l",
36 "-o",
37 "-W",
38 "--warn",
39 "-A",
40 "--allow",
41 "-D",
42 "--deny",
43 "-F",
44 "--forbid",
45 ]
46 .contains(&flag)
47 }
48
49 fn handle_flag_prefix<'a>(prev: &'a str, curr: &'a str) -> (&'a str, &'a str) {
50 match prev {
51 "--codegen" | "-C" => ("-C", curr),
52 // Handle flags passed like --codegen=code-model=small
53 _ if curr.starts_with("--codegen=") => ("-C", &curr[10..]),
54 "-Z" => ("-Z", curr),
55 "-L" | "-l" | "-o" => (prev, curr),
56 // Handle lint flags
57 "-W" | "--warn" => ("-W", curr),
58 "-A" | "--allow" => ("-A", curr),
59 "-D" | "--deny" => ("-D", curr),
60 "-F" | "--forbid" => ("-F", curr),
61 _ => ("", curr),
62 }
63 }
64
65 let mut codegen_flags = Self::default();
66
67 let mut prev_prefix = None;
68 for curr in rustflags_env.split("\u{1f}") {
69 let prev = prev_prefix.take().unwrap_or("");
70 if prev.is_empty() && is_flag_prefix(curr) {
71 prev_prefix = Some(curr);
72 continue;
73 }
74
75 let (prefix, rustc_flag) = handle_flag_prefix(prev, curr);
76 codegen_flags.set_rustc_flag(prefix, rustc_flag)?;
77 }
78
79 Ok(codegen_flags)
80 }
81
82 fn set_rustc_flag(&mut self, prefix: &str, flag: &'this str) -> Result<(), Error> {
83 // Convert a textual representation of a bool-like rustc flag argument into an actual bool
84 fn arg_to_bool(arg: impl AsRef<str>) -> Option<bool> {
85 match arg.as_ref() {
86 "y" | "yes" | "on" | "true" => Some(true),
87 "n" | "no" | "off" | "false" => Some(false),
88 _ => None,
89 }
90 }
91
92 fn arg_to_u32(arg: impl AsRef<str>) -> Option<u32> {
93 arg.as_ref().parse().ok()
94 }
95
96 let (flag, value) = if let Some((flag, value)) = flag.split_once('=') {
97 (flag, Some(value))
98 } else {
99 (flag, None)
100 };
101 let flag = if prefix.is_empty() {
102 Cow::Borrowed(flag)
103 } else {
104 Cow::Owned(format!("{prefix}{flag}"))
105 };
106 let flag = flag.as_ref();
107
108 fn flag_not_empty_generic<T>(
109 flag: &str,
110 flag_value: Option<T>,
111 ) -> Result<Option<T>, Error> {
112 if let Some(flag_value) = flag_value {
113 Ok(Some(flag_value))
114 } else {
115 Err(Error::new(
116 ErrorKind::InvalidFlag,
117 format!("{flag} must have a value"),
118 ))
119 }
120 }
121 let flag_not_empty = |flag_value| flag_not_empty_generic(flag, flag_value);
122
123 match flag {
124 // https://doc.rust-lang.org/rustc/codegen-options/index.html#code-model
125 "-Ccode-model" => {
126 self.code_model = flag_not_empty(value)?;
127 }
128 // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-vectorize-loops
129 "-Cno-vectorize-loops" => self.no_vectorize_loops = true,
130 // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-vectorize-slp
131 "-Cno-vectorize-slp" => self.no_vectorize_slp = true,
132 // https://doc.rust-lang.org/rustc/codegen-options/index.html#profile-generate
133 "-Cprofile-generate" => {
134 self.profile_generate = flag_not_empty(value)?;
135 }
136 // https://doc.rust-lang.org/rustc/codegen-options/index.html#profile-use
137 "-Cprofile-use" => {
138 self.profile_use = flag_not_empty(value)?;
139 }
140 // https://doc.rust-lang.org/rustc/codegen-options/index.html#control-flow-guard
141 "-Ccontrol-flow-guard" => self.control_flow_guard = value.or(Some("true")),
142 // https://doc.rust-lang.org/rustc/codegen-options/index.html#lto
143 //
144 // This variable is currently unused, we just keep it in case we need it in future
145 "-Clto" => self.lto = value.or(Some("true")),
146 // https://doc.rust-lang.org/rustc/linker-plugin-lto.html
147 "-Clinker-plugin-lto" => self.linker_plugin_lto = Some(true),
148 // https://doc.rust-lang.org/rustc/codegen-options/index.html#relocation-model
149 "-Crelocation-model" => {
150 self.relocation_model = flag_not_empty(value)?;
151 }
152 // https://doc.rust-lang.org/rustc/codegen-options/index.html#embed-bitcode
153 "-Cembed-bitcode" => self.embed_bitcode = value.map_or(Some(true), arg_to_bool),
154 // https://doc.rust-lang.org/rustc/codegen-options/index.html#force-frame-pointers
155 "-Cforce-frame-pointers" => {
156 self.force_frame_pointers = value.map_or(Some(true), arg_to_bool)
157 }
158 // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-redzone
159 "-Cno-redzone" => self.no_redzone = value.map_or(Some(true), arg_to_bool),
160 // https://doc.rust-lang.org/rustc/codegen-options/index.html#soft-float
161 // Note: This flag is now deprecated in rustc.
162 "-Csoft-float" => self.soft_float = value.map_or(Some(true), arg_to_bool),
163 // https://doc.rust-lang.org/beta/unstable-book/compiler-flags/branch-protection.html
164 // FIXME: Drop the -Z variant and update the doc link once the option is stabilised
165 "-Zbranch-protection" | "-Cbranch-protection" => {
166 self.branch_protection = flag_not_empty(value)?;
167 }
168 // https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#dwarf-version
169 "-Cdwarf-version" => {
170 self.dwarf_version = flag_not_empty_generic(flag, value.and_then(arg_to_u32))?;
171 }
172 // https://github.com/rust-lang/rust/issues/114903
173 // FIXME: Drop the -Z variant and update the doc link once the option is stabilized
174 "-Zstack-protector" | "-Cstack-protector" => {
175 self.stack_protector = flag_not_empty(value)?;
176 }
177 _ => {}
178 }
179 Ok(())
180 }
181
182 // Rust and clang/cc don't agree on what equivalent flags should look like.
183 pub(crate) fn cc_flags(&self, build: &Build, tool: &mut Tool, target: &TargetInfo<'_>) {
184 let family = tool.family;
185 // Push `flag` to `flags` if it is supported by the currently used CC
186 let mut push_if_supported = |flag: OsString| {
187 if build
188 .is_flag_supported_inner(&flag, tool, target)
189 .unwrap_or(false)
190 {
191 tool.args.push(flag);
192 } else {
193 build.cargo_output.print_warning(&format!(
194 "Inherited flag {flag:?} is not supported by the currently used CC"
195 ));
196 }
197 };
198
199 let clang_or_gnu =
200 matches!(family, ToolFamily::Clang { .. }) || matches!(family, ToolFamily::Gnu);
201
202 // Flags shared between clang and gnu
203 if clang_or_gnu {
204 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mbranch-protection
205 // https://gcc.gnu.org/onlinedocs/gcc/AArch64-Options.html#index-mbranch-protection (Aarch64)
206 // https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html#index-mbranch-protection-1 (ARM)
207 // https://developer.arm.com/documentation/101754/0619/armclang-Reference/armclang-Command-line-Options/-mbranch-protection
208 if let Some(value) = self.branch_protection {
209 push_if_supported(
210 format!("-mbranch-protection={}", value.replace(",", "+")).into(),
211 );
212 }
213 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mcmodel
214 // https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html (several archs, search for `-mcmodel=`).
215 // FIXME(madsmtm): Parse the model, to make sure we pass the correct value (depending on arch).
216 if let Some(value) = self.code_model {
217 push_if_supported(format!("-mcmodel={value}").into());
218 }
219 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-vectorize
220 // https://gcc.gnu.org/onlinedocs/gnat_ugn/Vectorization-of-loops.html
221 if self.no_vectorize_loops {
222 push_if_supported("-fno-vectorize".into());
223 }
224 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-slp-vectorize
225 // https://gcc.gnu.org/onlinedocs/gnat_ugn/Vectorization-of-loops.html
226 if self.no_vectorize_slp {
227 push_if_supported("-fno-slp-vectorize".into());
228 }
229 if let Some(value) = self.relocation_model {
230 let cc_flag = match value {
231 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fPIC
232 // https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fPIC
233 "pic" => Some("-fPIC"),
234 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fPIE
235 // https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fPIE
236 "pie" => Some("-fPIE"),
237 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mdynamic-no-pic
238 // https://gcc.gnu.org/onlinedocs/gcc/RS_002f6000-and-PowerPC-Options.html#index-mdynamic-no-pic
239 "dynamic-no-pic" => Some("-mdynamic-no-pic"),
240 _ => None,
241 };
242 if let Some(cc_flag) = cc_flag {
243 push_if_supported(cc_flag.into());
244 }
245 }
246 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-omit-frame-pointer
247 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-momit-leaf-frame-pointer
248 // https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-fomit-frame-pointer
249 if let Some(value) = self.force_frame_pointers {
250 if value {
251 push_if_supported("-fno-omit-frame-pointer".into());
252 push_if_supported("-mno-omit-leaf-frame-pointer".into());
253 }
254 }
255 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mno-red-zone
256 // https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-mno-red-zone
257 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mred-zone
258 // https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-mred-zone
259 if let Some(value) = self.no_redzone {
260 let cc_flag = if value { "-mno-red-zone" } else { "-mred-zone" };
261 push_if_supported(cc_flag.into());
262 }
263 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-msoft-float
264 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mhard-float
265 // https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html (several archs, search for `-msoft-float`).
266 // https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html (several archs, search for `-mhard-float`).
267 if let Some(value) = self.soft_float {
268 let cc_flag = if value {
269 "-msoft-float"
270 } else {
271 // Do not use -mno-soft-float, that's basically just an alias for -mno-implicit-float.
272 "-mhard-float"
273 };
274 push_if_supported(cc_flag.into());
275 }
276 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-gdwarf-2
277 // https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-gdwarf
278 if let Some(value) = self.dwarf_version {
279 push_if_supported(format!("-gdwarf-{value}").into());
280 }
281 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fstack-protector
282 // https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-fstack-protector
283 if let Some(value) = self.stack_protector {
284 // don't need to propagate stack-protector on MSVC since /GS is already the default
285 // https://learn.microsoft.com/en-us/cpp/build/reference/gs-buffer-security-check?view=msvc-170
286 //
287 // Do NOT `stack-protector=none` since it weakens security for C code,
288 // and `-Zstack-protector=basic` is deprecated and will be removed soon.
289 let cc_flag = match value {
290 "strong" => Some("-fstack-protector-strong"),
291 "all" => Some("-fstack-protector-all"),
292 _ => None,
293 };
294 if let Some(cc_flag) = cc_flag {
295 push_if_supported(cc_flag.into());
296 }
297 }
298 }
299
300 // Compiler-exclusive flags
301 match family {
302 ToolFamily::Clang { .. } => {
303 // GNU and Clang compilers both support the same PGO flags, but they use different libraries and
304 // different formats for the profile files which are not compatible.
305 // clang and rustc both internally use llvm, so we want to inherit the PGO flags only for clang.
306 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fprofile-generate
307 if let Some(value) = self.profile_generate {
308 push_if_supported(format!("-fprofile-generate={value}").into());
309 }
310 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fprofile-use
311 if let Some(value) = self.profile_use {
312 push_if_supported(format!("-fprofile-use={value}").into());
313 }
314
315 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fembed-bitcode
316 if let Some(value) = self.embed_bitcode {
317 let cc_val = if value { "all" } else { "off" };
318 push_if_supported(format!("-fembed-bitcode={cc_val}").into());
319 }
320
321 // https://doc.rust-lang.org/rustc/linker-plugin-lto.html
322 if self.linker_plugin_lto.unwrap_or(false) {
323 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-flto
324 // In order to use linker-plugin-lto to achieve cross-lang lto, cc has to use thin LTO
325 // to compile the c/c++ libraries because llvm linker plugin/lld uses thin LTO by default.
326 // And for thin LTO in linker plugin to work, the archive also has to be compiled using thin LTO,
327 // since thin LTO generates extra information that fat LTO does not generate that
328 // is required for thin LTO process.
329 push_if_supported("-flto=thin".into());
330 }
331 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mguard
332 if let Some(value) = self.control_flow_guard {
333 let cc_val = match value {
334 "y" | "yes" | "on" | "true" | "checks" => Some("cf"),
335 "nochecks" => Some("cf-nochecks"),
336 "n" | "no" | "off" | "false" => Some("none"),
337 _ => None,
338 };
339 if let Some(cc_val) = cc_val {
340 push_if_supported(format!("-mguard={cc_val}").into());
341 }
342 }
343 }
344 ToolFamily::Gnu => {}
345 ToolFamily::Msvc { .. } => {
346 // https://learn.microsoft.com/en-us/cpp/build/reference/guard-enable-control-flow-guard
347 if let Some(value) = self.control_flow_guard {
348 let cc_val = match value {
349 "y" | "yes" | "on" | "true" | "checks" => Some("cf"),
350 "n" | "no" | "off" | "false" => Some("cf-"),
351 _ => None,
352 };
353 if let Some(cc_val) = cc_val {
354 push_if_supported(format!("/guard:{cc_val}").into());
355 }
356 }
357 // https://learn.microsoft.com/en-us/cpp/build/reference/oy-frame-pointer-omission
358 if let Some(value) = self.force_frame_pointers {
359 // Flag is unsupported on 64-bit arches
360 if !target.arch.contains("64") {
361 let cc_flag = if value { "/Oy-" } else { "/Oy" };
362 push_if_supported(cc_flag.into());
363 }
364 }
365 }
366 }
367 }
368 }
369
370 #[cfg(test)]
371 mod tests {
372 use super::*;
373
374 #[track_caller]
375 fn check(env: &str, expected: &RustcCodegenFlags) {
376 let actual = RustcCodegenFlags::parse(env).unwrap();
377 assert_eq!(actual, *expected);
378 }
379
380 #[test]
381 fn codegen_type() {
382 let expected = RustcCodegenFlags {
383 code_model: Some("tiny"),
384 ..RustcCodegenFlags::default()
385 };
386 check("-Ccode-model=tiny", &expected);
387 check("-C\u{1f}code-model=tiny", &expected);
388 check("--codegen\u{1f}code-model=tiny", &expected);
389 check("--codegen=code-model=tiny", &expected);
390 }
391
392 #[test]
393 fn precedence() {
394 check(
395 "-ccode-model=tiny\u{1f}-Ccode-model=small",
396 &RustcCodegenFlags {
397 code_model: Some("small"),
398 ..RustcCodegenFlags::default()
399 },
400 );
401 }
402
403 #[test]
404 fn two_valid_prefixes() {
405 let expected = RustcCodegenFlags::default();
406 check("-L\u{1f}-Clto", &expected);
407 }
408
409 #[test]
410 fn stack_protector() {
411 let expected = RustcCodegenFlags {
412 stack_protector: Some("strong"),
413 ..RustcCodegenFlags::default()
414 };
415 check("-Zstack-protector=strong", &expected);
416 check("-Cstack-protector=strong", &expected);
417 }
418
419 #[test]
420 fn three_valid_prefixes() {
421 let expected = RustcCodegenFlags {
422 lto: Some("true"),
423 ..RustcCodegenFlags::default()
424 };
425 check("-L\u{1f}-L\u{1f}-Clto", &expected);
426 }
427
428 #[test]
429 fn all_rustc_flags() {
430 // Throw all possible flags at the parser to catch false positives
431 let flags = [
432 // Set all the flags we recognise first
433 "-Ccode-model=tiny",
434 "-Ccontrol-flow-guard=yes",
435 "-Cembed-bitcode=no",
436 "-Cforce-frame-pointers=yes",
437 "-Clto=false",
438 "-Clink-dead-code=yes",
439 "-Cno-redzone=yes",
440 "-Cno-vectorize-loops",
441 "-Cno-vectorize-slp",
442 "-Cprofile-generate=fooprofile",
443 "-Cprofile-use=fooprofile",
444 "-Crelocation-model=pic",
445 "-Csoft-float=yes",
446 "-Zbranch-protection=bti,pac-ret,leaf",
447 "-Cdwarf-version=5",
448 "-Zstack-protector=strong",
449 // Set flags we don't recognise but rustc supports next
450 // rustc flags
451 "--cfg",
452 "a",
453 "--check-cfg 'cfg(verbose)",
454 "-L",
455 "/usr/lib/foo",
456 "-l",
457 "static:+whole-archive=mylib",
458 "--crate-type=dylib",
459 "--crate-name=foo",
460 "--edition=2021",
461 "--emit=asm",
462 "--print=crate-name",
463 "-g",
464 "-O",
465 "-o",
466 "foooutput",
467 "--out-dir",
468 "foooutdir",
469 "--target",
470 "aarch64-unknown-linux-gnu",
471 "-W",
472 "missing-docs",
473 "-D",
474 "unused-variables",
475 "--force-warn",
476 "dead-code",
477 "-A",
478 "unused",
479 "-F",
480 "unused",
481 "--cap-lints",
482 "warn",
483 "--version",
484 "--verbose",
485 "-v",
486 "--extern",
487 "foocrate",
488 "--sysroot",
489 "fooroot",
490 "--error-format",
491 "human",
492 "--color",
493 "auto",
494 "--diagnostic-width",
495 "80",
496 "--remap-path-prefix",
497 "foo=bar",
498 "--json=artifact",
499 // Codegen flags
500 "-Car",
501 "-Ccodegen-units=1",
502 "-Ccollapse-macro-debuginfo=yes",
503 "-Cdebug-assertions=yes",
504 "-Cdebuginfo=1",
505 "-Cdefault-linker-libraries=yes",
506 "-Cdlltool=foo",
507 "-Cextra-filename=foo",
508 "-Cforce-unwind-tables=yes",
509 "-Cincremental=foodir",
510 "-Cinline-threshold=6",
511 "-Cinstrument-coverage",
512 "-Clink-arg=-foo",
513 "-Clink-args=-foo",
514 "-Clink-self-contained=yes",
515 "-Clinker=lld",
516 "-Clinker-flavor=ld.lld",
517 "-Clinker-plugin-lto=/path",
518 "-Cllvm-args=foo",
519 "-Cmetadata=foo",
520 "-Cno-prepopulate-passes",
521 "-Cno-stack-check",
522 "-Copt-level=3",
523 "-Coverflow-checks=yes",
524 "-Cpanic=abort",
525 "-Cpasses=foopass",
526 "-Cprefer-dynamic=yes",
527 "-Crelro-level=partial",
528 "-Cremark=all",
529 "-Crpath=yes",
530 "-Csave-temps=yes",
531 "-Csplit-debuginfo=packed",
532 "-Cstrip=symbols",
533 "-Csymbol-mangling-version=v0",
534 "-Ctarget-cpu=native",
535 "-Ctarget-feature=+sve",
536 // Unstable options
537 "-Ztune-cpu=machine",
538 ];
539 check(
540 &flags.join("\u{1f}"),
541 &RustcCodegenFlags {
542 code_model: Some("tiny"),
543 control_flow_guard: Some("yes"),
544 embed_bitcode: Some(false),
545 force_frame_pointers: Some(true),
546 lto: Some("false"),
547 no_redzone: Some(true),
548 no_vectorize_loops: true,
549 no_vectorize_slp: true,
550 profile_generate: Some("fooprofile"),
551 profile_use: Some("fooprofile"),
552 relocation_model: Some("pic"),
553 soft_float: Some(true),
554 branch_protection: Some("bti,pac-ret,leaf"),
555 dwarf_version: Some(5),
556 stack_protector: Some("strong"),
557 linker_plugin_lto: Some(true),
558 },
559 );
560 }
561 }