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 rec {
24 pname = "libfoo";
25 version = "1.2.3";
26 src = fetchurl {
27 url = "http://example.org/libfoo-source-${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 = [libbar perl ncurses];
41}
42```
43
44This 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.)
45
46Often 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:
47
48```nix
49stdenv.mkDerivation {
50 pname = "fnord";
51 version = "4.5";
52 ...
53 buildPhase = ''
54 gcc foo.c -o foo
55 '';
56 installPhase = ''
57 mkdir -p $out/bin
58 cp foo $out/bin
59 '';
60}
61```
62
63(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.)
64
65There are many other attributes to customise the build. These are listed in [](#ssec-stdenv-attributes).
66
67While the standard environment provides a generic builder, you can still supply your own build script:
68
69```nix
70stdenv.mkDerivation {
71 pname = "libfoo";
72 version = "1.2.3";
73 ...
74 builder = ./builder.sh;
75}
76```
77
78where the builder can do anything it wants, but typically starts with
79
80```bash
81source $stdenv/setup
82```
83
84to let `stdenv` set up the environment (e.g. by resetting `PATH` and populating it from build inputs). If you want, you can still use `stdenv`’s generic builder:
85
86```bash
87source $stdenv/setup
88
89buildPhase() {
90 echo "... this is my custom build phase ..."
91 gcc foo.c -o foo
92}
93
94installPhase() {
95 mkdir -p $out/bin
96 cp foo $out/bin
97}
98
99genericBuild
100```
101
102### Building a `stdenv` package in `nix-shell` {#sec-building-stdenv-package-in-nix-shell}
103
104To build a `stdenv` package in a [`nix-shell`](https://nixos.org/manual/nix/unstable/command-ref/nix-shell.html), use
105
106```bash
107nix-shell '<nixpkgs>' -A some_package
108eval "${unpackPhase:-unpackPhase}"
109cd $sourceRoot
110eval "${patchPhase:-patchPhase}"
111eval "${configurePhase:-configurePhase}"
112eval "${buildPhase:-buildPhase}"
113```
114
115To modify a [phase](#sec-stdenv-phases), first print it with
116
117```bash
118type buildPhase
119```
120
121then change it in a text editor, and paste it back to the terminal.
122
123## Tools provided by `stdenv` {#sec-tools-of-stdenv}
124
125The standard environment provides the following packages:
126
127- The GNU C Compiler, configured with C and C++ support.
128- GNU coreutils (contains a few dozen standard Unix commands).
129- GNU findutils (contains `find`).
130- GNU diffutils (contains `diff`, `cmp`).
131- GNU `sed`.
132- GNU `grep`.
133- GNU `awk`.
134- GNU `tar`.
135- `gzip`, `bzip2` and `xz`.
136- GNU Make.
137- 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.
138- The `patch` command.
139
140On Linux, `stdenv` also includes the `patchelf` utility.
141
142## Specifying dependencies {#ssec-stdenv-dependencies}
143
144Build 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.
145
146### Overview {#ssec-stdenv-dependencies-overview}
147
148A 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.
149It should cover most use cases.
150
151Add dependencies to `nativeBuildInputs` if they are executed during the build:
152- those which are needed on `$PATH` during the build, for example `cmake` and `pkg-config`
153- [setup hooks](#ssec-setup-hooks), for example [`makeWrapper`](#fun-makeWrapper)
154- interpreters needed by [`patchShebangs`](#patch-shebangs.sh) for build scripts (with the `--build` flag), which can be the case for e.g. `perl`
155
156Add dependencies to `buildInputs` if they will end up copied or linked into the final output or otherwise used at runtime:
157- libraries used by compilers, for example `zlib`,
158- interpreters needed by [`patchShebangs`](#patch-shebangs.sh) for scripts which are installed, which can be the case for e.g. `perl`
159
160::: {.note}
161These criteria are independent.
162
163For example, software using Wayland usually needs the `wayland` library at runtime, so `wayland` should be added to `buildInputs`.
164But it also executes the `wayland-scanner` program as part of the build to generate code, so `wayland` should also be added to `nativeBuildInputs`.
165:::
166
167Dependencies needed only to run tests are similarly classified between native (executed during build) and non-native (executed at runtime):
168- `nativeCheckInputs` for test tools needed on `$PATH` (such as `ctest`) and [setup hooks](#ssec-setup-hooks) (for example [`pytestCheckHook`](#python))
169- `checkInputs` for libraries linked into test executables (for example the `qcheck` OCaml package)
170
171These dependencies are only injected when [`doCheck`](#var-stdenv-doCheck) is set to `true`.
172
173#### Example {#ssec-stdenv-dependencies-overview-example}
174
175Consider for example this simplified derivation for `solo5`, a sandboxing tool:
176```nix
177stdenv.mkDerivation rec {
178 pname = "solo5";
179 version = "0.7.5";
180
181 src = fetchurl {
182 url = "https://github.com/Solo5/solo5/releases/download/v${version}/solo5-v${version}.tar.gz";
183 sha256 = "sha256-viwrS9lnaU8sTGuzK/+L/PlMM/xRRtgVuK5pixVeDEw=";
184 };
185
186 nativeBuildInputs = [ makeWrapper pkg-config ];
187 buildInputs = [ libseccomp ];
188
189 postInstall = ''
190 substituteInPlace $out/bin/solo5-virtio-mkimage \
191 --replace "/usr/lib/syslinux" "${syslinux}/share/syslinux" \
192 --replace "/usr/share/syslinux" "${syslinux}/share/syslinux" \
193 --replace "cp " "cp --no-preserve=mode "
194
195 wrapProgram $out/bin/solo5-virtio-mkimage \
196 --prefix PATH : ${lib.makeBinPath [ dosfstools mtools parted syslinux ]}
197 '';
198
199 doCheck = true;
200 nativeCheckInputs = [ util-linux qemu ];
201 checkPhase = '' [elided] '';
202}
203```
204
205- `makeWrapper` is a setup hook, i.e., a shell script sourced by the generic builder of `stdenv`.
206 It is thus executed during the build and must be added to `nativeBuildInputs`.
207- `pkg-config` is a build tool which the configure script of `solo5` expects to be on `$PATH` during the build:
208 therefore, it must be added to `nativeBuildInputs`.
209- `libseccomp` is a library linked into `$out/bin/solo5-elftool`.
210 As it is used at runtime, it must be added to `buildInputs`.
211- Tests need `qemu` and `getopt` (from `util-linux`) on `$PATH`, these must be added to `nativeCheckInputs`.
212- Some dependencies are injected directly in the shell code of phases: `syslinux`, `dosfstools`, `mtools`, and `parted`.
213In this specific case, they will end up in the output of the derivation (`$out` here).
214As Nix marks dependencies whose absolute path is present in the output as runtime dependencies, adding them to `buildInputs` is not required.
215
216For more complex cases, like libraries linked into an executable which is then executed as part of the build system, see [](#ssec-stdenv-dependencies-reference).
217
218### Reference {#ssec-stdenv-dependencies-reference}
219
220As 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.
221
222Dependencies can be broken down along three axes: their host and target platforms relative to the new derivation’s, and whether they are propagated. 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 or not the dependency is needed at run-time or build-time, a concept that makes perfect sense outside of cross compilation. By default, the run-time/build-time distinction is just a hint for mental clarity, but with `strictDeps` set it is mostly enforced even in the native case.
223
224The 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.
225
226A dependency is said to be **propagated** when some of its other-transitive (non-immediate) downstream dependencies also need it as an immediate dependency.
227[^footnote-stdenv-propagated-dependencies]
228
229It is important to note that dependencies are not necessarily propagated as the same sort of dependency that they were before, but rather as the corresponding sort so that the platform rules still line up. To 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:
230
231| `host → target` | attribute name | offset |
232| ------------------- | ------------------- | -------- |
233| `build --> build` | `depsBuildBuild` | `-1, -1` |
234| `build --> host` | `nativeBuildInputs` | `-1, 0` |
235| `build --> target` | `depsBuildTarget` | `-1, 1` |
236| `host --> host` | `depsHostHost` | `0, 0` |
237| `host --> target` | `buildInputs` | `0, 1` |
238| `target --> target` | `depsTargetTarget` | `1, 1` |
239
240Algorithmically, 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 is sort of a 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.
241
242We can define the process precisely with [Natural Deduction](https://en.wikipedia.org/wiki/Natural_deduction) using the inference rules. 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!
243
244```
245let mapOffset(h, t, i) = i + (if i <= 0 then h else t - 1)
246
247propagated-dep(h0, t0, A, B)
248propagated-dep(h1, t1, B, C)
249h0 + h1 in {-1, 0, 1}
250h0 + t1 in {-1, 0, 1}
251-------------------------------------- Transitive property
252propagated-dep(mapOffset(h0, t0, h1),
253 mapOffset(h0, t0, t1),
254 A, C)
255```
256
257```
258let mapOffset(h, t, i) = i + (if i <= 0 then h else t - 1)
259
260dep(h0, t0, A, B)
261propagated-dep(h1, t1, B, C)
262h0 + h1 in {-1, 0, 1}
263h0 + t1 in {-1, 0, -1}
264----------------------------- Take immediate dependencies' propagated dependencies
265propagated-dep(mapOffset(h0, t0, h1),
266 mapOffset(h0, t0, t1),
267 A, C)
268```
269
270```
271propagated-dep(h, t, A, B)
272----------------------------- Propagated dependencies count as dependencies
273dep(h, t, A, B)
274```
275
276Some explanation of this monstrosity is in order. In the common case, the target offset of a dependency is the successor to the target offset: `t = h + 1`. That means that:
277
278```
279let f(h, t, i) = i + (if i <= 0 then h else t - 1)
280let f(h, h + 1, i) = i + (if i <= 0 then h else (h + 1) - 1)
281let f(h, h + 1, i) = i + (if i <= 0 then h else h)
282let f(h, h + 1, i) = i + h
283```
284
285This 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 simply 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.
286
287Because of the bounds checks, the uncommon cases are `h = t` and `h + 2 = t`. In 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. In the other case, `h + 1` is skipped over between the host and target offsets. Instead of squashing the offsets, we need to “rip” them apart so no transitive dependencies’ offset is that one.
288
289Overall, 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 dependending 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 unforagable 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.
290
291#### Variables specifying dependencies {#variables-specifying-dependencies}
292
293##### `depsBuildBuild` {#var-stdenv-depsBuildBuild}
294
295A 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.
296
297Since 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.
298
299##### `nativeBuildInputs` {#var-stdenv-nativeBuildInputs}
300
301A 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.
302
303Since 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.
304
305##### `depsBuildTarget` {#var-stdenv-depsBuildTarget}
306
307A 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.
308
309This 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.
310
311Since 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.
312
313##### `depsHostHost` {#var-stdenv-depsHostHost}
314
315A 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.
316
317##### `buildInputs` {#var-stdenv-buildInputs}
318
319A 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`.
320
321These 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.
322
323##### `depsTargetTarget` {#var-stdenv-depsTargetTarget}
324
325A 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.
326
327##### `depsBuildBuildPropagated` {#var-stdenv-depsBuildBuildPropagated}
328
329The propagated equivalent of `depsBuildBuild`. This perhaps never ought to be used, but it is included for consistency \[see below for the others\].
330
331##### `propagatedNativeBuildInputs` {#var-stdenv-propagatedNativeBuildInputs}
332
333The 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`. If instead, package `Z` has `nativeBuildInputs = [Y]`, then `Z` will be built as if it included `X` in the `depsBuildBuild` of package `Z`, because of the sum of the two `-1` host offsets.
334
335##### `depsBuildTargetPropagated` {#var-stdenv-depsBuildTargetPropagated}
336
337The propagated equivalent of `depsBuildTarget`. This is prefixed for the same reason of alerting potential users.
338
339##### `depsHostHostPropagated` {#var-stdenv-depsHostHostPropagated}
340
341The propagated equivalent of `depsHostHost`.
342
343##### `propagatedBuildInputs` {#var-stdenv-propagatedBuildInputs}
344
345The propagated equivalent of `buildInputs`. This would be called `depsHostTargetPropagated` but for historical continuity.
346
347##### `depsTargetTargetPropagated` {#var-stdenv-depsTargetTargetPropagated}
348
349The propagated equivalent of `depsTargetTarget`. This is prefixed for the same reason of alerting potential users.
350
351## Attributes {#ssec-stdenv-attributes}
352
353### Variables affecting `stdenv` initialisation {#variables-affecting-stdenv-initialisation}
354
355#### `NIX_DEBUG` {#var-stdenv-NIX_DEBUG}
356
357A 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.
358
359### Attributes affecting build properties {#attributes-affecting-build-properties}
360
361#### `enableParallelBuilding` {#var-stdenv-enableParallelBuilding}
362
363If set to `true`, `stdenv` will pass specific flags to `make` and other build tools to enable parallel building with up to `build-cores` workers.
364
365Unless set to `false`, some build systems with good support for parallel building including `cmake`, `meson`, and `qmake` will set it to `true`.
366
367### Special variables {#special-variables}
368
369#### `passthru` {#var-stdenv-passthru}
370
371This is an attribute set which can be filled with arbitrary values. For example:
372
373```nix
374passthru = {
375 foo = "bar";
376 baz = {
377 value1 = 4;
378 value2 = 5;
379 };
380}
381```
382
383Values inside it are not passed to the builder, so you can change them without triggering a rebuild. However, they can be accessed outside of a derivation directly, as if they were set inside a derivation itself, e.g. `hello.baz.value1`. We don’t specify any usage or schema of `passthru` - it is meant for values that would be useful outside the derivation in other parts of a Nix expression (e.g. in other derivations). An example would be to convey some specific dependency of your derivation which contains a program with plugins support. Later, others who make derivations with plugins can use passed-through dependency to ensure that their plugin would be binary-compatible with built program.
384
385#### `passthru.updateScript` {#var-passthru-updateScript}
386
387A script to be run by `maintainers/scripts/update.nix` when the package is matched. The attribute can contain one of the following:
388
389- []{#var-passthru-updateScript-command} an executable file, either on the file system:
390
391 ```nix
392 passthru.updateScript = ./update.sh;
393 ```
394
395 or inside the expression itself:
396
397 ```nix
398 passthru.updateScript = writeScript "update-zoom-us" ''
399 #!/usr/bin/env nix-shell
400 #!nix-shell -i bash -p curl pcre common-updater-scripts
401
402 set -eu -o pipefail
403
404 version="$(curl -sI https://zoom.us/client/latest/zoom_x86_64.tar.xz | grep -Fi 'Location:' | pcregrep -o1 '/(([0-9]\.?)+)/')"
405 update-source-version zoom-us "$version"
406 '';
407 ```
408
409- a list, a script followed by arguments to be passed to it:
410
411 ```nix
412 passthru.updateScript = [ ../../update.sh pname "--requested-release=unstable" ];
413 ```
414
415- an attribute set containing:
416 - [`command`]{#var-passthru-updateScript-set-command} – a string or list in the [format expected by `passthru.updateScript`](#var-passthru-updateScript-command).
417 - [`attrPath`]{#var-passthru-updateScript-set-attrPath} (optional) – a string containing the canonical attribute path for the package. If present, it will be passed to the update script instead of the attribute path on which the package was discovered during Nixpkgs traversal.
418 - [`supportedFeatures`]{#var-passthru-updateScript-set-supportedFeatures} (optional) – a list of the [extra features](#var-passthru-updateScript-supported-features) the script supports.
419
420 ```nix
421 passthru.updateScript = {
422 command = [ ../../update.sh pname ];
423 attrPath = pname;
424 supportedFeatures = [ … ];
425 };
426 ```
427
428##### How update scripts are executed? {#var-passthru-updateScript-execution}
429
430Update scripts are to be invoked by `maintainers/scripts/update.nix` script. You can run `nix-shell maintainers/scripts/update.nix` in the root of Nixpkgs repository for information on how to use it. `update.nix` offers several modes for selecting packages to update (e.g. select by attribute path, traverse Nixpkgs and filter by maintainer, etc.), and it will execute update scripts for all matched packages that have an `updateScript` attribute.
431
432Each update script will be passed the following environment variables:
433
434- [`UPDATE_NIX_NAME`]{#var-passthru-updateScript-env-UPDATE_NIX_NAME} – content of the `name` attribute of the updated package.
435- [`UPDATE_NIX_PNAME`]{#var-passthru-updateScript-env-UPDATE_NIX_PNAME} – content of the `pname` attribute of the updated package.
436- [`UPDATE_NIX_OLD_VERSION`]{#var-passthru-updateScript-env-UPDATE_NIX_OLD_VERSION} – content of the `version` attribute of the updated package.
437- [`UPDATE_NIX_ATTR_PATH`]{#var-passthru-updateScript-env-UPDATE_NIX_ATTR_PATH} – attribute path the `update.nix` discovered the package on (or the [canonical `attrPath`](#var-passthru-updateScript-set-attrPath) when available). Example: `pantheon.elementary-terminal`
438
439::: {.note}
440An update script will be usually run from the root of the Nixpkgs repository but you should not rely on that. Also note that `update.nix` executes update scripts in parallel by default so you should avoid running `git commit` or any other commands that cannot handle that.
441:::
442
443::: {.tip}
444While update scripts should not create commits themselves, `maintainers/scripts/update.nix` supports automatically creating commits when running it with `--argstr commit true`. If you need to customize commit message, you can have the update script implement [`commit`](#var-passthru-updateScript-commit) feature.
445:::
446
447##### Supported features {#var-passthru-updateScript-supported-features}
448###### `commit` {#var-passthru-updateScript-commit}
449
450This feature allows update scripts to *ask* `update.nix` to create Git commits.
451
452When support of this feature is declared, whenever the update script exits with `0` return status, it is expected to print a JSON list containing an object described below for each updated attribute to standard output.
453
454When `update.nix` is run with `--argstr commit true` arguments, it will create a separate commit for each of the objects. An empty list can be returned when the script did not update any files, for example, when the package is already at the latest version.
455
456The commit object contains the following values:
457
458- [`attrPath`]{#var-passthru-updateScript-commit-attrPath} – a string containing attribute path.
459- [`oldVersion`]{#var-passthru-updateScript-commit-oldVersion} – a string containing old version.
460- [`newVersion`]{#var-passthru-updateScript-commit-newVersion} – a string containing new version.
461- [`files`]{#var-passthru-updateScript-commit-files} – a non-empty list of file paths (as strings) to add to the commit.
462- [`commitBody`]{#var-passthru-updateScript-commit-commitBody} (optional) – a string with extra content to be appended to the default commit message (useful for adding changelog links).
463- [`commitMessage`]{#var-passthru-updateScript-commit-commitMessage} (optional) – a string to use instead of the default commit message.
464
465If the returned array contains exactly one object (e.g. `[{}]`), all values are optional and will be determined automatically.
466
467```{=docbook}
468<example>
469<title>Standard output of an update script using commit feature</title>
470```
471
472```json
473[
474 {
475 "attrPath": "volume_key",
476 "oldVersion": "0.3.11",
477 "newVersion": "0.3.12",
478 "files": [
479 "/path/to/nixpkgs/pkgs/development/libraries/volume-key/default.nix"
480 ]
481 }
482]
483```
484
485```{=docbook}
486</example>
487```
488
489### Recursive attributes in `mkDerivation` {#mkderivation-recursive-attributes}
490
491If you pass a function to `mkDerivation`, it will receive as its argument the final arguments, including the overrides when reinvoked via `overrideAttrs`. For example:
492
493```nix
494mkDerivation (finalAttrs: {
495 pname = "hello";
496 withFeature = true;
497 configureFlags =
498 lib.optionals finalAttrs.withFeature ["--with-feature"];
499})
500```
501
502Note that this does not use the `rec` keyword to reuse `withFeature` in `configureFlags`.
503The `rec` keyword works at the syntax level and is unaware of overriding.
504
505Instead, the definition references `finalAttrs`, allowing users to change `withFeature`
506consistently with `overrideAttrs`.
507
508`finalAttrs` also contains the attribute `finalPackage`, which includes the output paths, etc.
509
510Let's look at a more elaborate example to understand the differences between
511various bindings:
512
513```nix
514# `pkg` is the _original_ definition (for illustration purposes)
515let pkg =
516 mkDerivation (finalAttrs: {
517 # ...
518
519 # An example attribute
520 packages = [];
521
522 # `passthru.tests` is a commonly defined attribute.
523 passthru.tests.simple = f finalAttrs.finalPackage;
524
525 # An example of an attribute containing a function
526 passthru.appendPackages = packages':
527 finalAttrs.finalPackage.overrideAttrs (newSelf: super: {
528 packages = super.packages ++ packages';
529 });
530
531 # For illustration purposes; referenced as
532 # `(pkg.overrideAttrs(x)).finalAttrs` etc in the text below.
533 passthru.finalAttrs = finalAttrs;
534 passthru.original = pkg;
535 });
536in pkg
537```
538
539Unlike 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`.
540
541See also the section about [`passthru.tests`](#var-meta-tests).
542
543## Phases {#sec-stdenv-phases}
544
545`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.
546
547This generic command invokes 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).
548
549Each 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`.
550
551When 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.
552
553While 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.
554
555### Controlling phases {#ssec-controlling-phases}
556
557There are a number of variables that control what phases are executed and in what order:
558
559#### Variables affecting phase control {#variables-affecting-phase-control}
560
561##### `phases` {#var-stdenv-phases}
562
563Specifies 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`.
564
565It 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).
566Usually, if you just want to add a few phases, it’s more convenient to set one of the variables below (such as `preInstallPhases`).
567
568##### `prePhases` {#var-stdenv-prePhases}
569
570Additional phases executed before any of the default phases.
571
572##### `preConfigurePhases` {#var-stdenv-preConfigurePhases}
573
574Additional phases executed just before the configure phase.
575
576##### `preBuildPhases` {#var-stdenv-preBuildPhases}
577
578Additional phases executed just before the build phase.
579
580##### `preInstallPhases` {#var-stdenv-preInstallPhases}
581
582Additional phases executed just before the install phase.
583
584##### `preFixupPhases` {#var-stdenv-preFixupPhases}
585
586Additional phases executed just before the fixup phase.
587
588##### `preDistPhases` {#var-stdenv-preDistPhases}
589
590Additional phases executed just before the distribution phase.
591
592##### `postPhases` {#var-stdenv-postPhases}
593
594Additional phases executed after any of the default phases.
595
596### The unpack phase {#ssec-unpack-phase}
597
598The 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:
599
600#### Tar files {#tar-files}
601
602These 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`).
603
604#### Zip files {#zip-files}
605
606Zip files are unpacked using `unzip`. However, `unzip` is not in the standard environment, so you should add it to `nativeBuildInputs` yourself.
607
608#### Directories in the Nix store {#directories-in-the-nix-store}
609
610These are simply 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`.
611
612Additional file types can be supported by setting the `unpackCmd` variable (see below).
613
614#### Variables controlling the unpack phase {#variables-controlling-the-unpack-phase}
615
616##### `srcs` / `src` {#var-stdenv-src}
617
618The 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`.
619
620##### `sourceRoot` {#var-stdenv-sourceRoot}
621
622After running `unpackPhase`, the generic builder changes the current directory to the directory created by unpacking the sources. If there are multiple source directories, you should set `sourceRoot` to the name of the intended directory. Set `sourceRoot = ".";` if you use `srcs` and control the unpack phase yourself.
623
624By default the `sourceRoot` is set to `"source"`. If you want to point to a sub-directory inside your project, you therefore need to set `sourceRoot = "source/my-sub-directory"`.
625
626##### `setSourceRoot` {#var-stdenv-setSourceRoot}
627
628Alternatively 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`.
629
630##### `preUnpack` {#var-stdenv-preUnpack}
631
632Hook executed at the start of the unpack phase.
633
634##### `postUnpack` {#var-stdenv-postUnpack}
635
636Hook executed at the end of the unpack phase.
637
638##### `dontUnpack` {#var-stdenv-dontUnpack}
639
640Set to true to skip the unpack phase.
641
642##### `dontMakeSourcesWritable` {#var-stdenv-dontMakeSourcesWritable}
643
644If 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.
645
646##### `unpackCmd` {#var-stdenv-unpackCmd}
647
648The unpack phase evaluates the string `$unpackCmd` for any unrecognised file. The path to the current source file is contained in the `curSrc` variable.
649
650### The patch phase {#ssec-patch-phase}
651
652The patch phase applies the list of patches defined in the `patches` variable.
653
654#### Variables controlling the patch phase {#variables-controlling-the-patch-phase}
655
656##### `dontPatch` {#var-stdenv-dontPatch}
657
658Set to true to skip the patch phase.
659
660##### `patches` {#var-stdenv-patches}
661
662The 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`).
663
664##### `patchFlags` {#var-stdenv-patchFlags}
665
666Flags 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.
667
668##### `prePatch` {#var-stdenv-prePatch}
669
670Hook executed at the start of the patch phase.
671
672##### `postPatch` {#var-stdenv-postPatch}
673
674Hook executed at the end of the patch phase.
675
676### The configure phase {#ssec-configure-phase}
677
678The configure phase prepares the source tree for building. The default `configurePhase` runs `./configure` (typically an Autoconf-generated script) if it exists.
679
680#### Variables controlling the configure phase {#variables-controlling-the-configure-phase}
681
682##### `configureScript` {#var-stdenv-configureScript}
683
684The 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`).
685
686##### `configureFlags` {#var-stdenv-configureFlags}
687
688A list of strings passed as additional arguments to the configure script.
689
690##### `dontConfigure` {#var-stdenv-dontConfigure}
691
692Set to true to skip the configure phase.
693
694##### `configureFlagsArray` {#var-stdenv-configureFlagsArray}
695
696A shell array containing additional arguments passed to the configure script. You must use this instead of `configureFlags` if the arguments contain spaces.
697
698##### `dontAddPrefix` {#var-stdenv-dontAddPrefix}
699
700By default, the flag `--prefix=$prefix` is added to the configure flags. If this is undesirable, set this variable to true.
701
702##### `prefix` {#var-stdenv-prefix}
703
704The prefix under which the package must be installed, passed via the `--prefix` option to the configure script. It defaults to `$out`.
705
706##### `prefixKey` {#var-stdenv-prefixKey}
707
708The key to use when specifying the prefix. By default, this is set to `--prefix=` as that is used by the majority of packages.
709
710##### `dontAddStaticConfigureFlags` {#var-stdenv-dontAddStaticConfigureFlags}
711
712By default, when building statically, stdenv will try to add build system appropriate configure flags to try to enable static builds.
713
714If this is undesirable, set this variable to true.
715
716##### `dontAddDisableDepTrack` {#var-stdenv-dontAddDisableDepTrack}
717
718By 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.
719
720##### `dontFixLibtool` {#var-stdenv-dontFixLibtool}
721
722By 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.
723
724##### `dontDisableStatic` {#var-stdenv-dontDisableStatic}
725
726By default, when the configure script has `--enable-static`, the option `--disable-static` is added to the configure flags.
727
728If this is undesirable, set this variable to true. It is automatically set to true when building statically, for example through `pkgsStatic`.
729
730##### `configurePlatforms` {#var-stdenv-configurePlatforms}
731
732By 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]
733
734##### `preConfigure` {#var-stdenv-preConfigure}
735
736Hook executed at the start of the configure phase.
737
738##### `postConfigure` {#var-stdenv-postConfigure}
739
740Hook executed at the end of the configure phase.
741
742### The build phase {#build-phase}
743
744The build phase is responsible for actually building the package (e.g. compiling it). The default `buildPhase` simply 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.
745
746#### Variables controlling the build phase {#variables-controlling-the-build-phase}
747
748##### `dontBuild` {#var-stdenv-dontBuild}
749
750Set to true to skip the build phase.
751
752##### `makefile` {#var-stdenv-makefile}
753
754The file name of the Makefile.
755
756##### `makeFlags` {#var-stdenv-makeFlags}
757
758A 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).
759
760```nix
761makeFlags = [ "PREFIX=$(out)" ];
762```
763
764::: {.note}
765The flags are quoted in bash, but environment variables can be specified by using the make syntax.
766:::
767
768##### `makeFlagsArray` {#var-stdenv-makeFlagsArray}
769
770A shell array containing additional arguments passed to `make`. You must use this instead of `makeFlags` if the arguments contain spaces, e.g.
771
772```nix
773preBuild = ''
774 makeFlagsArray+=(CFLAGS="-O0 -g" LDFLAGS="-lfoo -lbar")
775'';
776```
777
778Note 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.
779
780##### `buildFlags` / `buildFlagsArray` {#var-stdenv-buildFlags}
781
782A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the build phase.
783
784##### `preBuild` {#var-stdenv-preBuild}
785
786Hook executed at the start of the build phase.
787
788##### `postBuild` {#var-stdenv-postBuild}
789
790Hook executed at the end of the build phase.
791
792You can set flags for `make` through the `makeFlags` variable.
793
794Before and after running `make`, the hooks `preBuild` and `postBuild` are called, respectively.
795
796### The check phase {#ssec-check-phase}
797
798The 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.
799
800#### Variables controlling the check phase {#variables-controlling-the-check-phase}
801
802##### `doCheck` {#var-stdenv-doCheck}
803
804Controls 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
805
806```nix
807doCheck = true;
808```
809
810in 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.
811
812##### `makeFlags` / `makeFlagsArray` / `makefile` {#makeflags-makeflagsarray-makefile}
813
814See the [build phase](#var-stdenv-makeFlags) for details.
815
816##### `checkTarget` {#var-stdenv-checkTarget}
817
818The `make` target that runs the tests.
819If unset, use `check` if it exists, otherwise `test`; if neither is found, do nothing.
820
821##### `checkFlags` / `checkFlagsArray` {#var-stdenv-checkFlags}
822
823A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the check phase.
824
825##### `checkInputs` {#var-stdenv-checkInputs}
826
827A 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.
828
829##### `nativeCheckInputs` {#var-stdenv-nativeCheckInputs}
830
831A list of native dependencies used by the phase, notably tools needed on `$PATH`. This gets included in `nativeBuildInputs` when `doCheck` is set.
832
833##### `preCheck` {#var-stdenv-preCheck}
834
835Hook executed at the start of the check phase.
836
837##### `postCheck` {#var-stdenv-postCheck}
838
839Hook executed at the end of the check phase.
840
841### The install phase {#ssec-install-phase}
842
843The 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`.
844
845#### Variables controlling the install phase {#variables-controlling-the-install-phase}
846
847##### `dontInstall` {#var-stdenv-dontInstall}
848
849Set to true to skip the install phase.
850
851##### `makeFlags` / `makeFlagsArray` / `makefile` {#makeflags-makeflagsarray-makefile-1}
852
853See the [build phase](#var-stdenv-makeFlags) for details.
854
855##### `installTargets` {#var-stdenv-installTargets}
856
857The make targets that perform the installation. Defaults to `install`. Example:
858
859```nix
860installTargets = "install-bin install-doc";
861```
862
863##### `installFlags` / `installFlagsArray` {#var-stdenv-installFlags}
864
865A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the install phase.
866
867##### `preInstall` {#var-stdenv-preInstall}
868
869Hook executed at the start of the install phase.
870
871##### `postInstall` {#var-stdenv-postInstall}
872
873Hook executed at the end of the install phase.
874
875### The fixup phase {#ssec-fixup-phase}
876
877The fixup phase performs (Nix-specific) post-processing actions on the files installed under `$out` by the install phase. The default `fixupPhase` does the following:
878
879- It moves the `man/`, `doc/` and `info/` subdirectories of `$out` to `share/`.
880- It strips libraries and executables of debug information.
881- 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.
882- 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.
883
884#### Variables controlling the fixup phase {#variables-controlling-the-fixup-phase}
885
886##### `dontFixup` {#var-stdenv-dontFixup}
887
888Set to true to skip the fixup phase.
889
890##### `dontStrip` {#var-stdenv-dontStrip}
891
892If set, libraries and executables are not stripped. By default, they are.
893
894##### `dontStripHost` {#var-stdenv-dontStripHost}
895
896Like `dontStrip`, but only affects the `strip` command targeting the package’s host platform. Useful when supporting cross compilation, but otherwise feel free to ignore.
897
898##### `dontStripTarget` {#var-stdenv-dontStripTarget}
899
900Like `dontStrip`, but only affects the `strip` command targeting the packages’ target platform. Useful when supporting cross compilation, but otherwise feel free to ignore.
901
902##### `dontMoveSbin` {#var-stdenv-dontMoveSbin}
903
904If set, files in `$out/sbin` are not moved to `$out/bin`. By default, they are.
905
906##### `stripAllList` {#var-stdenv-stripAllList}
907
908List 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.
909
910##### `stripAllListTarget` {#var-stdenv-stripAllListTarget}
911
912Like `stripAllList`, but only applies to packages’ target platform. By default, it’s empty. Useful when supporting cross compilation.
913
914##### `stripAllFlags` {#var-stdenv-stripAllFlags}
915
916Flags passed to the `strip` command applied to the files in the directories listed in `stripAllList`. Defaults to `-s` (i.e. `--strip-all`).
917
918##### `stripDebugList` {#var-stdenv-stripDebugList}
919
920List 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`.
921
922##### `stripDebugListTarget` {#var-stdenv-stripDebugListTarget}
923
924Like `stripDebugList`, but only applies to packages’ target platform. By default, it’s empty. Useful when supporting cross compilation.
925
926##### `stripDebugFlags` {#var-stdenv-stripDebugFlags}
927
928Flags passed to the `strip` command applied to the files in the directories listed in `stripDebugList`. Defaults to `-S` (i.e. `--strip-debug`).
929
930##### `dontPatchELF` {#var-stdenv-dontPatchELF}
931
932If set, the `patchelf` command is not used to remove unnecessary `RPATH` entries. Only applies to Linux.
933
934##### `dontPatchShebangs` {#var-stdenv-dontPatchShebangs}
935
936If 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.
937
938##### `dontPruneLibtoolFiles` {#var-stdenv-dontPruneLibtoolFiles}
939
940If set, libtool `.la` files associated with shared libraries won’t have their `dependency_libs` field cleared.
941
942##### `forceShare` {#var-stdenv-forceShare}
943
944The list of directories that must be moved from `$out` to `$out/share`. Defaults to `man doc info`.
945
946##### `setupHook` {#var-stdenv-setupHook}
947
948A 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`.
949
950##### `preFixup` {#var-stdenv-preFixup}
951
952Hook executed at the start of the fixup phase.
953
954##### `postFixup` {#var-stdenv-postFixup}
955
956Hook executed at the end of the fixup phase.
957
958##### `separateDebugInfo` {#stdenv-separateDebugInfo}
959
960If 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.
961
962For example, with GDB, you can add
963
964```
965set debug-file-directory ~/.nix-profile/lib/debug
966```
967
968to `~/.gdbinit`. GDB will then be able to find debug information installed via `nix-env -i`.
969
970### The installCheck phase {#ssec-installCheck-phase}
971
972The installCheck phase checks whether the package was installed correctly by running its test suite against the installed directories. The default `installCheck` calls `make installcheck`.
973
974It is often better to add tests that are not part of the source distribution to `passthru.tests` (see <xref linkend="var-meta-tests"/>). This avoids adding overhead to every build and enables us to run them independently.
975
976#### Variables controlling the installCheck phase {#variables-controlling-the-installcheck-phase}
977
978##### `doInstallCheck` {#var-stdenv-doInstallCheck}
979
980Controls 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
981
982```nix
983doInstallCheck = true;
984```
985
986in 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.
987
988##### `installCheckTarget` {#var-stdenv-installCheckTarget}
989
990The make target that runs the install tests. Defaults to `installcheck`.
991
992##### `installCheckFlags` / `installCheckFlagsArray` {#var-stdenv-installCheckFlags}
993
994A list of strings passed as additional flags to `make`. Like `makeFlags` and `makeFlagsArray`, but only used by the installCheck phase.
995
996##### `installCheckInputs` {#var-stdenv-installCheckInputs}
997
998A 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.
999
1000##### `nativeInstallCheckInputs` {#var-stdenv-nativeInstallCheckInputs}
1001
1002A list of native dependencies used by the phase, notably tools needed on `$PATH`. This gets included in `nativeBuildInputs` when `doInstallCheck` is set.
1003
1004##### `preInstallCheck` {#var-stdenv-preInstallCheck}
1005
1006Hook executed at the start of the installCheck phase.
1007
1008##### `postInstallCheck` {#var-stdenv-postInstallCheck}
1009
1010Hook executed at the end of the installCheck phase.
1011
1012### The distribution phase {#ssec-distribution-phase}
1013
1014The 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.
1015
1016#### Variables controlling the distribution phase {#variables-controlling-the-distribution-phase}
1017
1018##### `doDist` {#var-stdenv-doDist}
1019
1020If set, the distribution phase is executed.
1021
1022##### `distTarget` {#var-stdenv-distTarget}
1023
1024The make target that produces the distribution. Defaults to `dist`.
1025
1026##### `distFlags` / `distFlagsArray` {#var-stdenv-distFlags}
1027
1028Additional flags passed to `make`.
1029
1030##### `tarballs` {#var-stdenv-tarballs}
1031
1032The names of the source distribution files to be copied to `$out/tarballs/`. It can contain shell wildcards. The default is `*.tar.gz`.
1033
1034##### `dontCopyDist` {#var-stdenv-dontCopyDist}
1035
1036If set, no files are copied to `$out/tarballs/`.
1037
1038##### `preDist` {#var-stdenv-preDist}
1039
1040Hook executed at the start of the distribution phase.
1041
1042##### `postDist` {#var-stdenv-postDist}
1043
1044Hook executed at the end of the distribution phase.
1045
1046## Shell functions and utilities {#ssec-stdenv-functions}
1047
1048The standard environment provides a number of useful functions.
1049
1050### `makeWrapper` \<executable\> \<wrapperfile\> \<args\> {#fun-makeWrapper}
1051
1052Constructs 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:
1053
1054```bash
1055# adds `FOOBAR=baz` to `$out/bin/foo`’s environment
1056makeWrapper $out/bin/foo $wrapperfile --set FOOBAR baz
1057
1058# Prefixes the binary paths of `hello` and `git`
1059# and suffixes the binary path of `xdg-utils`.
1060# Be advised that paths often should be patched in directly
1061# (via string replacements or in `configurePhase`).
1062makeWrapper $out/bin/foo $wrapperfile \
1063 --prefix PATH : ${lib.makeBinPath [ hello git ]} \
1064 --suffix PATH : ${lib.makeBinPath [ xdg-utils ]}
1065```
1066
1067Packages may expect or require other utilities to be available at runtime.
1068`makeWrapper` can be used to add packages to a `PATH` environment variable local to a wrapper.
1069
1070Use `--prefix` to explicitly set dependencies in `PATH`.
1071
1072::: {.note}
1073`--prefix` essentially hard-codes dependencies into the wrapper.
1074They cannot be overridden without rebuilding the package.
1075:::
1076
1077If dependencies should be resolved at runtime, use `--suffix` to append fallback values to `PATH`.
1078
1079There’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/build-support/setup-hooks/make-binary-wrapper/make-binary-wrapper.sh` for the `makeBinaryWrapper` implementation.
1080
1081`wrapProgram` is a convenience function you probably want to use most of the time, implemented by both `makeWrapper` and `makeBinaryWrapper`.
1082
1083Using 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.
1084
1085### `remove-references-to -t` \<storepath\> [ `-t` \<storepath\> ... ] \<file\> ... {#fun-remove-references-to}
1086
1087Removes 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.
1088To use this, add `removeReferencesTo` to `nativeBuildInputs`.
1089
1090As `remove-references-to` is an actual executable and not a shell function, it can be used with `find`.
1091Example removing all references to the compiler in the output:
1092```nix
1093postInstall = ''
1094 find "$out" -type f -exec remove-references-to -t ${stdenv.cc} '{}' +
1095'';
1096```
1097
1098### `substitute` \<infile\> \<outfile\> \<subs\> {#fun-substitute}
1099
1100Performs string substitution on the contents of \<infile\>, writing the result to \<outfile\>. The substitutions in \<subs\> are of the following form:
1101
1102#### `--replace` \<s1\> \<s2\> {#fun-substitute-replace}
1103
1104Replace every occurrence of the string \<s1\> by \<s2\>.
1105
1106#### `--subst-var` \<varName\> {#fun-substitute-subst-var}
1107
1108Replace 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.
1109
1110#### `--subst-var-by` \<varName\> \<s\> {#fun-substitute-subst-var-by}
1111
1112Replace every occurrence of `@varName@` by the string \<s\>.
1113
1114Example:
1115
1116```shell
1117substitute ./foo.in ./foo.out \
1118 --replace /usr/bin/bar $bar/bin/bar \
1119 --replace "a string containing spaces" "some other text" \
1120 --subst-var someVar
1121```
1122
1123### `substituteInPlace` \<multiple files\> \<subs\> {#fun-substituteInPlace}
1124
1125Like `substitute`, but performs the substitutions in place on the files passed.
1126
1127### `substituteAll` \<infile\> \<outfile\> {#fun-substituteAll}
1128
1129Replaces every occurrence of `@varName@`, where \<varName\> is any environment variable, in \<infile\>, writing the result to \<outfile\>. For instance, if \<infile\> has the contents
1130
1131```bash
1132#! @bash@/bin/sh
1133PATH=@coreutils@/bin
1134echo @foo@
1135```
1136
1137and 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
1138
1139```bash
1140#! /nix/store/bmwp0q28cf21...-bash-3.2-p39/bin/sh
1141PATH=/nix/store/68afga4khv0w...-coreutils-6.12/bin
1142echo @foo@
1143```
1144
1145That is, no substitution is performed for undefined variables.
1146
1147Environment 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).
1148
1149### `substituteAllInPlace` \<file\> {#fun-substituteAllInPlace}
1150
1151Like `substituteAll`, but performs the substitutions in place on the file \<file\>.
1152
1153### `stripHash` \<path\> {#fun-stripHash}
1154
1155Strips the directory and hash part of a store path, outputting the name part to `stdout`. For example:
1156
1157```bash
1158# prints coreutils-8.24
1159stripHash "/nix/store/9s9r019176g7cvn2nvcw41gsp862y6b4-coreutils-8.24"
1160```
1161
1162If you wish to store the result in another variable, then the following idiom may be useful:
1163
1164```bash
1165name="/nix/store/9s9r019176g7cvn2nvcw41gsp862y6b4-coreutils-8.24"
1166someVar=$(stripHash $name)
1167```
1168
1169### `wrapProgram` \<executable\> \<makeWrapperArgs\> {#fun-wrapProgram}
1170
1171Convenience 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).
1172
1173If you will apply it multiple times, it will overwrite the wrapper file and you will end up with double wrapping, which should be avoided.
1174
1175### `prependToVar` \<variableName\> \<elements...\> {#fun-prependToVar}
1176
1177Prepend elements to a variable.
1178
1179Example:
1180
1181```shellSession
1182$ configureFlags="--disable-static"
1183$ prependToVar configureFlags --disable-dependency-tracking --enable-foo
1184$ echo $configureFlags
1185--disable-dependency-tracking --enable-foo --disable-static
1186```
1187
1188### `appendToVar` \<variableName\> \<elements...\> {#fun-appendToVar}
1189
1190Append elements to a variable.
1191
1192Example:
1193
1194```shellSession
1195$ configureFlags="--disable-static"
1196$ appendToVar configureFlags --disable-dependency-tracking --enable-foo
1197$ echo $configureFlags
1198--disable-static --disable-dependency-tracking --enable-foo
1199```
1200
1201## Package setup hooks {#ssec-setup-hooks}
1202
1203Nix 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.
1204
1205In 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.
1206
1207The 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 simply 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.
1208
1209The 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).
1210
1211Packages 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
1212
1213```bash
1214addEnvHooks "$hostOffset" myBashFunction
1215```
1216
1217The *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.
1218
1219First, 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` or when using a custom builder that has `source $stdenv/setup`. Some of these are platform specific, so they may run on Linux but not Darwin or vice-versa.
1220
1221### `move-docs.sh` {#move-docs.sh}
1222
1223This 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.
1224
1225### `compress-man-pages.sh` {#compress-man-pages.sh}
1226
1227This 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.
1228
1229### `strip.sh` {#strip.sh}
1230
1231This 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.
1232
1233### `patch-shebangs.sh` {#patch-shebangs.sh}
1234
1235This 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.
1236
1237::: note
1238The [generic builder][generic-builder] populates `PATH` from inputs of the derivation.
1239:::
1240
1241[generic-builder]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/stdenv/generic/builder.sh
1242
1243#### Invocation {#patch-shebangs.sh-invocation}
1244
1245Multiple paths can be specified.
1246
1247```
1248patchShebangs [--build | --host] PATH...
1249```
1250
1251##### Flags {#patch-shebangs.sh-invocation-flags}
1252
1253`--build`
1254: Look up commands available at build time
1255
1256`--host`
1257: Look up commands available at run time
1258
1259##### Examples {#patch-shebangs.sh-invocation-examples}
1260
1261```sh
1262patchShebangs --host /nix/store/<hash>-hello-1.0/bin
1263```
1264
1265```sh
1266patchShebangs --build configure
1267```
1268
1269`#!/bin/sh` will be rewritten to `#!/nix/store/<hash>-some-bash/bin/sh`.
1270
1271`#!/usr/bin/env` gets special treatment: `#!/usr/bin/env python` is rewritten to `/nix/store/<hash>/bin/python`.
1272
1273Interpreter paths that point to a valid Nix store location are not changed.
1274
1275::: note
1276A script file must be marked as executable, otherwise it will not be
1277considered.
1278:::
1279
1280This mechanism ensures that the interpreter for a given script is always found and is exactly the one specified by the build.
1281
1282It can be disabled by setting [`dontPatchShebangs`](#var-stdenv-dontPatchShebangs):
1283
1284```nix
1285stdenv.mkDerivation {
1286 # ...
1287 dontPatchShebangs = true;
1288 # ...
1289}
1290```
1291
1292The 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.
1293
1294If you need to run `patchShebangs` at build time, it must be called explicitly within [one of the build phases](#sec-stdenv-phases).
1295
1296[patch-shebangs.sh]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/build-support/setup-hooks/patch-shebangs.sh
1297[patchShebangs]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/build-support/setup-hooks/patch-shebangs.sh#L24-L105
1298[patchShebangsAuto]: https://github.com/NixOS/nixpkgs/blob/19d4f7dc485f74109bd66ef74231285ff797a823/pkgs/build-support/setup-hooks/patch-shebangs.sh#L107-L119
1299
1300### `audit-tmpdir.sh` {#audit-tmpdir.sh}
1301
1302This 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.
1303
1304### `multiple-outputs.sh` {#multiple-outputs.sh}
1305
1306This 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.
1307
1308### `move-sbin.sh` {#move-sbin.sh}
1309
1310This setup hook moves any binaries installed in the `sbin/` subdirectory into `bin/`. In addition, a link is provided from `sbin/` to `bin/` for compatibility.
1311
1312### `move-lib64.sh` {#move-lib64.sh}
1313
1314This setup hook moves any libraries installed in the `lib64/` subdirectory into `lib/`. In addition, a link is provided from `lib64/` to `lib/` for compatibility.
1315
1316### `move-systemd-user-units.sh` {#move-systemd-user-units.sh}
1317
1318This 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.
1319
1320This hook only runs when compiling for Linux.
1321
1322### `set-source-date-epoch-to-latest.sh` {#set-source-date-epoch-to-latest.sh}
1323
1324This sets `SOURCE_DATE_EPOCH` to the modification time of the most recent file.
1325
1326### Bintools Wrapper and hook {#bintools-wrapper}
1327
1328The 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.
1329
1330The 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.
1331
1332A 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.
1333
1334A 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"`.
1335
1336### CC Wrapper and hook {#cc-wrapper}
1337
1338The 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.
1339
1340Dependency 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.
1341
1342Similarly, 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.
1343
1344Here 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.
1345
1346### Other hooks {#stdenv-other-hooks}
1347
1348Many other packages provide hooks, that are not part of `stdenv`. You can find
1349these in the [Hooks Reference](#chap-hooks).
1350
1351### Compiler and Linker wrapper hooks {#compiler-linker-wrapper-hooks}
1352
1353If the file `${cc}/nix-support/cc-wrapper-hook` exists, it will be run at the end of the [compiler wrapper](#cc-wrapper).
1354If the file `${binutils}/nix-support/post-link-hook` exists, it will be run at the end of the linker wrapper.
1355These hooks allow a user to inject code into the wrappers.
1356As 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.
1357
1358## Purity in Nixpkgs {#sec-purity-in-nixpkgs}
1359
1360*Measures taken to prevent dependencies on packages outside the store, and what you can do to prevent them.*
1361
1362GCC 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.
1363
1364## Hardening in Nixpkgs {#sec-hardening-in-nixpkgs}
1365
1366There are flags available to harden packages at compile or link-time. These can be toggled using the `stdenv.mkDerivation` parameters `hardeningDisable` and `hardeningEnable`.
1367
1368Both 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.
1369
1370For 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).
1371
1372### Hardening flags enabled by default {#sec-hardening-flags-enabled-by-default}
1373
1374The following flags are enabled by default and might require disabling with `hardeningDisable` if the program to package is incompatible.
1375
1376#### `format` {#format}
1377
1378Adds 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`.
1379
1380This needs to be turned off or fixed for errors similar to:
1381
1382```
1383/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]
1384 printf(help_message);
1385 ^
1386cc1plus: some warnings being treated as errors
1387```
1388
1389#### `stackprotector` {#stackprotector}
1390
1391Adds 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).
1392
1393This needs to be turned off or fixed for errors similar to:
1394
1395```
1396bin/blib.a(bios_console.o): In function `bios_handle_cup':
1397/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'
1398```
1399
1400#### `fortify` {#fortify}
1401
1402Adds 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.
1403
1404Additionally, 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`.
1405
1406This needs to be turned off or fixed for errors similar to:
1407
1408```
1409malloc.c:404:15: error: return type is an incomplete type
1410malloc.c:410:19: error: storage size of 'ms' isn't known
1411
1412strdup.h:22:1: error: expected identifier or '(' before '__extension__'
1413
1414strsep.c:65:23: error: register name not specified for 'delim'
1415
1416installwatch.c:3751:5: error: conflicting types for '__open_2'
1417
1418fcntl2.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
1419```
1420
1421#### `pic` {#pic}
1422
1423Adds the `-fPIC` compiler options. This options adds support for position independent code in shared libraries and thus making ASLR possible.
1424
1425Most 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.
1426
1427This needs to be turned off or fixed for assembler errors similar to:
1428
1429```
1430ccbLfRgg.s: Assembler messages:
1431ccbLfRgg.s:33: Error: missing or invalid displacement expression `private_key_len@GOTOFF'
1432```
1433
1434#### `strictoverflow` {#strictoverflow}
1435
1436Signed 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.
1437
1438This flag should not trigger any build or runtime errors.
1439
1440#### `relro` {#relro}
1441
1442Adds 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.
1443
1444This 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.
1445
1446#### `bindnow` {#bindnow}
1447
1448Adds the `-z bindnow` 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.
1449
1450This 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:
1451
1452```
1453intel_drv.so: undefined symbol: vgaHWFreeHWRec
1454```
1455
1456### Hardening flags disabled by default {#sec-hardening-flags-disabled-by-default}
1457
1458The following flags are disabled by default and should be enabled with `hardeningEnable` for packages that take untrusted input like network services.
1459
1460#### `pie` {#pie}
1461
1462This flag is disabled by default for normal `glibc` based NixOS package builds, but enabled by default for `musl` based package builds.
1463
1464Adds 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.
1465
1466Static libraries need to be compiled with `-fPIE` so that executables can link them in with the `-pie` linker option.
1467If the libraries lack `-fPIE`, you will get the error `recompile with -fPIE`.
1468
1469[^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.
1470[^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`.
1471[^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.
1472[^footnote-stdenv-find-inputs-location]: The `findInputs` function, currently residing in `pkgs/stdenv/generic/setup.sh`, implements the propagation logic.
1473[^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.
1474[^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.
1475[^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.