Commit Graph

79 Commits

Author SHA1 Message Date
e4m2
8d56e472c9 Replace std.rand references with std.Random 2024-02-08 15:21:35 +01:00
Andrew Kelley
a17505c711 zig build: avoid using stdout for communication with runner
Pass the required lazy dependencies from the build runner to the parent
process via a tmp file instead of stdout. I'll reproduce this comment to
explain it:

The `zig build` parent process needs a way to obtain results from the
configuration phase of the child process. In the future, the make phase
will be executed in a separate process than the configure phase, and we
can then use stdout from the configuration phase for this purpose.

However, currently, both phases are in the same process, and Run Step
provides API for making the runned subprocesses inherit stdout and stderr
which means these streams are not available for passing metadata back
to the parent.

Until make and configure phases are separated into different processes,
the strategy is to choose a temporary file name ahead of time, and then
read this file in the parent to obtain the results, in the case the child
exits with code 3.

This commit also extracts some common logic from the loop that rebuilds
the build runner so that it does not run again when the build runner is
rebuilt.
2024-02-02 20:43:01 -07:00
Andrew Kelley
252f4ab2a5 build system: implement lazy dependencies, part 1
Build manifest files support `lazy: true` for dependency sections.
This causes the auto-generated dependencies.zig to have 2 more
possibilities:
1. It communicates whether a dependency is lazy or not.
2. The dependency might be acknowledged, but missing due to being lazy
   and not fetched.

Lazy dependencies are not fetched by default, but if they are already
fetched then they are provided to the build script.

The build runner reports the set of missing lazy dependenices that are
required to the parent process via stdout and indicates the situation
with exit code 3.

std.Build now has a `lazyDependency` function. I'll let the doc comments
speak for themselves:

When this function is called, it means that the current build does, in
fact, require this dependency. If the dependency is already fetched, it
proceeds in the same manner as `dependency`. However if the dependency
was not fetched, then when the build script is finished running, the
build will not proceed to the make phase. Instead, the parent process
will additionally fetch all the lazy dependencies that were actually
required by running the build script, rebuild the build script, and then
run it again.
In other words, if this function returns `null` it means that the only
purpose of completing the configure phase is to find out all the other
lazy dependencies that are also required.
It is allowed to use this function for non-lazy dependencies, in which
case it will never return `null`. This allows toggling laziness via
build.zig.zon without changing build.zig logic.

The CLI for `zig build` detects this situation, but the logic for then
redoing the build process with these extra dependencies fetched is not
yet implemented.
2024-02-02 20:43:01 -07:00
Andrew Kelley
ed4ccea7ba build system: implement --system [dir]
This prevents package fetching and enables system_package_mode in the
build system which flips the defaults for system integrations.
2024-02-02 20:43:01 -07:00
Andrew Kelley
22537873f4 build system: implement --release[=mode]
This allows a `zig build` command to specify intention to create a
release build, regardless of what per-project options exist. It also
allows the command to specify a "preferred optimization mode", which is
chosen if the project itself does not choose one (in other words, the
project gets first choice). If neither the build command nor the project
specify a preferred release mode, an error occurs.
2024-02-02 20:43:01 -07:00
Andrew Kelley
2637b57376 std.Build: make system library integrations more general
Before it was named "library" inconsistently.

Now the CLI args are -fsys=[name] and -fno-sys=[name] and it is a more
general-purpose "system integration" which could be a library name or
perhaps a project name such as "ffmpeg" or a binary such as "nasm".
2024-02-02 20:43:01 -07:00
Andrew Kelley
370438943e std.Build: revert moving some fields to Graph
On second thought, let's keep a bunch of these flags how they already
were.

Partial revert of the previous commit.
2024-02-02 20:43:01 -07:00
Andrew Kelley
105db13536 std.Build: implement --host-target, --host-cpu, --host-dynamic-linker
This also makes a long-overdue change of extracting common state from
Build into a shared Graph object.

Getting the semantics right for these flags turned out to be quite
tricky. In the end it works like this:
* The override only happens when the target is fully native, with no
  additional query parameters, such as versions or CPU features added.
* The override affects the resolved Target but leaves the original Query
  unmodified.
