nextest_runner/
platform.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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Platform-related data structures.

use crate::{
    RustcCli,
    cargo_config::{CargoTargetArg, TargetTriple},
    errors::{
        DisplayErrorChain, HostPlatformDetectError, RustBuildMetaParseError, TargetTripleError,
    },
    reuse_build::{LibdirMapper, PlatformLibdirMapper},
};
use camino::{Utf8Path, Utf8PathBuf};
use indent_write::indentable::Indented;
use nextest_metadata::{
    BuildPlatformsSummary, HostPlatformSummary, PlatformLibdirSummary, PlatformLibdirUnavailable,
    TargetPlatformSummary,
};
pub use target_spec::Platform;
use target_spec::{
    TargetFeatures, errors::RustcVersionVerboseParseError, summaries::PlatformSummary,
};
use tracing::{debug, warn};

/// A representation of host and target platform.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildPlatforms {
    /// The host platform.
    pub host: HostPlatform,

    /// The target platform, if specified.
    ///
    /// In the future, this will support multiple targets.
    pub target: Option<TargetPlatform>,
}

impl BuildPlatforms {
    /// Creates a new `BuildPlatforms` with no libdirs or targets.
    ///
    /// Used for testing.
    pub fn new_with_no_target() -> Result<Self, HostPlatformDetectError> {
        Ok(Self {
            host: HostPlatform {
                // Because this is for testing, we just use the build target
                // rather than `rustc -vV` output.
                platform: Platform::build_target().map_err(|build_target_error| {
                    HostPlatformDetectError::BuildTargetError {
                        build_target_error: Box::new(build_target_error),
                    }
                })?,
                libdir: PlatformLibdir::Unavailable(PlatformLibdirUnavailable::new_const("test")),
            },
            target: None,
        })
    }

    /// Maps libdir paths.
    pub fn map_libdir(&self, mapper: &LibdirMapper) -> Self {
        Self {
            host: self.host.map_libdir(&mapper.host),
            target: self
                .target
                .as_ref()
                .map(|target| target.map_libdir(&mapper.target)),
        }
    }

    /// Returns the argument to pass into `cargo metadata --filter-platform <triple>`.
    pub fn to_cargo_target_arg(&self) -> Result<CargoTargetArg, TargetTripleError> {
        match &self.target {
            Some(target) => target.triple.to_cargo_target_arg(),
            None => {
                // If there's no target, use the host platform.
                Ok(CargoTargetArg::Builtin(
                    self.host.platform.triple_str().to_owned(),
                ))
            }
        }
    }

    /// Converts self to a summary.
    pub fn to_summary(&self) -> BuildPlatformsSummary {
        BuildPlatformsSummary {
            host: self.host.to_summary(),
            targets: self
                .target
                .as_ref()
                .map(|target| vec![target.to_summary()])
                .unwrap_or_default(),
        }
    }

    /// Converts self to a single summary.
    ///
    /// Pairs with [`Self::from_target_summary`]. Deprecated in favor of [`BuildPlatformsSummary`].
    pub fn to_target_or_host_summary(&self) -> PlatformSummary {
        if let Some(target) = &self.target {
            target.triple.platform.to_summary()
        } else {
            self.host.platform.to_summary()
        }
    }

    /// Converts a target triple to a [`String`] that can be stored in the build-metadata.
    ///
    /// Only for backward compatibility. Deprecated in favor of [`BuildPlatformsSummary`].
    pub fn to_summary_str(&self) -> Option<String> {
        self.target
            .as_ref()
            .map(|triple| triple.triple.platform.triple_str().to_owned())
    }

    /// Converts a summary to a [`BuildPlatforms`].
    pub fn from_summary(summary: BuildPlatformsSummary) -> Result<Self, RustBuildMetaParseError> {
        Ok(BuildPlatforms {
            host: HostPlatform::from_summary(summary.host)?,
            target: {
                if summary.targets.len() > 1 {
                    return Err(RustBuildMetaParseError::Unsupported {
                        message: "multiple build targets is not supported".to_owned(),
                    });
                }
                summary
                    .targets
                    .first()
                    .map(|target| TargetPlatform::from_summary(target.clone()))
                    .transpose()?
            },
        })
    }

