-
Notifications
You must be signed in to change notification settings - Fork 37
/
build.rs
268 lines (242 loc) Β· 9.35 KB
/
build.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
262
263
264
265
266
267
268
// Copyright (C) 2019-2021 Pierre Krieger
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::{
fs, io,
path::{Path, PathBuf},
process::Command,
};
/// Configuration for building the kernel.
#[derive(Debug)]
pub struct Config<'a> {
/// Path to the `Cargo.toml` of the standalone kernel library.
// TODO: once the standalone kernel is on crates.io, make it possible for the kernel builder to run as a completely stand-alone program and pass a build directory instead
pub kernel_cargo_toml: &'a Path,
/// If true, compiles with `--release`.
pub release: bool,
/// Name of the target to pass as `--target`.
pub target_name: &'a str,
/// JSON target specifications.
pub target_specs: &'a str,
/// Link script to pass to the linker.
pub link_script: &'a str,
}
/// Successful build.
#[derive(Debug)]
pub struct BuildOutput {
/// Path to the output of the compilation.
pub out_kernel_path: PathBuf,
}
/// Error that can happen during the build.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Could not start Cargo: {0}")]
CargoNotFound(io::Error),
#[error("Error while building the kernel")]
BuildError,
#[error("Failed to get metadata about the kernel Cargo.toml")]
MetadataFailed,
#[error("Invalid kernel Cargo.toml path")]
BadKernelCargoTomlPath,
#[error("{0}")]
Io(#[from] io::Error),
}
/// Builds the kernel.
pub fn build(cfg: Config) -> Result<BuildOutput, Error> {
assert_ne!(cfg.target_name, "debug");
assert_ne!(cfg.target_name, "release");
// Determine the path to the file that Cargo will generate.
let (output_file, target_dir_with_target) = {
let metadata = cargo_metadata::MetadataCommand::new()
.manifest_path(&cfg.kernel_cargo_toml)
.no_deps()
.exec()
.map_err(|_| Error::MetadataFailed)?;
let target_dir_with_target = metadata
.target_directory
.join(cfg.target_name)
.join("project");
let output_file = target_dir_with_target
.join("target")
.join(cfg.target_name)
.join(if cfg.release { "release" } else { "debug" })
.join("kernel");
(output_file, target_dir_with_target)
};
// Create and fill the directory where various source files are put.
// If `cargo_clean_needed` is set to true, the build will later be done from scratch.
let mut cargo_clean_needed = false;
fs::create_dir_all(&target_dir_with_target)?;
if write_if_changed(
(&target_dir_with_target).join(format!("{}.json", cfg.target_name)),
cfg.target_specs.as_bytes(),
)? {
cargo_clean_needed = true;
}
if write_if_changed(
(&target_dir_with_target).join("link.ld"),
cfg.link_script.as_bytes(),
)? {
// Note: this is overly conservative. Only the linking step needs to be done again, but
// there isn't any easy way to retrigger only the linking.
cargo_clean_needed = true;
}
{
let mut cargo_toml_prototype = toml::value::Table::new();
// TODO: should write `[profile]` in there
cargo_toml_prototype.insert("package".into(), {
let mut package = toml::value::Table::new();
package.insert("name".into(), "kernel".into());
package.insert("version".into(), "1.0.0".into());
package.insert("edition".into(), "2018".into());
package.into()
});
cargo_toml_prototype.insert("dependencies".into(), {
let mut dependencies = toml::value::Table::new();
dependencies.insert("redshirt-standalone-kernel".into(), {
let mut wasm_project = toml::value::Table::new();
wasm_project.insert(
"path".into(),
cfg.kernel_cargo_toml
.parent()
.ok_or(Error::BadKernelCargoTomlPath)?
.display()
.to_string()
.into(),
);
wasm_project.into()
});
dependencies.into()
});
cargo_toml_prototype.insert("profile".into(), {
let mut profiles = toml::value::Table::new();
profiles.insert("release".into(), {
let mut profile = toml::value::Table::new();
profile.insert("panic".into(), "abort".into());
profile.insert("lto".into(), true.into());
profile.insert("opt-level".into(), 3.into());
profile.into()
});
profiles.insert("dev".into(), {
let mut profile = toml::value::Table::new();
profile.insert("panic".into(), "abort".into());
profile.insert("opt-level".into(), 2.into());
profile.into()
});
profiles.into()
});
cargo_toml_prototype.insert("workspace".into(), toml::value::Table::new().into());
cargo_toml_prototype.insert("patch".into(), {
let mut patches = toml::value::Table::new();
patches.insert("crates-io".into(), {
let crates = toml::value::Table::new();
// Uncomment this in order to overwrite dependencies used during the kernel
// compilation.
/*crates.insert("foo".into(), {
let mut val = toml::value::Table::new();
val.insert("path".into(), "/path/to/foot".into());
val.into()
});*/
crates.into()
});
patches.into()
});
write_if_changed(
target_dir_with_target.join("Cargo.toml"),
toml::to_string_pretty(&cargo_toml_prototype).unwrap(),
)?;
}
{
fs::create_dir_all(&target_dir_with_target.join("src"))?;
let src = format!(
r#"
#![no_std]
#![no_main]
// TODO: these features are necessary because of the fact that we use a macro
#![feature(asm_sym, asm_const)] // TODO: https://github.com/rust-lang/rust/issues/72016
#![feature(naked_functions)] // TODO: https://github.com/rust-lang/rust/issues/32408
redshirt_standalone_kernel::__gen_boot! {{
entry: redshirt_standalone_kernel::run,
memory_zeroing_start: __bss_start,
memory_zeroing_end: __bss_end,
}}
extern "C" {{
static mut __bss_start: u8;
static mut __bss_end: u8;
}}
"#
);
write_if_changed(target_dir_with_target.join("src").join("main.rs"), src)?;
}
if cargo_clean_needed {
let status = Command::new("cargo")
.arg("clean")
.arg("--manifest-path")
.arg(target_dir_with_target.join("Cargo.toml"))
.status()
.map_err(Error::CargoNotFound)?;
// TODO: should we make it configurable where the stdout/stderr outputs go?
if !status.success() {
return Err(Error::BuildError);
}
}
// Actually build the kernel.
let build_status = Command::new("cargo")
.arg("build")
.args(&["-Z", "build-std=core,alloc"]) // TODO: nightly only; cc https://github.com/tomaka/redshirt/issues/300
.env("RUST_TARGET_PATH", &target_dir_with_target)
.env(
&format!(
"CARGO_TARGET_{}_RUSTFLAGS",
cfg.target_name.replace("-", "_").to_uppercase()
),
format!(
"-Clink-arg=--script -Clink-arg={}",
target_dir_with_target.join("link.ld").display()
),
)
.arg("--target")
.arg(cfg.target_name)
.arg("--manifest-path")
.arg(target_dir_with_target.join("Cargo.toml"))
.args(if cfg.release {
&["--release"][..]
} else {
&[][..]
})
.status()
.map_err(Error::CargoNotFound)?;
// TODO: should we make it configurable where the stdout/stderr outputs go?
if !build_status.success() {
return Err(Error::BuildError);
}
assert!(output_file.exists());
Ok(BuildOutput {
out_kernel_path: output_file,
})
}
/// Write to the given `file` if the `content` is different.
///
/// Returns `true` if the content was indeed different and a write has been performed.
///
/// This function is used in order to not make Cargo trigger a rebuild by writing over a file
/// with the same content as it already has.
fn write_if_changed(file: impl AsRef<Path>, content: impl AsRef<[u8]>) -> Result<bool, io::Error> {
if fs::read(file.as_ref()).ok().as_deref() != Some(content.as_ref()) {
fs::write(file, content.as_ref())?;
Ok(true)
} else {
Ok(false)
}
}