* The "is native?" detection logic operates on the original, unmodified
  query. This makes it possible to provide invalid host target
  information, causing confusing errors to occur. Don't do that.

There are some minor breaking changes to std.Build API such as the fact
that `b.zig_exe` is now moved to `b.graph.zig_exe`, as well as a handful
of other similar flags.
2024-02-02 20:43:01 -07:00
Andrew Kelley
8f867eaf84 build system: introduce system library integration
* New --help section
* Add b.systemLibraryOption
* Rework the build runner CLI logic a bit
2024-02-02 20:43:01 -07:00
Tristan Ross
c0e0bb385c std.process: return u64 in totalSystemMemory 2024-01-23 00:17:53 -08:00
Andrew Kelley
45ec851733 zig build: handle stderr more elegantly
* Specifically recognize stderr as a different concept than an error
  message in Step results.
* Display it differently when only stderr occurs but the build proceeds
  successfully.

closes #18473
2024-01-10 17:11:26 -08:00
Andrew Kelley
190f6038bf zig build: reintroduce --prominent-compile-errors
This reintroduced flag makes zig build behave the same as the previous
commit. Without this flag, the default behavior is now changed to
display compilation errors inline with the rest of error messages and
the build tree context.

This behavior is essential for making sense of error logs from projects
that have two or more steps emitting compilation errors which is why it
is now the default.
2024-01-01 19:49:07 -07:00
Andrew Kelley
b92e30ff0b std.Build.ResolvedTarget: rename target field to result
This change is seemingly insignificant but I actually agonized over this
for three days. Some other things I considered:

* (status quo in master branch) make Compile step creation functions
  accept a Target.Query and delete the ResolvedTarget struct.
  - downside: redundantly resolve target queries many times
* same as before but additionally add a hash map to cache target query
  resolutions.
  - downside: now there is a hash map that doesn't actually need to
    exist, just to make the API more ergonomic.
* add is_native_os and is_native_abi fields to std.Target and use it
  directly as the result of resolving a target query.
  - downside: they really don't belong there. They would be available
    as comptime booleans via `@import("builtin")` but they should not
    be exposed that way.

With this change the downsides are:
* the option name of addExecutable and friends is `target` instead of
  `resolved_target` matching the type name.
  - upside: this does not break compatibility with existing build
    scripts
* you likely end up seeing `target.result.cpu.arch` rather than
  `target.cpu.arch`.
  - upside: this is an improvement over `target.target.cpu.arch` which
    it was before this commit.
  - downside: `b.host.target` is now `b.host.result`.
2024-01-01 17:51:18 -07:00
Andrew Kelley
dbdb87502d std.Target: add DynamicLinker 2024-01-01 17:51:18 -07:00
Andrew Kelley
0ee8fbb15d build runner: print subtree of failed nodes context
Previously when an error message is printed, it is sometimes not
possible to know which build step it corresponds to. With the subtree
printed in this commit, the context is always clear.
2024-01-01 17:51:18 -07:00
Andrew Kelley
142471fcc4 zig build system: change target, compilation, and module APIs
Introduce the concept of "target query" and "resolved target". A target
query is what the user specifies, with some things left to default. A
resolved target has the default things discovered and populated.
In the future, std.zig.CrossTarget will be rename to std.Target.Query.
Introduces `std.Build.resolveTargetQuery` to get from one to the other.

The concept of `main_mod_path` is gone, no longer supported. You have to
put the root source file at the module root now.

* remove deprecated API
* update build.zig for the breaking API changes in this branch
* move std.Build.Step.Compile.BuildId to std.zig.BuildId
* add more options to std.Build.ExecutableOptions, std.Build.ObjectOptions,
  std.Build.SharedLibraryOptions, std.Build.StaticLibraryOptions, and
  std.Build.TestOptions.
* remove `std.Build.constructCMacro`. There is no use for this API.
* deprecate `std.Build.Step.Compile.defineCMacro`. Instead,
  `std.Build.Module.addCMacro` is provided.
  - remove `std.Build.Step.Compile.defineCMacroRaw`.
* deprecate `std.Build.Step.Compile.linkFrameworkNeeded`
  - use `std.Build.Module.linkFramework`
