flowey_lib_hvlite/init_cross_build.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Install dependencies and set environment variables for cross compiling
5
6use flowey::node::prelude::*;
7use std::collections::BTreeMap;
8use target_lexicon::Architecture;
9
10flowey_request! {
11 pub struct Request {
12 pub target: target_lexicon::Triple,
13 pub injected_env: WriteVar<BTreeMap<String, String>>,
14 }
15}
16
17new_flow_node!(struct Node);
18
19impl FlowNode for Node {
20 type Request = Request;
21
22 fn imports(ctx: &mut ImportCtx<'_>) {
23 ctx.import::<flowey_lib_common::install_dist_pkg::Node>();
24 }
25
26 fn emit(requests: Vec<Self::Request>, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()> {
27 let host_platform = ctx.platform();
28 let host_arch = ctx.arch();
29
30 let native = |target: &target_lexicon::Triple| -> bool {
31 // Check if the target matches the host platform, treat Linux distros as equivalent
32 let os_matches = matches!(
33 (host_platform, target.operating_system),
34 (
35 FlowPlatform::Linux(_),
36 target_lexicon::OperatingSystem::Linux
37 ) | (
38 FlowPlatform::Windows,
39 target_lexicon::OperatingSystem::Windows
40 ) | (
41 FlowPlatform::MacOs,
42 target_lexicon::OperatingSystem::Darwin(_)
43 )
44 );
45
46 let arch_matches = match target.architecture {
47 Architecture::X86_64 => host_arch == FlowArch::X86_64,
48 Architecture::Aarch64(_) => host_arch == FlowArch::Aarch64,
49 _ => false,
50 };
51
52 os_matches && arch_matches
53 };
54
55 for Request {
56 target,
57 injected_env: injected_env_write,
58 } in requests
59 {
60 let mut pre_build_deps = Vec::new();
61 let mut injected_env = BTreeMap::new();
62
63 if !native(&target) {
64 let platform = ctx.platform();
65
66 match (platform, target.operating_system) {
67 (FlowPlatform::Linux(_), target_lexicon::OperatingSystem::Linux) => {
68 let (gcc_pkg, bin): (Option<&str>, String) = match target.architecture {
69 Architecture::X86_64 => match platform {
70 FlowPlatform::Linux(linux_distribution) => {
71 let pkg = match linux_distribution {
72 FlowPlatformLinuxDistro::Fedora => {
73 Some("gcc-x86_64-linux-gnu")
74 }
75 FlowPlatformLinuxDistro::Ubuntu => {
76 Some("gcc-x86-64-linux-gnu")
77 }
78 FlowPlatformLinuxDistro::AzureLinux => {
79 // Azure Linux doesn't have an x86_64 cross-gcc;
80 // the native `gcc` package is used on x86_64 hosts.
81 match_arch!(host_arch, FlowArch::X86_64, Some("gcc"))
82 }
83 FlowPlatformLinuxDistro::Arch => {
84 match_arch!(host_arch, FlowArch::X86_64, Some("gcc"))
85 }
86 FlowPlatformLinuxDistro::Nix => None,
87 FlowPlatformLinuxDistro::Unknown => {
88 anyhow::bail!("Unknown Linux distribution")
89 }
90 };
91 (pkg, "x86_64-linux-gnu-gcc".to_string())
92 }
93 _ => anyhow::bail!("Unsupported platform"),
94 },
95 Architecture::Aarch64(_) => match platform {
96 FlowPlatform::Linux(linux_distribution) => {
97 let pkg = match linux_distribution {
98 FlowPlatformLinuxDistro::Fedora
99 | FlowPlatformLinuxDistro::Ubuntu
100 | FlowPlatformLinuxDistro::AzureLinux => {
101 Some("gcc-aarch64-linux-gnu")
102 }
103 FlowPlatformLinuxDistro::Arch => match_arch!(
104 host_arch,
105 FlowArch::X86_64,
106 Some("aarch64-linux-gnu-gcc")
107 ),
108 FlowPlatformLinuxDistro::Nix => None,
109 FlowPlatformLinuxDistro::Unknown => {
110 anyhow::bail!("Unknown Linux distribution")
111 }
112 };
113 (pkg, "aarch64-linux-gnu-gcc".to_string())
114 }
115 _ => anyhow::bail!("Unsupported platform"),
116 },
117 arch => anyhow::bail!("unsupported arch {arch}"),
118 };
119
120 // We use `gcc`'s linker for cross-compiling due to:
121 //
122 // * The special baremetal options are the same. These options
123 // don't work for the LLVM linker,
124 // * The compiler team at Microsoft has stated that `rust-lld`
125 // is not a production option,
126 // * The only Rust `aarch64` targets that produce
127 // position-independent static ELF binaries with no std are
128 // `aarch64-unknown-linux-*`.
129 //
130 // Skip package installation for Nix (shell.nix provides cross-compilers)
131 if let Some(gcc_pkg) = gcc_pkg {
132 pre_build_deps.push(ctx.reqv(|v| {
133 flowey_lib_common::install_dist_pkg::Request::Install {
134 package_names: vec![gcc_pkg.into()],
135 done: v,
136 }
137 }));
138 }
139
140 // when cross compiling for gnu linux, explicitly set the
141 // linker being used.
142 //
143 // Note: Don't do this for musl, since for that we use the
144 // openhcl linker set in the repo's `.cargo/config.toml`
145 // This isn't ideal because it means _any_ musl code (not just
146 // code running in VTL2) will use the openhcl-specific musl
147 if matches!(target.environment, target_lexicon::Environment::Gnu) {
148 injected_env.insert(
149 format!(
150 "CARGO_TARGET_{}_LINKER",
151 target.to_string().replace('-', "_").to_uppercase()
152 ),
153 bin,
154 );
155 }
156 }
157 // Cross compiling for Windows with the MSVC toolchain
158 // relies on the appropriate Visual Studio Build Tools
159 // components being installed. The necessary libraries can
160 // be accessed from WSL, allowing for compilation of Windows
161 // applications from Linux. For now, just silently continue
162 // regardless.
163 // TODO: Detect (and potentially install) these dependencies
164 //
165 // Cross compiling for Windows with the GNU (mingw-w64)
166 // toolchain works on a native (non-WSL) Linux host without
167 // the Windows SDK, and is used to build Windows *guest*
168 // payloads (e.g. pipette). Install the mingw-w64 cross gcc,
169 // which rustc auto-detects as the linker
170 // (`x86_64-w64-mingw32-gcc`).
171 (
172 FlowPlatform::Linux(linux_distribution),
173 target_lexicon::OperatingSystem::Windows,
174 ) => {
175 if matches!(target.environment, target_lexicon::Environment::Gnu)
176 && matches!(target.architecture, Architecture::X86_64)
177 {
178 let pkg = match linux_distribution {
179 FlowPlatformLinuxDistro::Ubuntu => {
180 Some("gcc-mingw-w64-x86-64-win32")
181 }
182 FlowPlatformLinuxDistro::Fedora => Some("mingw64-gcc"),
183 _ => None,
184 };
185 if let Some(pkg) = pkg {
186 pre_build_deps.push(ctx.reqv(|v| {
187 flowey_lib_common::install_dist_pkg::Request::Install {
188 package_names: vec![pkg.into()],
189 done: v,
190 }
191 }));
192 }
193 }
194 }
195 (FlowPlatform::Windows, target_lexicon::OperatingSystem::Windows) => {}
196 (_, target_lexicon::OperatingSystem::None_) => {}
197 (_, target_lexicon::OperatingSystem::Uefi) => {}
198 (host_os, target_os) => {
199 anyhow::bail!("cannot cross compile for {target_os} on {host_os}")
200 }
201 }
202 }
203
204 ctx.emit_minor_rust_step("inject cross env", |ctx| {
205 pre_build_deps.claim(ctx);
206 let injected_env_write = injected_env_write.claim(ctx);
207 move |rt| {
208 rt.write(injected_env_write, &injected_env);
209 }
210 });
211 }
212
213 Ok(())
214 }
215}