跳转到内容

std.zig.system.darwin.macos

标准库Zig 0.17.1官方原文
源码std/zig/system/darwin/macos.zig

第 1 行

std.zig.system.darwin.macos.assert

别名

第 6 行

别名目标 std.debug.assert

std.zig.system.darwin.macos.builtin

常量

第 1 行

std.zig.system.darwin.macos.detect

函数

第 13 行

检测 macOS 版本。 出错时不修改 target_os。

pub fn detect(io: Io, target_os: *Target.Os) !void

参数

io: Io
target_os: *Target.Os

std.zig.system.darwin.macos.detectNativeCpuAndFeatures

函数

第 400 行

pub fn detectNativeCpuAndFeatures() ?Target.Cpu

std.zig.system.darwin.macos.Io

别名

第 4 行

别名目标 std.Io

std.zig.system.darwin.macos.mem

别名

第 7 行

别名目标 std.mem

std.zig.system.darwin.macos.parseSystemVersion

函数

第 80 行

fn parseSystemVersion(buf: []const u8) !std.SemanticVersion

参数

buf: []const u8

std.zig.system.darwin.macos.posix

别名

第 5 行

别名目标 std.posix

std.zig.system.darwin.macos.std

别名

第 3 行

别名目标 std

std.zig.system.darwin.macos.SystemVersionTokenizer

容器

第 96 行

字段

bytes: []const u8
index: usize = 0
state: State = .begin

std.zig.system.darwin.macos.SystemVersionTokenizer.expectContent

函数

第 236 行

fn expectContent(self: *@This()) ![]const u8

参数

self: *@This()

std.zig.system.darwin.macos.SystemVersionTokenizer.next

函数

第 101 行

fn next(self: *@This()) !?Token

参数

self: *@This()

std.zig.system.darwin.macos.SystemVersionTokenizer.skipUntilTag

函数

第 248 行

fn skipUntilTag(self: *@This(), kind: Tag.Kind, name: []const u8) !void

参数

self: *@This()
kind: Tag.Kind
name: []const u8

std.zig.system.darwin.macos.SystemVersionTokenizer.State

容器

第 260 行

字段

begin
tag0
tag0_end_or_empty
tagN
tagN_end
tag_string
content

std.zig.system.darwin.macos.SystemVersionTokenizer.Tag

容器

第 275 行

字段

kind: Kind = .unknown
name: []const u8 = ""

std.zig.system.darwin.macos.SystemVersionTokenizer.Tag.Kind

容器

第 279 行

字段

unknown
start
end
empty

std.zig.system.darwin.macos.SystemVersionTokenizer.Token

容器

第 270 行

字段

tag: Tag
content: []const u8

std.zig.system.darwin.macos.Target

别名

第 9 行

别名目标 std.Target

std.zig.system.darwin.macos.testing

别名

第 8 行

别名目标 std.testing

源码

std/zig/system/darwin/macos.zig

const builtin = @import("builtin");

const std = @import("std");
const Io = std.Io;
const posix = std.posix;
const assert = std.debug.assert;
const mem = std.mem;
const testing = std.testing;
const Target = std.Target;