* deprecate `std.Build.Step.Compile.linkFrameworkWeak`
  - use `std.Build.Module.linkFramework`
* move more logic into `std.Build.Module`
* allow `target` and `optimize` to be `null` when creating a Module.
  Along with other fields, those unspecified options will be inherited
  from parent `Module` when inserted into an import table.
* the `target` field of `addExecutable` is now required. pass `b.host`
  to get the host target.
2024-01-01 17:51:18 -07:00
mlugg
51595d6b75
lib: correct unnecessary uses of 'var' 2023-11-19 09:55:07 +00:00
Andrew Kelley
dff13e088b build runner: fix missing newline in error message 2023-11-03 20:05:32 -07:00
Andrew Kelley
10200970bb build system: fixups to --seed mechanism
* support 0x prefixed hex code for CLI seed arguments
* don't change the build summary; the printed CLI on build runner
  failure is sufficient
* use `std.crypto.random` instead of system time for entropy
2023-10-19 14:24:35 -04:00
Sahnvour
b87353a17f std.Build: add --seed argument to randomize step dependencies spawning
help detect possibly hidden dependencies on the running order of steps,
especially in -j1 mode
2023-10-19 14:24:35 -04:00
Andrew Kelley
a605bd9887 zig build: add --fetch argument
closes #14280
2023-10-08 16:54:31 -07:00
kcbanner
53d1282f0c build: add --skip-oom-steps
Specifying this argument causes steps that specify a max_rss that exceeds the
total max_rss value of the runner to be skipped, instead of failing.
2023-09-22 15:08:51 -07:00
mlugg
94529ffb62 package manager: write deps in a flat format, eliminating the FQN concept
The new `@depedencies` module contains generated code like the
following (where strings like "abc123" represent hashes):

```zig
pub const root_deps = [_]struct { []const u8, []const u8 }{
    .{ "foo", "abc123" },
};

pub const packages = struct {
    pub const abc123 = struct {
        pub const build_root = "/home/mlugg/.cache/zig/blah/abc123";
        pub const build_zig = @import("abc123");
        pub const deps = [_]struct { []const u8, []const u8 }{
            .{ "bar", "abc123" },
            .{ "name", "ghi789" },
        };
    };
};
```

Each package contains a build root string, the build.zig import, and a
mapping from dependency names to package hashes. There is also such a
mapping for the root package dependencies.

In theory, we could now remove the `dep_prefix` field from `std.Build`,
since its main purpose is now handled differently. I believe this is a
desirable goal, as it doesn't really make sense to assign a single FQN
to any package (because it may appear in many different places in the
package hierarchy). This commit does not remove that field, as it's used
non-trivially in a few places in the build runner and compiler tests:
this will be a future enhancement.

Resolves: #16354
Resolves: #17135
2023-09-15 14:04:23 -07:00
Andrew Kelley
38840e2e58 build system: follow-up enhancements regarding LazyPath
* introduce LazyPath.cwd_relative variant and use it for --zig-lib-dir. closes #12685
* move overrideZigLibDir and setMainPkgPath to options fields set once
  and then never mutated.
* avoid introducing Build/util.zig
* use doc comments for deprecation notices so that they show up in
  generated documentation.
* introduce InstallArtifact.Options, accept it as a parameter to
  addInstallArtifact, and move override_dest_dir into it. Instead of
  configuring the installation via Compile step, configure the
  installation via the InstallArtifact step. In retrospect this is
  obvious.
* remove calls to pushInstalledFile in InstallArtifact. See #14943
* rewrite InstallArtifact to not incorrectly observe whether a Compile
  step has any generated outputs. InstallArtifact is meant to trigger
  output generation.
* fix child process evaluation code handling of `-fno-emit-bin`.
* don't store out_h_filename, out_ll_filename, etc., pointlessly. these
  are all just simple extensions appended to the root name.
* make emit_directory optional. It's possible to have nothing outputted,
  for example, if you're just type-checking.
* avoid passing -femit-foo/-fno-emit-foo when it is the default
* rename ConfigHeader.getTemplate to getOutput
* deprecate addOptionArtifact
* update the random number seed of Options step caching.
* avoid using `inline for` pointlessly
* avoid using `override_Dest_dir` pointlessly
* avoid emitting an executable pointlessly in test cases

