Compare commits

...

121 Commits

Author SHA1 Message Date
mergify[bot]
920f14a360 Merge pull request #13208 from NixOS/mergify/bp/2.27-maintenance/pr-13207
dev-shell: Drop bear dependency (backport #13207)
2025-05-15 21:58:20 +00:00
Sergei Zimmerman
775c045a9e dev-shell: Drop bear dependency
Since the autotools-based build system has been removed
and meson already generates compile database there's no
need to have it in the devshell.

(cherry picked from commit 67535263a5)
2025-05-15 21:49:07 +00:00
Eelco Dolstra
9febd9f84b Merge pull request #13020 from NixOS/mergify/bp/2.27-maintenance/pr-13019
Mention BLAKE3 in the Nix 2.27 release notes (backport #13019)
2025-04-14 15:57:09 +02:00
Eelco Dolstra
064c141fc8 Mention BLAKE3 in the Nix 2.27 release notes
(cherry picked from commit c0ed07755a)
2025-04-14 13:47:54 +00:00
mergify[bot]
af298ee53f Merge pull request #12981 from NixOS/mergify/bp/2.27-maintenance/pr-12979
Actually ignore system/user registries during locking (backport #12979)
2025-04-09 16:53:03 +00:00
Eelco Dolstra
4dfe5eb587 Actually ignore system/user registries during locking
Something went wrong in #12068 so this didn't work. Also added a test.

(cherry picked from commit 77d4316353)
2025-04-09 16:33:40 +00:00
mergify[bot]
b23189061e Merge pull request #12971 from NixOS/mergify/bp/2.27-maintenance/pr-12967
Add trailing commas on addFlag incantations (backport #12967)
2025-04-07 23:37:16 +00:00
Graham Christensen
025c935ba2 format as required
(cherry picked from commit 9b47b2b217)
2025-04-07 23:16:22 +00:00
Graham Christensen
29d37eb2db Add trailing commas on addFlag incantations
(cherry picked from commit 06acbd37bd)
2025-04-07 23:16:22 +00:00
mergify[bot]
d0f98c76f9 Merge pull request #12954 from NixOS/mergify/bp/2.27-maintenance/pr-12951
tests/functional/repl: fix race condition (backport #12951)
2025-04-07 12:39:59 +00:00
Jörg Thalheim
eb97d69f0d tests/functional/repl: fix race condition
the sleep 1 is not enough in some circumstances. Switching to a fifo
helps.

(cherry picked from commit 1de951d31d)
2025-04-07 12:19:27 +00:00
mergify[bot]
92b4578a65 Merge pull request #12948 from NixOS/mergify/bp/2.27-maintenance/pr-12944
maintainers/release-notes: Let it fail (backport #12944)
2025-04-07 09:11:32 +00:00
Robert Hensing
6733f72ea4 maintainers/release-notes: Let it fail
Fail when a command fails.

Basic error handling was missing, which would lead to errors getting
obscured a bit by subsequent successful logging.

(cherry picked from commit da36c34db7)
2025-04-07 08:52:36 +00:00
Jörg Thalheim
ad814e7b93 Merge pull request #12923 from NixOS/mergify/bp/2.27-maintenance/pr-12911
create cache entry for paths already in the nix store (backport #12911)
2025-04-04 16:23:54 +02:00
Jörg Thalheim
82a47978db create cache entry for paths already in the nix store
This allows path:/nix/store/* paths to not be copied twice to the nix
store.

(cherry picked from commit 61c6210dbf)
2025-04-04 16:04:14 +02:00
mergify[bot]
f02ce07682 Merge pull request #12920 from NixOS/mergify/bp/2.27-maintenance/pr-12919
Reinstate Darwin minversion (backport #12919)
2025-04-04 06:46:44 +00:00
Robert Hensing
f0bf94fe29 packaging/dependency: Clarify darwinMinVersion
(cherry picked from commit 4be92e7b82)
2025-04-04 06:39:08 +00:00
Robert Hensing
22168ff57d Revert "remove obsolete stdenv darwinMinVersion override"
This reverts commit d91310bb32.

> Some packages require setting a non-default deployment target
> (or minimum version) to gain access to certain APIs. You do
> that using the darwinMinVersionHook, which takes the deployment
> target version as a parameter.

-- 60b54c7aee/doc/stdenv/platform-notes.chapter.md (what-is-a-deployment-target-or-minimum-version-sec-darwin-troubleshooting-using-deployment-targets)

This will again solve error:

    ../nix_api_expr.cc:38:18: error: aligned allocation function of type 'void *(std::size_t, std::align_val_t)' is only available on macOS 10.13 or newer

-- https://hydra.nixos.org/build/294088946

(cherry picked from commit 5c4a4aeed7)
2025-04-04 06:39:08 +00:00
mergify[bot]
bfa581fcff Merge pull request #12913 from NixOS/mergify/bp/2.27-maintenance/pr-12912
Set path display for substituted inputs (backport #12912)
2025-04-03 13:07:34 +00:00
Eelco Dolstra
8d1c97a55a Set path display for substituted inputs
(cherry picked from commit 4a397cfb80)
2025-04-03 12:50:23 +00:00
mergify[bot]
71aad3ad44 Merge pull request #12865 from NixOS/mergify/bp/2.27-maintenance/pr-12810
Packaging improvements from Nixpkgs (backport #12810)
2025-04-03 08:19:38 +00:00
Robert Hensing
aa5ffba310 packaging: finalAttrs.doCheck -> finalAttrs.finalPackage.doCheck
This includes the logic that disables checks on cross appropriately.

Co-authored-by: Peder Bergebakken Sundt <pbsds@hotmail.com>
(cherry picked from commit 27d71b21fc)
2025-04-03 09:52:57 +02:00
Robert Hensing
bb104e9b28 packaging: Various improvements
Co-authored-by: Mic92 <Mic92@users.noreply.github.com>
(cherry picked from commit 1172e49a3a)
2025-04-03 09:52:57 +02:00
Eelco Dolstra
c73c503d5f Merge pull request #12881 from NixOS/mergify/bp/2.27-maintenance/pr-12869
Apply makeNotAllowedError to empty Git repos (backport #12869)
2025-04-03 09:52:46 +02:00
Eelco Dolstra
95cd6c1e48 Merge remote-tracking branch 'origin/2.27-maintenance' into mergify/bp/2.27-maintenance/pr-12869 2025-04-03 09:32:40 +02:00
Eelco Dolstra
635a9975fd Merge pull request #12900 from NixOS/revert-12892-mergify/bp/2.27-maintenance/pr-12876
Revert "decrease connect-timeout to 5s (backport #12876)"
2025-04-03 09:26:45 +02:00
mergify[bot]
45aba8d640 Merge pull request #12905 from NixOS/mergify/bp/2.27-maintenance/pr-12886
symlink_exists: wrap exceptions into nix exception (backport #12886)
2025-04-02 23:37:30 +00:00
Jörg Thalheim
fa140349b8 symlink_exists: wrap exceptions into nix exception
(cherry picked from commit 779687854f)
2025-04-02 23:14:01 +00:00
mergify[bot]
2c02b58617 Merge pull request #12894 from NixOS/mergify/bp/2.27-maintenance/pr-12863
libgit2: use upstream version if possible (backport #12863)
2025-04-02 22:28:06 +00:00
Robert Hensing
cb3c8bba70 Revert "decrease connect-timeout to 5s (backport #12876)" 2025-04-02 23:53:21 +02:00
mergify[bot]
5ecb8a12ee Merge pull request #12892 from NixOS/mergify/bp/2.27-maintenance/pr-12876
decrease connect-timeout to 5s (backport #12876)
2025-04-02 21:39:44 +00:00
Jörg Thalheim
a6a621c8ff remove obsolete stdenv darwinMinVersion override
we are more up-to-date now:

nix-repl> stdenv.hostPlatform.darwinMinVersion
"11.3"

(cherry picked from commit d91310bb32)
2025-04-02 20:45:31 +00:00
Jörg Thalheim
f1cb0e6ddb libgit2: use upstream version if possible
we don't seem to use libgit2 for fetching via ssh, hence it shouldn't
matter if it's using libssh or the ssh binary.

(cherry picked from commit 0b61b758fb)
2025-04-02 20:45:30 +00:00
Jörg Thalheim
7ef0eddfdc decrease connect-timeout to 5s
For people self-hosting caches that can be occasionally down, the
default timeout is very long. This is annoying if you are trying to
update your binary cache at the same time you are trying to update
another machine. Same if cachix has one of its rare hiccups.

We tested this value of 5s in srvos now for years and we like to travel
around the world with shitty internet, so it should be still reasonable
high.

(cherry picked from commit bef91a618a)
2025-04-02 20:43:28 +00:00
Eelco Dolstra
c0b4fb0de8 Merge pull request #12883 from NixOS/mergify/bp/2.27-maintenance/pr-12870
Git fetcher: Improve error message for untracked files (backport #12870)
2025-04-02 21:30:50 +02:00
Eelco Dolstra
2b4ddbbf47 Make Git error messages more consistent
(cherry picked from commit f15681df26)
2025-04-02 19:15:12 +00:00
Eelco Dolstra
d653225a24 Tweak error message
(cherry picked from commit 277c29a64b)
2025-04-02 19:15:12 +00:00
Graham Christensen
398c4136c2 Improve and fix the error message when a file is not tracked by Git
(cherry picked from commit 62e2304891)
2025-04-02 19:15:11 +00:00
Eelco Dolstra
084e75ed2f Apply makeNotAllowedError to empty repos
(cherry picked from commit 67e957b636)
2025-04-02 18:33:01 +00:00
mergify[bot]
ae2bd40d06 Merge pull request #12861 from NixOS/mergify/bp/2.27-maintenance/pr-12853
flake: nixpkgs: 24.11 -> nixos-unstable (backport #12853)
2025-04-01 17:18:43 +00:00
Robert Hensing
9b87c4f806 tests/nixos: Work around network-online.target inactivity
(cherry picked from commit 58b657b976)
2025-04-01 16:50:27 +00:00
Robert Hensing
5671175a5e Format
clang-format: 18.1.8 -> 19.1.7
(cherry picked from commit 55297f865c)

# Conflicts:
#	src/libstore-test-support/outputs-spec.cc
2025-04-01 16:50:27 +00:00
Robert Hensing
f33a435329 flake: nixpkgs: 24.11 -> nixos-unstable
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/48d12d5e70ee91fe8481378e540433a7303dbf6a?narHash=sha256-1Noao/H%2BN8nFB4Beoy8fgwrcOQLVm9o4zKW1ODaqK9E%3D' (2024-12-16)
  → 'github:NixOS/nixpkgs/52faf482a3889b7619003c0daec593a1912fddc1?narHash=sha256-6hl6L/tRnwubHcA4pfUUtk542wn2Om%2BD4UnDhlDW9BE%3D' (2025-03-30)

(cherry picked from commit c212035d94)
2025-04-01 16:50:26 +00:00
mergify[bot]
07309b497a Merge pull request #12856 from NixOS/mergify/bp/2.27-maintenance/pr-12765
Add various clang tidy fixes (backport #12765)
2025-04-01 14:27:32 +00:00
Jörg Thalheim
a42345a1ff libstore/daemon: make sure monitor is not considered "unused"
(cherry picked from commit 5c3682d7a1)
2025-04-01 13:37:46 +00:00
Jörg Thalheim
9ee7318a23 test/ca-fd-leak: fix clang-tidy lints
(cherry picked from commit b050db951b)
2025-04-01 13:37:45 +00:00
Jörg Thalheim
b1826f720c git/getStringUntil: fix uninitialized stack variable
at least clang-tidy is not convinced that this initialized.
If this is not the case, the impact should be small and hopefully also
more robust if changed.

(cherry picked from commit 7e540059a3)
2025-04-01 13:37:45 +00:00
Jörg Thalheim
da1b5599b7 libstore/local-store: fix linting warning about unused variable
(cherry picked from commit 05082ea1c5)
2025-04-01 13:37:45 +00:00
mergify[bot]
8c5107a640 Merge pull request #12843 from NixOS/mergify/bp/2.27-maintenance/pr-12805
nix-daemon: source nix-profile-daemon.sh only once (backport #12805)
2025-04-01 07:49:39 +00:00
Thomas Miedema
a5f003555e nix-daemon: source nix-profile-daemon.sh only once
On my system (Ubuntu 24.04 with nix installed using
https://zero-to-nix.com/), I noticed that my PATH
contained multiple times the following entries:

  /home/thomas/.nix-profile/bin
  /nix/var/nix/profiles/default/bin

Fix it by inserting a missing `export`, to make
sure `nix-daemon.sh` is really only executed once.

(cherry picked from commit 2b4e3fa144)
2025-04-01 06:48:29 +00:00
mergify[bot]
668e09f74a Merge pull request #12816 from NixOS/mergify/bp/2.27-maintenance/pr-12812
Disable packaging-overriding test (backport #12812)
2025-03-31 16:48:51 +00:00
Eelco Dolstra
67aa608856 Disable packaging-overriding
Fixes #12690.

(cherry picked from commit a4be66828a)
2025-03-31 16:31:11 +00:00
John Ericson
4688590733 Merge pull request #12797 from NixOS/mergify/bp/2.27-maintenance/pr-12794
Fix windows build (backport #12794)
2025-03-28 21:50:47 -04:00
John Ericson
44c2bd35e0 Fix windows build
PR #12767 accidentally broke it.

(cherry picked from commit 99041b4d84)
2025-03-29 01:05:25 +00:00
mergify[bot]
eb7d96a8ac Merge pull request #12793 from NixOS/mergify/bp/2.27-maintenance/pr-12789
nix daemon: Don't open the store (backport #12789)
2025-03-29 00:24:30 +00:00
Eelco Dolstra
84a25dc846 nix daemon: Don't open the store
This makes it behave the same as nix-daemon. Opening the store in the
parent can cause a SIGBUS in libsqlite in the child:

  #0  0x00007f141cf6f789 in __memset_avx2_unaligned_erms () from /nix/store/wn7v2vhyyyi6clcyn0s9ixvl7d4d87ic-glibc-2.40-36/lib/libc.so.6
  #1  0x00007f141c322fe8 in walIndexAppend () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #2  0x00007f141c3711a2 in pagerWalFrames () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #3  0x00007f141c38317e in sqlite3PagerCommitPhaseOne.part.0 () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #4  0x00007f141c383555 in sqlite3BtreeCommitPhaseOne.part.0 () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #5  0x00007f141c384797 in sqlite3VdbeHalt () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #6  0x00007f141c3b8f60 in sqlite3VdbeExec () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #7  0x00007f141c3bbfef in sqlite3_step () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #8  0x00007f141c3bd0e5 in sqlite3_exec () from /nix/store/bbd59cqw259149r2ddk4w1q0lr2fch8c-sqlite-3.46.1/lib/libsqlite3.so.0
  #9  0x00007f141da140e0 in nix::SQLiteTxn::commit() () from /nix/store/1m4r8s7s1v54zq9isncvjgia02bffxlz-determinate-nix-store-3.1.0/lib/libnixstore.so
  #10 0x00007f141d9ce69c in nix::LocalStore::registerValidPaths(std::map<nix::StorePath, nix::ValidPathInfo, std::less<nix::StorePath>, std::allocator<std::pair<nix::StorePath const, nix::ValidPathInfo> > > const&)::{lambda()#1}::operator()() const () from /nix/store/1m4r8s7s1v54zq9isncvjgia02bffxlz-determinate-nix-store-3.1.0/lib/libnixstore.so

(cherry picked from commit 9590167290)
2025-03-29 00:02:50 +00:00
mergify[bot]
d891f233cb Merge pull request #12785 from NixOS/mergify/bp/2.27-maintenance/pr-12758
libutil: Fix error message (backport #12758)
2025-03-28 19:23:41 +00:00
mergify[bot]
84c4049e3c Merge pull request #12778 from NixOS/mergify/bp/2.27-maintenance/pr-12767
use createDirs consistently everywhere (backport #12767)
2025-03-28 18:09:59 +00:00
Robert Hensing
9c20bb18de libutil: Fix error message
I encountered this with a misconfigured libutil. I doubt that a
non-lutimes config is viable, because tests were failing.

(cherry picked from commit 1cffcd91a9)
2025-03-28 17:08:23 +00:00
mergify[bot]
52049bc76e Merge pull request #12776 from NixOS/mergify/bp/2.27-maintenance/pr-12772
Light packaging cleanups (backport #12772)
2025-03-28 16:44:06 +00:00
Jörg Thalheim
e308524097 use createDirs consistently everywhere
(cherry picked from commit a8217f2642)
2025-03-28 15:56:02 +00:00
John Ericson
5056aae63a Add a withAWS flag to libstore
Nixpkgs wants this, at least.

(cherry picked from commit e4c571c2f1)
2025-03-28 15:54:57 +00:00
John Ericson
602840bfd2 Link the right issue about the bad AWS pkg-config
It is https://github.com/aws/aws-sdk-cpp/issues/2673

(cherry picked from commit fb9c9ee35a)
2025-03-28 15:54:56 +00:00
John Ericson
71b0edcfe3 Remove boost env vars
https://github.com/NixOS/nixpkgs/issues/86131 is now fixed!
(cherry picked from commit 459fb59493)
2025-03-28 15:54:56 +00:00
John Ericson
1763cf115b Fix a bunch of missing meson boilerplate
These other libraries need this too

(cherry picked from commit ffdce51cd5)
2025-03-28 15:54:56 +00:00
mergify[bot]
6f3dd6527d Merge pull request #12755 from NixOS/mergify/bp/2.27-maintenance/pr-12105
local-derivation-goal: improve "illegal reference" error (backport #12105)
2025-03-25 16:22:19 +00:00
Sergei Trofimovich
cadfed692c tests/functional/check-refs.nix: format newly added test
(cherry picked from commit 4d72e0f73b)
2025-03-25 15:49:31 +00:00
Sergei Trofimovich
c2cffe6249 tests/functional/check-refs.sh: guard test12 against too old nix daemon
Otherwise without the change the test fails on nix-2.26 as:

    error: derivation contains an illegal reference specifier 'dev'

Note: the error message does not match intended change.
(cherry picked from commit 1e7c7244cf)
2025-03-25 15:49:31 +00:00
Robert Hensing
6f54b90f36 test illegal reference specifier error message
(cherry picked from commit f4def47c89)
2025-03-25 15:49:31 +00:00
Robert Hensing
db1950e768 checkRefs: use concatMapStringsSep
(cherry picked from commit 2b4d461c14)
2025-03-25 15:49:30 +00:00
Robert Hensing
aa7433982b nix-util: Use small_vector in concatMapStringsSep
(cherry picked from commit 32898dc46a)
2025-03-25 15:49:30 +00:00
Robert Hensing
f9d1f36169 nix-util: Add concatMapStrings
(cherry picked from commit f3dbaa3f54)
2025-03-25 15:49:29 +00:00
Sergei Trofimovich
79122c66b1 local-derivation-goal: improve "illegal reference" error
Before the change "illegal reference" was hard to interpret as it did
not mention what derivation actually hits it.

Today's `nixpkgs` example:

Before the change:

    $ nix build --no-link -f. postgresql_14
    ...
    error: derivation contains an illegal reference specifier 'man'

After the change:

    $ nix build --no-link -f. postgresql_14
    ...
    error: derivation '/nix/store/bxp6g57limvwiga61vdlyvhy7i8rp6wd-postgresql-14.15.drv' output check for 'lib' contains an illegal reference specifier 'man', expected store path or output name (one of [debug, dev, doc, lib, out])

(cherry picked from commit bbdc3197a9)
2025-03-25 15:49:29 +00:00
Eelco Dolstra
01ffee0033 Bump version 2025-03-24 16:29:59 +01:00
Jörg Thalheim
9cb662df74 Merge pull request #12743 from NixOS/mergify/bp/2.27-maintenance/pr-12734
packaging/everything.nix: make sure doc and manpage outputs are symlinks (backport #12734)
2025-03-24 14:47:47 +01:00
Kirens
53ac3c8ba9 make sure doc and manpage outputs are symlinks
Part of https://github.com/NixOS/nixpkgs/pull/392549
The doc and manpage fix already happend in 0ddfbc5939

(cherry picked from commit 15dfeb9182)
2025-03-24 13:10:27 +00:00
Jörg Thalheim
9178731176 Merge pull request #12740 from NixOS/mergify/bp/2.27-maintenance/pr-12736
`MonitorFdHup::~MonitorFdHup`: use proper close method instead of lib… (backport #12736)
2025-03-24 13:50:33 +01:00
Jörg Thalheim
2e9a36a8fe MonitorFdHup::~MonitorFdHup: use proper close method instead of libc close()
Otherwise closing it again will cause an EBADF in the AutoCloseFd class.

(cherry picked from commit 87a34a45ff)
2025-03-24 12:17:04 +00:00
John Ericson
1a87f122f4 Merge pull request #12733 from NixOS/mergify/bp/2.27-maintenance/pr-12714
`MonitorFdHup`: replace `pthread_cancel` trick with a notification pipe (backport #12714)
2025-03-23 20:24:23 -04:00
John Ericson
490e7c0984 MonitorFdHup: Don't sleep anymore
After the previous commit it should not be necessary. Furthermore, if we
*do* sleep, we'll exacerbate a race condition (in conjunction with
getting rid of the thread cancellation) that will cause test failures.

(cherry picked from commit 49f486d8e0)
2025-03-23 23:54:11 +00:00
Jade Lovelace
27f29ff6ed daemon: remove workaround for macOS kernel bug that seems fixed
This was filed as https://github.com/nixos/nix/issues/7584, but as far
as I can tell, the previous solution of POLLHUP works just fine on macOS
14. I've also tested on an ancient machine with macOS 10.15.7, which
also has POLLHUP work correctly.

It's possible this might regress some older versions of macOS that have
a kernel bug, but I went looking through the history on the sources and
didn't find anything that looked terribly convincingly like a bug fix
between 2020 and today. If such a broken version exists, it seems pretty
reasonable to suggest simply updating the OS.

Change-Id: I178a038baa000f927ea2cbc4587d69d8ab786843

Based off of commit 69e2ee5b25752ba5fd8644cef56fb9d627ca4a64. Ericson2314 added
additional other information.

(cherry picked from commit 9b3352c3c8)
2025-03-23 23:54:10 +00:00
Félix Baylac Jacqué
ea19cb2f50 MonitorFdHup: replace pthread_cancel trick with a notification pipe
On https://github.com/NixOS/nix/issues/8946, we faced a surprising
behaviour wrt. exception when using pthread_cancel. In a nutshell when
a thread is inside a catch block and it's getting pthread_cancel by
another one, then the original exception is bubbled up and crashes the
process.

We now poll on the notification pipe from the thread and exit when the
main thread closes its end. This solution does not exhibit surprising
behaviour wrt. exceptions.

Co-authored-by: Mic92 <joerg@thalheim.io>

Fixes https://github.com/NixOS/nix/issues/8946

See also Lix https://gerrit.lix.systems/c/lix/+/1605 which is very
similar by coincidence. Pulled a comment from that.

(cherry picked from commit 1c636284a3)
2025-03-23 23:54:10 +00:00
John Ericson
df18c9b2ed MonitorFdHup: introduce a num_fds variable
Better than just putting `1` in multiple spots.

(cherry picked from commit cb95791198)
2025-03-23 23:54:10 +00:00
John Ericson
1a461baee1 MonitorFdHup: Cleanup a bit with designated initializers
(cherry picked from commit d028bb4c4a)
2025-03-23 23:54:10 +00:00
Jörg Thalheim
709e228589 MonitorFdHup: raise explicit SysError rather unreachable
Syscalls can fail for many reasons and we don't want to loose the errno
and error context.

(cherry picked from commit 8e0bc2c3a8)
2025-03-23 23:54:09 +00:00
John Ericson
7d7508fb7a monitor-fd.hh: Format
It's a pretty small diff, so let's just start formatting before we make
other changes.

(cherry picked from commit 041394b741)
2025-03-23 23:54:09 +00:00
mergify[bot]
991b297011 Merge pull request #12726 from NixOS/mergify/bp/2.27-maintenance/pr-12723
packaging/everything.nix: Fix doc and man outputs (backport #12723)
2025-03-23 11:59:19 +00:00
Sergei Zimmerman
c73f672afd packaging/everything.nix: Fix doc and man outputs
We want the $doc, $man outputs to be symlinks pointing to nix-manual and
nix-manual.man. Creating the directories first makes the `ln` command
produce symlink $doc/${nix-manual} instead.

```
$file /nix/store/q4dwlnd36gpfajgfcp6hca2xwy068wjq-nix-2.27.1-man/rwh8ky3k040wyrywl8k2v5b3csdfbdg7-nix-manual-2.27.1-man

/nix/store/q4dwlnd36gpfajgfcp6hca2xwy068wjq-nix-2.27.1-man/rwh8ky3k040wyrywl8k2v5b3csdfbdg7-nix-manual-2.27.1-man:
  symbolic link to /nix/store/rwh8ky3k040wyrywl8k2v5b3csdfbdg7-nix-manual-2.27.1-man
```

This is the reason `nix-env --help` is once again broken on 2.26/2.27/master
after 4108529.

(cherry picked from commit 0ddfbc5939)
2025-03-23 11:54:17 +00:00
mergify[bot]
e39c497cee Merge pull request #12720 from NixOS/mergify/bp/2.27-maintenance/pr-12719
rl-2.27.md: Fix GitHub links (backport #12719)
2025-03-21 19:59:15 +00:00
Eelco Dolstra
d000f5943a rl-2.27.md: Fix GitHub links
https://discourse.nixos.org/t/nix-2-27-0-released/62003/2?u=edolstra
(cherry picked from commit be5a455a1a)
2025-03-21 19:48:51 +00:00
Eelco Dolstra
624b54a392 Bump version 2025-03-21 19:31:47 +01:00
mergify[bot]
d72fc01ffd Merge pull request #12713 from NixOS/mergify/bp/2.27-maintenance/pr-12636
port crash-handler from lix to nix (backport #12636)
2025-03-21 15:45:09 +00:00
Jade Lovelace
b1f0f1c5a1 port crash-handler from lix to nix
It was first introduced in 19e0ce2c03

In Nix we only register the crash handler in main instead of initNix,
because library user may want to use their own crash handler.

Sample output:

Mar 12 08:38:06 eve nix[2303762]: Nix crashed. This is a bug. Please report this at https://github.com/NixOS/nix/issues with the following information included:
Mar 12 08:38:06 eve nix[2303762]: Exception: nix::SysError: error: writing to file: Resource temporarily unavailable
Mar 12 08:38:06 eve nix[2303762]: Stack trace:
Mar 12 08:38:06 eve nix[2303762]:  0# 0x000000000076876A in nix
                                   1# 0x00007FDA40E9F20A in /nix/store/2lhklm5aizx30qbw49acnrrzkj9lbmij-gcc-14-20241116-lib/lib/libstdc++.so.6
                                   2# std::unexpected() in /nix/store/2lhklm5aizx30qbw49acnrrzkj9lbmij-gcc-14-20241116-lib/lib/libstdc++.so.6
                                   3# 0x00007FDA40E9F487 in /nix/store/2lhklm5aizx30qbw49acnrrzkj9lbmij-gcc-14-20241116-lib/lib/libstdc++.so.6
                                   4# nix::writeFull(int, std::basic_string_view<char, std::char_traits<char> >, bool) in /home/joerg/git/nix/inst/lib/libnixutil.so
                                   5# nix::writeLine(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) in /home/joerg/git/nix/inst/lib/libnixutil.so
                                   6# nix::JSONLogger::write(nlohmann::json_abi_v3_11_3::basic_json<std::map, std::vector, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool, long, unsigned long, double, std::allocator, nlohmann::json_abi_v3_11_3::adl_serializer, std::vector<unsigned char, std::allocator<unsigned char> >, void> const&) in /home/joerg/git/nix/inst/lib/libnixutil.so
                                   7# nix::JSONLogger::logEI(nix::ErrorInfo const&) in /home/joerg/git/nix/inst/lib/libnixutil.so
                                   8# nix::Logger::logEI(nix::Verbosity, nix::ErrorInfo) in nix
                                   9# nix::handleExceptions(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::function<void ()>) in /home/joerg/git/nix/inst/lib/libnixmain.so
                                  10# 0x000000000087A563 in nix
                                  11# 0x00007FDA40BD41FE in /nix/store/6q2mknq81cyscjmkv72fpcsvan56qhmg-glibc-2.40-66/lib/libc.so.6
                                  12# __libc_start_main in /nix/store/6q2mknq81cyscjmkv72fpcsvan56qhmg-glibc-2.40-66/lib/libc.so.6
                                  13# 0x00000000006F4DF5 in nix

Co-authored-by: eldritch horrors <pennae@lix.systems>
(cherry picked from commit 163f94412a)
2025-03-21 15:31:03 +00:00
mergify[bot]
616109a040 Merge pull request #12711 from NixOS/mergify/bp/2.27-maintenance/pr-12701
stack overflow is EvalBaseError (backport #12701)
2025-03-21 14:37:25 +00:00
Shahar "Dawn" Or
3f56dd9927 stack overflow is EvalBaseError
(cherry picked from commit 23c7a45a05)
2025-03-21 14:13:40 +00:00
mergify[bot]
54bb3f54e8 Merge pull request #12696 from NixOS/mergify/bp/2.27-maintenance/pr-12682
libfetchers: fix double quote in path printed in logger (backport #12682)
2025-03-19 22:48:41 +00:00
Jörg Thalheim
0ec28acef9 libfetchers: fix double quote in path printed in logger
(cherry picked from commit 314e9fbeda)
2025-03-19 22:25:06 +00:00
mergify[bot]
b5dc44c586 Merge pull request #12691 from NixOS/mergify/bp/2.27-maintenance/pr-12687
libutil/file-descriptor: handle EAGAIN in read/write operations (backport #12687)
2025-03-19 22:08:46 +00:00
Jörg Thalheim
32ab3ef598 libutil/file-descriptor: handle EAGAIN in read/write operations
We now see exception beeing thrown when remote building in master
because of writing to a non-blocking file descriptor from our json logger.

> #0  0x00007f2ea97aea9c in __pthread_kill_implementation () from /nix/store/wn7v2vhyyyi6clcyn0s9ixvl7d4d87ic-glibc-2.40-36/lib/libc.so.6
> #1  0x00007f2ea975c576 in raise () from /nix/store/wn7v2vhyyyi6clcyn0s9ixvl7d4d87ic-glibc-2.40-36/lib/libc.so.6
> #2  0x00007f2ea9744935 in abort () from /nix/store/wn7v2vhyyyi6clcyn0s9ixvl7d4d87ic-glibc-2.40-36/lib/libc.so.6
> #3  0x00007f2ea99e8c2b in __gnu_cxx::__verbose_terminate_handler() [clone .cold] () from /nix/store/ybjcla5bhj8g1y84998pn4a2drfxybkv-gcc-13.3.0-lib/lib/libstdc++.so.6
> #4  0x00007f2ea99f820a in __cxxabiv1::__terminate(void (*)()) () from /nix/store/ybjcla5bhj8g1y84998pn4a2drfxybkv-gcc-13.3.0-lib/lib/libstdc++.so.6
> #5  0x00007f2ea99f8275 in std::terminate() () from /nix/store/ybjcla5bhj8g1y84998pn4a2drfxybkv-gcc-13.3.0-lib/lib/libstdc++.so.6
> #6  0x00007f2ea99f84c7 in __cxa_throw () from /nix/store/ybjcla5bhj8g1y84998pn4a2drfxybkv-gcc-13.3.0-lib/lib/libstdc++.so.6
> #7  0x00007f2eaa5035c2 in nix::writeFull (fd=2, s=..., allowInterrupts=true) at ../unix/file-descriptor.cc:43
> #8  0x00007f2eaa5633c4 in nix::JSONLogger::write (this=this@entry=0x249a7d40, json=...) at /nix/store/4krab2h0hd4wvxxmscxrw21pl77j4i7j-gcc-13.3.0/include/c++/13.3.0/bits/char_traits.h:358
> #9  0x00007f2eaa5658d7 in nix::JSONLogger::logEI (this=<optimized out>, ei=...) at ../logging.cc:242
> #10 0x00007f2ea9c5d048 in nix::Logger::logEI (ei=..., lvl=nix::lvlError, this=0x249a7d40) at /nix/store/a7cq5bqh0ryvnkv4m19ffchnvi8l9qx6-nix-util-2.27.0-dev/include/nix/logging.hh:108
> #11 nix::handleExceptions (programName="nix", fun=...) at ../shared.cc:343
> #12 0x0000000000465b1f in main (argc=<optimized out>, argv=<optimized out>) at /nix/store/4krab2h0hd4wvxxmscxrw21pl77j4i7j-gcc-13.3.0/include/c++/13.3.0/bits/allocator.h:163
> (gdb) frame 10
> #10 0x00007f2ea9c5d048 in nix::Logger::logEI (ei=..., lvl=nix::lvlError, this=0x249a7d40) at /nix/store/a7cq5bqh0ryvnkv4m19ffchnvi8l9qx6-nix-util-2.27.0-dev/include/nix/logging.hh:108
> 108             logEI(ei);

So far only drainFD sets the non-blocking flag on a "readable" file descriptor,
while this is a "writeable" file descriptor.
It's not clear to me yet, why we see logs after that point, but it's
also not that bad to handle EAGAIN in read/write functions after all.

(cherry picked from commit 2790f5f9ae)
2025-03-19 21:46:21 +00:00
mergify[bot]
8705feb7cc Merge pull request #12686 from NixOS/mergify/bp/2.27-maintenance/pr-12570
Fix macos sandbox issue (backport #12570)
2025-03-19 21:23:43 +00:00
Pierre-Etienne Meunier
aecd2b5d92 Fix macos sandbox issue
Co-authored-by: John Ericson <git@JohnEricson.me>

Co-authored-by: Poliorcetics <poliorcetics@users.noreply.github.com>
(cherry picked from commit 300465c7b8)
2025-03-19 20:21:53 +00:00
mergify[bot]
bdaa8c55d2 Merge pull request #12655 from NixOS/mergify/bp/2.27-maintenance/pr-12645
Make debugger significantly faster (backport #12645)
2025-03-14 13:54:47 +00:00
Sergei Zimmerman
11919bc471 {libexpr,libcmd}: Make debugger significantly faster
The underlying issue is that debugger code path was
calling PosTable::operator[] in each eval method.
This has become incredibly expensive since 5d9fdab3de.

While we are it it, I've reworked the code to
not use std::shared_ptr where it really isn't necessary.

As I've documented in previous commits, this is actually
more a workaround for recursive header dependencies now
and is only necessary in `error.hh` code.

Some ad-hoc benchmarking:

After this commit:

```
Benchmark 1: nix eval nixpkgs#hello --impure --ignore-try --no-eval-cache --debugger
  Time (mean ± σ):     784.2 ms ±   7.1 ms    [User: 561.4 ms, System: 147.7 ms]
  Range (min … max):   773.5 ms … 792.6 ms    10 runs
```

On master 3604c7c51:

```
Benchmark 1: nix eval nixpkgs#hello --impure --ignore-try --no-eval-cache --debugger
  Time (mean ± σ):     22.914 s ±  0.178 s    [User: 18.524 s, System: 4.151 s]
  Range (min … max):   22.738 s … 23.290 s    10 runs
```

(cherry picked from commit adbd08399c)
2025-03-14 13:22:53 +00:00
Sergei Zimmerman
593e0eebeb libutil: Fix Pos::getSourcePath
Previous implementation didn't actually check if
std::get_if returned a nullptr:

std::optional<SourcePath> getSourcePath() const {
    return *std::get_if<SourcePath>(&origin);
}

(cherry picked from commit 50123f2a56)
2025-03-14 13:22:52 +00:00
Sergei Zimmerman
8c2a792d2b libutil: Document hacks and problems around Pos class
This should provide context for follow-up commits in
the patch series.

(cherry picked from commit bf12aedf2e)
2025-03-14 13:22:52 +00:00
Sergei Zimmerman
b540c2419f {libutil,libexpr}: Move pos-idx,pos-table code to libutil
All of this code doesn't actually depend on anything from
libexpr. Because Pos is so tigtly coupled with Error, it
makes sense to have in the same library.

(cherry picked from commit a53b184e63)
2025-03-14 13:22:52 +00:00
mergify[bot]
96f0fd3ce0 Merge pull request #12605 from NixOS/mergify/bp/2.27-maintenance/pr-12604
Fix chopped up repl output (backport #12604)
2025-03-04 19:33:00 +00:00
Robert Hensing
dc6a936d97 repl: Fix :print corruption
See preceding commits.

(cherry picked from commit 1e1c587073)
2025-03-04 19:10:02 +00:00
Robert Hensing
ac3fc8876c refactor: RAII logger suspension
(cherry picked from commit 30694b5d8a)
2025-03-04 19:10:01 +00:00
Robert Hensing
375df6c086 repl: Fix value printing corruption
The resume call would get some non-flushed(?) data.
Extending the pause to include the newline makes the complete flush
part of the pause.

(cherry picked from commit 880489051a)
2025-03-04 19:10:01 +00:00
Robert Hensing
88e6b7d6b2 progress-bar: Make pause/resume nestable
(cherry picked from commit 49d8ee5359)
2025-03-04 19:10:01 +00:00
mergify[bot]
181ffe30be Merge pull request #12602 from NixOS/mergify/bp/2.27-maintenance/pr-12600
packaging: Typo in setVersionLayer / preConfigure (backport #12600)
2025-03-04 17:09:29 +00:00
Robert Hensing
afad1e536e packaging: Typo in setVersionLayer / preConfigure
Apparently dead code in our use case, but good to keep nonetheless.
Credit: ztzg in https://github.com/NixOS/nix/pull/12498#pullrequestreview-2658031853

(cherry picked from commit dcaea8cb1c)
2025-03-04 16:46:18 +00:00
John Ericson
fffb54d8f7 Merge pull request #12594 from NixOS/mergify/bp/2.27-maintenance/pr-12442
Expand manual on derivation outputs (backport #12442)
2025-03-03 17:28:32 -05:00
Robert Hensing
8b9d401fe4 manual: Edit
(cherry picked from commit 1e00d14c29)
2025-03-03 22:13:09 +00:00
John Ericson
f278a631b0 Expand manual on derivation outputs
Note, this includes some text adapted from from Eelco's dissertation

(cherry picked from commit 2aa6e0f084)
2025-03-03 22:13:08 +00:00
mergify[bot]
7e61e9650c Merge pull request #12590 from NixOS/mergify/bp/2.27-maintenance/pr-12582
packaging/everything.nix: Use a multi-output derivation (backport #12582)
2025-03-02 13:16:07 +00:00
Robert Hensing
7e7e9d9eab packaging/everything.nix: Use a multi-output derivation
This should fix a few packaging regressions.

`dev` also includes a merged `includes/`, which may be helpful until
inter-component includes are fixed properly.

(cherry picked from commit 41085295ab)
2025-03-02 13:09:49 +00:00
Robert Hensing
863c1b60d2 Merge pull request #12576 from obsidiansystems/2.27-no-dyn-drv
[2.27] Once again revert "Adapt scheduler to work with dynamic derivations"
2025-02-27 20:56:16 +01:00
John Ericson
f636ced7d2 Revert "Revert "Revert "Adapt scheduler to work with dynamic derivations"""
The bug reappeared after all, and the fix introduced a different bug. We
want to release 2.27 imminently so there is no time to do a proper fix,
which appears to require a larger reworking. Hopefully we will have it
for 2.28, however.

This reverts commit c98525235f.
2025-02-27 13:42:57 -05:00
Eelco Dolstra
494953cfb6 Mark official release 2025-02-27 17:03:27 +01:00
137 changed files with 1711 additions and 1087 deletions

2
.gitignore vendored
View File

@@ -14,7 +14,7 @@
/tests/functional/lang/*.err
/tests/functional/lang/*.ast
outputs/
/outputs
*~

View File

@@ -1 +1 @@
2.27.0
2.27.2

View File

@@ -22,7 +22,10 @@
- [Store Object](store/store-object.md)
- [Content-Addressing Store Objects](store/store-object/content-address.md)
- [Store Path](store/store-path.md)
- [Store Derivation and Deriving Path](store/drv.md)
- [Store Derivation and Deriving Path](store/derivation/index.md)
- [Derivation Outputs and Types of Derivations](store/derivation/outputs/index.md)
- [Content-addressing derivation outputs](store/derivation/outputs/content-address.md)
- [Input-addressing derivation outputs](store/derivation/outputs/input-address.md)
- [Building](store/building.md)
- [Store Types](store/types/index.md)
{{#include ./store/types/SUMMARY.md}}

View File

@@ -20,7 +20,7 @@ For a local machine to forward a build to a remote machine, the remote machine m
## Testing
To test connecting to a remote Nix instance (in this case `mac`), run:
To test connecting to a remote [Nix instance] (in this case `mac`), run:
```console
nix store info --store ssh://username@mac
@@ -106,3 +106,5 @@ file included in `builders` via the syntax `@/path/to/file`. For example,
causes the list of machines in `/etc/nix/machines` to be included.
(This is the default.)
[Nix instance]: @docroot@/glossary.md#gloss-nix-instance

View File

@@ -1,5 +1,13 @@
# Glossary
- [build system]{#gloss-build-system}
Generic term for software that facilitates the building of software by automating the invocation of compilers, linkers, and other tools.
Nix can be used as a generic build system.
It has no knowledge of any particular programming language or toolchain.
These details are specified in [derivation expressions](#gloss-derivation-expression).
- [content address]{#gloss-content-address}
A
@@ -19,10 +27,14 @@
Besides content addressing, the Nix store also uses [input addressing](#gloss-input-addressed-store-object).
- [content-addressed storage]{#gloss-content-addressed-store}
The industry term for storage and retrieval systems using [content addressing](#gloss-content-address). A Nix store also has [input addressing](#gloss-input-addressed-store-object), and metadata.
- [store derivation]{#gloss-store-derivation}
A single build task.
See [Store Derivation](@docroot@/store/drv.md#store-derivation) for details.
See [Store Derivation](@docroot@/store/derivation/index.md#store-derivation) for details.
[store derivation]: #gloss-store-derivation
@@ -30,7 +42,7 @@
A [store path] which uniquely identifies a [store derivation].
See [Referencing Store Derivations](@docroot@/store/drv.md#derivation-path) for details.
See [Referencing Store Derivations](@docroot@/store/derivation/index.md#derivation-path) for details.
Not to be confused with [deriving path].
@@ -88,6 +100,12 @@
[store]: #gloss-store
- [Nix instance]{#gloss-nix-instance}
<!-- ambiguous -->
1. An installation of Nix, which includes the presence of a [store], and the Nix package manager which operates on that store.
A local Nix installation and a [remote builder](@docroot@/advanced-topics/distributed-builds.md) are two examples of Nix instances.
2. A running Nix process, such as the `nix` command.
- [binary cache]{#gloss-binary-cache}
A *binary cache* is a Nix store which uses a different format: its
@@ -220,7 +238,7 @@
directly or indirectly “reachable” from that store path; that is,
its the closure of the path under the *references* relation. For
a package, the closure of its derivation is equivalent to the
build-time dependencies, while the closure of its output path is
build-time dependencies, while the closure of its [output path] is
equivalent to its runtime dependencies. For correct deployment it
is necessary to deploy whole closures, since otherwise at runtime
files could be missing. The command `nix-store --query --requisites ` prints out
@@ -252,7 +270,7 @@
Deriving paths are a way to refer to [store objects][store object] that might not yet be [realised][realise].
See [Deriving Path](./store/drv.md#deriving-path) for details.
See [Deriving Path](./store/derivation/index.md#deriving-path) for details.
Not to be confused with [derivation path].

View File

@@ -99,8 +99,8 @@ Derivations can declare some infrequently used optional attributes.
to make it use the proxy server configuration specified by the user
in the environment variables `http_proxy` and friends.
This attribute is only allowed in *fixed-output derivations* (see
below), where impurities such as these are okay since (the hash
This attribute is only allowed in [fixed-output derivations][fixed-output derivation],
where impurities such as these are okay since (the hash
of) the output is known in advance. It is ignored for all other
derivations.
@@ -119,135 +119,6 @@ Derivations can declare some infrequently used optional attributes.
[`impure-env`](@docroot@/command-ref/conf-file.md#conf-impure-env)
configuration setting.
- [`outputHash`]{#adv-attr-outputHash}; [`outputHashAlgo`]{#adv-attr-outputHashAlgo}; [`outputHashMode`]{#adv-attr-outputHashMode}\
These attributes declare that the derivation is a so-called *fixed-output derivation* (FOD), which means that a cryptographic hash of the output is already known in advance.
As opposed to regular derivations, the [`builder`] executable of a fixed-output derivation has access to the network.
Nix computes a cryptographic hash of its output and compares that to the hash declared with these attributes.
If there is a mismatch, the derivation fails.
The rationale for fixed-output derivations is derivations such as
those produced by the `fetchurl` function. This function downloads a
file from a given URL. To ensure that the downloaded file has not
been modified, the caller must also specify a cryptographic hash of
the file. For example,
```nix
fetchurl {
url = "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}
```
It sometimes happens that the URL of the file changes, e.g., because
servers are reorganised or no longer available. We then must update
the call to `fetchurl`, e.g.,
```nix
fetchurl {
url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}
```
If a `fetchurl` derivation was treated like a normal derivation, the
output paths of the derivation and *all derivations depending on it*
would change. For instance, if we were to change the URL of the
Glibc source distribution in Nixpkgs (a package on which almost all
other packages depend) massive rebuilds would be needed. This is
unfortunate for a change which we know cannot have a real effect as
it propagates upwards through the dependency graph.
For fixed-output derivations, on the other hand, the name of the
output path only depends on the `outputHash*` and `name` attributes,
while all other attributes are ignored for the purpose of computing
the output path. (The `name` attribute is included because it is
part of the path.)
As an example, here is the (simplified) Nix expression for
`fetchurl`:
```nix
{ stdenv, curl }: # The curl program is used for downloading.
{ url, sha256 }:
stdenv.mkDerivation {
name = baseNameOf (toString url);
builder = ./builder.sh;
buildInputs = [ curl ];
# This is a fixed-output derivation; the output must be a regular
# file with SHA256 hash sha256.
outputHashMode = "flat";
outputHashAlgo = "sha256";
outputHash = sha256;
inherit url;
}
```
The `outputHash` attribute must be a string containing the hash in either hexadecimal or "nix32" encoding, or following the format for integrity metadata as defined by [SRI](https://www.w3.org/TR/SRI/).
The "nix32" encoding is an adaptation of base-32 encoding.
The [`convertHash`](@docroot@/language/builtins.md#builtins-convertHash) function shows how to convert between different encodings, and the [`nix-hash` command](../command-ref/nix-hash.md) has information about obtaining the hash for some contents, as well as converting to and from encodings.
The `outputHashAlgo` attribute specifies the hash algorithm used to compute the hash.
It can currently be `"blake3", "sha1"`, `"sha256"`, `"sha512"`, or `null`.
`outputHashAlgo` can only be `null` when `outputHash` follows the SRI format.
The `outputHashMode` attribute determines how the hash is computed.
It must be one of the following values:
- [`"flat"`](@docroot@/store/store-object/content-address.md#method-flat)
This is the default.
- [`"recursive"` or `"nar"`](@docroot@/store/store-object/content-address.md#method-nix-archive)
> **Compatibility**
>
> `"recursive"` is the traditional way of indicating this,
> and is supported since 2005 (virtually the entire history of Nix).
> `"nar"` is more clear, and consistent with other parts of Nix (such as the CLI),
> however support for it is only added in Nix version 2.21.
- [`"text"`](@docroot@/store/store-object/content-address.md#method-text)
> **Warning**
>
> The use of this method for derivation outputs is part of the [`dynamic-derivations`][xp-feature-dynamic-derivations] experimental feature.
- [`"git"`](@docroot@/store/store-object/content-address.md#method-git)
> **Warning**
>
> This method is part of the [`git-hashing`][xp-feature-git-hashing] experimental feature.
- [`__contentAddressed`]{#adv-attr-__contentAddressed}
> **Warning**
> This attribute is part of an [experimental feature](@docroot@/development/experimental-features.md).
>
> To use this attribute, you must enable the
> [`ca-derivations`][xp-feature-ca-derivations] experimental feature.
> For example, in [nix.conf](../command-ref/conf-file.md) you could add:
>
> ```
> extra-experimental-features = ca-derivations
> ```
If this attribute is set to `true`, then the derivation
outputs will be stored in a content-addressed location rather than the
traditional input-addressed one.
Setting this attribute also requires setting
[`outputHashMode`](#adv-attr-outputHashMode)
and
[`outputHashAlgo`](#adv-attr-outputHashAlgo)
like for *fixed-output derivations* (see above).
It also implicitly requires that the machine to build the derivation must have the `ca-derivations` [system feature](@docroot@/command-ref/conf-file.md#conf-system-features).
- [`passAsFile`]{#adv-attr-passAsFile}\
A list of names of attributes that should be passed via files rather
than environment variables. For example, if you have
@@ -370,6 +241,134 @@ Derivations can declare some infrequently used optional attributes.
ensures that the derivation can only be built on a machine with the `kvm` feature.
[xp-feature-ca-derivations]: @docroot@/development/experimental-features.md#xp-feature-ca-derivations
## Setting the derivation type
As discussed in [Derivation Outputs and Types of Derivations](@docroot@/store/derivation/outputs/index.md), there are multiples kinds of derivations / kinds of derivation outputs.
The choice of the following attributes determines which kind of derivation we are making.
- [`__contentAddressed`]
- [`outputHash`]
- [`outputHashAlgo`]
- [`outputHashMode`]
The three types of derivations are chosen based on the following combinations of these attributes.
All other combinations are invalid.
- [Input-addressing derivations](@docroot@/store/derivation/outputs/input-address.md)
This is the default for `builtins.derivation`.
Nix only currently supports one kind of input-addressing, so no other information is needed.
`__contentAddressed = false;` may also be included, but is not needed, and will trigger the experimental feature check.
- [Fixed-output derivations][fixed-output derivation]
All of [`outputHash`], [`outputHashAlgo`], and [`outputHashMode`].
<!--
`__contentAddressed` is ignored, becaused fixed-output derivations always content-address their outputs, by definition.
**TODO CHECK**
-->
- [(Floating) content-addressing derivations](@docroot@/store/derivation/outputs/content-address.md)
Both [`outputHashAlgo`] and [`outputHashMode`], `__contentAddressed = true;`, and *not* `outputHash`.
If an output hash was given, then the derivation output would be "fixed" not "floating".
Here is more information on the `output*` attributes, and what values they may be set to:
- [`outputHashMode`]{#adv-attr-outputHashMode}
This specifies how the files of a content-addressing derivation output are digested to produce a content address.
This works in conjunction with [`outputHashAlgo`](#adv-attr-outputHashAlgo).
Specifying one without the other is an error (unless [`outputHash` is also specified and includes its own hash algorithm as described below).
The `outputHashMode` attribute determines how the hash is computed.
It must be one of the following values:
- [`"flat"`](@docroot@/store/store-object/content-address.md#method-flat)
This is the default.
- [`"recursive"` or `"nar"`](@docroot@/store/store-object/content-address.md#method-nix-archive)
> **Compatibility**
>
> `"recursive"` is the traditional way of indicating this,
> and is supported since 2005 (virtually the entire history of Nix).
> `"nar"` is more clear, and consistent with other parts of Nix (such as the CLI),
> however support for it is only added in Nix version 2.21.
- [`"text"`](@docroot@/store/store-object/content-address.md#method-text)
> **Warning**
>
> The use of this method for derivation outputs is part of the [`dynamic-derivations`][xp-feature-dynamic-derivations] experimental feature.
- [`"git"`](@docroot@/store/store-object/content-address.md#method-git)
> **Warning**
>
> This method is part of the [`git-hashing`][xp-feature-git-hashing] experimental feature.
See [content-addressing store objects](@docroot@/store/store-object/content-address.md) for more information about the process this flag controls.
- [`outputHashAlgo`]{#adv-attr-outputHashAlgo}
This specifies the hash alorithm used to digest the [file system object] data of a content-addressing derivation output.
This works in conjunction with [`outputHashMode`](#adv-attr-outputHashAlgo).
Specifying one without the other is an error (unless [`outputHash` is also specified and includes its own hash algorithm as described below).
The `outputHashAlgo` attribute specifies the hash algorithm used to compute the hash.
It can currently be `"blake3"`, "sha1"`, `"sha256"`, `"sha512"`, or `null`.
`outputHashAlgo` can only be `null` when `outputHash` follows the SRI format, because in that case the choice of hash algorithm is determined by `outputHash`.
- [`outputHash`]{#adv-attr-outputHashAlgo}; [`outputHash`]{#adv-attr-outputHashMode}\
This will specify the output hash of the single output of a [fixed-output derivation].
The `outputHash` attribute must be a string containing the hash in either hexadecimal or "nix32" encoding, or following the format for integrity metadata as defined by [SRI](https://www.w3.org/TR/SRI/).
The "nix32" encoding is an adaptation of base-32 encoding.
> **Note**
>
> The [`convertHash`](@docroot@/language/builtins.md#builtins-convertHash) function shows how to convert between different encodings.
> The [`nix-hash` command](../command-ref/nix-hash.md) has information about obtaining the hash for some contents, as well as converting to and from encodings.
- [`__contentAddressed`]{#adv-attr-__contentAddressed}
> **Warning**
>
> This attribute is part of an [experimental feature](@docroot@/development/experimental-features.md).
>
> To use this attribute, you must enable the
> [`ca-derivations`][xp-feature-ca-derivations] experimental feature.
> For example, in [nix.conf](../command-ref/conf-file.md) you could add:
>
> ```
> extra-experimental-features = ca-derivations
> ```
This is a boolean with a default of `false`.
It determines whether the derivation is floating content-addressing.
[`__contentAddressed`]: #adv-attr-__contentAddressed
[`outputHash`]: #adv-attr-outputHash
[`outputHashAlgo`]: #adv-attr-outputHashAlgo
[`outputHashMode`]: #adv-attr-outputHashMode
[fixed-output derivation]: @docroot@/glossary.md#gloss-fixed-output-derivation
[file system object]: @docroot@/store/file-system-object.md
[store object]: @docroot@/store/store-object.md
[xp-feature-dynamic-derivations]: @docroot@/development/experimental-features.md#xp-feature-dynamic-derivations
[xp-feature-git-hashing]: @docroot@/development/experimental-features.md#xp-feature-git-hashing

View File

@@ -1,7 +1,7 @@
# Derivations
The most important built-in function is `derivation`, which is used to describe a single store-layer [store derivation].
Consult the [store chapter](@docroot@/store/drv.md) for what a store derivation is;
Consult the [store chapter](@docroot@/store/derivation/index.md) for what a store derivation is;
this section just concerns how to create one from the Nix language.
This builtin function takes as input an attribute set, the attributes of which specify the inputs to the process.
@@ -16,7 +16,7 @@ It outputs an attribute set, and produces a [store derivation] as a side effect
- [`name`]{#attr-name} ([String](@docroot@/language/types.md#type-string))
A symbolic name for the derivation.
See [derivation outputs](@docroot@/store/drv.md#outputs) for what this is affects.
See [derivation outputs](@docroot@/store/derivation/index.md#outputs) for what this is affects.
[store path]: @docroot@/store/store-path.md
@@ -34,7 +34,7 @@ It outputs an attribute set, and produces a [store derivation] as a side effect
- [`system`]{#attr-system} ([String](@docroot@/language/types.md#type-string))
See [system](@docroot@/store/drv.md#system).
See [system](@docroot@/store/derivation/index.md#system).
> **Example**
>
@@ -64,7 +64,7 @@ It outputs an attribute set, and produces a [store derivation] as a side effect
- [`builder`]{#attr-builder} ([Path](@docroot@/language/types.md#type-path) | [String](@docroot@/language/types.md#type-string))
See [builder](@docroot@/store/drv.md#builder).
See [builder](@docroot@/store/derivation/index.md#builder).
> **Example**
>
@@ -113,7 +113,7 @@ It outputs an attribute set, and produces a [store derivation] as a side effect
Default: `[ ]`
See [args](@docroot@/store/drv.md#args).
See [args](@docroot@/store/derivation/index.md#args).
> **Example**
>

View File

@@ -53,7 +53,7 @@ where
method of content addressing store objects,
if the hash algorithm is [SHA-256].
Just like in the "Text" case, we can have the store objects referenced by their paths.
Additionally, we can have an optional `:self` label to denote self reference.
Additionally, we can have an optional `:self` label to denote self-reference.
- ```ebnf
| "output:" id

View File

@@ -30,14 +30,23 @@
The evaluator now presents a "union" filesystem view of the `/nix/store` in the host and the chroot.
This change also removes some hacks that broke `builtins.{path,filterSource}` in chroot stores [#11503](https://github.com/NixOS/nix/issue/11503).
This change also removes some hacks that broke `builtins.{path,filterSource}` in chroot stores [#11503](https://github.com/NixOS/nix/issues/11503).
- `nix flake prefetch` now has a `--out-link` option [#12443](https://github.com/NixOS/nix/issue/12443)
- `nix flake prefetch` now has a `--out-link` option [#12443](https://github.com/NixOS/nix/pull/12443)
- Set `FD_CLOEXEC` on sockets created by curl [#12439](https://github.com/NixOS/nix/pull/12439)
Curl created sockets without setting `FD_CLOEXEC`/`SOCK_CLOEXEC`. This could previously cause connections to remain open forever when using commands like `nix shell`. This change sets the `FD_CLOEXEC` flag using a `CURLOPT_SOCKOPTFUNCTION` callback.
- Add BLAKE3 hash algorithm [#12379](https://github.com/NixOS/nix/pull/12379)
Nix now supports the BLAKE3 hash algorithm as an experimental feature (`blake3-hashes`):
```console
# nix hash file ./file --type blake3 --extra-experimental-features blake3-hashes
blake3-34P4p+iZXcbbyB1i4uoF7eWCGcZHjmaRn6Y7QdynLwU=
```
# Contributors
This release was made possible by the following 21 contributors:

View File

@@ -10,7 +10,7 @@
## Builder Execution
The [`builder`](./drv.md#builder) is executed as follows:
The [`builder`](./derivation/index.md#builder) is executed as follows:
- A temporary directory is created under the directory specified by
`TMPDIR` (default `/tmp`) where the build will take place. The
@@ -54,7 +54,7 @@ The [`builder`](./drv.md#builder) is executed as follows:
its `out`.)
- If an output path already exists, it is removed. Also, locks are
acquired to prevent multiple Nix instances from performing the same
acquired to prevent multiple [Nix instances][Nix instance] from performing the same
build at the same time.
- A log of the combined standard output and error is written to
@@ -95,3 +95,6 @@ If the builder exited successfully, the following steps happen in order to turn
Nix also scans for references to other outputs' paths in the same way, because outputs are allowed to refer to each other.
If the outputs' references to each other form a cycle, this is an error, because the references of store objects much be acyclic.
[Nix instance]: @docroot@/glossary.md#gloss-nix-instance

View File

@@ -1,7 +1,7 @@
# Store Derivation and Deriving Path
Besides functioning as a [content addressed store] the Nix store layer works as a [build system].
Other system (like Git or IPFS) also store and transfer immutable data, but they don't concern themselves with *how* that data was created.
Besides functioning as a [content-addressed store], the Nix store layer works as a [build system].
Other systems (like Git or IPFS) also store and transfer immutable data, but they don't concern themselves with *how* that data was created.
This is where Nix distinguishes itself.
*Derivations* represent individual build steps, and *deriving paths* are needed to refer to the *outputs* of those build steps before they are built.
@@ -9,15 +9,24 @@ This is where Nix distinguishes itself.
## Store Derivation {#store-derivation}
A derivation is a specification for running an executable on precisely defined input files to repeatably produce output files at uniquely determined file system paths.
A derivation is a specification for running an executable on precisely defined input to produce on more [store objects][store object].
These store objects are known as the derivation's *outputs*.
Derivations are *built*, in which case the process is spawned according to the spec, and when it exits, required to leave behind files which will (after post-processing) become the outputs of the derivation.
This process is described in detail in [Building](@docroot@/store/building.md).
<!--
Some of these things are described directly below, but we envision with more material the exposition will probably want to migrate to separate pages benough this.
See outputs spec for an example of this one that migrated to its own page.
-->
A derivation consists of:
- A name
- A set of [*inputs*][inputs], a set of [deriving paths][deriving path]
- An [inputs specification][inputs], a set of [deriving paths][deriving path]
- A map of [*outputs*][outputs], from names to other data
- An [outputs specification][outputs], specifying which outputs should be produced, and various metadata about them.
- The ["system" type][system] (e.g. `x86_64-linux`) where the executable is to run.
@@ -26,13 +35,15 @@ A derivation consists of:
[store derivation]: #store-derivation
[inputs]: #inputs
[input]: #inputs
[outputs]: #outputs
[output]: #outputs
[outputs]: ./outputs/index.md
[output]: ./outputs/index.md
[process creation fields]: #process-creation-fields
[builder]: #builder
[args]: #args
[env]: #env
[system]: #system
[content-addressed store]: @docroot@/glossary.md#gloss-content-addressed-store
[build system]: @docroot@/glossary.md#gloss-build-system
### Referencing derivations {#derivation-path}
@@ -69,7 +80,7 @@ type DerivingPath = ConstantPath | OutputPath;
```
Deriving paths are necessary because, in general and particularly for [content-addressing derivations][content-addressing derivation], the [store path] of an [output] is not known in advance.
We can use an output deriving path to refer to such an out, instead of the store path which we do not yet know.
We can use an output deriving path to refer to such an output, instead of the store path which we do not yet know.
[deriving path]: #deriving-path
[validity]: @docroot@/glossary.md#gloss-validity
@@ -80,47 +91,26 @@ A derivation is constructed from the parts documented in the following subsectio
### Inputs {#inputs}
The inputs are a set of [deriving paths][deriving path], refering to all store objects needed in order to perform this build step.
The inputs are a set of [deriving paths][deriving path], referring to all store objects needed in order to perform this build step.
The [process creation fields] will presumably include many [store paths][store path]:
- The path to the executable normally starts with a store path
- The arguments and environment variables likely contain many other store paths.
But rather than somehow scanning all the other fields for inputs, Nix requires that all inputs be explicitly collected in the inputs field. It is instead the responsibility of the creator of a derivation (e.g. the evaluator) to ensure that every store object referenced in another field (e.g. referenced by store path) is included in this inputs field.
### Outputs {#outputs}
The outputs are the derivations are the [store objects][store object] it is obligated to produce.
Outputs are assigned names, and also consistent of other information based on the type of derivation.
Output names can be any string which is also a valid [store path] name.
The store path of the output store object (also called an [output path] for short), has a name based on the derivation name and the output name.
In the general case, store paths have name `derivationName + "-" + outputName`.
However, an output named "out" has a store path with name is just the derivation name.
This is to allow derivations with a single output to avoid a superfluous `"-${outputName}"` in their single output's name when no disambiguation is needed.
> **Example**
>
> A derivation is named `hello`, and has two outputs, `out`, and `dev`
>
> - The derivation's path will be: `/nix/store/<hash>-hello.drv`.
>
> - The store path of `out` will be: `/nix/store/<hash>-hello`.
>
> - The store path of `dev` will be: `/nix/store/<hash>-hello-dev`.
But rather than somehow scanning all the other fields for inputs, Nix requires that all inputs be explicitly collected in the inputs field. It is instead the responsibility of the creator of a derivation (e.g. the evaluator) to ensure that every store object referenced in another field (e.g. referenced by store path) is included in this inputs field.
### System {#system}
The system type on which the [`builder`](#attr-builder) executable is meant to be run.
A necessary condition for Nix to schedule a given derivation on some Nix instance is for the "system" of that derivation to match that instance's [`system` configuration option].
A necessary condition for Nix to schedule a given derivation on some [Nix instance] is for the "system" of that derivation to match that instance's [`system` configuration option] or [`extra-platforms` configuration option].
By putting the `system` in each derivation, Nix allows *heterogenous* build plans, where not all steps can be run on the same machine or same sort of machine.
Nix can schedule builds such that it automatically builds on other platforms by [forwarding build requests](@docroot@/advanced-topics/distributed-builds.md) to other Nix instances.
[`system` configuration option]: @docroot@/command-ref/conf-file.md#conf-system
[`extra-platforms` configuration option]: @docroot@/command-ref/conf-file.md#conf-extra-platforms
[content-addressing derivation]: @docroot@/glossary.md#gloss-content-addressing-derivation
[realise]: @docroot@/glossary.md#gloss-realise
@@ -253,14 +243,14 @@ That works because we've implicitly assumed that all derivations are created *st
But what if derivations could also be created dynamically within Nix?
In other words, what if derivations could be the outputs of other derivations?
:::{.note}
In the parlance of "Build Systems à la carte", we are generalizing the Nix store layer to be a "Monadic" instead of "Applicative" build system.
:::
> **Note**
>
> In the parlance of "Build Systems à la carte", we are generalizing the Nix store layer to be a "Monadic" instead of "Applicative" build system.
How should we refer to such derivations?
A deriving path works, the same as how we refer to other derivation outputs.
But what about a dynamic derivations output?
(i.e. how do we refer to the output of an output of a derivation?)
(i.e. how do we refer to the output of a derivation, which is itself an output of a derivation?)
For that we need to generalize the definition of deriving path, replacing the store path used to refer to the derivation with a nested deriving path:
```diff
@@ -308,3 +298,5 @@ The result of this is that it is possible to have a chain of `^<output-name>` at
> |------------------------------------------------------------| |-----|
> innermost constant store path (usual encoding) output name
> ```
[Nix instance]: @docroot@/glossary.md#gloss-nix-instance

View File

@@ -0,0 +1,192 @@
# Content-addressing derivation outputs
The content-addressing of an output only depends on that store object itself, not any other information external (such has how it was made, when it was made, etc.).
As a consequence, a store object will be content-addressed the same way regardless of whether it was manually inserted into the store, outputted by some derivation, or outputted by a some other derivation.
The output spec for a content-addressed output must contains the following field:
- *method*: how the data of the store object is digested into a content address
The possible choices of *method* are described in the [section on content-addressing store objects](@docroot@/store/store-object/content-address.md).
Given the method, the output's name (computed from the derivation name and output spec mapping as described above), and the data of the store object, the output's store path will be computed as described in that section.
## Fixed-output content-addressing {#fixed}
In this case the content address of the *fixed* in advanced by the derivation itself.
In other words, when the derivation has finished [building](@docroot@/store/building.md), and the provisional output' content-address is computed as part of the process to turn it into a *bona fide* store object, the calculated content address must much that given in the derivation, or the build of that derivation will be deemed a failure.
The output spec for an output with a fixed content addresses additionally contains:
- *hash*, the hash expected from digesting the store object's file system objects.
This hash may be of a freely-chosen hash algorithm (that Nix supports)
> **Design note**
>
> In principle, the output spec could also specify the references the store object should have, since the references and file system objects are equally parts of a content-addressed store object proper that contribute to its content-addressed.
> However, at this time, the references are not not done because all fixed content-addressed outputs are required to have no references (including no self-reference).
>
> Also in principle, rather than specifying the references and file system object data with separate hashes, a single hash that constraints both could be used.
> This could be done with the final store path's digest, or better yet, the hash that will become the store path's digest before it is truncated.
>
> These possible future extensions are included to elucidate the core property of fixed-output content addressing --- that all parts of the output must be cryptographically fixed with one or more hashes --- separate from the particulars of the currently-supported store object content-addressing schemes.
### Design rationale
What is the purpose of fixing an output's content address in advanced?
In abstract terms, the answer is carefully controlled impurity.
Unlike a regular derivation, the [builder] executable of a derivation that produced fixed outputs has access to the network.
The outputs' guaranteed content-addresses are supposed to mitigate the risk of the builder being given these capabilities;
regardless of what the builder does *during* the build, it cannot influence downstream builds in unanticipated ways because all information it passed downstream flows through the outputs whose content-addresses are fixed.
[builder]: @docroot@/store/derivation/index.md#builder
In concrete terms, the purpose of this feature is fetching fixed input data like source code from the network.
For example, consider a family of "fetch URL" derivations.
These derivations download files from given URL.
To ensure that the downloaded file has not been modified, each derivation must also specify a cryptographic hash of the file.
For example,
```jsonc
{
"outputs: {
"out": {
"method": "nar",
"hashAlgo": "sha256",
"hash: "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465",
},
},
"env": {
"url": "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz"
// ...
},
// ...
}
```
It sometimes happens that the URL of the file changes,
e.g., because servers are reorganised or no longer available.
In these cases, we then must update the call to `fetchurl`, e.g.,
```diff
"env": {
- "url": "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz"
+ "url": "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz"
// ...
},
```
If a `fetchurl` derivation's outputs were [input-addressed][input addressing], the output paths of the derivation and of *all derivations depending on it* would change.
For instance, if we were to change the URL of the Glibc source distribution in Nixpkgs (a package on which almost all other packages depend on Linux) massive rebuilds would be needed.
This is unfortunate for a change which we know cannot have a real effect as it propagates upwards through the dependency graph.
For content-addressed outputs (fixed or floating), on the other hand, the outputs' store path only depends on the derivation's name, data, and the `method` of the outputs' specs.
The rest of the derivation is ignored for the purpose of computing the output path.
> **History Note**
>
> Fixed content-addressing is especially important both today and historically as the *only* form of content-addressing that is stabilized.
> This is why the rationale above contrasts it with [input addressing].
## (Floating) Content-Addressing {#floating}
> **Warning**
> This is part of an [experimental feature](@docroot@/development/experimental-features.md).
>
> To use this type of output addressing, you must enable the
> [`ca-derivations`][xp-feature-ca-derivations] experimental feature.
> For example, in [nix.conf](@docroot@/command-ref/conf-file.md) you could add:
>
> ```
> extra-experimental-features = ca-derivations
> ```
With this experimemental feature enabled, derivation outputs can also be content-addressed *without* fixing in the output spec what the outputs' content address must be.
### Purity
Because the derivation output is not fixed (just like with [input addressing]), the [builder] is not given any impure capabilities [^purity].
> **Configuration note**
>
> Strictly speaking, the extent to which sandboxing and deprivilaging is possible varies with the environment Nix is running in.
> Nix's configuration settings indicate what level of sandboxing is required or enabled.
> Builds of derivations will fail if they request an absense of sandboxing which is not allowed.
> Builds of derivations will also fail if the level of sandboxing specified in the configure exceeds what is possible in teh given environment.
>
> (The "environment", in this case, consists of attributes such as the Operating System Nix runs atop, along with the operating-system-specific privilages that Nix has been granted.
> Because of how conventional operating systems like macos, Linux, etc. work, granting builders *fewer* privilages may ironically require that Nix be run with *more* privilages.)
That said, derivations producing floating content-addressed outputs may declare their builders as impure (like the builders of derivations producing producing fixed outputs).
This is provisionally supported as part of the [`impure-derivations`][xp-feature-impure-derivations] experimental feature.
### Compatibility negotiation
Any derivation producing a floating content-addresssed output implicitly requires the `ca-derivations` [system feature](@docroot@/command-ref/conf-file.md#conf-system-features).
This prevents scheduling the building of the derivation on a machine without the experimental feature enabled.
Even once the experimental feature is stabilized, this is still useful in order to be allow using remote builder running odler versions of Nix, or alternative implementations that do not support floating content addressing.
### Determinism
In the earlier [discussion of how self-references are handled when content-addressing store objects](@docroot@/store/store-object/content-address.html#self-references), it was pointed out that methods of producing store objects ought to be deterministic regardless of the choice of provisional store path.
For store objects produced by manually inserting into the store to create a store object, the "method of production" is an informally concept --- formally, Nix has no idea where the store object came from, and content-addressing is crucial in order to ensure that the derivation is *intrinsically* tamper-proof.
But for store objects produced by derivation, the "method is quite formal" --- the whole point of derivations is to be a formal notion of building, after all.
In this case, we can elevate this informal property to a formal one.
A *determinstic* content-addressing derivation should produce outputs with the same content addresses:
1. Every time the builder is run
This is because either the builder is completely sandboxed, or because all any remaining impurities that leak inside the build sandbox are ignored by the builder and do not influence its behavior.
2. Regardless of the choice of any provisional outputs paths
Provisional store paths must be chosen for any output that has a self-reference.
The choice of provisional store path can be thought of as an impurity, since it is an arbitrary choice.
If provisional outputs paths are deterministically chosen, we are in the first branch of part (1).
The builder the data it produces based on it in arbitrary ways, but this gets us closer to to [input addressing].
Deterministically choosing the provisional path may be considered "complete sandboxing" by removing an impurity, but this is unsatisfactory
<!--
TODO
(Both these points will be expanded-upon below.)
-->
If provisional outputs paths are randomly chosen, we are in the second branch of part (1).
The builder *must* not let the random input affect the final outputs it produces, and multiple builds may be performed and the compared in order to ensure that this is in fact the case.
### Floating versus Fixed
While the distinction between content- and input-addressing is one of *mechanism*, the distinction between fixed and floating content addressing is more one of *policy*.
A fixed output that passes its content address check is just like a floating output.
It is only in the potential for that check to fail that they are different.
> **Design Note**
>
> In a future world where floating content-addressing is also stable, we in principle no longer need separate [fixed](#fixed) content-addressing.
> Instead, we could always use floating content-addressing, and separately assert the precise value content address of a given store object to be used as an input (of another derivation).
> A stand-alone assertion object of this sort is not yet implemented, but its possible creation is tracked in [Issue #11955](https://github.com/NixOS/nix/issues/11955).
>
> In the current version of Nix, fixed outputs which fail their hash check are still registered as valid store objects, just not registered as outputs of the derivation which produced them.
> This is an optimization that means if the wrong output hash is specified in a derivation, and then the derivation is recreated with the right output hash, derivation does not need to be rebuilt --- avoiding downloading potentially large amounts of data twice.
> This optimisation prefigures the design above:
> If the output hash assertion was removed outside the derivation itself, Nix could additionally not only register that outputted store object like today, but could also make note that derivation did in fact successfully download some data.
For example, for the "fetch URL" example above, making such a note is tantamount to recording what data is available at the time of download at the given URL.
> It would only be when Nix subsequently tries to build something with that (refining our example) downloaded source code that Nix would be forced to check the output hash assertion, preventing it from e.g. building compromised malware.
>
> Recapping, Nix would
>
> 1. successfully download data
> 2. insert that data into the store
> 3. associate (presumably with some sort of expiration policy) the downloaded data with the derivation that downloaded it
>
> But only use the downloaded store object in subsequent derivations that depended upon the assertion if the assertion passed.
>
> This possible future extension is included to illustrate this distinction:
[input addressing]: ./input-address.md
[xp-feature-ca-derivations]: @docroot@/development/experimental-features.md#xp-feature-ca-derivations
[xp-feature-git-hashing]: @docroot@/development/experimental-features.md#xp-feature-git-hashing
[xp-feature-impure-derivations]: @docroot@/development/experimental-features.md#xp-feature-impure-derivations

View File

@@ -0,0 +1,97 @@
# Derivation Outputs and Types of Derivations
As stated on the [main pages on derivations](../index.md#store-derivation),
a derivation produces [store objects], which are known as the *outputs* of the derivation.
Indeed, the entire point of derivations is to produce these outputs, and to reliably and reproducably produce these derivations each time the derivation is run.
One of the parts of a derivation is its *outputs specification*, which specifies certain information about the outputs the derivation produces when run.
The outputs specification is a map, from names to specifications for individual outputs.
## Output Names {#outputs}
Output names can be any string which is also a valid [store path] name.
The name mapped to each output specification is not actually the name of the output.
In the general case, the output store object has name `derivationName + "-" + outputSpecName`, not any other metadata about it.
However, an output spec named "out" describes and output store object whose name is just the derivation name.
> **Example**
>
> A derivation is named `hello`, and has two outputs, `out`, and `dev`
>
> - The derivation's path will be: `/nix/store/<hash>-hello.drv`.
>
> - The store path of `out` will be: `/nix/store/<hash>-hello`.
>
> - The store path of `dev` will be: `/nix/store/<hash>-hello-dev`.
The outputs are the derivations are the [store objects][store object] it is obligated to produce.
> **Note**
>
> The formal terminology here is somewhat at adds with everyday communication in the Nix community today.
> "output" in casual usage tends to refer to either to the actual output store object, or the notional output spec, depending on context.
>
> For example "hello's `dev` output" means the store object referred to by the store path `/nix/store/<hash>-hello-dev`.
> It is unusual to call this the "`hello-dev` output", even though `hello-dev` is the actual name of that store object.
## Types of output addressing
The main information contained in an output specification is how the derivation output is addressed.
In particular, the specification decides:
- whether the output is [content-addressed](./content-address.md) or [input-addressed](./input-address.md)
- if the content is content-addressed, how is it content addressed
- if the content is content-addressed, [what is its content address](./content-address.md#fixed-content-addressing) (and thus what is its [store path])
## Types of derivations
The sections on each type of derivation output addressing ended up discussing other attributes of the derivation besides its outputs, such as purity, scheduling, determinism, etc.
This is no concidence; for the type of a derivation is in fact one-for-one with the type of its outputs:
- A derivation that produces *xyz-addressed* outputs is an *xyz-addressing* derivations.
The rules for this are fairly concise:
- All the outputs must be of the same type / use the same addressing
- The derivation must have at least one output
- Additionally, if the outputs are fixed content-addressed, there must be exactly one output, whose specification is mapped from the name `out`.
(The name `out` is special, according to the rules described above.
Having only one output and calling its specification `out` means the single output is effectively anonymous; the store path just has the derivation name.)
(This is an arbitrary restriction that could be lifted.)
- The output is either *fixed* or *floating*, indicating whether the its store path is known prior to building it.
- With fixed content-addressing it is fixed.
> A *fixed content-addressing* derivation is also called a *fixed-output derivation*, since that is the only currently-implemented form of fixed-output addressing
- With floating content-addressing or input-addressing it is floating.
> Thus, historically with Nix, with no experimental features enabled, *all* outputs are fixed.
- The derivation may be *pure* or *impure*, indicating what read access to the outside world the [builder](../index.md#builder) has.
- An input-addressing derivation *must* be pure.
> If it is impure, we would have a large problem, because an input-addressed derivation always produces outputs with the same paths.
- A content-addressing derivation may be pure or impure
- If it is impure, it may be be fixed (typical), or it may be floating if the additional [`impure-derivations`][xp-feature-impure-derivations] experimental feature is enabled.
- If it is pure, it must be floating.
- Pure, fixed content-addressing derivations are not suppported
> There is no use for this forth combination.
> The sole purpose of an output's store path being fixed is to support the derivation being impure.
[xp-feature-ca-derivations]: @docroot@/development/experimental-features.md#xp-feature-ca-derivations
[xp-feature-git-hashing]: @docroot@/development/experimental-features.md#xp-feature-git-hashing
[xp-feature-impure-derivations]: @docroot@/development/experimental-features.md#xp-feature-impure-derivations

View File

@@ -0,0 +1,31 @@
# Input-addressing derivation outputs
[input addressing]: #input-addressing
"Input addressing" means the address the store object by the *way it was made* rather than *what it is*.
That is to say, an input-addressed output's store path is a function not of the output itself, but of the derivation that produced it.
Even if two store paths have the same contents, if they are produced in different ways, and one is input-addressed, then they will have different store paths, and thus guaranteed to not be the same store object.
<!---
### Modulo fixed-output derivations
**TODO hash derivation modulo.**
So how do we compute the hash part of the output path of a derivation?
This is done by the function `hashDrv`, shown in Figure 5.10.
It distinguishes between two cases.
If the derivation is a fixed-output derivation, then it computes a hash over just the `outputHash` attributes.
If the derivation is not a fixed-output derivation, we replace each element in the derivations inputDrvs with the result of a call to `hashDrv` for that element.
(The derivation at each store path in `inputDrvs` is converted from its on-disk ATerm representation back to a `StoreDrv` by the function `parseDrv`.) In essence, `hashDrv` partitions store derivations into equivalence classes, and for hashing purpose it replaces each store path in a derivation graph with its equivalence class.
The recursion in Figure 5.10 is inefficient:
it will call itself once for each path by which a subderivation can be reached, i.e., `O(V k)` times for a derivation graph with `V` derivations and with out-degree of at most `k`.
In the actual implementation, memoisation is used to reduce this to `O(V + E)` complexity for a graph with E edges.
-->
[xp-feature-ca-derivations]: @docroot@/development/experimental-features.md#xp-feature-ca-derivations
[xp-feature-git-hashing]: @docroot@/development/experimental-features.md#xp-feature-git-hashing
[xp-feature-impure-derivations]: @docroot@/development/experimental-features.md#xp-feature-impure-derivations

View File

@@ -24,13 +24,17 @@ For the full specification of the algorithms involved, see the [specification of
### File System Objects
With all currently supported store object content addressing methods, the file system object is always [content-addressed][fso-ca] first, and then that hash is incorporated into content address computation for the store object.
With all currently-supported store object content-addressing methods, the file system object is always [content-addressed][fso-ca] first, and then that hash is incorporated into content address computation for the store object.
### References
#### References to other store objects
With all currently supported store object content addressing methods,
other objects are referred to by their regular (string-encoded-) [store paths][Store Path].
#### Self-references
Self-references however cannot be referred to by their path, because we are in the midst of describing how to compute that path!
> The alternative would require finding as hash function fixed point, i.e. the solution to an equation in the form
@@ -40,7 +44,28 @@ Self-references however cannot be referred to by their path, because we are in t
> which is computationally infeasible.
> As far as we know, this is equivalent to finding a hash collision.
Instead we just have a "has self reference" boolean, which will end up affecting the digest.
Instead we have a "has self-reference" boolean, which ends up affecting the digest:
In all currently-supported store object content-addressing methods, when hashing the file system object data, any occurence of store object's own store path in the digested data is replaced with a [sentinel value](https://en.wikipedia.org/wiki/Sentinel_value).
The hashes of these modified input streams are used instead.
When validating the content address of a store object after the fact, the above process works as written.
However, when first creating the store object we don't know the store object's store path, as explained just above.
We therefore, strictly speaking, do not know what value we will be replacing with the sentinental value in the inputs to hash functions.
What instead happens is that the provisional store object --- the data from which we wish to create a store object --- is paired with a provisional "scratch" store path (that presumably was chosen when the data was created).
That provisional store path is instead what is replaced with the sentinel value, rather than the final store object which we do not yet know.
> **Design note**
>
> It is an informal property of content-addressed store objects that the choice of provisional store path should not matter.
> In other words, if a provisional store object is prepared in the same way except for the choice of provision store path, the provisional data need not be identical.
> But, after the sentinel value is substituted in place of each provisional store object's provision store path, the final so-normalized data *should* be identical.
>
> If, conversely, the data after this normalization process is still different, we'll compute a different content-address.
> The method of preparing the provisional self-referenced data has *failed* to be deterministic in the sense of not *leaking* the choice of provisional store path --- a choice which is supposed to be arbitrary --- into the final store object.
>
> This property is informal because at this stage, we are just described store objects, which have no formal notion of their origin.
> Without such a formal notion, there is nothing to formally accuse of being insufficiently deterministic.
> Where we cover [derivations](@docroot@/store/derivation/index.md), we will have a chance to make this a formal property, not of content-addressed store objects themselves, but of derivations that *produce* content-addressed store objects.
### Name and Store Directory
@@ -63,7 +88,7 @@ References are not supported: store objects with flat hashing *and* references c
This also uses the corresponding [Flat](../file-system-object/content-address.md#serial-flat) method of file system object content addressing.
References to other store objects are supported, but self references are not.
References to other store objects are supported, but self-references are not.
This is the only store-object content-addressing method that is not named identically with a corresponding file system object method.
It is somewhat obscure, mainly used for "drv files"
@@ -74,7 +99,7 @@ Prefer another method if possible.
This uses the corresponding [Nix Archive](../file-system-object/content-address.md#serial-nix-archive) method of file system object content addressing.
References (to other store objects and self references alike) are supported so long as the hash algorithm is SHA-256, but not (neither kind) otherwise.
References (to other store objects and self-references alike) are supported so long as the hash algorithm is SHA-256, but not (neither kind) otherwise.
### Git { #method-git }

8
flake.lock generated
View File

@@ -63,16 +63,16 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1734359947,
"narHash": "sha256-1Noao/H+N8nFB4Beoy8fgwrcOQLVm9o4zKW1ODaqK9E=",
"lastModified": 1743315132,
"narHash": "sha256-6hl6L/tRnwubHcA4pfUUtk542wn2Om+D4UnDhlDW9BE=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "48d12d5e70ee91fe8481378e540433a7303dbf6a",
"rev": "52faf482a3889b7619003c0daec593a1912fddc1",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "release-24.11",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}

View File

@@ -1,7 +1,7 @@
{
description = "The purely functional package manager";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/release-24.11";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
inputs.nixpkgs-regression.url = "github:NixOS/nixpkgs/215d4d0fd80ca5163643b03a33fde804a29cc1e2";
inputs.nixpkgs-23-11.url = "github:NixOS/nixpkgs/a62e6edd6d5e1fa0329b8653c801147986f8d446";
@@ -32,7 +32,7 @@
let
inherit (nixpkgs) lib;
officialRelease = false;
officialRelease = true;
linux32BitSystems = [ "i686-linux" ];
linux64BitSystems = [
@@ -156,6 +156,13 @@
inherit officialRelease;
pkgs = final;
src = self;
maintainers = with lib.maintainers; [
edolstra
Ericson2314
Mic92
roberth
tomberek
];
};
};
@@ -230,24 +237,28 @@
This shouldn't build anything significant; just check that things
(including derivations) are _set up_ correctly.
*/
packaging-overriding =
let
pkgs = nixpkgsFor.${system}.native;
nix = self.packages.${system}.nix;
in
assert (nix.appendPatches [ pkgs.emptyFile ]).libs.nix-util.src.patches == [ pkgs.emptyFile ];
if pkgs.stdenv.buildPlatform.isDarwin then
lib.warn "packaging-overriding check currently disabled because of a permissions issue on macOS" pkgs.emptyFile
else
# If this fails, something might be wrong with how we've wired the scope,
# or something could be broken in Nixpkgs.
pkgs.testers.testEqualContents {
assertion = "trivial patch does not change source contents";
expected = "${./.}";
actual =
# Same for all components; nix-util is an arbitrary pick
(nix.appendPatches [ pkgs.emptyFile ]).libs.nix-util.src;
};
# Disabled due to a bug in `testEqualContents` (see
# https://github.com/NixOS/nix/issues/12690).
/*
packaging-overriding =
let
pkgs = nixpkgsFor.${system}.native;
nix = self.packages.${system}.nix;
in
assert (nix.appendPatches [ pkgs.emptyFile ]).libs.nix-util.src.patches == [ pkgs.emptyFile ];
if pkgs.stdenv.buildPlatform.isDarwin then
lib.warn "packaging-overriding check currently disabled because of a permissions issue on macOS" pkgs.emptyFile
else
# If this fails, something might be wrong with how we've wired the scope,
# or something could be broken in Nixpkgs.
pkgs.testers.testEqualContents {
assertion = "trivial patch does not change source contents";
expected = "${./.}";
actual =
# Same for all components; nix-util is an arbitrary pick
(nix.appendPatches [ pkgs.emptyFile ]).libs.nix-util.src;
};
*/
}
// (lib.optionalAttrs (builtins.elem system linux64BitSystems)) {
dockerImage = self.hydraJobs.dockerImage.${system};

View File

@@ -127,7 +127,6 @@
''^src/libexpr/nixexpr\.cc$''
''^src/libexpr/nixexpr\.hh$''
''^src/libexpr/parser-state\.hh$''
''^src/libexpr/pos-table\.hh$''
''^src/libexpr/primops\.cc$''
''^src/libexpr/primops\.hh$''
''^src/libexpr/primops/context\.cc$''
@@ -397,7 +396,6 @@
''^src/libutil/types\.hh$''
''^src/libutil/unix/file-descriptor\.cc$''
''^src/libutil/unix/file-path\.cc$''
''^src/libutil/unix/monitor-fd\.hh$''
''^src/libutil/unix/processes\.cc$''
''^src/libutil/unix/signals-impl\.hh$''
''^src/libutil/unix/signals\.cc$''

View File

@@ -2,6 +2,8 @@
# vim: set filetype=bash:
#!nix shell .#changelog-d --command bash
set -euo pipefail
# --- CONFIGURATION ---
# This does double duty for

View File

@@ -3,6 +3,7 @@
pkgs,
src,
officialRelease,
maintainers,
}:
scope:
@@ -51,7 +52,7 @@ let
setVersionLayer = finalAttrs: prevAttrs: {
preConfigure =
prevAttrs.prevAttrs or ""
prevAttrs.preConfigure or ""
+
# Update the repo-global .version file.
# Symlink ./.version points there, but by default only workDir is writable.
@@ -110,7 +111,7 @@ let
let
n = lib.length finalScope.patches;
in
if n == 0 then finalAttrs.version else finalAttrs.version + "+${toString n}";
if n == 0 then prevAttrs.version else prevAttrs.version + "+${toString n}";
# Clear what `derivation` can't/shouldn't serialize; see prevAttrs.workDir.
fileset = null;
@@ -180,9 +181,24 @@ let
mesonFlags = [ (lib.mesonBool "b_asneeded" false) ] ++ prevAttrs.mesonFlags or [ ];
};
miscGoodPractice = finalAttrs: prevAttrs: {
nixDefaultsLayer = finalAttrs: prevAttrs: {
strictDeps = prevAttrs.strictDeps or true;
enableParallelBuilding = true;
pos = builtins.unsafeGetAttrPos "pname" prevAttrs;
meta = prevAttrs.meta or { } // {
homepage = prevAttrs.meta.homepage or "https://nixos.org/nix";
longDescription =
prevAttrs.longDescription or ''
Nix is a powerful package manager for mainly Linux and other Unix systems that
makes package management reliable and reproducible. It provides atomic
upgrades and rollbacks, side-by-side installation of multiple versions of
a package, multi-user package management and easy setup of build
environments.
'';
license = prevAttrs.meta.license or lib.licenses.lgpl21Plus;
maintainers = prevAttrs.meta.maintainers or [ ] ++ scope.maintainers;
platforms = prevAttrs.meta.platforms or (lib.platforms.unix ++ lib.platforms.windows);
};
};
/**
@@ -202,6 +218,7 @@ in
{
version = baseVersion + versionSuffix;
inherit versionSuffix;
inherit maintainers;
inherit filesetToSource;
@@ -237,6 +254,10 @@ in
but it does make the build non-granular; all components will use a complete source.
Packaging expressions will be ignored.
Single argument: the source to use.
See also `appendPatches`
*/
overrideSource =
src:
@@ -265,6 +286,7 @@ in
}
);
resolvePath = p: finalScope.patchedSrc + "/${resolveRelPath p}";
filesetToSource = { root, fileset }: finalScope.resolvePath root;
appendPatches = appendPatches finalScope;
}
);
@@ -281,14 +303,14 @@ in
(scope.overrideSource "${./..}").appendPatches patches;
mkMesonDerivation = mkPackageBuilder [
miscGoodPractice
nixDefaultsLayer
scope.sourceLayer
setVersionLayer
mesonLayer
scope.mesonComponentOverrides
];
mkMesonExecutable = mkPackageBuilder [
miscGoodPractice
nixDefaultsLayer
bsdNoLinkAsNeeded
scope.sourceLayer
setVersionLayer
@@ -297,7 +319,7 @@ in
scope.mesonComponentOverrides
];
mkMesonLibrary = mkPackageBuilder [
miscGoodPractice
nixDefaultsLayer
bsdNoLinkAsNeeded
scope.sourceLayer
mesonLayer
@@ -347,7 +369,7 @@ in
nix-perl-bindings = callPackage ../src/perl/package.nix { };
nix-everything = callPackage ../packaging/everything.nix { } // {
# Note: no `passthru.overrideAllMesonComponents`
# Note: no `passthru.overrideAllMesonComponents` etc
# This would propagate into `nix.overrideAttrs f`, but then discard
# `f` when `.overrideAllMesonComponents` is used.
# Both "methods" should be views on the same fixpoint overriding mechanism
@@ -355,6 +377,8 @@ in
# two-fixpoint solution.
/**
Apply an extension function (i.e. overlay-shaped) to all component derivations, and return the nix package.
Single argument: the extension function to apply (finalAttrs: prevAttrs: { ... })
*/
overrideAllMesonComponents = f: (scope.overrideAllMesonComponents f).nix-everything;
@@ -363,6 +387,10 @@ in
This affects all components.
Changes to the packaging expressions will be ignored.
Single argument: list of patches to apply
See also `overrideSource`
*/
appendPatches = ps: (scope.appendPatches ps).nix-everything;
@@ -371,8 +399,26 @@ in
but it does make the build non-granular; all components will use a complete source.
Packaging expressions will be ignored.
Filesets in the packaging expressions will be ignored.
Single argument: the source to use.
See also `appendPatches`
*/
overrideSource = src: (scope.overrideSource src).nix-everything;
/**
Override any internals of the Nix package set.
Single argument: the extension function to apply to the package set (finalScope: prevScope: { ... })
Example:
```
overrideScope (finalScope: prevScope: { aws-sdk-cpp = null; })
```
*/
overrideScope = f: (scope.overrideScope f).nix-everything;
};
}

