microsoft/openvmm
Publicmirrored fromhttps://github.com/microsoft/openvmmAvailable
openhcl/build_info/src/lib.rs
73lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | //! Provides build metadata |
| 5 | |
| 6 | use inspect::Inspect; |
| 7 | |
| 8 | #[derive(Debug, Inspect)] |
| 9 | pub struct BuildInfo { |
| 10 | #[inspect(safe)] |
| 11 | crate_name: &'static str, |
| 12 | #[inspect(safe, rename = "scm_revision")] |
| 13 | revision: &'static str, |
| 14 | #[inspect(safe, rename = "scm_branch")] |
| 15 | branch: &'static str, |
| 16 | } |
| 17 | |
| 18 | impl BuildInfo { |
| 19 | pub const fn new() -> Self { |
| 20 | // TODO: Once Option::unwrap_or() is stable in the const context |
| 21 | // can replace the if statements with it. |
| 22 | // Deliberately not storing `Option` to the build information |
| 23 | // structure to be closer to PODs. |
| 24 | Self { |
| 25 | crate_name: env!("CARGO_PKG_NAME"), |
| 26 | revision: if let Some(r) = option_env!("VERGEN_GIT_SHA") { |
| 27 | r |
| 28 | } else { |
| 29 | "" |
| 30 | }, |
| 31 | branch: if let Some(b) = option_env!("VERGEN_GIT_BRANCH") { |
| 32 | b |
| 33 | } else { |
| 34 | "" |
| 35 | }, |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | pub fn crate_name(&self) -> &'static str { |
| 40 | self.crate_name |
| 41 | } |
| 42 | |
| 43 | pub fn scm_revision(&self) -> &'static str { |
| 44 | self.revision |
| 45 | } |
| 46 | |
| 47 | pub fn scm_branch(&self) -> &'static str { |
| 48 | self.branch |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Placing into a separate section to make easier to discover |
| 53 | // the build information even without a debugger. |
| 54 | // |
| 55 | // The #[used] attribute is not used as the static is reachable |
| 56 | // via a public function. |
| 57 | // |
| 58 | // The #[external_name] attribute is used to give the static |
| 59 | // an unmangled name and again be easily discoverable even without |
| 60 | // a debugger. With a debugger, the non-mangled name is easier |
| 61 | // to use. |
| 62 | |
| 63 | // UNSAFETY: link_section and export_name are considered unsafe. |
| 64 | #[allow(unsafe_code)] |
| 65 | #[unsafe(link_section = ".build_info")] |
| 66 | #[unsafe(export_name = "BUILD_INFO")] |
| 67 | static BUILD_INFO: BuildInfo = BuildInfo::new(); |
| 68 | |
| 69 | pub fn get() -> &'static BuildInfo { |
| 70 | // Without `black_box`, BUILD_INFO is optimized away |
| 71 | // in the release builds with `fat` LTO. |
| 72 | std::hint::black_box(&BUILD_INFO) |
| 73 | } |
| 74 | |