Compare commits

..
35 Commits
Author SHA1 Message Date
Robert Hensing fd9ad915f6 WIP: Add nix repl :probe
For checking laziness (to a degree)
2025-03-09 15:40:17 +01:00
Robert Hensing a047dec120 Merge pull request #12620 from nix-windows/c-api/leaks
c-api: fix a few memory leaks
2025-03-08 22:06:59 +01:00
John Ericson fb4d55c227 Merge pull request #12619 from nix-windows/tests/fix-rapidcheck-arbitraries
rapidcheck: change to working arbitrary instances
2025-03-08 08:42:12 -08:00
Brian McKenna 79b019ec4f c-api: fix a few memory leaks 2025-03-08 20:23:07 +11:00
Brian McKenna c58202c6f9 DerivedPathTest: disable prop_legacy_round_rip until fixed 2025-03-08 19:51:25 +11:00
Brian McKenna c82ef825d4 coerceToSingleDerivedPathUnchecked: pass through experimental features
This fixes a few of the property tests, now that the property tests
are actually generating arbitrary data - some of that data now
requiring experimental features to function properly.
2025-03-08 19:14:58 +11:00
Brian McKenna 9a04f1e732 rapidcheck: change to working arbitrary instances
Here we're switching to combinators instead of dereference operator.
It turns out the dereference operator was being executed upon test
setup, meaning that we were only using a only single value for each of
the executions of the property tests! Really not good.

And on Windows, we instead get:

    operator* is not allowed in this context

https://github.com/emil-e/rapidcheck/blob/ff6af6fc683159deb51c543b065eba14dfcf329b/src/gen/detail/GenerationHandler.cpp#L16C31-L16C71

Now a few of the property tests fail, because we're generating cases
which haven't been exercised before.
2025-03-08 19:08:29 +11:00
Eelco Dolstra 47e23811ff Merge pull request #12613 from Mic92/minor-cleanups
Fix double quoting in some error messages
2025-03-07 18:38:48 +01:00
Jörg Thalheim 3b1e23af09 libstore/remote-store: avoid old-style casting for maxConnections
Type-checking works better this way as (type) style casting is too
permissive.
2025-03-07 04:00:26 +01:00
Jörg Thalheim 3b0b2fd8d6 libflake: fix double quoting when updating flakes 2025-03-07 04:00:24 +01:00
Jörg Thalheim 559a2d1bc7 libfetchers/git: fix double quoting in error message 2025-03-07 04:00:22 +01:00
Robert Hensing 2c1447b7f2 Merge pull request #12604 from NixOS/issue-12599
Fix chopped up repl output
2025-03-04 20:09:16 +01:00
Robert Hensing 1e1c587073 repl: Fix :print corruption
See preceding commits.
2025-03-04 19:48:22 +01:00
Robert Hensing 30694b5d8a refactor: RAII logger suspension 2025-03-04 19:48:22 +01:00
Robert Hensing 880489051a 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.
2025-03-04 19:48:22 +01:00
Robert Hensing 49d8ee5359 progress-bar: Make pause/resume nestable 2025-03-04 19:48:22 +01:00
Robert Hensing a5cf291dde Merge pull request #12600 from roberth/packaging-typo-preConfigure
packaging: Typo in setVersionLayer / preConfigure
2025-03-04 17:44:47 +01:00
Robert Hensing dcaea8cb1c 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
2025-03-04 17:22:24 +01:00
John Ericson 24463dd025 Merge pull request #11672 from fricklerhandwerk/at-pattern-default
doc: note that @-pattern is accessible in default values
2025-03-04 00:57:17 -05:00
Valentin GagarinandRobert Hensing 9c3dd34cfe doc: note that function bindings are accessible in default values
Co-authored-by: Robert Hensing <roberth@users.noreply.github.com>
2025-03-04 00:44:46 -05:00
Robert Hensing efbd4c1ebb Merge pull request #12442 from NixOS/store-derivation-options
Expand manual on derivation outputs
2025-03-03 23:11:51 +01:00
Robert Hensing 1e00d14c29 manual: Edit 2025-03-03 19:09:24 +01:00
Robert Hensing 89b495520d Merge pull request #12591 from obsidiansystems/temp-revert-no-dyn-drv
Once again temporarily revert "Adapt scheduler to work with dynamic derivations"
2025-03-02 21:57:56 +01:00
John Ericson f4f28cdd0e Revert "Revert "Revert "Adapt scheduler to work with dynamic derivations"""
The bug reappeared after all, and the fix introduced a different bug. I
just reverted on 2.27 first, in #12576, but upon further introspection
and discussion with @roberth, with preparing for and travelling to
Planet Nix I will not be able to fix it on `master` soon enough for a
revert to not be warranted here in the meantime also.

