-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
cargo.rs
261 lines (232 loc) · 8.55 KB
/
cargo.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use std::ffi::{OsStr, OsString};
use std::io::{Result, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use cargo_metadata::camino::Utf8PathBuf;
use cargo_metadata::semver::Version;
#[cfg(target_os = "macos")]
const ARCH: &str = "darwin-x86_64";
#[cfg(target_os = "linux")]
const ARCH: &str = "linux-x86_64";
#[cfg(target_os = "windows")]
const ARCH: &str = "windows-x86_64";
#[cfg(target_os = "windows")]
const CLANG_EXT: &str = ".cmd";
#[cfg(not(target_os = "windows"))]
const CLANG_EXT: &str = "";
#[cfg(target_os = "windows")]
const BIN_EXT: &str = ".exe";
#[cfg(not(target_os = "windows"))]
const BIN_EXT: &str = "";
fn clang_suffix(triple: &str, arch: &str, platform: u8, postfix: &str) -> PathBuf {
let tool_triple = match triple {
"arm-linux-androideabi" => "armv7a-linux-androideabi",
"armv7-linux-androideabi" => "armv7a-linux-androideabi",
_ => triple,
};
[
"toolchains",
"llvm",
"prebuilt",
arch,
"bin",
&format!("{}{}-clang{}{}", tool_triple, platform, postfix, CLANG_EXT),
]
.iter()
.collect()
}
fn toolchain_triple(triple: &str) -> &str {
match triple {
"armv7-linux-androideabi" => "arm-linux-androideabi",
_ => triple,
}
}
fn toolchain_suffix(triple: &str, arch: &str, bin: &str) -> PathBuf {
[
"toolchains",
"llvm",
"prebuilt",
arch,
"bin",
&format!("{}-{}{}", toolchain_triple(triple), bin, BIN_EXT),
]
.iter()
.collect()
}
fn ndk23_tool(arch: &str, tool: &str) -> PathBuf {
["toolchains", "llvm", "prebuilt", arch, "bin", tool]
.iter()
.collect()
}
fn sysroot_suffix(arch: &str) -> PathBuf {
["toolchains", "llvm", "prebuilt", arch, "sysroot"]
.iter()
.collect()
}
fn cargo_env_target_cfg(triple: &str, key: &str) -> String {
format!("CARGO_TARGET_{}_{}", &triple.replace('-', "_"), key).to_uppercase()
}
fn create_libgcc_linker_script_workaround(target_dir: &Utf8PathBuf) -> Result<Utf8PathBuf> {
let libgcc_workaround_dir = target_dir.join("cargo-ndk").join("libgcc-workaround");
std::fs::create_dir_all(&libgcc_workaround_dir)?;
let libgcc_workaround_file = libgcc_workaround_dir.join("libgcc.a");
let mut file = std::fs::File::create(libgcc_workaround_file)?;
file.write_all(b"INPUT(-lunwind)")?;
Ok(libgcc_workaround_dir)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run(
dir: &Path,
target_dir: &Utf8PathBuf,
ndk_home: &Path,
version: Version,
triple: &str,
platform: u8,
cargo_args: &[String],
cargo_manifest: &Path,
bindgen: bool,
) -> std::process::ExitStatus {
log::debug!("Detected NDK version: {:?}", &version);
let target_linker = Path::new(&ndk_home).join(clang_suffix(triple, ARCH, platform, ""));
let target_cxx = Path::new(&ndk_home).join(clang_suffix(triple, ARCH, platform, "++"));
let target_sysroot = Path::new(&ndk_home).join(sysroot_suffix(ARCH));
let target_ar = if version.major >= 23 {
Path::new(&ndk_home).join(ndk23_tool(ARCH, "llvm-ar"))
} else {
Path::new(&ndk_home).join(toolchain_suffix(triple, ARCH, "ar"))
};
let cc_key = format!("CC_{}", &triple);
let ar_key = format!("AR_{}", &triple);
let cxx_key = format!("CXX_{}", &triple);
let bindgen_clang_args_key = format!("BINDGEN_EXTRA_CLANG_ARGS_{}", &triple.replace('-', "_"));
let cargo_bin = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
log::debug!("cargo: {}", &cargo_bin);
log::debug!("{}={}", &ar_key, &target_ar.display());
log::debug!("{}={}", &cc_key, &target_linker.display());
log::debug!("{}={}", &cxx_key, &target_cxx.display());
log::debug!(
"{}={}",
cargo_env_target_cfg(triple, "ar"),
&target_ar.display()
);
log::debug!(
"{}={}",
cargo_env_target_cfg(triple, "linker"),
&target_linker.display()
);
log::debug!(
"{}={}",
&bindgen_clang_args_key,
&std::env::var(bindgen_clang_args_key.clone()).unwrap_or_default()
);
log::debug!("Args: {:?}", &cargo_args);
// Read initial RUSTFLAGS
let mut rustflags = match std::env::var("CARGO_ENCODED_RUSTFLAGS") {
Ok(val) => val,
Err(std::env::VarError::NotPresent) => "".to_string(),
Err(std::env::VarError::NotUnicode(_)) => {
log::error!("RUSTFLAGS environment variable contains non-unicode characters");
std::process::exit(1);
}
};
// Insert Cargo arguments before any `--` arguments.
let arg_insertion_position = cargo_args
.iter()
.enumerate()
.find(|e| e.1.trim() == "--")
.map(|e| e.0)
.unwrap_or(cargo_args.len());
let mut cargo_args: Vec<OsString> = cargo_args.iter().map(|arg| arg.into()).collect();
let mut cargo_cmd = Command::new(cargo_bin);
cargo_cmd
.current_dir(dir)
.env(ar_key, &target_ar)
.env(cc_key, &target_linker)
.env(cxx_key, &target_cxx)
.env(cargo_env_target_cfg(triple, "ar"), &target_ar)
.env(cargo_env_target_cfg(triple, "linker"), &target_linker);
// NDK releases >= 23 beta3 no longer include libgcc which rust's pre-built
// standard libraries depend on. As a workaround for newer NDKs we redirect
// libgcc to libunwind.
//
// Note: there is a tiny chance of a false positive here while the first two
// beta releases for NDK v23 didn't yet include libunwind for all
// architectures.
//
// Note: even though rust-lang merged a fix to support linking the standard
// libraries against newer NDKs they still (up to 1.62.0 at time of writing)
// choose to build binaries (distributed by rustup) against an older NDK
// release (presumably aiming for broader compatibility) which means that
// even the latest versions still require this workaround.
//
// Ref: https://github.com/rust-lang/rust/pull/85806
if version.major >= 23 {
match create_libgcc_linker_script_workaround(target_dir) {
Ok(libdir) => {
// Note that we don't use `cargo rustc` to pass custom library search paths to
// rustc and instead use `CARGO_ENCODED_RUSTFLAGS` because it affects the building
// of all transitive cdylibs (which all need this workaround).
if !rustflags.is_empty() {
// Avoid creating an empty '' rustc argument
rustflags.push('\x1f');
}
rustflags.push_str("-L\x1f");
rustflags.push_str(libdir.as_str());
cargo_cmd.env("CARGO_ENCODED_RUSTFLAGS", rustflags);
}
Err(e) => {
log::error!("Failed to create libgcc.a linker script workaround");
log::error!("{}", e);
std::process::exit(1);
}
}
}
let extra_include = format!("{}/usr/include/{}", &target_sysroot.display(), triple);
if bindgen {
let bindgen_args = format!(
"--sysroot={} -I{}",
&target_sysroot.display(),
extra_include
);
cargo_cmd.env(bindgen_clang_args_key, bindgen_args.clone());
log::debug!("bindgen_args={}", bindgen_args);
}
match dir.parent() {
Some(parent) => {
if parent != dir {
log::debug!("Working directory does not match manifest-path");
cargo_args.insert(
arg_insertion_position,
cargo_manifest.as_os_str().to_owned(),
);
cargo_args.insert(
arg_insertion_position,
OsStr::new("--manifest-path").to_owned(),
);
}
}
_ => {
log::warn!("Parent of current working directory does not exist");
}
}
cargo_args.insert(arg_insertion_position, OsStr::new(triple).to_owned());
cargo_args.insert(arg_insertion_position, OsStr::new("--target").to_owned());
cargo_cmd.args(cargo_args).status().expect("cargo crashed")
}
pub(crate) fn strip(
ndk_home: &Path,
triple: &str,
bin_path: &Path,
version: Version,
) -> std::process::ExitStatus {
let target_strip = if version.major >= 23 {
Path::new(&ndk_home).join(ndk23_tool(ARCH, "llvm-strip"))
} else {
Path::new(&ndk_home).join(toolchain_suffix(triple, ARCH, "strip"))
};
log::debug!("strip: {}", &target_strip.display());
Command::new(target_strip)
.arg(bin_path)
.status()
.expect("strip crashed")
}