/// 检测 macOS 版本。
/// 出错时不修改 `target_os`。
pub fn detect(io: Io, target_os: *Target.Os) !void {
    // 不再使用 osproductversion sysctl,原因如下:
    //   1. 仅在 10.13.4 High Sierra 及之后版本可用。
    //   2. 针对低于 SDK 11.0 构建的二进制使用它时,会返回 10.16,掩盖 Big Sur 11.x 版本。
    //
    // 新方案第一步,解析文件:
    //
    //   /System/Library/CoreServices/SystemVersion.plist
    //
    // 注意:`SystemVersion.plist` 最早大约于 2003 年随 Mac OS X 10.3.0 Panther 出现。
    //
    // 如果其中的版本形如 `10.16`,且次版本 `16` 满足 `>= 16`,则该值并非规范版本,弃用并继续下一步;否则接受此版本。
    //
    // 背景:`10.(16+)` 不是准确版本,无法足够精确地表示 Big Sur 及之后版本的次版本或修订版本。这是内核为了向后兼容而产生的上下文相关结果;内核很可能检查可执行文件是否链接了早于 Big Sur 的 SDK。
    //
    // 第二步,解析另一个文件:
    //
    //   /System/Library/CoreServices/.SystemVersionPlatform.plist
    //
    // 注意:`SystemVersionPlatform.plist` 最早大约于 2020 年随 macOS 11.0 Big Sur 出现。
    //
    // 通过该路径访问内容,可以绕过上下文相关结果,取得规范的 Big Sur 版本。
    //
    // 目前尚不知道针对低于 SDK 11.0 构建的可执行文件还能通过其他方式获取规范的 Big Sur 版本。
    //
    // 本实现采用适度简化的方式解析 .plist 文件。虽然它是 XML 文档,但该文件及格式有充分历史依据,因此采用极简解析器。不支持字符串转义和一般转义等功能。
    //
    //
    //
    //
    //
    //
    //
    //
    //
    //
    //
    const prefixSlash = "/System/Library/CoreServices/";
    const paths = [_][]const u8{
        prefixSlash ++ "SystemVersion.plist",
        prefixSlash ++ ".SystemVersionPlatform.plist",
    };
    for (paths) |path| {
        // 约为历史文件大小的 4 倍
        var buf: [2048]u8 = undefined;

        if (Io.Dir.cwd().readFile(io, path, &buf)) |bytes| {
            if (parseSystemVersion(bytes)) |ver| {
                // 绝不返回非规范的 `10.(16+)`
                if (!(ver.major == 10 and ver.minor >= 16)) {
                    assert(ver.pre == null);
                    assert(ver.build == null);
                    target_os.version_range.semver.min = ver;
                    target_os.version_range.semver.max = ver;
                    return;
                }
                continue;
            } else |_| {
                return error.OSVersionDetectionFail;
            }
        } else |_| {
            return error.OSVersionDetectionFail;
        }
    }
    return error.OSVersionDetectionFail;
}

fn parseSystemVersion(buf: []const u8) !std.SemanticVersion {
    var svt = SystemVersionTokenizer{ .bytes = buf };
    try svt.skipUntilTag(.start, "dict");
    while (true) {
        try svt.skipUntilTag(.start, "key");
        const content = try svt.expectContent();
        try svt.skipUntilTag(.end, "key");
        if (mem.eql(u8, content, "ProductVersion")) break;
    }
    try svt.skipUntilTag(.start, "string");
    const ver = try svt.expectContent();
    try svt.skipUntilTag(.end, "string");

    return try std.Target.Query.parseVersion(ver);
}

const SystemVersionTokenizer = struct {
    bytes: []const u8,
    index: usize = 0,
    state: State = .begin,

    fn next(self: *@This()) !?Token {
        var mark: usize = self.index;
        var tag = Tag{};
        var content: []const u8 = "";

        while (self.index < self.bytes.len) {
            const char = self.bytes[self.index];
            switch (self.state) {
                .begin => switch (char) {
                    '<' => {
                        self.state = .tag0;
                        self.index += 1;
                        tag = Tag{};
                        mark = self.index;
                    },
                    '>' => {
                        return error.BadToken;
                    },
                    else => {
                        self.state = .content;
                        content = "";
                        mark = self.index;
                    },
                },
                .tag0 => switch (char) {
                    '<' => {
                        return error.BadToken;
                    },
                    '>' => {
                        self.state = .begin;
                        self.index += 1;
                        tag.name = self.bytes[mark..self.index];
                        return Token{ .tag = tag };
                    },
                    '"' => {
                        self.state = .tag_string;
                        self.index += 1;
                    },
                    '/' => {
                        self.state = .tag0_end_or_empty;
                        self.index += 1;
                    },
                    'A'...'Z', 'a'...'z' => {
                        self.state = .tagN;
                        tag.kind = .start;
                        self.index += 1;
                    },
                    else => {
                        self.state = .tagN;
                        self.index += 1;
                    },
                },
                .tag0_end_or_empty => switch (char) {
                    '<' => {
                        return error.BadToken;
                    },
                    '>' => {
                        self.state = .begin;
                        tag.kind = .empty;
                        tag.name = self.bytes[self.index..self.index];
                        self.index += 1;
                        return Token{ .tag = tag };
                    },
                    else => {
                        self.state = .tagN;
                        tag.kind = .end;
                        mark = self.index;
                        self.index += 1;
                    },
                },
                .tagN => switch (char) {
                    '<' => {
                        return error.BadToken;
                    },
                    '>' => {
                        self.state = .begin;
                        tag.name = self.bytes[mark..self.index];
                        self.index += 1;
                        return Token{ .tag = tag };
                    },
                    '"' => {
                        self.state = .tag_string;
                        self.index += 1;
                    },
                    '/' => {
                        self.state = .tagN_end;
                        tag.kind = .end;
                        self.index += 1;
                    },
                    else => {
                        self.index += 1;
                    },
                },
                .tagN_end => switch (char) {
                    '>' => {
                        self.state = .begin;
                        tag.name = self.bytes[mark..self.index];
                        self.index += 1;
                        return Token{ .tag = tag };
                    },
                    else => {
                        return error.BadToken;
                    },
                },
                .tag_string => switch (char) {
                    '"' => {
                        self.state = .tagN;
                        self.index += 1;
                    },
                    else => {
                        self.index += 1;
                    },
                },
                .content => switch (char) {
                    '<' => {
                        self.state = .tag0;
                        content = self.bytes[mark..self.index];
                        self.index += 1;
                        tag = Tag{};
                        mark = self.index;
                        return Token{ .content = content };
                    },
                    '>' => {
                        return error.BadToken;
                    },
                    else => {
                        self.index += 1;
                    },
                },
            }
        }

        return null;
    }

    fn expectContent(self: *@This()) ![]const u8 {
        if (try self.next()) |tok| {
            switch (tok) {
                .content => |content| {
                    return content;
                },
                else => {},
            }
        }
        return error.UnexpectedToken;
    }

    fn skipUntilTag(self: *@This(), kind: Tag.Kind, name: []const u8) !void {
        while (try self.next()) |tok| {
            switch (tok) {
                .tag => |tag| {
                    if (tag.kind == kind and mem.eql(u8, tag.name, name)) return;
                },
                else => {},
            }
        }
        return error.TagNotFound;
    }

    const State = enum {
        begin,
        tag0,
        tag0_end_or_empty,
        tagN,
        tagN_end,
        tag_string,
        content,
    };

    const Token = union(enum) {
        tag: Tag,
        content: []const u8,
    };

    const Tag = struct {
        kind: Kind = .unknown,
        name: []const u8 = "",

        const Kind = enum { unknown, start, end, empty };
    };
};