This reverts commit c98525235f.
2025-03-02 15:34:21 -05:00
Robert Hensing 7cfc52fd42 Merge pull request #12587 from NixOS/mergiy-2-27-backports
.mergify.yml: Add backport 2.27-maintenance entry
2025-03-02 14:08:49 +01:00
Eelco Dolstra 67aaed7f99 Merge pull request #12588 from fricklerhandwerk/exit-fricklerhandwerk
remove fricklerhandwerk from CODEOWNERS
2025-03-02 12:28:41 +01:00
Valentin Gagarin 0358007da3 remove fricklerhandwerk from CODEOWNERS
stepping aside as a Nix maintainer:
https://discourse.nixos.org/t/time-to-step-aside/61050
2025-03-02 00:06:15 +01:00
Robert Hensing 529cbea343 .mergify.yml: Add backport 2.27-maintenance entry 2025-03-01 22:54:57 +01:00
John Ericson 77f22db567 Merge pull request #12582 from roberth/nix-everything-symlink-megafarm
packaging/everything.nix: Use a multi-output derivation
2025-02-28 12:47:11 -05:00
Robert Hensing 41085295ab 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.
2025-02-28 17:40:32 +01:00
Eelco Dolstra d8a7c50495 Merge pull request #12580 from ysndr/fix/fetchers/host-in-locked-url
Add host attribute of github/gitlab flakerefs to URL serialization
2025-02-28 15:41:02 +01:00
Yannik Sander 954e9101ba Add host attribute of github/gitlab flakerefs to URL serialization
`GitArchiveInputScheme::toUrl` currently drops the `host` attribute,
creating invalid urls when locking `github:` or `gitlab:` urls pointing to alterative instances and serializing the input back to a url.

```
❯ cat flake.nix
{
  inputs.gnome-2048 = {
    url = "gitlab:GNOME/gnome-2048?host=gitlab.gnome.org";
    flake = false;
  };

  outputs = inputs: {};
}
f1xb57354q79t_jpw5_h79cw0000gq/T/tmp.MOBbzbpT35
❯ nix flake metadata
warning: creating lock file '/private/var/folders/fb/f1xb57354q79t_jpw5_h79cw0000gq/T/tmp.MOBbzbpT35/flake.lock':
• Added input 'gnome-2048':
    'gitlab:GNOME/gnome-2048/70e0e430ca4bf590990433a3abdce6b631d50e6e?narHash=sha256-bya45ug2mDSU4SMn0fSBlZCuPl9y15B12ubKeb2A58s%3D' (2025-02-21)
Resolved URL:  path:/private/var/folders/fb/f1xb57354q79t_jpw5_h79cw0000gq/T/tmp.MOBbzbpT35
Locked URL:    path:/private/var/folders/fb/f1xb57354q79t_jpw5_h79cw0000gq/T/tmp.MOBbzbpT35?lastModified=1740744684&narHash=sha256-nxUL/JiTYbZX2c1XiN/TC6aA1hf%2B1YXsUvhL7ASY2uE%3D
Path:          /nix/store/f4xczpwhdxs8gal1rika1c5bvhyd472l-source
Last modified: 2025-02-28 13:11:24
Inputs:
└───gnome-2048: gitlab:GNOME/gnome-2048/70e0e430ca4bf590990433a3abdce6b631d50e6e?narHash=sha256-bya45ug2mDSU4SMn0fSBlZCuPl9y15B12ubKeb2A58s%3D (2025-02-21 23:18:46)
```

Note the gnome-2048 input url missing the original host query.

The Url after this commit:

```
[...]
Inputs:
└───gnome-2048: gitlab:GNOME/gnome-2048/70e0e430ca4bf590990433a3abdce6b631d50e6e?host=gitlab.gnome.org&narHash=sha256-bya45ug2mDSU4SMn0fSBlZCuPl9y15B12ubKeb2A58s%3D (2025-02-21 23:18:46)
```
2025-02-28 13:14:16 +01:00
John Ericson 92c4789ec7 Merge pull request #12573 from tomberek/tomberek.update_meeting
fix: update work meeting calendar link
2025-02-27 16:37:45 -05:00
John Ericson 2aa6e0f084 Expand manual on derivation outputs
Note, this includes some text adapted from from Eelco's dissertation
2025-02-27 02:13:36 -05:00
Thomas Bereknyei 068cdfafb8 fix: update work meeting calendar link 2025-02-26 15:45:57 -05:00
41 changed files with 313 additions and 353 deletions

No files matched your search

