1# The Standard Environment {#chap-stdenv}
2
3The standard build environment in the Nix Packages collection provides an environment for building Unix packages that does a lot of common build tasks automatically. In fact, for Unix packages that use the standard `./configure; make; make install` build interface, you don’t need to write a build script at all; the standard environment does everything automatically. If `stdenv` doesn’t do what you need automatically, you can easily customise or override the various build phases.
4
5## Using `stdenv` {#sec-using-stdenv}
6
7To build a package with the standard environment, you use the function `stdenv.mkDerivation`, instead of the primitive built-in function `derivation`, e.g.
8
9```nix
10stdenv.mkDerivation {
11 name = "libfoo-1.2.3";
12 src = fetchurl {
13 url = "http://example.org/libfoo-1.2.3.tar.bz2";
14 hash = "sha256-tWxU/LANbQE32my+9AXyt3nCT7NBVfJ45CX757EMT3Q=";
15 };
16}
17```
18
19(`stdenv` needs to be in scope, so if you write this in a separate Nix expression from `pkgs/all-packages.nix`, you need to pass it as a function argument.) Specifying a `name` and a `src` is the absolute minimum Nix requires. For convenience, you can also use `pname` and `version` attributes and `mkDerivation` will automatically set `name` to `"${pname}-${version}"` by default.
20**Since [RFC 0035](https://github.com/NixOS/rfcs/pull/35), this is preferred for packages in Nixpkgs**, as it allows us to reuse the version easily:
21
22```nix
23stdenv.mkDerivation (finalAttrs: {
24 pname = "libfoo";
25 version = "1.2.3";
26 src = fetchurl {
27 url = "http://example.org/libfoo-source-${finalAttrs.version}.tar.bz2";
28 hash = "sha256-tWxU/LANbQE32my+9AXyt3nCT7NBVfJ45CX757EMT3Q=";
29 };
30})
31```
32
33Many packages have dependencies that are not provided in the standard environment. It’s usually sufficient to specify those dependencies in the `buildInputs` attribute:
34
35```nix
36stdenv.mkDerivation {
37 pname = "libfoo";
38 version = "1.2.3";
39 # ...
40 buildInputs = [
41 libbar
42 perl
43 ncurses
44 ];
45}
46```
47
48This attribute ensures that the `bin` subdirectories of these packages appear in the `PATH` environment variable during the build, that their `include` subdirectories are searched by the C compiler, and so on. (See [](#ssec-setup-hooks) for details.)
49
50Often it is necessary to override or modify some aspect of the build. To make this easier, the standard environment breaks the package build into a number of *phases*, all of which can be overridden or modified individually: unpacking the sources, applying patches, configuring, building, and installing. (There are some others; see [](#sec-stdenv-phases).) For instance, a package that doesn’t supply a makefile but instead has to be compiled "manually" could be handled like this:
51
52```nix
53stdenv.mkDerivation {
54 pname = "fnord";
55 version = "4.5";
56
57 # ...
58
59 buildPhase = ''
60 runHook preBuild
61
62 gcc foo.c -o foo
63
64 runHook postBuild
65 '';
66
67 installPhase = ''
68 runHook preInstall
69
70 mkdir -p $out/bin
71 cp foo $out/bin
72
73 runHook postInstall
74 '';
75}
76```
77
78(Note the use of `''`-style string literals, which are very convenient for large multi-line script fragments because they don’t need escaping of `"` and `\`, and because indentation is intelligently removed.)
79
80There are many other attributes to customise the build. These are listed in [](#ssec-stdenv-attributes).
81
82While the standard environment provides a generic builder, you can still supply your own build script:
83
84```nix
85stdenv.mkDerivation {
86 pname = "libfoo";
87 version = "1.2.3";
88 # ...
89 builder = ./builder.sh;
90}
91```
92
93where `stdenv` sets up the environment automatically (e.g. by resetting `PATH` and populating it from build inputs). If you want, you can use `stdenv`’s generic builder:
94
95```bash
96buildPhase() {
97 echo "... this is my custom build phase ..."
98 gcc foo.c -o foo
99}
100
101installPhase() {
102 mkdir -p $out/bin
103 cp foo $out/bin
104}
105
106genericBuild
107```
108
109### Building a `stdenv` package in `nix-shell` {#sec-building-stdenv-package-in-nix-shell}
110
111To build a `stdenv` package in a [`nix-shell`](https://nixos.org/manual/nix/unstable/command-ref/nix-shell.html), enter a shell, find the [phases](#sec-stdenv-phases) you wish to build, then invoke `genericBuild` manually:
112
113Go to an empty directory, invoke `nix-shell` with the desired package, and from inside the shell, set the output variables to a writable directory:
114
115```bash
116cd "$(mktemp -d)"
117nix-shell '<nixpkgs>' -A some_package
118export out=$(pwd)/out
119```
120
121Next, invoke the desired parts of the build.
122First, run the phases that generate a working copy of the sources, which will change directory to the sources for you:
123
124```bash
125phases="${prePhases[*]:-} unpackPhase patchPhase" genericBuild
126```
127
128Then, run more phases up until the failure is reached.
129If the failure is in the build or check phase, the following phases would be required:
130
131```bash
132phases="${preConfigurePhases[*]:-} configurePhase ${preBuildPhases[*]:-} buildPhase checkPhase" genericBuild
133```
134
135Use this command to run all install phases:
136```bash
137phases="${preInstallPhases[*]:-} installPhase ${preFixupPhases[*]:-} fixupPhase installCheckPhase" genericBuild
138```
139
140Single phase can be re-run as many times as necessary to examine the failure like so:
141
142```bash
143phases="buildPhase" genericBuild
144```
145
146To modify a [phase](#sec-stdenv-phases), first print it with
147
148```bash
149echo "$buildPhase"
150```
151
152Or, if that is empty, for instance, if it is using a function:
153
154```bash
155type buildPhase
156```
157
158then change it in a text editor, and paste it back to the terminal.
159
160::: {.note}
161This method may have some inconsistencies in environment variables and behaviour compared to a normal build within the [Nix build sandbox](https://nixos.org/manual/nix/unstable/language/derivations#builder-execution).
162The following is a non-exhaustive list of such differences:
163
164- `TMP`, `TMPDIR`, and similar variables likely point to non-empty directories that the build might conflict with files in.
165- Output store paths are not writable, so the variables for outputs need to be overridden to writable paths.
166- Other environment variables may be inconsistent with a `nix-build` either due to `nix-shell`'s initialization script or due to the use of `nix-shell` without the `--pure` option.
167
168If the build fails differently inside the shell than in the sandbox, consider using [`breakpointHook`](#breakpointhook) and invoking `nix-build` instead.
169The [`--keep-failed`](https://nixos.org/manual/nix/unstable/command-ref/conf-file#conf-keep-failed) option for `nix-build` may also be useful to examine the build directory of a failed build.
170:::
171
172## Tools provided by `stdenv` {#sec-tools-of-stdenv}
173
174The standard environment provides the following packages:
175
176- The GNU C Compiler, configured with C and C++ support.
177- GNU coreutils (contains a few dozen standard Unix commands).
178- GNU findutils (contains `find`).
179- GNU diffutils (contains `diff`, `cmp`).
180- GNU `sed`.
181- GNU `grep`.
182- GNU `awk`.
183- GNU `tar`.
184- `gzip`, `bzip2` and `xz`.
185- GNU Make.
186- Bash. This is the shell used for all builders in the Nix Packages collection. Not using `/bin/sh` removes a large source of portability problems.
187- The `patch` command.
188
189On Linux, `stdenv` also includes the `patchelf` utility.
190
191## Specifying dependencies {#ssec-stdenv-dependencies}
192
193Build systems often require more dependencies than just what `stdenv` provides. This section describes attributes accepted by `stdenv.mkDerivation` that can be used to make these dependencies available to the build system.
194
195### Overview {#ssec-stdenv-dependencies-overview}
196
197A full reference of the different kinds of dependencies is provided in [](#ssec-stdenv-dependencies-reference), but here is an overview of the most common ones.
198It should cover most use cases.
199
200Add dependencies to `nativeBuildInputs` if they are executed during the build:
201- those which are needed on `$PATH` during the build, for example `cmake` and `pkg-config`
202- [setup hooks](#ssec-setup-hooks), for example [`makeWrapper`](#fun-makeWrapper)
203- interpreters needed by [`patchShebangs`](#patch-shebangs.sh) for build scripts (with the `--build` flag), which can be the case for e.g. `perl`
204
205Add dependencies to `buildInputs` if they will end up copied or linked into the final output or otherwise used at runtime:
206- libraries used by compilers, for example `zlib`,
207- interpreters needed by [`patchShebangs`](#patch-shebangs.sh) for scripts which are installed, which can be the case for e.g. `perl`
208
209::: {.note}
210These criteria are independent.
211
212For example, software using Wayland usually needs the `wayland` library at runtime, so `wayland` should be added to `buildInputs`.
213But it also executes the `wayland-scanner` program as part of the build to generate code, so `wayland` should also be added to `nativeBuildInputs`.
214:::
215
216Dependencies needed only to run tests are similarly classified between native (executed during build) and non-native (executed at runtime):
217- `nativeCheckInputs` for test tools needed on `$PATH` (such as `ctest`) and [setup hooks](#ssec-setup-hooks) (for example [`pytestCheckHook`](#python))
218- `checkInputs` for libraries linked into test executables (for example the `qcheck` OCaml package)
219
220These dependencies are only injected when [`doCheck`](#var-stdenv-doCheck) is set to `true`.
221
222#### Example {#ssec-stdenv-dependencies-overview-example}
223
224Consider for example this simplified derivation for `solo5`, a sandboxing tool:
225```nix
226stdenv.mkDerivation (finalAttrs: {
227 pname = "solo5";
228 version = "0.7.5";
229
230 src = fetchurl {
231 url = "https://github.com/Solo5/solo5/releases/download/v${finalAttrs.version}/solo5-v${finalAttrs.version}.tar.gz";
232 hash = "sha256-viwrS9lnaU8sTGuzK/+L/PlMM/xRRtgVuK5pixVeDEw=";
233 };
234
235 nativeBuildInputs = [
236 makeWrapper
237 pkg-config
238 ];
239
240 buildInputs = [ libseccomp ];
241
242 postInstall = ''
243 substituteInPlace $out/bin/solo5-virtio-mkimage \
244 --replace-fail "/usr/lib/syslinux" "${syslinux}/share/syslinux" \
245 --replace-fail "/usr/share/syslinux" "${syslinux}/share/syslinux" \
246 --replace-fail "cp " "cp --no-preserve=mode "
247
248 wrapProgram $out/bin/solo5-virtio-mkimage \
249 --prefix PATH : ${
250 lib.makeBinPath [
251 dosfstools
252 mtools
253 parted
254 syslinux
255 ]
256 }
257 '';
258
259 doCheck = true;
260 nativeCheckInputs = [
261 util-linux
262 qemu
263 ];
264 # `checkPhase` elided
265})
266```
267
268- `makeWrapper` is a setup hook, i.e., a shell script sourced by the generic builder of `stdenv`.
269 It is thus executed during the build and must be added to `nativeBuildInputs`.
270- `pkg-config` is a build tool which the configure script of `solo5` expects to be on `$PATH` during the build:
271 therefore, it must be added to `nativeBuildInputs`.
272- `libseccomp` is a library linked into `$out/bin/solo5-elftool`.
273 As it is used at runtime, it must be added to `buildInputs`.
274- Tests need `qemu` and `getopt` (from `util-linux`) on `$PATH`, these must be added to `nativeCheckInputs`.
275- Some dependencies are injected directly in the shell code of phases: `syslinux`, `dosfstools`, `mtools`, and `parted`.
276In this specific case, they will end up in the output of the derivation (`$out` here).
277As Nix marks dependencies whose absolute path is present in the output as runtime dependencies, adding them to `buildInputs` is not required.
278
279For more complex cases, like libraries linked into an executable which is then executed as part of the build system, see [](#ssec-stdenv-dependencies-reference).
280
281### Reference {#ssec-stdenv-dependencies-reference}
282
283As described in the Nix manual, almost any `*.drv` store path in a derivation’s attribute set will induce a dependency on that derivation. `mkDerivation`, however, takes a few attributes intended to include all the dependencies of a package. This is done both for structure and consistency, but also so that certain other setup can take place. For example, certain dependencies need their bin directories added to the `PATH`. That is built-in, but other setup is done via a pluggable mechanism that works in conjunction with these dependency attributes. See [](#ssec-setup-hooks) for details.
284
285Dependencies can be broken down along these axes: their host and target platforms relative to the new derivation’s. The platform distinctions are motivated by cross compilation; see [](#chap-cross) for exactly what each platform means. [^footnote-stdenv-ignored-build-platform] But even if one is not cross compiling, the platforms imply whether a dependency is needed at run-time or build-time.
286
287The extension of `PATH` with dependencies, alluded to above, proceeds according to the relative platforms alone. The process is carried out only for dependencies whose host platform matches the new derivation’s build platform i.e. dependencies which run on the platform where the new derivation will be built. [^footnote-stdenv-native-dependencies-in-path] For each dependency \<dep\> of those dependencies, `dep/bin`, if present, is added to the `PATH` environment variable.
288
289### Dependency propagation {#ssec-stdenv-dependencies-propagated}
290
291Propagated dependencies are made available to all downstream dependencies.
292This is particularly useful for interpreted languages, where all transitive dependencies have to be present in the same environment.
293Therefore it is used for the Python infrastructure in Nixpkgs.
294
295:::{.note}
296Propagated dependencies should be used with care, because they obscure the actual build inputs of dependent derivations and cause side effects through setup hooks.
297This can lead to conflicting dependencies that cannot easily be resolved.
298:::
299
300:::{.example}
301# A propagated dependency
302
303```nix
304with import <nixpkgs> { };
305let
306 bar = stdenv.mkDerivation {
307 name = "bar";
308 dontUnpack = true;
309 # `hello` is also made available to dependents, such as `foo`
310 propagatedBuildInputs = [ hello ];
311 postInstall = "mkdir $out";
312 };
313 foo = stdenv.mkDerivation {
314 name = "foo";
315 dontUnpack = true;
316 # `bar` is a direct dependency, which implicitly includes the propagated `hello`
317 buildInputs = [ bar ];
318 # The `hello` binary is available!
319 postInstall = "hello > $out";
320 };
321in
322foo
323```
324:::
325
326Dependency propagation takes cross compilation into account, meaning that dependencies that cross platform boundaries are properly adjusted.
327
328To determine the exact rules for dependency propagation, we start by assigning to each dependency a couple of ternary numbers (`-1` for `build`, `0` for `host`, and `1` for `target`) representing its [dependency type](#possible-dependency-types), which captures how its host and target platforms are each "offset" from the depending derivation’s host and target platforms. The following table summarize the different combinations that can be obtained:
329
330| `host → target` | attribute name | offset | typical purpose |
331| ------------------- | ------------------- | -------- | --------------------------------------------- |
332| `build --> build` | `depsBuildBuild` | `-1, -1` | compilers for build helpers |
333| `build --> host` | `nativeBuildInputs` | `-1, 0` | build tools, compilers, setup hooks |
334| `build --> target` | `depsBuildTarget` | `-1, 1` | compilers to build stdlibs to run on target |
335| `host --> host` | `depsHostHost` | `0, 0` | compilers to build C code at runtime (rare) |
336| `host --> target` | `buildInputs` | `0, 1` | libraries |
337| `target --> target` | `depsTargetTarget` | `1, 1` | stdlibs to run on target |
338
339Algorithmically, we traverse propagated inputs, accumulating every propagated dependency’s propagated dependencies and adjusting them to account for the “shift in perspective” described by the current dependency’s platform offsets. This results in a sort of transitive closure of the dependency relation, with the offsets being approximately summed when two dependency links are combined. We also prune transitive dependencies whose combined offsets go out-of-bounds, which can be viewed as a filter over that transitive closure removing dependencies that are blatantly absurd.
340
341We can define the process precisely with [Natural Deduction](https://en.wikipedia.org/wiki/Natural_deduction) using the inference rules below. This probably seems a bit obtuse, but so is the bash code that actually implements it! [^footnote-stdenv-find-inputs-location] They’re confusing in very different ways so… hopefully if something doesn’t make sense in one presentation, it will in the other!
342
343**Definitions:**
344
345`dep(h_offset, t_offset, X, Y)`
346: Package X has a direct dependency on Y in a position with host offset `h_offset` and target offset `t_offset`.
347
348 For example, `nativeBuildInputs = [ Y ]` means `dep(-1, 0, X, Y)`.
349
350`propagated-dep(h_offset, t_offset, X, Y)`
351: Package X has a propagated dependency on Y in a position with host offset `h_offset` and target offset `t_offset`.
352
353 For example, `depsBuildTargetPropagated = [ Y ]` means `propagated-dep(-1, 1, X, Y)`.
354
355`mapOffset(h, t, i) = offs`
356: In a package X with a dependency on Y in a position with host offset `h` and target offset `t`, Y's transitive dependency Z in a position with offset `i` is mapped to offset `offs` in X.
357
358
359::: {.example}
360# Truth table of `mapOffset(h, t, i)`
361
362`x` means that the dependency was discarded because `h + i ∉ {-1, 0, 1}`.
363
364<!-- This is written as an ascii art table because the CSS was introducing so much space it was unreadable and doesn't support double lines -->
365
366```
367 h | t || i=-1 | i=0 | i=1
368----|------||------|------|-----
369 -1 | -1 || x | -1 | -1
370 -1 | 0 || x | -1 | 0
371 -1 | 1 || x | -1 | 1
372 0 | 0 || -1 | 0 | 0
373 0 | 1 || -1 | 0 | 1
374 1 | 1 || 0 | 1 | x
375```
376
377:::
378
379```
380let mapOffset(h, t, i) = i + (if i <= 0 then h else t - 1)
381
382propagated-dep(h0, t0, A, B)
383propagated-dep(h1, t1, B, C)
384h0 + h1 in {-1, 0, 1}
385h0 + t1 in {-1, 0, 1}
386-------------------------------------- Transitive property
387propagated-dep(mapOffset(h0, t0, h1),
388 mapOffset(h0, t0, t1),
389 A, C)
390```
391
392```
393let mapOffset(h, t, i) = i + (if i <= 0 then h else t - 1)
394
395dep(h0, t0, A, B)
396propagated-dep(h1, t1, B, C)
397h0 + h1 in {-1, 0, 1}
398h0 + t1 in {-1, 0, 1}
399----------------------------- Take immediate dependencies' propagated dependencies
400propagated-dep(mapOffset(h0, t0, h1),
401 mapOffset(h0, t0, t1),
402 A, C)
403```
404
405```
406propagated-dep(h, t, A, B)
407----------------------------- Propagated dependencies count as dependencies
408dep(h, t, A, B)
409```
410
411Some explanation of this monstrosity is in order. In the common case of `nativeBuildInputs` or `buildInputs`, the target offset of a dependency is one greater than the host offset: `t = h + 1`. That means that:
412
413```
414let f(h, t, i) = i + (if i <= 0 then h else t - 1)
415let f(h, h + 1, i) = i + (if i <= 0 then h else (h + 1) - 1)
416let f(h, h + 1, i) = i + (if i <= 0 then h else h)
417let f(h, h + 1, i) = i + h
418```
419
420This is where “sum-like” comes in from above: We can just sum all of the host offsets to get the host offset of the transitive dependency. The target offset is the transitive dependency is the host offset + 1, just as it was with the dependencies composed to make this transitive one; it can be ignored as it doesn’t add any new information.
421
422Because of the bounds checks, the uncommon cases are `h = t` (`depsBuildBuild`, etc) and `h + 2 = t` (`depsBuildTarget`).
423
424In the former case, the motivation for `mapOffset` is that since its host and target platforms are the same, no transitive dependency of it should be able to “discover” an offset greater than its reduced target offsets. `mapOffset` effectively “squashes” all its transitive dependencies’ offsets so that none will ever be greater than the target offset of the original `h = t` package.
425
426In the other case, `h + 1` (0) is skipped over between the host (-1) and target (1) offsets. Instead of squashing the offsets, we need to “rip” them apart so no transitive dependency’s offset is 0.
427
428Overall, the unifying theme here is that propagation shouldn’t be introducing transitive dependencies involving platforms the depending package is unaware of. \[One can imagine the depending package asking for dependencies with the platforms it knows about; other platforms it doesn’t know how to ask for. The platform description in that scenario is a kind of unforgeable capability.\] The offset bounds checking and definition of `mapOffset` together ensure that this is the case. Discovering a new offset is discovering a new platform, and since those platforms weren’t in the derivation “spec” of the needing package, they cannot be relevant. From a capability perspective, we can imagine that the host and target platforms of a package are the capabilities a package requires, and the depending package must provide the capability to the dependency.
429
430#### Variables specifying dependencies {#variables-specifying-dependencies}
431
432##### `depsBuildBuild` {#var-stdenv-depsBuildBuild}
433
434A list of dependencies whose host and target platforms are the new derivation’s build platform. These are programs and libraries used at build time that produce programs and libraries also used at build time. If the dependency doesn’t care about the target platform (i.e. isn’t a compiler or similar tool), put it in `nativeBuildInputs` instead. The most common use of this `buildPackages.stdenv.cc`, the default C compiler for this role. That example crops up more than one might think in old commonly used C libraries.
435
436Since these packages are able to be run at build-time, they are always added to the `PATH`, as described above. But since these packages are only guaranteed to be able to run then, they shouldn’t persist as run-time dependencies. This isn’t currently enforced, but could be in the future.
437
438##### `nativeBuildInputs` {#var-stdenv-nativeBuildInputs}
439
440A list of dependencies whose host platform is the new derivation’s build platform, and target platform is the new derivation’s host platform. These are programs and libraries used at build-time that, if they are a compiler or similar tool, produce code to run at run-time—i.e. tools used to build the new derivation. If the dependency doesn’t care about the target platform (i.e. isn’t a compiler or similar tool), put it here, rather than in `depsBuildBuild` or `depsBuildTarget`. This could be called `depsBuildHost`, but `nativeBuildInputs` is used for historical continuity.
441
442Since these packages are able to be run at build-time, they are added to the `PATH`, as described above. But since these packages are only guaranteed to be able to run then, they shouldn’t persist as run-time dependencies. This isn’t currently enforced, but could be in the future.
443
444##### `depsBuildTarget` {#var-stdenv-depsBuildTarget}
445
446A list of dependencies whose host platform is the new derivation’s build platform, and target platform is the new derivation’s target platform. These are programs used at build time that produce code to run with code produced by the depending package. Most commonly, these are tools used to build the runtime or standard library that the currently-being-built compiler will inject into any code it compiles. In many cases, the currently-being-built-compiler is itself employed for that task, but when that compiler won’t run (i.e. its build and host platform differ) this is not possible. Other times, the compiler relies on some other tool, like binutils, that is always built separately so that the dependency is unconditional.
447
448This is a somewhat confusing concept to wrap one’s head around, and for good reason. As the only dependency type where the platform offsets, `-1` and `1`, are not adjacent integers, it requires thinking of a bootstrapping stage *two* away from the current one. It and its use-case go hand in hand and are both considered poor form: try to not need this sort of dependency, and try to avoid building standard libraries and runtimes in the same derivation as the compiler produces code using them. Instead strive to build those like a normal library, using the newly-built compiler just as a normal library would. In short, do not use this attribute unless you are packaging a compiler and are sure it is needed.
449
450Since these packages are able to run at build time, they are added to the `PATH`, as described above. But since these packages are only guaranteed to be able to run then, they shouldn’t persist as run-time dependencies. This isn’t currently enforced, but could be in the future.
451
452##### `depsHostHost` {#var-stdenv-depsHostHost}
453
454A list of dependencies whose host and target platforms match the new derivation’s host platform. In practice, this would usually be tools used by compilers for macros or a metaprogramming system, or libraries used by the macros or metaprogramming code itself. It’s always preferable to use a `depsBuildBuild` dependency in the derivation being built over a `depsHostHost` on the tool doing the building for this purpose.
455
456##### `buildInputs` {#var-stdenv-buildInputs}
457
458A list of dependencies whose host platform and target platform match the new derivation’s. This would be called `depsHostTarget` but for historical continuity. If the dependency doesn’t care about the target platform (i.e. isn’t a compiler or similar tool), put it here, rather than in `depsBuildBuild`.
459
460These are often programs and libraries used by the new derivation at *run*-time, but that isn’t always the case. For example, the machine code in a statically-linked library is only used at run-time, but the derivation containing the library is only needed at build-time. Even in the dynamic case, the library may also be needed at build-time to appease the linker.
461
462##### `depsTargetTarget` {#var-stdenv-depsTargetTarget}
463
464A list of dependencies whose host platform matches the new derivation’s target platform. These are packages that run on the target platform, e.g. the standard library or run-time deps of standard library that a compiler insists on knowing about. It’s poor form in almost all cases for a package to depend on another from a future stage \[future stage corresponding to positive offset\]. Do not use this attribute unless you are packaging a compiler and are sure it is needed.
465
466##### `depsBuildBuildPropagated` {#var-stdenv-depsBuildBuildPropagated}
467
468The propagated equivalent of `depsBuildBuild`. This perhaps never ought to be used, but it is included for consistency \[see below for the others\].
469
470##### `propagatedNativeBuildInputs` {#var-stdenv-propagatedNativeBuildInputs}
471
472The propagated equivalent of `nativeBuildInputs`. This would be called `depsBuildHostPropagated` but for historical continuity. For example, if package `Y` has `propagatedNativeBuildInputs = [X]`, and package `Z` has `buildInputs = [Y]`, then package `Z` will be built as if it included package `X` in its `nativeBuildInputs`. Note that if instead, package `Z` has `nativeBuildInputs = [Y]`, then `X` will not be included at all.
473
474##### `depsBuildTargetPropagated` {#var-stdenv-depsBuildTargetPropagated}
475
476The propagated equivalent of `depsBuildTarget`. This is prefixed for the same reason of alerting potential users.
477
478##### `depsHostHostPropagated` {#var-stdenv-depsHostHostPropagated}
479
480The propagated equivalent of `depsHostHost`.
481
482##### `propagatedBuildInputs` {#var-stdenv-propagatedBuildInputs}
483
484The propagated equivalent of `buildInputs`. This would be called `depsHostTargetPropagated` but for historical continuity.
485
486##### `depsTargetTargetPropagated` {#var-stdenv-depsTargetTargetPropagated}
487
488The propagated equivalent of `depsTargetTarget`. This is prefixed for the same reason of alerting potential users.
489
490## Attributes {#ssec-stdenv-attributes}
491
492### Variables affecting `stdenv` initialisation {#variables-affecting-stdenv-initialisation}
493
494#### `NIX_DEBUG` {#var-stdenv-NIX_DEBUG}
495
496A number between 0 and 7 indicating how much information to log. If set to 1 or higher, `stdenv` will print moderate debugging information during the build. In particular, the `gcc` and `ld` wrapper scripts will print out the complete command line passed to the wrapped tools. If set to 6 or higher, the `stdenv` setup script will be run with `set -x` tracing. If set to 7 or higher, the `gcc` and `ld` wrapper scripts will also be run with `set -x` tracing.
497
498### Attributes affecting build properties {#attributes-affecting-build-properties}
499
500#### `enableParallelBuilding` {#var-stdenv-enableParallelBuilding}
501
502If set to `true`, `stdenv` will pass specific flags to `make` and other build tools to enable parallel building with up to `build-cores` workers.
503
504Unless set to `false`, some build systems with good support for parallel building including `cmake`, `meson`, and `qmake` will set it to `true`.
505
506### Fixed-point arguments of `mkDerivation` {#mkderivation-recursive-attributes}
507
508If you pass a function to `mkDerivation`, it will receive as its argument the final arguments, including the overrides when reinvoked via `overrideAttrs`. For example:
509
510```nix
511mkDerivation (finalAttrs: {
512 pname = "hello";
513 withFeature = true;
514 configureFlags = lib.optionals finalAttrs.withFeature [ "--with-feature" ];
515})
516```
517
518Note that this does not use the `rec` keyword to reuse `withFeature` in `configureFlags`.
519The `rec` keyword works at the syntax level and is unaware of overriding.
520
521Instead, the definition references `finalAttrs`, allowing users to change `withFeature`
522consistently with `overrideAttrs`.
523
524`finalAttrs` also contains the attribute `finalPackage`, which includes the output paths, etc.
525
526Let's look at a more elaborate example to understand the differences between
527various bindings:
528
529```nix
530# `pkg` is the _original_ definition (for illustration purposes)
531let
532 pkg = mkDerivation (finalAttrs: {
533 # ...
534
535 # An example attribute
536 packages = [ ];
537
538 # `passthru.tests` is a commonly defined attribute.
539 passthru.tests.simple = f finalAttrs.finalPackage;
540
541 # An example of an attribute containing a function
542 passthru.appendPackages =
543 packages':
544 finalAttrs.finalPackage.overrideAttrs (newSelf: super: { packages = super.packages ++ packages'; });
545
546 # For illustration purposes; referenced as
547 # `(pkg.overrideAttrs(x)).finalAttrs` etc in the text below.
548 passthru.finalAttrs = finalAttrs;
549 passthru.original = pkg;
550 });
551in
552pkg
553```
554
555Unlike the `pkg` binding in the above example, the `finalAttrs` parameter always references the final attributes. For instance `(pkg.overrideAttrs(x)).finalAttrs.finalPackage` is identical to `pkg.overrideAttrs(x)`, whereas `(pkg.overrideAttrs(x)).original` is the same as the original `pkg`.
556
557See also the section about [`passthru.tests`](#var-passthru-tests).
558
559## Phases {#sec-stdenv-phases}
560
561`stdenv.mkDerivation` sets the Nix [derivation](https://nixos.org/manual/nix/stable/expressions/derivations.html#derivations)'s builder to a script that loads the stdenv `setup.sh` bash library and calls `genericBuild`. Most packaging functions rely on this default builder.
562
563This generic command either invokes a script at *buildCommandPath*, or a *buildCommand*, or a number of *phases*. Package builds are split into phases to make it easier to override specific parts of the build (e.g., unpacking the sources or installing the binaries).
564
565Each phase can be overridden in its entirety either by setting the environment variable `namePhase` to a string containing some shell commands to be executed, or by redefining the shell function `namePhase`. The former is convenient to override a phase from the derivation, while the latter is convenient from a build script. However, typically one only wants to *add* some commands to a phase, e.g. by defining `postInstall` or `preFixup`, as skipping some of the default actions may have unexpected consequences. The default script for each phase is defined in the file `pkgs/stdenv/generic/setup.sh`.
566
567When overriding a phase, for example `installPhase`, it is important to start with `runHook preInstall` and end it with `runHook postInstall`, otherwise `preInstall` and `postInstall` will not be run. Even if you don't use them directly, it is good practice to do so anyways for downstream users who would want to add a `postInstall` by overriding your derivation.
568
569While inside an interactive `nix-shell`, if you wanted to run all phases in the order they would be run in an actual build, you can invoke `genericBuild` yourself.
570
571### Controlling phases {#ssec-controlling-phases}
572
573There are a number of variables that control what phases are executed and in what order:
574
575#### Variables affecting phase control {#variables-affecting-phase-control}
576
577##### `phases` {#var-stdenv-phases}
578
579Specifies the phases. You can change the order in which phases are executed, or add new phases, by setting this variable. If it’s not set, the default value is used, which is `$prePhases unpackPhase patchPhase $preConfigurePhases configurePhase $preBuildPhases buildPhase checkPhase $preInstallPhases installPhase fixupPhase installCheckPhase $preDistPhases distPhase $postPhases`.
580
581The elements of `phases` must not contain spaces. If `phases` is specified as a Nix Language attribute, it should be specified as lists instead of strings. The same rules apply to the `*Phases` variables.
582
583It is discouraged to set this variable, as it is easy to miss some important functionality hidden in some of the less obviously needed phases (like `fixupPhase` which patches the shebang of scripts).
584Usually, if you just want to add a few phases, it’s more convenient to set one of the `*Phases` variables below.
585
586##### `prePhases` {#var-stdenv-prePhases}
587
588Additional phases executed before any of the default phases.
589
590##### `preConfigurePhases` {#var-stdenv-preConfigurePhases}
591
592Additional phases executed just before the configure phase.
593
594##### `preBuildPhases` {#var-stdenv-preBuildPhases}
595
596Additional phases executed just before the build phase.
597
598##### `preInstallPhases` {#var-stdenv-preInstallPhases}
599
600Additional phases executed just before the install phase.
601
602##### `preFixupPhases` {#var-stdenv-preFixupPhases}
603
604Additional phases executed just before the fixup phase.
605
606##### `preDistPhases` {#var-stdenv-preDistPhases}
607
608Additional phases executed just before the distribution phase.
609
610##### `postPhases` {#var-stdenv-postPhases}
611
612Additional phases executed after any of the default phases.
613
614### The unpack phase {#ssec-unpack-phase}
615
616The unpack phase is responsible for unpacking the source code of the package. The default implementation of `unpackPhase` unpacks the source files listed in the `src` environment variable to the current directory. It supports the following files by default:
617
618#### Tar files {#tar-files}
619
620These can optionally be compressed using `gzip` (`.tar.gz`, `.tgz` or `.tar.Z`), `bzip2` (`.tar.bz2`, `.tbz2` or `.tbz`) or `xz` (`.tar.xz`, `.tar.lzma` or `.txz`).
621
622#### Zip files {#zip-files}
623
624Zip files are unpacked using `unzip`. However, `unzip` is not in the standard environment, so you should add it to `nativeBuildInputs` yourself.
625
626#### Directories in the Nix store {#directories-in-the-nix-store}
627
628These are copied to the current directory. The hash part of the file name is stripped, e.g. `/nix/store/1wydxgby13cz...-my-sources` would be copied to `my-sources`.
629
630Additional file types can be supported by setting the `unpackCmd` variable (see below).
631
632#### Variables controlling the unpack phase {#variables-controlling-the-unpack-phase}
633
634##### `srcs` / `src` {#var-stdenv-src}
635
636The list of source files or directories to be unpacked or copied. One of these must be set. Note that if you use `srcs`, you should also set `sourceRoot` or `setSourceRoot`.
637
638These should ideally actually be sources and licensed under a FLOSS license. If you have to use a binary upstream release or package non-free software, make sure you correctly mark your derivation as such in the [`sourceProvenance`](#var-meta-sourceProvenance) and [`license`](#sec-meta-license) fields of the [`meta`](#chap-meta) section.
639
640##### `sourceRoot` {#var-stdenv-sourceRoot}
641
642After unpacking all of `src` and `srcs`, if neither of `sourceRoot` and `setSourceRoot` are set, `unpackPhase` of the generic builder checks that the unpacking produced a single directory and moves the current working directory into it.
643
644If `unpackPhase` produces multiple source directories, you should set `sourceRoot` to the name of the intended directory.
645You can also set `sourceRoot = ".";` if you want to control it yourself in a later phase.
646
647For example, if you want your build to start in a sub-directory inside your sources, and you are using `fetchzip`-derived `src` (like `fetchFromGitHub` or similar), you need to set `sourceRoot = "${src.name}/my-sub-directory"`.
648
649##### `setSourceRoot` {#var-stdenv-setSourceRoot}
650
651Alternatively to setting `sourceRoot`, you can set `setSourceRoot` to a shell command to be evaluated by the unpack phase after the sources have been unpacked. This command must set `sourceRoot`.
652
653For example, if you are using `fetchurl` on an archive file that gets unpacked into a single directory the name of which changes between package versions, and you want your build to start in its sub-directory, you need to set `setSourceRoot = "sourceRoot=$(echo */my-sub-directory)";`, or in the case of multiple sources, you could use something more specific, like `setSourceRoot = "sourceRoot=$(echo ${pname}-*/my-sub-directory)";`.
654
655##### `preUnpack` {#var-stdenv-preUnpack}
656
657Hook executed at the start of the unpack phase.
658
659##### `postUnpack` {#var-stdenv-postUnpack}
660
661Hook executed at the end of the unpack phase.
662
663##### `dontUnpack` {#var-stdenv-dontUnpack}
664
665Set to true to skip the unpack phase.
666
667##### `dontMakeSourcesWritable` {#var-stdenv-dontMakeSourcesWritable}
668
669If set to `1`, the unpacked sources are *not* made writable. By default, they are made writable to prevent problems with read-only sources. For example, copied store directories would be read-only without this.
670
671##### `unpackCmd` {#var-stdenv-unpackCmd}
672
673The unpack phase evaluates the string `$unpackCmd` for any unrecognised file. The path to the current source file is contained in the `curSrc` variable.
674
675### The patch phase {#ssec-patch-phase}
676
677The patch phase applies the list of patches defined in the `patches` variable.
678
679#### Variables controlling the patch phase {#variables-controlling-the-patch-phase}
680
681##### `dontPatch` {#var-stdenv-dontPatch}
682
683Set to true to skip the patch phase.
684
685##### `patches` {#var-stdenv-patches}
686
687The list of patches. They must be in the format accepted by the `patch` command, and may optionally be compressed using `gzip` (`.gz`), `bzip2` (`.bz2`) or `xz` (`.xz`).
688
689##### `patchFlags` {#var-stdenv-patchFlags}
690
691Flags to be passed to `patch`. If not set, the argument `-p1` is used, which causes the leading directory component to be stripped from the file names in each patch.
692
693##### `prePatch` {#var-stdenv-prePatch}
694
695Hook executed at the start of the patch phase.
696
697##### `postPatch` {#var-stdenv-postPatch}
698
699Hook executed at the end of the patch phase.
700
701### The configure phase {#ssec-configure-phase}
702
703The configure phase prepares the source tree for building. The default `configurePhase` runs `./configure` (typically an Autoconf-generated script) if it exists.
704
705#### Variables controlling the configure phase {#variables-controlling-the-configure-phase}
706
707##### `configureScript` {#var-stdenv-configureScript}
708
709The name of the configure script. It defaults to `./configure` if it exists; otherwise, the configure phase is skipped. This can actually be a command (like `perl ./Configure.pl`).
710
711##### `configureFlags` {#var-stdenv-configureFlags}
712
713A list of strings passed as additional arguments to the configure script.
714
715##### `dontConfigure` {#var-stdenv-dontConfigure}
716
717Set to true to skip the configure phase.
718
719##### `configureFlagsArray` {#var-stdenv-configureFlagsArray}
720
721A shell array containing additional arguments passed to the configure script. You must use this instead of `configureFlags` if the arguments contain spaces.
722
723##### `dontAddPrefix` {#var-stdenv-dontAddPrefix}
724
725By default, `./configure` is passed the concatenation of [`prefixKey`](#var-stdenv-prefixKey) and [`prefix`](#var-stdenv-prefix) on the command line. Disable this by setting `dontAddPrefix` to `true`.
726
727##### `prefix` {#var-stdenv-prefix}
728
729The prefix under which the package must be installed, passed via the `--prefix` option to the configure script. It defaults to `$out`.
730
731##### `prefixKey` {#var-stdenv-prefixKey}
732
733The key to use when specifying the installation [`prefix`](#var-stdenv-prefix). By default, this is set to `--prefix=` as that is used by the majority of packages. Other packages may need `--prefix ` (with a trailing space) or `PREFIX=`.
734
735##### `dontAddStaticConfigureFlags` {#var-stdenv-dontAddStaticConfigureFlags}
736
737By default, when building statically, `stdenv` will try to add build system appropriate configure flags to try to enable static builds.
738
739If this is undesirable, set this variable to true.
740
741##### `dontAddDisableDepTrack` {#var-stdenv-dontAddDisableDepTrack}
742
743By default, the flag `--disable-dependency-tracking` is added to the configure flags to speed up Automake-based builds. If this is undesirable, set this variable to true.
744
745##### `dontFixLibtool` {#var-stdenv-dontFixLibtool}
746
747By default, the configure phase applies some special hackery to all files called `ltmain.sh` before running the configure script in order to improve the purity of Libtool-based packages [^footnote-stdenv-sys-lib-search-path] . If this is undesirable, set this variable to true.
748
749##### `dontDisableStatic` {#var-stdenv-dontDisableStatic}
750
751By default, when the configure script has `--enable-static`, the option `--disable-static` is added to the configure flags.
752
753If this is undesirable, set this variable to true. It is automatically set to true when building statically, for example through `pkgsStatic`.
754
755##### `configurePlatforms` {#var-stdenv-configurePlatforms}
756
757By default, when cross compiling, the configure script has `--build=...` and `--host=...` passed. Packages can instead pass `[ "build" "host" "target" ]` or a subset to control exactly which platform flags are passed. Compilers and other tools can use this to also pass the target platform. [^footnote-stdenv-build-time-guessing-impurity]
758
759##### `preConfigure` {#var-stdenv-preConfigure}
760
761Hook executed at the start of the configure phase.
762
763##### `postConfigure` {#var-stdenv-postConfigure}
764
765Hook executed at the end of the configure phase.
766
767### The build phase {#build-phase}
768
769The build phase is responsible for actually building the package (e.g. compiling it). The default `buildPhase` calls `make` if a file named `Makefile`, `makefile` or `GNUmakefile` exists in the current directory (or the `makefile` is explicitly set); otherwise it does nothing.
770
771#### Variables controlling the build phase {#variables-controlling-the-build-phase}
772
773##### `dontBuild` {#var-stdenv-dontBuild}
774
775Set to true to skip the build phase.
776
777##### `makefile` {#var-stdenv-makefile}
778
779The file name of the Makefile.
780
781##### `makeFlags` {#var-stdenv-makeFlags}
782
783A list of strings passed as additional flags to `make`. These flags are also used by the default install and check phase. For setting make flags specific to the build phase, use `buildFlags` (see below).
784
785```nix
786{ makeFlags = [ "PREFIX=$(out)" ]; }
787```
788
789::: {.note}
790The flags are quoted in bash, but environment variables can be specified by using the make syntax.
791:::
792
793##### `makeFlagsArray` {#var-stdenv-makeFlagsArray}
794
795A shell array containing additional arguments passed to `make`. You must use this instead of `makeFlags` if the arguments contain spaces, e.g.
796
797```nix
798{
799 preBuild = ''
800 makeFlagsArray+=(CFLAGS="-O0 -g" LDFLAGS="-lfoo -lbar")
801 '';
802}
803```
804
805Note that shell arrays cannot be passed through environment variables, so you cannot set `makeFlagsArray` in a derivation attribute (because those are passed through environment variables): you have to define them in shell code.
806
807##### `buildFlags` / `buildFlagsArray` {#var-stdenv-buildFlags}
808
809A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the build phase. Any build targets should be specified as part of the `buildFlags`.
810
811##### `preBuild` {#var-stdenv-preBuild}
812
813Hook executed at the start of the build phase.
814
815##### `postBuild` {#var-stdenv-postBuild}
816
817Hook executed at the end of the build phase.
818
819You can set flags for `make` through the `makeFlags` variable.
820
821Before and after running `make`, the hooks `preBuild` and `postBuild` are called, respectively.
822
823### The check phase {#ssec-check-phase}
824
825The check phase checks whether the package was built correctly by running its test suite. The default `checkPhase` calls `make $checkTarget`, but only if the [`doCheck` variable](#var-stdenv-doCheck) is enabled.
826
827It is highly recommended, for packages' sources that are not distributed with any tests, to at least use [`versionCheckHook`](#versioncheckhook) to test that the resulting executable is basically functional.
828
829#### Variables controlling the check phase {#variables-controlling-the-check-phase}
830
831##### `doCheck` {#var-stdenv-doCheck}
832
833Controls whether the check phase is executed. By default it is skipped, but if `doCheck` is set to true, the check phase is usually executed. Thus you should set
834
835```nix
836{ doCheck = true; }
837```
838
839in the derivation to enable checks. The exception is cross compilation. Cross compiled builds never run tests, no matter how `doCheck` is set, as the newly-built program won’t run on the platform used to build it.
840
841##### `makeFlags` / `makeFlagsArray` / `makefile` {#makeflags-makeflagsarray-makefile}
842
843See the [build phase](#var-stdenv-makeFlags) for details.
844
845##### `checkTarget` {#var-stdenv-checkTarget}
846
847The `make` target that runs the tests.
848If unset, use `check` if it exists, otherwise `test`; if neither is found, do nothing.
849
850##### `checkFlags` / `checkFlagsArray` {#var-stdenv-checkFlags}
851
852A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the check phase. Unlike with `buildFlags`, the `checkTarget` is automatically added to the `make` invocation in addition to any `checkFlags` specified.
853
854##### `checkInputs` {#var-stdenv-checkInputs}
855
856A list of host dependencies used by the phase, usually libraries linked into executables built during tests. This gets included in `buildInputs` when `doCheck` is set.
857
858##### `nativeCheckInputs` {#var-stdenv-nativeCheckInputs}
859
860A list of native dependencies used by the phase, notably tools needed on `$PATH`. This gets included in `nativeBuildInputs` when `doCheck` is set.
861
862##### `preCheck` {#var-stdenv-preCheck}
863
864Hook executed at the start of the check phase.
865
866##### `postCheck` {#var-stdenv-postCheck}
867
868Hook executed at the end of the check phase.
869
870### The install phase {#ssec-install-phase}
871
872The install phase is responsible for installing the package in the Nix store under `out`. The default `installPhase` creates the directory `$out` and calls `make install`.
873
874#### Variables controlling the install phase {#variables-controlling-the-install-phase}
875
876##### `dontInstall` {#var-stdenv-dontInstall}
877
878Set to true to skip the install phase.
879
880##### `makeFlags` / `makeFlagsArray` / `makefile` {#makeflags-makeflagsarray-makefile-1}
881
882See the [build phase](#var-stdenv-makeFlags) for details.
883
884##### `installTargets` {#var-stdenv-installTargets}
885
886The make targets that perform the installation. Defaults to `install`. Example:
887
888```nix
889{ installTargets = "install-bin install-doc"; }
890```
891
892##### `installFlags` / `installFlagsArray` {#var-stdenv-installFlags}
893
894A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the install phase. Unlike with `buildFlags`, the `installTargets` are automatically added to the `make` invocation in addition to any `installFlags` specified.
895
896##### `preInstall` {#var-stdenv-preInstall}
897
898Hook executed at the start of the install phase.
899
900##### `postInstall` {#var-stdenv-postInstall}
901
902Hook executed at the end of the install phase.
903
904### The fixup phase {#ssec-fixup-phase}
905
906The fixup phase performs (Nix-specific) post-processing actions on the files installed under `$out` by the install phase. The default `fixupPhase` does the following:
907
908- It moves the `man/`, `doc/` and `info/` subdirectories of `$out` to `share/`.
909- It strips libraries and executables of debug information.
910- On Linux, it applies the `patchelf` command to ELF executables and libraries to remove unused directories from the `RPATH` in order to prevent unnecessary runtime dependencies.
911- It rewrites the interpreter paths of shell scripts to paths found in `PATH`. E.g., `/usr/bin/perl` will be rewritten to `/nix/store/some-perl/bin/perl` found in `PATH`. See [](#patch-shebangs.sh) for details.
912
913#### Variables controlling the fixup phase {#variables-controlling-the-fixup-phase}
914
915##### `dontFixup` {#var-stdenv-dontFixup}
916
917Set to true to skip the fixup phase.
918
919##### `dontStrip` {#var-stdenv-dontStrip}
920
921If set, libraries and executables are not stripped. By default, they are.
922
923##### `dontStripHost` {#var-stdenv-dontStripHost}
924
925Like `dontStrip`, but only affects the `strip` command targeting the package’s host platform. Useful when supporting cross compilation, but otherwise feel free to ignore.
926
927##### `dontStripTarget` {#var-stdenv-dontStripTarget}
928
929Like `dontStrip`, but only affects the `strip` command targeting the packages’ target platform. Useful when supporting cross compilation, but otherwise feel free to ignore.
930
931##### `dontMoveSbin` {#var-stdenv-dontMoveSbin}
932
933If set, files in `$out/sbin` are not moved to `$out/bin`. By default, they are.
934
935##### `stripAllList` {#var-stdenv-stripAllList}
936
937List of directories to search for libraries and executables from which *all* symbols should be stripped. By default, it’s empty. Stripping all symbols is risky, since it may remove not just debug symbols but also ELF information necessary for normal execution.
938
939##### `stripAllListTarget` {#var-stdenv-stripAllListTarget}
940
941Like `stripAllList`, but only applies to packages’ target platform. By default, it’s empty. Useful when supporting cross compilation.
942
943##### `stripAllFlags` {#var-stdenv-stripAllFlags}
944
945Flags passed to the `strip` command applied to the files in the directories listed in `stripAllList`. Defaults to `-s -p` (i.e. `--strip-all --preserve-dates`).
946
947##### `stripDebugList` {#var-stdenv-stripDebugList}
948
949List of directories to search for libraries and executables from which only debugging-related symbols should be stripped. It defaults to `lib lib32 lib64 libexec bin sbin`.
950
951##### `stripDebugListTarget` {#var-stdenv-stripDebugListTarget}
952
953Like `stripDebugList`, but only applies to packages’ target platform. By default, it’s empty. Useful when supporting cross compilation.
954
955##### `stripDebugFlags` {#var-stdenv-stripDebugFlags}
956
957Flags passed to the `strip` command applied to the files in the directories listed in `stripDebugList`. Defaults to `-S -p` (i.e. `--strip-debug --preserve-dates`).
958
959##### `stripExclude` {#var-stdenv-stripExclude}
960
961A list of filenames or path patterns to avoid stripping. A file is excluded if its name _or_ path (from the derivation root) matches.
962
963This example prevents all `*.rlib` files from being stripped:
964
965```nix
966stdenv.mkDerivation {
967 # ...
968 stripExclude = [ "*.rlib" ];
969}
970```
971
972This example prevents files within certain paths from being stripped:
973
974```nix
975stdenv.mkDerivation {
976 # ...
977 stripExclude = [ "lib/modules/*/build/*" ];
978}
979```
980
981##### `dontPatchELF` {#var-stdenv-dontPatchELF}
982
983If set, the `patchelf` command is not used to remove unnecessary `RPATH` entries. Only applies to Linux.
984
985##### `dontPatchShebangs` {#var-stdenv-dontPatchShebangs}
986
987If set, scripts starting with `#!` do not have their interpreter paths rewritten to paths in the Nix store. See [](#patch-shebangs.sh) on how patching shebangs works.
988
989##### `dontPruneLibtoolFiles` {#var-stdenv-dontPruneLibtoolFiles}
990
991If set, libtool `.la` files associated with shared libraries won’t have their `dependency_libs` field cleared.
992
993##### `forceShare` {#var-stdenv-forceShare}
994
995The list of directories that must be moved from `$out` to `$out/share`. Defaults to `man doc info`.
996
997##### `setupHook` {#var-stdenv-setupHook}
998
999A package can export a [setup hook](#ssec-setup-hooks) by setting this variable. The setup hook, if defined, is copied to `$out/nix-support/setup-hook`. Environment variables are then substituted in it using `substituteAll`.
1000
1001##### `preFixup` {#var-stdenv-preFixup}
1002
1003Hook executed at the start of the fixup phase.
1004
1005##### `postFixup` {#var-stdenv-postFixup}
1006
1007Hook executed at the end of the fixup phase.
1008
1009##### `separateDebugInfo` {#stdenv-separateDebugInfo}
1010
1011If set to `true`, the standard environment will enable debug information in C/C++ builds. After installation, the debug information will be separated from the executables and stored in the output named `debug`. (This output is enabled automatically; you don’t need to set the `outputs` attribute explicitly.) To be precise, the debug information is stored in `debug/lib/debug/.build-id/XX/YYYY…`, where \<XXYYYY…\> is the \<build ID\> of the binary — a SHA-1 hash of the contents of the binary. Debuggers like GDB use the build ID to look up the separated debug information.
1012
1013:::{.example #ex-gdb-debug-symbols-socat}
1014
1015# Enable debug symbols for use with GDB
1016
1017To make GDB find debug information for the `socat` package and its dependencies, you can use the following `shell.nix`:
1018
1019```nix
1020{
1021 pkgs ? import <nixpkgs> {
1022 config = { };
1023 overlays = [
1024 (final: prev: {
1025 ncurses = prev.ncurses.overrideAttrs { separateDebugInfo = true; };
1026 readline = prev.readline.overrideAttrs { separateDebugInfo = true; };
1027 })
1028 ];
1029 },
1030}:
1031pkgs.mkShell {
1032 NIX_DEBUG_INFO_DIRS = pkgs.lib.makeSearchPathOutput "debug" "lib/debug" [
1033 pkgs.glibc
1034 pkgs.ncurses
1035 pkgs.openssl
1036 pkgs.readline
1037 ];
1038
1039 packages = [
1040 pkgs.gdb
1041 pkgs.socat
1042 ];
1043
1044 shellHook = ''
1045 gdb socat
1046 '';
1047}
1048```
1049
1050This setup works as follows:
1051- Add [`overlays`](#chap-overlays) to the package set, since debug symbols are disabled for `ncurses` and `readline` by default.
1052- Set the environment variable `NIX_DEBUG_INFO_DIRS` in the shell. Nixpkgs patches `gdb` to use this variable for looking up debug symbols.
1053 [`lib.makeSearchPathOutput`](#function-library-lib.strings.makeSearchPathOutput) constructs a colon-separated search path, pointing to the directories containing the debug symbols of the listed packages.
1054- Run `gdb` on the `socat` binary on shell startup in the [`shellHook`](#sec-pkgs-mkShell).
1055
1056:::
1057
1058### The installCheck phase {#ssec-installCheck-phase}
1059
1060The installCheck phase checks whether the package was installed correctly by running its test suite against the installed directories. The default `installCheck` calls `make installcheck`.
1061
1062It is often better to add tests that are not part of the source distribution to `passthru.tests` (see
1063[](#var-passthru-tests)). This avoids adding overhead to every build and enables us to run them independently.
1064
1065#### Variables controlling the installCheck phase {#variables-controlling-the-installcheck-phase}
1066
1067##### `doInstallCheck` {#var-stdenv-doInstallCheck}
1068
1069Controls whether the installCheck phase is executed. By default it is skipped, but if `doInstallCheck` is set to true, the installCheck phase is usually executed. Thus you should set
1070
1071```nix
1072{ doInstallCheck = true; }
1073```
1074
1075in the derivation to enable install checks. The exception is cross compilation. Cross compiled builds never run tests, no matter how `doInstallCheck` is set, as the newly-built program won’t run on the platform used to build it.
1076
1077##### `installCheckTarget` {#var-stdenv-installCheckTarget}
1078
1079The make target that runs the install tests. Defaults to `installcheck`.
1080
1081##### `installCheckFlags` / `installCheckFlagsArray` {#var-stdenv-installCheckFlags}
1082
1083A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the installCheck phase.
1084
1085##### `installCheckInputs` {#var-stdenv-installCheckInputs}
1086
1087A list of host dependencies used by the phase, usually libraries linked into executables built during tests. This gets included in `buildInputs` when `doInstallCheck` is set.
1088
1089##### `nativeInstallCheckInputs` {#var-stdenv-nativeInstallCheckInputs}
1090
1091A list of native dependencies used by the phase, notably tools needed on `$PATH`. This gets included in `nativeBuildInputs` when `doInstallCheck` is set.
1092
1093##### `preInstallCheck` {#var-stdenv-preInstallCheck}
1094
1095Hook executed at the start of the installCheck phase.
1096
1097##### `postInstallCheck` {#var-stdenv-postInstallCheck}
1098
1099Hook executed at the end of the installCheck phase.
1100
1101### The distribution phase {#ssec-distribution-phase}
1102
1103The distribution phase is intended to produce a source distribution of the package. The default `distPhase` first calls `make dist`, then it copies the resulting source tarballs to `$out/tarballs/`. This phase is only executed if the attribute `doDist` is set.
1104
1105#### Variables controlling the distribution phase {#variables-controlling-the-distribution-phase}
1106
1107##### `doDist` {#var-stdenv-doDist}
1108
1109If set, the distribution phase is executed.
1110
1111##### `distTarget` {#var-stdenv-distTarget}
1112
1113The make target that produces the distribution. Defaults to `dist`.
1114
1115##### `distFlags` / `distFlagsArray` {#var-stdenv-distFlags}
1116
1117Additional flags passed to `make`.
1118
1119##### `tarballs` {#var-stdenv-tarballs}
1120
1121The names of the source distribution files to be copied to `$out/tarballs/`. It can contain shell wildcards. The default is `*.tar.gz`.
1122
1123##### `dontCopyDist` {#var-stdenv-dontCopyDist}
1124
1125If set, no files are copied to `$out/tarballs/`.
1126
1127##### `preDist` {#var-stdenv-preDist}
1128
1129Hook executed at the start of the distribution phase.
1130
1131##### `postDist` {#var-stdenv-postDist}
1132
1133Hook executed at the end of the distribution phase.
1134
1135## Shell functions and utilities {#ssec-stdenv-functions}
1136
1137The standard environment provides a number of useful functions.
1138
1139### `makeWrapper` \<executable\> \<wrapperfile\> \<args\> {#fun-makeWrapper}
1140
1141Constructs a wrapper for a program with various possible arguments. It is defined as part of 2 setup-hooks named `makeWrapper` and `makeBinaryWrapper` that implement the same bash functions. Hence, to use it you have to add `makeWrapper` to your `nativeBuildInputs`. Here's an example usage:
1142
1143```bash
1144# adds `FOOBAR=baz` to `$out/bin/foo`’s environment
1145makeWrapper $out/bin/foo $wrapperfile --set FOOBAR baz
1146
1147# Prefixes the binary paths of `hello` and `git`
1148# and suffixes the binary path of `xdg-utils`.
1149# Be advised that paths often should be patched in directly
1150# (via string replacements or in `configurePhase`).
1151makeWrapper $out/bin/foo $wrapperfile \
1152 --prefix PATH : ${lib.makeBinPath [ hello git ]} \
1153 --suffix PATH : ${lib.makeBinPath [ xdg-utils ]}
1154```
1155
1156Packages may expect or require other utilities to be available at runtime.
1157`makeWrapper` can be used to add packages to a `PATH` environment variable local to a wrapper.
1158
1159Use `--prefix` to explicitly set dependencies in `PATH`.
1160
1161::: {.note}
1162`--prefix` essentially hard-codes dependencies into the wrapper.
1163They cannot be overridden without rebuilding the package.
1164:::
1165
1166If dependencies should be resolved at runtime, use `--suffix` to append fallback values to `PATH`.
1167
1168There’s many more kinds of arguments, they are documented in `nixpkgs/pkgs/build-support/setup-hooks/make-wrapper.sh` for the `makeWrapper` implementation and in `nixpkgs/pkgs/by-name/ma/makeBinaryWrapper/make-binary-wrapper.sh` for the `makeBinaryWrapper` implementation.
1169
1170`wrapProgram` is a convenience function you probably want to use most of the time, implemented by both `makeWrapper` and `makeBinaryWrapper`.
1171
1172Using the `makeBinaryWrapper` implementation is usually preferred, as it creates a tiny _compiled_ wrapper executable, that can be used as a shebang interpreter. This is needed mostly on Darwin, where shebangs cannot point to scripts, [due to a limitation with the `execve`-syscall](https://stackoverflow.com/questions/67100831/macos-shebang-with-absolute-path-not-working). Compiled wrappers generated by `makeBinaryWrapper` can be inspected with `less <path-to-wrapper>` - by scrolling past the binary data you should be able to see the shell command that generated the executable and there see the environment variables that were injected into the wrapper.
1173
1174However, `makeWrapper` is more flexible and implements more arguments.
1175Use `makeWrapper` if you need the wrapper to use shell features (e.g. look up environment variables) at runtime.
1176
1177### `remove-references-to -t` \<storepath\> [ `-t` \<storepath\> ... ] \<file\> ... {#fun-remove-references-to}
1178
1179Removes the references of the specified files to the specified store files. This is done without changing the size of the file by replacing the hash by `eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`, and should work on compiled executables. This is meant to be used to remove the dependency of the output on inputs that are known to be unnecessary at runtime. Of course, reckless usage will break the patched programs.
1180To use this, add `removeReferencesTo` to `nativeBuildInputs`.
1181
1182As `remove-references-to` is an actual executable and not a shell function, it can be used with `find`.
1183Example removing all references to the compiler in the output:
1184```nix
1185{
1186 postInstall = ''
1187 find "$out" -type f -exec remove-references-to -t ${stdenv.cc} '{}' +
1188 '';
1189}
1190```
1191
1192### `runHook` \<hook\> {#fun-runHook}
1193
1194Execute \<hook\> and the values in the array associated with it. The array's name is determined by removing `Hook` from the end of \<hook\> and appending `Hooks`.
1195
1196For example, `runHook postHook` would run the hook `postHook` and all of the values contained in the `postHooks` array, if it exists.
1197
1198### `substitute` \<infile\> \<outfile\> \<subs\> {#fun-substitute}
1199
1200Performs string substitution on the contents of \<infile\>, writing the result to \<outfile\>. The substitutions in \<subs\> are of the following form:
1201
1202#### `--replace-fail` \<s1\> \<s2\> {#fun-substitute-replace-fail}
1203
1204Replace every occurrence of the string \<s1\> by \<s2\>.
1205Will error if no change is made.
1206
1207#### `--replace-warn` \<s1\> \<s2\> {#fun-substitute-replace-warn}
1208
1209Replace every occurrence of the string \<s1\> by \<s2\>.
1210Will print a warning if no change is made.
1211
1212#### `--replace-quiet` \<s1\> \<s2\> {#fun-substitute-replace-quiet}
1213
1214Replace every occurrence of the string \<s1\> by \<s2\>.
1215Will do nothing if no change can be made.
1216
1217#### `--subst-var` \<varName\> {#fun-substitute-subst-var}
1218
1219Replace every occurrence of `@varName@` by the contents of the environment variable \<varName\>. This is useful for generating files from templates, using `@...@` in the template as placeholders.
1220
1221#### `--subst-var-by` \<varName\> \<s\> {#fun-substitute-subst-var-by}
1222
1223Replace every occurrence of `@varName@` by the string \<s\>.
1224
1225Example:
1226
1227```shell
1228substitute ./foo.in ./foo.out \
1229 --replace-fail /usr/bin/bar $bar/bin/bar \
1230 --replace-fail "a string containing spaces" "some other text" \
1231 --subst-var someVar
1232```
1233
1234### `substituteInPlace` \<multiple files\> \<subs\> {#fun-substituteInPlace}
1235
1236Like `substitute`, but performs the substitutions in place on the files passed.
1237
1238### `substituteAll` \<infile\> \<outfile\> {#fun-substituteAll}
1239
1240Replaces every occurrence of `@varName@`, where \<varName\> is any environment variable, in \<infile\>, writing the result to \<outfile\>. For instance, if \<infile\> has the contents
1241
1242```bash
1243#! @bash@/bin/sh
1244PATH=@coreutils@/bin
1245echo @foo@
1246```
1247
1248and the environment contains `bash=/nix/store/bmwp0q28cf21...-bash-3.2-p39` and `coreutils=/nix/store/68afga4khv0w...-coreutils-6.12`, but does not contain the variable `foo`, then the output will be
1249
1250```bash
1251#! /nix/store/bmwp0q28cf21...-bash-3.2-p39/bin/sh
1252PATH=/nix/store/68afga4khv0w...-coreutils-6.12/bin
1253echo @foo@
1254```
1255
1256That is, no substitution is performed for undefined variables.
1257
1258Environment variables that start with an uppercase letter or an underscore are filtered out, to prevent global variables (like `HOME`) or private variables (like `__ETC_PROFILE_DONE`) from accidentally getting substituted. The variables also have to be valid bash "names", as defined in the bash manpage (alphanumeric or `_`, must not start with a number).
1259
1260### `substituteAllInPlace` \<file\> {#fun-substituteAllInPlace}
1261
1262Like `substituteAll`, but performs the substitutions in place on the file \<file\>.
1263
1264### `stripHash` \<path\> {#fun-stripHash}
1265
1266Strips the directory and hash part of a store path, outputting the name part to `stdout`. For example:
1267
1268```bash
1269# prints coreutils-8.24
1270stripHash "/nix/store/9s9r019176g7cvn2nvcw41gsp862y6b4-coreutils-8.24"
1271```
1272
1273If you wish to store the result in another variable, then the following idiom may be useful:
1274
1275```bash
1276name="/nix/store/9s9r019176g7cvn2nvcw41gsp862y6b4-coreutils-8.24"
1277someVar=$(stripHash $name)
1278```
1279
1280### `wrapProgram` \<executable\> \<makeWrapperArgs\> {#fun-wrapProgram}
1281
1282Convenience function for `makeWrapper` that replaces `<executable>` with a wrapper that executes the original program. It takes all the same arguments as `makeWrapper`, except for `--inherit-argv0` (used by the `makeBinaryWrapper` implementation) and `--argv0` (used by both `makeWrapper` and `makeBinaryWrapper` wrapper implementations).
1283
1284If you will apply it multiple times, it will overwrite the wrapper file and you will end up with double wrapping, which should be avoided.
1285
1286### `prependToVar` \<variableName\> \<elements...\> {#fun-prependToVar}
1287
1288Prepend elements to a variable.
1289
1290Example:
1291
1292```shellSession
1293$ configureFlags="--disable-static"
1294$ prependToVar configureFlags --disable-dependency-tracking --enable-foo
1295$ echo $configureFlags
1296--disable-dependency-tracking --enable-foo --disable-static
1297```
1298
1299### `appendToVar` \<variableName\> \<elements...\> {#fun-appendToVar}
1300
1301Append elements to a variable.
1302
1303Example:
1304
1305```shellSession
1306$ configureFlags="--disable-static"
1307$ appendToVar configureFlags --disable-dependency-tracking --enable-foo
1308$ echo $configureFlags
1309--disable-static --disable-dependency-tracking --enable-foo
1310```
1311
1312## Package setup hooks {#ssec-setup-hooks}
1313
1314Nix itself considers a build-time dependency as merely something that should previously be built and accessible at build time—packages themselves are on their own to perform any additional setup. In most cases, that is fine, and the downstream derivation can deal with its own dependencies. But for a few common tasks, that would result in almost every package doing the same sort of setup work—depending not on the package itself, but entirely on which dependencies were used.
1315
1316In order to alleviate this burden, the setup hook mechanism was written, where any package can include a shell script that \[by convention rather than enforcement by Nix\], any downstream reverse-dependency will source as part of its build process. That allows the downstream dependency to merely specify its dependencies, and lets those dependencies effectively initialize themselves. No boilerplate mirroring the list of dependencies is needed.
1317
1318The setup hook mechanism is a bit of a sledgehammer though: a powerful feature with a broad and indiscriminate area of effect. The combination of its power and implicit use may be expedient, but isn’t without costs. Nix itself is unchanged, but the spirit of added dependencies being effect-free is violated even if the latter isn’t. For example, if a derivation path is mentioned more than once, Nix itself doesn’t care and makes sure the dependency derivation is already built just the same—depending is just needing something to exist, and needing is idempotent. However, a dependency specified twice will have its setup hook run twice, and that could easily change the build environment (though a well-written setup hook will therefore strive to be idempotent so this is in fact not observable). More broadly, setup hooks are anti-modular in that multiple dependencies, whether the same or different, should not interfere and yet their setup hooks may well do so.
1319
1320The most typical use of the setup hook is actually to add other hooks which are then run (i.e. after all the setup hooks) on each dependency. For example, the C compiler wrapper’s setup hook feeds itself flags for each dependency that contains relevant libraries and headers. This is done by defining a bash function, and appending its name to one of `envBuildBuildHooks`, `envBuildHostHooks`, `envBuildTargetHooks`, `envHostHostHooks`, `envHostTargetHooks`, or `envTargetTargetHooks`. These 6 bash variables correspond to the 6 sorts of dependencies by platform (there’s 12 total but we ignore the propagated/non-propagated axis).
1321
1322Packages adding a hook should not hard code a specific hook, but rather choose a variable *relative* to how they are included. Returning to the C compiler wrapper example, if the wrapper itself is an `n` dependency, then it only wants to accumulate flags from `n + 1` dependencies, as only those ones match the compiler’s target platform. The `hostOffset` variable is defined with the current dependency’s host offset `targetOffset` with its target offset, before its setup hook is sourced. Additionally, since most environment hooks don’t care about the target platform, that means the setup hook can append to the right bash array by doing something like
1323
1324```bash
1325addEnvHooks "$hostOffset" myBashFunction
1326```
1327
1328The *existence* of setups hooks has long been documented and packages inside Nixpkgs are free to use this mechanism. Other packages, however, should not rely on these mechanisms not changing between Nixpkgs versions. Because of the existing issues with this system, there’s little benefit from mandating it be stable for any period of time.
1329
1330First, let’s cover some setup hooks that are part of Nixpkgs default `stdenv`. This means that they are run for every package built using `stdenv.mkDerivation`, even with custom builders. Some of these are platform specific, so they may run on Linux but not Darwin or vice-versa.
1331
1332### `move-docs.sh` {#move-docs.sh}
1333
1334This setup hook moves any installed documentation to the `/share` subdirectory directory. This includes the man, doc and info directories. This is needed for legacy programs that do not know how to use the `share` subdirectory.
1335
1336### `compress-man-pages.sh` {#compress-man-pages.sh}
1337
1338This setup hook compresses any man pages that have been installed. The compression is done using the gzip program. This helps to reduce the installed size of packages.
1339
1340### `strip.sh` {#strip.sh}
1341
1342This runs the strip command on installed binaries and libraries. This removes unnecessary information like debug symbols when they are not needed. This also helps to reduce the installed size of packages.
1343
1344### `patch-shebangs.sh` {#patch-shebangs.sh}
1345
1346This setup hook patches installed scripts to add Nix store paths to their shebang interpreter as found in the build environment. The [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line tells a Unix-like operating system which interpreter to use to execute the script's contents.
1347
1348::: {.note}
1349The [generic builder][generic-builder] populates `PATH` from inputs of the derivation.
1350:::
1351
1352[generic-builder]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/stdenv/generic/builder.sh
1353
1354#### Invocation {#patch-shebangs.sh-invocation}
1355
1356Multiple paths can be specified.
1357
1358```
1359patchShebangs [--build | --host] PATH...
1360```
1361
1362##### Flags {#patch-shebangs.sh-invocation-flags}
1363
1364`--build`
1365: Look up commands available at build time
1366
1367`--host`
1368: Look up commands available at run time
1369
1370##### Examples {#patch-shebangs.sh-invocation-examples}
1371
1372```sh
1373patchShebangs --host /nix/store/<hash>-hello-1.0/bin
1374```
1375
1376```sh
1377patchShebangs --build configure
1378```
1379
1380`#!/bin/sh` will be rewritten to `#!/nix/store/<hash>-some-bash/bin/sh`.
1381
1382`#!/usr/bin/env` gets special treatment: `#!/usr/bin/env python` is rewritten to `/nix/store/<hash>/bin/python`.
1383
1384Interpreter paths that point to a valid Nix store location are not changed.
1385
1386::: {.note}
1387A script file must be marked as executable, otherwise it will not be
1388considered.
1389:::
1390
1391This mechanism ensures that the interpreter for a given script is always found and is exactly the one specified by the build.
1392
1393It can be disabled by setting [`dontPatchShebangs`](#var-stdenv-dontPatchShebangs):
1394
1395```nix
1396stdenv.mkDerivation {
1397 # ...
1398 dontPatchShebangs = true;
1399 # ...
1400}
1401```
1402
1403The file [`patch-shebangs.sh`][patch-shebangs.sh] defines the [`patchShebangs`][patchShebangs] function. It is used to implement [`patchShebangsAuto`][patchShebangsAuto], the [setup hook](#ssec-setup-hooks) that is registered to run during the [fixup phase](#ssec-fixup-phase) by default.
1404
1405If you need to run `patchShebangs` at build time, it must be called explicitly within [one of the build phases](#sec-stdenv-phases).
1406
1407[patch-shebangs.sh]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/build-support/setup-hooks/patch-shebangs.sh
1408[patchShebangs]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/build-support/setup-hooks/patch-shebangs.sh#L24-L105
1409[patchShebangsAuto]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/build-support/setup-hooks/patch-shebangs.sh#L107-L119
1410
1411### `audit-tmpdir.sh` {#audit-tmpdir.sh}
1412
1413This verifies that no references are left from the install binaries to the directory used to build those binaries. This ensures that the binaries do not need things outside the Nix store. This is currently supported in Linux only.
1414
1415### `multiple-outputs.sh` {#multiple-outputs.sh}
1416
1417This setup hook adds configure flags that tell packages to install files into any one of the proper outputs listed in `outputs`. This behavior can be turned off by setting `setOutputFlags` to false in the derivation environment. See [](#chap-multiple-output) for more information.
1418
1419### `move-sbin.sh` {#move-sbin.sh}
1420
1421This setup hook moves any binaries installed in the `sbin/` subdirectory into `bin/`. In addition, a link is provided from `sbin/` to `bin/` for compatibility.
1422
1423### `move-lib64.sh` {#move-lib64.sh}
1424
1425This setup hook moves any libraries installed in the `lib64/` subdirectory into `lib/`. In addition, a link is provided from `lib64/` to `lib/` for compatibility.
1426
1427### `move-systemd-user-units.sh` {#move-systemd-user-units.sh}
1428
1429This setup hook moves any systemd user units installed in the `lib/` subdirectory into `share/`. In addition, a link is provided from `share/` to `lib/` for compatibility. This is needed for systemd to find user services when installed into the user profile.
1430
1431This hook only runs when compiling for Linux.
1432
1433### `no-broken-symlinks.sh` {#no-broken-symlinks.sh}
1434
1435This setup hook checks for, reports, and (by default) fails builds when "broken" symlinks are found. A symlink is considered "broken" if it's dangling (the target doesn't exist) or reflexive (it refers to itself).
1436
1437This hook can be disabled by setting `dontCheckForBrokenSymlinks`.
1438
1439::: {.note}
1440The hook only considers symlinks with targets inside the Nix store or $TMPDIR directory (typically /nix/store and /build in the builder environment, the later being where build is executed).
1441:::
1442
1443::: {.note}
1444The check for reflexivity is direct and does not account for transitivity, so this hook will not prevent cycles in symlinks.
1445:::
1446
1447### `set-source-date-epoch-to-latest.sh` {#set-source-date-epoch-to-latest.sh}
1448
1449This sets `SOURCE_DATE_EPOCH` to the modification time of the most recent file.
1450
1451### `add-bin-to-path.sh` {#add-bin-to-path.sh}
1452
1453This setup hook checks if the `bin/` directory exists in the `$out` output path
1454and, if so, adds it to the `PATH` environment variable. This ensures that
1455executables located in `$out/bin` are accessible.
1456
1457This hook is particularly useful during testing, as it allows packages to locate their executables without requiring manual modifications to the `PATH`.
1458
1459**Note**: This hook is specifically designed for the `$out/bin` directory only
1460and does not handle and support other paths like `$sourceRoot/bin`. It may not
1461work as intended in cases with multiple outputs or when binaries are located in
1462directories like `sbin/`. These caveats should be considered when using this
1463hook, as they might introduce unexpected behavior in some specific cases.
1464
1465### `writable-tmpdir-as-home.sh` {#writable-tmpdir-as-home.sh}
1466
1467This setup hook ensures that the directory specified by the `HOME` environment
1468variable is writable. If it is not, the hook assigns `HOME` to a writable
1469directory (in `.home` in `$NIX_BUILD_TOP`). This adjustment is necessary for
1470certain packages that require write access to a home directory.
1471
1472By setting `HOME` to a writable directory, this setup hook prevents failures in
1473packages that attempt to write to the home directory.
1474
1475### Bintools Wrapper and hook {#bintools-wrapper}
1476
1477The Bintools Wrapper wraps the binary utilities for a bunch of miscellaneous purposes. These are GNU Binutils when targeting Linux, and a mix of cctools and GNU binutils for Darwin. \[The “Bintools” name is supposed to be a compromise between “Binutils” and “cctools” not denoting any specific implementation.\] Specifically, the underlying bintools package, and a C standard library (glibc or Darwin’s libSystem, just for the dynamic loader) are all fed in, and dependency finding, hardening (see below), and purity checks for each are handled by the Bintools Wrapper. Packages typically depend on CC Wrapper, which in turn (at run time) depends on the Bintools Wrapper.
1478
1479The Bintools Wrapper was only just recently split off from CC Wrapper, so the division of labor is still being worked out. For example, it shouldn’t care about the C standard library, but just take a derivation with the dynamic loader (which happens to be the glibc on linux). Dependency finding however is a task both wrappers will continue to need to share, and probably the most important to understand. It is currently accomplished by collecting directories of host-platform dependencies (i.e. `buildInputs` and `nativeBuildInputs`) in environment variables. The Bintools Wrapper’s setup hook causes any `lib` and `lib64` subdirectories to be added to `NIX_LDFLAGS`. Since the CC Wrapper and the Bintools Wrapper use the same strategy, most of the Bintools Wrapper code is sparsely commented and refers to the CC Wrapper. But the CC Wrapper’s code, by contrast, has quite lengthy comments. The Bintools Wrapper merely cites those, rather than repeating them, to avoid falling out of sync.
1480
1481A final task of the setup hook is defining a number of standard environment variables to tell build systems which executables fulfill which purpose. They are defined to just be the base name of the tools, under the assumption that the Bintools Wrapper’s binaries will be on the path. Firstly, this helps poorly-written packages, e.g. ones that look for just `gcc` when `CC` isn’t defined yet `clang` is to be used. Secondly, this helps packages not get confused when cross-compiling, in which case multiple Bintools Wrappers may simultaneously be in use. [^footnote-stdenv-per-platform-wrapper] `BUILD_`- and `TARGET_`-prefixed versions of the normal environment variable are defined for additional Bintools Wrappers, properly disambiguating them.
1482
1483A problem with this final task is that the Bintools Wrapper is honest and defines `LD` as `ld`. Most packages, however, firstly use the C compiler for linking, secondly use `LD` anyways, defining it as the C compiler, and thirdly, only so define `LD` when it is undefined as a fallback. This triple-threat means Bintools Wrapper will break those packages, as LD is already defined as the actual linker which the package won’t override yet doesn’t want to use. The workaround is to define, just for the problematic package, `LD` as the C compiler. A good way to do this would be `preConfigure = "LD=$CC"`.
1484
1485### CC Wrapper and hook {#cc-wrapper}
1486
1487The CC Wrapper wraps a C toolchain for a bunch of miscellaneous purposes. Specifically, a C compiler (GCC or Clang), wrapped binary tools, and a C standard library (glibc or Darwin’s libSystem, just for the dynamic loader) are all fed in, and dependency finding, hardening (see below), and purity checks for each are handled by the CC Wrapper. Packages typically depend on the CC Wrapper, which in turn (at run-time) depends on the Bintools Wrapper.
1488
1489Dependency finding is undoubtedly the main task of the CC Wrapper. This works just like the Bintools Wrapper, except that any `include` subdirectory of any relevant dependency is added to `NIX_CFLAGS_COMPILE`. The setup hook itself contains elaborate comments describing the exact mechanism by which this is accomplished.
1490
1491Similarly, the CC Wrapper follows the Bintools Wrapper in defining standard environment variables with the names of the tools it wraps, for the same reasons described above. Importantly, while it includes a `cc` symlink to the c compiler for portability, the `CC` will be defined using the compiler’s “real name” (i.e. `gcc` or `clang`). This helps lousy build systems that inspect on the name of the compiler rather than run it.
1492
1493Here are some more packages that provide a setup hook. Since the list of hooks is extensible, this is not an exhaustive list. The mechanism is only to be used as a last resort, so it might cover most uses.
1494
1495### Other hooks {#stdenv-other-hooks}
1496
1497Many other packages provide hooks, that are not part of `stdenv`. You can find
1498these in the [Hooks Reference](#chap-hooks).
1499
1500### Compiler and Linker wrapper hooks {#compiler-linker-wrapper-hooks}
1501
1502If the file `${cc}/nix-support/cc-wrapper-hook` exists, it will be run at the end of the [compiler wrapper](#cc-wrapper).
1503If the file `${binutils}/nix-support/ld-wrapper-hook` exists, it will be run at the end of the linker wrapper, before the linker runs.
1504If the file `${binutils}/nix-support/post-link-hook` exists, it will be run at the end of the linker wrapper.
1505These hooks allow a user to inject code into the wrappers.
1506As an example, these hooks can be used to extract `extraBefore`, `params` and `extraAfter` which store all the command line arguments passed to the compiler and linker respectively.
1507
1508## Purity in Nixpkgs {#sec-purity-in-nixpkgs}
1509
1510*Measures taken to prevent dependencies on packages outside the store, and what you can do to prevent them.*
1511
1512GCC doesn’t search in locations such as `/usr/include`. In fact, attempts to add such directories through the `-I` flag are filtered out. Likewise, the linker (from GNU binutils) doesn’t search in standard locations such as `/usr/lib`. Programs built on Linux are linked against a GNU C Library that likewise doesn’t search in the default system locations.
1513
1514## Hardening in Nixpkgs {#sec-hardening-in-nixpkgs}
1515
1516There are flags available to harden packages at compile or link-time. These can be toggled using the `stdenv.mkDerivation` parameters `hardeningDisable` and `hardeningEnable`.
1517
1518Both parameters take a list of flags as strings. The special `"all"` flag can be passed to `hardeningDisable` to turn off all hardening. These flags can also be used as environment variables for testing or development purposes.
1519
1520For more in-depth information on these hardening flags and hardening in general, refer to the [Debian Wiki](https://wiki.debian.org/Hardening), [Ubuntu Wiki](https://wiki.ubuntu.com/Security/Features), [Gentoo Wiki](https://wiki.gentoo.org/wiki/Project:Hardened), and the [Arch Wiki](https://wiki.archlinux.org/title/Security).
1521
1522Note that support for some hardening flags varies by compiler, CPU architecture, target OS and libc. Combinations of these that don't support a particular hardening flag will silently ignore attempts to enable it. To see exactly which hardening flags are being employed in any invocation, the `NIX_DEBUG` environment variable can be used.
1523
1524### Hardening flags enabled by default {#sec-hardening-flags-enabled-by-default}
1525
1526The following flags are enabled by default and might require disabling with `hardeningDisable` if the program to be packaged is incompatible.
1527
1528#### `format` {#format}
1529
1530Adds the `-Wformat -Wformat-security -Werror=format-security` compiler options. At present, this warns about calls to `printf` and `scanf` functions where the format string is not a string literal and there are no format arguments, as in `printf(foo);`. This may be a security hole if the format string came from untrusted input and contains `%n`.
1531
1532This needs to be turned off or fixed for errors similar to:
1533
1534```
1535/tmp/nix-build-zynaddsubfx-2.5.2.drv-0/zynaddsubfx-2.5.2/src/UI/guimain.cpp:571:28: error: format not a string literal and no format arguments [-Werror=format-security]
1536 printf(help_message);
1537 ^
1538cc1plus: some warnings being treated as errors
1539```
1540
1541#### `stackprotector` {#stackprotector}
1542
1543Adds the `-fstack-protector-strong --param ssp-buffer-size=4` compiler options. This adds safety checks against stack overwrites rendering many potential code injection attacks into aborting situations. In the best case this turns code injection vulnerabilities into denial of service or into non-issues (depending on the application).
1544
1545This needs to be turned off or fixed for errors similar to:
1546
1547```
1548bin/blib.a(bios_console.o): In function `bios_handle_cup':
1549/tmp/nix-build-ipxe-20141124-5cbdc41.drv-0/ipxe-5cbdc41/src/arch/i386/firmware/pcbios/bios_console.c:86: undefined reference to `__stack_chk_fail'
1550```
1551
1552#### `fortify` {#fortify}
1553
1554Adds the `-O2 -D_FORTIFY_SOURCE=2` compiler options. During code generation the compiler knows a great deal of information about buffer sizes (where possible), and attempts to replace insecure unlimited length buffer function calls with length-limited ones. This is especially useful for old, crufty code. Additionally, format strings in writable memory that contain `%n` are blocked. If an application depends on such a format string, it will need to be worked around.
1555
1556Additionally, some warnings are enabled which might trigger build failures if compiler warnings are treated as errors in the package build. In this case, set `env.NIX_CFLAGS_COMPILE` to `-Wno-error=warning-type`.
1557
1558This needs to be turned off or fixed for errors similar to:
1559
1560```
1561malloc.c:404:15: error: return type is an incomplete type
1562malloc.c:410:19: error: storage size of 'ms' isn't known
1563
1564strdup.h:22:1: error: expected identifier or '(' before '__extension__'
1565
1566strsep.c:65:23: error: register name not specified for 'delim'
1567
1568installwatch.c:3751:5: error: conflicting types for '__open_2'
1569
1570fcntl2.h:50:4: error: call to '__open_missing_mode' declared with attribute error: open with O_CREAT or O_TMPFILE in second argument needs 3 arguments
1571```
1572
1573Disabling `fortify` implies disablement of `fortify3`
1574
1575#### `fortify3` {#fortify3}
1576
1577Adds the `-O2 -D_FORTIFY_SOURCE=3` compiler options. This expands the cases that can be protected by fortify-checks to include some situations with dynamic-length buffers whose length can be inferred at runtime using compiler hints.
1578
1579Enabling this flag implies enablement of `fortify`. Disabling this flag does not imply disablement of `fortify`.
1580
1581This flag can sometimes conflict with a build-system's own attempts at enabling fortify support and result in errors complaining about `redefinition of _FORTIFY_SOURCE`.
1582
1583#### `pic` {#pic}
1584
1585Adds the `-fPIC` compiler options. This options adds support for position independent code in shared libraries and thus making ASLR possible.
1586
1587Most notably, the Linux kernel, kernel modules and other code not running in an operating system environment like boot loaders won’t build with PIC enabled. The compiler will is most cases complain that PIC is not supported for a specific build.
1588
1589This needs to be turned off or fixed for assembler errors similar to:
1590
1591```
1592ccbLfRgg.s: Assembler messages:
1593ccbLfRgg.s:33: Error: missing or invalid displacement expression `private_key_len@GOTOFF'
1594```
1595
1596#### `strictoverflow` {#strictoverflow}
1597
1598Signed integer overflow is undefined behaviour according to the C standard. If it happens, it is an error in the program as it should check for overflow before it can happen, not afterwards. GCC provides built-in functions to perform arithmetic with overflow checking, which are correct and faster than any custom implementation. As a workaround, the option `-fno-strict-overflow` makes gcc behave as if signed integer overflows were defined.
1599
1600This flag should not trigger any build or runtime errors.
1601
1602#### `relro` {#relro}
1603
1604Adds the `-z relro` linker option. During program load, several ELF memory sections need to be written to by the linker, but can be turned read-only before turning over control to the program. This prevents some GOT (and .dtors) overwrite attacks, but at least the part of the GOT used by the dynamic linker (.got.plt) is still vulnerable.
1605
1606This flag can break dynamic shared object loading. For instance, the module systems of Xorg and OpenCV are incompatible with this flag. In almost all cases the `bindnow` flag must also be disabled and incompatible programs typically fail with similar errors at runtime.
1607
1608#### `bindnow` {#bindnow}
1609
1610Adds the `-z now` linker option. During program load, all dynamic symbols are resolved, allowing for the complete GOT to be marked read-only (due to `relro`). This prevents GOT overwrite attacks. For very large applications, this can incur some performance loss during initial load while symbols are resolved, but this shouldn’t be an issue for daemons.
1611
1612This flag can break dynamic shared object loading. For instance, the module systems of Xorg and PHP are incompatible with this flag. Programs incompatible with this flag often fail at runtime due to missing symbols, like:
1613
1614```
1615intel_drv.so: undefined symbol: vgaHWFreeHWRec
1616```
1617
1618#### `zerocallusedregs` {#zerocallusedregs}
1619
1620Adds the `-fzero-call-used-regs=used-gpr` compiler option. This causes the general-purpose registers that an architecture's calling convention considers "call-used" to be zeroed on return from the function. This can make it harder for attackers to construct useful ROP gadgets and also reduces the chance of data leakage from a function call.
1621
1622#### `stackclashprotection` {#stackclashprotection}
1623
1624This flag adds the `-fstack-clash-protection` compiler option, which causes growth of a program's stack to access each successive page in order. This should force the guard page to be accessed and cause an attempt to "jump over" this guard page to crash.
1625
1626### Hardening flags disabled by default {#sec-hardening-flags-disabled-by-default}
1627
1628The following flags are disabled by default and should be enabled with `hardeningEnable` for packages that take untrusted input like network services.
1629
1630#### `nostrictaliasing` {#nostrictaliasing}
1631
1632This flag adds the `-fno-strict-aliasing` compiler option, which prevents the compiler from assuming code has been written strictly following the standard in regards to pointer aliasing and therefore performing optimizations that may be unsafe for code that has not followed these rules.
1633
1634#### `pie` {#pie}
1635
1636This flag is disabled by default for normal `glibc` based NixOS package builds, but enabled by default for
1637
1638 - `musl`-based package builds, except on Aarch64 and Aarch32, where there are issues.
1639
1640 - Statically-linked for OpenBSD builds, where it appears to be required to get a working binary.
1641
1642Adds the `-fPIE` compiler and `-pie` linker options. Position Independent Executables are needed to take advantage of Address Space Layout Randomization, supported by modern kernel versions. While ASLR can already be enforced for data areas in the stack and heap (brk and mmap), the code areas must be compiled as position-independent. Shared libraries already do this with the `pic` flag, so they gain ASLR automatically, but binary .text regions need to be build with `pie` to gain ASLR. When this happens, ROP attacks are much harder since there are no static locations to bounce off of during a memory corruption attack.
1643
1644Static libraries need to be compiled with `-fPIE` so that executables can link them in with the `-pie` linker option.
1645If the libraries lack `-fPIE`, you will get the error `recompile with -fPIE`.
1646
1647#### `strictflexarrays1` {#strictflexarrays1}
1648
1649This flag adds the `-fstrict-flex-arrays=1` compiler option, which reduces the cases the compiler treats as "flexible arrays" to those declared with length `[1]`, `[0]` or (the correct) `[]`. This increases the coverage of fortify checks, because such arrays declared as the trailing element of a structure can normally not have their intended length determined by the compiler.
1650
1651Enabling this flag on packages that still use length declarations of flexible arrays >1 may cause the package to fail to compile citing accesses beyond the bounds of an array or even crash at runtime by detecting an array access as an "overrun". Few projects still use length declarations of flexible arrays >1.
1652
1653Disabling `strictflexarrays1` implies disablement of `strictflexarrays3`.
1654
1655#### `strictflexarrays3` {#strictflexarrays3}
1656
1657This flag adds the `-fstrict-flex-arrays=3` compiler option, which reduces the cases the compiler treats as "flexible arrays" to only those declared with length as (the correct) `[]`. This increases the coverage of fortify checks, because such arrays declared as the trailing element of a structure can normally not have their intended length determined by the compiler.
1658
1659Enabling this flag on packages that still use non-empty length declarations for flexible arrays may cause the package to fail to compile citing accesses beyond the bounds of an array or even crash at runtime by detecting an array access as an "overrun". Many projects still use such non-empty length declarations for flexible arrays.
1660
1661Enabling this flag implies enablement of `strictflexarrays1`. Disabling this flag does not imply disablement of `strictflexarrays1`.
1662
1663#### `shadowstack` {#shadowstack}
1664
1665Adds the `-fcf-protection=return` compiler option. This enables the Shadow Stack feature supported by some newer processors, which maintains a user-inaccessible copy of the program's stack containing only return-addresses. When returning from a function, the processor compares the return-address value on the two stacks and throws an error if they do not match, considering it a sign of corruption and possible tampering. This should significantly increase the difficulty of ROP attacks.
1666
1667For the Shadow Stack to be enabled at runtime, all code linked into a process must be built with Shadow Stack enabled, so this is probably only useful to enable on a wide scale, so that all of a packages dependencies also have the feature enabled.
1668
1669This is currently only supported on some newer Intel and AMD processors as part of the Intel CET set of features. However, the generated code should continue to work on older processors which will simply omit any of this checking.
1670
1671This breaks some code that does advanced stack management or exception handling. If enabling this hardening flag it is important to test the result on a system that has known working and enabled CET support, so that any such breakage can be discovered.
1672
1673#### `trivialautovarinit` {#trivialautovarinit}
1674
1675Adds the `-ftrivial-auto-var-init=pattern` compiler option. Uninitialized variables generally take on their values based on fragments of previous program state, and attackers can carefully manipulate that state to craft malicious initial values for these variables. This flag causes "trivially-initializable" uninitialized stack variables to be forcibly initialized with a nonzero value that is likely to cause a crash (and therefore be noticed).
1676
1677Use of this flag is controversial as it can prevent tools that detect uninitialized variable use (such as valgrind) from operating correctly.
1678
1679This should be turned off or fixed for build errors such as:
1680
1681```
1682sorry, unimplemented: __builtin_clear_padding not supported for variable length aggregates
1683```
1684
1685#### `glibcxxassertions` {#glibcxxassertions}
1686
1687Adds the `-D_GLIBCXX_ASSERTIONS` compiler flag. This flag only has an effect on libstdc++ targets, and when defined, enables extra error checking in the form of precondition assertions, such as bounds checking in c++ strings and null pointer checks when dereferencing c++ smart pointers.
1688
1689These checks may have an impact on performance in some cases.
1690
1691#### `pacret` {#pacret}
1692
1693This flag adds the `-mbranch-protection=pac-ret` compiler option on aarch64-linux targets. This uses ARM v8.3's Pointer Authentication feature to sign function return pointers before adding them to the stack. The pointer's authenticity is then validated before returning to its destination. This dramatically increases the difficulty of ROP exploitation techniques.
1694
1695This may cause problems with code that does advanced stack manipulation, and debugging/stack-unwinding tools need to be pac-ret aware to work correctly when these features are in operation.
1696
1697Pre-ARM v8.3 processors will ignore Pointer Authentication instructions, so code built with this flag will continue to work on older processors, though without any of the intended protections. If enabling this flag, it is recommended to ensure the resultant packages are tested against an ARM v8.3+ linux system with known-working Pointer Authentication support so that any breakage caused by this feature is actually detected.
1698
1699[^footnote-stdenv-ignored-build-platform]: The build platform is ignored because it is a mere implementation detail of the package satisfying the dependency: As a general programming principle, dependencies are always *specified* as interfaces, not concrete implementation.
1700[^footnote-stdenv-native-dependencies-in-path]: Currently, this means for native builds all dependencies are put on the `PATH`. But in the future that may not be the case for sake of matching cross: the platforms would be assumed to be unique for native and cross builds alike, so only the `depsBuild*` and `nativeBuildInputs` would be added to the `PATH`.
1701[^footnote-stdenv-propagated-dependencies]: Nix itself already takes a package’s transitive dependencies into account, but this propagation ensures nixpkgs-specific infrastructure like [setup hooks](#ssec-setup-hooks) also are run as if it were a propagated dependency.
1702[^footnote-stdenv-find-inputs-location]: The `findInputs` function, currently residing in `pkgs/stdenv/generic/setup.sh`, implements the propagation logic.
1703[^footnote-stdenv-sys-lib-search-path]: It clears the `sys_lib_*search_path` variables in the Libtool script to prevent Libtool from using libraries in `/usr/lib` and such.
1704[^footnote-stdenv-build-time-guessing-impurity]: Eventually these will be passed building natively as well, to improve determinism: build-time guessing, as is done today, is a risk of impurity.
1705[^footnote-stdenv-per-platform-wrapper]: Each wrapper targets a single platform, so if binaries for multiple platforms are needed, the underlying binaries must be wrapped multiple times. As this is a property of the wrapper itself, the multiple wrappings are needed whether or not the same underlying binaries can target multiple platforms.