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
use std::{borrow::Cow, env};

use crate::spec::{add_link_args, add_link_args_iter};
use crate::spec::{cvs, Cc, DebuginfoKind, FramePointer, LinkArgs, LinkerFlavor, Lld};
use crate::spec::{SplitDebuginfo, StackProbeType, StaticCow, Target, TargetOptions};

#[cfg(test)]
mod tests;

use Arch::*;
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, PartialEq)]
pub enum Arch {
    Armv7k,
    Armv7s,
    Arm64,
    Arm64e,
    Arm64_32,
    I386,
    I386_sim,
    I686,
    X86_64,
    X86_64h,
    X86_64_sim,
    X86_64_macabi,
    Arm64_macabi,
    Arm64_sim,
}

impl Arch {
    pub fn target_name(self) -> &'static str {
        match self {
            Armv7k => "armv7k",
            Armv7s => "armv7s",
            Arm64 | Arm64_macabi | Arm64_sim => "arm64",
            Arm64e => "arm64e",
            Arm64_32 => "arm64_32",
            I386 | I386_sim => "i386",
            I686 => "i686",
            X86_64 | X86_64_sim | X86_64_macabi => "x86_64",
            X86_64h => "x86_64h",
        }
    }

    pub fn target_arch(self) -> Cow<'static, str> {
        Cow::Borrowed(match self {
            Armv7k | Armv7s => "arm",
            Arm64 | Arm64e | Arm64_32 | Arm64_macabi | Arm64_sim => "aarch64",
            I386 | I386_sim | I686 => "x86",
            X86_64 | X86_64_sim | X86_64_macabi | X86_64h => "x86_64",
        })
    }

    fn target_abi(self) -> &'static str {
        match self {
            Armv7k | Armv7s | Arm64 | Arm64e | Arm64_32 | I386 | I686 | X86_64 | X86_64h => "",
            X86_64_macabi | Arm64_macabi => "macabi",
            I386_sim | Arm64_sim | X86_64_sim => "sim",
        }
    }

    fn target_cpu(self) -> &'static str {
        match self {
            Armv7k => "cortex-a8",
            Armv7s => "swift", // iOS 10 is only supported on iPhone 5 or higher.
            Arm64 => "apple-a7",
            Arm64e => "apple-a12",
            Arm64_32 => "apple-s4",
            // Only macOS 10.12+ is supported, which means
            // all x86_64/x86 CPUs must be running at least penryn
            // https://github.com/llvm/llvm-project/blob/01f924d0e37a5deae51df0d77e10a15b63aa0c0f/clang/lib/Driver/ToolChains/Arch/X86.cpp#L79-L82
            I386 | I386_sim | I686 => "penryn",
            X86_64 | X86_64_sim => "penryn",
            X86_64_macabi => "penryn",
            // Note: `core-avx2` is slightly more advanced than `x86_64h`, see
            // comments (and disabled features) in `x86_64h_apple_darwin` for
            // details. It is a higher baseline then `penryn` however.
            X86_64h => "core-avx2",
            Arm64_macabi => "apple-a12",
            Arm64_sim => "apple-a12",
        }
    }

    fn stack_probes(self) -> StackProbeType {
        match self {
            Armv7k | Armv7s => StackProbeType::None,
            Arm64 | Arm64e | Arm64_32 | I386 | I386_sim | I686 | X86_64 | X86_64h | X86_64_sim
            | X86_64_macabi | Arm64_macabi | Arm64_sim => StackProbeType::Inline,
        }
    }
}

fn pre_link_args(os: &'static str, arch: Arch, abi: &'static str) -> LinkArgs {
    let platform_name: StaticCow<str> = match abi {
        "sim" => format!("{os}-simulator").into(),
        "macabi" => "mac-catalyst".into(),
        _ => os.into(),
    };

    let min_version: StaticCow<str> = {
        let (major, minor) = match os {
            "ios" => ios_deployment_target(arch, abi),
            "tvos" => tvos_deployment_target(),
            "watchos" => watchos_deployment_target(),
            "macos" => macos_deployment_target(arch),
            _ => unreachable!(),
        };
        format!("{major}.{minor}").into()
    };
    let sdk_version = min_version.clone();

    let mut args = TargetOptions::link_args(
        LinkerFlavor::Darwin(Cc::No, Lld::No),
        &["-arch", arch.target_name(), "-platform_version"],
    );
    add_link_args_iter(
        &mut args,
        LinkerFlavor::Darwin(Cc::No, Lld::No),
        [platform_name, min_version, sdk_version].into_iter(),
    );
    if abi != "macabi" {
        add_link_args(
            &mut args,
            LinkerFlavor::Darwin(Cc::Yes, Lld::No),
            &["-arch", arch.target_name()],
        );
    } else {
        add_link_args_iter(
            &mut args,
            LinkerFlavor::Darwin(Cc::Yes, Lld::No),
            ["-target".into(), mac_catalyst_llvm_target(arch).into()].into_iter(),
        );
    }

    args
}

