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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! # Cargo-Sysroot
//!
//! Compiles the Rust sysroot crates, core, compiler_builtins, and alloc.
use anyhow::{anyhow, Context, Error, Result};
use cargo_toml2::{
    from_path,
    to_path,
    CargoToml,
    Dependency,
    DependencyFull,
    Package,
    Patches,
    TargetConfig,
    Workspace,
};
use std::{
    collections::BTreeMap,
    env,
    ffi::OsString,
    fs,
    path::{Path, PathBuf},
    process::Command,
};

mod util;

pub use util::get_rust_src;

/// The sysroot crates to build.
///
/// See [`build_sysroot_with`] for details.
#[derive(Debug, Copy, Clone)]
pub enum Sysroot {
    /// The core crate. Provides core functionality.
    ///
    /// This does **not** include [`Sysroot::CompilerBuiltins`],
    /// which is what you probably want unless your target
    /// needs special handling.
    Core,

    /// Compiler-builtins crate.
    ///
    /// This implies [`Sysroot::Core`].
    CompilerBuiltins,

    /// The alloc crate. Gives you a heap, and things to put on it.
    ///
    /// This implies [`Sysroot::Core`], and [`Sysroot::CompilerBuiltins`].
    Alloc,

    /// The standard library. Gives you an operating system.
    ///
    /// This implies [`Sysroot::Alloc`], [`Sysroot::Core`], and
    /// [`Sysroot::CompilerBuiltins`].
    Std,
}

/// Features to enable when building the sysroot crates
///
/// See [`SysrootBuilder::features`] for usage.
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Ord, Eq)]
pub enum Features {
    /// This enables the `mem` feature of [`compiler_builtins`][1],
    /// which will provide memory related intrinsics such as `memcpy`.
    ///
    /// [1]: https://github.com/rust-lang/compiler-builtins
    CompilerBuiltinsMem,

    /// This enables the `c` feature of [`compiler_builtins`][1],
    /// which enables compilation of `C` code and may result in more
    /// optimized implementations, and fills in the rare unimplemented
    /// intrinsics.
    ///
    /// [1]: https://github.com/rust-lang/compiler-builtins
    CompilerBuiltinsC,

    /// This enables the `no-asm` feature of [`compiler_builtins`][1],
    /// which disables any implementations which use
    /// inline assembly and fall back to pure Rust versions (if available).
    ///
    /// [1]: https://github.com/rust-lang/compiler-builtins
    // TODO: Would only work on the [`Sysroot::CompilerBuiltins`] target,
    // as it's not exported through alloc, but could be forced by
    // adding compiler_builtins as an explicit dependency and enabling it,
    // relying on features collapsing.
    CompilerBuiltinsNoAsm,
}

/// A builder interface for constructing the Sysroot
///
/// See the individual methods for more details on what this means
/// and what defaults exist.
#[derive(Debug, Clone)]
pub struct SysrootBuilder {
    /// Manifest to use for cargo profiles
    manifest: Option<PathBuf>,

    /// Output directory, where the built sysroot will be anchored.
    output: PathBuf,

    /// Target triple/json to build for
    target: Option<PathBuf>,

    /// The rust sources to use
    rust_src: Option<PathBuf>,

    /// Which crates to include in the sysroot
    sysroot_crate: Sysroot,

    /// What custom features to enable, if any. See [`Features`] for details.
    features: Vec<Features>,

    /// Custom flags to pass to rustc.
    rustc_flags: Vec<OsString>,
}

impl SysrootBuilder {
    /// New [`SysrootBuilder`].
    ///
    /// `sysroot_crate` specifies which libraries to build as part of
    /// the sysroot. See [`Sysroot`] for more details.
    pub fn new(sysroot_crate: Sysroot) -> Self {
        Self {
            manifest: Default::default(),
            output: PathBuf::from(".").join("target").join("sysroot"),
            target: Default::default(),
            // Set in [`SysrootBuilder::build`] since `new` can't error.
            rust_src: Default::default(),
            sysroot_crate,
            features: Vec::with_capacity(3),
            rustc_flags: Default::default(),
        }
    }