Removes forceBuild and forceEmit. Let's consider these additions separately.
Nearly all of the usage sites were suspicious.
2023-07-30 11:19:32 -07:00
dweiller
e45d24c0de rename ZIG_DEBUG_COLOR env variable to YES_COLOR 2023-06-22 10:29:45 +10:00
Veikka Tuominen
0f5aff3441 zig build: add option to only print failed steps
The motivating case for this is that currently when a test fails
the CI log will include ~5k lines of listing steps that succeeded.
2023-06-16 15:17:59 -07:00
Linus Groh
0f6fa3f20b std: Move std.debug.{TTY.Config,detectTTYConfig} to std.io.tty
Also get rid of the TTY wrapper struct, which was exlusively used as a
namespace - this is done by the tty.zig root struct now.

detectTTYConfig has been renamed to just detectConfig, which is enough
given the new namespace. Additionally, a doc comment had been added.
2023-05-24 10:15:02 +01:00
Linus Groh
39c2eee285 std.debug: Rename TTY.Color enum values to snake case 2023-05-24 10:15:02 +01:00
Evin Yulo
6d7bb255a4 Add std.fmt.parseIntSizeSuffix and use for --maxrss
Fixes #14955
2023-05-10 16:31:51 +03:00
square
887abd0f33 delete --prominent-compile-errors from help 2023-03-18 20:13:52 +02:00
Motiejus Jakštys
c31007bb47 fix copy-paste errors
--sysroot was copy-pasted instead of --maxrss from above. Also, make it less likely in other places for this to be repeated.

I found this by accident when reviewing f51413d2cf
2023-03-17 19:42:46 -04:00
Motiejus Jakštys
9f2aa3fbee Build.zig_exe: make it sentinel-aware
This is useful for tests that want to `execve` zig directly. The string
is already null-terminated, so this will just expose it as such,
removing an extra allocation from the test.

Will be used in #14462
2023-03-17 15:54:09 -04:00
Jacob Young
cfcd6698cd main: add debug option to dump unoptimized llvm ir 2023-03-17 01:57:14 -04:00
Andrew Kelley
63bd0fe58e use DEC graphics instead of Unicode for box drawing 2023-03-15 10:48:15 -07:00
Andrew Kelley
b1299d5153 build runner: tweak progress bar display 2023-03-15 10:48:15 -07:00
Andrew Kelley
ede5dcffea make the build runner and test runner talk to each other
std.Build.addTest creates a CompileStep as before, however, this kind of
step no longer actually runs the unit tests. Instead it only compiles
it, and one must additionally create a RunStep from the CompileStep in
order to actually run the tests.

RunStep gains integration with the default test runner, which now
supports the standard --listen=- argument in order to communicate over
stdin and stdout. It also reports test statistics; how many passed,
failed, and leaked, as well as directly associating the relevant stderr
with the particular test name that failed.

This separation of CompileStep and RunStep means that
`CompileStep.Kind.test_exe` is no longer needed, and therefore has been
removed in this commit.

 * build runner: show unit test statistics in build summary
 * added Step.writeManifest since many steps want to treat it as a
   warning and emit the same message if it fails.
 * RunStep: fixed error message that prints the failed command printing
   the original argv and not the adjusted argv in case an interpreter
   was used.
 * RunStep: fixed not passing the command line arguments to the
   interpreter.
 * move src/Server.zig to std.zig.Server so that the default test runner
   can use it.
 * the simpler test runner function which is used by work-in-progress
   backends now no longer prints to stderr, which is necessary in order
   for the build runner to not print the stderr as a warning message.
2023-03-15 10:48:14 -07:00
Andrew Kelley
ba77959137 Revert "build runner: print to stderr in dumb terminals"
This reverts commit e6f759e1c64668c50d3ff2d02c64a66c871da0ac.

I changed my mind. I don't like the output because it makes it harder to
find the actual errors in CI logs.
2023-03-15 10:48:14 -07:00
Andrew Kelley
7d5bce56e1 build runner: print to stderr in dumb terminals
Terminal progress is suppressed and instead there is an explicit
handling of printing to stderr, one line per step make() function call.
The output looks very similar to Ninja.

