zig/tools/dump-cov.zig
mlugg dcc3e6e1dd build system: replace fuzzing UI with build UI, add time report
This commit replaces the "fuzzer" UI, previously accessed with the
`--fuzz` and `--port` flags, with a more interesting web UI which allows
more interactions with the Zig build system. Most notably, it allows
accessing the data emitted by a new "time report" system, which allows
users to see which parts of Zig programs take the longest to compile.

The option to expose the web UI is `--webui`. By default, it will listen
on `[::1]` on a random port, but any IPv6 or IPv4 address can be
specified with e.g. `--webui=[::1]:8000` or `--webui=127.0.0.1:8000`.
The options `--fuzz` and `--time-report` both imply `--webui` if not
given. Currently, `--webui` is incompatible with `--watch`; specifying
both will cause `zig build` to exit with a fatal error.

When the web UI is enabled, the build runner spawns the web server as
soon as the configure phase completes. The frontend code consists of one
HTML file, one JavaScript file, two CSS files, and a few Zig source
files which are built into a WASM blob on-demand -- this is all very
similar to the old fuzzer UI. Also inherited from the fuzzer UI is that
the build system communicates with web clients over a WebSocket
connection.

When the build finishes, if `--webui` was passed (i.e. if the web server
is running), the build runner does not terminate; it continues running
to serve web requests, allowing interactive control of the build system.

In the web interface is an overall "status" indicating whether a build
is currently running, and also a list of all steps in this build. There
are visual indicators (colors and spinners) for in-progress, succeeded,
and failed steps. There is a "Rebuild" button which will cause the build
system to reset the state of every step (note that this does not affect
caching) and evaluate the step graph again.

If `--time-report` is passed to `zig build`, a new section of the
interface becomes visible, which associates every build step with a
"time report". For most steps, this is just a simple "time taken" value.
However, for `Compile` steps, the compiler communicates with the build
system to provide it with much more interesting information: time taken
for various pipeline phases, with a per-declaration and per-file
breakdown, sorted by slowest declarations/files first. This feature is
still in its early stages: the data can be a little tricky to
understand, and there is no way to, for instance, sort by different
properties, or filter to certain files. However, it has already given us
some interesting statistics, and can be useful for spotting, for
instance, particularly complex and slow compile-time logic.
Additionally, if a compilation uses LLVM, its time report includes the
"LLVM pass timing" information, which was previously accessible with the
(now removed) `-ftime-report` compiler flag.

To make time reports more useful, ZIR and compilation caches are ignored
by the Zig compiler when they are enabled -- in other words, `Compile`
steps *always* run, even if their result should be cached. This means
that the flag can be used to analyze a project's compile time without
having to repeatedly clear cache directory, for instance. However, when
using `-fincremental`, updates other than the first will only show you
the statistics for what changed on that particular update. Notably, this
gives us a fairly nice way to see exactly which declarations were
re-analyzed by an incremental update.

If `--fuzz` is passed to `zig build`, another section of the web
interface becomes visible, this time exposing the fuzzer. This is quite
similar to the fuzzer UI this commit replaces, with only a few cosmetic
tweaks. The interface is closer than before to supporting multiple fuzz
steps at a time (in line with the overall strategy for this build UI,
the goal will be for all of the fuzz steps to be accessible in the same
interface), but still doesn't actually support it. The fuzzer UI looks
quite different under the hood: as a result, various bugs are fixed,
although other bugs remain. For instance, viewing the source code of any
file other than the root of the main module is completely broken (as on
master) due to some bogus file-to-module assignment logic in the fuzzer
UI.

Implementation notes:

* The `lib/build-web/` directory holds the client side of the web UI.

* The general server logic is in `std.Build.WebServer`.

* Fuzzing-specific logic is in `std.Build.Fuzz`.

* `std.Build.abi` is the new home of `std.Build.Fuzz.abi`, since it now
  relates to the build system web UI in general.