    /// Creates a [`BuildPlatforms`] from a single `PlatformSummary`.
    ///
    /// Only for backwards compatibility. Deprecated in favor of [`BuildPlatformsSummary`].
    pub fn from_target_summary(summary: PlatformSummary) -> Result<Self, RustBuildMetaParseError> {
        // In this case:
        //
        // * no libdirs are available
        // * the host might be serialized as the target platform as well (we can't detect this case
        //   reliably, so we treat it as the target platform as well, which isn't a problem in
        //   practice).
        let host = HostPlatform {
            // We don't necessarily have `rustc` available, so we use the build
            // target instead.
            platform: Platform::build_target()
                .map_err(RustBuildMetaParseError::DetectBuildTargetError)?,
            libdir: PlatformLibdir::Unavailable(PlatformLibdirUnavailable::OLD_SUMMARY),
        };

        let target = TargetTriple::deserialize(Some(summary))?.map(|triple| {
            TargetPlatform::new(
                triple,
                PlatformLibdir::Unavailable(PlatformLibdirUnavailable::OLD_SUMMARY),
            )
        });

        Ok(Self { host, target })
    }

    /// Creates a [`BuildPlatforms`] from a target triple.
    ///
    /// Only for backward compatibility. Deprecated in favor of [`BuildPlatformsSummary`].
    pub fn from_summary_str(summary: Option<String>) -> Result<Self, RustBuildMetaParseError> {
        // In this case:
        //
        // * no libdirs are available
        // * can't represent custom platforms
        // * the host might be serialized as the target platform as well (we can't detect this case
        //   reliably, so we treat it as the target platform as well, which isn't a problem in
        //   practice).
        let host = HostPlatform {
            // We don't necessarily have `rustc` available, so we use the build
            // target instead.
            platform: Platform::build_target()
                .map_err(RustBuildMetaParseError::DetectBuildTargetError)?,
            libdir: PlatformLibdir::Unavailable(PlatformLibdirUnavailable::OLD_SUMMARY),
        };

        let target = TargetTriple::deserialize_str(summary)?.map(|triple| {
            TargetPlatform::new(
                triple,
                PlatformLibdir::Unavailable(PlatformLibdirUnavailable::OLD_SUMMARY),
            )
        });

        Ok(Self { host, target })
    }
}

/// A representation of a host platform during a build.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HostPlatform {
    /// The platform.
    pub platform: Platform,

    /// The host libdir.
    pub libdir: PlatformLibdir,
}

impl HostPlatform {
    /// Creates a new `HostPlatform` representing the current platform by
    /// querying rustc.
    ///
    /// This may fall back to the build target if `rustc -vV` fails.
    pub fn detect(libdir: PlatformLibdir) -> Result<Self, HostPlatformDetectError> {
        let platform = detect_host_platform()?;
        Ok(Self { platform, libdir })
    }

    /// Converts self to a summary.
    pub fn to_summary(&self) -> HostPlatformSummary {
        HostPlatformSummary {
            platform: self.platform.to_summary(),
            libdir: self.libdir.to_summary(),
        }
    }

    /// Converts a summary to a [`HostPlatform`].
    pub fn from_summary(summary: HostPlatformSummary) -> Result<Self, RustBuildMetaParseError> {
        let platform = summary
            .platform
            .to_platform()
            .map_err(RustBuildMetaParseError::PlatformDeserializeError)?;
        Ok(Self {
            platform,
            libdir: PlatformLibdir::from_summary(summary.libdir),
        })
    }

    fn map_libdir(&self, mapper: &PlatformLibdirMapper) -> Self {
        Self {
            platform: self.platform.clone(),
            libdir: mapper.map(&self.libdir),
        }
    }
}