A future commit should add a -q to quiet the output.
2023-03-15 10:48:14 -07:00
Andrew Kelley
bf73620cbd build runner: communicate TTY conf to child procs via env vars 2023-03-15 10:48:14 -07:00
Andrew Kelley
7cc4a6965c build runner enhancements in preparation for test-cases
* std.zig.ErrorBundle: support rendering options for whether to include
   the reference trace, whether to include the source line, and TTY
   configuration.

 * build runner: don't print progress in dumb terminals

 * std.Build.CompileStep:
   - add a way to expect compilation errors via the new `expect_errors`
     field. This is an advanced setting that can change the intent of
     the CompileStep. If this slice has nonzero length, it means that
     the CompileStep exists to check for compile errors and return
     *success* if they match, and failure otherwise.
   - remove the object format parameter from `checkObject`. The object
     format is known based on the CompileStep's target.
   - Avoid passing -L and -I flags for nonexistent directories within
     search_prefixes. This prevents a warning, that should probably be
     upgraded to an error in Zig's CLI parsing code, when the linker
     sees an -L directory that does not exist.

 * std.Build.Step:
   - When spawning the zig compiler process, takes advantage of the new
     `std.Progress.Node.setName` API to avoid ticking up a meaningless
     number at every progress update.
2023-03-15 10:48:14 -07:00
Andrew Kelley
e897637d8d re-enable compare-output test cases 2023-03-15 10:48:13 -07:00
Andrew Kelley
f51413d2cf zig build: add an OOM-prevention system
The problem is that one may execute too many subprocesses concurrently
that, together, exceed an RSS value that causes the OOM killer to kill
something problematic such as the window manager. Or worse, nothing, and
the system freezes.

This is a real world problem. For example when building LLVM a simple
`ninja install` will bring your system to its knees if you don't know
that you should add `-DLLVM_PARALLEL_LINK_JOBS=1`.

In particular: compiling the zig std lib tests takes about 2G each,
which at 16x at once (8 cores + hyperthreading) is using all 32GB of my
RAM, causing the OOM killer to kill my window manager

The idea here is that you can annotate steps that might use a high
amount of system resources with an upper bound. So for example I could
mark the std lib tests as having an upper bound peak RSS of 3 GiB.

Then the build system will do 2 things:

1. ulimit the child process, so that it will fail if it would exceed
   that memory limit.
2. Notice how much system RAM is available and avoid running too many
   concurrent jobs at once that would total more than that.

This implements (1) not with an operating system enforced limit, but by
checking the maxrss after a child process exits.

However it does implement (2) correctly.

The available memory used by the build system defaults to the total
system memory, regardless of whether it is used by other processes at
the time of spawning the build runner. This value can be overridden with
the new --maxrss flag to `zig build`. This mechanism will ensure that
the sum total of upper bound RSS memory of concurrent tasks will not
exceed this value.

This system makes it so that project maintainers can annotate
problematic subprocesses, avoiding bug reports from users, who can
blissfully execute `zig build` without worrying about the project's
internals.

Nobody's computer crashes, and the build system uses as much parallelism
as possible without risking OOM. Users do not need to unnecessarily
resort to -j1 when the build system can figure this out for them.
2023-03-15 10:48:13 -07:00
Andrew Kelley
6377aad23a build runner: fix typo in max rss display 2023-03-15 10:48:13 -07:00
Andrew Kelley
1e63573d35 std.build.CompileStep: eliminate std.log usage 2023-03-15 10:48:13 -07:00
Andrew Kelley
80d1976db9 build runner: add microseconds to elapsed in build summary 2023-03-15 10:48:13 -07:00
Andrew Kelley
d695f36e70 build runner supports reporting cached status and duration 2023-03-15 10:48:13 -07:00
Andrew Kelley
dcec4d55e3 eliminate stderr usage in std.Build make() functions
* Eliminate all uses of `std.debug.print` in make() functions, instead
  properly using the step failure reporting mechanism.
* Introduce the concept of skipped build steps. These do not cause the
  build to fail, and they do allow their dependants to run.