+1 -10
View File
@@ -11,16 +11,7 @@
.github/CODEOWNERS @edolstra
# Documentation of built-in functions
src/libexpr/primops.cc @roberth @fricklerhandwerk
# Documentation of settings
src/libexpr/eval-settings.hh @fricklerhandwerk
src/libstore/globals.hh @fricklerhandwerk
# Documentation
doc/manual @fricklerhandwerk
maintainers/*.md @fricklerhandwerk
src/**/*.md @fricklerhandwerk
src/libexpr/primops.cc @roberth
# Libstore layer
/src/libstore @ericson2314
+11
View File
@@ -117,3 +117,14 @@ pull_request_rules:
labels:
- automatic backport
- merge-queue
- name: backport patches to 2.27
conditions:
- label=backport 2.27-maintenance
actions:
backport:
branches:
- "2.27-maintenance"
labels:
- automatic backport
- merge-queue
+40 -1
View File
@@ -443,7 +443,7 @@ three kinds of patterns:
This works on any set that contains at least the three named
attributes.
It is possible to provide *default values* for attributes, in
- It is possible to provide *default values* for attributes, in
which case they are allowed to be missing. A default value is
specified by writing `name ? e`, where *e* is an arbitrary
expression. For example,
@@ -503,6 +503,45 @@ three kinds of patterns:
> [ 23 {} ]
> ```
- All bindings introduced by the function are in scope in the entire function expression; not just in the body.
It can therefore be used in default values.
> **Example**
>
> A parameter (`x`), is used in the default value for another parameter (`y`):
>
> ```nix
> let
> f = { x, y ? [x] }: { inherit y; };
> in
> f { x = 3; }
> ```
>
> This evaluates to:
>
> ```nix
> {
> y = [ 3 ];
> }
> ```
> **Example**
>
> The binding of an `@` pattern, `args`, is used in the default value for a parameter, `x`:
>
> ```nix
> let
> f = args@{ x ? args.a, ... }: x;
> in
> f { a = 1; }
> ```
>
> This evaluates to:
>
> ```nix
> 1
> ```
Note that functions do not have names. If you want to give them a name,
you can bind them to an attribute, e.g.,
+1 -1
View File
@@ -32,7 +32,7 @@
let
inherit (nixpkgs) lib;
officialRelease = true;
officialRelease = false;
linux32BitSystems = [ "i686-linux" ];
linux64BitSystems = [
+2 -2
View File
@@ -37,7 +37,7 @@ The team is on Github as [@NixOS/nix-team](https://github.com/orgs/NixOS/teams/n
The team meets twice a week (times are denoted in the [Europe/Amsterdam](https://en.m.wikipedia.org/wiki/Time_in_the_Netherlands) time zone):
- Discussion meeting: [Wednesday 21:00-22:00 Europe/Amsterdam](https://www.google.com/calendar/event?eid=ZG5rZzNyajRjajducGV2NGY5aGkzYWIwdnJfMjAyNDA1MDhUMTkwMDAwWiBiOW81MmZvYnFqYWs4b3E4bGZraGczdDBxZ0Bn)
- Discussion meeting: Wednesday 21:00-22:00 Europe/Amsterdam see [calendar](https://calendar.google.com/calendar/u/0/embed?src=b9o52fobqjak8oq8lfkhg3t0qg@group.calendar.google.com).
1. Triage issues and pull requests from the [No Status](#no-status) column (30 min)
2. Discuss issues and pull requests from the [To discuss](#to-discuss) column (30 min).
@@ -46,7 +46,7 @@ The team meets twice a week (times are denoted in the [Europe/Amsterdam](https:/
- mark it as draft if it is blocked on the contributor
- escalate it back to the team by moving it to To discuss, and leaving a comment as to why the issue needs to be discussed again.
- Work meeting: [Mondays 14:00-16:00 Europe/Amsterdam](https://www.google.com/calendar/event?eid=Ym52NDdzYnRic2NzcDcybjZiNDhpNzhpa3NfMjAyNDA1MTNUMTIwMDAwWiBiOW81MmZvYnFqYWs4b3E4bGZraGczdDBxZ0Bn)
- Work meeting: Mondays 14:00-16:00 Europe/Amsterdam see [calendar](https://calendar.google.com/calendar/u/0/embed?src=b9o52fobqjak8oq8lfkhg3t0qg@group.calendar.google.com).
1. Code review on pull requests from [In review](#in-review).
2. Other chores and tasks.
+1
View File
@@ -127,6 +127,7 @@
''^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$''
+66 -4
View File
@@ -3,6 +3,7 @@
#include <cstring>
#include "error.hh"
#include "eval-error.hh"
#include "repl-interacter.hh"
#include "repl.hh"
@@ -140,13 +141,16 @@ static std::ostream & showDebugTrace(std::ostream & out, const PosTable & positi
out << ANSI_RED "error: " << ANSI_NORMAL;
out << dt.hint.str() << "\n";
auto pos = dt.getPos(positions);
// prefer direct pos, but if noPos then try the expr.
auto pos = dt.pos
? dt.pos
: positions[dt.expr.getPos() ? dt.expr.getPos() : noPos];
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";
}
}
@@ -341,6 +345,58 @@ void NixRepl::loadDebugTraceEnv(DebugTrace & dt)
}
}
static Value * lazyProbe(Expr * e, EvalState &state, Env &env)
{
if (auto select = dynamic_cast<ExprSelect *>(e)) {
if (select->attrPath.size() != 1) {
throw Unsupported(":probe: Nested attribute selection not supported yet. Workaround: use parentheses?");
}
if (select->def) {
// This seems like nonsensical input, and we only really support simple attribute paths
throw Unsupported(":probe: %1% keyword is not supported.", "or");
}
auto attr = select->attrPath[0];
if (!attr.symbol) {
throw Unsupported(":probe: Computed attribute selection not supported yet.");
}
auto name = state.symbols[attr.symbol];
auto v = lazyProbe(select->e, state, env);
if (v->type() != nAttrs) {
state.error<TypeError>("can't look up '%1%', expecting the left hand side to be an attribute set, but it is %2%", name, v->type()).atPos(select->e->getPos()).debugThrow();
}
auto it = v->attrs()->find(attr.symbol);
if (it == v->attrs()->end()) {
state.error<EvalError>("attribute '%1%' missing", state.symbols[attr.symbol]).atPos(select->e->getPos()).debugThrow();
}
return it->value;
}
if (auto ref = dynamic_cast<ExprVar *>(e)) {
auto name = state.symbols[ref->name];
// TODO: subtly different intent, so factor out common logic from maybeThunk instead
Value * v = ref->maybeThunk(state, env);
if (!v) {
state.error<EvalError>("Variable '%1%' not found in scope", name).atPos(ref->getPos()).debugThrow();
}
return v;
}
state.error<EvalError>("'%s' is not an expression I can probe. Use variables and attribute selection").atPos(e->getPos()).debugThrow();
}
static void printLazyProbe(Expr * e, EvalState &state, Env &env)
{
Value * v = lazyProbe(e, state, env);
auto suspension = logger->suspend();
std::cout << (v->type() == nThunk ? ANSI_GREEN : ANSI_BLUE);
std::cout << v->type() << std::endl;
std::cout << ANSI_NORMAL;
}
ProcessLineResult NixRepl::processLine(std::string line)
{
line = trim(line);
@@ -377,6 +433,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
<< " :lf, :load-flake <ref> Load Nix flake and add it to scope\n"
<< " :p, :print <expr> Evaluate and print expression recursively\n"
<< " Strings are printed directly, without escaping.\n"
<< " :probe <select> Do not evaluate, but report type or thunk.\n"
<< " :q, :quit Exit nix-repl\n"
<< " :r, :reload Reload all files\n"
<< " :sh <expr> Build dependencies of derivation, then start\n"
@@ -593,6 +650,11 @@ ProcessLineResult NixRepl::processLine(std::string line)
std::cout << std::endl;
}
else if (command == ":probe") {
auto expr = parseString(arg);
printLazyProbe(expr, *state, *env);
}
else if (command == ":q" || command == ":quit") {
state->debugStop = false;
return ProcessLineResult::Quit;
+3 -1
View File
@@ -199,7 +199,9 @@ EvalState * nix_state_create(nix_c_context * context, const char ** lookupPath_c
!= NIX_OK)
return nullptr;
return nix_eval_state_build(context, builder);
auto *state = nix_eval_state_build(context, builder);
nix_eval_state_builder_free(builder);
return state;
}
void nix_state_free(EvalState * state)
+21 -12
View File
@@ -8,23 +8,32 @@ using namespace nix;
Gen<NixStringContextElem::DrvDeep> Arbitrary<NixStringContextElem::DrvDeep>::arbitrary()
{
return gen::just(NixStringContextElem::DrvDeep {
.drvPath = *gen::arbitrary<StorePath>(),
return gen::map(gen::arbitrary<StorePath>(), [](StorePath drvPath) {
return NixStringContextElem::DrvDeep{
.drvPath = drvPath,
};
});
}
Gen<NixStringContextElem> Arbitrary<NixStringContextElem>::arbitrary()
{
switch (*gen::inRange<uint8_t>(0, std::variant_size_v<NixStringContextElem::Raw>)) {
case 0:
return gen::just<NixStringContextElem>(*gen::arbitrary<NixStringContextElem::Opaque>());
case 1:
return gen::just<NixStringContextElem>(*gen::arbitrary<NixStringContextElem::DrvDeep>());
case 2:
return gen::just<NixStringContextElem>(*gen::arbitrary<NixStringContextElem::Built>());
default:
assert(false);
}
return gen::mapcat(
gen::inRange<uint8_t>(0, std::variant_size_v<NixStringContextElem::Raw>),
[](uint8_t n) -> Gen<NixStringContextElem> {
switch (n) {
case 0:
return gen::map(
gen::arbitrary<NixStringContextElem::Opaque>(), [](NixStringContextElem a) { return a; });
case 1:
return gen::map(
gen::arbitrary<NixStringContextElem::DrvDeep>(), [](NixStringContextElem a) { return a; });
case 2:
return gen::map(
gen::arbitrary<NixStringContextElem::Built>(), [](NixStringContextElem a) { return a; });
default:
assert(false);
}
});
}
}
+7 -4
View File
@@ -44,11 +44,11 @@ RC_GTEST_FIXTURE_PROP(
* to worry about race conditions if the tests run concurrently.
*/
ExperimentalFeatureSettings mockXpSettings;
mockXpSettings.set("experimental-features", "ca-derivations");
mockXpSettings.set("experimental-features", "ca-derivations dynamic-derivations");
auto * v = state.allocValue();
state.mkOutputString(*v, b, std::nullopt, mockXpSettings);
auto [d, _] = state.coerceToSingleDerivedPathUnchecked(noPos, *v, "");
auto [d, _] = state.coerceToSingleDerivedPathUnchecked(noPos, *v, "", mockXpSettings);
RC_ASSERT(SingleDerivedPath { b } == d);
}
@@ -57,9 +57,12 @@ RC_GTEST_FIXTURE_PROP(
prop_derived_path_built_out_path_round_trip,
(const SingleDerivedPath::Built & b, const StorePath & outPath))
{
ExperimentalFeatureSettings mockXpSettings;
mockXpSettings.set("experimental-features", "dynamic-derivations");
auto * v = state.allocValue();
state.mkOutputString(*v, b, outPath);
auto [d, _] = state.coerceToSingleDerivedPathUnchecked(noPos, *v, "");
state.mkOutputString(*v, b, outPath, mockXpSettings);
auto [d, _] = state.coerceToSingleDerivedPathUnchecked(noPos, *v, "", mockXpSettings);
RC_ASSERT(SingleDerivedPath { b } == d);
}
+3
View File
@@ -63,6 +63,9 @@ TEST_F(nix_api_expr_test, nix_expr_eval_external)
std::string string_value;
nix_get_string(nullptr, valueResult, OBSERVE_STRING(string_value));
ASSERT_STREQ("nix-external<MyExternalValueDesc( 42 )>", string_value.c_str());
nix_state_free(stateResult);
nix_state_free(stateFn);
}
}
+3 -1
View File
@@ -124,7 +124,9 @@ RC_GTEST_PROP(
prop_round_rip,
(const NixStringContextElem & o))
{
RC_ASSERT(o == NixStringContextElem::parse(o.to_string()));
ExperimentalFeatureSettings xpSettings;
xpSettings.set("experimental-features", "dynamic-derivations");
RC_ASSERT(o == NixStringContextElem::parse(o.to_string(), xpSettings));
}
#endif
+1 -1
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 = expr.getPos(),
.pos = error.state.positions[expr.getPos()],
.expr = expr,
.env = env,
.hint = HintFmt("Fake frame for debugging purposes"),
+1 -1
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<EvalBaseError>("stack overflow; max-call-depth exceeded").atPos(pos).debugThrow();
error<EvalError>("stack overflow; max-call-depth exceeded").atPos(pos).debugThrow();
return CallDepth(callDepth);
};
+26 -30
View File
@@ -771,26 +771,18 @@ void EvalState::runDebugRepl(const Error * error, const Env & env, const Expr &
if (!debugRepl || inDebugger)
return;
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();
}(),
auto dts =
error && expr.getPos()
? std::make_unique<DebugTraceStacker>(
*this,
DebugTrace {
.pos = error->info().pos ? error->info().pos : positions[expr.getPos()],
.expr = expr,
.env = env,
.hint = error->info().msg,
.isError = true};
return std::make_unique<DebugTraceStacker>(*this, std::move(trace));
}
return nullptr;
}();
.isError = true
})
: nullptr;
if (error)
{
@@ -835,7 +827,7 @@ static std::unique_ptr<DebugTraceStacker> makeDebugTraceStacker(
EvalState & state,
Expr & expr,
Env & env,
std::variant<Pos, PosIdx> pos,
std::shared_ptr<Pos> && pos,
const Args & ... formatArgs)
{
return std::make_unique<DebugTraceStacker>(state,
@@ -1112,7 +1104,7 @@ void EvalState::evalFile(const SourcePath & path, Value & v, bool mustBeTrivial)
*this,
*e,
this->baseEnv,
e->getPos(),
e->getPos() ? std::make_shared<Pos>(positions[e->getPos()]) : nullptr,
"while evaluating the file '%1%':", resolvedPath.to_string())
: nullptr;
@@ -1338,7 +1330,9 @@ void ExprLet::eval(EvalState & state, Env & env, Value & v)
state,
*this,
env2,
getPos(),
getPos()
? std::make_shared<Pos>(state.positions[getPos()])
: nullptr,
"while evaluating a '%1%' expression",
"let"
)
@@ -1407,7 +1401,7 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
state,
*this,
env,
getPos(),
state.positions[getPos()],
"while evaluating the attribute '%1%'",
showAttrPath(state, env, attrPath))
: nullptr;
@@ -1608,7 +1602,7 @@ void EvalState::callFunction(Value & fun, std::span<Value *> args, Value & vRes,
try {
auto dts = debugRepl
? makeDebugTraceStacker(
*this, *lambda.body, env2, lambda.pos,
*this, *lambda.body, env2, positions[lambda.pos],
"while calling %s",
lambda.name
? concatStrings("'", symbols[lambda.name], "'")
@@ -1743,7 +1737,9 @@ void ExprCall::eval(EvalState & state, Env & env, Value & v)
state,
*this,
env,
getPos(),
getPos()
? std::make_shared<Pos>(state.positions[getPos()])
: nullptr,
"while calling a function"
)
: nullptr;
@@ -2127,7 +2123,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, i.pos,
? makeDebugTraceStacker(*this, *i.value->payload.thunk.expr, *i.value->payload.thunk.env, positions[i.pos],
"while evaluating the attribute '%1%'", symbols[i.name])
: nullptr;
@@ -2249,18 +2245,18 @@ std::string_view EvalState::forceString(Value & v, const PosIdx pos, std::string
}
void copyContext(const Value & v, NixStringContext & context)
void copyContext(const Value & v, NixStringContext & context, const ExperimentalFeatureSettings & xpSettings)
{
if (v.payload.string.context)
for (const char * * p = v.payload.string.context; *p; ++p)
context.insert(NixStringContextElem::parse(*p));
context.insert(NixStringContextElem::parse(*p, xpSettings));
}
std::string_view EvalState::forceString(Value & v, NixStringContext & context, const PosIdx pos, std::string_view errorCtx)
std::string_view EvalState::forceString(Value & v, NixStringContext & context, const PosIdx pos, std::string_view errorCtx, const ExperimentalFeatureSettings & xpSettings)
{
auto s = forceString(v, pos, errorCtx);
copyContext(v, context);
copyContext(v, context, xpSettings);
return s;
}
@@ -2466,10 +2462,10 @@ StorePath EvalState::coerceToStorePath(const PosIdx pos, Value & v, NixStringCon
}
std::pair<SingleDerivedPath, std::string_view> EvalState::coerceToSingleDerivedPathUnchecked(const PosIdx pos, Value & v, std::string_view errorCtx)
std::pair<SingleDerivedPath, std::string_view> EvalState::coerceToSingleDerivedPathUnchecked(const PosIdx pos, Value & v, std::string_view errorCtx, const ExperimentalFeatureSettings & xpSettings)
{
NixStringContext context;
auto s = forceString(v, context, pos, errorCtx);
auto s = forceString(v, context, pos, errorCtx, xpSettings);
auto csize = context.size();
if (csize != 1)
error<EvalError>(
+4 -21
View File
@@ -159,7 +159,7 @@ void printEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env &
std::unique_ptr<ValMap> mapStaticEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env);
void copyContext(const Value & v, NixStringContext & context);
void copyContext(const Value & v, NixStringContext & context, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings);
std::string printValue(EvalState & state, Value & v);
@@ -171,28 +171,11 @@ struct RegexCache;
std::shared_ptr<RegexCache> makeRegexCache();
struct DebugTrace {
/* 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;
std::shared_ptr<Pos> 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>
@@ -527,7 +510,7 @@ public:
*/
void forceFunction(Value & v, const PosIdx pos, std::string_view errorCtx);
std::string_view forceString(Value & v, const PosIdx pos, std::string_view errorCtx);
std::string_view forceString(Value & v, NixStringContext & context, const PosIdx pos, std::string_view errorCtx);
std::string_view forceString(Value & v, NixStringContext & context, const PosIdx pos, std::string_view errorCtx, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings);
std::string_view forceStringNoCtx(Value & v, const PosIdx pos, std::string_view errorCtx);
template<typename... Args>
@@ -579,7 +562,7 @@ public:
/**
* Part of `coerceToSingleDerivedPath()` without any store IO which is exposed for unit testing only.
*/
std::pair<SingleDerivedPath, std::string_view> coerceToSingleDerivedPathUnchecked(const PosIdx pos, Value & v, std::string_view errorCtx);
std::pair<SingleDerivedPath, std::string_view> coerceToSingleDerivedPathUnchecked(const PosIdx pos, Value & v, std::string_view errorCtx, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings);
/**
* Coerce to `SingleDerivedPath`.
+2
View File
@@ -172,6 +172,8 @@ 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',
+35
View File
@@ -601,6 +601,41 @@ 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
@@ -1,5 +1,4 @@
#pragma once
///@file
#include <cinttypes>
#include <functional>
@@ -1,5 +1,4 @@
#pragma once
///@file
#include <cstdint>
#include <vector>
@@ -19,12 +18,9 @@ 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;
@@ -76,17 +72,6 @@ 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
+1 -1
View File
@@ -637,7 +637,7 @@ struct GitInputScheme : InputScheme
if (!input.getRev())
setWriteTime(localRefFile, now, now);
} catch (Error & e) {
warn("could not update mtime for file '%s': %s", localRefFile, e.info().msg);
warn("could not update mtime for file %s: %s", localRefFile, e.info().msg);
}
if (!originalRef && !storeCachedHead(repoUrl.to_string(), ref))
warn("could not update cached head '%s' for '%s'", ref, repoInfo.locationToArg());
+3
View File
@@ -149,6 +149,9 @@ struct GitArchiveInputScheme : InputScheme
};
if (auto narHash = input.getNarHash())
url.query.insert_or_assign("narHash", narHash->to_string(HashFormat::SRI, true));
auto host = maybeGetStrAttr(input.attrs, "host");
if (host)
url.query.insert_or_assign("host", *host);
return url;
}
+1 -1
View File
@@ -125,7 +125,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());
+3
View File
@@ -43,6 +43,9 @@ TEST_F(nix_api_store_test, nix_api_init_global_getFlake_exists)
ASSERT_NE(nullptr, value);
nix_err err = nix_expr_eval_from_string(ctx, state, "builtins.getFlake", ".", value);
nix_state_free(state);
assert_ctx_ok();
ASSERT_EQ(NIX_OK, err);
ASSERT_EQ(NIX_TYPE_FUNCTION, nix_get_type(ctx, value));
+3 -3
View File
@@ -863,11 +863,11 @@ LockedFlake lockFlake(
auto s = chomp(diff);
if (lockFileExists) {
if (s.empty())
warn("updating lock file '%s'", outputLockFilePath);
warn("updating lock file %s", outputLockFilePath);
else
warn("updating lock file '%s':\n%s", outputLockFilePath, s);
warn("updating lock file %s:\n%s", outputLockFilePath, s);
} else
warn("creating lock file '%s': \n%s", outputLockFilePath, s);
warn("creating lock file %s: \n%s", outputLockFilePath, s);
std::optional<std::string> commitMessage = std::nullopt;
+38 -24
View File
@@ -9,49 +9,63 @@ using namespace nix;
Gen<SingleDerivedPath::Opaque> Arbitrary<SingleDerivedPath::Opaque>::arbitrary()
{
return gen::just(DerivedPath::Opaque {
.path = *gen::arbitrary<StorePath>(),
return gen::map(gen::arbitrary<StorePath>(), [](StorePath path) {
return DerivedPath::Opaque{
.path = path,
};
});
}
Gen<SingleDerivedPath::Built> Arbitrary<SingleDerivedPath::Built>::arbitrary()
{
return gen::just(SingleDerivedPath::Built {
.drvPath = make_ref<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath>()),
.output = (*gen::arbitrary<StorePathName>()).name,
return gen::mapcat(gen::arbitrary<SingleDerivedPath>(), [](SingleDerivedPath drvPath) {
return gen::map(gen::arbitrary<StorePathName>(), [drvPath](StorePathName outputPath) {
return SingleDerivedPath::Built{
.drvPath = make_ref<SingleDerivedPath>(drvPath),
.output = outputPath.name,
};
});
});
}
Gen<DerivedPath::Built> Arbitrary<DerivedPath::Built>::arbitrary()
{
return gen::just(DerivedPath::Built {
.drvPath = make_ref<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath>()),
.outputs = *gen::arbitrary<OutputsSpec>(),
return gen::mapcat(gen::arbitrary<SingleDerivedPath>(), [](SingleDerivedPath drvPath) {
return gen::map(gen::arbitrary<OutputsSpec>(), [drvPath](OutputsSpec outputs) {
return DerivedPath::Built{
.drvPath = make_ref<SingleDerivedPath>(drvPath),
.outputs = outputs,
};
});
});
}
Gen<SingleDerivedPath> Arbitrary<SingleDerivedPath>::arbitrary()
{
switch (*gen::inRange<uint8_t>(0, std::variant_size_v<SingleDerivedPath::Raw>)) {
case 0:
return gen::just<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath::Opaque>());
case 1:
return gen::just<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath::Built>());
default:
assert(false);
}
return gen::mapcat(gen::inRange<uint8_t>(0, std::variant_size_v<SingleDerivedPath::Raw>), [](uint8_t n) {
switch (n) {
case 0:
return gen::map(gen::arbitrary<SingleDerivedPath::Opaque>(), [](SingleDerivedPath a) { return a; });
case 1:
return gen::map(gen::arbitrary<SingleDerivedPath::Built>(), [](SingleDerivedPath a) { return a; });
default:
assert(false);
}
});
}
Gen<DerivedPath> Arbitrary<DerivedPath>::arbitrary()
{
switch (*gen::inRange<uint8_t>(0, std::variant_size_v<DerivedPath::Raw>)) {
case 0:
return gen::just<DerivedPath>(*gen::arbitrary<DerivedPath::Opaque>());
case 1:
return gen::just<DerivedPath>(*gen::arbitrary<DerivedPath::Built>());
default:
assert(false);
}
return gen::mapcat(gen::inRange<uint8_t>(0, std::variant_size_v<DerivedPath::Raw>), [](uint8_t n) {
switch (n) {
case 0:
return gen::map(gen::arbitrary<DerivedPath::Opaque>(), [](DerivedPath a) { return a; });
case 1:
return gen::map(gen::arbitrary<DerivedPath::Built>(), [](DerivedPath a) { return a; });
default:
assert(false);
}
});
}
}
+13 -11
View File
@@ -7,18 +7,20 @@ using namespace nix;
Gen<OutputsSpec> Arbitrary<OutputsSpec>::arbitrary()
{
switch (*gen::inRange<uint8_t>(0, std::variant_size_v<OutputsSpec::Raw>)) {
case 0:
return gen::just((OutputsSpec) OutputsSpec::All { });
case 1:
return gen::just((OutputsSpec) OutputsSpec::Names {
*gen::nonEmpty(gen::container<StringSet>(gen::map(
gen::arbitrary<StorePathName>(),
[](StorePathName n) { return n.name; }))),
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);
}
});
default:
assert(false);
}
}
}
+12 -3
View File
@@ -79,12 +79,19 @@ TEST_F(DerivedPathTest, built_built_xp) {
#ifndef COVERAGE
/* TODO: Disabled due to the following error:
path '00000000000000000000000000000000-0^0' is not a valid store path:
name '0^0' contains illegal character '^'
*/
RC_GTEST_FIXTURE_PROP(
DerivedPathTest,
prop_legacy_round_rip,
DISABLED_prop_legacy_round_rip,
(const DerivedPath & o))
{
RC_ASSERT(o == DerivedPath::parseLegacy(*store, o.to_string_legacy(*store)));
ExperimentalFeatureSettings xpSettings;
xpSettings.set("experimental-features", "dynamic-derivations");
RC_ASSERT(o == DerivedPath::parseLegacy(*store, o.to_string_legacy(*store), xpSettings));
}
RC_GTEST_FIXTURE_PROP(
@@ -92,7 +99,9 @@ RC_GTEST_FIXTURE_PROP(
prop_round_rip,
(const DerivedPath & o))
{
RC_ASSERT(o == DerivedPath::parse(*store, o.to_string(*store)));
ExperimentalFeatureSettings xpSettings;
xpSettings.set("experimental-features", "dynamic-derivations");
RC_ASSERT(o == DerivedPath::parse(*store, o.to_string(*store), xpSettings));
}
#endif
+1 -1
View File
@@ -28,7 +28,7 @@ RemoteStore::RemoteStore(const Params & params)
: RemoteStoreConfig(params)
, Store(params)
, connections(make_ref<Pool<Connection>>(
std::max(1, (int) maxConnections),
std::max(1, maxConnections.get()),
[this]() {
auto conn = openConnectionWrapper();
try {
@@ -2144,18 +2144,7 @@ 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",
-8
View File
@@ -50,14 +50,6 @@ 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,
-3
View File
@@ -155,7 +155,6 @@ sources = files(
'memory-source-accessor.cc',
'mounted-source-accessor.cc',
'position.cc',
'pos-table.cc',
'posix-source-accessor.cc',
'references.cc',
'serialise.cc',
@@ -226,8 +225,6 @@ 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',
-37
View File
@@ -1,37 +0,0 @@
#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;
}
}
-7
View File
@@ -66,13 +66,6 @@ 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) {
+3 -2
View File
@@ -50,7 +50,6 @@ 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;
/**
@@ -70,7 +69,9 @@ struct Pos
/**
* Get the SourcePath, if the source was loaded from a file.
*/
std::optional<SourcePath> getSourcePath() const;
std::optional<SourcePath> getSourcePath() const {
return *std::get_if<SourcePath>(&origin);
}
struct LinesIterator {
using difference_type = size_t;
+4 -40
View File
@@ -5,27 +5,9 @@
#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;
@@ -35,18 +17,14 @@ 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) {
switch (errno) {
case EINTR: continue;
case EAGAIN:
pollFD(fd, POLLIN);
continue;
}
if (errno == EINTR) continue;
throw SysError("reading from file");
}
if (res == 0) throw EndOfFile("unexpected end-of-file");
@@ -61,15 +39,8 @@ 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) {
switch (errno) {
case EINTR: continue;
case EAGAIN:
pollFD(fd, POLLOUT);
continue;
}
if (res == -1 && errno != EINTR)
throw SysError("writing to file");
}
if (res > 0)
s.remove_prefix(res);
}
@@ -85,15 +56,8 @@ std::string readLine(int fd, bool eofOk)
// FIXME: inefficient
ssize_t rd = read(fd, &ch, 1);
if (rd == -1) {
switch (errno) {
case EINTR: continue;
case EAGAIN: {
pollFD(fd, POLLIN);
continue;
}
default:
if (errno != EINTR)
throw SysError("reading a line");
}
} else if (rd == 0) {
if (eofOk)
return s;
-67
View File
@@ -1,67 +0,0 @@
#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
View File
@@ -1,11 +0,0 @@
#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();
}
-3
View File
@@ -20,7 +20,6 @@
#include "flake/flake.hh"
#include "self-exe.hh"
#include "json-utils.hh"
#include "crash-handler.hh"
#include <sys/types.h>
#include <regex>
@@ -355,8 +354,6 @@ void mainWrapped(int argc, char * * argv)
{
savedArgv = argv;
registerCrashHandler();
/* The chroot helper needs to be run before any threads have been
started. */
#ifndef _WIN32
-1
View File
@@ -77,7 +77,6 @@ nix_sources = [config_h] + files(
'config-check.cc',
'config.cc',
'copy.cc',
'crash-handler.cc',
'derivation-add.cc',
'derivation-show.cc',
'derivation.cc',
-11
View File
@@ -22,11 +22,6 @@ cat >"$flake1Dir/flake.nix" <<EOF
echo true > \$out
'';
};
stack-depth =
let
f = x: if x == 0 then true else f (x - 1);
in
assert (f 100); self.drv;
ifd = assert (import self.drv); self.drv;
};
}
@@ -38,12 +33,6 @@ git -C "$flake1Dir" commit -m "Init"
expect 1 nix build "$flake1Dir#foo.bar" 2>&1 | grepQuiet 'error: breaks'
expect 1 nix build "$flake1Dir#foo.bar" 2>&1 | grepQuiet 'error: breaks'
# Stack overflow error must not be cached
expect 1 nix build --max-call-depth 50 "$flake1Dir#stack-depth" 2>&1 \
| grepQuiet 'error: stack overflow; max-call-depth exceeded'
# If the SO is cached, the following invocation will produce a cached failure; we expect it to succeed
nix build --no-link "$flake1Dir#stack-depth"
# Conditional error should not be cached
expect 1 nix build "$flake1Dir#ifd" --option allow-import-from-derivation false 2>&1 \
| grepQuiet 'error: cannot build .* during evaluation because the option '\''allow-import-from-derivation'\'' is disabled'