test "detect" {
    const cases: [5]struct { []const u8, std.SemanticVersion } = .{
        .{
            \\<?xml version="1.0" encoding="UTF-8"?>
            \\<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
            \\<plist version="1.0">
            \\<dict>
            \\    <key>ProductBuildVersion</key>
            \\    <string>7B85</string>
            \\    <key>ProductCopyright</key>
            \\    <string>Apple Computer, Inc. 1983-2003</string>
            \\    <key>ProductName</key>
            \\    <string>Mac OS X</string>
            \\    <key>ProductUserVisibleVersion</key>
            \\    <string>10.3</string>
            \\    <key>ProductVersion</key>
            \\    <string>10.3</string>
            \\</dict>
            \\</plist>
            ,
            .{ .major = 10, .minor = 3, .patch = 0 },
        },
        .{
            \\<?xml version="1.0" encoding="UTF-8"?>
            \\<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
            \\<plist version="1.0">
            \\<dict>
            \\ <key>ProductBuildVersion</key>
            \\ <string>7W98</string>
            \\ <key>ProductCopyright</key>
            \\ <string>Apple Computer, Inc. 1983-2004</string>
            \\ <key>ProductName</key>
            \\ <string>Mac OS X</string>
            \\ <key>ProductUserVisibleVersion</key>
            \\ <string>10.3.9</string>
            \\ <key>ProductVersion</key>
            \\ <string>10.3.9</string>
            \\</dict>
            \\</plist>
            ,
            .{ .major = 10, .minor = 3, .patch = 9 },
        },
        .{
            \\<?xml version="1.0" encoding="UTF-8"?>
            \\<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
            \\<plist version="1.0">
            \\<dict>
            \\ <key>ProductBuildVersion</key>
            \\ <string>19G68</string>
            \\ <key>ProductCopyright</key>
            \\ <string>1983-2020 Apple Inc.</string>
            \\ <key>ProductName</key>
            \\ <string>Mac OS X</string>
            \\ <key>ProductUserVisibleVersion</key>
            \\ <string>10.15.6</string>
            \\ <key>ProductVersion</key>
            \\ <string>10.15.6</string>
            \\ <key>iOSSupportVersion</key>
            \\ <string>13.6</string>
            \\</dict>
            \\</plist>
            ,
            .{ .major = 10, .minor = 15, .patch = 6 },
        },
        .{
            \\<?xml version="1.0" encoding="UTF-8"?>
            \\<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
            \\<plist version="1.0">
            \\<dict>
            \\ <key>ProductBuildVersion</key>
            \\ <string>20A2408</string>
            \\ <key>ProductCopyright</key>
            \\ <string>1983-2020 Apple Inc.</string>
            \\ <key>ProductName</key>
            \\ <string>macOS</string>
            \\ <key>ProductUserVisibleVersion</key>
            \\ <string>11.0</string>
            \\ <key>ProductVersion</key>
            \\ <string>11.0</string>
            \\ <key>iOSSupportVersion</key>
            \\ <string>14.2</string>
            \\</dict>
            \\</plist>
            ,
            .{ .major = 11, .minor = 0, .patch = 0 },
        },
        .{
            \\<?xml version="1.0" encoding="UTF-8"?>
            \\<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
            \\<plist version="1.0">
            \\<dict>
            \\ <key>ProductBuildVersion</key>
            \\ <string>20C63</string>
            \\ <key>ProductCopyright</key>
            \\ <string>1983-2020 Apple Inc.</string>
            \\ <key>ProductName</key>
            \\ <string>macOS</string>
            \\ <key>ProductUserVisibleVersion</key>
            \\ <string>11.1</string>
            \\ <key>ProductVersion</key>
            \\ <string>11.1</string>
            \\ <key>iOSSupportVersion</key>
            \\ <string>14.3</string>
            \\</dict>
            \\</plist>
            ,
            .{ .major = 11, .minor = 1, .patch = 0 },
        },
    };

    inline for (cases) |case| {
        const ver0 = try parseSystemVersion(case[0]);
        const ver1 = case[1];
        try testing.expectEqual(std.math.Order.eq, ver0.order(ver1));
    }
}

