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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#![recursion_limit = "128"]
#[macro_use] extern crate quick_error;
pub mod compress;
pub mod control;
pub mod data;
pub mod listener;
pub mod manifest;
pub use crate::debarchive::DebArchive;
pub use crate::error::*;
pub use crate::manifest::Config;
#[macro_use]
mod util;
mod config;
mod debarchive;
mod dependencies;
mod dh_installsystemd;
mod dh_lib;
mod error;
mod ok_or;
mod pathbytes;
mod tararchive;
mod wordsplit;
use crate::listener::Listener;
use crate::manifest::AssetSource;
use rayon::prelude::*;
use std::env;
use std::fs;
use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus};
const TAR_REJECTS_CUR_DIR: bool = true;
const DEFAULT_TARGET: &str = include_str!(concat!(env!("OUT_DIR"), "/default_target.rs"));
pub fn install_deb(path: &Path) -> CDResult<()> {
let status = Command::new("sudo").arg("dpkg").arg("-i").arg(path)
.status()?;
if !status.success() {
return Err(CargoDebError::InstallFailed);
}
Ok(())
}
pub fn reset_deb_temp_directory(options: &Config) -> io::Result<()> {
let deb_dir = options.default_deb_output_dir();
let deb_temp_dir = options.deb_temp_dir();
remove_deb_temp_directory(options);
let g = deb_dir.join(DebArchive::filename_glob(options));
if let Ok(old_files) = glob::glob(g.to_str().expect("utf8 path")) {
for old_file in old_files.flatten() {
let _ = fs::remove_file(old_file);
}
}
fs::create_dir_all(deb_temp_dir)
}
pub fn remove_deb_temp_directory(options: &Config) {
let deb_temp_dir = options.deb_temp_dir();
let _ = fs::remove_dir(&deb_temp_dir);
}
pub fn cargo_build(options: &Config, target: Option<&str>, build_command: &str, build_flags: &[String], verbose: bool) -> CDResult<()> {
let mut cmd = Command::new("cargo");
cmd.current_dir(&options.pacakge_manifest_dir);
cmd.arg(build_command);
cmd.args(build_flags);
if verbose {
cmd.arg("--verbose");
}
if let Some(target) = target {
cmd.args(["--target", target]);
if env::var_os("PKG_CONFIG_ALLOW_CROSS").is_none() && env::var_os("PKG_CONFIG_PATH").is_none() {
let pkg_config_path = format!("/usr/lib/{}/pkgconfig", debian_triple(target));
if Path::new(&pkg_config_path).exists() {
cmd.env("PKG_CONFIG_ALLOW_CROSS", "1");
cmd.env("PKG_CONFIG_PATH", pkg_config_path);
}
}
}
if !options.default_features {
cmd.arg("--no-default-features");
}
let features = &options.features;
if !features.is_empty() {
cmd.args(["--features", &features.join(",")]);
}
log::debug!("cargo build {:?}", cmd.get_args());
let status = cmd.status()
.map_err(|e| CargoDebError::CommandFailed(e, "cargo"))?;
if !status.success() {
return Err(CargoDebError::BuildFailed);
}
Ok(())
}
fn debian_triple(rust_target_triple: &str) -> String {
let mut p = rust_target_triple.split('-');
let arch = p.next().unwrap();
let abi = p.last().unwrap_or("");
let (darch, dabi) = match (arch, abi) {
("i586", _) |
("i686", _) => ("i386", "gnu"),
("x86_64", _) => ("x86_64", "gnu"),
("aarch64", _) => ("aarch64", "gnu"),
(arm, abi) if arm.starts_with("arm") || arm.starts_with("thumb") => {
("arm", if abi.ends_with("hf") {"gnueabihf"} else {"gnueabi"})
},
("mipsel", _) => ("mipsel", "gnu"),
(risc, _) if risc.starts_with("riscv64") => ("riscv64", "gnu"),
(arch, abi) => (arch, abi),
};
format!("{darch}-linux-{dabi}")
}
fn ensure_success(status: ExitStatus) -> io::Result<()> {
if status.success() {
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, status.to_string()))
}
}
pub fn strip_binaries(options: &mut Config, target: Option<&str>, listener: &dyn Listener, separate_file: bool) -> CDResult<()> {
let mut cargo_config = None;
let objcopy_tmp;
let strip_tmp;
let mut objcopy_cmd = Path::new("objcopy");
let mut strip_cmd = Path::new("strip");
if let Some(target) = target {
cargo_config = options.cargo_config()?;
if let Some(ref conf) = cargo_config {
if let Some(cmd) = conf.objcopy_command(target) {
listener.info(format!("Using '{}' for '{target}'", cmd.display()));
objcopy_tmp = cmd;
objcopy_cmd = &objcopy_tmp;
}
if let Some(cmd) = conf.strip_command(target) {
listener.info(format!("Using '{}' for '{target}'", cmd.display()));
strip_tmp = cmd;
strip_cmd = &strip_tmp;
}
}
}
let stripped_binaries_output_dir = options.default_deb_output_dir();
options.built_binaries_mut().par_iter_mut().enumerate().try_for_each(|(i, asset)| {
let new_source = match asset.source.path() {
Some(path) => {
if !path.exists() {
return Err(CargoDebError::StripFailed(path.to_owned(), "The file doesn't exist".into()));
}
let debug_path = asset.source.debug_source().expect("Failed to compute debug source path");
let conf_path = cargo_config.as_ref().map(|c| c.path())
.unwrap_or_else(|| Path::new(".cargo/config"));
if separate_file {
log::debug!("extracting debug info of {} with {}", path.display(), objcopy_cmd.display());
let _ = std::fs::remove_file(&debug_path);
Command::new(objcopy_cmd)
.arg("--only-keep-debug")
.arg(path)
.arg(&debug_path)
.status()
.and_then(ensure_success)
.map_err(|err| {
if let Some(target) = target {
CargoDebError::StripFailed(path.to_owned(), format!("{}: {}.\nhint: Target-specific strip commands are configured in [target.{}] objcopy = {{ path =\"{}\" }} in {}", objcopy_cmd.display(), err, target, objcopy_cmd.display(), conf_path.display()))
} else {
CargoDebError::CommandFailed(err, "objcopy")
}
})?;
}
let file_name = path.file_name().ok_or(CargoDebError::Str("bad path"))?;
let file_name = format!("{}.tmp{}-stripped", file_name.to_string_lossy(), i);
let stripped_temp_path = stripped_binaries_output_dir.join(file_name);
let _ = std::fs::remove_file(&stripped_temp_path);
log::debug!("stripping {} with {}", path.display(), strip_cmd.display());
Command::new(strip_cmd)
.arg("--strip-unneeded")
.arg("-o")
.arg(&stripped_temp_path)
.arg(path)
.status()
.and_then(ensure_success)
.map_err(|err| {
if let Some(target) = target {
CargoDebError::StripFailed(path.to_owned(), format!("{}: {}.\nhint: Target-specific strip commands are configured in [target.{}] strip = {{ path = \"{}\" }} in {}", strip_cmd.display(), err, target, strip_cmd.display(), conf_path.display()))
} else {
CargoDebError::CommandFailed(err, "strip")
}
})?;
if !stripped_temp_path.exists() {
return Err(CargoDebError::StripFailed(path.to_owned(), format!("{} command failed to create output '{}'", strip_cmd.display(), stripped_temp_path.display())));
}
if separate_file {
log::debug!("linking debug info to {} with {}", debug_path.display(), objcopy_cmd.display());
let debug_filename = debug_path.file_name().expect("Built binary has no filename");
Command::new(objcopy_cmd)
.current_dir(debug_path.parent().expect("Debug source file had no parent path"))
.arg(format!(
"--add-gnu-debuglink={}",
debug_filename.to_str().expect("Debug source file had no filename")
))
.arg(&stripped_temp_path)
.status()
.and_then(ensure_success)
.map_err(|err| CargoDebError::CommandFailed(err, "objcopy"))?;
}
listener.info(format!("Stripped '{}'", path.display()));
AssetSource::Path(stripped_temp_path)
},
None => {
listener.warning(format!("Found built asset with non-path source '{:?}'", asset));
return Ok(());
},
};
asset.source = new_source;
Ok::<_, CargoDebError>(())
})?;
if separate_file {
options.add_debug_assets();
}
Ok(())
}