zig/src/libs/libunwind.zig
mlugg 37a9a4e0f1
compiler: refactor Zcu.File and path representation
This commit makes some big changes to how we track state for Zig source
files. In particular, it changes:

* How `File` tracks its path on-disk
* How AstGen discovers files
* How file-level errors are tracked
* How `builtin.zig` files and modules are created

The original motivation here was to address incremental compilation bugs
with the handling of files, such as #22696. To fix this, a few changes
are necessary.

Just like declarations may become unreferenced on an incremental update,
meaning we suppress analysis errors associated with them, it is also
possible for all imports of a file to be removed on an incremental
update, in which case file-level errors for that file should be
suppressed. As such, after AstGen, the compiler must traverse files
(starting from analysis roots) and discover the set of "live files" for
this update.

Additionally, the compiler's previous handling of retryable file errors
was not very good; the source location the error was reported as was
based only on the first discovered import of that file. This source
location also disappeared on future incremental updates. So, as a part
of the file traversal above, we also need to figure out the source
locations of imports which errors should be reported against.

Another observation I made is that the "file exists in multiple modules"
error was not implemented in a particularly good way (I get to say that
because I wrote it!). It was subject to races, where the order in which
different imports of a file were discovered affects both how errors are
printed, and which module the file is arbitrarily assigned, with the
latter in turn affecting which other files are considered for import.
The thing I realised here is that while the AstGen worker pool is
running, we cannot know for sure which module(s) a file is in; we could
always discover an import later which changes the answer.

So, here's how the AstGen workers have changed. We initially ensure that
`zcu.import_table` contains the root files for all modules in this Zcu,
even if we don't know any imports for them yet. Then, the AstGen
workers do not need to be aware of modules. Instead, they simply ignore
module imports, and only spin off more workers when they see a by-path
import.

During AstGen, we can't use module-root-relative paths, since we don't
know which modules files are in; but we don't want to unnecessarily use
absolute files either, because those are non-portable and can make
`error.NameTooLong` more likely. As such, I have introduced a new
abstraction, `Compilation.Path`. This type is a way of representing a
filesystem path which has a *canonical form*. The path is represented
relative to one of a few special directories: the lib directory, the
global cache directory, or the local cache directory. As a fallback, we
use absolute (or cwd-relative on WASI) paths. This is kind of similar to
`std.Build.Cache.Path` with a pre-defined list of possible
`std.Build.Cache.Directory`, but has stricter canonicalization rules
based on path resolution to make sure deduplicating files works
properly. A `Compilation.Path` can be trivially converted to a
`std.Build.Cache.Path` from a `Compilation`, but is smaller, has a
canonical form, and has a digest which will be consistent across
different compiler processes with the same lib and cache directories
(important when we serialize incremental compilation state in the
future). `Zcu.File` and `Zcu.EmbedFile` both contain a
`Compilation.Path`, which is used to access the file on-disk;
module-relative sub paths are used quite rarely (`EmbedFile` doesn't
even have one now for simplicity).

After the AstGen workers all complete, we know that any file which might
be imported is definitely in `import_table` and up-to-date. So, we
perform a single-threaded graph traversal; similar to what
`resolveReferences` plays for `AnalUnit`s, but for files instead. We
figure out which files are alive, and which module each file is in. If a
file turns out to be in multiple modules, we set a field on `Zcu` to
indicate this error. If a file is in a different module to a prior
update, we set a flag instructing `updateZirRefs` to invalidate all
dependencies on the file. This traversal also discovers "import errors";
these are errors associated with a specific `@import`. With Zig's
current design, there is only one possible error here: "import outside
of module root". This must be identified during this traversal instead
of during AstGen, because it depends on which module the file is in. I
tried also representing "module not found" errors in this same way, but
it turns out to be much more useful to report those in Sema, because of
use cases like optional dependencies where a module import is behind a
comptime-known build option.

For simplicity, `failed_files` now just maps to `?[]u8`, since the
source location is always the whole file. In fact, this allows removing
`LazySrcLoc.Offset.entire_file` completely, slightly simplifying some
error reporting logic. File-level errors are now directly built in the
`std.zig.ErrorBundle.Wip`. If the payload is not `null`, it is the
message for a retryable error (i.e. an error loading the source file),
and will be reported with a "file imported here" note pointing to the
import site discovered during the single-threaded file traversal.