View File

@@ -26,6 +26,9 @@ let
# Despite the use of the 10.13 deployment target here, the aligned
# allocation function Clang uses with this setting actually works
# all the way back to 10.6.
# NOTE: this is not just a version constraint, but a request to make Darwin
# provide this version level of support. Removing this minimum version
# request will regress the above error.
darwinStdenv = pkgs.overrideSDK prevStdenv { darwinMinVersion = "10.13"; };
in
@@ -65,39 +68,37 @@ scope: {
installPhase = lib.replaceStrings [ "--without-python" ] [ "" ] old.installPhase;
});
libgit2 = pkgs.libgit2.overrideAttrs (
attrs:
{
cmakeFlags = attrs.cmakeFlags or [ ] ++ [ "-DUSE_SSH=exec" ];
}
# libgit2: Nixpkgs 24.11 has < 1.9.0, which needs our patches
// lib.optionalAttrs (!lib.versionAtLeast pkgs.libgit2.version "1.9.0") {
nativeBuildInputs =
attrs.nativeBuildInputs or [ ]
# gitMinimal does not build on Windows. See packbuilder patch.
++ lib.optionals (!stdenv.hostPlatform.isWindows) [
# Needed for `git apply`; see `prePatch`
pkgs.buildPackages.gitMinimal
];
# Only `git apply` can handle git binary patches
prePatch =
attrs.prePatch or ""
+ lib.optionalString (!stdenv.hostPlatform.isWindows) ''
patch() {
git apply
}
'';
patches =
attrs.patches or [ ]
++ [
./patches/libgit2-mempack-thin-packfile.patch
]
# gitMinimal does not build on Windows, but fortunately this patch only
# impacts interruptibility
++ lib.optionals (!stdenv.hostPlatform.isWindows) [
# binary patch; see `prePatch`
./patches/libgit2-packbuilder-callback-interruptible.patch
];
}
);
libgit2 =
if lib.versionAtLeast pkgs.libgit2.version "1.9.0" then
pkgs.libgit2
else
pkgs.libgit2.overrideAttrs (attrs: {
# libgit2: Nixpkgs 24.11 has < 1.9.0, which needs our patches
nativeBuildInputs =
attrs.nativeBuildInputs or [ ]
# gitMinimal does not build on Windows. See packbuilder patch.
++ lib.optionals (!stdenv.hostPlatform.isWindows) [
# Needed for `git apply`; see `prePatch`
pkgs.buildPackages.gitMinimal
];
# Only `git apply` can handle git binary patches
prePatch =
attrs.prePatch or ""
+ lib.optionalString (!stdenv.hostPlatform.isWindows) ''
patch() {
git apply
}
'';
patches =
attrs.patches or [ ]
++ [
./patches/libgit2-mempack-thin-packfile.patch
]
# gitMinimal does not build on Windows, but fortunately this patch only
# impacts interruptibility
++ lib.optionals (!stdenv.hostPlatform.isWindows) [
# binary patch; see `prePatch`
./patches/libgit2-packbuilder-callback-interruptible.patch
];
});
}