pub fn detectNativeCpuAndFeatures() ?Target.Cpu {
    var cpu_family: std.c.CPUFAMILY = undefined;
    var len: usize = @sizeOf(@TypeOf(cpu_family));
    switch (posix.errno(posix.system.sysctlbyname("hw.cpufamily", &cpu_family, &len, null, 0))) {
        .SUCCESS => {},
        .FAULT => unreachable, // 段错误
        .PERM => unreachable, // 仅在设置值时,
        .NOMEM => unreachable, // 内存已位于栈上
        .NOENT => unreachable, // 常量,已知有效的值
        else => return null,
    }

    const current_arch = builtin.cpu.arch;
    switch (current_arch) {
        .aarch64 => {
            const model = switch (cpu_family) {
                .ARM_CYCLONE => &Target.aarch64.cpu.apple_a7,
                .ARM_TYPHOON => &Target.aarch64.cpu.apple_a8,
                .ARM_TWISTER => &Target.aarch64.cpu.apple_a9,
                .ARM_HURRICANE => &Target.aarch64.cpu.apple_a10,
                .ARM_MONSOON_MISTRAL => &Target.aarch64.cpu.apple_a11,
                .ARM_VORTEX_TEMPEST => &Target.aarch64.cpu.apple_a12,
                .ARM_LIGHTNING_THUNDER => &Target.aarch64.cpu.apple_a13,
                .ARM_FIRESTORM_ICESTORM => &Target.aarch64.cpu.apple_a14,
                .ARM_BLIZZARD_AVALANCHE => &Target.aarch64.cpu.apple_a15,
                .ARM_EVEREST_SAWTOOTH => &Target.aarch64.cpu.apple_a16,
                .ARM_IBIZA => &Target.aarch64.cpu.apple_m3, // 基址
                .ARM_PALMA => &Target.aarch64.cpu.apple_m3, // 最大值
                .ARM_LOBOS => &Target.aarch64.cpu.apple_m3, // pro
                .ARM_COLL => &Target.aarch64.cpu.apple_a17, // pro
                .ARM_DONAN => &Target.aarch64.cpu.apple_m4, // 基址
                .ARM_BRAVA => &Target.aarch64.cpu.apple_m4, // pro/max
                .ARM_TAHITI => &Target.aarch64.cpu.apple_a18, // pro
                .ARM_TUPAI => &Target.aarch64.cpu.apple_a18, // 基址
                .ARM_HIDRA => &Target.aarch64.cpu.apple_m5, // 基址
                .ARM_SOTRA => &Target.aarch64.cpu.apple_m5, // pro/max
                .ARM_THERA => &Target.aarch64.cpu.apple_a19, // pro
                .ARM_TILOS => &Target.aarch64.cpu.apple_a19, // 基址
                else => return null,
            };

            return model.toCpu(current_arch);
        },
        else => {},
    }

    return null;
}