The last piece of fallout here is how `Builtin` works. Rather than
constructing "builtin" modules when creating `Package.Module`s, they are
now constructed on-the-fly by `Zcu`. The map `Zcu.builtin_modules` maps
from digests to `*Package.Module`s. These digests are abstract hashes of
the `Builtin` value; i.e. all of the options which are placed into
"builtin.zig". During the file traversal, we populate `builtin_modules`
as needed, so that when we see this imports in Sema, we just grab the
relevant entry from this map. This eliminates a bunch of awkward state
tracking during construction of the module graph. It's also now clearer
exactly what options the builtin module has, since previously it
inherited some options arbitrarily from the first-created module with
that "builtin" module!

The user-visible effects of this commit are:
* retryable file errors are now consistently reported against the whole
  file, with a note pointing to a live import of that file
* some theoretical bugs where imports are wrongly considered distinct
  (when the import path moves out of the cwd and then back in) are fixed
* some consistency issues with how file-level errors are reported are
  fixed; these errors will now always be printed in the same order
  regardless of how the AstGen pass assigns file indices
* incremental updates do not print retryable file errors differently
  between updates or depending on file structure/contents
* incremental updates support files changing modules
* incremental updates support files becoming unreferenced

Resolves: #22696
2025-05-18 17:37:02 +01:00

216 lines
8.3 KiB
Zig