* RunStep gains a new flag, `skip_foreign_checks` which causes the
  RunStep to be skipped if stdio mode is `check` and the binary cannot
  be executed due to it being a foreign executable.
  - RunStep is improved to automatically use known interpreters to
    execute binaries if possible (integrating with flags such as
    -fqemu and -fwasmtime). It only does this after attempting a native
    execution and receiving a "exec file format" error.
  - Update RunStep to use an ArrayList for the checks rather than this
    ad-hoc reallocation/copying mechanism.
  - `expectStdOutEqual` now also implicitly adds an exit_code==0 check
    if there is not already an expected termination. This matches
    previously expected behavior from older API and can be overridden by
    directly setting the checks array.
* Add `dest_sub_path` to `InstallArtifactStep` which allows choosing an
  arbitrary subdirectory relative to the prefix, as well as overriding
  the basename.
  - Delete the custom InstallWithRename step that I found deep in the
    test/ directory.
* WriteFileStep will now update its step display name after the first
  file is added.
* Add missing stdout checks to various standalone test case build
  scripts.
2023-03-15 10:48:13 -07:00
Andrew Kelley
58edefc6d1 zig build: many enhancements related to parallel building
Rework std.Build.Step to have an `owner: *Build` field. This
simplified the implementation of installation steps, as well as provided
some much-needed common API for the new parallelized build system.

--verbose is now defined very concretely: it prints to stderr just
before spawning a child process.

Child process execution is updated to conform to the new
parallel-friendly make() function semantics.

DRY up the failWithCacheError handling code. It now integrates properly
with the step graph instead of incorrectly dumping to stderr and calling
process exit.

In the main CLI, fix `zig fmt` crash when there are no errors and stdin
is used.

Deleted steps:
 * EmulatableRunStep - this entire thing can be removed in favor of a
   flag added to std.Build.RunStep called `skip_foreign_checks`.
 * LogStep - this doesn't really fit with a multi-threaded build runner
   and is effectively superseded by the new build summary output.

build runner:
 * add -fsummary and -fno-summary to override the default behavior,
   which is to print a summary if any of the build steps fail.
 * print the dep prefix when emitting error messages for steps.

std.Build.FmtStep:
 * This step now supports exclude paths as well as a check flag.
 * The check flag decides between two modes, modify mode, and check
   mode. These can be used to update source files in place, or to fail
   the build, respectively.

Zig's own build.zig:
 * The `test-fmt` step will do all the `zig fmt` checking that we expect
   to be done. Since the `test` step depends on this one, we can simply
   remove the explicit call to `zig fmt` in the CI.
 * The new `fmt` step will actually perform `zig fmt` and update source
   files in place.

std.Build.RunStep:
 * expose max_stdio_size is a field (previously an unchangeable
   hard-coded value).
 * rework the API. Instead of configuring each stream independently,
   there is a `stdio` field where you can choose between
   `infer_from_args`, `inherit`, or `check`. These determine whether the
   RunStep is considered to have side-effects or not. The previous
   field, `condition` is gone.
 * when stdio mode is set to `check` there is a slice of any number of
   checks to make, which include things like exit code, stderr matching,
   or stdout matching.
 * remove the ill-defined `print` field.
 * when adding an output arg, it takes the opportunity to give itself a
   better name.
 * The flag `skip_foreign_checks` is added. If this is true, a RunStep
   which is configured to check the output of the executed binary will
   not fail the build if the binary cannot be executed due to being for
   a foreign binary to the host system which is running the build graph.
   Command-line arguments such as -fqemu and -fwasmtime may affect
   whether a binary is detected as foreign, as well as system
   configuration such as Rosetta (macOS) and binfmt_misc (Linux).
   - This makes EmulatableRunStep no longer needed.
 * Fix the child process handling to properly integrate with the new
   bulid API and to avoid deadlocks in stdout/stderr streams by polling
   if necessary.

std.Build.RemoveDirStep now uses the open build_root directory handle
instead of an absolute path.
2023-03-15 10:48:13 -07:00
Andrew Kelley
b465dc1234 build runner: slight rewording in build summary 2023-03-15 10:48:13 -07:00
Andrew Kelley
533c7b56f2 build runner: hide repeated steps in the build summary 2023-03-15 10:48:13 -07:00