    /// Set path to the `Cargo.toml` of the project requiring a custom sysroot.
    ///
    /// If provided, any [Cargo Profile's][1] in the provided manifest
    /// will be copied into the sysroot crate being compiled.
    ///
    /// If not provided, profiles use their default settings.
    ///
    /// By default this will be `None`.
    ///
    /// [1]: https://doc.rust-lang.org/stable/cargo/reference/profiles.html
    pub fn manifest(&mut self, manifest: PathBuf) -> &mut Self {
        self.manifest = Some(manifest);
        self
    }

    /// Set where the sysroot directory will be placed.
    ///
    /// By default this is `./target/sysroot`.
    pub fn output(&mut self, output: PathBuf) -> &mut Self {
        self.output = output;
        self
    }

    /// The target to compile *for*. This can be a target-triple,
    /// or a [JSON Target Specification][1].
    ///
    /// By default this is `None`, and if not set when
    /// [`SysrootBuilder::build`] is called, will cause an error.
    ///
    /// [1]: https://doc.rust-lang.org/rustc/targets/custom.html
    pub fn target(&mut self, target: PathBuf) -> &mut Self {
        self.target = Some(target);
        self
    }

    /// The rust source directory. These are used to compile the sysroot.
    ///
    /// By default this uses the `rust-src` component from the
    /// current `rustup` toolchain.
    pub fn rust_src(&mut self, rust_src: PathBuf) -> &mut Self {
        self.rust_src = Some(rust_src);
        self
    }

    /// Which features to enable.
    ///
    /// This *adds* to, not *replaces*, any previous calls to this method.
    ///
    /// By default this is empty.
    ///
    /// See [`Features`] for details.
    pub fn features(&mut self, features: &[Features]) -> &mut Self {
        self.features.extend_from_slice(features);
        // TODO: Should?? Not??
        self.features.sort_unstable();
        self.features.dedup();
        self
    }

    /// Custom flags to pass to **all** `rustc` compiler invocations.
    ///
    /// This *adds* to, not *replaces*, any previous calls to this method.
    ///
    /// By default this is empty.
    ///
    /// # Internal
    ///
    /// This will use the `RUSTFLAGS` to ensure flags are set for all
    /// invocations.
    ///
    /// Flags passed to this method will be *appended*
    /// to any existing `RUSTFLAGS`.
    pub fn rustc_flags<I, S>(&mut self, flags: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        self.rustc_flags.extend(flags.into_iter().map(Into::into));
        self
    }

    /// Build the Sysroot, and return a path suitable to pass to rustc.
    ///
    /// # Errors
    ///
    /// - [`SysrootBuilder::target`] was not called
    /// - If `manifest` is provided and does not exist
    /// - If `target` is a JSON specification, but doesn't exist.
    /// - If the `rust_src` directory does not exist, or could not be detected.
    /// - If the sysroot cannot be setup, or fails to compile
    pub fn build(&self) -> Result<PathBuf> {
        let target = match &self.target {
            Some(t) => t,
            None => return Err(anyhow!("SysrootBuilder::target was not called")),
        };
        if let Some(manifest) = &self.manifest {
            if !manifest.exists() {
                return Err(anyhow!(
                    "Provided manifest did not exist. Path: {}",
                    manifest.display()
                ));
            }
        }
        // If `target` has an extension, assume target spec...
        if target.extension().is_some() {
            // ...and check if it exists.
            if !target.exists() {
                return Err(anyhow!(
                    "Provided JSON Target Specification did not exist: {}",
                    target.display()
                ));
            }
        }
        let rust_src = match &self.rust_src {
            Some(s) => {
                if !s.exists() {
                    return Err(anyhow!(
                        "The provided rust-src directory did not exist: {}",
                        s.display()
                    ));
                }
                s.clone()
            }
            None => {
                let src = util::get_rust_src().context("Could not detect appropriate rust-src")?;
                if !src.exists() {
                    return Err(anyhow!("Rust-src component not installed?"));
                }
                src
            }
        };
        fs::create_dir_all(&self.output).context("Couldn't create sysroot output directory")?;
        fs::create_dir_all(artifact_dir(&self.output, target)?)
            .context("Failed to setup sysroot directory structure")?;

        let sysroot_cargo_toml = generate_sysroot_cargo_toml(&SysrootBuilder {
            // HACK: So it can see auto-detected rust-src.
            rust_src: Some(rust_src),
            ..self.clone()
        })?;
        build_alloc(&sysroot_cargo_toml, &self).context("Failed to build sysroot")?;

        // Copy host tools to the new sysroot, so that stuff like proc-macros and
        // testing can work.
        util::copy_host_tools(&self.output).context("Couldn't copy host tools to sysroot")?;
        Ok(self.output.canonicalize().with_context(|| {
            format!(
                "Couldn't get canonical path to sysroot: {}",
                self.output.display()
            )
        })?)
    }
}