* The build runner now has an **actual** general-purpose allocator,
  because thanks to `--watch` and `--webui`, the process can be
  arbitrarily long-lived. The gpa is `std.heap.DebugAllocator`, but the
  arena remains backed by `std.heap.page_allocator` for efficiency. I
  fixed several crashes caused by conflation of `gpa` and `arena` in the
  build runner and `std.Build`, but there may still be some I have
  missed.

* The I/O logic in `std.Build.WebServer` is pretty gnarly; there are a
  *lot* of threads involved. I anticipate this situation improving
  significantly once the `std.Io` interface (with concurrency support)
  is introduced.
2025-08-01 23:48:21 +01:00

89 lines
3.2 KiB
Zig

//! Reads a Zig coverage file and prints human-readable information to stdout,
//! including file:line:column information for each PC.
const std = @import("std");
const fatal = std.process.fatal;
const Path = std.Build.Cache.Path;
const assert = std.debug.assert;
const SeenPcsHeader = std.Build.abi.fuzz.SeenPcsHeader;
pub fn main() !void {
var general_purpose_allocator: std.heap.GeneralPurposeAllocator(.{}) = .init;
defer _ = general_purpose_allocator.deinit();
const gpa = general_purpose_allocator.allocator();
var arena_instance = std.heap.ArenaAllocator.init(gpa);
defer arena_instance.deinit();
const arena = arena_instance.allocator();
const args = try std.process.argsAlloc(arena);
const exe_file_name = args[1];
const cov_file_name = args[2];
const exe_path: Path = .{
.root_dir = std.Build.Cache.Directory.cwd(),
.sub_path = exe_file_name,
};
const cov_path: Path = .{
.root_dir = std.Build.Cache.Directory.cwd(),
.sub_path = cov_file_name,
};
var coverage = std.debug.Coverage.init;
defer coverage.deinit(gpa);
var debug_info = std.debug.Info.load(gpa, exe_path, &coverage) catch |err| {
fatal("failed to load debug info for {f}: {s}", .{ exe_path, @errorName(err) });
};
defer debug_info.deinit(gpa);
const cov_bytes = cov_path.root_dir.handle.readFileAllocOptions(
arena,
cov_path.sub_path,
1 << 30,
null,
.of(SeenPcsHeader),
null,
) catch |err| {
fatal("failed to load coverage file {f}: {s}", .{ cov_path, @errorName(err) });
};
var stdout_buffer: [4000]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writerStreaming(&stdout_buffer);
const stdout = &stdout_writer.interface;
const header: *SeenPcsHeader = @ptrCast(cov_bytes);
try stdout.print("{any}\n", .{header.*});
const pcs = header.pcAddrs();
var indexed_pcs: std.AutoArrayHashMapUnmanaged(usize, void) = .empty;
try indexed_pcs.entries.resize(arena, pcs.len);
@memcpy(indexed_pcs.entries.items(.key), pcs);
try indexed_pcs.reIndex(arena);
const sorted_pcs = try arena.dupe(usize, pcs);
std.mem.sortUnstable(usize, sorted_pcs, {}, std.sort.asc(usize));
const source_locations = try arena.alloc(std.debug.Coverage.SourceLocation, sorted_pcs.len);
try debug_info.resolveAddresses(gpa, sorted_pcs, source_locations);
const seen_pcs = header.seenBits();
for (sorted_pcs, source_locations) |pc, sl| {
if (sl.file == .invalid) {
try stdout.print(" {x}: invalid\n", .{pc});
continue;
}
const file = debug_info.coverage.fileAt(sl.file);
const dir_name = debug_info.coverage.directories.keys()[file.directory_index];
const dir_name_slice = debug_info.coverage.stringAt(dir_name);
const seen_i = indexed_pcs.getIndex(pc).?;
const hit: u1 = @truncate(seen_pcs[seen_i / @bitSizeOf(usize)] >> @intCast(seen_i % @bitSizeOf(usize)));
try stdout.print("{c}{x}: {s}/{s}:{d}:{d}\n", .{
"-+"[hit], pc, dir_name_slice, debug_info.coverage.stringAt(file.basename), sl.line, sl.column,
});
}
try stdout.flush();
}