puffin_build/harness/
put.rs

1use std::collections::HashSet;
2
3use itertools::Itertools;
4
5use crate::harness::Harness;
6use crate::library::Library;
7use crate::utils::{clang, make_rust_identifier};
8
9#[derive(Debug, Clone)]
10pub struct Put {
11    library: Library,
12    harness: Harness,
13    objects: Vec<std::path::PathBuf>,
14}
15
16impl Put {
17    pub fn new(library: Library, harness: Harness, objects: Vec<std::path::PathBuf>) -> Self {
18        Self {
19            library,
20            harness,
21            objects,
22        }
23    }
24
25    pub fn name(&self) -> String {
26        self.library.name().clone()
27    }
28
29    pub fn id(&self) -> String {
30        self.library.id()
31    }
32
33    pub fn library(&self) -> Library {
34        self.library.clone()
35    }
36
37    pub fn harness(&self) -> Harness {
38        self.harness.clone()
39    }
40
41    pub fn objects(&self) -> Vec<std::path::PathBuf> {
42        self.objects.clone()
43    }
44
45    pub fn registration(&self) -> String {
46        format!(
47            r###"
48            registration_c!(
49                {id},
50                r#"{name}"#,
51                r#"{harness_name} {harness_version}"#,
52                r#"{library_name} {library_version}"#,
53                std::collections::HashSet::from([
54                    {capabilities}
55                ])
56            );
57            "###,
58            id = self.id(),
59            name = self.name(),
60            library_name = self.library.metadata().vendor,
61            library_version = self.library.metadata().version,
62            harness_name = "puffin",
63            harness_version = crate::puffin::version(),
64            capabilities = self
65                .library
66                .metadata()
67                .capabilities
68                .iter()
69                .map(|s| format!(r#"String::from("{s}")"#))
70                .join(","),
71        )
72    }
73
74    pub fn print_cargo_metadata(&self) {
75        println!("cargo:rerun-if-changed={}", self.library.path().display());
76        // Check for harness files
77        println!("cargo:rerun-if-changed={}", self.harness.path.display());
78        // Check for added or removed vendors: slow, adds a few seconds before each run
79        // but can be useful when switching often, building new ones etc...
80        #[cfg(feature = "watch-vendor")]
81        println!(
82            "cargo:rerun-if-changed={}",
83            self.library.path().join("..").display()
84        );
85
86        for instrumentation_type in self.library.metadata().instrumentation.iter() {
87            println!(
88                "cargo:rustc-cfg={}=\"{}\"",
89                make_rust_identifier(instrumentation_type),
90                self.name()
91            )
92        }
93
94        let lib = self.library.metadata();
95        let known_vulnerabilities: HashSet<String> =
96            HashSet::from_iter(lib.known_vulnerabilities.iter().cloned());
97        let fixed_vulnerabilities: HashSet<String> =
98            HashSet::from_iter(lib.fixed_vulnerabilities.iter().cloned());
99
100        known_vulnerabilities
101            .difference(&fixed_vulnerabilities)
102            .for_each(|vulnerability| {
103                println!(
104                    "cargo:rustc-cfg={}=\"{}\"",
105                    make_rust_identifier(vulnerability),
106                    self.name()
107                )
108            });
109
110        lib.capabilities.iter().for_each(|capability| {
111            println!(
112                "cargo:rustc-cfg={}=\"{}\"",
113                make_rust_identifier(capability),
114                self.name()
115            )
116        });
117
118        println!(
119            "cargo:rustc-cfg={}=\"{}\"",
120            make_rust_identifier(&lib.vendor),
121            self.name()
122        );
123        println!("cargo:rustc-cfg=has_put=\"{}\"", self.name());
124
125        // One cfg per PUT, named after its preset without the `-asan` suffix: a test filter can
126        // then select a version whatever its ASAN variant (`openssl340` matches both `openssl340`
127        // and `openssl340-asan`).
128        println!(
129            "cargo:rustc-cfg={}=\"{}\"",
130            make_rust_identifier(self.name().replace("-asan", "")),
131            self.name()
132        );
133
134        if lib.vendor == "boringssl" {
135            if cfg!(target_os = "macos") {
136                println!("cargo:rustc-link-lib=c++");
137                // BoringSSL objects referenced by the C harness pull C++ ABI symbols on macOS.
138                println!("cargo:rustc-link-lib=c++abi");
139            } else {
140                // On Linux, Cargo places dynamic cargo:rustc-link-lib entries before static
141                // ones, so libstdc++ would appear before libputs-bundle.a in the link command.
142                // With --as-needed (default on Linux), the linker skips libstdc++ since no
143                // references have been seen yet, then fails on undefined C++ symbols from
144                // puts-bundle.a. Using --push-state/--no-as-needed forces libstdc++ to be
145                // linked unconditionally regardless of position in the link command.
146                println!(
147                    "cargo:rustc-link-arg=-Wl,--push-state,--no-as-needed,-lstdc++,--pop-state"
148                );
149            }
150        }
151
152        if self
153            .library
154            .metadata()
155            .instrumentation
156            .iter()
157            .any(|i| i == "asan")
158        {
159            // NOTE adding compiler-rt to rpath for libasan is not straightforward
160            //
161            //     Unfortunately, passing `-frtlib-add-rpath` to clang doesn't add
162            //     the correct rpath on linux platforms. Instead, we find the folder
163            //     containing the compiler-rt runtime and add it to rpath ourselves.
164            let runtime_dir = clang::runtime_dir();
165            println!("cargo:rustc-link-arg=-Wl,-rpath,{}", runtime_dir);
166            println!("cargo:rustc-link-arg=-fsanitize=address");
167
168            if cfg!(target_os = "macos") {
169                // On macOS, `-shared-libasan` is not supported by all clang
170                // variants (e.g. Nix's clang wrapper). Explicitly link the
171                // ASAN runtime dylib instead.
172                println!("cargo:rustc-link-search=native={}", runtime_dir);
173                println!("cargo:rustc-link-lib=dylib=clang_rt.asan_osx_dynamic");
174            } else {
175                println!("cargo:rustc-link-arg=-shared-libasan");
176            }
177        }
178
179        if self
180            .library
181            .metadata()
182            .instrumentation
183            .iter()
184            .any(|i| i == "gcov")
185        {
186            println!("cargo:rustc-link-arg=-ftest-coverage");
187            println!("cargo:rustc-link-arg=-fprofile-arcs");
188        }
189
190        if self
191            .library
192            .metadata()
193            .instrumentation
194            .iter()
195            .any(|i| i == "llvm_cov")
196        {
197            println!("cargo:rustc-link-arg=-fprofile-instr-generate");
198            println!("cargo:rustc-link-arg=-fcoverage-mapping");
199        }
200    }
201}