pub fn opts(os: &'static str, arch: Arch) -> TargetOptions {
    let abi = arch.target_abi();

    TargetOptions {
        abi: abi.into(),
        os: os.into(),
        cpu: arch.target_cpu().into(),
        link_env_remove: link_env_remove(os),
        vendor: "apple".into(),
        linker_flavor: LinkerFlavor::Darwin(Cc::Yes, Lld::No),
        // macOS has -dead_strip, which doesn't rely on function_sections
        function_sections: false,
        dynamic_linking: true,
        pre_link_args: pre_link_args(os, arch, abi),
        families: cvs!["unix"],
        is_like_osx: true,
        // LLVM notes that macOS 10.11+ and iOS 9+ default
        // to v4, so we do the same.
        // https://github.com/llvm/llvm-project/blob/378778a0d10c2f8d5df8ceff81f95b6002984a4b/clang/lib/Driver/ToolChains/Darwin.cpp#L1203
        default_dwarf_version: 4,
        frame_pointer: FramePointer::Always,
        has_rpath: true,
        dll_suffix: ".dylib".into(),
        archive_format: "darwin".into(),
        // Thread locals became available with iOS 8 and macOS 10.7,
        // and both are far below our minimum.
        has_thread_local: true,
        abi_return_struct_as_int: true,
        emit_debug_gdb_scripts: false,
        eh_frame_header: false,
        stack_probes: arch.stack_probes(),

        debuginfo_kind: DebuginfoKind::DwarfDsym,
        // The historical default for macOS targets is to run `dsymutil` which
        // generates a packed version of debuginfo split from the main file.
        split_debuginfo: SplitDebuginfo::Packed,
        supported_split_debuginfo: Cow::Borrowed(&[
            SplitDebuginfo::Packed,
            SplitDebuginfo::Unpacked,
            SplitDebuginfo::Off,
        ]),

        // This environment variable is pretty magical but is intended for
        // producing deterministic builds. This was first discovered to be used
        // by the `ar` tool as a way to control whether or not mtime entries in
        // the archive headers were set to zero or not. It appears that
        // eventually the linker got updated to do the same thing and now reads
        // this environment variable too in recent versions.
        //
        // For some more info see the commentary on #47086
        link_env: Cow::Borrowed(&[(Cow::Borrowed("ZERO_AR_DATE"), Cow::Borrowed("1"))]),

        ..Default::default()
    }
}

pub fn sdk_version(platform: u32) -> Option<(u32, u32)> {
    // NOTE: These values are from an arbitrary point in time but shouldn't make it into the final
    // binary since the final link command will have the current SDK version passed to it.
    match platform {
        object::macho::PLATFORM_MACOS => Some((13, 1)),
        object::macho::PLATFORM_IOS
        | object::macho::PLATFORM_IOSSIMULATOR
        | object::macho::PLATFORM_TVOS
        | object::macho::PLATFORM_TVOSSIMULATOR
        | object::macho::PLATFORM_MACCATALYST => Some((16, 2)),
        object::macho::PLATFORM_WATCHOS | object::macho::PLATFORM_WATCHOSSIMULATOR => Some((9, 1)),
        _ => None,
    }
}

pub fn platform(target: &Target) -> Option<u32> {
    Some(match (&*target.os, &*target.abi) {
        ("macos", _) => object::macho::PLATFORM_MACOS,
        ("ios", "macabi") => object::macho::PLATFORM_MACCATALYST,
        ("ios", "sim") => object::macho::PLATFORM_IOSSIMULATOR,
        ("ios", _) => object::macho::PLATFORM_IOS,
        ("watchos", "sim") => object::macho::PLATFORM_WATCHOSSIMULATOR,
        ("watchos", _) => object::macho::PLATFORM_WATCHOS,
        ("tvos", "sim") => object::macho::PLATFORM_TVOSSIMULATOR,
        ("tvos", _) => object::macho::PLATFORM_TVOS,
        _ => return None,
    })
}

pub fn deployment_target(target: &Target) -> Option<(u32, u32)> {
    let (major, minor) = match &*target.os {
        "macos" => {
            // This does not need to be specific. It just needs to handle x86 vs M1.
            let arch = match target.arch.as_ref() {
                "x86" | "x86_64" => X86_64,
                "arm64e" => Arm64e,
                _ => Arm64,
            };
            macos_deployment_target(arch)
        }
        "ios" => {
            let arch = match target.arch.as_ref() {
                "arm64e" => Arm64e,
                _ => Arm64,
            };
            ios_deployment_target(arch, &target.abi)
        }
        "watchos" => watchos_deployment_target(),
        "tvos" => tvos_deployment_target(),
        _ => return None,
    };

    Some((major, minor))
}

fn from_set_deployment_target(var_name: &str) -> Option<(u32, u32)> {
    let deployment_target = env::var(var_name).ok()?;
    let (unparsed_major, unparsed_minor) = deployment_target.split_once('.')?;
    let (major, minor) = (unparsed_major.parse().ok()?, unparsed_minor.parse().ok()?);

    Some((major, minor))
}

