Skip to content

Commit ab6a6eb

Browse files
committed
Apple: Refactor deployment target version parsing
- Merge minimum OS version list into one function (makes it easier to see the logic in it). - Parse patch deployment target versions. - Consistently specify deployment target in LLVM target (previously omitted on `aarch64-apple-watchos`).
1 parent cf98e6f commit ab6a6eb

28 files changed

+322
-363
lines changed

compiler/rustc_codegen_ssa/src/back/metadata.rs

+24-9
Original file line numberDiff line numberDiff line change
@@ -372,27 +372,42 @@ pub(crate) fn create_object_file(sess: &Session) -> Option<write::Object<'static
372372
Some(file)
373373
}
374374

375-
/// Since Xcode 15 Apple's LD requires object files to contain information about what they were
376-
/// built for (LC_BUILD_VERSION): the platform (macOS/watchOS etc), minimum OS version, and SDK
377-
/// version. This returns a `MachOBuildVersion` for the target.
375+
/// Mach-O files contain information about:
376+
/// - The platform/OS they were built for (macOS/watchOS/Mac Catalyst/iOS simulator etc).
377+
/// - The minimum OS version / deployment target.
378+
/// - The version of the SDK they were targetting.
379+
///
380+
/// In the past, this was accomplished using the LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
381+
/// LC_VERSION_MIN_TVOS or LC_VERSION_MIN_WATCHOS load commands, which each contain information
382+
/// about the deployment target and SDK version, and implicitly, by their presence, which OS they
383+
/// target. Simulator targets were determined if the architecture was x86_64, but there was e.g. a
384+
/// LC_VERSION_MIN_IPHONEOS present.
385+
///
386+
/// This is of course brittle and limited, so modern tooling emit the LC_BUILD_VERSION load
387+
/// command (which contains all three pieces of information in one) when the deployment target is
388+
/// high enough, or the target is something that wouldn't be encodable with the old load commands
389+
/// (such as Mac Catalyst, or Aarch64 iOS simulator).
390+
///
391+
/// Since Xcode 15, Apple's LD apparently requires object files to use this load command, so this
392+
/// returns the `MachOBuildVersion` for the target to do so.
378393
fn macho_object_build_version_for_target(target: &Target) -> object::write::MachOBuildVersion {
379394
/// The `object` crate demands "X.Y.Z encoded in nibbles as xxxx.yy.zz"
380395
/// e.g. minOS 14.0 = 0x000E0000, or SDK 16.2 = 0x00100200
381-
fn pack_version((major, minor): (u32, u32)) -> u32 {
382-
(major << 16) | (minor << 8)
396+
fn pack_version((major, minor, patch): (u16, u8, u8)) -> u32 {
397+
let (major, minor, patch) = (major as u32, minor as u32, patch as u32);
398+
(major << 16) | (minor << 8) | patch
383399
}
384400

385401
let platform =
386402
rustc_target::spec::current_apple_platform(target).expect("unknown Apple target OS");
387-
let min_os = rustc_target::spec::current_apple_deployment_target(target)
388-
.expect("unknown Apple target OS");
389-
let sdk =
403+
let min_os = rustc_target::spec::current_apple_deployment_target(target);
404+
let (sdk_major, sdk_minor) =
390405
rustc_target::spec::current_apple_sdk_version(platform).expect("unknown Apple target OS");
391406

392407
let mut build_version = object::write::MachOBuildVersion::default();
393408
build_version.platform = platform;
394409
build_version.minos = pack_version(min_os);
395-
build_version.sdk = pack_version(sdk);
410+
build_version.sdk = pack_version((sdk_major, sdk_minor, 0));
396411
build_version
397412
}
398413

compiler/rustc_driver_impl/src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -871,9 +871,9 @@ fn print_crate_info(
871871
use rustc_target::spec::current_apple_deployment_target;
872872

873873
if sess.target.is_like_osx {
874-
let (major, minor) = current_apple_deployment_target(&sess.target)
875-
.expect("unknown Apple target OS");
876-
println_info!("deployment_target={}", format!("{major}.{minor}"))
874+
let (major, minor, patch) = current_apple_deployment_target(&sess.target);
875+
let patch = if patch != 0 { format!(".{patch}") } else { String::new() };
876+
println_info!("deployment_target={major}.{minor}{patch}")
877877
} else {
878878
#[allow(rustc::diagnostic_outside_of_impl)]
879879
sess.dcx().fatal("only Apple targets currently support deployment version info")

compiler/rustc_target/src/spec/base/apple/mod.rs

+125-137
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::borrow::Cow;
22
use std::env;
3+
use std::num::ParseIntError;
34

45
use crate::spec::{
56
add_link_args, add_link_args_iter, cvs, Cc, DebuginfoKind, FramePointer, LinkArgs,
@@ -123,15 +124,8 @@ fn pre_link_args(os: &'static str, arch: Arch, abi: TargetAbi) -> LinkArgs {
123124
};
124125

125126
let min_version: StaticCow<str> = {
126-
let (major, minor) = match os {
127-
"ios" => ios_deployment_target(arch, abi.target_abi()),
128-
"tvos" => tvos_deployment_target(),
129-
"watchos" => watchos_deployment_target(),
130-
"visionos" => visionos_deployment_target(),
131-
"macos" => macos_deployment_target(arch),
132-
_ => unreachable!(),
133-
};
134-
format!("{major}.{minor}").into()
127+
let (major, minor, patch) = deployment_target(os, arch, abi);
128+
format!("{major}.{minor}.{patch}").into()
135129
};
136130
let sdk_version = min_version.clone();
137131

@@ -161,15 +155,22 @@ fn pre_link_args(os: &'static str, arch: Arch, abi: TargetAbi) -> LinkArgs {
161155
add_link_args_iter(
162156
&mut args,
163157
LinkerFlavor::Darwin(Cc::Yes, Lld::No),
164-
["-target".into(), mac_catalyst_llvm_target(arch).into()].into_iter(),
158+
["-target".into(), llvm_target(os, arch, abi)].into_iter(),
165159
);
166160
}
167161

168162
args
169163
}
170164

171-
pub(crate) fn opts(os: &'static str, arch: Arch, abi: TargetAbi) -> TargetOptions {
172-
TargetOptions {
165+
/// Get the base target options, LLVM target and `target_arch` from the three
166+
/// things that uniquely identify Rust's Apple targets: The OS, the
167+
/// architecture, and the ABI.
168+
pub(crate) fn base(
169+
os: &'static str,
170+
arch: Arch,
171+
abi: TargetAbi,
172+
) -> (TargetOptions, StaticCow<str>, StaticCow<str>) {
173+
let opts = TargetOptions {
173174
abi: abi.target_abi().into(),
174175
os: os.into(),
175176
cpu: arch.target_cpu(abi).into(),
@@ -219,10 +220,11 @@ pub(crate) fn opts(os: &'static str, arch: Arch, abi: TargetAbi) -> TargetOption
219220
link_env: Cow::Borrowed(&[(Cow::Borrowed("ZERO_AR_DATE"), Cow::Borrowed("1"))]),
220221

221222
..Default::default()
222-
}
223+
};
224+
(opts, llvm_target(os, arch, abi), arch.target_arch())
223225
}
224226

225-
pub fn sdk_version(platform: u32) -> Option<(u32, u32)> {
227+
pub fn sdk_version(platform: u32) -> Option<(u16, u8)> {
226228
// NOTE: These values are from an arbitrary point in time but shouldn't make it into the final
227229
// binary since the final link command will have the current SDK version passed to it.
228230
match platform {
@@ -256,58 +258,108 @@ pub fn platform(target: &Target) -> Option<u32> {
256258
})
257259
}
258260

259-
pub fn deployment_target(target: &Target) -> Option<(u32, u32)> {
260-
let (major, minor) = match &*target.os {
261-
"macos" => {
262-
// This does not need to be specific. It just needs to handle x86 vs M1.
263-
let arch = match target.arch.as_ref() {
264-
"x86" | "x86_64" => X86_64,
265-
"arm64e" => Arm64e,
266-
_ => Arm64,
267-
};
268-
macos_deployment_target(arch)
269-
}
270-
"ios" => {
271-
let arch = match target.arch.as_ref() {
272-
"arm64e" => Arm64e,
273-
_ => Arm64,
274-
};
275-
ios_deployment_target(arch, &target.abi)
276-
}
277-
"watchos" => watchos_deployment_target(),
278-
"tvos" => tvos_deployment_target(),
279-
"visionos" => visionos_deployment_target(),
280-
_ => return None,
261+
/// Hack for calling `deployment_target` outside of this module.
262+
pub fn deployment_target_for_target(target: &Target) -> (u16, u8, u8) {
263+
let arch = if target.llvm_target.starts_with("arm64e") {
264+
Arch::Arm64e
265+
} else if target.arch == "aarch64" {
266+
Arch::Arm64
267+
} else {
268+
// Dummy architecture, only used by `deployment_target` anyhow
269+
Arch::X86_64
281270
};
282-
283-
Some((major, minor))
271+
let abi = match &*target.abi {
272+
"macabi" => TargetAbi::MacCatalyst,
273+
"sim" => TargetAbi::Simulator,
274+
"" => TargetAbi::Normal,
275+
abi => unreachable!("invalid abi '{abi}' for Apple target"),
276+
};
277+
deployment_target(&target.os, arch, abi)
284278
}
285279

286-
fn from_set_deployment_target(var_name: &str) -> Option<(u32, u32)> {
287-
let deployment_target = env::var(var_name).ok()?;
288-
let (unparsed_major, unparsed_minor) = deployment_target.split_once('.')?;
289-
let (major, minor) = (unparsed_major.parse().ok()?, unparsed_minor.parse().ok()?);
280+
/// Get the deployment target based on the standard environment variables, or
281+
/// fall back to a sane default.
282+
fn deployment_target(os: &str, arch: Arch, abi: TargetAbi) -> (u16, u8, u8) {
283+
// When bumping a version in here, remember to update the platform-support
284+
// docs too.
285+
//
286+
// NOTE: If you are looking for the default deployment target, prefer
287+
// `rustc --print deployment-target`, as the default here may change in
288+
// future `rustc` versions.
289+
290+
// Minimum operating system versions currently supported by `rustc`.
291+
let os_min = match os {
292+
"macos" => (10, 12, 0),
293+
"ios" => (10, 0, 0),
294+
"tvos" => (10, 0, 0),
295+
"watchos" => (5, 0, 0),
296+
"visionos" => (1, 0, 0),
297+
_ => unreachable!("tried to get deployment target for non-Apple platform"),
298+
};
290299

291-
Some((major, minor))
292-
}
300+
// On certain targets it makes sense to raise the minimum OS version.
301+
let min = match (os, arch, abi) {
302+
// Use 11.0 on Aarch64 as that's the earliest version with M1 support.
303+
("macos", Arch::Arm64 | Arch::Arm64e, _) => (11, 0, 0),
304+
("ios", Arch::Arm64e, _) => (14, 0, 0),
305+
// Mac Catalyst defaults to 13.1 in Clang.
306+
("ios", _, TargetAbi::MacCatalyst) => (13, 1, 0),
307+
_ => os_min,
308+
};
293309

294-
fn macos_default_deployment_target(arch: Arch) -> (u32, u32) {
295-
match arch {
296-
Arm64 | Arm64e => (11, 0),
297-
_ => (10, 12),
298-
}
299-
}
310+
// The environment variable used to fetch the deployment target.
311+
let env_var = match os {
312+
"macos" => "MACOSX_DEPLOYMENT_TARGET",
313+
"ios" => "IPHONEOS_DEPLOYMENT_TARGET",
314+
"watchos" => "WATCHOS_DEPLOYMENT_TARGET",
315+
"tvos" => "TVOS_DEPLOYMENT_TARGET",
316+
"visionos" => "XROS_DEPLOYMENT_TARGET",
317+
_ => unreachable!("tried to get deployment target env var for non-Apple platform"),
318+
};
300319

301-
fn macos_deployment_target(arch: Arch) -> (u32, u32) {
302-
// If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
303-
// Note: If bumping this version, remember to update it in the rustc/platform-support docs.
304-
from_set_deployment_target("MACOSX_DEPLOYMENT_TARGET")
305-
.unwrap_or_else(|| macos_default_deployment_target(arch))
320+
if let Ok(deployment_target) = env::var(env_var) {
321+
match parse_version(&deployment_target) {
322+
// It is common that the deployment target is set too low, e.g. on
323+
// macOS Aarch64 to also target older x86_64, the user may set a
324+
// lower deployment target than supported.
325+
//
326+
// To avoid such issues, we silently raise the deployment target
327+
// here.
328+
// FIXME: We want to show a warning when `version < os_min`.
329+
Ok(version) => version.max(min),
330+
// FIXME: Report erroneous environment variable to user.
331+
Err(_) => min,
332+
}
333+
} else {
334+
min
335+
}
306336
}
307337

308-
pub(crate) fn macos_llvm_target(arch: Arch) -> String {
309-
let (major, minor) = macos_deployment_target(arch);
310-
format!("{}-apple-macosx{}.{}.0", arch.target_name(), major, minor)
338+
/// Generate the target triple that we need to pass to LLVM and/or Clang.
339+
fn llvm_target(os: &str, arch: Arch, abi: TargetAbi) -> StaticCow<str> {
340+
// The target triple depends on the deployment target, and is required to
341+
// enable features such as cross-language LTO, and for picking the right
342+
// Mach-O commands.
343+
//
344+
// Certain optimizations also depend on the deployment target.
345+
let (major, minor, patch) = deployment_target(os, arch, abi);
346+
let arch = arch.target_name();
347+
// Convert to the "canonical" OS name used by LLVM:
348+
// https://github.com/llvm/llvm-project/blob/llvmorg-18.1.8/llvm/lib/TargetParser/Triple.cpp#L236-L282
349+
let os = match os {
350+
"macos" => "macosx",
351+
"ios" => "ios",
352+
"watchos" => "watchos",
353+
"tvos" => "tvos",
354+
"visionos" => "xros",
355+
_ => unreachable!("tried to get LLVM target OS for non-Apple platform"),
356+
};
357+
let environment = match abi {
358+
TargetAbi::Normal => "",
359+
TargetAbi::MacCatalyst => "-macabi",
360+
TargetAbi::Simulator => "-simulator",
361+
};
362+
format!("{arch}-apple-{os}{major}.{minor}.{patch}{environment}").into()
311363
}
312364

313365
fn link_env_remove(os: &'static str) -> StaticCow<[StaticCow<str>]> {
@@ -347,83 +399,19 @@ fn link_env_remove(os: &'static str) -> StaticCow<[StaticCow<str>]> {
347399
}
348400
}
349401

350-
fn ios_deployment_target(arch: Arch, abi: &str) -> (u32, u32) {
351-
// If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
352-
// Note: If bumping this version, remember to update it in the rustc/platform-support docs.
353-
let (major, minor) = match (arch, abi) {
354-
(Arm64e, _) => (14, 0),
355-
// Mac Catalyst defaults to 13.1 in Clang.
356-
(_, "macabi") => (13, 1),
357-
_ => (10, 0),
358-
};
359-
from_set_deployment_target("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or((major, minor))
360-
}
361-
362-
pub(crate) fn ios_llvm_target(arch: Arch) -> String {
363-
// Modern iOS tooling extracts information about deployment target
364-
// from LC_BUILD_VERSION. This load command will only be emitted when
365-
// we build with a version specific `llvm_target`, with the version
366-
// set high enough. Luckily one LC_BUILD_VERSION is enough, for Xcode
367-
// to pick it up (since std and core are still built with the fallback
368-
// of version 7.0 and hence emit the old LC_IPHONE_MIN_VERSION).
369-
let (major, minor) = ios_deployment_target(arch, "");
370-
format!("{}-apple-ios{}.{}.0", arch.target_name(), major, minor)
371-
}
372-
373-
pub(crate) fn mac_catalyst_llvm_target(arch: Arch) -> String {
374-
let (major, minor) = ios_deployment_target(arch, "macabi");
375-
format!("{}-apple-ios{}.{}.0-macabi", arch.target_name(), major, minor)
376-
}
377-
378-
pub(crate) fn ios_sim_llvm_target(arch: Arch) -> String {
379-
let (major, minor) = ios_deployment_target(arch, "sim");
380-
format!("{}-apple-ios{}.{}.0-simulator", arch.target_name(), major, minor)
381-
}
382-
383-
fn tvos_deployment_target() -> (u32, u32) {
384-
// If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
385-
// Note: If bumping this version, remember to update it in the rustc platform-support docs.
386-
from_set_deployment_target("TVOS_DEPLOYMENT_TARGET").unwrap_or((10, 0))
387-
}
388-
389-
pub(crate) fn tvos_llvm_target(arch: Arch) -> String {
390-
let (major, minor) = tvos_deployment_target();
391-
format!("{}-apple-tvos{}.{}.0", arch.target_name(), major, minor)
392-
}
393-
394-
pub(crate) fn tvos_sim_llvm_target(arch: Arch) -> String {
395-
let (major, minor) = tvos_deployment_target();
396-
format!("{}-apple-tvos{}.{}.0-simulator", arch.target_name(), major, minor)
397-
}
398-
399-
fn watchos_deployment_target() -> (u32, u32) {
400-
// If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
401-
// Note: If bumping this version, remember to update it in the rustc platform-support docs.
402-
from_set_deployment_target("WATCHOS_DEPLOYMENT_TARGET").unwrap_or((5, 0))
403-
}
404-
405-
pub(crate) fn watchos_llvm_target(arch: Arch) -> String {
406-
let (major, minor) = watchos_deployment_target();
407-
format!("{}-apple-watchos{}.{}.0", arch.target_name(), major, minor)
408-
}
409-
410-
pub(crate) fn watchos_sim_llvm_target(arch: Arch) -> String {
411-
let (major, minor) = watchos_deployment_target();
412-
format!("{}-apple-watchos{}.{}.0-simulator", arch.target_name(), major, minor)
413-
}
414-
415-
fn visionos_deployment_target() -> (u32, u32) {
416-
// If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
417-
// Note: If bumping this version, remember to update it in the rustc platform-support docs.
418-
from_set_deployment_target("XROS_DEPLOYMENT_TARGET").unwrap_or((1, 0))
419-
}
420-
421-
pub(crate) fn visionos_llvm_target(arch: Arch) -> String {
422-
let (major, minor) = visionos_deployment_target();
423-
format!("{}-apple-visionos{}.{}.0", arch.target_name(), major, minor)
424-
}
425-
426-
pub(crate) fn visionos_sim_llvm_target(arch: Arch) -> String {
427-
let (major, minor) = visionos_deployment_target();
428-
format!("{}-apple-visionos{}.{}.0-simulator", arch.target_name(), major, minor)
402+
/// Parse an OS version triple (SDK version or deployment target).
403+
///
404+
/// The size of the returned numbers here are limited by Mach-O's
405+
/// `LC_BUILD_VERSION`.
406+
fn parse_version(version: &str) -> Result<(u16, u8, u8), ParseIntError> {
407+
if let Some((major, minor)) = version.split_once('.') {
408+
let major = major.parse()?;
409+
if let Some((minor, patch)) = minor.split_once('.') {
410+
Ok((major, minor.parse()?, patch.parse()?))
411+
} else {
412+
Ok((major, minor.parse()?, 0))
413+
}
414+
} else {
415+
Ok((version.parse()?, 0, 0))
416+
}
429417
}

compiler/rustc_target/src/spec/base/apple/tests.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use super::parse_version;
12
use crate::spec::targets::{
23
aarch64_apple_darwin, aarch64_apple_ios_sim, aarch64_apple_visionos_sim,
34
aarch64_apple_watchos_sim, i686_apple_darwin, x86_64_apple_darwin, x86_64_apple_ios,
@@ -42,3 +43,11 @@ fn macos_link_environment_unmodified() {
4243
);
4344
}
4445
}
46+
47+
#[test]
48+
fn test_parse_version() {
49+
assert_eq!(parse_version("10"), Ok((10, 0, 0)));
50+
assert_eq!(parse_version("10.12"), Ok((10, 12, 0)));
51+
assert_eq!(parse_version("10.12.6"), Ok((10, 12, 6)));
52+
assert_eq!(parse_version("9999.99.99"), Ok((9999, 99, 99)));
53+
}

0 commit comments

Comments
 (0)