/// Detect the host platform by using `rustc -vV`, and falling back to the build
/// target.
///
/// Returns an error if both of those methods fail, and produces a warning if
/// `rustc -vV` fails.
fn detect_host_platform() -> Result<Platform, HostPlatformDetectError> {
    // A test-only environment variable to always make the build target a fixed
    // value, or to error out.
    const FORCE_BUILD_TARGET_VAR: &str = "__NEXTEST_FORCE_BUILD_TARGET";

    enum ForceBuildTarget {
        Triple(String),
        Error,
    }

    let force_build_target = match std::env::var(FORCE_BUILD_TARGET_VAR).as_deref() {
        Ok("error") => Some(ForceBuildTarget::Error),
        Ok(triple) => Some(ForceBuildTarget::Triple(triple.to_owned())),
        Err(_) => None,
    };

    let build_target = match force_build_target {
        Some(ForceBuildTarget::Triple(triple)) => Platform::new(triple, TargetFeatures::Unknown),
        Some(ForceBuildTarget::Error) => Err(target_spec::Error::RustcVersionVerboseParse(
            RustcVersionVerboseParseError::MissingHostLine {
                output: format!(
                    "({} set to \"error\", forcibly failing build target detection)\n",
                    FORCE_BUILD_TARGET_VAR
                ),
            },
        )),
        None => Platform::build_target(),
    };

    let rustc_vv = RustcCli::version_verbose()
        .to_expression()
        .stdout_capture()
        .stderr_capture()
        .unchecked();
    match rustc_vv.run() {
        Ok(output) => {
            if output.status.success() {
                // Neither `rustc` nor `cargo` tell us what target features are
                // enabled for the host, so we must use
                // `TargetFeatures::Unknown`.
                match Platform::from_rustc_version_verbose(output.stdout, TargetFeatures::Unknown) {
                    Ok(platform) => Ok(platform),
                    Err(host_platform_error) => {
                        match build_target {
                            Ok(build_target) => {
                                warn!(
                                    "for host platform, parsing `rustc -vV` failed; \
                                     falling back to build target `{}`\n\
                                     - host platform error:\n{}",
                                    build_target.triple().as_str(),
                                    DisplayErrorChain::new_with_initial_indent(
                                        "  ",
                                        host_platform_error
                                    ),
                                );
                                Ok(build_target)
                            }
                            Err(build_target_error) => {
                                // In this case, we can't do anything.
                                Err(HostPlatformDetectError::HostPlatformParseError {
                                    host_platform_error: Box::new(host_platform_error),
                                    build_target_error: Box::new(build_target_error),
                                })
                            }
                        }
                    }
                }
            } else {
                match build_target {
                    Ok(build_target) => {
                        warn!(
                            "for host platform, `rustc -vV` failed with {}; \
                             falling back to build target `{}`\n\
                             - `rustc -vV` stdout:\n{}\n\
                             - `rustc -vV` stderr:\n{}",
                            output.status,
                            build_target.triple().as_str(),
                            Indented {
                                item: String::from_utf8_lossy(&output.stdout),
                                indent: "  "
                            },
                            Indented {
                                item: String::from_utf8_lossy(&output.stderr),
                                indent: "  "
                            },
                        );
                        Ok(build_target)
                    }
                    Err(build_target_error) => {
                        // If the build target isn't available either, we
                        // can't do anything.
                        Err(HostPlatformDetectError::RustcVvFailed {
                            status: output.status,
                            stdout: output.stdout,
                            stderr: output.stderr,
                            build_target_error: Box::new(build_target_error),
                        })
                    }
                }
            }
        }
        Err(error) => {
            match build_target {
                Ok(build_target) => {
                    warn!(
                        "for host platform, failed to spawn `rustc -vV`; \
                         falling back to build target `{}`\n\
                         - host platform error:\n{}",
                        build_target.triple().as_str(),
                        DisplayErrorChain::new_with_initial_indent("  ", error),
                    );
                    Ok(build_target)
                }
                Err(build_target_error) => {
                    // If the build target isn't available either, we
                    // can't do anything.
                    Err(HostPlatformDetectError::RustcVvSpawnError {
                        error,
                        build_target_error: Box::new(build_target_error),
                    })
                }
            }
        }
    }
}

/// The target platform.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TargetPlatform {
    /// The target triple: the platform, along with its source and where it was obtained from.
    pub triple: TargetTriple,

    /// The target libdir.
    pub libdir: PlatformLibdir,
}

impl TargetPlatform {
    /// Creates a new [`TargetPlatform`].
    pub fn new(triple: TargetTriple, libdir: PlatformLibdir) -> Self {
        Self { triple, libdir }
    }

    /// Converts self to a summary.
    pub fn to_summary(&self) -> TargetPlatformSummary {
        TargetPlatformSummary {
            platform: self.triple.platform.to_summary(),
            libdir: self.libdir.to_summary(),
        }
    }

    /// Converts a summary to a [`TargetPlatform`].
    pub fn from_summary(summary: TargetPlatformSummary) -> Result<Self, RustBuildMetaParseError> {
        Ok(Self {
            triple: TargetTriple::deserialize(Some(summary.platform))
                .map_err(RustBuildMetaParseError::PlatformDeserializeError)?
                .expect("the input is not None, so the output must not be None"),
            libdir: PlatformLibdir::from_summary(summary.libdir),
        })
    }

    fn map_libdir(&self, mapper: &PlatformLibdirMapper) -> Self {
        Self {
            triple: self.triple.clone(),
            libdir: mapper.map(&self.libdir),
        }
    }
}