fn macos_default_deployment_target(arch: Arch) -> (u32, u32) {
    match arch {
        // Note: Arm64_sim is not included since macOS has no simulator.
        Arm64 | Arm64e | Arm64_macabi => (11, 0),
        _ => (10, 12),
    }
}

fn macos_deployment_target(arch: Arch) -> (u32, u32) {
    // If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
    from_set_deployment_target("MACOSX_DEPLOYMENT_TARGET")
        .unwrap_or_else(|| macos_default_deployment_target(arch))
}

pub fn macos_llvm_target(arch: Arch) -> String {
    let (major, minor) = macos_deployment_target(arch);
    format!("{}-apple-macosx{}.{}.0", arch.target_name(), major, minor)
}

fn link_env_remove(os: &'static str) -> StaticCow<[StaticCow<str>]> {
    // Apple platforms only officially support macOS as a host for any compilation.
    //
    // If building for macOS, we go ahead and remove any erroneous environment state
    // that's only applicable to cross-OS compilation. Always leave anything for the
    // host OS alone though.
    if os == "macos" {
        let mut env_remove = Vec::with_capacity(2);
        // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which
        // may occur when we're linking a custom build script while targeting iOS for example.
        if let Ok(sdkroot) = env::var("SDKROOT") {
            if sdkroot.contains("iPhoneOS.platform")
                || sdkroot.contains("iPhoneSimulator.platform")
                || sdkroot.contains("AppleTVOS.platform")
                || sdkroot.contains("AppleTVSimulator.platform")
                || sdkroot.contains("WatchOS.platform")
                || sdkroot.contains("WatchSimulator.platform")
            {
                env_remove.push("SDKROOT".into())
            }
        }
        // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
        // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
        // although this is apparently ignored when using the linker at "/usr/bin/ld".
        env_remove.push("IPHONEOS_DEPLOYMENT_TARGET".into());
        env_remove.push("TVOS_DEPLOYMENT_TARGET".into());
        env_remove.into()
    } else {
        // Otherwise if cross-compiling for a different OS/SDK (including Mac Catalyst), remove any part
        // of the linking environment that's wrong and reversed.
        cvs!["MACOSX_DEPLOYMENT_TARGET"]
    }
}

fn ios_deployment_target(arch: Arch, abi: &str) -> (u32, u32) {
    // If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
    let (major, minor) = match (arch, abi) {
        (Arm64e, _) => (14, 0),
        // Mac Catalyst defaults to 13.1 in Clang.
        (_, "macabi") => (13, 1),
        _ => (10, 0),
    };
    from_set_deployment_target("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or((major, minor))
}

pub fn ios_llvm_target(arch: Arch) -> String {
    // Modern iOS tooling extracts information about deployment target
    // from LC_BUILD_VERSION. This load command will only be emitted when
    // we build with a version specific `llvm_target`, with the version
    // set high enough. Luckily one LC_BUILD_VERSION is enough, for Xcode
    // to pick it up (since std and core are still built with the fallback
    // of version 7.0 and hence emit the old LC_IPHONE_MIN_VERSION).
    let (major, minor) = ios_deployment_target(arch, "");
    format!("{}-apple-ios{}.{}.0", arch.target_name(), major, minor)
}

pub fn mac_catalyst_llvm_target(arch: Arch) -> String {
    let (major, minor) = ios_deployment_target(arch, "macabi");
    format!("{}-apple-ios{}.{}.0-macabi", arch.target_name(), major, minor)
}

pub fn ios_sim_llvm_target(arch: Arch) -> String {
    let (major, minor) = ios_deployment_target(arch, "sim");
    format!("{}-apple-ios{}.{}.0-simulator", arch.target_name(), major, minor)
}

fn tvos_deployment_target() -> (u32, u32) {
    // If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
    from_set_deployment_target("TVOS_DEPLOYMENT_TARGET").unwrap_or((10, 0))
}

pub fn tvos_llvm_target(arch: Arch) -> String {
    let (major, minor) = tvos_deployment_target();
    format!("{}-apple-tvos{}.{}.0", arch.target_name(), major, minor)
}

pub fn tvos_sim_llvm_target(arch: Arch) -> String {
    let (major, minor) = tvos_deployment_target();
    format!("{}-apple-tvos{}.{}.0-simulator", arch.target_name(), major, minor)
}

fn watchos_deployment_target() -> (u32, u32) {
    // If you are looking for the default deployment target, prefer `rustc --print deployment-target`.
    from_set_deployment_target("WATCHOS_DEPLOYMENT_TARGET").unwrap_or((5, 0))
}

pub fn watchos_sim_llvm_target(arch: Arch) -> String {
    let (major, minor) = watchos_deployment_target();
    format!("{}-apple-watchos{}.{}.0-simulator", arch.target_name(), major, minor)
}