/// Generate a Cargo.toml for building the sysroot crates
///
/// Should ONLY be called by [`SysrootBuilder::build`].
///
/// See [`build_sysroot_with`].
fn generate_sysroot_cargo_toml(builder: &SysrootBuilder) -> Result<PathBuf> {
    fs::write(
        builder.output.join("lib.rs"),
        "#![feature(no_core)]\n#![no_core]",
    )?;
    let toml = CargoToml {
        package: Package {
            name: "Sysroot".into(),
            version: "0.0.0".into(),
            authors: vec!["The Rust Project Developers".into(), "DianaNites".into()],
            edition: Some("2018".into()),
            autotests: Some(false),
            autobenches: Some(false),
            ..Default::default()
        },
        lib: Some(TargetConfig {
            name: Some("sysroot".into()),
            path: Some("lib.rs".into()),
            ..Default::default()
        }),
        workspace: Some(Workspace::default()),
        dependencies: Some({
            let mut deps = BTreeMap::new();
            match builder.sysroot_crate {
                Sysroot::Core => {
                    deps.insert(
                        "core".into(),
                        Dependency::Full(DependencyFull {
                            path: Some(builder.rust_src.as_ref().unwrap().join("core")),
                            ..Default::default()
                        }),
                    );
                }

                Sysroot::CompilerBuiltins => {
                    deps.insert(
                        "compiler_builtins".into(),
                        Dependency::Full(DependencyFull {
                            version: Some("0.1".into()),
                            features: {
                                let mut f = vec!["rustc-dep-of-std".into()];
                                if builder.features.contains(&Features::CompilerBuiltinsMem) {
                                    f.push("mem".into());
                                }
                                Some(f)
                            },
                            ..Default::default()
                        }),
                    );
                }

                Sysroot::Alloc => {
                    deps.insert(
                        "alloc".into(),
                        Dependency::Full(DependencyFull {
                            path: Some(builder.rust_src.as_ref().unwrap().join("alloc")),
                            features: if builder.features.contains(&Features::CompilerBuiltinsMem) {
                                Some(vec!["compiler-builtins-mem".into()])
                            } else {
                                None
                            },
                            ..Default::default()
                        }),
                    );
                }

                Sysroot::Std => {
                    deps.insert(
                        "std".into(),
                        Dependency::Full(DependencyFull {
                            path: Some(builder.rust_src.as_ref().unwrap().join("std")),
                            features: if builder.features.contains(&Features::CompilerBuiltinsMem) {
                                Some(vec!["compiler-builtins-mem".into()])
                            } else {
                                None
                            },
                            ..Default::default()
                        }),
                    );
                }
            }
            deps
        }),
        patch: Some(Patches {
            sources: if let Sysroot::Core = builder.sysroot_crate {
                BTreeMap::new()
            } else {
                let mut sources = BTreeMap::new();
                sources.insert("crates-io".into(), {
                    let mut x = BTreeMap::new();
                    x.insert(
                        "rustc-std-workspace-core".to_string(),
                        Dependency::Full(DependencyFull {
                            path: Some(
                                builder
                                    .rust_src
                                    .as_ref()
                                    .unwrap()
                                    .join("rustc-std-workspace-core"),
                            ),
                            ..Default::default()
                        }),
                    );
                    x
                });
                sources
            },
        }),
        profile: {
            match &builder.manifest {
                Some(manifest) => {
                    let toml: CargoToml =
                        from_path(manifest).with_context(|| manifest.display().to_string())?;
                    toml.profile
                }
                None => None,
            }
        },
        ..Default::default()
    };
    let path = builder.output.join("Cargo.toml");
    to_path(&path, &toml).context("Failed writing sysroot Cargo.toml")?;
    Ok(path)
}

