diff options
Diffstat (limited to 'src/libexpr/primops.cc')
-rw-r--r-- | src/libexpr/primops.cc | 311 |
1 files changed, 253 insertions, 58 deletions
diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 28fea276e..de8d74292 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -46,7 +46,11 @@ StringMap EvalState::realiseContext(const PathSet & context) auto [ctx, outputName] = decodeContext(*store, i); auto ctxS = store->printStorePath(ctx); if (!store->isValidPath(ctx)) - throw InvalidPathError(store->printStorePath(ctx)); + { + auto e = InvalidPathError(store->printStorePath(ctx)); + debugLastTrace(e); + throw e; + } if (!outputName.empty() && ctx.isDerivation()) { drvs.push_back({ctx, {outputName}}); } else { @@ -57,9 +61,13 @@ StringMap EvalState::realiseContext(const PathSet & context) if (drvs.empty()) return {}; if (!evalSettings.enableImportFromDerivation) - throw Error( + { + auto e = Error( "cannot build '%1%' during evaluation because the option 'allow-import-from-derivation' is disabled", store->printStorePath(drvs.begin()->drvPath)); + debugLastTrace(e); + throw e; + } /* Build/substitute the context. */ std::vector<DerivedPath> buildReqs; @@ -71,9 +79,12 @@ StringMap EvalState::realiseContext(const PathSet & context) const auto outputPaths = store->queryDerivationOutputMap(drvPath); for (auto & outputName : outputs) { auto outputPath = get(outputPaths, outputName); - if (!outputPath) - throw Error("derivation '%s' does not have an output named '%s'", - store->printStorePath(drvPath), outputName); + if (!outputPath) { + auto e = Error("derivation '%s' does not have an output named '%s'", + store->printStorePath(drvPath), outputName); + debugLastTrace(e); + throw e; + } res.insert_or_assign( downstreamPlaceholder(*store, drvPath, outputName), store->printStorePath(*outputPath) @@ -216,11 +227,11 @@ static void import(EvalState & state, const PosIdx pos, Value & vPath, Value * v Env * env = &state.allocEnv(vScope->attrs->size()); env->up = &state.baseEnv; - StaticEnv staticEnv(false, &state.staticBaseEnv, vScope->attrs->size()); + auto staticEnv = std::make_shared<StaticEnv>(false, state.staticBaseEnv.get(), vScope->attrs->size()); unsigned int displ = 0; for (auto & attr : *vScope->attrs) { - staticEnv.vars.emplace_back(attr.name, displ); + staticEnv->vars.emplace_back(attr.name, displ); env->values[displ++] = attr.value; } @@ -318,18 +329,26 @@ void prim_importNative(EvalState & state, const PosIdx pos, Value * * args, Valu std::string sym(state.forceStringNoCtx(*args[1], pos)); void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); - if (!handle) - throw EvalError("could not open '%1%': %2%", path, dlerror()); + if (!handle) { + auto e = EvalError("could not open '%1%': %2%", path, dlerror()); + state.debugLastTrace(e); + throw e; + } dlerror(); ValueInitializer func = (ValueInitializer) dlsym(handle, sym.c_str()); if(!func) { char *message = dlerror(); - if (message) - throw EvalError("could not load symbol '%1%' from '%2%': %3%", sym, path, message); - else - throw EvalError("symbol '%1%' from '%2%' resolved to NULL when a function pointer was expected", + if (message) { + auto e = EvalError("could not load symbol '%1%' from '%2%': %3%", sym, path, message); + state.debugLastTrace(e); + throw e; + } else { + auto e = EvalError("symbol '%1%' from '%2%' resolved to NULL when a function pointer was expected", sym, path); + state.debugLastTrace(e); + throw e; + } } (func)(state, v); @@ -345,10 +364,12 @@ void prim_exec(EvalState & state, const PosIdx pos, Value * * args, Value & v) auto elems = args[0]->listElems(); auto count = args[0]->listSize(); if (count == 0) { - throw EvalError({ + auto e = EvalError({ .msg = hintfmt("at least one argument to 'exec' required"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; } PathSet context; auto program = state.coerceToString(pos, *elems[0], context, false, false).toOwned(); @@ -359,11 +380,13 @@ void prim_exec(EvalState & state, const PosIdx pos, Value * * args, Value & v) try { auto _ = state.realiseContext(context); // FIXME: Handle CA derivations } catch (InvalidPathError & e) { - throw EvalError({ + auto ee = EvalError({ .msg = hintfmt("cannot execute '%1%', since path '%2%' is not valid", program, e.path), .errPos = state.positions[pos] }); + state.debugLastTrace(ee); + throw ee; } auto output = runProgram(program, true, commandArgs); @@ -546,8 +569,11 @@ struct CompareValues return v1->fpoint < v2->integer; if (v1->type() == nInt && v2->type() == nFloat) return v1->integer < v2->fpoint; - if (v1->type() != v2->type()) - throw EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2)); + if (v1->type() != v2->type()) { + auto e = EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2)); + state.debugLastTrace(e); + throw e; + } switch (v1->type()) { case nInt: return v1->integer < v2->integer; @@ -568,8 +594,11 @@ struct CompareValues return (*this)(v1->listElems()[i], v2->listElems()[i]); } } - default: - throw EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2)); + default: { + auto e = EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2)); + state.debugLastTrace(e); + throw e; + } } } }; @@ -599,10 +628,12 @@ static Bindings::iterator getAttr( auto aPos = attrSet->pos; if (!aPos) { - throw TypeError({ + auto e = TypeError({ .msg = errorMsg, .errPos = state.positions[pos], }); + state.debugLastTrace(e); + throw e; } else { auto e = TypeError({ .msg = errorMsg, @@ -612,6 +643,7 @@ static Bindings::iterator getAttr( // Adding another trace for the function name to make it clear // which call received wrong arguments. e.addTrace(state.positions[pos], hintfmt("while invoking '%s'", funcName)); + state.debugLastTrace(e); throw e; } } @@ -665,11 +697,14 @@ static void prim_genericClosure(EvalState & state, const PosIdx pos, Value * * a Bindings::iterator key = e->attrs->find(state.sKey); - if (key == e->attrs->end()) - throw EvalError({ + if (key == e->attrs->end()) { + auto e = EvalError({ .msg = hintfmt("attribute 'key' required"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } state.forceValue(*key->value, pos); if (!doneKeys.insert(key->value).second) continue; @@ -725,6 +760,41 @@ static RegisterPrimOp primop_genericClosure(RegisterPrimOp::Info { .fun = prim_genericClosure, }); + +static RegisterPrimOp primop_break({ + .name = "break", + .args = {"v"}, + .doc = R"( + In debug mode (enabled using `--debugger`), pause Nix expression evaluation and enter the REPL. + Otherwise, return the argument `v`. + )", + .fun = [](EvalState & state, const PosIdx pos, Value * * args, Value & v) + { + if (debuggerHook && !state.debugTraces.empty()) { + auto error = Error(ErrorInfo { + .level = lvlInfo, + .msg = hintfmt("breakpoint reached"), + .errPos = state.positions[pos], + }); + + auto & dt = state.debugTraces.front(); + debuggerHook(&error, dt.env, dt.expr); + + if (state.debugQuit) { + // If the user elects to quit the repl, throw an exception. + throw Error(ErrorInfo{ + .level = lvlInfo, + .msg = hintfmt("quit the debugger"), + .errPos = state.positions[noPos], + }); + } + } + + // Return the value we were passed. + v = *args[0]; + } +}); + static RegisterPrimOp primop_abort({ .name = "abort", .args = {"s"}, @@ -735,7 +805,11 @@ static RegisterPrimOp primop_abort({ { PathSet context; auto s = state.coerceToString(pos, *args[0], context).toOwned(); - throw Abort("evaluation aborted with the following error message: '%1%'", s); + { + auto e = Abort("evaluation aborted with the following error message: '%1%'", s); + state.debugLastTrace(e); + throw e; + } } }); @@ -753,7 +827,9 @@ static RegisterPrimOp primop_throw({ { PathSet context; auto s = state.coerceToString(pos, *args[0], context).toOwned(); - throw ThrownError(s); + auto e = ThrownError(s); + state.debugLastTrace(e); + throw e; } }); @@ -818,6 +894,8 @@ static RegisterPrimOp primop_floor({ static void prim_tryEval(EvalState & state, const PosIdx pos, Value * * args, Value & v) { auto attrs = state.buildBindings(2); + auto saveDebuggerHook = debuggerHook; + debuggerHook = nullptr; try { state.forceValue(*args[0], pos); attrs.insert(state.sValue, args[0]); @@ -826,6 +904,7 @@ static void prim_tryEval(EvalState & state, const PosIdx pos, Value * * args, Va attrs.alloc(state.sValue).mkBool(false); attrs.alloc("success").mkBool(false); } + debuggerHook = saveDebuggerHook; v.mkAttrs(attrs); } @@ -1008,37 +1087,53 @@ static void prim_derivationStrict(EvalState & state, const PosIdx pos, Value * * if (s == "recursive") ingestionMethod = FileIngestionMethod::Recursive; else if (s == "flat") ingestionMethod = FileIngestionMethod::Flat; else - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("invalid value '%s' for 'outputHashMode' attribute", s), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } }; auto handleOutputs = [&](const Strings & ss) { outputs.clear(); for (auto & j : ss) { if (outputs.find(j) != outputs.end()) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("duplicate derivation output '%1%'", j), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } /* !!! Check whether j is a valid attribute name. */ /* Derivations cannot be named ‘drv’, because then we'd have an attribute ‘drvPath’ in the resulting set. */ if (j == "drv") - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("invalid derivation output name 'drv'" ), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } outputs.insert(j); } if (outputs.empty()) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("derivation cannot have an empty set of outputs"), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } }; try { @@ -1163,23 +1258,35 @@ static void prim_derivationStrict(EvalState & state, const PosIdx pos, Value * * /* Do we have all required attributes? */ if (drv.builder == "") - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("required attribute 'builder' missing"), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } if (drv.platform == "") - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("required attribute 'system' missing"), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } /* Check whether the derivation name is valid. */ if (isDerivation(drvName)) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("derivation names are not allowed to end in '%s'", drvExtension), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } if (outputHash) { /* Handle fixed-output derivations. @@ -1187,10 +1294,14 @@ static void prim_derivationStrict(EvalState & state, const PosIdx pos, Value * * Ignore `__contentAddressed` because fixed output derivations are already content addressed. */ if (outputs.size() != 1 || *(outputs.begin()) != "out") - throw Error({ + { + auto e = Error({ .msg = hintfmt("multiple outputs are not supported in fixed-output derivations"), .errPos = state.positions[posDrvName] }); + state.debugLastTrace(e); + throw e; + } auto h = newHashAllowEmpty(*outputHash, parseHashTypeOpt(outputHashAlgo)); @@ -1358,10 +1469,14 @@ static RegisterPrimOp primop_toPath({ static void prim_storePath(EvalState & state, const PosIdx pos, Value * * args, Value & v) { if (evalSettings.pureEval) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("'%s' is not allowed in pure evaluation mode", "builtins.storePath"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } PathSet context; Path path = state.checkSourcePath(state.coerceToPath(pos, *args[0], context)); @@ -1370,10 +1485,14 @@ static void prim_storePath(EvalState & state, const PosIdx pos, Value * * args, e.g. nix-push does the right thing. */ if (!state.store->isStorePath(path)) path = canonPath(path, true); if (!state.store->isInStore(path)) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("path '%1%' is not in the Nix store", path), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } auto path2 = state.store->toStorePath(path).first; if (!settings.readOnlyMode) state.store->ensurePath(path2); @@ -1476,7 +1595,11 @@ static void prim_readFile(EvalState & state, const PosIdx pos, Value * * args, V auto path = realisePath(state, pos, *args[0]); auto s = readFile(path); if (s.find((char) 0) != std::string::npos) - throw Error("the contents of the file '%1%' cannot be represented as a Nix string", path); + { + auto e = Error("the contents of the file '%1%' cannot be represented as a Nix string", path); + state.debugLastTrace(e); + throw e; + } StorePathSet refs; if (state.store->isInStore(path)) { try { @@ -1528,10 +1651,12 @@ static void prim_findFile(EvalState & state, const PosIdx pos, Value * * args, V auto rewrites = state.realiseContext(context); path = rewriteStrings(path, rewrites); } catch (InvalidPathError & e) { - throw EvalError({ + auto ee = EvalError({ .msg = hintfmt("cannot find '%1%', since path '%2%' is not valid", path, e.path), .errPos = state.positions[pos] }); + state.debugLastTrace(ee); + throw ee; } @@ -1555,10 +1680,14 @@ static void prim_hashFile(EvalState & state, const PosIdx pos, Value * * args, V auto type = state.forceStringNoCtx(*args[0], pos); std::optional<HashType> ht = parseHashType(type); if (!ht) - throw Error({ + { + auto e = Error({ .msg = hintfmt("unknown hash type '%1%'", type), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } auto path = realisePath(state, pos, *args[1]); @@ -1795,13 +1924,17 @@ static void prim_toFile(EvalState & state, const PosIdx pos, Value * * args, Val for (auto path : context) { if (path.at(0) != '/') - throw EvalError( { + { + auto e = EvalError( { .msg = hintfmt( "in 'toFile': the file named '%1%' must not contain a reference " "to a derivation but contains (%2%)", name, path), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } refs.insert(state.store->parseStorePath(path)); } @@ -1959,7 +2092,11 @@ static void addPath( ? state.store->computeStorePathForPath(name, path, method, htSHA256, filter).first : state.store->addToStore(name, path, method, htSHA256, filter, state.repair, refs); if (expectedHash && expectedStorePath != dstPath) - throw Error("store path mismatch in (possibly filtered) path added from '%s'", path); + { + auto e = Error("store path mismatch in (possibly filtered) path added from '%s'", path); + state.debugLastTrace(e); + throw e; + } state.allowAndSetStorePathString(dstPath, v); } else state.allowAndSetStorePathString(*expectedStorePath, v); @@ -1977,12 +2114,16 @@ static void prim_filterSource(EvalState & state, const PosIdx pos, Value * * arg state.forceValue(*args[0], pos); if (args[0]->type() != nFunction) - throw TypeError({ + { + auto e = TypeError({ .msg = hintfmt( "first argument in call to 'filterSource' is not a function but %1%", showType(*args[0])), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } addPath(state, pos, std::string(baseNameOf(path)), path, args[0], FileIngestionMethod::Recursive, std::nullopt, v, context); } @@ -2066,16 +2207,24 @@ static void prim_path(EvalState & state, const PosIdx pos, Value * * args, Value else if (n == "sha256") expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, attr.pos), htSHA256); else - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("unsupported argument '%1%' to 'addPath'", state.symbols[attr.name]), .errPos = state.positions[attr.pos] }); + state.debugLastTrace(e); + throw e; + } } if (path.empty()) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("'path' required"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } if (name.empty()) name = baseNameOf(path); @@ -2447,10 +2596,14 @@ static void prim_functionArgs(EvalState & state, const PosIdx pos, Value * * arg return; } if (!args[0]->isLambda()) - throw TypeError({ + { + auto e = TypeError({ .msg = hintfmt("'functionArgs' requires a function"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } if (!args[0]->lambda.fun->hasFormals()) { v.mkAttrs(&state.emptyBindings); @@ -2538,7 +2691,8 @@ static void prim_zipAttrsWith(EvalState & state, const PosIdx pos, Value * * arg attrsSeen[attr.name].first++; } catch (TypeError & e) { e.addTrace(state.positions[pos], hintfmt("while invoking '%s'", "zipAttrsWith")); - throw; + state.debugLastTrace(e); + throw e; } } @@ -2625,10 +2779,14 @@ static void elemAt(EvalState & state, const PosIdx pos, Value & list, int n, Val { state.forceList(list, pos); if (n < 0 || (unsigned int) n >= list.listSize()) - throw Error({ + { + auto e = Error({ .msg = hintfmt("list index %1% is out of bounds", n), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } state.forceValue(*list.listElems()[n], pos); v = *list.listElems()[n]; } @@ -2673,10 +2831,14 @@ static void prim_tail(EvalState & state, const PosIdx pos, Value * * args, Value { state.forceList(*args[0], pos); if (args[0]->listSize() == 0) - throw Error({ + { + auto e = Error({ .msg = hintfmt("'tail' called on an empty list"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } state.mkList(v, args[0]->listSize() - 1); for (unsigned int n = 0; n < v.listSize(); ++n) @@ -2911,10 +3073,14 @@ static void prim_genList(EvalState & state, const PosIdx pos, Value * * args, Va auto len = state.forceInt(*args[1], pos); if (len < 0) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("cannot create list of size %1%", len), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } state.mkList(v, len); @@ -3123,7 +3289,8 @@ static void prim_concatMap(EvalState & state, const PosIdx pos, Value * * args, state.forceList(lists[n], lists[n].determinePos(args[0]->determinePos(pos))); } catch (TypeError &e) { e.addTrace(state.positions[pos], hintfmt("while invoking '%s'", "concatMap")); - throw; + state.debugLastTrace(e); + throw e; } len += lists[n].listSize(); } @@ -3218,10 +3385,14 @@ static void prim_div(EvalState & state, const PosIdx pos, Value * * args, Value NixFloat f2 = state.forceFloat(*args[1], pos); if (f2 == 0) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("division by zero"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } if (args[0]->type() == nFloat || args[1]->type() == nFloat) { v.mkFloat(state.forceFloat(*args[0], pos) / state.forceFloat(*args[1], pos)); @@ -3230,10 +3401,14 @@ static void prim_div(EvalState & state, const PosIdx pos, Value * * args, Value NixInt i2 = state.forceInt(*args[1], pos); /* Avoid division overflow as it might raise SIGFPE. */ if (i1 == std::numeric_limits<NixInt>::min() && i2 == -1) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("overflow in integer division"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } v.mkInt(i1 / i2); } @@ -3361,10 +3536,14 @@ static void prim_substring(EvalState & state, const PosIdx pos, Value * * args, auto s = state.coerceToString(pos, *args[2], context); if (start < 0) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("negative start position in 'substring'"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } v.mkString((unsigned int) start >= s->size() ? "" : s->substr(start, len), context); } @@ -3412,10 +3591,14 @@ static void prim_hashString(EvalState & state, const PosIdx pos, Value * * args, auto type = state.forceStringNoCtx(*args[0], pos); std::optional<HashType> ht = parseHashType(type); if (!ht) - throw Error({ + { + auto e = Error({ .msg = hintfmt("unknown hash type '%1%'", type), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } PathSet context; // discarded auto s = state.forceString(*args[1], context, pos); @@ -3485,15 +3668,19 @@ void prim_match(EvalState & state, const PosIdx pos, Value * * args, Value & v) } catch (std::regex_error &e) { if (e.code() == std::regex_constants::error_space) { // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++ - throw EvalError({ + auto e = EvalError({ .msg = hintfmt("memory limit exceeded by regular expression '%s'", re), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; } else { - throw EvalError({ + auto e = EvalError({ .msg = hintfmt("invalid regular expression '%s'", re), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; } } } @@ -3590,15 +3777,19 @@ void prim_split(EvalState & state, const PosIdx pos, Value * * args, Value & v) } catch (std::regex_error &e) { if (e.code() == std::regex_constants::error_space) { // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++ - throw EvalError({ + auto e = EvalError({ .msg = hintfmt("memory limit exceeded by regular expression '%s'", re), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; } else { - throw EvalError({ + auto e = EvalError({ .msg = hintfmt("invalid regular expression '%s'", re), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; } } } @@ -3675,10 +3866,14 @@ static void prim_replaceStrings(EvalState & state, const PosIdx pos, Value * * a state.forceList(*args[0], pos); state.forceList(*args[1], pos); if (args[0]->listSize() != args[1]->listSize()) - throw EvalError({ + { + auto e = EvalError({ .msg = hintfmt("'from' and 'to' arguments to 'replaceStrings' have different lengths"), .errPos = state.positions[pos] }); + state.debugLastTrace(e); + throw e; + } std::vector<std::string> from; from.reserve(args[0]->listSize()); @@ -3931,7 +4126,7 @@ void EvalState::createBaseEnv() because attribute lookups expect it to be sorted. */ baseEnv.values[0]->attrs->sort(); - staticBaseEnv.sort(); + staticBaseEnv->sort(); /* Note: we have to initialize the 'derivation' constant *after* building baseEnv/staticBaseEnv because it uses 'builtins'. */ |