std.Target: add DynamicLinker

This commit is contained in:
Andrew Kelley 2023-12-04 15:26:57 -07:00
parent 3179f58c41
commit dbdb87502d
16 changed files with 1280 additions and 1295 deletions

View File

@ -516,7 +516,6 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/lib/std/zig/string_literal.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/system.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/system/NativePaths.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/system/NativeTargetInfo.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/system/x86.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/tokenizer.zig"
"${CMAKE_SOURCE_DIR}/src/Air.zig"

View File

@ -46,11 +46,9 @@ pub fn main() !void {
return error.InvalidArgs;
};
const detected = try std.zig.system.NativeTargetInfo.detect(.{});
const host: std.Build.ResolvedTarget = .{
.query = .{},
.target = detected.target,
.dynamic_linker = detected.dynamic_linker,
.target = try std.zig.system.resolveTargetQuery(.{}),
};
const build_root_directory: std.Build.Cache.Directory = .{

View File

@ -2129,14 +2129,6 @@ pub fn hex64(x: u64) [16]u8 {
pub const ResolvedTarget = struct {
query: Target.Query,
target: Target,
dynamic_linker: Target.DynamicLinker,
pub fn toNativeTargetInfo(self: ResolvedTarget) std.zig.system.NativeTargetInfo {
return .{
.target = self.target,
.dynamic_linker = self.dynamic_linker,
};
}
};
/// Converts a target query into a fully resolved target that can be passed to
@ -2146,13 +2138,10 @@ pub fn resolveTargetQuery(b: *Build, query: Target.Query) ResolvedTarget {
// resolved via a WASI API or via the build protocol.
_ = b;
const result = std.zig.system.NativeTargetInfo.detect(query) catch
@panic("unable to resolve target query");
return .{
.query = query,
.target = result.target,
.dynamic_linker = result.dynamic_linker,
.target = std.zig.system.resolveTargetQuery(query) catch
@panic("unable to resolve target query"),
};
}

View File

@ -746,5 +746,4 @@ const Module = @This();
const std = @import("std");
const assert = std.debug.assert;
const LazyPath = std.Build.LazyPath;
const NativeTargetInfo = std.zig.system.NativeTargetInfo;
const Step = std.Build.Step;

View File

@ -9,7 +9,6 @@ const StringHashMap = std.StringHashMap;
const Sha256 = std.crypto.hash.sha2.Sha256;
const Allocator = mem.Allocator;
const Step = std.Build.Step;
const NativeTargetInfo = std.zig.system.NativeTargetInfo;
const LazyPath = std.Build.LazyPath;
const PkgConfigPkg = std.Build.PkgConfigPkg;
const PkgConfigError = std.Build.PkgConfigError;

View File

@ -294,11 +294,9 @@ test Options {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const detected = try std.zig.system.NativeTargetInfo.detect(.{});
const host: std.Build.ResolvedTarget = .{
.query = .{},
.target = detected.target,
.dynamic_linker = detected.dynamic_linker,
.target = try std.zig.system.resolveTargetQuery(.{}),
};
var cache: std.Build.Cache = .{

View File

@ -678,8 +678,8 @@ fn runCommand(
const need_cross_glibc = exe.rootModuleTarget().isGnuLibC() and
exe.is_linking_libc;
const other_target_info = exe.root_module.target.?.toNativeTargetInfo();
switch (b.host.toNativeTargetInfo().getExternalExecutor(&other_target_info, .{
const other_target = exe.root_module.target.?.target;
switch (std.zig.system.getExternalExecutor(b.host.target, &other_target, .{
.qemu_fixes_dl = need_cross_glibc and b.glibc_runtimes_dir != null,
.link_libc = exe.is_linking_libc,
})) {
@ -752,7 +752,7 @@ fn runCommand(
.bad_dl => |foreign_dl| {
if (allow_skip) return error.MakeSkipped;
const host_dl = b.host.dynamic_linker.get() orelse "(none)";
const host_dl = b.host.target.dynamic_linker.get() orelse "(none)";
return step.fail(
\\the host system is unable to execute binaries from the target

View File

@ -1,7 +1,13 @@
//! All the details about the machine that will be executing code.
//! Unlike `Query` which might leave some things as "default" or "host", this
//! data is fully resolved into a concrete set of OS versions, CPU features,
//! etc.
cpu: Cpu,
os: Os,
abi: Abi,
ofmt: ObjectFormat,
dynamic_linker: DynamicLinker = DynamicLinker.none,
pub const Query = @import("Target/Query.zig");
@ -1529,13 +1535,19 @@ pub inline fn hasDynamicLinker(self: Target) bool {
}
pub const DynamicLinker = struct {
/// Contains the memory used to store the dynamic linker path. This field should
/// not be used directly. See `get` and `set`. This field exists so that this API requires no allocator.
buffer: [255]u8 = undefined,
/// Contains the memory used to store the dynamic linker path. This field
/// should not be used directly. See `get` and `set`. This field exists so
/// that this API requires no allocator.
buffer: [255]u8,
/// Used to construct the dynamic linker path. This field should not be used
/// directly. See `get` and `set`.
max_byte: ?u8 = null,
max_byte: ?u8,
pub const none: DynamicLinker = .{
.buffer = undefined,
.max_byte = null,
};
/// Asserts that the length is less than or equal to 255 bytes.
pub fn init(dl_or_null: ?[]const u8) DynamicLinker {
@ -1561,8 +1573,12 @@ pub const DynamicLinker = struct {
}
};
pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
var result: DynamicLinker = .{};
pub fn standardDynamicLinkerPath(target: Target) DynamicLinker {
return standardDynamicLinkerPath_cpu_os_abi(target.cpu, target.os.tag, target.abi);
}
pub fn standardDynamicLinkerPath_cpu_os_abi(cpu: Cpu, os_tag: Os.Tag, abi: Abi) DynamicLinker {
var result = DynamicLinker.none;
const S = struct {
fn print(r: *DynamicLinker, comptime fmt: []const u8, args: anytype) DynamicLinker {
r.max_byte = @as(u8, @intCast((std.fmt.bufPrint(&r.buffer, fmt, args) catch unreachable).len - 1));
@ -1577,32 +1593,32 @@ pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
const print = S.print;
const copy = S.copy;
if (self.abi == .android) {
const suffix = if (self.ptrBitWidth() == 64) "64" else "";
if (abi == .android) {
const suffix = if (ptrBitWidth_cpu_abi(cpu, abi) == 64) "64" else "";
return print(&result, "/system/bin/linker{s}", .{suffix});
}
if (self.abi.isMusl()) {
const is_arm = switch (self.cpu.arch) {
if (abi.isMusl()) {
const is_arm = switch (cpu.arch) {
.arm, .armeb, .thumb, .thumbeb => true,
else => false,
};
const arch_part = switch (self.cpu.arch) {
const arch_part = switch (cpu.arch) {
.arm, .thumb => "arm",
.armeb, .thumbeb => "armeb",
else => |arch| @tagName(arch),
};
const arch_suffix = if (is_arm and self.abi.floatAbi() == .hard) "hf" else "";
const arch_suffix = if (is_arm and abi.floatAbi() == .hard) "hf" else "";
return print(&result, "/lib/ld-musl-{s}{s}.so.1", .{ arch_part, arch_suffix });
}
switch (self.os.tag) {
switch (os_tag) {
.freebsd => return copy(&result, "/libexec/ld-elf.so.1"),
.netbsd => return copy(&result, "/libexec/ld.elf_so"),
.openbsd => return copy(&result, "/usr/libexec/ld.so"),
.dragonfly => return copy(&result, "/libexec/ld-elf.so.2"),
.solaris, .illumos => return copy(&result, "/lib/64/ld.so.1"),
.linux => switch (self.cpu.arch) {
.linux => switch (cpu.arch) {
.x86,
.sparc,
.sparcel,
@ -1616,7 +1632,7 @@ pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
.armeb,
.thumb,
.thumbeb,
=> return copy(&result, switch (self.abi.floatAbi()) {
=> return copy(&result, switch (abi.floatAbi()) {
.hard => "/lib/ld-linux-armhf.so.3",
else => "/lib/ld-linux.so.3",
}),
@ -1626,12 +1642,12 @@ pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
.mips64,
.mips64el,
=> {
const lib_suffix = switch (self.abi) {
const lib_suffix = switch (abi) {
.gnuabin32, .gnux32 => "32",
.gnuabi64 => "64",
else => "",
};
const is_nan_2008 = mips.featureSetHas(self.cpu.features, .nan2008);
const is_nan_2008 = mips.featureSetHas(cpu.features, .nan2008);
const loader = if (is_nan_2008) "ld-linux-mipsn8.so.1" else "ld.so.1";
return print(&result, "/lib{s}/{s}", .{ lib_suffix, loader });
},
@ -1640,7 +1656,7 @@ pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
.powerpc64, .powerpc64le => return copy(&result, "/lib64/ld64.so.2"),
.s390x => return copy(&result, "/lib64/ld64.so.1"),
.sparc64 => return copy(&result, "/lib64/ld-linux.so.2"),
.x86_64 => return copy(&result, switch (self.abi) {
.x86_64 => return copy(&result, switch (abi) {
.gnux32 => "/libx32/ld-linux-x32.so.2",
else => "/lib64/ld-linux-x86-64.so.2",
}),
@ -1862,17 +1878,17 @@ pub fn maxIntAlignment(target: Target) u16 {
};
}
pub fn ptrBitWidth(target: Target) u16 {
switch (target.abi) {
pub fn ptrBitWidth_cpu_abi(cpu: Cpu, abi: Abi) u16 {
switch (abi) {
.gnux32, .muslx32, .gnuabin32, .gnuilp32 => return 32,
.gnuabi64 => return 64,
else => {},
}
switch (target.cpu.arch) {
return switch (cpu.arch) {
.avr,
.msp430,
.spu_2,
=> return 16,
=> 16,
.arc,
.arm,
@ -1908,7 +1924,7 @@ pub fn ptrBitWidth(target: Target) u16 {
.loongarch32,
.dxil,
.xtensa,
=> return 32,
=> 32,
.aarch64,
.aarch64_be,
@ -1933,10 +1949,14 @@ pub fn ptrBitWidth(target: Target) u16 {
.ve,
.spirv64,
.loongarch64,
=> return 64,
=> 64,
.sparc => return if (std.Target.sparc.featureSetHas(target.cpu.features, .v9)) 64 else 32,
}
.sparc => if (std.Target.sparc.featureSetHas(cpu.features, .v9)) 64 else 32,
};
}
pub fn ptrBitWidth(target: Target) u16 {
return ptrBitWidth_cpu_abi(target.cpu, target.abi);
}
pub fn stackAlignment(target: Target) u16 {

View File

@ -34,7 +34,7 @@ abi: ?Target.Abi = null,
/// When `os_tag` is `null`, then `null` means native. Otherwise it means the standard path
/// based on the `os_tag`.
dynamic_linker: DynamicLinker = DynamicLinker{},
dynamic_linker: Target.DynamicLinker = Target.DynamicLinker.none,
/// `null` means default for the cpu/arch/os combo.
ofmt: ?Target.ObjectFormat = null,
@ -61,8 +61,6 @@ pub const OsVersion = union(enum) {
pub const SemanticVersion = std.SemanticVersion;
pub const DynamicLinker = Target.DynamicLinker;
pub fn fromTarget(target: Target) Query {
var result: Query = .{
.cpu_arch = target.cpu.arch,
@ -164,7 +162,7 @@ fn updateOsVersionRange(self: *Query, os: Target.Os) void {
}
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
/// TODO deprecated, use `std.zig.system.resolveTargetQuery`.
pub fn toTarget(self: Query) Target {
return .{
.cpu = self.getCpu(),
@ -232,7 +230,7 @@ pub fn parse(args: ParseOptions) !Query {
const diags = args.diagnostics orelse &dummy_diags;
var result: Query = .{
.dynamic_linker = DynamicLinker.init(args.dynamic_linker),
.dynamic_linker = Target.DynamicLinker.init(args.dynamic_linker),
};
var it = mem.splitScalar(u8, args.arch_os_abi, '-');
@ -379,13 +377,13 @@ test parseVersion {
try std.testing.expectError(error.InvalidVersion, parseVersion("1.2.3.4"));
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
/// TODO deprecated, use `std.zig.system.resolveTargetQuery`.
pub fn getCpu(self: Query) Target.Cpu {
switch (self.cpu_model) {
.native => {
// This works when doing `zig build` because Zig generates a build executable using
// native CPU model & features. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
// will need to be integrated with `std.zig.system.resolveTargetQuery`.
return builtin.cpu;
},
.baseline => {
@ -396,7 +394,7 @@ pub fn getCpu(self: Query) Target.Cpu {
.determined_by_cpu_arch => if (self.cpu_arch == null) {
// This works when doing `zig build` because Zig generates a build executable using
// native CPU model & features. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
// will need to be integrated with `std.zig.system.resolveTargetQuery`.
return builtin.cpu;
} else {
var adjusted_baseline = Target.Cpu.baseline(self.getCpuArch());
@ -426,11 +424,11 @@ pub fn getCpuFeatures(self: Query) Target.Cpu.Feature.Set {
return self.getCpu().features;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
/// TODO deprecated, use `std.zig.system.resolveTargetQuery`.
pub fn getOs(self: Query) Target.Os {
// `builtin.os` works when doing `zig build` because Zig generates a build executable using
// native OS version range. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
// will need to be integrated with `std.zig.system.resolveTargetQuery`.
var adjusted_os = if (self.os_tag) |os_tag| os_tag.defaultVersionRange(self.getCpuArch()) else builtin.os;
if (self.os_version_min) |min| switch (min) {
@ -463,7 +461,7 @@ pub fn getOsTag(self: Query) Target.Os.Tag {
return self.os_tag orelse builtin.os.tag;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
/// TODO deprecated, use `std.zig.system.resolveTargetQuery`.
pub fn getOsVersionMin(self: Query) OsVersion {
if (self.os_version_min) |version_min| return version_min;
var tmp: Query = undefined;
@ -471,7 +469,7 @@ pub fn getOsVersionMin(self: Query) OsVersion {
return tmp.os_version_min.?;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
/// TODO deprecated, use `std.zig.system.resolveTargetQuery`.
pub fn getOsVersionMax(self: Query) OsVersion {
if (self.os_version_max) |version_max| return version_max;
var tmp: Query = undefined;
@ -479,14 +477,14 @@ pub fn getOsVersionMax(self: Query) OsVersion {
return tmp.os_version_max.?;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
/// TODO deprecated, use `std.zig.system.resolveTargetQuery`.
pub fn getAbi(self: Query) Target.Abi {
if (self.abi) |abi| return abi;
if (self.os_tag == null) {
// This works when doing `zig build` because Zig generates a build executable using
// native CPU model & features. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
// will need to be integrated with `std.zig.system.resolveTargetQuery`.
return builtin.abi;
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@ const process = std.process;
const mem = std.mem;
const NativePaths = @This();
const NativeTargetInfo = std.zig.system.NativeTargetInfo;
arena: Allocator,
include_dirs: std.ArrayListUnmanaged([]const u8) = .{},
@ -14,8 +13,7 @@ framework_dirs: std.ArrayListUnmanaged([]const u8) = .{},
rpaths: std.ArrayListUnmanaged([]const u8) = .{},
warnings: std.ArrayListUnmanaged([]const u8) = .{},
pub fn detect(arena: Allocator, native_info: NativeTargetInfo) !NativePaths {
const native_target = native_info.target;
pub fn detect(arena: Allocator, native_target: std.Target) !NativePaths {
var self: NativePaths = .{ .arena = arena };
var is_nix = false;
if (process.getEnvVarOwned(arena, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| {

File diff suppressed because it is too large Load Diff

View File

@ -6527,7 +6527,6 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: Allocator) Alloca
try buffer.writer().print(" .{},\n", .{std.zig.fmtId(feature.name)});
}
}
try buffer.writer().print(
\\ }}),
\\}};
@ -6607,15 +6606,31 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: Allocator) Alloca
.{ windows.min, windows.max },
),
}
try buffer.appendSlice("};\n");
try buffer.writer().print(
\\pub const target = std.Target{{
try buffer.appendSlice(
\\};
\\pub const target: std.Target = .{
\\ .cpu = cpu,
\\ .os = os,
\\ .abi = abi,
\\ .ofmt = object_format,
\\}};
\\
);
if (target.dynamic_linker.get()) |dl| {
try buffer.writer().print(
\\ .dynamic_linker = std.Target.DynamicLinker.init("{s}"),
\\}};
\\
, .{dl});
} else {
try buffer.appendSlice(
\\ .dynamic_linker = std.Target.DynamicLinker.none,
\\};
\\
);
}
try buffer.writer().print(
\\pub const object_format = std.Target.ObjectFormat.{};
\\pub const mode = std.builtin.OptimizeMode.{};
\\pub const link_libc = {};

View File

@ -321,13 +321,14 @@ pub fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !voi
} else if (mem.eql(u8, cmd, "init")) {
return cmdInit(gpa, arena, cmd_args);
} else if (mem.eql(u8, cmd, "targets")) {
const info = try detectNativeTargetInfo(.{});
const host = try std.zig.system.resolveTargetQuery(.{});
const stdout = io.getStdOut().writer();
return @import("print_targets.zig").cmdTargets(arena, cmd_args, stdout, info.target);
return @import("print_targets.zig").cmdTargets(arena, cmd_args, stdout, host);
} else if (mem.eql(u8, cmd, "version")) {
try std.io.getStdOut().writeAll(build_options.version ++ "\n");
// Check libc++ linkage to make sure Zig was built correctly, but only for "env" and "version"
// to avoid affecting the startup time for build-critical commands (check takes about ~10 μs)
// Check libc++ linkage to make sure Zig was built correctly, but only
// for "env" and "version" to avoid affecting the startup time for
// build-critical commands (check takes about ~10 μs)
return verifyLibcxxCorrectlyLinked();
} else if (mem.eql(u8, cmd, "env")) {
verifyLibcxxCorrectlyLinked();
@ -2608,9 +2609,9 @@ fn buildOutputType(
}
const target_query = try parseTargetQueryOrReportFatalError(arena, target_parse_options);
const target_info = try detectNativeTargetInfo(target_query);
const target = try std.zig.system.resolveTargetQuery(target_query);
if (target_info.target.os.tag != .freestanding) {
if (target.os.tag != .freestanding) {
if (ensure_libc_on_non_freestanding)
link_libc = true;
if (ensure_libcpp_on_non_freestanding)
@ -2621,7 +2622,7 @@ fn buildOutputType(
if (!force) {
entry = null;
} else if (entry == null and output_mode == .Exe) {
entry = switch (target_info.target.ofmt) {
entry = switch (target.ofmt) {
.coff => "wWinMainCRTStartup",
.macho => "_main",
.elf, .plan9 => "_start",
@ -2629,12 +2630,12 @@ fn buildOutputType(
else => |tag| fatal("No default entry point available for output format {s}", .{@tagName(tag)}),
};
}
} else if (entry == null and target_info.target.isWasm() and output_mode == .Exe) {
} else if (entry == null and target.isWasm() and output_mode == .Exe) {
// For WebAssembly the compiler defaults to setting the entry name when no flags are set.
entry = defaultWasmEntryName(wasi_exec_model);
}
if (target_info.target.ofmt == .coff) {
if (target.ofmt == .coff) {
// Now that we know the target supports resources,
// we can add the res files as link objects.
for (res_files.items) |res_file| {
@ -2652,7 +2653,7 @@ fn buildOutputType(
}
}
if (target_info.target.cpu.arch.isWasm()) blk: {
if (target.cpu.arch.isWasm()) blk: {
if (single_threaded == null) {
single_threaded = true;
}
@ -2678,8 +2679,8 @@ fn buildOutputType(
fatal("shared memory is not allowed in object files", .{});
}
if (!target_info.target.cpu.features.isEnabled(@intFromEnum(std.Target.wasm.Feature.atomics)) or
!target_info.target.cpu.features.isEnabled(@intFromEnum(std.Target.wasm.Feature.bulk_memory)))
if (!target.cpu.features.isEnabled(@intFromEnum(std.Target.wasm.Feature.atomics)) or
!target.cpu.features.isEnabled(@intFromEnum(std.Target.wasm.Feature.bulk_memory)))
{
fatal("'atomics' and 'bulk-memory' features must be enabled to use shared memory", .{});
}
@ -2777,15 +2778,15 @@ fn buildOutputType(
}
for (system_libs.keys(), system_libs.values()) |lib_name, info| {
if (target_info.target.is_libc_lib_name(lib_name)) {
if (target.is_libc_lib_name(lib_name)) {
link_libc = true;
continue;
}
if (target_info.target.is_libcpp_lib_name(lib_name)) {
if (target.is_libcpp_lib_name(lib_name)) {
link_libcpp = true;
continue;
}
switch (target_util.classifyCompilerRtLibName(target_info.target, lib_name)) {
switch (target_util.classifyCompilerRtLibName(target, lib_name)) {
.none => {},
.only_libunwind, .both => {
link_libunwind = true;
@ -2797,8 +2798,8 @@ fn buildOutputType(
},
}
if (target_info.target.isMinGW()) {
const exists = mingw.libExists(arena, target_info.target, zig_lib_directory, lib_name) catch |err| {
if (target.isMinGW()) {
const exists = mingw.libExists(arena, target, zig_lib_directory, lib_name) catch |err| {
fatal("failed to check zig installation for DLL import libs: {s}", .{
@errorName(err),
});
@ -2820,7 +2821,7 @@ fn buildOutputType(
fatal("cannot use absolute path as a system library: {s}", .{lib_name});
}
if (target_info.target.os.tag == .wasi) {
if (target.os.tag == .wasi) {
if (wasi_libc.getEmulatedLibCRTFile(lib_name)) |crt_file| {
try wasi_emulated_libs.append(crt_file);
continue;
@ -2838,7 +2839,7 @@ fn buildOutputType(
if (sysroot == null and target_query.isNativeOs() and target_query.isNativeAbi() and
(external_system_libs.len != 0 or want_native_include_dirs))
{
const paths = std.zig.system.NativePaths.detect(arena, target_info) catch |err| {
const paths = std.zig.system.NativePaths.detect(arena, target) catch |err| {
fatal("unable to detect native system paths: {s}", .{@errorName(err)});
};
for (paths.warnings.items) |warning| {
@ -2857,7 +2858,7 @@ fn buildOutputType(
}
if (builtin.target.os.tag == .windows and
target_info.target.abi == .msvc and
target.abi == .msvc and
external_system_libs.len != 0)
{
if (libc_installation == null) {
@ -2902,7 +2903,7 @@ fn buildOutputType(
&checked_paths,
lib_dir_path,
lib_name,
target_info.target,
target,
info.preferred_mode,
)) {
const path = try arena.dupe(u8, test_path.items);
@ -2936,7 +2937,7 @@ fn buildOutputType(
&checked_paths,
lib_dir_path,
lib_name,
target_info.target,
target,
info.fallbackMode(),
)) {
const path = try arena.dupe(u8, test_path.items);
@ -2970,7 +2971,7 @@ fn buildOutputType(
&checked_paths,
lib_dir_path,
lib_name,
target_info.target,
target,
info.preferred_mode,
)) {
const path = try arena.dupe(u8, test_path.items);
@ -2994,7 +2995,7 @@ fn buildOutputType(
&checked_paths,
lib_dir_path,
lib_name,
target_info.target,
target,
info.fallbackMode(),
)) {
const path = try arena.dupe(u8, test_path.items);
@ -3089,15 +3090,13 @@ fn buildOutputType(
}
// After this point, resolved_frameworks is used instead of frameworks.
const object_format = target_info.target.ofmt;
if (output_mode == .Obj and (object_format == .coff or object_format == .macho)) {
if (output_mode == .Obj and (target.ofmt == .coff or target.ofmt == .macho)) {
const total_obj_count = c_source_files.items.len +
@intFromBool(root_src_file != null) +
rc_source_files.items.len +
link_objects.items.len;
if (total_obj_count > 1) {
fatal("{s} does not support linking multiple objects into one", .{@tagName(object_format)});
fatal("{s} does not support linking multiple objects into one", .{@tagName(target.ofmt)});
}
}
@ -3110,7 +3109,7 @@ fn buildOutputType(
const resolved_soname: ?[]const u8 = switch (soname) {
.yes => |explicit| explicit,
.no => null,
.yes_default_value => switch (object_format) {
.yes_default_value => switch (target.ofmt) {
.elf => if (have_version)
try std.fmt.allocPrint(arena, "lib{s}.so.{d}", .{ root_name, version.major })
else
@ -3119,7 +3118,7 @@ fn buildOutputType(
},
};
const a_out_basename = switch (object_format) {
const a_out_basename = switch (target.ofmt) {
.coff => "a.exe",
else => "a.out",
};
@ -3141,7 +3140,7 @@ fn buildOutputType(
},
.basename = try std.zig.binNameAlloc(arena, .{
.root_name = root_name,
.target = target_info.target,
.target = target,
.output_mode = output_mode,
.link_mode = link_mode,
.version = optional_version,
@ -3269,7 +3268,7 @@ fn buildOutputType(
// Note that cmake when targeting Windows will try to execute
// zig cc to make an executable and output an implib too.
const implib_eligible = is_exe_or_dyn_lib and
emit_bin_loc != null and target_info.target.os.tag == .windows;
emit_bin_loc != null and target.os.tag == .windows;
if (!implib_eligible) {
if (!emit_implib_arg_provided) {
emit_implib = .no;
@ -3419,7 +3418,7 @@ fn buildOutputType(
// "-" is stdin. Dump it to a real file.
const sep = fs.path.sep_str;
const sub_path = try std.fmt.allocPrint(arena, "tmp" ++ sep ++ "{x}-stdin{s}", .{
std.crypto.random.int(u64), ext.canonicalName(target_info.target),
std.crypto.random.int(u64), ext.canonicalName(target),
});
try local_cache_directory.handle.makePath("tmp");
// Note that in one of the happy paths, execve() is used to switch
@ -3454,10 +3453,10 @@ fn buildOutputType(
.local_cache_directory = local_cache_directory,
.global_cache_directory = global_cache_directory,
.root_name = root_name,
.target = target_info.target,
.target = target,
.is_native_os = target_query.isNativeOs(),
.is_native_abi = target_query.isNativeAbi(),
.dynamic_linker = target_info.dynamic_linker.get(),
.dynamic_linker = target.dynamic_linker.get(),
.sysroot = sysroot,
.output_mode = output_mode,
.main_mod = main_mod,
@ -3603,7 +3602,6 @@ fn buildOutputType(
.want_structured_cfg = want_structured_cfg,
}) catch |err| switch (err) {
error.LibCUnavailable => {
const target = target_info.target;
const triple_name = try target.zigTriple(arena);
std.log.err("unable to find or provide libc for target '{s}'", .{triple_name});
@ -3692,7 +3690,7 @@ fn buildOutputType(
try comp.makeBinFileExecutable();
saveState(comp, debug_incremental);
if (test_exec_args.items.len == 0 and object_format == .c) default_exec_args: {
if (test_exec_args.items.len == 0 and target.ofmt == .c) default_exec_args: {
// Default to using `zig run` to execute the produced .c code from `zig test`.
const c_code_loc = emit_bin_loc orelse break :default_exec_args;
const c_code_directory = c_code_loc.directory orelse comp.bin_file.options.emit.?.directory;
@ -3707,7 +3705,7 @@ fn buildOutputType(
if (link_libc) {
try test_exec_args.append("-lc");
} else if (target_info.target.os.tag == .windows) {
} else if (target.os.tag == .windows) {
try test_exec_args.appendSlice(&.{
"--subsystem", "console",
"-lkernel32", "-lntdll",
@ -3741,7 +3739,7 @@ fn buildOutputType(
test_exec_args.items,
self_exe_path.?,
arg_mode,
&target_info,
&target,
&comp_destroyed,
all_args,
runtime_args_start,
@ -3861,7 +3859,7 @@ fn serve(
// test_exec_args,
// self_exe_path.?,
// arg_mode,
// target_info,
// target,
// true,
// &comp_destroyed,
// all_args,
@ -4071,7 +4069,7 @@ fn runOrTest(
test_exec_args: []const ?[]const u8,
self_exe_path: []const u8,
arg_mode: ArgMode,
target_info: *const std.zig.system.NativeTargetInfo,
target: *const std.Target,
comp_destroyed: *bool,
all_args: []const []const u8,
runtime_args_start: ?usize,
@ -4105,7 +4103,7 @@ fn runOrTest(
if (process.can_execv and arg_mode == .run) {
// execv releases the locks; no need to destroy the Compilation here.
const err = process.execve(gpa, argv.items, &env_map);
try warnAboutForeignBinaries(arena, arg_mode, target_info, link_libc);
try warnAboutForeignBinaries(arena, arg_mode, target, link_libc);
const cmd = try std.mem.join(arena, " ", argv.items);
fatal("the following command failed to execve with '{s}':\n{s}", .{ @errorName(err), cmd });
} else if (process.can_spawn) {
@ -4121,7 +4119,7 @@ fn runOrTest(
comp_destroyed.* = true;
const term = child.spawnAndWait() catch |err| {
try warnAboutForeignBinaries(arena, arg_mode, target_info, link_libc);
try warnAboutForeignBinaries(arena, arg_mode, target, link_libc);
const cmd = try std.mem.join(arena, " ", argv.items);
fatal("the following command failed with '{s}':\n{s}", .{ @errorName(err), cmd });
};
@ -4820,12 +4818,10 @@ pub fn cmdLibC(gpa: Allocator, args: []const []const u8) !void {
if (!target_query.isNative()) {
fatal("unable to detect libc for non-native target", .{});
}
const target_info = try detectNativeTargetInfo(target_query);
var libc = LibCInstallation.findNative(.{
.allocator = gpa,
.verbose = true,
.target = target_info.target,
.target = try std.zig.system.resolveTargetQuery(target_query),
}) catch |err| {
fatal("unable to detect native libc: {s}", .{@errorName(err)});
};
@ -5114,11 +5110,11 @@ pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !voi
gimmeMoreOfThoseSweetSweetFileDescriptors();
const target_query: std.Target.Query = .{};
const target_info = try detectNativeTargetInfo(target_query);
const target = try std.zig.system.resolveTargetQuery(target_query);
const exe_basename = try std.zig.binNameAlloc(arena, .{
.root_name = "build",
.target = target_info.target,
.target = target,
.output_mode = .Exe,
});
const emit_bin: Compilation.EmitLoc = .{
@ -5282,10 +5278,10 @@ pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !voi
.local_cache_directory = local_cache_directory,
.global_cache_directory = global_cache_directory,
.root_name = "build",
.target = target_info.target,
.target = target,
.is_native_os = target_query.isNativeOs(),
.is_native_abi = target_query.isNativeAbi(),
.dynamic_linker = target_info.dynamic_linker.get(),
.dynamic_linker = target.dynamic_linker.get(),
.output_mode = .Exe,
.main_mod = &main_mod,
.emit_bin = emit_bin,
@ -6269,10 +6265,6 @@ test "fds" {
gimmeMoreOfThoseSweetSweetFileDescriptors();
}
fn detectNativeTargetInfo(target_query: std.Target.Query) !std.zig.system.NativeTargetInfo {
return std.zig.system.NativeTargetInfo.detect(target_query);
}
const usage_ast_check =
\\Usage: zig ast-check [file]
\\
@ -6669,24 +6661,24 @@ fn parseIntSuffix(arg: []const u8, prefix_len: usize) u64 {
fn warnAboutForeignBinaries(
arena: Allocator,
arg_mode: ArgMode,
target_info: *const std.zig.system.NativeTargetInfo,
target: *const std.Target,
link_libc: bool,
) !void {
const host_query: std.Target.Query = .{};
const host_target_info = try detectNativeTargetInfo(host_query);
const host_target = try std.zig.system.resolveTargetQuery(host_query);
switch (host_target_info.getExternalExecutor(target_info, .{ .link_libc = link_libc })) {
switch (std.zig.system.getExternalExecutor(host_target, target, .{ .link_libc = link_libc })) {
.native => return,
.rosetta => {
const host_name = try host_target_info.target.zigTriple(arena);
const foreign_name = try target_info.target.zigTriple(arena);
const host_name = try host_target.zigTriple(arena);
const foreign_name = try target.zigTriple(arena);
warn("the host system ({s}) does not appear to be capable of executing binaries from the target ({s}). Consider installing Rosetta.", .{
host_name, foreign_name,
});
},
.qemu => |qemu| {
const host_name = try host_target_info.target.zigTriple(arena);
const foreign_name = try target_info.target.zigTriple(arena);
const host_name = try host_target.zigTriple(arena);
const foreign_name = try target.zigTriple(arena);
switch (arg_mode) {
.zig_test => warn(
"the host system ({s}) does not appear to be capable of executing binaries " ++
@ -6702,8 +6694,8 @@ fn warnAboutForeignBinaries(
}
},
.wine => |wine| {
const host_name = try host_target_info.target.zigTriple(arena);
const foreign_name = try target_info.target.zigTriple(arena);
const host_name = try host_target.zigTriple(arena);
const foreign_name = try target.zigTriple(arena);
switch (arg_mode) {
.zig_test => warn(
"the host system ({s}) does not appear to be capable of executing binaries " ++
@ -6719,8 +6711,8 @@ fn warnAboutForeignBinaries(
}
},
.wasmtime => |wasmtime| {
const host_name = try host_target_info.target.zigTriple(arena);
const foreign_name = try target_info.target.zigTriple(arena);
const host_name = try host_target.zigTriple(arena);
const foreign_name = try target.zigTriple(arena);
switch (arg_mode) {
.zig_test => warn(
"the host system ({s}) does not appear to be capable of executing binaries " ++
@ -6736,8 +6728,8 @@ fn warnAboutForeignBinaries(
}
},
.darling => |darling| {
const host_name = try host_target_info.target.zigTriple(arena);
const foreign_name = try target_info.target.zigTriple(arena);
const host_name = try host_target.zigTriple(arena);
const foreign_name = try target.zigTriple(arena);
switch (arg_mode) {
.zig_test => warn(
"the host system ({s}) does not appear to be capable of executing binaries " ++
@ -6753,7 +6745,7 @@ fn warnAboutForeignBinaries(
}
},
.bad_dl => |foreign_dl| {
const host_dl = host_target_info.dynamic_linker.get() orelse "(none)";
const host_dl = host_target.dynamic_linker.get() orelse "(none)";
const tip_suffix = switch (arg_mode) {
.zig_test => ", '--test-no-exec', or '--test-cmd'",
else => "",
@ -6763,8 +6755,8 @@ fn warnAboutForeignBinaries(
});
},
.bad_os_or_cpu => {
const host_name = try host_target_info.target.zigTriple(arena);
const foreign_name = try target_info.target.zigTriple(arena);
const host_name = try host_target.zigTriple(arena);
const foreign_name = try target.zigTriple(arena);
const tip_suffix = switch (arg_mode) {
.zig_test => ". Consider using '--test-no-exec' or '--test-cmd'",
else => "",

View File

@ -17,8 +17,8 @@ pub fn cmdEnv(arena: Allocator, args: []const []const u8, stdout: std.fs.File.Wr
const global_cache_dir = try introspect.resolveGlobalCacheDir(arena);
const info = try std.zig.system.NativeTargetInfo.detect(.{});
const triple = try info.target.zigTriple(arena);
const host = try std.zig.system.resolveTargetQuery(.{});
const triple = try host.zigTriple(arena);
var bw = std.io.bufferedWriter(stdout);
const w = bw.writer();

View File

@ -541,7 +541,7 @@ pub fn lowerToBuildSteps(
cases_dir_path: []const u8,
incremental_exe: *std.Build.Step.Compile,
) void {
const host = std.zig.system.NativeTargetInfo.detect(.{}) catch |err|
const host = std.zig.system.resolveTargetQuery(.{}) catch |err|
std.debug.panic("unable to detect native host: {s}\n", .{@errorName(err)});
for (self.incremental_cases.items) |incr_case| {
@ -648,8 +648,7 @@ pub fn lowerToBuildSteps(
},
.Execution => |expected_stdout| no_exec: {
const run = if (case.target.target.ofmt == .c) run_step: {
const target_info = case.target.toNativeTargetInfo();
if (host.getExternalExecutor(&target_info, .{ .link_libc = true }) != .native) {
if (getExternalExecutor(host, &case.target.target, .{ .link_libc = true }) != .native) {
// We wouldn't be able to run the compiled C code.
break :no_exec;
}
@ -694,8 +693,7 @@ pub fn lowerToBuildSteps(
continue; // Pass test.
}
const target_info = case.target.toNativeTargetInfo();
if (host.getExternalExecutor(&target_info, .{ .link_libc = true }) != .native) {
if (getExternalExecutor(host, &case.target.target, .{ .link_libc = true }) != .native) {
// We wouldn't be able to run the compiled C code.
continue; // Pass test.
}
@ -1199,6 +1197,8 @@ const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const getExternalExecutor = std.zig.system.getExternalExecutor;
const Compilation = @import("../../src/Compilation.zig");
const zig_h = @import("../../src/link.zig").File.C.zig_h;
const introspect = @import("../../src/introspect.zig");
@ -1386,18 +1386,15 @@ pub fn main() !void {
}
fn resolveTargetQuery(query: std.Target.Query) std.Build.ResolvedTarget {
const result = std.zig.system.NativeTargetInfo.detect(query) catch
@panic("unable to resolve target query");
return .{
.query = query,
.target = result.target,
.dynamic_linker = result.dynamic_linker,
.target = std.zig.system.resolveTargetQuery(query) catch
@panic("unable to resolve target query"),
};
}
fn runCases(self: *Cases, zig_exe_path: []const u8) !void {
const host = try std.zig.system.NativeTargetInfo.detect(.{});
const host = try std.zig.system.resolveTargetQuery(.{});
var progress = std.Progress{};
const root_node = progress.start("compiler", self.cases.items.len);
@ -1478,7 +1475,7 @@ fn runOneCase(
zig_exe_path: []const u8,
thread_pool: *ThreadPool,
global_cache_directory: Compilation.Directory,
host: std.zig.system.NativeTargetInfo,
host: std.Target,
) !void {
const tmp_src_path = "tmp.zig";
const enable_rosetta = build_options.enable_rosetta;
@ -1488,8 +1485,7 @@ fn runOneCase(
const enable_darling = build_options.enable_darling;
const glibc_runtimes_dir: ?[]const u8 = build_options.glibc_runtimes_dir;
const target_info = try std.zig.system.NativeTargetInfo.detect(case.target);
const target = target_info.target;
const target = try std.zig.system.resolveTargetQuery(case.target);
var arena_allocator = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator.deinit();
@ -1579,7 +1575,7 @@ fn runOneCase(
.keep_source_files_loaded = true,
.is_native_os = case.target.isNativeOs(),
.is_native_abi = case.target.isNativeAbi(),
.dynamic_linker = target_info.dynamic_linker.get(),
.dynamic_linker = target.dynamic_linker.get(),
.link_libc = case.link_libc,
.use_llvm = use_llvm,
.self_exe_path = zig_exe_path,
@ -1715,7 +1711,7 @@ fn runOneCase(
.{ &tmp.sub_path, bin_name },
);
if (case.target.ofmt != null and case.target.ofmt.? == .c) {
if (host.getExternalExecutor(target_info, .{ .link_libc = true }) != .native) {
if (getExternalExecutor(host, &target, .{ .link_libc = true }) != .native) {
// We wouldn't be able to run the compiled C code.
continue :update; // Pass test.
}
@ -1734,7 +1730,7 @@ fn runOneCase(
if (zig_lib_directory.path) |p| {
try argv.appendSlice(&.{ "-I", p });
}
} else switch (host.getExternalExecutor(target_info, .{ .link_libc = case.link_libc })) {
} else switch (getExternalExecutor(host, &target, .{ .link_libc = case.link_libc })) {
.native => {
if (case.backend == .stage2 and case.target.getCpuArch().isArmOrThumb()) {
// https://github.com/ziglang/zig/issues/13623