/// The entry-point for building the alloc crate, which builds all the others
///
/// Should ONLY be called by [`SysrootBuilder::build`].
fn build_alloc(alloc_cargo_toml: &Path, builder: &SysrootBuilder) -> Result<()> {
    let path = alloc_cargo_toml;
    let triple = builder.target.as_ref().unwrap();
    let target_dir = builder.output.join("target");

    // TODO: Eat output if up to date? Always? On error?
    let exit = Command::new(env::var_os("CARGO").unwrap_or_else(|| "cargo".into()))
        .arg("rustc")
        .arg("--release")
        .arg("--target")
        // If it doesn't work, assume it's a builtin path?
        .arg(&triple.canonicalize().unwrap_or_else(|_| triple.into()))
        .arg("--target-dir")
        .arg(&target_dir)
        .arg("--manifest-path")
        .arg(path)
        .arg("--") // Pass to rustc directly.
        .arg("-Z")
        // The rust build system only passes this for rustc? xbuild passes this for alloc. 🤷‍♀️
        .arg("force-unstable-if-unmarked")
        .env("RUSTFLAGS", {
            let mut env = OsString::new();
            if let Some(exist) = std::env::var_os("RUSTFLAGS") {
                env.push(exist);
            }
            for flag in &builder.rustc_flags {
                env.push(" ");
                env.push(flag)
            }
            env
        })
        // Causes clippy to leak output
        // See #6
        .env_remove("RUSTC_WORKSPACE_WRAPPER")
        .status()
        .context("Couldn't find/run cargo command")?;
    if !exit.success() {
        return Err(anyhow!(
            "Failed to build sysroot: Exit code {}",
            exit.code()
                .map(|i| i.to_string())
                .unwrap_or_else(|| "Killed by signal".to_string())
        ));
    }

    // Copy artifacts to sysroot.
    for entry in fs::read_dir(
        target_dir
            .join(
                &triple
                    .file_stem()
                    .context("Failed to parse target triple")?,
            )
            .join("release")
            .join("deps"),
    )
    .context("Failure to read artifact directory")?
    {
        let entry = entry?;
        let name = entry
            .file_name()
            .into_string()
            .map_err(|e| Error::msg(e.to_string_lossy().to_string()))
            .context("Invalid Unicode in path")?;
        if name.starts_with("lib") {
            let out = artifact_dir(&builder.output, &triple)?.join(name);
            fs::copy(entry.path(), &out).with_context(|| {
                format!(
                    "Copying sysroot artifact from {} to {} failed",
                    entry.path().display(),
                    out.display()
                )
            })?;
        }
    }

    Ok(())
}

/// The output artifact directory
///
/// Not part of the public API.
fn artifact_dir(sysroot_dir: &Path, target: &Path) -> Result<PathBuf> {
    Ok(sysroot_dir
        .join("lib")
        .join("rustlib")
        .join(target.file_stem().context("Invalid Target Specification")?)
        .join("lib"))
}

/// Clean up generated sysroot artifacts.
///
/// Should be called before [`build_sysroot`] if you want this behavior.
pub fn clean_artifacts(sysroot_dir: &Path) -> Result<()> {
    // Clean-up old artifacts
    match remove_dir_all::remove_dir_all(sysroot_dir) {
        Ok(_) => (),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
        e => e.context("Couldn't clean sysroot artifacts")?,
    };
    Ok(())
}