const std = @import("std");
const path = std.fs.path;
const assert = std.debug.assert;
const target_util = @import("../target.zig");
const Compilation = @import("../Compilation.zig");
const Module = @import("../Package/Module.zig");
const build_options = @import("build_options");
const trace = @import("../tracy.zig").trace;
pub const BuildError = error{
OutOfMemory,
SubCompilationFailed,
ZigCompilerNotBuiltWithLLVMExtensions,
};
pub fn buildStaticLib(comp: *Compilation, prog_node: std.Progress.Node) BuildError!void {
if (!build_options.have_llvm) {
return error.ZigCompilerNotBuiltWithLLVMExtensions;
}
const tracy = trace(@src());
defer tracy.end();
var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const output_mode = .Lib;
const target = comp.root_mod.resolved_target.result;
const unwind_tables: std.builtin.UnwindTables =
if (target.cpu.arch == .x86 and target.os.tag == .windows) .none else .@"async";
const config = Compilation.Config.resolve(.{
.output_mode = .Lib,
.resolved_target = comp.root_mod.resolved_target,
.is_test = false,
.have_zcu = false,
.emit_bin = true,
.root_optimize_mode = comp.compilerRtOptMode(),
.root_strip = comp.compilerRtStrip(),
.link_libc = true,
.any_unwind_tables = unwind_tables != .none,
.lto = comp.config.lto,
}) catch |err| {
comp.setMiscFailure(
.libunwind,
"unable to build libunwind: resolving configuration failed: {s}",
.{@errorName(err)},
);
return error.SubCompilationFailed;
};
const root_mod = Module.create(arena, .{
.paths = .{
.root = .zig_lib_root,
.root_src_path = "",
},
.fully_qualified_name = "root",
.inherited = .{
.resolved_target = comp.root_mod.resolved_target,
.strip = comp.compilerRtStrip(),
.stack_check = false,
.stack_protector = 0,
.red_zone = comp.root_mod.red_zone,
.omit_frame_pointer = comp.root_mod.omit_frame_pointer,
.valgrind = false,
.sanitize_c = .off,
.sanitize_thread = false,
// necessary so that libunwind can unwind through its own stack frames
// The old 32-bit x86 variant of SEH doesn't use tables.
.unwind_tables = unwind_tables,
.pic = if (target_util.supports_fpic(target)) true else null,
.optimize_mode = comp.compilerRtOptMode(),
.code_model = comp.root_mod.code_model,
},
.global = config,
.cc_argv = &.{},
.parent = null,
}) catch |err| {
comp.setMiscFailure(
.libunwind,
"unable to build libunwind: creating module failed: {s}",
.{@errorName(err)},
);
return error.SubCompilationFailed;
};
const root_name = "unwind";
const link_mode = .static;
const basename = try std.zig.binNameAlloc(arena, .{
.root_name = root_name,
.target = target,
.output_mode = output_mode,
.link_mode = link_mode,
});
const emit_bin = Compilation.EmitLoc{
.directory = null, // Put it in the cache directory.
.basename = basename,
};
var c_source_files: [unwind_src_list.len]Compilation.CSourceFile = undefined;
for (unwind_src_list, 0..) |unwind_src, i| {
var cflags = std.ArrayList([]const u8).init(arena);
switch (Compilation.classifyFileExt(unwind_src)) {
.c => {
try cflags.appendSlice(&.{
"-std=c99",
"-fexceptions",
});
},
.cpp => {
try cflags.append("-fno-exceptions");
try cflags.append("-fno-rtti");
},
.assembly_with_cpp => {},
else => unreachable, // See `unwind_src_list`.
}
try cflags.append("-I");
try cflags.append(try comp.dirs.zig_lib.join(arena, &.{ "libunwind", "include" }));
try cflags.append("-D_LIBUNWIND_HIDE_SYMBOLS");
try cflags.append("-Wa,--noexecstack");
try cflags.append("-fvisibility=hidden");
try cflags.append("-fvisibility-inlines-hidden");
try cflags.append("-fvisibility-global-new-delete=force-hidden");
// This is intentionally always defined because the macro definition means, should it only
// build for the target specified by compiler defines. Since we pass -target the compiler
// defines will be correct.
try cflags.append("-D_LIBUNWIND_IS_NATIVE_ONLY");
if (comp.root_mod.optimize_mode == .Debug) {
try cflags.append("-D_DEBUG");
}
if (!comp.config.any_non_single_threaded) {
try cflags.append("-D_LIBUNWIND_HAS_NO_THREADS");
}
if (target.cpu.arch.isArm() and target.abi.float() == .hard) {
try cflags.append("-DCOMPILER_RT_ARMHF_TARGET");
}
try cflags.append("-Wno-bitwise-conditional-parentheses");
try cflags.append("-Wno-visibility");
try cflags.append("-Wno-incompatible-pointer-types");
if (target.os.tag == .windows) {
try cflags.append("-Wno-dll-attribute-on-redeclaration");
}
c_source_files[i] = .{
.src_path = try comp.dirs.zig_lib.join(arena, &.{unwind_src}),
.extra_flags = cflags.items,
.owner = root_mod,
};
}
const sub_compilation = Compilation.create(comp.gpa, arena, .{
.dirs = comp.dirs.withoutLocalCache(),
.self_exe_path = comp.self_exe_path,
.config = config,
.root_mod = root_mod,
.cache_mode = .whole,
.root_name = root_name,
.main_mod = null,
.thread_pool = comp.thread_pool,
.libc_installation = comp.libc_installation,
.emit_bin = emit_bin,
.function_sections = comp.function_sections,
.c_source_files = &c_source_files,
.verbose_cc = comp.verbose_cc,
.verbose_link = comp.verbose_link,
.verbose_air = comp.verbose_air,
.verbose_llvm_ir = comp.verbose_llvm_ir,
.verbose_llvm_bc = comp.verbose_llvm_bc,
.verbose_cimport = comp.verbose_cimport,
.verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
.clang_passthrough_mode = comp.clang_passthrough_mode,
.skip_linker_dependencies = true,
}) catch |err| {
comp.setMiscFailure(
.libunwind,
"unable to build libunwind: create compilation failed: {s}",
.{@errorName(err)},
);
return error.SubCompilationFailed;
};
defer sub_compilation.destroy();
comp.updateSubCompilation(sub_compilation, .libunwind, prog_node) catch |err| switch (err) {
error.SubCompilationFailed => return error.SubCompilationFailed,
else => |e| {
comp.setMiscFailure(
.libunwind,
"unable to build libunwind: compilation failed: {s}",
.{@errorName(e)},
);
return error.SubCompilationFailed;
},
};
const crt_file = try sub_compilation.toCrtFile();
comp.queueLinkTaskMode(crt_file.full_object_path, output_mode);
assert(comp.libunwind_static_lib == null);
comp.libunwind_static_lib = crt_file;
}
const unwind_src_list = [_][]const u8{
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "libunwind.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-EHABI.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-seh.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindLevel1.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindLevel1-gcc-ext.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-sjlj.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-wasm.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindRegistersRestore.S",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindRegistersSave.S",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind_AIXExtras.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "gcc_personality_v0.c",
};