builtinnative_endianstdmemelffsassertTargetposixIoNativePathsdarwinfreebsdlinuxnetbsdopenbsdwindowsExecutorGetExternalExecutorOptionsgetExternalExecutorDetectErrorresolveTargetQueryupdateCpuFeaturesdetectNativeCpuAndFeaturesAbiAndDynamicLinkerFromFileErrorabiAndDynamicLinkerFromFileglibcVerFromLinkNameglibcVerFromRPathglibcVerFromSoFiledetectAbiAndDynamicLinkerdefaultAbiAndDynamicLinkerLdInfodetectAndroidApiLevel
std.zig.system.abiAndDynamicLinkerFromFile
函数
fn abiAndDynamicLinkerFromFile( file_reader: *Io.File.Reader, header: *const elf.Header, cpu: Target.Cpu, os: Target.Os, ld_info_list: []const LdInfo, query: Target.Query, ) AbiAndDynamicLinkerFromFileError!Target
参数
file_reader: *Io.File.Reader
header: *const elf.Header
cpu: Target.Cpu
os: Target.Os
ld_info_list: []const LdInfo
query: Target.Query
错误
- AccessDenied
- BrokenPipe
- Canceled
- ConnectionResetByPeer
- EndOfStream
- FileSystem
- InputOutput
- InvalidElfFile
- IsDir
- LockViolation
- NameTooLong
- NotOpenForReading
- ProcessFdQuotaExceeded
- ReadFailed
- SocketUnconnected
- StaticElfFile
- StreamTooLong
- SymLinkLoop
- SystemFdQuotaExceeded
- SystemResources
- Timeout
- Unexpected
- Unseekable
- WouldBlock
std.zig.system.AbiAndDynamicLinkerFromFileError
错误集合
错误
- AccessDenied
- BrokenPipe
- Canceled
- ConnectionResetByPeer
- EndOfStream
- FileSystem
- InputOutput
- InvalidElfFile
- IsDir
- LockViolation
- NameTooLong
- NotOpenForReading
- ProcessFdQuotaExceeded
- ReadFailed
- SocketUnconnected
- StaticElfFile
- StreamTooLong
- SymLinkLoop
- SystemFdQuotaExceeded
- SystemResources
- Timeout
- Unexpected
- Unseekable
- WouldBlock
std.zig.system.assert
别名
别名目标 std.debug.assert
std.zig.system.builtin
常量
std.zig.system.darwin
别名
std.zig.system.defaultAbiAndDynamicLinker
函数
fn defaultAbiAndDynamicLinker(cpu: Target.Cpu, os: Target.Os, query: Target.Query) Target
参数
std.zig.system.detectAbiAndDynamicLinker
函数
过去,此函数会在可执行文件动态链接时尝试使用该可执行文件自身,以同时判断 C ABI 和动态链接器。但在某些系统中,编译器二进制文件使用 RUNPATH,可能因此绑定到较旧版本的 glibc;而 /usr/bin/env 等系统二进制文件则使用较新版本。问题在于 libc.so.6 的 glibc 版本会与系统匹配,而动态链接器版本会与编译器二进制文件匹配。两者版本不一致的可执行文件将无法运行。
因此,无论编译器二进制文件是动态链接还是静态链接,此函数的行为都相同。它会检查 /usr/bin/env,将其视为 ELF 文件,以获取这些问题的答案;如果文件包含 shebang 行,则会递归追踪其中引用的文件。若仍无法确定,则回退到默认值。
fn detectAbiAndDynamicLinker(io: Io, cpu: Target.Cpu, os: Target.Os, query: Target.Query) !Target
参数
std.zig.system.detectAndroidApiLevel
函数
fn detectAndroidApiLevel(io: Io) !u32
参数
io: Io
std.zig.system.DetectError
错误集合
错误
- ApiLevelQueryFailed
仅限 Android。通过
getprop查询 API 级别失败。- Canceled Cancelable
调用方请求停止异步操作。
- DeviceBusy
- FileSystem
- OSVersionDetectionFail
- ProcessFdQuotaExceeded
- SymLinkLoop
- SystemFdQuotaExceeded
- SystemResources
- Unexpected
std.zig.system.detectNativeCpuAndFeatures
函数
fn detectNativeCpuAndFeatures(io: Io, cpu_arch: Target.Cpu.Arch) ?Target.Cpu
参数
std.zig.system.elf
别名
别名目标 std.elf
std.zig.system.Executor
容器
字段
native
rosetta
qemu: []const u8
wine: []const u8
wasmtime: []const u8
darling: []const u8
bad_dl: []const u8
bad_os_or_cpu
std.zig.system.freebsd
别名
std.zig.system.fs
别名
别名目标 std.fs
std.zig.system.getExternalExecutor
函数
返回给定主机是否能够运行 另一目标的可执行文件。
pub fn getExternalExecutor(io: Io, candidate: *const std.Target, options: GetExternalExecutorOptions) Executor
参数
std.zig.system.GetExternalExecutorOptions
容器
字段
std.zig.system.glibcVerFromLinkName
函数
fn glibcVerFromLinkName(link_name: []const u8, prefix: []const u8) error{ UnrecognizedGnuLibCFileName, InvalidGnuLibCVersion }!std.SemanticVersion
参数
link_name: []const u8
prefix: []const u8
错误
- InvalidGnuLibCVersion
- UnrecognizedGnuLibCFileName
用法示例
test glibcVerFromLinkName {
try std.testing.expectError(error.UnrecognizedGnuLibCFileName, glibcVerFromLinkName("ld-2.37.so", "this-prefix-does-not-exist"));
try std.testing.expectError(error.UnrecognizedGnuLibCFileName, glibcVerFromLinkName("libc-2.37.so-is-not-end", "libc-"));
try std.testing.expectError(error.InvalidGnuLibCVersion, glibcVerFromLinkName("ld-2.so", "ld-"));
try std.testing.expectEqual(std.SemanticVersion{ .major = 2, .minor = 37, .patch = 0 }, try glibcVerFromLinkName("ld-2.37.so", "ld-"));
try std.testing.expectEqual(std.SemanticVersion{ .major = 2, .minor = 37, .patch = 0 }, try glibcVerFromLinkName("ld-2.37.0.so", "ld-"));
try std.testing.expectEqual(std.SemanticVersion{ .major = 2, .minor = 37, .patch = 1 }, try glibcVerFromLinkName("ld-2.37.1.so", "ld-"));
try std.testing.expectError(error.InvalidGnuLibCVersion, glibcVerFromLinkName("ld-2.37.4.5.so", "ld-"));
}
std.zig.system.glibcVerFromRPath
函数
fn glibcVerFromRPath(io: Io, rpath: []const u8) !std.SemanticVersion
参数
io: Io
rpath: []const u8
std.zig.system.glibcVerFromSoFile
函数
fn glibcVerFromSoFile(file_reader: *Io.File.Reader) !std.SemanticVersion
参数
std.zig.system.Io
别名
别名目标 std.Io
std.zig.system.LdInfo
容器
字段
ld: Target.DynamicLinker
abi: Target.Abi
std.zig.system.linux
别名
别名目标 std.zig.system.linux
std.zig.system.mem
别名
别名目标 std.mem
std.zig.system.native_endian
常量
std.zig.system.NativePaths
别名
std.zig.system.netbsd
别名
std.zig.system.openbsd
别名
std.zig.system.posix
别名
别名目标 std.posix
std.zig.system.resolveTargetQuery
函数
给定 Target.Query,其中详细指定目标的哪些部分应从原生系统检测、哪些应采用标准或默认值、哪些已显式提供。
此函数先检测原生系统以解析原生组件,再相对于该结果解析标准或默认部分。
pub fn resolveTargetQuery(io: Io, query: Target.Query) DetectError!Target
参数
错误
- ApiLevelQueryFailed
仅限 Android。通过
getprop查询 API 级别失败。- Canceled Cancelable
调用方请求停止异步操作。
- DeviceBusy
- FileSystem
- OSVersionDetectionFail
- ProcessFdQuotaExceeded
- SymLinkLoop
- SystemFdQuotaExceeded
- SystemResources
- Unexpected
std.zig.system.std
别名
别名目标 std
std.zig.system.Target
别名
别名目标 std.Target
std.zig.system.updateCpuFeatures
函数
fn updateCpuFeatures( set: *Target.Cpu.Feature.Set, all_features_list: []const Target.Cpu.Feature, add_set: Target.Cpu.Feature.Set, sub_set: Target.Cpu.Feature.Set, ) void
参数
std.zig.system.windows
别名
源码
std/zig/system.zig
const builtin = @import("builtin");
const native_endian = builtin.cpu.arch.endian();
const std = @import("../std.zig");
const mem = std.mem;
const elf = std.elf;
const fs = std.fs;
const assert = std.debug.assert;
const Target = std.Target;
const posix = std.posix;
const Io = std.Io;
pub const NativePaths = @import("system/NativePaths.zig");
pub const darwin = @import("system/darwin.zig");
pub const freebsd = @import("system/freebsd.zig");
pub const linux = @import("system/linux.zig");
pub const netbsd = @import("system/netbsd.zig");
pub const openbsd = @import("system/openbsd.zig");
pub const windows = @import("system/windows.zig");
pub const Executor = union(enum) {
native,
rosetta,
qemu: []const u8,
wine: []const u8,
wasmtime: []const u8,
darling: []const u8,
bad_dl: []const u8,
bad_os_or_cpu,
};
pub const GetExternalExecutorOptions = struct {
host_cpu_arch: std.Target.Cpu.Arch,
host_os_tag: std.Target.Os.Tag,
qemu_fixes_dl: bool = false,
link_mode: std.lang.LinkMode,
link_libc: bool,
};
/// 返回给定主机是否能够运行
/// 另一目标的可执行文件。
pub fn getExternalExecutor(io: Io, candidate: *const std.Target, options: GetExternalExecutorOptions) Executor {
const host_os_tag = options.host_os_tag;
const host_cpu_arch = options.host_cpu_arch;
const os_match = host_os_tag == candidate.os.tag;
const cpu_ok = cpu_ok: {
if (host_cpu_arch == candidate.cpu.arch)
break :cpu_ok true;
if (host_cpu_arch == .x86_64 and candidate.cpu.arch == .x86)
break :cpu_ok true;
if (host_cpu_arch == .aarch64 and candidate.cpu.arch == .arm)
break :cpu_ok true;
if (host_cpu_arch == .aarch64_be and candidate.cpu.arch == .armeb)
break :cpu_ok true;
// TODO: 额外检测不兼容的 CPU 特性。
// 注意,遇到非法指令时,某些情况下操作系统内核会模拟缺失的 CPU 特性。
//
break :cpu_ok false;
};
var bad_result: Executor = .bad_os_or_cpu;
if (os_match and cpu_ok) native: {
if (options.link_libc and options.link_mode == .dynamic) {
if (candidate.dynamic_linker.get()) |candidate_dl| {
Io.Dir.cwd().access(io, candidate_dl, .{}) catch {
bad_result = .{ .bad_dl = candidate_dl };
break :native;
};
}
}
return .native;
}
// 如果操作系统匹配、系统为 macOS 且 CPU 为 arm64,则可使用 Rosetta 2
// 模拟其他架构。
if (os_match and (host_os_tag == .maccatalyst or host_os_tag == .macos) and host_cpu_arch == .aarch64) {
switch (candidate.cpu.arch) {
.x86_64 => return .rosetta,
else => return bad_result,
}
}
// 若操作系统匹配,可使用 QEMU 仿真其他架构。
if (os_match and (!cpu_ok or options.qemu_fixes_dl)) {
return switch (candidate.cpu.arch) {
inline .aarch64,
.arm,
.riscv64,
.x86,
.x86_64,
=> |t| switch (candidate.os.tag) {
.linux,
.freebsd,
=> .{ .qemu = switch (t) {
.x86 => "qemu-i386",
.x86_64 => switch (candidate.abi) {
.gnux32, .muslx32, .x32 => return bad_result,
else => "qemu-x86_64",
},
else => "qemu-" ++ @tagName(t),
} },
else => bad_result,
},
inline .aarch64_be,
.alpha,
.armeb,
.hexagon,
.hppa,
.loongarch64,
.m68k,
.microblaze,
.microblazeel,
.mips,
.mipsel,
.mips64,
.mips64el,
.or1k,
.powerpc,
.powerpc64,
.powerpc64le,
.riscv32,
.s390x,
.sh,
.sheb,
.sparc,
.sparc64,
.thumb,
.thumbeb,
.xtensa,
.xtensaeb,
=> |t| switch (candidate.os.tag) {
.linux,
=> .{
.qemu = switch (t) {
.powerpc => "qemu-ppc",
.powerpc64 => "qemu-ppc64",
.powerpc64le => "qemu-ppc64le",
.mips64, .mips64el => switch (candidate.abi) {
.gnuabin32, .muslabin32, .abin32 => if (t == .mips64el) "qemu-mipsn32el" else "qemu-mipsn32",
else => "qemu-" ++ @tagName(t),
},
// TODO: 实际检查 SuperH 版本。
.sh => "qemu-sh4",
.sheb => "qemu-sh4eb",
.sparc => "qemu-sparc32plus",
.thumb => "qemu-arm",
.thumbeb => "qemu-armeb",
else => "qemu-" ++ @tagName(t),
},
},
else => bad_result,
},
else => bad_result,
};
}
if (candidate.cpu.arch.isWasm()) {
return .{ .wasmtime = "wasmtime" };
}
switch (candidate.os.tag) {
.windows => {
const wine_supported = switch (candidate.cpu.arch) {
.thumb => switch (host_cpu_arch) {
.arm, .thumb, .aarch64 => true,
else => false,
},
.aarch64 => host_cpu_arch == .aarch64,
.x86 => host_cpu_arch.isX86(),
.x86_64 => host_cpu_arch == .x86_64,
else => false,
};
return if (wine_supported) .{ .wine = "wine" } else bad_result;
},
.driverkit, .macos => {
// 当 darling 添加基于 QEMU 的非主机架构仿真层后,可放宽此检查:
// https://github.com/darlinghq/darling/issues/863
//
if (candidate.cpu.arch != host_cpu_arch) {
return bad_result;
}
return .{ .darling = "darling" };
},
else => return bad_result,
}
}
pub const DetectError = error{
FileSystem,
SystemResources,
SymLinkLoop,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
DeviceBusy,
OSVersionDetectionFail,
Unexpected,
/// 仅限 Android。通过 `getprop` 查询 API 级别失败。
ApiLevelQueryFailed,
} || Io.Cancelable;
/// 给定 `Target.Query`,其中详细指定目标的哪些部分应从原生系统检测、哪些应采用标准或默认值、哪些已显式提供。
/// 此函数先检测原生系统以解析原生组件,再相对于该结果解析标准或默认部分。
///
///
///
pub fn resolveTargetQuery(io: Io, query: Target.Query) DetectError!Target {
// 在 https://github.com/ziglang/zig/issues/4592 实现之前,即支持检测本机 CPU 架构
// 与当前目标不同的情况之前,使用此方式:
const query_cpu_arch = query.cpu_arch orelse builtin.cpu.arch;
const query_os_tag = query.os_tag orelse builtin.os.tag;
const query_abi = query.abi orelse builtin.abi;
var os = query_os_tag.defaultVersionRange(query_cpu_arch, query_abi);
if (query.os_tag == null) {
switch (builtin.target.os.tag) {
.linux, .illumos => {
const uts = posix.uname();
const release = mem.sliceTo(&uts.release, 0);
// release 字段有时具有不常见的格式,
// `Version.parse` 将尝试找出有意义的解释。
if (std.SemanticVersion.parse(release)) |ver| {
var stripped = ver;
stripped.pre = null;
stripped.build = null;
os.version_range.linux.range.min = stripped;
os.version_range.linux.range.max = stripped;
} else |err| switch (err) {
error.Overflow => {},
error.InvalidVersion => {},
}
},
.windows => {
const detected_version = windows.detectRuntimeVersion();
os.version_range.windows.min = detected_version;
os.version_range.windows.max = detected_version;
},
.macos => try darwin.macos.detect(io, &os),
.freebsd, .netbsd, .dragonfly => {
const key = switch (builtin.target.os.tag) {
.freebsd => "kern.osreldate",
.netbsd, .dragonfly => "kern.osrevision",
else => unreachable,
};
var value: u32 = undefined;
var len: usize = @sizeOf(@TypeOf(value));
switch (posix.errno(posix.system.sysctlbyname(key, &value, &len, null, 0))) {
.SUCCESS => {},
.FAULT => unreachable,
.PERM => unreachable, // 仅在设置值时,
.NOMEM => unreachable, // 内存已位于栈上
.NOENT => unreachable, // 常量,已知有效的值
else => return error.OSVersionDetectionFail,
}
switch (builtin.target.os.tag) {
.freebsd => {
// https://www.freebsd.org/doc/en_US.ISO8859-1/books/porters-handbook/versions.html
// Major * 100,000 自 FreeBSD 2.2(1997)起成为惯例
// Minor * 1(0),000 求和自 FreeBSD 2.2(1997)起成为惯例
// 例如,492101 = 4.11-STABLE = 4.(9+2)
const major = value / 100_000;
const minor1 = value % 100_000 / 10_000; // 自 5.1 起通常为 0
const minor2 = value % 10_000 / 1_000; // 5.1 之前为 0,此后为次版本号
const patch = value % 1_000;
os.version_range.semver.min = .{ .major = major, .minor = minor1 + minor2, .patch = patch };
os.version_range.semver.max = os.version_range.semver.min;
},
.netbsd => {
// #define __NetBSD_Version__ MMmmrrpp00
//
// M = 主版本
// m = 次版本;次版本号为 99 表示当前开发版本。
// r = 0 (*)
// p = 补丁级别
const major = value / 100_000_000;
const minor = value % 100_000_000 / 1_000_000;
const patch = value % 10_000 / 100;
os.version_range.semver.min = .{ .major = major, .minor = minor, .patch = patch };
os.version_range.semver.max = os.version_range.semver.min;
},
.dragonfly => {
// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/cb2cde83771754aeef9bb3251ee48959138dec87/Makefile.inc1#L15-L17
// 扁平十进制格式:Mmmmpp
// M = 主版本
// m = 次版本;奇数表示当前开发分支
// p = 补丁版本
const major = value / 100_000;
const minor = value % 100_000 / 100;
const patch = value % 100;
os.version_range.semver.min = .{ .major = major, .minor = minor, .patch = patch };
os.version_range.semver.max = os.version_range.semver.min;
},
else => unreachable,
}
},
.openbsd => {
const mib: [2]c_int = [_]c_int{
posix.CTL.KERN,
posix.KERN.OSRELEASE,
};
var buf: [64:0]u8 = undefined;
// 注意 sysctl 结果包含空终止符
var len: usize = buf.len + 1;
posix.sysctl(&mib, &buf, &len, null, 0) catch |err| switch (err) {
error.NameTooLong => unreachable, // 常量,已知有效的值
error.PermissionDenied => unreachable, // 仅在设置值时,
error.SystemResources => unreachable, // 内存已位于栈上
error.UnknownName => unreachable, // 常量,已知有效的值
error.Unexpected => return error.OSVersionDetectionFail,
};
if (Target.Query.parseVersion(buf[0 .. len - 1 :0])) |ver| {
assert(ver.build == null);
assert(ver.pre == null);
os.version_range.semver.min = ver;
os.version_range.semver.max = ver;
} else |_| {
return error.OSVersionDetectionFail;
}
},
else => {
// 尚未实现,回退到默认版本范围。
},
}
}
if (query.os_version_min) |min| switch (min) {
.none => {},
.semver => |semver| switch (os.tag.versionRangeTag()) {
inline .hurd, .linux => |t| @field(os.version_range, @tagName(t)).range.min = semver,
else => os.version_range.semver.min = semver,
},
.windows => |win_ver| os.version_range.windows.min = win_ver,
};
if (query.os_version_max) |max| switch (max) {
.none => {},
.semver => |semver| switch (os.tag.versionRangeTag()) {
inline .hurd, .linux => |t| @field(os.version_range, @tagName(t)).range.max = semver,
else => os.version_range.semver.max = semver,
},
.windows => |win_ver| os.version_range.windows.max = win_ver,
};
if (query.glibc_version) |glibc| {
switch (os.tag.versionRangeTag()) {
inline .hurd, .linux => |t| @field(os.version_range, @tagName(t)).glibc = glibc,
else => {},
}
}
if (query.android_api_level) |android| {
os.version_range.linux.android = android;
}
var cpu = switch (query.cpu_model) {
.native => detectNativeCpuAndFeatures(io, query_cpu_arch),
.baseline => null,
.determined_by_arch_os => if (query.cpu_arch == null)
detectNativeCpuAndFeatures(io, query_cpu_arch)
else
null,
.explicit => |model| model.toCpu(query_cpu_arch),
} orelse Target.Cpu.baseline(query_cpu_arch, os);
// 对于 x86,需要根据架构和模式填充部分处理器特性
// 标志:
// * 16bit_mode => 架构为 x86_16 时
// * 32bit_mode => 架构为 x86 时
// 但“模式”标志可作为覆盖项,因此如果用户明确
// 设置其中一个,就优先使用用户设置。
switch (query_cpu_arch) {
.x86_16 => {
cpu.features.addFeature(@backingInt(Target.x86.Feature.@"16bit_mode"));
},
.x86 => {
if (!Target.x86.featureSetHasAny(query.cpu_features_add, .{
.@"16bit_mode", .@"32bit_mode",
})) {
cpu.features.addFeature(@backingInt(Target.x86.Feature.@"32bit_mode"));
}
},
.arm, .armeb => {
// XXX:若目标具有 noarm 特性,应如何处理?
// 若用户指定 +thumb_mode,又该如何处理?
},
.thumb, .thumbeb => {
cpu.features.addFeature(@backingInt(Target.arm.Feature.thumb_mode));
},
else => {},
}
updateCpuFeatures(
&cpu.features,
cpu.arch.allFeaturesList(),
query.cpu_features_add,
query.cpu_features_sub,
);
var result = detectAbiAndDynamicLinker(io, cpu, os, query) catch |err| switch (err) {
error.Canceled => |e| return e,
error.Unexpected => |e| return e,
error.ApiLevelQueryFailed => |e| return e,
error.WouldBlock => return error.Unexpected,
error.ConnectionResetByPeer => return error.Unexpected,
error.NotOpenForReading => return error.Unexpected,
error.SocketUnconnected => return error.Unexpected,
error.ReadOnlyFileSystem => return error.Unexpected,
error.AccessDenied,
error.SymLinkLoop,
error.ProcessFdQuotaExceeded,
error.SystemFdQuotaExceeded,
error.SystemResources,
error.IsDir,
error.DeviceBusy,
error.InputOutput,
error.LockViolation,
error.FileSystem,
error.UnableToOpenElfFile,
error.UnhelpfulFile,
error.InvalidElfFile,
error.RelativeShebang,
=> return defaultAbiAndDynamicLinker(cpu, os, query),
};
// 这些针对 CPU 特性的特殊处理必须在 ABI 检测之后进行。
{
if (result.cpu.arch == .hexagon) {
// LLVM 和 LLD 对小数据区的支持都有问题,但 LLVM 对所有 Hexagon CPU
// 默认启用此特性。Clang 的应对方式是将 Hexagon 后端的
// `-gpsize` 命令行参数默认为 0,使常量不进入
// SDA。(当然,如果用户向 Clang 传入
// `-G <n>`,此方法就失效。)我们无法采用 `-gpsize` 的变通方案,因为可能并发
// 执行多个 LLVM 输出任务,而 LLVM 的命令行选项是全局共享的。因此,
// 只能强制关闭此特性。真令人无奈。
result.cpu.features.removeFeature(@backingInt(Target.hexagon.Feature.small_data));
}
// https://github.com/llvm/llvm-project/issues/105978
if (result.cpu.arch.isArm() and result.abi.float() == .soft) {
result.cpu.features.removeFeature(@backingInt(Target.arm.Feature.vfp2));
}
if (result.cpu.arch.isXtensa() and result.abi == .call0) {
result.cpu.features.removeFeature(@backingInt(Target.xtensa.Feature.windowed));
}
}
// 可能已检测出原生 ABI,却未能检测出操作系统版本,或者调用者要求使用默认操作系统版本范围。
// 此时虽然无法确定确切的原生操作系统版本,但至少知道某些 ABI 要求特定操作系统版本,见 `std.zig.target.available_libcs`。
// 因此在这种情况下,将操作系统版本调整为已知必需的最低版本。
//
//
if (result.abi != query_abi and query.os_version_min == null) {
const result_ver_range = &result.os.version_range;
const abi_ver_range = result.os.tag.defaultVersionRange(result.cpu.arch, result.abi).version_range;
switch (result.os.tag.versionRangeTag()) {
.none => {},
.semver => if (result_ver_range.semver.min.order(abi_ver_range.semver.min) == .lt) {
result_ver_range.semver.min = abi_ver_range.semver.min;
},
inline .hurd, .linux => |t| {
if (@field(result_ver_range, @tagName(t)).range.min.order(@field(abi_ver_range, @tagName(t)).range.min) == .lt) {
@field(result_ver_range, @tagName(t)).range.min = @field(abi_ver_range, @tagName(t)).range.min;
}
if (@field(result_ver_range, @tagName(t)).glibc.order(@field(abi_ver_range, @tagName(t)).glibc) == .lt and
query.glibc_version == null)
{
@field(result_ver_range, @tagName(t)).glibc = @field(abi_ver_range, @tagName(t)).glibc;
}
},
.windows => if (!result_ver_range.windows.min.isAtLeast(abi_ver_range.windows.min)) {
result_ver_range.windows.min = abi_ver_range.windows.min;
},
}
}
return result;
}
fn updateCpuFeatures(
set: *Target.Cpu.Feature.Set,
all_features_list: []const Target.Cpu.Feature,
add_set: Target.Cpu.Feature.Set,
sub_set: Target.Cpu.Feature.Set,
) void {
set.removeFeatureSet(sub_set);
set.addFeatureSet(add_set);
set.populateDependencies(all_features_list);
set.removeFeatureSet(sub_set);
}
fn detectNativeCpuAndFeatures(io: Io, cpu_arch: Target.Cpu.Arch) ?Target.Cpu {
const family = builtin.target.cpu.arch.family();
assert(cpu_arch.family() == family);
switch (family) {
.loongarch => return @import("system/loongarch.zig").detectNativeCpuAndFeatures(cpu_arch),
.x86 => return @import("system/x86.zig").detectNativeCpuAndFeatures(cpu_arch),
else => {},
}
switch (builtin.os.tag) {
.freebsd => return freebsd.detectNativeCpuAndFeatures(),
.linux => return linux.detectNativeCpuAndFeatures(io),
.macos => return darwin.macos.detectNativeCpuAndFeatures(),
.netbsd => return netbsd.detectNativeCpuAndFeatures(),
.openbsd => return openbsd.detectNativeCpuAndFeatures(),
.windows => return windows.detectNativeCpuAndFeatures(),
else => {},
}
// 此架构尚未实现 CPU 型号及特性检测。
return null;
}
pub const AbiAndDynamicLinkerFromFileError = error{
Canceled,
AccessDenied,
Unexpected,
Unseekable,
ReadFailed,
EndOfStream,
NameTooLong,
StaticElfFile,
InvalidElfFile,
StreamTooLong,
Timeout,
SymLinkLoop,
SystemResources,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
IsDir,
WouldBlock,
InputOutput,
BrokenPipe,
ConnectionResetByPeer,
NotOpenForReading,
SocketUnconnected,
LockViolation,
FileSystem,
};
fn abiAndDynamicLinkerFromFile(
file_reader: *Io.File.Reader,
header: *const elf.Header,
cpu: Target.Cpu,
os: Target.Os,
ld_info_list: []const LdInfo,
query: Target.Query,
) AbiAndDynamicLinkerFromFileError!Target {
assert(query.abi == null); // 参见 `detectAbiAndDynamicLinker` 中的提前退出。
const io = file_reader.io;
var result: Target = .{
.cpu = cpu,
.os = os,
.abi = Target.Abi.default(cpu.arch, os.tag),
.ofmt = query.ofmt orelse Target.ObjectFormat.default(os.tag, cpu.arch),
.dynamic_linker = query.dynamic_linker orelse .none,
};
var rpath_offset: ?u64 = null; // 位于 PT.DYNAMIC 中
const look_for_ld = query.dynamic_linker == null;
var got_dyn_section: bool = false;
{
var it = header.iterateProgramHeaders(file_reader);
while (try it.next()) |phdr| switch (phdr.type) {
.INTERP => {
got_dyn_section = true;
var interp: Target.DynamicLinker = .none;
const p_filesz = phdr.filesz;
if (p_filesz < 2) return error.InvalidElfFile;
if (p_filesz > interp.buffer.len) return error.NameTooLong;
const filesz: usize = @intCast(p_filesz);
try file_reader.seekTo(phdr.offset);
try file_reader.interface.readSliceAll(interp.buffer[0..filesz]);
// PT.INTERP 的 filesz 包含一个空字节。
const len = filesz - 1;
// dynamic_linker.max_byte 表示“max”,而非“len”。
// 由于上方已与 dynamic_linker.buffer.len 比较,已知它可放入 u8。
interp.len = @intCast(len);
// 用它确定 ABI。
for (ld_info_list) |ld_info| {
if (std.mem.endsWith(u8, interp.get().?, fs.path.basename(ld_info.ld.get().?))) {
result.abi = ld_info.abi;
if (look_for_ld) result.dynamic_linker = interp;
break;
}
}
},
// 仅在检测 glibc 版本时需要此内容。
.DYNAMIC => {
got_dyn_section = true;
if (builtin.target.os.tag == .linux and result.isGnuLibC() and query.glibc_version == null) {
var dyn_it = header.iterateDynamicSection(file_reader, phdr.offset, phdr.filesz);
while (try dyn_it.next()) |dyn| {
if (dyn.d_tag == elf.DT_RUNPATH) {
rpath_offset = dyn.d_val;
break;
}
}
}
},
else => continue,
};
}
if (look_for_ld and result.dynamic_linker.get() == null) {
result.dynamic_linker = .standard(cpu, os.tag, result.abi);
}
if (!got_dyn_section) {
return error.StaticElfFile;
}
if (builtin.target.os.tag == .linux and result.isGnuLibC() and query.glibc_version == null) {
const str_section_off = header.shoff + @as(u64, header.shentsize) * @as(u64, header.shstrndx);
try file_reader.seekTo(str_section_off);
const shstr = try elf.takeSectionHeader(&file_reader.interface, header.is_64, header.endian);
var strtab_buf: [4096]u8 = undefined;
const shstrtab = strtab_buf[0..@min(shstr.sh_size, strtab_buf.len)];
try file_reader.seekTo(shstr.sh_offset);
try file_reader.interface.readSliceAll(shstrtab);
const dynstr: ?struct { offset: u64, size: u64 } = find_dyn_str: {
var it = header.iterateSectionHeaders(file_reader);
while (try it.next()) |shdr| {
const end = mem.findScalarPos(u8, shstrtab, shdr.sh_name, 0) orelse continue;
const sh_name = shstrtab[shdr.sh_name..end :0];
if (mem.eql(u8, sh_name, ".dynstr")) break :find_dyn_str .{
.offset = shdr.sh_offset,
.size = shdr.sh_size,
};
} else break :find_dyn_str null;
};
if (dynstr) |ds| {
if (rpath_offset) |rpoff| {
if (rpoff > ds.size) return error.InvalidElfFile;
const rpoff_file = ds.offset + rpoff;
const rp_max_size = ds.size - rpoff;
try file_reader.seekTo(rpoff_file);
const rpath_list = try file_reader.interface.takeSentinel(0);
if (rpath_list.len > rp_max_size) return error.StreamTooLong;
var it = mem.tokenizeScalar(u8, rpath_list, ':');
while (it.next()) |rpath| {
if (glibcVerFromRPath(io, rpath)) |ver| {
result.os.version_range.linux.glibc = ver;
return result;
} else |err| switch (err) {
error.GLibCNotFound => continue,
else => |e| return e,
}
}
}
}
if (result.dynamic_linker.get()) |dl_path| glibc_ver: {
// 不存在 DT_RUNPATH,因此尝试在动态链接器
// 所在目录中查找 libc.so.6。
if (fs.path.dirname(dl_path)) |rpath| {
if (glibcVerFromRPath(io, rpath)) |ver| {
result.os.version_range.linux.glibc = ver;
return result;
} else |err| switch (err) {
error.GLibCNotFound => {},
else => |e| return e,
}
}
// 目前尚未成功。接下来检查动态链接器路径的
// 符号链接数据中是否包含所需信息。
var link_buffer: [posix.PATH_MAX]u8 = undefined;
const link_name = if (Io.Dir.readLinkAbsolute(io, dl_path, &link_buffer)) |n|
link_buffer[0..n]
else |err| switch (err) {
error.NameTooLong => unreachable,
error.BadPathName => unreachable, // 仅限 Windows
error.UnsupportedReparsePointType => unreachable, // 仅限 Windows
error.NetworkNotFound => unreachable, // 仅限 Windows
error.AntivirusInterference => unreachable, // 仅限 Windows
error.FileBusy => unreachable, // 仅限 Windows
error.AccessDenied,
error.PermissionDenied,
error.FileNotFound,
error.NotLink,
error.NotDir,
=> break :glibc_ver,
error.SystemResources,
error.FileSystem,
error.SymLinkLoop,
error.Canceled,
error.Unexpected,
=> |e| return e,
};
result.os.version_range.linux.glibc = glibcVerFromLinkName(
fs.path.basename(link_name),
"ld-",
) catch |err| switch (err) {
error.UnrecognizedGnuLibCFileName,
error.InvalidGnuLibCVersion,
=> break :glibc_ver,
};
return result;
}
// 此前的方法均失败。最终回退到硬编码搜索路径。
// Debian 等发行版将 libc.so.6 存放在 `/lib/$triple/` 中。
var path_buf: [posix.PATH_MAX]u8 = undefined;
var index: usize = 0;
const prefix = "/lib/";
const cpu_arch = @tagName(result.cpu.arch);
const os_tag = @tagName(result.os.tag);
const abi = @tagName(result.abi);
@memcpy(path_buf[index..][0..prefix.len], prefix);
index += prefix.len;
@memcpy(path_buf[index..][0..cpu_arch.len], cpu_arch);
index += cpu_arch.len;
path_buf[index] = '-';
index += 1;
@memcpy(path_buf[index..][0..os_tag.len], os_tag);
index += os_tag.len;
path_buf[index] = '-';
index += 1;
@memcpy(path_buf[index..][0..abi.len], abi);
index += abi.len;
const rpath = path_buf[0..index];
if (glibcVerFromRPath(io, rpath)) |ver| {
result.os.version_range.linux.glibc = ver;
return result;
} else |err| switch (err) {
error.GLibCNotFound => {},
else => |e| return e,
}
}
return result;
}
fn glibcVerFromLinkName(link_name: []const u8, prefix: []const u8) error{ UnrecognizedGnuLibCFileName, InvalidGnuLibCVersion }!std.SemanticVersion {
// 示例:"libc-2.3.4.so"
// 示例:"libc-2.27.so"
// 示例:"ld-2.33.so"
const suffix = ".so";
if (!mem.startsWith(u8, link_name, prefix) or !mem.endsWith(u8, link_name, suffix)) {
return error.UnrecognizedGnuLibCFileName;
}
// 去掉 "libc-" 和 ".so"
const link_name_chopped = link_name[prefix.len .. link_name.len - suffix.len];
return Target.Query.parseVersion(link_name_chopped) catch |err| switch (err) {
error.Overflow => return error.InvalidGnuLibCVersion,
error.InvalidVersion => return error.InvalidGnuLibCVersion,
};
}
test glibcVerFromLinkName {
try std.testing.expectError(error.UnrecognizedGnuLibCFileName, glibcVerFromLinkName("ld-2.37.so", "this-prefix-does-not-exist"));
try std.testing.expectError(error.UnrecognizedGnuLibCFileName, glibcVerFromLinkName("libc-2.37.so-is-not-end", "libc-"));
try std.testing.expectError(error.InvalidGnuLibCVersion, glibcVerFromLinkName("ld-2.so", "ld-"));
try std.testing.expectEqual(std.SemanticVersion{ .major = 2, .minor = 37, .patch = 0 }, try glibcVerFromLinkName("ld-2.37.so", "ld-"));
try std.testing.expectEqual(std.SemanticVersion{ .major = 2, .minor = 37, .patch = 0 }, try glibcVerFromLinkName("ld-2.37.0.so", "ld-"));
try std.testing.expectEqual(std.SemanticVersion{ .major = 2, .minor = 37, .patch = 1 }, try glibcVerFromLinkName("ld-2.37.1.so", "ld-"));
try std.testing.expectError(error.InvalidGnuLibCVersion, glibcVerFromLinkName("ld-2.37.4.5.so", "ld-"));
}
fn glibcVerFromRPath(io: Io, rpath: []const u8) !std.SemanticVersion {
const cwd: Io.Dir = .cwd();
var dir = cwd.openDir(io, rpath, .{}) catch |err| switch (err) {
error.NameTooLong => return error.Unexpected,
error.BadPathName => return error.Unexpected,
error.NetworkNotFound => return error.Unexpected, // 仅限 Windows
error.FileNotFound => return error.GLibCNotFound,
error.NotDir => return error.GLibCNotFound,
error.AccessDenied => return error.GLibCNotFound,
error.PermissionDenied => return error.GLibCNotFound,
error.NoDevice => return error.GLibCNotFound,
error.ProcessFdQuotaExceeded => |e| return e,
error.SystemFdQuotaExceeded => |e| return e,
error.SystemResources => |e| return e,
error.SymLinkLoop => |e| return e,
error.Unexpected => |e| return e,
error.Canceled => |e| return e,
};
defer dir.close(io);
// 现在已得到 libc 共享对象路径的候选值。过去在此使用 readlink(),因为链接名称会体现 glibc 版本。但较新的 GNU/Linux 安装中不再有该符号链接,因此改用更稳健的检查:打开 libc 共享对象,查看 .dynstr 节,并查找以“GLIBC_2.”开头的符号中的最大版本号。
//
//
//
//
//
//
const glibc_so_basename = "libc.so.6";
var file = dir.openFile(io, glibc_so_basename, .{}) catch |err| switch (err) {
error.NameTooLong => return error.Unexpected,
error.BadPathName => return error.Unexpected,
error.PipeBusy => return error.Unexpected, // 仅限 Windows
error.NetworkNotFound => return error.Unexpected, // 仅限 Windows
error.AntivirusInterference => return error.Unexpected, // 仅限 Windows
error.FileLocksUnsupported => return error.Unexpected, // 未请求锁。
error.NoSpaceLeft => return error.Unexpected, // 只读
error.PathAlreadyExists => return error.Unexpected, // 只读
error.DeviceBusy => return error.Unexpected, // 只读
error.FileBusy => return error.Unexpected, // 只读
error.ReadOnlyFileSystem => return error.Unexpected, // 只读
error.NoDevice => return error.Unexpected, // 未请求特殊设备
error.FileTooBig => return error.Unexpected,
error.WouldBlock => return error.Unexpected, // 在非阻塞模式下未打开
error.AccessDenied => return error.GLibCNotFound,
error.PermissionDenied => return error.GLibCNotFound,
error.FileNotFound => return error.GLibCNotFound,
error.NotDir => return error.GLibCNotFound,
error.IsDir => return error.GLibCNotFound,
error.ProcessFdQuotaExceeded => |e| return e,
error.SystemFdQuotaExceeded => |e| return e,
error.SystemResources => |e| return e,
error.SymLinkLoop => |e| return e,
error.Unexpected => |e| return e,
error.Canceled => |e| return e,
};
defer file.close(io);
// 实际观察中,本系统 glibc 2.34 的 libc.so 的 .dynstr 节为 32441 字节。
var buffer: [8000]u8 = undefined;
var file_reader: Io.File.Reader = .init(file, io, &buffer);
return glibcVerFromSoFile(&file_reader) catch |err| switch (err) {
error.InvalidElfMagic,
error.InvalidElfEndian,
error.InvalidElfClass,
error.InvalidElfVersion,
error.InvalidGnuLibCVersion,
error.EndOfStream,
=> return error.GLibCNotFound,
error.ReadFailed => return file_reader.err.?,
else => |e| return e,
};
}
fn glibcVerFromSoFile(file_reader: *Io.File.Reader) !std.SemanticVersion {
const header = try elf.Header.read(&file_reader.interface);
const str_section_off = header.shoff + @as(u64, header.shentsize) * @as(u64, header.shstrndx);
try file_reader.seekTo(str_section_off);
const shstr = try elf.takeSectionHeader(&file_reader.interface, header.is_64, header.endian);
var strtab_buf: [4096]u8 = undefined;
const shstrtab = strtab_buf[0..@min(shstr.sh_size, strtab_buf.len)];
try file_reader.seekTo(shstr.sh_offset);
try file_reader.interface.readSliceAll(shstrtab);
const dynstr: struct { offset: u64, size: u64 } = find_dyn_str: {
var it = header.iterateSectionHeaders(file_reader);
while (try it.next()) |shdr| {
const end = mem.findScalarPos(u8, shstrtab, shdr.sh_name, 0) orelse continue;
const sh_name = shstrtab[shdr.sh_name..end :0];
if (mem.eql(u8, sh_name, ".dynstr")) break :find_dyn_str .{
.offset = shdr.sh_offset,
.size = shdr.sh_size,
};
} else return error.InvalidGnuLibCVersion;
};
// 遍历 dynstr 字符串表中的所有字符串,假定任何
// 以 "GLIBC_2." 开头的字符串都表示存在相应 glibc 版本,
// 并进一步假定系统安装的 glibc 至少为该版本。
var max_ver: std.SemanticVersion = .{ .major = 2, .minor = 2, .patch = 5 };
var offset: u64 = 0;
try file_reader.seekTo(dynstr.offset);
while (offset < dynstr.size) {
if (file_reader.interface.takeSentinel(0)) |s| {
if (mem.startsWith(u8, s, "GLIBC_2.")) {
const chopped = s["GLIBC_".len..];
const ver = Target.Query.parseVersion(chopped) catch |err| switch (err) {
error.Overflow => return error.InvalidGnuLibCVersion,
error.InvalidVersion => return error.InvalidGnuLibCVersion,
};
switch (ver.order(max_ver)) {
.gt => max_ver = ver,
.lt, .eq => continue,
}
}
offset += s.len + 1;
} else |err| switch (err) {
error.EndOfStream, error.StreamTooLong => break,
error.ReadFailed => |e| return e,
}
}
return max_ver;
}
/// 过去,此函数会在可执行文件动态链接时尝试使用该可执行文件自身,以同时判断 C ABI 和动态链接器。但在某些系统中,编译器二进制文件使用 RUNPATH,可能因此绑定到较旧版本的 glibc;而 /usr/bin/env 等系统二进制文件则使用较新版本。问题在于 libc.so.6 的 glibc 版本会与系统匹配,而动态链接器版本会与编译器二进制文件匹配。两者版本不一致的可执行文件将无法运行。
///
/// 因此,无论编译器二进制文件是动态链接还是静态链接,此函数的行为都相同。它会检查 `/usr/bin/env`,将其视为 ELF 文件,以获取这些问题的答案;如果文件包含 shebang 行,则会递归追踪其中引用的文件。若仍无法确定,则回退到默认值。
///
///
///
///
///
///
///
///
///
///
fn detectAbiAndDynamicLinker(io: Io, cpu: Target.Cpu, os: Target.Os, query: Target.Query) !Target {
const native_os_uses_elf = comptime Target.ObjectFormat.default(builtin.target.os.tag, builtin.target.cpu.arch) == .elf;
const native_ld_needs_abi = comptime Target.DynamicLinker.kind(builtin.target.os.tag) == .arch_os_abi;
if (!native_os_uses_elf or !native_ld_needs_abi or query.os_tag != null or query.abi != null) {
return defaultAbiAndDynamicLinker(cpu, os, query);
}
assert(os.tag == builtin.target.os.tag);
// 此处不能依赖当前目标的 ABI。例如,可以为 riscv64-linux-musl
// 构建 Zig 编译器,并提供 tar 包供用户下载。
// 用户随后可能在 riscv64-linux-gnu 上运行该编译器。这是 Zig
// 明确定义并支持的用法,因此必须在此处检测系统 ABI,
// 而不能依赖 `builtin.target`。
const all_abis = comptime blk: {
assert(@backingInt(Target.Abi.none) == 0);
const field_names = @typeInfo(Target.Abi).@"enum".field_names[1..];
var array: [field_names.len]Target.Abi = undefined;
for (field_names, 0..) |field_name, i| {
array[i] = @field(Target.Abi, field_name);
}
break :blk array;
};
var ld_info_list_buffer: [all_abis.len]LdInfo = undefined;
var ld_info_list_len: usize = 0;
for (all_abis) |abi| {
const ld: Target.DynamicLinker = .standard(cpu, os.tag, abi);
// 生成的目标三元组是否确实具有标准动态链接器路径?
if (ld.get() == null) continue;
ld_info_list_buffer[ld_info_list_len] = .{
.ld = ld,
.abi = abi,
};
ld_info_list_len += 1;
}
const ld_info_list = ld_info_list_buffer[0..ld_info_list_len];
var file_reader: Io.File.Reader = undefined;
// 根据 `man 2 execve`:
//
// 内核限制脚本开头“#!”之后文本的最大长度,超过限制的字符会被忽略。
// Linux 5.1 之前,限制为 127 个字符。
// 自 Linux 5.1 起,限制为 255 个字符。
//
// 测试表明,bash 和 zsh 将 255 视为总长度限制,包括“#!”字符,但不包括换行符。
// 为安全起见,最大长度设为 255 + \n(1)。
//
//
//
const max_shebang_line_size = 256;
var file_reader_buffer: [4096]u8 = undefined;
comptime assert(file_reader_buffer.len >= max_shebang_line_size);
// 最佳情况:可执行文件采用动态链接,可以遍历
// 自身的共享对象并找到动态链接器。
const header = elf_file: {
// 此代码块检查“/usr/bin/env”中的 shebang 行。若找到,
// 则不再将“/usr/bin/env”用作要检查的 ELF 文件,
// 而是使用该行引用的文件;若又找到 shebang 行,
// 则递归执行相同逻辑。
// 许多可移植脚本的 shebang 行都硬编码 /usr/bin/env,因此它是相当可靠的起始路径。
//
var file_name: []const u8 = "/usr/bin/env";
while (true) {
const file = Io.Dir.openFileAbsolute(io, file_name, .{}) catch |err| switch (err) {
error.NoSpaceLeft => return error.Unexpected,
error.NameTooLong => return error.Unexpected,
error.PathAlreadyExists => return error.Unexpected,
error.BadPathName => return error.Unexpected,
error.PipeBusy => return error.Unexpected,
error.FileLocksUnsupported => return error.Unexpected,
error.FileBusy => return error.Unexpected, // 打开时无写入权限
error.AntivirusInterference => return error.Unexpected, // 仅 Windows 存在的错误
error.IsDir,
error.NotDir,
error.AccessDenied,
error.PermissionDenied,
error.NoDevice,
error.FileNotFound,
error.NetworkNotFound,
error.FileTooBig,
error.Unexpected,
=> |e| if (builtin.target.os.tag == .linux and e == error.FileNotFound and mem.eql(u8, file_name, "/usr/bin/env")) {
// Android 没有 /usr 目录,因此重试
file_name = "/system/bin/env";
continue;
} else return error.UnableToOpenElfFile,
else => |e| return e,
};
var is_elf_file = false;
defer if (!is_elf_file) file.close(io);
file_reader = .init(file, io, &file_reader_buffer);
file_name = undefined; // 它与 file_reader_buffer 互为别名
const header = elf.Header.read(&file_reader.interface) catch |hdr_err| switch (hdr_err) {
error.EndOfStream,
error.InvalidElfMagic,
=> {
const shebang_line = file_reader.interface.takeSentinel('\n') catch |err| switch (err) {
error.ReadFailed => return file_reader.err.?,
// 既不是 ELF 文件,也不是带 shebang 行的文件。
error.EndOfStream, error.StreamTooLong => return error.UnhelpfulFile,
};
if (!mem.startsWith(u8, shebang_line, "#!")) return error.UnhelpfulFile;
// 检测到 shebang,现在解析整行。
// 移除前导的 "#!"、空格和制表符。
const trimmed_line = mem.trimStart(u8, shebang_line[2..], &.{ ' ', '\t' });
// 此行可包含:
// * 仅解释器路径;
// * 解释器路径及参数,全部由空格、制表符或 NUL 字符分隔。
// 末尾还可有可选换行符。
const path_maybe_args = mem.trimEnd(u8, trimmed_line, "\n");
// 分离路径与参数。
const path_end = mem.findAny(u8, path_maybe_args, &.{ ' ', '\t', 0 }) orelse path_maybe_args.len;
const unvalidated_path = path_maybe_args[0..path_end];
file_name = if (fs.path.isAbsolute(unvalidated_path)) unvalidated_path else return error.RelativeShebang;
continue;
},
error.InvalidElfVersion,
error.InvalidElfClass,
error.InvalidElfEndian,
=> return error.InvalidElfFile,
error.ReadFailed => return file_reader.err.?,
};
is_elf_file = true;
break :elf_file header;
}
};
defer file_reader.file.close(io);
var result = abiAndDynamicLinkerFromFile(&file_reader, &header, cpu, os, ld_info_list, query) catch |err| switch (err) {
error.FileSystem,
error.SystemResources,
error.SymLinkLoop,
error.ProcessFdQuotaExceeded,
error.SystemFdQuotaExceeded,
error.Canceled,
=> |e| return e,
error.ReadFailed => return file_reader.err.?,
else => |e| {
std.log.warn("encountered {t}; falling back to default ABI and dynamic linker", .{e});
return defaultAbiAndDynamicLinker(cpu, os, query);
},
};
if (builtin.target.os.tag == .linux and result.isBionicLibC() and query.android_api_level == null) {
result.os.version_range.linux.android = detectAndroidApiLevel(io) catch |err| return switch (err) {
error.InvalidWtf8,
error.InvalidBatchScriptArg,
=> unreachable, // 仅限 Windows
error.ApiLevelQueryFailed => |e| e,
else => blk: {
std.log.err("spawning or reading from getprop failed ({s})", .{@errorName(err)});
switch (err) {
error.SystemResources,
error.FileSystem,
error.ProcessFdQuotaExceeded,
error.SystemFdQuotaExceeded,
error.SymLinkLoop,
=> |e| break :blk e,
else => break :blk error.ApiLevelQueryFailed,
}
},
};
}
return result;
}
fn defaultAbiAndDynamicLinker(cpu: Target.Cpu, os: Target.Os, query: Target.Query) Target {
const abi = query.abi orelse Target.Abi.default(cpu.arch, os.tag);
return .{
.cpu = cpu,
.os = os,
.abi = abi,
.ofmt = query.ofmt orelse Target.ObjectFormat.default(os.tag, cpu.arch),
.dynamic_linker = query.dynamic_linker orelse .standard(cpu, os.tag, abi),
};
}
const LdInfo = struct {
ld: Target.DynamicLinker,
abi: Target.Abi,
};
fn detectAndroidApiLevel(io: Io) !u32 {
comptime if (builtin.os.tag != .linux) unreachable;
var child = try std.process.spawn(io, .{
.argv = &.{
"/system/bin/getprop",
"ro.build.version.sdk",
},
.stdin = .ignore,
.stdout = .pipe,
.stderr = .ignore,
});
errdefer child.kill(io);
// PROP_VALUE_MAX 为 92,输出为值加换行符。
// 目前 API 级别为两位数,但需要确保绝不读取到不完整的值。
var stdout_buf: [92 + 1]u8 = undefined;
var reader = child.stdout.?.readerStreaming(io, &.{});
const n = try reader.interface.readSliceShort(&stdout_buf);
switch (try child.wait(io)) {
.exited => |code| if (code != 0) {
std.log.err("getprop terminated abnormally with exit code: {d}", .{code});
return error.ApiLevelQueryFailed;
},
.signal => |sig| {
std.log.err("getprop terminated abnormally with signal: {t}", .{sig});
return error.ApiLevelQueryFailed;
},
.stopped => |sig| {
std.log.err("getprop stopped abnormally with signal: {t}", .{sig});
return error.ApiLevelQueryFailed;
},
.unknown => {
std.log.err("getprop terminated abnormally", .{});
return error.ApiLevelQueryFailed;
},
}
const result = mem.trimEnd(u8, stdout_buf[0..n], "\n");
return std.fmt.parseInt(u32, result, 10) catch |e| {
std.log.err(
"Could not parse API level, unexpected getprop output '{s}' ({s})",
.{ result, @errorName(e) },
);
return error.ApiLevelQueryFailed;
};
}
test {
_ = NativePaths;
_ = darwin;
_ = freebsd;
_ = linux;
_ = netbsd;
_ = openbsd;
_ = windows;
}