View File

@@ -72,10 +72,6 @@ pkgs.nixComponents.nix-util.overrideAttrs (
src = null;
env = {
# Needed for Meson to find Boost.
# https://github.com/NixOS/nixpkgs/issues/86131.
BOOST_INCLUDEDIR = "${lib.getDev pkgs.nixDependencies.boost}/include";
BOOST_LIBRARYDIR = "${lib.getLib pkgs.nixDependencies.boost}/lib";
# For `make format`, to work without installing pre-commit
_NIX_PRE_COMMIT_HOOKS_CONFIG = "${(pkgs.formats.yaml { }).generate "pre-commit-config.yaml"
modular.pre-commit.settings.rawConfig
@@ -118,9 +114,6 @@ pkgs.nixComponents.nix-util.overrideAttrs (
(pkgs.writeScriptBin "pre-commit-hooks-install" modular.pre-commit.settings.installationScript)
pkgs.buildPackages.nixfmt-rfc-style
]
# TODO: Remove the darwin check once
# https://github.com/NixOS/nixpkgs/pull/291814 is available
++ lib.optional (stdenv.cc.isClang && !stdenv.buildPlatform.isDarwin) pkgs.buildPackages.bear
++ lib.optional (stdenv.cc.isClang && stdenv.hostPlatform == stdenv.buildPlatform) (
lib.hiPrio pkgs.buildPackages.clang-tools
);

View File

@@ -1,8 +1,11 @@
{
lib,
stdenv,
lndir,
buildEnv,
maintainers,
nix-util,
nix-util-c,
nix-util-tests,
@@ -38,7 +41,8 @@
nix-perl-bindings,
testers,
runCommand,
patchedSrc ? null,
}:
let
@@ -68,48 +72,6 @@ let
;
};
dev = stdenv.mkDerivation (finalAttrs: {
name = "nix-${nix-cli.version}-dev";
pname = "nix";
version = nix-cli.version;
dontUnpack = true;
dontBuild = true;
libs = map lib.getDev (lib.attrValues libs);
installPhase = ''
mkdir -p $out/nix-support
echo $libs >> $out/nix-support/propagated-build-inputs
'';
passthru = {
tests = {
pkg-config = testers.hasPkgConfigModules {
package = finalAttrs.finalPackage;
};
};
# If we were to fully emulate output selection here, we'd confuse the Nix CLIs,
# because they rely on `drvPath`.
dev = finalAttrs.finalPackage.out;
libs = throw "`nix.dev.libs` is not meant to be used; use `nix.libs` instead.";
};
meta = {
mainProgram = "nix";
pkgConfigModules = [
"nix-cmd"
"nix-expr"
"nix-expr-c"
"nix-fetchers"
"nix-flake"
"nix-flake-c"
"nix-main"
"nix-main-c"
"nix-store"
"nix-store-c"
"nix-util"
"nix-util-c"
];
};
});
devdoc = buildEnv {
name = "nix-${nix-cli.version}-devdoc";
paths = [
@@ -119,92 +81,164 @@ let
};
in
(buildEnv {
name = "nix-${nix-cli.version}";
paths = [
nix-cli
nix-manual.man
stdenv.mkDerivation (finalAttrs: {
pname = "nix";
version = nix-cli.version;
/**
This package uses a multi-output derivation, even though some outputs could
have been provided directly by the constituent component that provides it.
This is because not all tooling handles packages composed of arbitrary
outputs yet. This includes nix itself, https://github.com/NixOS/nix/issues/6507.
`devdoc` is also available, but not listed here, because this attribute is
not an output of the same derivation that provides `out`, `dev`, etc.
*/
outputs = [
"out"
"dev"
"doc"
"man"
];
meta.mainProgram = "nix";
}).overrideAttrs
(
finalAttrs: prevAttrs: {
doCheck = true;
doInstallCheck = true;
/**
Unpacking is handled in this package's constituent components
*/
dontUnpack = true;
/**
Building is handled in this package's constituent components
*/
dontBuild = true;
checkInputs =
[
# Make sure the unit tests have passed
nix-util-tests.tests.run
nix-store-tests.tests.run
nix-expr-tests.tests.run
nix-fetchers-tests.tests.run
nix-flake-tests.tests.run
/**
`doCheck` controles whether tests are added as build gate for the combined package.
This includes both the unit tests and the functional tests, but not the
integration tests that run in CI (the flake's `hydraJobs` and some of the `checks`).
*/
doCheck = true;
# Make sure the functional tests have passed
nix-functional-tests
/**
`fixupPhase` currently doesn't understand that a symlink output isn't writable.
# dev bundle is ok
# (checkInputs must be empty paths??)
(runCommand "check-pkg-config" { checked = dev.tests.pkg-config; } "mkdir $out")
]
++ lib.optionals
(!stdenv.hostPlatform.isStatic && stdenv.buildPlatform.canExecute stdenv.hostPlatform)
[
# Perl currently fails in static build
# TODO: Split out tests into a separate derivation?
nix-perl-bindings
];
passthru = prevAttrs.passthru // {
inherit (nix-cli) version;
We don't compile or link anything in this derivation, so fixups aren't needed.
*/
dontFixup = true;
/**
These are the libraries that are part of the Nix project. They are used
by the Nix CLI and other tools.
checkInputs =
[
# Make sure the unit tests have passed
nix-util-tests.tests.run
nix-store-tests.tests.run
nix-expr-tests.tests.run
nix-fetchers-tests.tests.run
nix-flake-tests.tests.run
If you need to use these libraries in your project, we recommend to use
the `-c` C API libraries exclusively, if possible.
# Make sure the functional tests have passed
nix-functional-tests
]
++ lib.optionals
(!stdenv.hostPlatform.isStatic && stdenv.buildPlatform.canExecute stdenv.hostPlatform)
[
# Perl currently fails in static build
# TODO: Split out tests into a separate derivation?
nix-perl-bindings
];
We also recommend that you build the complete package to ensure that the unit tests pass.
You could do this in CI, or by passing it in an unused environment variable. e.g in a `mkDerivation` call:
nativeBuildInputs = [
lndir
];
```nix
buildInputs = [ nix.libs.nix-util-c nix.libs.nix-store-c ];
# Make sure the nix libs we use are ok
unusedInputsForTests = [ nix ];
disallowedReferences = nix.all;
```
*/
inherit libs;
installPhase =
let
devPaths = lib.mapAttrsToList (_k: lib.getDev) finalAttrs.finalPackage.libs;
in
''
mkdir -p $out $dev/nix-support
tests = prevAttrs.passthru.tests or { } // {
# TODO: create a proper fixpoint and:
# pkg-config =
# testers.hasPkgConfigModules {
# package = finalPackage;
# };
};
# Custom files
echo $libs >> $dev/nix-support/propagated-build-inputs
echo ${nix-cli} ${lib.escapeShellArgs devPaths} >> $dev/nix-support/propagated-build-inputs
/**
A derivation referencing the `dev` outputs of the Nix libraries.
*/
inherit dev;
inherit devdoc;
doc = nix-manual;
outputs = [
"out"
"dev"
"devdoc"
"doc"
];
all = lib.attrValues (
lib.genAttrs finalAttrs.passthru.outputs (outName: finalAttrs.finalPackage.${outName})
);
# Merged outputs
lndir ${nix-cli} $out
for lib in ${lib.escapeShellArgs devPaths}; do
lndir $lib $dev
done
# Forwarded outputs
ln -sT ${nix-manual} $doc
ln -sT ${nix-manual.man} $man
'';
passthru = {
inherit (nix-cli) version;
src = patchedSrc;
/**
These are the libraries that are part of the Nix project. They are used
by the Nix CLI and other tools.
If you need to use these libraries in your project, we recommend to use
the `-c` C API libraries exclusively, if possible.
We also recommend that you build the complete package to ensure that the unit tests pass.
You could do this in CI, or by passing it in an unused environment variable. e.g in a `mkDerivation` call:
```nix
buildInputs = [ nix.libs.nix-util-c nix.libs.nix-store-c ];
# Make sure the nix libs we use are ok
unusedInputsForTests = [ nix ];
disallowedReferences = nix.all;
```
*/
inherit libs;
/**
Developer documentation for `nix`, in `share/doc/nix/{internal,external}-api/`.
This is not a proper output; see `outputs` for context.
*/
inherit devdoc;
/**
Extra tests that test this package, but do not run as part of the build.
See <https://nixos.org/manual/nixpkgs/stable/index.html#var-passthru-tests>
*/
tests = {
pkg-config = testers.hasPkgConfigModules {
package = finalAttrs.finalPackage;
};
meta = prevAttrs.meta // {
description = "The Nix package manager";
pkgConfigModules = dev.meta.pkgConfigModules;
};
}
)
};
};
meta = {
mainProgram = "nix";
description = "The Nix package manager";
longDescription = nix-cli.meta.longDescription;
homepage = nix-cli.meta.homepage;
license = nix-cli.meta.license;
maintainers = maintainers;
platforms = nix-cli.meta.platforms;
outputsToInstall = [
"out"
"man"
];
pkgConfigModules = [
"nix-cmd"
"nix-expr"
"nix-expr-c"
"nix-fetchers"
"nix-flake"
"nix-flake-c"
"nix-main"
"nix-main-c"
"nix-store"
"nix-store-c"
"nix-util"
"nix-util-c"
];
};
})

View File

@@ -1,7 +1,7 @@
# Only execute this file once per shell.
# This file is tested by tests/installer/default.nix.
if [ -n "${__ETC_PROFILE_NIX_SOURCED:-}" ]; then return; fi
__ETC_PROFILE_NIX_SOURCED=1
export __ETC_PROFILE_NIX_SOURCED=1
NIX_LINK=$HOME/.nix-profile
if [ -n "${XDG_STATE_HOME-}" ]; then

View File

@@ -237,12 +237,13 @@ void StorePathCommand::run(ref<Store> store, StorePaths && storePaths)
MixProfile::MixProfile()
{
addFlag(
{.longName = "profile",
.description = "The profile to operate on.",
.labels = {"path"},
.handler = {&profile},
.completer = completePath});
addFlag({
.longName = "profile",
.description = "The profile to operate on.",
.labels = {"path"},
.handler = {&profile},
.completer = completePath,
});
}
void MixProfile::updateProfile(const StorePath & storePath)

View File

@@ -63,7 +63,7 @@ MixEvalArgs::MixEvalArgs()
.description = "Pass the value *expr* as the argument *name* to Nix functions.",
.category = category,
.labels = {"name", "expr"},
.handler = {[&](std::string name, std::string expr) { autoArgs.insert_or_assign(name, AutoArg{AutoArgExpr{expr}}); }}
.handler = {[&](std::string name, std::string expr) { autoArgs.insert_or_assign(name, AutoArg{AutoArgExpr{expr}}); }},
});
addFlag({
@@ -80,7 +80,7 @@ MixEvalArgs::MixEvalArgs()
.category = category,
.labels = {"name", "path"},
.handler = {[&](std::string name, std::string path) { autoArgs.insert_or_assign(name, AutoArg{AutoArgFile{path}}); }},
.completer = completePath
.completer = completePath,
});
addFlag({
@@ -105,7 +105,7 @@ MixEvalArgs::MixEvalArgs()
.labels = {"path"},
.handler = {[&](std::string s) {
lookupPath.elements.emplace_back(LookupPath::Elem::parse(s));
}}
}},
});
addFlag({
@@ -131,7 +131,7 @@ MixEvalArgs::MixEvalArgs()
}},
.completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) {
completeFlakeRef(completions, openStore(), prefix);
}}
}},
});
addFlag({

View File

@@ -64,21 +64,21 @@ MixFlakeOptions::MixFlakeOptions()
.handler = {[&]() {
lockFlags.recreateLockFile = true;
warn("'--recreate-lock-file' is deprecated and will be removed in a future version; use 'nix flake update' instead.");
}}
}},
});
addFlag({
.longName = "no-update-lock-file",
.description = "Do not allow any updates to the flake's lock file.",
.category = category,
.handler = {&lockFlags.updateLockFile, false}
.handler = {&lockFlags.updateLockFile, false},
});
addFlag({
.longName = "no-write-lock-file",
.description = "Do not write the flake's newly generated lock file.",
.category = category,
.handler = {&lockFlags.writeLockFile, false}
.handler = {&lockFlags.writeLockFile, false},
});
addFlag({
@@ -94,14 +94,14 @@ MixFlakeOptions::MixFlakeOptions()
.handler = {[&]() {
lockFlags.useRegistries = false;
warn("'--no-registries' is deprecated; use '--no-use-registries'");
}}
}},
});
addFlag({
.longName = "commit-lock-file",
.description = "Commit changes to the flake's lock file.",
.category = category,
.handler = {&lockFlags.commitLockFile, true}
.handler = {&lockFlags.commitLockFile, true},
});
addFlag({
@@ -121,7 +121,7 @@ MixFlakeOptions::MixFlakeOptions()
}},
.completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) {
completeFlakeInputAttrPath(completions, getEvalState(), getFlakeRefsForCompletion(), prefix);
}}
}},
});
addFlag({
@@ -141,7 +141,7 @@ MixFlakeOptions::MixFlakeOptions()
} else if (n == 1) {
completeFlakeRef(completions, getEvalState()->store, prefix);
}
}}
}},
});
addFlag({
@@ -152,7 +152,7 @@ MixFlakeOptions::MixFlakeOptions()
.handler = {[&](std::string lockFilePath) {
lockFlags.referenceLockFilePath = {getFSSourceAccessor(), CanonPath(absPath(lockFilePath))};
}},
.completer = completePath
.completer = completePath,
});
addFlag({
@@ -163,7 +163,7 @@ MixFlakeOptions::MixFlakeOptions()
.handler = {[&](std::string lockFilePath) {
lockFlags.outputLockFilePath = lockFilePath;
}},
.completer = completePath
.completer = completePath,
});
addFlag({
@@ -190,7 +190,7 @@ MixFlakeOptions::MixFlakeOptions()
}},
.completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) {
completeFlakeRef(completions, getEvalState()->store, prefix);
}}
}},
});
}
@@ -206,7 +206,7 @@ SourceExprCommand::SourceExprCommand()
.category = installablesCategory,
.labels = {"file"},
.handler = {&file},
.completer = completePath
.completer = completePath,
});
addFlag({
@@ -214,7 +214,7 @@ SourceExprCommand::SourceExprCommand()
.description = "Interpret [*installables*](@docroot@/command-ref/new-cli/nix.md#installables) as attribute paths relative to the Nix expression *expr*.",
.category = installablesCategory,
.labels = {"expr"},
.handler = {&expr}
.handler = {&expr},
});
}
@@ -834,7 +834,7 @@ RawInstallablesCommand::RawInstallablesCommand()
addFlag({
.longName = "stdin",
.description = "Read installables from the standard input. No default installable applied.",
.handler = {&readFromStdIn, true}
.handler = {&readFromStdIn, true},
});
expectArgs({

View File

@@ -113,10 +113,15 @@ headers = [config_h] + files(
'repl.hh',
)
subdir('nix-meson-build-support/export-all-symbols')
subdir('nix-meson-build-support/windows-version')
this_library = library(
'nixcmd',
sources,
dependencies : deps_public + deps_private + deps_other,
include_directories : include_dirs,
link_args: linker_export_flags,
prelink : true, # For C++ static initializers
install : true,
)

View File

@@ -102,8 +102,7 @@ struct NixRepl
unsigned int maxDepth = std::numeric_limits<unsigned int>::max())
{
// Hide the progress bar during printing because it might interfere
logger->pause();
Finally resumeLoggerDefer([]() { logger->resume(); });
auto suspension = logger->suspend();
::nix::printValue(*state, str, v, PrintOptions {
.ansiColors = true,
.force = true,
@@ -141,16 +140,13 @@ static std::ostream & showDebugTrace(std::ostream & out, const PosTable & positi
out << ANSI_RED "error: " << ANSI_NORMAL;
out << dt.hint.str() << "\n";
// prefer direct pos, but if noPos then try the expr.
auto pos = dt.pos
? dt.pos
: positions[dt.expr.getPos() ? dt.expr.getPos() : noPos];
auto pos = dt.getPos(positions);
if (pos) {
out << *pos;
if (auto loc = pos->getCodeLines()) {
out << pos;
if (auto loc = pos.getCodeLines()) {
out << "\n";
printCodeLines(out, "", *pos, *loc);
printCodeLines(out, "", pos, *loc);
out << "\n";
}
}
@@ -180,18 +176,20 @@ ReplExitStatus NixRepl::mainLoop()
while (true) {
// Hide the progress bar while waiting for user input, so that it won't interfere.
logger->pause();
// When continuing input from previous lines, don't print a prompt, just align to the same
// number of chars as the prompt.
if (!interacter->getLine(input, input.empty() ? ReplPromptType::ReplPrompt : ReplPromptType::ContinuationPrompt)) {
// Ctrl-D should exit the debugger.
state->debugStop = false;
logger->cout("");
// TODO: Should Ctrl-D exit just the current debugger session or
// the entire program?
return ReplExitStatus::QuitAll;
{
auto suspension = logger->suspend();
// When continuing input from previous lines, don't print a prompt, just align to the same
// number of chars as the prompt.
if (!interacter->getLine(input, input.empty() ? ReplPromptType::ReplPrompt : ReplPromptType::ContinuationPrompt)) {
// Ctrl-D should exit the debugger.
state->debugStop = false;
logger->cout("");
// TODO: Should Ctrl-D exit just the current debugger session or
// the entire program?
return ReplExitStatus::QuitAll;
}
// `suspension` resumes the logger
}
logger->resume();
try {
switch (processLine(input)) {
case ProcessLineResult::Quit:
@@ -586,6 +584,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
else if (command == ":p" || command == ":print") {
Value v;
evalString(arg, v);
auto suspension = logger->suspend();
if (v.type() == nString) {
std::cout << v.string_view();
} else {
@@ -694,6 +693,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
} else {
Value v;
evalString(line, v);
auto suspension = logger->suspend();
printValue(std::cout, v, 1);
std::cout << std::endl;
}

View File

@@ -45,7 +45,7 @@ EvalErrorBuilder<T> & EvalErrorBuilder<T>::withFrame(const Env & env, const Expr
// TODO: check compatibility with nested debugger calls.
// TODO: What side-effects??
error.state.debugTraces.push_front(DebugTrace{
.pos = error.state.positions[expr.getPos()],
.pos = expr.getPos(),
.expr = expr,
.env = env,
.hint = HintFmt("Fake frame for debugging purposes"),

View File

@@ -146,7 +146,7 @@ inline void EvalState::forceList(Value & v, const PosIdx pos, std::string_view e
[[gnu::always_inline]]
inline CallDepth EvalState::addCallDepth(const PosIdx pos) {
if (callDepth > settings.maxCallDepth)
error<EvalError>("stack overflow; max-call-depth exceeded").atPos(pos).debugThrow();
error<EvalBaseError>("stack overflow; max-call-depth exceeded").atPos(pos).debugThrow();
return CallDepth(callDepth);
};

View File

@@ -272,7 +272,7 @@ EvalState::EvalState(
/* Apply access control if needed. */
if (settings.restrictEval || settings.pureEval)
accessor = AllowListSourceAccessor::create(accessor, {},
accessor = AllowListSourceAccessor::create(accessor, {}, {},
[&settings](const CanonPath & path) -> RestrictedPathError {
auto modeInformation = settings.pureEval
? "in pure evaluation mode (use '--impure' to override)"
@@ -771,18 +771,26 @@ void EvalState::runDebugRepl(const Error * error, const Env & env, const Expr &
if (!debugRepl || inDebugger)
return;
auto dts =
error && expr.getPos()
? std::make_unique<DebugTraceStacker>(
*this,
DebugTrace {
.pos = error->info().pos ? error->info().pos : positions[expr.getPos()],
auto dts = [&]() -> std::unique_ptr<DebugTraceStacker> {
if (error && expr.getPos()) {
auto trace = DebugTrace{
.pos = [&]() -> std::variant<Pos, PosIdx> {
if (error->info().pos) {
if (auto * pos = error->info().pos.get())
return *pos;
return noPos;
}
return expr.getPos();
}(),
.expr = expr,
.env = env,
.hint = error->info().msg,
.isError = true
})
: nullptr;
.isError = true};
return std::make_unique<DebugTraceStacker>(*this, std::move(trace));
}
return nullptr;
}();
if (error)
{
@@ -827,7 +835,7 @@ static std::unique_ptr<DebugTraceStacker> makeDebugTraceStacker(
EvalState & state,
Expr & expr,
Env & env,
std::shared_ptr<Pos> && pos,
std::variant<Pos, PosIdx> pos,
const Args & ... formatArgs)
{
return std::make_unique<DebugTraceStacker>(state,
@@ -1104,7 +1112,7 @@ void EvalState::evalFile(const SourcePath & path, Value & v, bool mustBeTrivial)
*this,
*e,
this->baseEnv,
e->getPos() ? std::make_shared<Pos>(positions[e->getPos()]) : nullptr,
e->getPos(),
"while evaluating the file '%1%':", resolvedPath.to_string())
: nullptr;
@@ -1330,9 +1338,7 @@ void ExprLet::eval(EvalState & state, Env & env, Value & v)
state,
*this,
env2,
getPos()
? std::make_shared<Pos>(state.positions[getPos()])
: nullptr,
getPos(),
"while evaluating a '%1%' expression",
"let"
)
@@ -1401,7 +1407,7 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
state,
*this,
env,
state.positions[getPos()],
getPos(),
"while evaluating the attribute '%1%'",
showAttrPath(state, env, attrPath))
: nullptr;
@@ -1602,7 +1608,7 @@ void EvalState::callFunction(Value & fun, std::span<Value *> args, Value & vRes,
try {
auto dts = debugRepl
? makeDebugTraceStacker(
*this, *lambda.body, env2, positions[lambda.pos],
*this, *lambda.body, env2, lambda.pos,
"while calling %s",
lambda.name
? concatStrings("'", symbols[lambda.name], "'")
@@ -1737,9 +1743,7 @@ void ExprCall::eval(EvalState & state, Env & env, Value & v)
state,
*this,
env,
getPos()
? std::make_shared<Pos>(state.positions[getPos()])
: nullptr,
getPos(),
"while calling a function"
)
: nullptr;
@@ -2123,7 +2127,7 @@ void EvalState::forceValueDeep(Value & v)
try {
// If the value is a thunk, we're evaling. Otherwise no trace necessary.
auto dts = debugRepl && i.value->isThunk()
? makeDebugTraceStacker(*this, *i.value->payload.thunk.expr, *i.value->payload.thunk.env, positions[i.pos],
? makeDebugTraceStacker(*this, *i.value->payload.thunk.expr, *i.value->payload.thunk.env, i.pos,
"while evaluating the attribute '%1%'", symbols[i.name])
: nullptr;

View File

@@ -171,11 +171,28 @@ struct RegexCache;
std::shared_ptr<RegexCache> makeRegexCache();
struct DebugTrace {
std::shared_ptr<Pos> pos;
/* WARNING: Converting PosIdx -> Pos should be done with extra care. This is
due to the fact that operator[] of PosTable is incredibly expensive. */
std::variant<Pos, PosIdx> pos;
const Expr & expr;
const Env & env;
HintFmt hint;
bool isError;
Pos getPos(const PosTable & table) const
{
return std::visit(
overloaded{
[&](PosIdx idx) {
// Prefer direct pos, but if noPos then try the expr.
if (!idx)
idx = expr.getPos();
return table[idx];
},
[&](Pos pos) { return pos; },
},
pos);
}
};
class EvalState : public std::enable_shared_from_this<EvalState>

View File

@@ -172,8 +172,6 @@ headers = [config_h] + files(
# internal: 'lexer-helpers.hh',
'nixexpr.hh',
'parser-state.hh',
'pos-idx.hh',
'pos-table.hh',
'primops.hh',
'print-ambiguous.hh',
'print-options.hh',
@@ -189,6 +187,9 @@ headers = [config_h] + files(
subdir('primops')
subdir('nix-meson-build-support/export-all-symbols')
subdir('nix-meson-build-support/windows-version')
this_library = library(
'nixexpr',
sources,
@@ -196,6 +197,8 @@ this_library = library(
lexer_tab,
generated_headers,
dependencies : deps_public + deps_private + deps_other,
include_directories : include_dirs,
link_args: linker_export_flags,
prelink : true, # For C++ static initializers
install : true,
)

View File

@@ -601,41 +601,6 @@ void ExprLambda::setDocComment(DocComment docComment) {
}
};
/* Position table. */
Pos PosTable::operator[](PosIdx p) const
{
auto origin = resolve(p);
if (!origin)
return {};
const auto offset = origin->offsetOf(p);
Pos result{0, 0, origin->origin};
auto lines = this->lines.lock();
auto linesForInput = (*lines)[origin->offset];
if (linesForInput.empty()) {
auto source = result.getSource().value_or("");
const char * begin = source.data();
for (Pos::LinesIterator it(source), end; it != end; it++)
linesForInput.push_back(it->data() - begin);
if (linesForInput.empty())
linesForInput.push_back(0);
}
// as above: the first line starts at byte 0 and is always present
auto lineStartOffset = std::prev(
std::upper_bound(linesForInput.begin(), linesForInput.end(), offset));
result.line = 1 + (lineStartOffset - linesForInput.begin());
result.column = 1 + (offset - *lineStartOffset);
return result;
}
/* Symbol table. */
size_t SymbolTable::totalSize() const

View File

@@ -81,13 +81,6 @@ mkMesonLibrary (finalAttrs: {
(lib.mesonEnable "gc" enableGC)
];
env = {
# Needed for Meson to find Boost.
# https://github.com/NixOS/nixpkgs/issues/86131.
BOOST_INCLUDEDIR = "${lib.getDev boost}/include";
BOOST_LIBRARYDIR = "${lib.getLib boost}/lib";
};
meta = {
platforms = lib.platforms.unix ++ lib.platforms.windows;
};

View File

@@ -1595,7 +1595,7 @@ static RegisterPrimOp primop_placeholder({
.args = {"output"},
.doc = R"(
Return at
[output placeholder string](@docroot@/store/drv.md#output-placeholder)
[output placeholder string](@docroot@/store/derivation/index.md#output-placeholder)
for the specified *output* that will be substituted by the corresponding
[output path](@docroot@/glossary.md#gloss-output-path)
at build time.
@@ -2139,7 +2139,7 @@ static RegisterPrimOp primop_outputOf({
.args = {"derivation-reference", "output-name"},
.doc = R"(
Return the output path of a derivation, literally or using an
[input placeholder string](@docroot@/store/drv.md#input-placeholder)
[input placeholder string](@docroot@/store/derivation/index.md#input-placeholder)
if needed.
If the derivation has a statically-known output path (i.e. the derivation output is input-addressed, or fixed content-addresed), the output path will just be returned.

View File

@@ -1,9 +1,23 @@
#include "fetch-to-store.hh"
#include "fetchers.hh"
#include "cache.hh"
namespace nix {
fetchers::Cache::Key makeFetchToStoreCacheKey(
const std::string &name,
const std::string &fingerprint,
ContentAddressMethod method,
const std::string &path)
{
return fetchers::Cache::Key{"fetchToStore", {
{"name", name},
{"fingerprint", fingerprint},
{"method", std::string{method.render()}},
{"path", path}
}};
}
StorePath fetchToStore(
Store & store,
const SourcePath & path,
@@ -19,12 +33,7 @@ StorePath fetchToStore(
std::optional<fetchers::Cache::Key> cacheKey;
if (!filter && path.accessor->fingerprint) {
cacheKey = fetchers::Cache::Key{"fetchToStore", {
{"name", std::string{name}},
{"fingerprint", *path.accessor->fingerprint},
{"method", std::string{method.render()}},
{"path", path.path.abs()}
}};
cacheKey = makeFetchToStoreCacheKey(std::string{name}, *path.accessor->fingerprint, method, path.path.abs());
if (auto res = fetchers::getCache()->lookupStorePath(*cacheKey, store)) {
debug("store path cache hit for '%s'", path);
return res->storePath;

View File

@@ -5,6 +5,7 @@
#include "file-system.hh"
#include "repair-flag.hh"
#include "file-content-address.hh"
#include "cache.hh"
namespace nix {
@@ -22,4 +23,7 @@ StorePath fetchToStore(
PathFilter * filter = nullptr,
RepairFlag repair = NoRepair);
fetchers::Cache::Key makeFetchToStoreCacheKey(
const std::string & name, const std::string & fingerprint, ContentAddressMethod method, const std::string & path);
}

View File

@@ -323,6 +323,8 @@ std::pair<ref<SourceAccessor>, Input> Input::getAccessorUnchecked(ref<Store> sto
accessor->fingerprint = getFingerprint(store);
accessor->setPathDisplay("«" + to_string() + "»");
return {accessor, *this};
} catch (Error & e) {
debug("substitution of input '%s' failed: %s", to_string(), e.what());

View File

@@ -58,18 +58,23 @@ void FilteringSourceAccessor::checkAccess(const CanonPath & path)
struct AllowListSourceAccessorImpl : AllowListSourceAccessor
{
std::set<CanonPath> allowedPrefixes;
std::unordered_set<CanonPath> allowedPaths;
AllowListSourceAccessorImpl(
ref<SourceAccessor> next,
std::set<CanonPath> && allowedPrefixes,
std::unordered_set<CanonPath> && allowedPaths,
MakeNotAllowedError && makeNotAllowedError)
: AllowListSourceAccessor(SourcePath(next), std::move(makeNotAllowedError))
, allowedPrefixes(std::move(allowedPrefixes))
, allowedPaths(std::move(allowedPaths))
{ }
bool isAllowed(const CanonPath & path) override
{
return path.isAllowed(allowedPrefixes);
return
allowedPaths.contains(path)
|| path.isAllowed(allowedPrefixes);
}
void allowPrefix(CanonPath prefix) override
@@ -81,9 +86,14 @@ struct AllowListSourceAccessorImpl : AllowListSourceAccessor
ref<AllowListSourceAccessor> AllowListSourceAccessor::create(
ref<SourceAccessor> next,
std::set<CanonPath> && allowedPrefixes,
std::unordered_set<CanonPath> && allowedPaths,
MakeNotAllowedError && makeNotAllowedError)
{
return make_ref<AllowListSourceAccessorImpl>(next, std::move(allowedPrefixes), std::move(makeNotAllowedError));
return make_ref<AllowListSourceAccessorImpl>(
next,
std::move(allowedPrefixes),
std::move(allowedPaths),
std::move(makeNotAllowedError));
}
bool CachingFilteringSourceAccessor::isAllowed(const CanonPath & path)

View File

@@ -2,6 +2,8 @@
#include "source-path.hh"
#include <unordered_set>
namespace nix {
/**
@@ -70,6 +72,7 @@ struct AllowListSourceAccessor : public FilteringSourceAccessor
static ref<AllowListSourceAccessor> create(
ref<SourceAccessor> next,
std::set<CanonPath> && allowedPrefixes,
std::unordered_set<CanonPath> && allowedPaths,
MakeNotAllowedError && makeNotAllowedError);
using FilteringSourceAccessor::FilteringSourceAccessor;

View File

@@ -44,10 +44,11 @@ static void downloadToSink(
static std::string getLfsApiToken(const ParsedURL & url)
{
auto [status, output] = runProgram(RunOptions{
.program = "ssh",
.args = {*url.authority, "git-lfs-authenticate", url.path, "download"},
});
auto [status, output] = runProgram(
RunOptions{
.program = "ssh",
.args = {*url.authority, "git-lfs-authenticate", url.path, "download"},
});
if (output.empty())
throw Error(

View File

@@ -1215,16 +1215,12 @@ ref<SourceAccessor> GitRepoImpl::getAccessor(
ref<SourceAccessor> GitRepoImpl::getAccessor(const WorkdirInfo & wd, bool exportIgnore, MakeNotAllowedError makeNotAllowedError)
{
auto self = ref<GitRepoImpl>(shared_from_this());
/* In case of an empty workdir, return an empty in-memory tree. We
cannot use AllowListSourceAccessor because it would return an
error for the root (and we can't add the root to the allow-list
since that would allow access to all its children). */
ref<SourceAccessor> fileAccessor =
wd.files.empty()
? makeEmptySourceAccessor()
: AllowListSourceAccessor::create(
AllowListSourceAccessor::create(
makeFSSourceAccessor(path),
std::set<CanonPath> { wd.files },
std::set<CanonPath>{ wd.files },
// Always allow access to the root, but not its children.
std::unordered_set<CanonPath>{CanonPath::root},
std::move(makeNotAllowedError)).cast<SourceAccessor>();
if (exportIgnore)
return make_ref<GitExportIgnoreSourceAccessor>(self, fileAccessor, std::nullopt);

View File

@@ -351,8 +351,7 @@ struct GitInputScheme : InputScheme
if (commitMsg) {
// Pause the logger to allow for user input (such as a gpg passphrase) in `git commit`
logger->pause();
Finally restoreLogger([]() { logger->resume(); });
auto suspension = logger->suspend();
runProgram("git", true,
{ "-C", repoPath->string(), "--git-dir", repoInfo.gitDir, "commit", std::string(path.rel()), "-F", "-" },
*commitMsg);
@@ -533,14 +532,20 @@ struct GitInputScheme : InputScheme
return *head;
}
static MakeNotAllowedError makeNotAllowedError(std::string url)
static MakeNotAllowedError makeNotAllowedError(std::filesystem::path repoPath)
{
return [url{std::move(url)}](const CanonPath & path) -> RestrictedPathError
{
if (nix::pathExists(path.abs()))
return RestrictedPathError("access to path '%s' is forbidden because it is not under Git control; maybe you should 'git add' it to the repository '%s'?", path, url);
return [repoPath{std::move(repoPath)}](const CanonPath & path) -> RestrictedPathError {
if (nix::pathExists(repoPath / path.rel()))
return RestrictedPathError(
"Path '%1%' in the repository %2% is not tracked by Git.\n"
"\n"
"To make it visible to Nix, run:\n"
"\n"
"git -C %2% add \"%1%\"",
path.rel(),
repoPath);
else
return RestrictedPathError("path '%s' does not exist in Git repository '%s'", path, url);
return RestrictedPathError("Path '%s' does not exist in Git repository %s.", path.rel(), repoPath);
};
}
@@ -748,7 +753,7 @@ struct GitInputScheme : InputScheme
ref<SourceAccessor> accessor =
repo->getAccessor(repoInfo.workdirInfo,
exportIgnore,
makeNotAllowedError(repoInfo.locationToArg()));
makeNotAllowedError(repoPath));
/* If the repo has submodules, return a mounted input accessor
consisting of the accessor for the top-level repo and the

View File

@@ -76,10 +76,15 @@ headers = files(
'tarball.hh',
)
subdir('nix-meson-build-support/export-all-symbols')
subdir('nix-meson-build-support/windows-version')
this_library = library(
'nixfetchers',
sources,
dependencies : deps_public + deps_private + deps_other,
include_directories : include_dirs,
link_args: linker_export_flags,
prelink : true, # For C++ static initializers
install : true,
)

View File

@@ -2,6 +2,9 @@
#include "store-api.hh"
#include "archive.hh"
#include "store-path-accessor.hh"
#include "store-path-accessor.hh"
#include "cache.hh"
#include "fetch-to-store.hh"
namespace nix::fetchers {
@@ -125,7 +128,7 @@ struct PathInputScheme : InputScheme
auto absPath = getAbsPath(input);
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying '%s' to the store", absPath));
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying %s to the store", absPath));
// FIXME: check whether access to 'path' is allowed.
auto storePath = store->maybeParseStorePath(absPath.string());
@@ -142,6 +145,14 @@ struct PathInputScheme : InputScheme
storePath = store->addToStoreFromDump(*src, "source");
}
// To avoid copying the path again to the /nix/store, we need to add a cache entry.
ContentAddressMethod method = ContentAddressMethod::Raw::NixArchive;
auto fp = getFingerprint(store, input);
if (fp) {
auto cacheKey = makeFetchToStoreCacheKey(input.getName(), *fp, method, "/");
fetchers::getCache()->upsert(cacheKey, *store, {}, *storePath);
}
/* Trust the lastModified value supplied by the user, if
any. It's not a "secure" attribute so we don't care. */
if (!input.getLastModified())

View File

@@ -39,7 +39,7 @@ FlakeRef FlakeRef::resolve(
ref<Store> store,
const fetchers::RegistryFilter & filter) const
{
auto [input2, extraAttrs] = lookupInRegistries(store, input);
auto [input2, extraAttrs] = lookupInRegistries(store, input, filter);
return FlakeRef(std::move(input2), fetchers::maybeGetStrAttr(extraAttrs, "dir").value_or(subdir));
}

View File

@@ -58,10 +58,15 @@ headers = files(
'flake/url-name.hh',
)
subdir('nix-meson-build-support/export-all-symbols')
subdir('nix-meson-build-support/windows-version')
this_library = library(
'nixflake',
sources,
dependencies : deps_public + deps_private + deps_other,
include_directories : include_dirs,
link_args: linker_export_flags,
prelink : true, # For C++ static initializers
install : true,
)

View File

@@ -57,7 +57,7 @@ MixCommonArgs::MixCommonArgs(const std::string & programName)
if (hasPrefix(s.first, prefix))
completions.add(s.first, fmt("Set the `%s` setting.", s.first));
}
}
},
});
addFlag({
@@ -75,7 +75,7 @@ MixCommonArgs::MixCommonArgs(const std::string & programName)
.labels = Strings{"jobs"},
.handler = {[=](std::string s) {
settings.set("max-jobs", s);
}}
}},
});
std::string cat = "Options to override configuration settings";

View File

@@ -82,10 +82,15 @@ headers = [config_h] + files(
'shared.hh',
)
subdir('nix-meson-build-support/export-all-symbols')
subdir('nix-meson-build-support/windows-version')
this_library = library(
'nixmain',
sources,
dependencies : deps_public + deps_private + deps_other,
include_directories : include_dirs,
link_args: linker_export_flags,
prelink : true, # For C++ static initializers
install : true,
)

View File

@@ -73,8 +73,13 @@ private:
uint64_t corruptedPaths = 0, untrustedPaths = 0;
bool active = true;
bool paused = false;
size_t suspensions = 0;
bool haveUpdate = true;
bool isPaused() const
{
return suspensions > 0;
}
};
/** Helps avoid unnecessary redraws, see `redraw()` */
@@ -130,18 +135,30 @@ public:
void pause() override {
auto state (state_.lock());
state->paused = true;
state->suspensions++;
if (state->suspensions > 1) {
// already paused
return;
}
if (state->active)
writeToStderr("\r\e[K");
}
void resume() override {
auto state (state_.lock());
state->paused = false;
if (state->active)
writeToStderr("\r\e[K");
state->haveUpdate = true;
updateCV.notify_one();
if (state->suspensions == 0) {
log(lvlError, "nix::ProgressBar: resume() called without a matching preceding pause(). This is a bug.");
return;
} else {
state->suspensions--;
}
if (state->suspensions == 0) {
if (state->active)
writeToStderr("\r\e[K");
state->haveUpdate = true;
updateCV.notify_one();
}
}
bool isVerbose() override
@@ -383,7 +400,7 @@ public:
auto nextWakeup = std::chrono::milliseconds::max();
state.haveUpdate = false;
if (state.paused || !state.active) return nextWakeup;
if (state.isPaused() || !state.active) return nextWakeup;
std::string line;

View File

@@ -228,7 +228,7 @@ LegacyArgs::LegacyArgs(const std::string & programName,
.handler = {[=](std::string s) {
auto n = string2IntWithUnitPrefix<uint64_t>(s);
settings.set(dest, std::to_string(n));
}}
}},
});
};

View File

@@ -0,0 +1,27 @@
#include "nix/tests/outputs-spec.hh"
#include <rapidcheck.h>
namespace rc {
using namespace nix;
Gen<OutputsSpec> Arbitrary<OutputsSpec>::arbitrary()
{
return gen::mapcat(
gen::inRange<uint8_t>(0, std::variant_size_v<OutputsSpec::Raw>), [](uint8_t n) -> Gen<OutputsSpec> {
switch (n) {
case 0:
return gen::just((OutputsSpec) OutputsSpec::All{});
case 1:
return gen::map(
gen::nonEmpty(
gen::container<StringSet>(
gen::map(gen::arbitrary<StorePathName>(), [](StorePathName n) { return n.name; }))),
[](StringSet names) { return (OutputsSpec) OutputsSpec::Names{names}; });
default:
assert(false);
}
});
}
}

View File

@@ -1,126 +0,0 @@
#include "derivation-creation-and-realisation-goal.hh"
#include "worker.hh"
namespace nix {
DerivationCreationAndRealisationGoal::DerivationCreationAndRealisationGoal(
ref<SingleDerivedPath> drvReq, const OutputsSpec & wantedOutputs, Worker & worker, BuildMode buildMode)
: Goal(worker, DerivedPath::Built{.drvPath = drvReq, .outputs = wantedOutputs})
, drvReq(drvReq)
, wantedOutputs(wantedOutputs)
, buildMode(buildMode)
{
name =
fmt("outer obtaining drv from '%s' and then building outputs %s",
drvReq->to_string(worker.store),
std::visit(
overloaded{
[&](const OutputsSpec::All) -> std::string { return "* (all of them)"; },
[&](const OutputsSpec::Names os) { return concatStringsSep(", ", quoteStrings(os)); },
},
wantedOutputs.raw));
trace("created outer");
worker.updateProgress();
}
DerivationCreationAndRealisationGoal::~DerivationCreationAndRealisationGoal() {}
static StorePath pathPartOfReq(const SingleDerivedPath & req)
{
return std::visit(
overloaded{
[&](const SingleDerivedPath::Opaque & bo) { return bo.path; },
[&](const SingleDerivedPath::Built & bfd) { return pathPartOfReq(*bfd.drvPath); },
},
req.raw());
}
std::string DerivationCreationAndRealisationGoal::key()
{
/* Ensure that derivations get built in order of their name,
i.e. a derivation named "aardvark" always comes before "baboon". And
substitution goals and inner derivation goals always happen before
derivation goals (due to "b$"). */
return "c$" + std::string(pathPartOfReq(*drvReq).name()) + "$" + drvReq->to_string(worker.store);
}
void DerivationCreationAndRealisationGoal::timedOut(Error && ex) {}
void DerivationCreationAndRealisationGoal::addWantedOutputs(const OutputsSpec & outputs)
{
/* If we already want all outputs, there is nothing to do. */
auto newWanted = wantedOutputs.union_(outputs);
bool needRestart = !newWanted.isSubsetOf(wantedOutputs);
wantedOutputs = newWanted;
if (!needRestart)
return;
if (!optDrvPath)
// haven't started steps where the outputs matter yet
return;
worker.makeDerivationGoal(*optDrvPath, outputs, buildMode);
}
Goal::Co DerivationCreationAndRealisationGoal::init()
{
trace("outer init");
/* The first thing to do is to make sure that the derivation
exists. If it doesn't, it may be created through a
substitute. */
if (auto optDrvPath = [this]() -> std::optional<StorePath> {
if (buildMode != bmNormal)
return std::nullopt;
auto drvPath = StorePath::dummy;
try {
drvPath = resolveDerivedPath(worker.store, *drvReq);
} catch (MissingRealisation &) {
return std::nullopt;
}
auto cond = worker.evalStore.isValidPath(drvPath) || worker.store.isValidPath(drvPath);
return cond ? std::optional{drvPath} : std::nullopt;
}()) {
trace(
fmt("already have drv '%s' for '%s', can go straight to building",
worker.store.printStorePath(*optDrvPath),
drvReq->to_string(worker.store)));
} else {
trace("need to obtain drv we want to build");
addWaitee(worker.makeGoal(DerivedPath::fromSingle(*drvReq)));
co_await Suspend{};
}
trace("outer load and build derivation");
if (nrFailed != 0) {
co_return amDone(ecFailed, Error("cannot build missing derivation '%s'", drvReq->to_string(worker.store)));
}
StorePath drvPath = resolveDerivedPath(worker.store, *drvReq);
/* Build this step! */
concreteDrvGoal = worker.makeDerivationGoal(drvPath, wantedOutputs, buildMode);
{
auto g = upcast_goal(concreteDrvGoal);
/* We will finish with it ourselves, as if we were the derivational goal. */
g->preserveException = true;
}
optDrvPath = std::move(drvPath);
addWaitee(upcast_goal(concreteDrvGoal));
co_await Suspend{};
trace("outer build done");
buildResult = upcast_goal(concreteDrvGoal)
->getBuildResult(DerivedPath::Built{
.drvPath = drvReq,
.outputs = wantedOutputs,
});
auto g = upcast_goal(concreteDrvGoal);
co_return amDone(g->exitCode, g->ex);
}
}

View File

@@ -1,88 +0,0 @@
#pragma once
#include "parsed-derivations.hh"
#include "store-api.hh"
#include "pathlocks.hh"
#include "goal.hh"
namespace nix {
struct DerivationGoal;
/**
* This goal type is essentially the serial composition (like function
* composition) of a goal for getting a derivation, and then a
* `DerivationGoal` using the newly-obtained derivation.
*
* In the (currently experimental) general inductive case of derivations
* that are themselves build outputs, that first goal will be *another*
* `DerivationCreationAndRealisationGoal`. In the (much more common) base-case
* where the derivation has no provence and is just referred to by
* (content-addressed) store path, that first goal is a
* `SubstitutionGoal`.
*
* If we already have the derivation (e.g. if the evaluator has created
* the derivation locally and then instructured the store to build it),
* we can skip the first goal entirely as a small optimization.
*/
struct DerivationCreationAndRealisationGoal : public Goal
{
/**
* How to obtain a store path of the derivation to build.
*/
ref<SingleDerivedPath> drvReq;
/**
* The path of the derivation, once obtained.
**/
std::optional<StorePath> optDrvPath;
/**
* The goal for the corresponding concrete derivation.
**/
std::shared_ptr<DerivationGoal> concreteDrvGoal;
/**
* The specific outputs that we need to build.
*/
OutputsSpec wantedOutputs;
/**
* The final output paths of the build.
*
* - For input-addressed derivations, always the precomputed paths
*
* - For content-addressed derivations, calcuated from whatever the
* hash ends up being. (Note that fixed outputs derivations that
* produce the "wrong" output still install that data under its
* true content-address.)
*/
OutputPathMap finalOutputs;
BuildMode buildMode;
DerivationCreationAndRealisationGoal(
ref<SingleDerivedPath> drvReq,
const OutputsSpec & wantedOutputs,
Worker & worker,
BuildMode buildMode = bmNormal);
virtual ~DerivationCreationAndRealisationGoal();
void timedOut(Error && ex) override;
std::string key() override;
/**
* Add wanted outputs to an already existing derivation goal.
*/
void addWantedOutputs(const OutputsSpec & outputs);
Co init() override;
JobCategory jobCategory() const override
{
return JobCategory::Administration;
};
};
}

View File

@@ -137,8 +137,21 @@ Goal::Co DerivationGoal::init() {
trace("init");
if (useDerivation) {
/* The first thing to do is to make sure that the derivation
exists. If it doesn't, it may be created through a
substitute. */
if (buildMode != bmNormal || !worker.evalStore.isValidPath(drvPath)) {
addWaitee(upcast_goal(worker.makePathSubstitutionGoal(drvPath)));
co_await Suspend{};
}
trace("loading derivation");
if (nrFailed != 0) {
co_return done(BuildResult::MiscFailure, {}, Error("cannot build missing derivation '%s'", worker.store.printStorePath(drvPath)));
}
/* `drvPath' should already be a root, but let's be on the safe
side: if the user forgot to make it a root, we wouldn't want
things being garbage collected while we're busy. */
@@ -1540,24 +1553,23 @@ void DerivationGoal::waiteeDone(GoalPtr waitee, ExitCode result)
if (!useDerivation || !drv) return;
auto & fullDrv = *dynamic_cast<Derivation *>(drv.get());
std::optional info = tryGetConcreteDrvGoal(waitee);
if (!info) return;
const auto & [dg, drvReq] = *info;
auto * dg = dynamic_cast<DerivationGoal *>(&*waitee);
if (!dg) return;
auto * nodeP = fullDrv.inputDrvs.findSlot(drvReq.get());
auto * nodeP = fullDrv.inputDrvs.findSlot(DerivedPath::Opaque { .path = dg->drvPath });
if (!nodeP) return;
auto & outputs = nodeP->value;
for (auto & outputName : outputs) {
auto buildResult = dg.get().getBuildResult(DerivedPath::Built {
.drvPath = makeConstantStorePathRef(dg.get().drvPath),
auto buildResult = dg->getBuildResult(DerivedPath::Built {
.drvPath = makeConstantStorePathRef(dg->drvPath),
.outputs = OutputsSpec::Names { outputName },
});
if (buildResult.success()) {
auto i = buildResult.builtOutputs.find(outputName);
if (i != buildResult.builtOutputs.end())
inputDrvOutputs.insert_or_assign(
{ dg.get().drvPath, outputName },
{ dg->drvPath, outputName },
i->second.outPath);
}
}

View File

@@ -57,10 +57,6 @@ struct InitialOutput {
/**
* A goal for building some or all of the outputs of a derivation.
*
* The derivation must already be present, either in the store in a drv
* or in memory. If the derivation itself needs to be gotten first, a
* `DerivationCreationAndRealisationGoal` goal must be used instead.
*/
struct DerivationGoal : public Goal
{

View File

@@ -1,7 +1,6 @@
#include "worker.hh"
#include "substitution-goal.hh"
#ifndef _WIN32 // TODO Enable building on Windows
# include "derivation-creation-and-realisation-goal.hh"
# include "derivation-goal.hh"
#endif
#include "local-store.hh"
@@ -30,8 +29,8 @@ void Store::buildPaths(const std::vector<DerivedPath> & reqs, BuildMode buildMod
}
if (i->exitCode != Goal::ecSuccess) {
#ifndef _WIN32 // TODO Enable building on Windows
if (auto i2 = dynamic_cast<DerivationCreationAndRealisationGoal *>(i.get()))
failed.insert(i2->drvReq->to_string(*this));
if (auto i2 = dynamic_cast<DerivationGoal *>(i.get()))
failed.insert(printStorePath(i2->drvPath));
else
#endif
if (auto i2 = dynamic_cast<PathSubstitutionGoal *>(i.get()))

View File

@@ -175,7 +175,7 @@ Goal::Done Goal::amDone(ExitCode result, std::optional<Error> ex)
exitCode = result;
if (ex) {
if (!preserveException && !waiters.empty())
if (!waiters.empty())
logError(ex->info());
else
this->ex = std::move(*ex);

View File

@@ -50,16 +50,6 @@ enum struct JobCategory {
* A substitution an arbitrary store object; it will use network resources.
*/
Substitution,
/**
* A goal that does no "real" work by itself, and just exists to depend on
* other goals which *do* do real work. These goals therefore are not
* limited.
*
* These goals cannot infinitely create themselves, so there is no risk of
* a "fork bomb" type situation (which would be a problem even though the
* goal do no real work) either.
*/
Administration,
};
struct Goal : public std::enable_shared_from_this<Goal>
@@ -383,17 +373,6 @@ public:
*/
BuildResult getBuildResult(const DerivedPath &) const;
/**
* Hack to say that this goal should not log `ex`, but instead keep
* it around. Set by a waitee which sees itself as the designated
* continuation of this goal, responsible for reporting its
* successes or failures.
*
* @todo this is yet another not-nice hack in the goal system that
* we ought to get rid of. See #11927
*/
bool preserveException = false;
/**
* Exception containing an error message, if any.
*/

View File

@@ -4,7 +4,6 @@
#include "substitution-goal.hh"
#include "drv-output-substitution-goal.hh"
#include "derivation-goal.hh"
#include "derivation-creation-and-realisation-goal.hh"
#ifndef _WIN32 // TODO Enable building on Windows
# include "local-derivation-goal.hh"
# include "hook-instance.hh"
@@ -44,24 +43,6 @@ Worker::~Worker()
}
std::shared_ptr<DerivationCreationAndRealisationGoal> Worker::makeDerivationCreationAndRealisationGoal(
ref<SingleDerivedPath> drvReq,
const OutputsSpec & wantedOutputs,
BuildMode buildMode)
{
std::weak_ptr<DerivationCreationAndRealisationGoal> & goal_weak = outerDerivationGoals.ensureSlot(*drvReq).value;
std::shared_ptr<DerivationCreationAndRealisationGoal> goal = goal_weak.lock();
if (!goal) {
goal = std::make_shared<DerivationCreationAndRealisationGoal>(drvReq, wantedOutputs, *this, buildMode);
goal_weak = goal;
wakeUp(goal);
} else {
goal->addWantedOutputs(wantedOutputs);
}
return goal;
}
std::shared_ptr<DerivationGoal> Worker::makeDerivationGoalCommon(
const StorePath & drvPath,
const OutputsSpec & wantedOutputs,
@@ -139,7 +120,10 @@ GoalPtr Worker::makeGoal(const DerivedPath & req, BuildMode buildMode)
{
return std::visit(overloaded {
[&](const DerivedPath::Built & bfd) -> GoalPtr {
return makeDerivationCreationAndRealisationGoal(bfd.drvPath, bfd.outputs, buildMode);
if (auto bop = std::get_if<DerivedPath::Opaque>(&*bfd.drvPath))
return makeDerivationGoal(bop->path, bfd.outputs, buildMode);
else
throw UnimplementedError("Building dynamic derivations in one shot is not yet implemented.");
},
[&](const DerivedPath::Opaque & bo) -> GoalPtr {
return makePathSubstitutionGoal(bo.path, buildMode == bmRepair ? Repair : NoRepair);
@@ -148,46 +132,24 @@ GoalPtr Worker::makeGoal(const DerivedPath & req, BuildMode buildMode)
}
template<typename K, typename V, typename F>
static void cullMap(std::map<K, V> & goalMap, F f)
{
for (auto i = goalMap.begin(); i != goalMap.end();)
if (!f(i->second))
i = goalMap.erase(i);
else ++i;
}
template<typename K, typename G>
static void removeGoal(std::shared_ptr<G> goal, std::map<K, std::weak_ptr<G>> & goalMap)
{
/* !!! inefficient */
cullMap(goalMap, [&](const std::weak_ptr<G> & gp) -> bool {
return gp.lock() != goal;
});
}
template<typename K>
static void removeGoal(std::shared_ptr<DerivationCreationAndRealisationGoal> goal, std::map<K, DerivedPathMap<std::weak_ptr<DerivationCreationAndRealisationGoal>>::ChildNode> & goalMap);
template<typename K>
static void removeGoal(std::shared_ptr<DerivationCreationAndRealisationGoal> goal, std::map<K, DerivedPathMap<std::weak_ptr<DerivationCreationAndRealisationGoal>>::ChildNode> & goalMap)
{
/* !!! inefficient */
cullMap(goalMap, [&](DerivedPathMap<std::weak_ptr<DerivationCreationAndRealisationGoal>>::ChildNode & node) -> bool {
if (node.value.lock() == goal)
node.value.reset();
removeGoal(goal, node.childMap);
return !node.value.expired() || !node.childMap.empty();
});
for (auto i = goalMap.begin();
i != goalMap.end(); )
if (i->second.lock() == goal) {
auto j = i; ++j;
goalMap.erase(i);
i = j;
}
else ++i;
}
void Worker::removeGoal(GoalPtr goal)
{
if (auto drvGoal = std::dynamic_pointer_cast<DerivationCreationAndRealisationGoal>(goal))
nix::removeGoal(drvGoal, outerDerivationGoals.map);
else if (auto drvGoal = std::dynamic_pointer_cast<DerivationGoal>(goal))
if (auto drvGoal = std::dynamic_pointer_cast<DerivationGoal>(goal))
nix::removeGoal(drvGoal, derivationGoals);
else
if (auto subGoal = std::dynamic_pointer_cast<PathSubstitutionGoal>(goal))
@@ -253,9 +215,6 @@ void Worker::childStarted(GoalPtr goal, const std::set<MuxablePipePollState::Com
case JobCategory::Build:
nrLocalBuilds++;
break;
case JobCategory::Administration:
/* Intentionally not limited, see docs */
break;
default:
unreachable();
}
@@ -279,9 +238,6 @@ void Worker::childTerminated(Goal * goal, bool wakeSleepers)
assert(nrLocalBuilds > 0);
nrLocalBuilds--;
break;
case JobCategory::Administration:
/* Intentionally not limited, see docs */
break;
default:
unreachable();
}
@@ -334,9 +290,9 @@ void Worker::run(const Goals & _topGoals)
for (auto & i : _topGoals) {
topGoals.insert(i);
if (auto goal = dynamic_cast<DerivationCreationAndRealisationGoal *>(i.get())) {
if (auto goal = dynamic_cast<DerivationGoal *>(i.get())) {
topPaths.push_back(DerivedPath::Built {
.drvPath = goal->drvReq,
.drvPath = makeConstantStorePathRef(goal->drvPath),
.outputs = goal->wantedOutputs,
});
} else
@@ -596,22 +552,4 @@ GoalPtr upcast_goal(std::shared_ptr<DrvOutputSubstitutionGoal> subGoal)
return subGoal;
}
GoalPtr upcast_goal(std::shared_ptr<DerivationGoal> subGoal)
{
return subGoal;
}
std::optional<std::pair<std::reference_wrapper<const DerivationGoal>, std::reference_wrapper<const SingleDerivedPath>>> tryGetConcreteDrvGoal(GoalPtr waitee)
{
auto * odg = dynamic_cast<DerivationCreationAndRealisationGoal *>(&*waitee);
if (!odg) return std::nullopt;
/* If we failed to obtain the concrete drv, we won't have created
the concrete derivation goal. */
if (!odg->concreteDrvGoal) return std::nullopt;
return {{
std::cref(*odg->concreteDrvGoal),
std::cref(*odg->drvReq),
}};
}
}

View File

@@ -3,7 +3,6 @@
#include "types.hh"
#include "store-api.hh"
#include "derived-path-map.hh"
#include "goal.hh"
#include "realisation.hh"
#include "muxable-pipe.hh"
@@ -14,7 +13,6 @@
namespace nix {
/* Forward definition. */
struct DerivationCreationAndRealisationGoal;
struct DerivationGoal;
struct PathSubstitutionGoal;
class DrvOutputSubstitutionGoal;
@@ -33,25 +31,9 @@ class DrvOutputSubstitutionGoal;
*/
GoalPtr upcast_goal(std::shared_ptr<PathSubstitutionGoal> subGoal);
GoalPtr upcast_goal(std::shared_ptr<DrvOutputSubstitutionGoal> subGoal);
GoalPtr upcast_goal(std::shared_ptr<DerivationGoal> subGoal);
typedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point;
/**
* The current implementation of impure derivations has
* `DerivationGoal`s accumulate realisations from their waitees.
* Unfortunately, `DerivationGoal`s don't directly depend on other
* goals, but instead depend on `DerivationCreationAndRealisationGoal`s.
*
* We try not to share any of the details of any goal type with any
* other, for sake of modularity and quicker rebuilds. This means we
* cannot "just" downcast and fish out the field. So as an escape hatch,
* we have made the function, written in `worker.cc` where all the goal
* types are visible, and use it instead.
*/
std::optional<std::pair<std::reference_wrapper<const DerivationGoal>, std::reference_wrapper<const SingleDerivedPath>>> tryGetConcreteDrvGoal(GoalPtr waitee);
/**
* A mapping used to remember for each child process to what goal it
* belongs, and comm channels for receiving log data and output
@@ -121,9 +103,6 @@ private:
* Maps used to prevent multiple instantiations of a goal for the
* same derivation / path.
*/
DerivedPathMap<std::weak_ptr<DerivationCreationAndRealisationGoal>> outerDerivationGoals;
std::map<StorePath, std::weak_ptr<DerivationGoal>> derivationGoals;
std::map<StorePath, std::weak_ptr<PathSubstitutionGoal>> substitutionGoals;
std::map<DrvOutput, std::weak_ptr<DrvOutputSubstitutionGoal>> drvOutputSubstitutionGoals;
@@ -217,9 +196,6 @@ public:
* @ref DerivationGoal "derivation goal"
*/
private:
std::shared_ptr<DerivationCreationAndRealisationGoal> makeDerivationCreationAndRealisationGoal(
ref<SingleDerivedPath> drvPath,
const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal);
std::shared_ptr<DerivationGoal> makeDerivationGoalCommon(
const StorePath & drvPath, const OutputsSpec & wantedOutputs,
std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal);

View File

@@ -23,11 +23,7 @@ void builtinUnpackChannel(
throw Error("channelName is not allowed to contain filesystem separators, got %1%", channelName);
}
try {
fs::create_directories(out);
} catch (fs::filesystem_error &) {
throw SysError("creating directory '%1%'", out.string());
}
createDirs(out);
unpackTarfile(src, out);

View File

@@ -1025,6 +1025,7 @@ void processConnection(
{
#ifndef _WIN32 // TODO need graceful async exit support on Windows?
auto monitor = !recursive ? std::make_unique<MonitorFdHup>(from.fd) : nullptr;
(void) monitor; // suppress warning
#endif
/* Exchange the greeting. */

View File

@@ -52,7 +52,6 @@ typename DerivedPathMap<V>::ChildNode * DerivedPathMap<V>::findSlot(const Single
// instantiations
#include "derivation-creation-and-realisation-goal.hh"
namespace nix {
template<>
@@ -69,7 +68,4 @@ std::strong_ordering DerivedPathMap<std::set<std::string>>::ChildNode::operator
template struct DerivedPathMap<std::set<std::string>>::ChildNode;
template struct DerivedPathMap<std::set<std::string>>;
template struct DerivedPathMap<std::weak_ptr<DerivationCreationAndRealisationGoal>>;
};

View File

@@ -21,11 +21,8 @@ namespace nix {
*
* @param V A type to instantiate for each output. It should probably
* should be an "optional" type so not every interior node has to have a
* value. For example, the scheduler uses
* `DerivedPathMap<std::weak_ptr<DerivationCreationAndRealisationGoal>>` to
* remember which goals correspond to which outputs. `* const Something`
* or `std::optional<Something>` would also be good choices for
* "optional" types.
* value. `* const Something` or `std::optional<Something>` would be
* good choices for "optional" types.
*/
template<typename V>
struct DerivedPathMap {

View File

@@ -278,21 +278,21 @@ template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::s
.aliases = aliases,
.description = "Enable sandboxing.",
.category = category,
.handler = {[this]() { override(smEnabled); }}
.handler = {[this]() { override(smEnabled); }},
});
args.addFlag({
.longName = "no-" + name,
.aliases = aliases,
.description = "Disable sandboxing.",
.category = category,
.handler = {[this]() { override(smDisabled); }}
.handler = {[this]() { override(smDisabled); }},
});
args.addFlag({
.longName = "relaxed-" + name,
.aliases = aliases,
.description = "Enable sandboxing, but allow builds to disable it.",
.category = category,
.handler = {[this]() { override(smRelaxed); }}
.handler = {[this]() { override(smRelaxed); }},
});
}

View File

@@ -116,7 +116,7 @@ LocalStore::LocalStore(
state->stmts = std::make_unique<State::Stmts>();
/* Create missing state directories if they don't already exist. */
createDirs(realStoreDir);
createDirs(realStoreDir.get());
if (readOnly) {
experimentalFeatureSettings.require(Xp::ReadOnlyLocalStore);
} else {
@@ -247,7 +247,7 @@ LocalStore::LocalStore(
else if (curSchema == 0) { /* new store */
curSchema = nixSchemaVersion;
openDB(*state, true);
writeFile(schemaPath, fmt("%1%", nixSchemaVersion), 0666, true);
writeFile(schemaPath, fmt("%1%", curSchema), 0666, true);
}
else if (curSchema < nixSchemaVersion) {

View File

@@ -112,7 +112,8 @@ deps_public += nlohmann_json
sqlite = dependency('sqlite3', 'sqlite', version : '>=3.6.19')
deps_private += sqlite
# AWS C++ SDK has bad pkg-config
# AWS C++ SDK has bad pkg-config. See
# https://github.com/aws/aws-sdk-cpp/issues/2673 for details.
aws_s3 = dependency('aws-cpp-sdk-s3', required : false)
configdata.set('ENABLE_S3', aws_s3.found().to_int())
if aws_s3.found()
@@ -183,7 +184,6 @@ sources = files(
'binary-cache-store.cc',
'build-result.cc',
'build/derivation-goal.cc',
'build/derivation-creation-and-realisation-goal.cc',
'build/drv-output-substitution-goal.cc',
'build/entry-points.cc',
'build/goal.cc',
@@ -257,7 +257,6 @@ headers = [config_h] + files(
'binary-cache-store.hh',
'build-result.hh',
'build/derivation-goal.hh',
'build/derivation-creation-and-realisation-goal.hh',
'build/drv-output-substitution-goal.hh',
'build/goal.hh',
'build/substitution-goal.hh',

View File

@@ -21,6 +21,10 @@
version,
embeddedSandboxShell ? stdenv.hostPlatform.isStatic,
withAWS ?
# Default is this way because there have been issues building this dependency
stdenv.hostPlatform == stdenv.buildPlatform && (stdenv.isLinux || stdenv.isDarwin),
}:
let
@@ -60,9 +64,7 @@ mkMesonLibrary (finalAttrs: {
++ lib.optional stdenv.hostPlatform.isLinux libseccomp
# There have been issues building these dependencies
++ lib.optional stdenv.hostPlatform.isDarwin darwin.apple_sdk.libs.sandbox
++ lib.optional (
stdenv.hostPlatform == stdenv.buildPlatform && (stdenv.isLinux || stdenv.isDarwin)
) aws-sdk-cpp;
++ lib.optional withAWS aws-sdk-cpp;
propagatedBuildInputs = [
nix-util
@@ -78,13 +80,6 @@ mkMesonLibrary (finalAttrs: {
(lib.mesonOption "sandbox-shell" "${busybox-sandbox-shell}/bin/busybox")
];
env = {
# Needed for Meson to find Boost.
# https://github.com/NixOS/nixpkgs/issues/86131.
BOOST_INCLUDEDIR = "${lib.getDev boost}/include";
BOOST_LIBRARYDIR = "${lib.getLib boost}/lib";
};
meta = {
platforms = lib.platforms.unix ++ lib.platforms.windows;
};

View File

@@ -117,10 +117,10 @@ std::unique_ptr<SSHMaster::Connection> SSHMaster::startCommand(
ProcessOptions options;
options.dieWithParent = false;
std::unique_ptr<Logger::Suspension> loggerSuspension;
if (!fakeSSH && !useMaster) {
logger->pause();
loggerSuspension = std::make_unique<Logger::Suspension>(logger->suspend());
}
Finally cleanup = [&]() { logger->resume(); };
conn->sshPid = startProcess([&]() {
restoreProcessContext();
@@ -199,8 +199,7 @@ Path SSHMaster::startMaster()
ProcessOptions options;
options.dieWithParent = false;
logger->pause();
Finally cleanup = [&]() { logger->resume(); };
auto suspension = logger->suspend();
if (isMasterRunning())
return state->socketPath;

View File

@@ -2144,7 +2144,18 @@ void LocalDerivationGoal::runChild()
without file-write* allowed, access() incorrectly returns EPERM
*/
sandboxProfile += "(allow file-read* file-write* process-exec\n";
// We create multiple allow lists, to avoid exceeding a limit in the darwin sandbox interpreter.
// See https://github.com/NixOS/nix/issues/4119
// We split our allow groups approximately at half the actual limit, 1 << 16
const int breakpoint = sandboxProfile.length() + (1 << 14);
for (auto & i : pathsInChroot) {
if (sandboxProfile.length() >= breakpoint) {
debug("Sandbox break: %d %d", sandboxProfile.length(), breakpoint);
sandboxProfile += ")\n(allow file-read* file-write* process-exec\n";
}
if (i.first != i.second.source)
throw Error(
"can't map '%1%' to '%2%': mismatched impure paths not supported on Darwin",
@@ -2909,8 +2920,12 @@ void LocalDerivationGoal::checkOutputs(const std::map<std::string, ValidPathInfo
spec.insert(worker.store.parseStorePath(i));
else if (auto output = get(outputs, i))
spec.insert(output->path);
else
throw BuildError("derivation contains an illegal reference specifier '%s'", i);
else {
std::string outputsListing = concatMapStringsSep(", ", outputs, [](auto & o) { return o.first; });
throw BuildError("derivation '%s' output check for '%s' contains an illegal reference specifier '%s',"
" expected store path or output name (one of [%s])",
worker.store.printStorePath(drvPath), outputName, i, outputsListing);
}
}
auto used = recursive

View File

@@ -0,0 +1,18 @@
#include "util.hh"
#include "monitor-fd.hh"
#include <sys/file.h>
#include <gtest/gtest.h>
namespace nix {
TEST(MonitorFdHup, shouldNotBlock)
{
Pipe p;
p.create();
{
// when monitor gets destroyed it should cancel the
// background thread and do not block
MonitorFdHup monitor(p.readSide.get());
}
}
}

View File

@@ -80,6 +80,42 @@ TEST(concatStringsSep, buildSingleString)
ASSERT_EQ(concatStringsSep(",", strings), "this");
}
TEST(concatMapStringsSep, empty)
{
Strings strings;
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "");
}
TEST(concatMapStringsSep, justOne)
{
Strings strings;
strings.push_back("this");
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "this");
}
TEST(concatMapStringsSep, two)
{
Strings strings;
strings.push_back("this");
strings.push_back("that");
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "this,that");
}
TEST(concatMapStringsSep, map)
{
std::map<std::string, std::string> strings;
strings["this"] = "that";
strings["1"] = "one";
ASSERT_EQ(
concatMapStringsSep(
", ", strings, [](const std::pair<std::string, std::string> & s) { return s.first + " -> " + s.second; }),
"1 -> one, this -> that");
}
/* ----------------------------------------------------------------------------
* dropEmptyInitThenConcatStringsSep
* --------------------------------------------------------------------------*/

View File

@@ -50,6 +50,14 @@ struct LinesOfCode {
std::optional<std::string> nextLineOfCode;
};
/* NOTE: position.hh recursively depends on source-path.hh -> source-accessor.hh
-> hash.hh -> config.hh -> experimental-features.hh -> error.hh -> Pos.
There are other such cycles.
Thus, Pos has to be an incomplete type in this header. But since ErrorInfo/Trace
have to refer to Pos, they have to use pointer indirection via std::shared_ptr
to break the recursive header dependency.
FIXME: Untangle this mess. Should there be AbstractPos as there used to be before
4feb7d9f71? */
struct Pos;
void printCodeLines(std::ostream & out,

View File

@@ -29,7 +29,17 @@
namespace nix {
namespace fs { using namespace std::filesystem; }
namespace fs {
using namespace std::filesystem;
bool symlink_exists(const std::filesystem::path & path) {
try {
return std::filesystem::exists(std::filesystem::symlink_status(path));
} catch (const std::filesystem::filesystem_error & e) {
throw SysError("cannot check existence of %1%", path);
}
}
}
bool isAbsolute(PathView path)
{
@@ -475,12 +485,12 @@ void createDir(const Path & path, mode_t mode)
throw SysError("creating directory '%1%'", path);
}
void createDirs(const Path & path)
void createDirs(const fs::path & path)
{
try {
fs::create_directories(path);
} catch (fs::filesystem_error & e) {
throw SysError("creating directory '%1%'", path);
throw SysError("creating directory '%1%'", path.string());
}
}
@@ -680,7 +690,7 @@ void setWriteTime(
if (utimes(path.c_str(), times) == -1)
throw SysError("changing modification time of %s (not a symlink)", path);
} else {
throw Error("Cannot modification time of symlink %s", path);
throw Error("Cannot change modification time of symlink %s", path);
}
#endif
#endif

View File

@@ -134,6 +134,7 @@ bool pathExists(const Path & path);
namespace fs {
/**
* TODO: we may actually want to use pathExists instead of this function
* ```
* symlink_exists(p) = std::filesystem::exists(std::filesystem::symlink_status(p))
* ```
@@ -142,9 +143,7 @@ namespace fs {
* std::filesystem::exists(p) = std::filesystem::exists(std::filesystem::status(p))
* ```
*/
inline bool symlink_exists(const std::filesystem::path & path) {
return std::filesystem::exists(std::filesystem::symlink_status(path));
}
bool symlink_exists(const std::filesystem::path & path);
} // namespace fs
@@ -231,14 +230,9 @@ void deletePath(const std::filesystem::path & path, uint64_t & bytesFreed);
/**
* Create a directory and all its parents, if necessary.
*
* In the process of being deprecated for
* `std::filesystem::create_directories`.
* Wrapper around `std::filesystem::create_directories` to handle exceptions.
*/
void createDirs(const Path & path);
inline void createDirs(PathView path)
{
return createDirs(Path(path));
}
void createDirs(const std::filesystem::path & path);
/**
* Create a single directory.

View File

@@ -33,7 +33,7 @@ std::optional<Mode> decodeMode(RawMode m) {
static std::string getStringUntil(Source & source, char byte)
{
std::string s;
char n[1];
char n[1] = { 0 };
source(std::string_view { n, 1 });
while (*n != byte) {
s += *n;

View File

@@ -43,6 +43,19 @@ void Logger::writeToStdout(std::string_view s)
writeFull(standard_out, "\n");
}
Logger::Suspension Logger::suspend()
{
pause();
return Suspension { ._finalize = {[this](){this->resume();}} };
}
std::optional<Logger::Suspension> Logger::suspendIf(bool cond)
{
if (cond)
return suspend();
return {};
}
class SimpleLogger : public Logger
{
public:

View File

@@ -4,6 +4,7 @@
#include "error.hh"
#include "config.hh"
#include "file-descriptor.hh"
#include "finally.hh"
#include <nlohmann/json_fwd.hpp>
@@ -75,6 +76,17 @@ public:
virtual void stop() { };
/**
* Guard object to resume the logger when done.
*/
struct Suspension {
Finally<std::function<void()>> _finalize;
};
Suspension suspend();
std::optional<Suspension> suspendIf(bool cond);
virtual void pause() { };
virtual void resume() { };

View File

@@ -155,6 +155,7 @@ sources = files(
'memory-source-accessor.cc',
'mounted-source-accessor.cc',
'position.cc',
'pos-table.cc',
'posix-source-accessor.cc',
'references.cc',
'serialise.cc',
@@ -225,6 +226,8 @@ headers = [config_h] + files(
'muxable-pipe.hh',
'os-string.hh',
'pool.hh',
'pos-idx.hh',
'pos-table.hh',
'position.hh',
'posix-source-accessor.hh',
'processes.hh',

View File

@@ -58,13 +58,6 @@ mkMesonLibrary (finalAttrs: {
(lib.mesonEnable "cpuid" stdenv.hostPlatform.isx86_64)
];
env = {
# Needed for Meson to find Boost.
# https://github.com/NixOS/nixpkgs/issues/86131.
BOOST_INCLUDEDIR = "${lib.getDev boost}/include";
BOOST_LIBRARYDIR = "${lib.getLib boost}/lib";
};
meta = {
platforms = lib.platforms.unix ++ lib.platforms.windows;
};

View File

@@ -1,4 +1,5 @@
#pragma once
///@file
#include <cinttypes>
#include <functional>

37
src/libutil/pos-table.cc Normal file
View File

@@ -0,0 +1,37 @@
#include "pos-table.hh"
#include <algorithm>
namespace nix {
/* Position table. */
Pos PosTable::operator[](PosIdx p) const
{
auto origin = resolve(p);
if (!origin)
return {};
const auto offset = origin->offsetOf(p);
Pos result{0, 0, origin->origin};
auto lines = this->lines.lock();
auto linesForInput = (*lines)[origin->offset];
if (linesForInput.empty()) {
auto source = result.getSource().value_or("");
const char * begin = source.data();
for (Pos::LinesIterator it(source), end; it != end; it++)
linesForInput.push_back(it->data() - begin);
if (linesForInput.empty())
linesForInput.push_back(0);
}
// as above: the first line starts at byte 0 and is always present
auto lineStartOffset = std::prev(std::upper_bound(linesForInput.begin(), linesForInput.end(), offset));
result.line = 1 + (lineStartOffset - linesForInput.begin());
result.column = 1 + (offset - *lineStartOffset);
return result;
}
}

View File

@@ -1,4 +1,5 @@
#pragma once
///@file
#include <cstdint>
#include <vector>
@@ -18,9 +19,12 @@ public:
private:
uint32_t offset;
Origin(Pos::Origin origin, uint32_t offset, size_t size):
offset(offset), origin(origin), size(size)
{}
Origin(Pos::Origin origin, uint32_t offset, size_t size)
: offset(offset)
, origin(origin)
, size(size)
{
}
public:
const Pos::Origin origin;
@@ -72,6 +76,17 @@ public:
return PosIdx(1 + origin.offset + offset);
}
/**
* Convert a byte-offset PosIdx into a Pos with line/column information.
*
* @param p Byte offset into the virtual concatenation of all parsed contents
* @return Position
*
* @warning Very expensive to call, as this has to read the entire source
* into memory each time. Call this only if absolutely necessary. Prefer
* to keep PosIdx around instead of needlessly converting it into Pos by
* using this lookup method.
*/
Pos operator[](PosIdx p) const;
Pos::Origin originOf(PosIdx p) const

View File

@@ -66,6 +66,13 @@ std::optional<std::string> Pos::getSource() const
}, origin);
}
std::optional<SourcePath> Pos::getSourcePath() const
{
if (auto * path = std::get_if<SourcePath>(&origin))
return *path;
return std::nullopt;
}
void Pos::print(std::ostream & out, bool showOrigin) const
{
if (showOrigin) {

View File

@@ -50,6 +50,7 @@ struct Pos
explicit operator bool() const { return line > 0; }
/* TODO: Why std::shared_ptr<Pos> and not std::shared_ptr<const Pos>? */
operator std::shared_ptr<Pos>() const;
/**
@@ -69,9 +70,7 @@ struct Pos
/**
* Get the SourcePath, if the source was loaded from a file.
*/
std::optional<SourcePath> getSourcePath() const {
return *std::get_if<SourcePath>(&origin);
}
std::optional<SourcePath> getSourcePath() const;
struct LinesIterator {
using difference_type = size_t;

View File

@@ -37,6 +37,7 @@ basicSplitString(std::basic_string_view<OsChar> s, std::basic_string_view<OsChar
template std::string concatStringsSep(std::string_view, const std::list<std::string> &);
template std::string concatStringsSep(std::string_view, const std::set<std::string> &);
template std::string concatStringsSep(std::string_view, const std::vector<std::string> &);
template std::string concatStringsSep(std::string_view, const boost::container::small_vector<std::string, 64> &);
typedef std::string_view strings_2[2];
template std::string concatStringsSep(std::string_view, const strings_2 &);

View File

@@ -6,6 +6,8 @@
#include <string>
#include <vector>
#include <boost/container/small_vector.hpp>
namespace nix {
/*
@@ -54,6 +56,21 @@ std::string concatStringsSep(const std::string_view sep, const C & ss);
extern template std::string concatStringsSep(std::string_view, const std::list<std::string> &);
extern template std::string concatStringsSep(std::string_view, const std::set<std::string> &);
extern template std::string concatStringsSep(std::string_view, const std::vector<std::string> &);
extern template std::string concatStringsSep(std::string_view, const boost::container::small_vector<std::string, 64> &);
/**
* Apply a function to the `iterable`'s items and concat them with `separator`.
*/
template<class C, class F>
std::string concatMapStringsSep(std::string_view separator, const C & iterable, F fn)
{
boost::container::small_vector<std::string, 64> strings;
strings.reserve(iterable.size());
for (const auto & elem : iterable) {
strings.push_back(fn(elem));
}
return concatStringsSep(separator, strings);
}
/**
* Ignore any empty strings at the start of the list, and then concatenate the

View File

@@ -166,7 +166,7 @@ void unpackTarfile(Source & source, const fs::path & destDir)
{
auto archive = TarArchive(source);
fs::create_directories(destDir);
createDirs(destDir);
extract_archive(archive, destDir);
}
@@ -174,7 +174,7 @@ void unpackTarfile(const fs::path & tarFile, const fs::path & destDir)
{
auto archive = TarArchive(tarFile);
fs::create_directories(destDir);
createDirs(destDir);
extract_archive(archive, destDir);
}

View File

@@ -5,9 +5,27 @@
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
namespace nix {
namespace {
// This function is needed to handle non-blocking reads/writes. This is needed in the buildhook, because
// somehow the json logger file descriptor ends up beeing non-blocking and breaks remote-building.
// TODO: get rid of buildhook and remove this function again (https://github.com/NixOS/nix/issues/12688)
void pollFD(int fd, int events)
{
struct pollfd pfd;
pfd.fd = fd;
pfd.events = events;
int ret = poll(&pfd, 1, -1);
if (ret == -1) {
throw SysError("poll on file descriptor failed");
}
}
}
std::string readFile(int fd)
{
struct stat st;
@@ -17,14 +35,18 @@ std::string readFile(int fd)
return drainFD(fd, true, st.st_size);
}
void readFull(int fd, char * buf, size_t count)
{
while (count) {
checkInterrupt();
ssize_t res = read(fd, buf, count);
if (res == -1) {
if (errno == EINTR) continue;
switch (errno) {
case EINTR: continue;
case EAGAIN:
pollFD(fd, POLLIN);
continue;
}
throw SysError("reading from file");
}
if (res == 0) throw EndOfFile("unexpected end-of-file");
@@ -39,8 +61,15 @@ void writeFull(int fd, std::string_view s, bool allowInterrupts)
while (!s.empty()) {
if (allowInterrupts) checkInterrupt();
ssize_t res = write(fd, s.data(), s.size());
if (res == -1 && errno != EINTR)
if (res == -1) {
switch (errno) {
case EINTR: continue;
case EAGAIN:
pollFD(fd, POLLOUT);
continue;
}
throw SysError("writing to file");
}
if (res > 0)
s.remove_prefix(res);
}
@@ -56,8 +85,15 @@ std::string readLine(int fd, bool eofOk)
// FIXME: inefficient
ssize_t rd = read(fd, &ch, 1);
if (rd == -1) {
if (errno != EINTR)
switch (errno) {
case EINTR: continue;
case EAGAIN: {
pollFD(fd, POLLIN);
continue;
}
default:
throw SysError("reading a line");
}
} else if (rd == 0) {
if (eofOk)
return s;

View File

@@ -14,35 +14,74 @@
namespace nix {
class MonitorFdHup
{
private:
std::thread thread;
Pipe notifyPipe;
public:
MonitorFdHup(int fd)
{
thread = std::thread([fd]() {
notifyPipe.create();
thread = std::thread([this, fd]() {
while (true) {
/* Wait indefinitely until a POLLHUP occurs. */
struct pollfd fds[1];
fds[0].fd = fd;
/* Polling for no specific events (i.e. just waiting
for an error/hangup) doesn't work on macOS
anymore. So wait for read events and ignore
them. */
fds[0].events =
#ifdef __APPLE__
POLLRDNORM
#else
// There is a POSIX violation on macOS: you have to listen for
// at least POLLHUP to receive HUP events for a FD. POSIX says
// this is not so, and you should just receive them regardless.
// However, as of our testing on macOS 14.5, the events do not
// get delivered if in the all-bits-unset case, but do get
// delivered if `POLLHUP` is set.
//
// This bug filed as rdar://37537852
// (https://openradar.appspot.com/37537852).
//
// macOS's own man page
// (https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/poll.2.html)
// additionally says that `POLLHUP` is ignored as an input. It
// seems the likely order of events here was
//
// 1. macOS did not follow the POSIX spec
//
// 2. Somebody ninja-fixed this other spec violation to make
// sure `POLLHUP` was not forgotten about, even though they
// "fixed" this issue in a spec-non-compliant way. Whatever,
// we'll use the fix.
//
// Relevant code, current version, which shows the :
// https://github.com/apple-oss-distributions/xnu/blob/94d3b452840153a99b38a3a9659680b2a006908e/bsd/kern/sys_generic.c#L1751-L1758
//
// The `POLLHUP` detection was added in
// https://github.com/apple-oss-distributions/xnu/commit/e13b1fa57645afc8a7b2e7d868fe9845c6b08c40#diff-a5aa0b0e7f4d866ca417f60702689fc797e9cdfe33b601b05ccf43086c35d395R1468
// That means added in 2007 or earlier. Should be good enough
// for us.
short hangup_events =
#ifdef __APPLE__
POLLHUP
#else
0
#endif
#endif
;
auto count = poll(fds, 1, -1);
if (count == -1)
unreachable();
/* Wait indefinitely until a POLLHUP occurs. */
constexpr size_t num_fds = 2;
struct pollfd fds[num_fds] = {
{
.fd = fd,
.events = hangup_events,
},
{
.fd = notifyPipe.readSide.get(),
.events = hangup_events,
},
};
auto count = poll(fds, num_fds, -1);
if (count == -1) {
if (errno == EINTR || errno == EAGAIN)
continue;
throw SysError("failed to poll() in MonitorFdHup");
}
/* This shouldn't happen, but can on macOS due to a bug.
See rdar://37550628.
@@ -50,25 +89,42 @@ public:
coordination with the main thread if spinning proves
too harmful.
*/
if (count == 0) continue;
if (count == 0)
continue;
if (fds[0].revents & POLLHUP) {
unix::triggerInterrupt();
break;
}
/* This will only happen on macOS. We sleep a bit to
avoid waking up too often if the client is sending
input. */
sleep(1);
if (fds[1].revents & POLLHUP) {
break;
}
// On macOS, (jade thinks that) it is possible (although not
// observed on macOS 14.5) that in some limited cases on buggy
// kernel versions, all the non-POLLHUP events for the socket
// get delivered.
//
// We could sleep to avoid pointlessly spinning a thread on
// those, but this opens up a different problem, which is that
// if do sleep, it will be longer before the daemon fork for a
// client exits. Imagine a sequential shell script, running Nix
// commands, each of which talk to the daemon. If the previous
// command registered a temp root, exits, and then the next
// command issues a delete request before the temp root is
// cleaned up, that delete request might fail.
//
// Not sleeping doesn't actually fix the race condition --- we
// would need to block on the old connections' tempt roots being
// cleaned up in in the new connection --- but it does make it
// much less likely.
}
});
};
~MonitorFdHup()
{
pthread_cancel(thread.native_handle());
notifyPipe.writeSide.close();
thread.join();
}
};
}

View File

@@ -306,15 +306,7 @@ void runProgram2(const RunOptions & options)
// case), so we can't use it if we alter the environment
processOptions.allowVfork = !options.environment;
std::optional<Finally<std::function<void()>>> resumeLoggerDefer;
if (options.isInteractive) {
logger->pause();
resumeLoggerDefer.emplace(
[]() {
logger->resume();
}
);
}
auto suspension = logger->suspendIf(options.isInteractive);
/* Fork. */
Pid pid = startProcess([&] {

View File

@@ -312,11 +312,7 @@ void runProgram2(const RunOptions & options)
// TODO: Implement shebang / program interpreter lookup on Windows
auto interpreter = getProgramInterpreter(realProgram);
std::optional<Finally<std::function<void()>>> resumeLoggerDefer;
if (options.isInteractive) {
logger->pause();
resumeLoggerDefer.emplace([]() { logger->resume(); });
}
auto suspension = logger->suspendIf(options.isInteractive);
Pid pid = spawnProcess(interpreter.has_value() ? *interpreter : realProgram, options, out, in);

View File

@@ -55,7 +55,7 @@ struct CmdBuild : InstallablesCommand, MixDryRun, MixJSON, MixProfile
.description = "Use *path* as prefix for the symlinks to the build results. It defaults to `result`.",
.labels = {"path"},
.handler = {&outLink},
.completer = completePath
.completer = completePath,
});
addFlag({

View File

@@ -24,7 +24,7 @@ struct CmdBundle : InstallableValueCommand
.handler = {&bundler},
.completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) {
completeFlakeRef(completions, getStore(), prefix);
}}
}},
});
addFlag({
@@ -33,7 +33,7 @@ struct CmdBundle : InstallableValueCommand
.description = "Override the name of the symlink to the build result. It defaults to the base name of the app.",
.labels = {"path"},
.handler = {&outLink},
.completer = completePath
.completer = completePath,
});
}

View File

@@ -21,7 +21,7 @@ struct CmdCopy : virtual CopyCommand, virtual BuiltPathsCommand, MixProfile
.description = "Create symlinks prefixed with *path* to the top-level store paths fetched from the source store.",
.labels = {"path"},
.handler = {&outLink},
.completer = completePath
.completer = completePath,
});
addFlag({

67
src/nix/crash-handler.cc Normal file
View File

@@ -0,0 +1,67 @@
#include "crash-handler.hh"
#include "fmt.hh"
#include "logging.hh"
#include <boost/core/demangle.hpp>
#include <exception>
#include <sstream>
// Darwin and FreeBSD stdenv do not define _GNU_SOURCE but do have _Unwind_Backtrace.
#if __APPLE__ || __FreeBSD__
# define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED
#endif
#include <boost/stacktrace/stacktrace.hpp>
#ifndef _WIN32
# include <syslog.h>
#endif
namespace nix {
namespace {
void logFatal(std::string const & s)
{
writeToStderr(s + "\n");
// std::string for guaranteed null termination
#ifndef _WIN32
syslog(LOG_CRIT, "%s", s.c_str());
#endif
}
void onTerminate()
{
logFatal(
"Nix crashed. This is a bug. Please report this at https://github.com/NixOS/nix/issues with the following information included:\n");
try {
std::exception_ptr eptr = std::current_exception();
if (eptr) {
std::rethrow_exception(eptr);
} else {
logFatal("std::terminate() called without exception");
}
} catch (const std::exception & ex) {
logFatal(fmt("Exception: %s: %s", boost::core::demangle(typeid(ex).name()), ex.what()));
} catch (...) {
logFatal("Unknown exception!");
}
logFatal("Stack trace:");
std::stringstream ss;
ss << boost::stacktrace::stacktrace();
logFatal(ss.str());
std::abort();
}
}
void registerCrashHandler()
{
// DO NOT use this for signals. Boost stacktrace is very much not
// async-signal-safe, and in a world with ASLR, addr2line is pointless.
//
// If you want signals, set up a minidump system and do it out-of-process.
std::set_terminate(onTerminate);
}
}

11
src/nix/crash-handler.hh Normal file
View File

@@ -0,0 +1,11 @@
#pragma once
/// @file Crash handler for Nix that prints back traces (hopefully in instances where it is not just going to crash the
/// process itself).
namespace nix {
/** Registers the Nix crash handler for std::terminate (currently; will support more crashes later). See also
* detectStackOverflow(). */
void registerCrashHandler();
}

Some files were not shown because too many files have changed in this diff Show More