/// A platform libdir.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PlatformLibdir {
    /// The libdir is known and available.
    Available(Utf8PathBuf),

    /// The libdir is unavailable.
    Unavailable(PlatformLibdirUnavailable),
}

impl PlatformLibdir {
    /// Constructs a new `PlatformLibdir` from a `Utf8PathBuf`.
    pub fn from_path(path: Utf8PathBuf) -> Self {
        Self::Available(path)
    }

    /// Constructs a new `PlatformLibdir` from rustc's standard output.
    ///
    /// None implies that rustc failed, and will be stored as such.
    pub fn from_rustc_stdout(rustc_output: Option<Vec<u8>>) -> Self {
        fn inner(v: Option<Vec<u8>>) -> Result<Utf8PathBuf, PlatformLibdirUnavailable> {
            let v = v.ok_or(PlatformLibdirUnavailable::RUSTC_FAILED)?;

            let s = String::from_utf8(v).map_err(|e| {
                debug!("failed to convert the output to a string: {e}");
                PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR
            })?;

            let mut lines = s.lines();
            let Some(out) = lines.next() else {
                debug!("empty output");
                return Err(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR);
            };

            let trimmed = out.trim();
            if trimmed.is_empty() {
                debug!("empty output");
                return Err(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR);
            }

            // If there's another line, it must be empty.
            for line in lines {
                if !line.trim().is_empty() {
                    debug!("unexpected additional output: {line}");
                    return Err(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR);
                }
            }

            Ok(Utf8PathBuf::from(trimmed))
        }

        match inner(rustc_output) {
            Ok(path) => Self::Available(path),
            Err(error) => Self::Unavailable(error),
        }
    }

    /// Constructs a new `PlatformLibdir` from a `PlatformLibdirUnavailable`.
    pub fn from_unavailable(error: PlatformLibdirUnavailable) -> Self {
        Self::Unavailable(error)
    }

    /// Returns self as a path if available.
    pub fn as_path(&self) -> Option<&Utf8Path> {
        match self {
            Self::Available(path) => Some(path),
            Self::Unavailable(_) => None,
        }
    }

    /// Converts self to a summary.
    pub fn to_summary(&self) -> PlatformLibdirSummary {
        match self {
            Self::Available(path) => PlatformLibdirSummary::Available { path: path.clone() },
            Self::Unavailable(reason) => PlatformLibdirSummary::Unavailable {
                reason: reason.clone(),
            },
        }
    }

    /// Converts a summary to a [`PlatformLibdir`].
    pub fn from_summary(summary: PlatformLibdirSummary) -> Self {
        match summary {
            PlatformLibdirSummary::Available { path: libdir } => Self::Available(libdir),
            PlatformLibdirSummary::Unavailable { reason } => Self::Unavailable(reason),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_case::test_case;

    #[test]
    fn test_from_rustc_output_invalid() {
        // None.
        assert_eq!(
            PlatformLibdir::from_rustc_stdout(None),
            PlatformLibdir::Unavailable(PlatformLibdirUnavailable::RUSTC_FAILED),
        );

        // Empty input.
        assert_eq!(
            PlatformLibdir::from_rustc_stdout(Some(Vec::new())),
            PlatformLibdir::Unavailable(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR),
        );

        // A single empty line.
        assert_eq!(
            PlatformLibdir::from_rustc_stdout(Some(b"\n".to_vec())),
            PlatformLibdir::Unavailable(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR),
        );

        // Multiple lines.
        assert_eq!(
            PlatformLibdir::from_rustc_stdout(Some(b"/fake/libdir/1\n/fake/libdir/2\n".to_vec())),
            PlatformLibdir::Unavailable(PlatformLibdirUnavailable::RUSTC_OUTPUT_ERROR),
        );
    }

    #[test_case(b"/fake/libdir/22548", "/fake/libdir/22548"; "single line")]
    #[test_case(
        b"\t /fake/libdir\t \n\r",
        "/fake/libdir";
        "with leading or trailing whitespace"
    )]
    #[test_case(
        b"/fake/libdir/1\n\n",
        "/fake/libdir/1";
        "trailing newlines"
    )]
    fn test_read_from_rustc_output_valid(input: &[u8], actual: &str) {
        assert_eq!(
            PlatformLibdir::from_rustc_stdout(Some(input.to_vec())),
            PlatformLibdir::Available(actual.into()),
        );
    }
}