1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2025-06-25 02:21:16 +02:00

No global eval settings in libnixexpr

Progress on #5638

There is still a global eval settings, but it pushed down into
`libnixcmd`, which is a lot less bad a place for this sort of thing.
This commit is contained in:
John Ericson 2024-06-14 12:41:09 -04:00
parent cb0c868da4
commit 52bfccf8d8
24 changed files with 102 additions and 71 deletions

View file

@ -45,7 +45,8 @@ static Strings parseNixPath(const std::string & s)
return res;
}
EvalSettings::EvalSettings()
EvalSettings::EvalSettings(bool & readOnlyMode)
: readOnlyMode{readOnlyMode}
{
auto var = getEnv("NIX_PATH");
if (var) nixPath = parseNixPath(*var);
@ -55,7 +56,7 @@ EvalSettings::EvalSettings()
builtinsAbortOnWarn = true;
}
Strings EvalSettings::getDefaultNixPath()
Strings EvalSettings::getDefaultNixPath() const
{
Strings res;
auto add = [&](const Path & p, const std::string & s = std::string()) {
@ -68,7 +69,7 @@ Strings EvalSettings::getDefaultNixPath()
}
};
if (!evalSettings.restrictEval && !evalSettings.pureEval) {
if (!restrictEval && !pureEval) {
add(getNixDefExpr() + "/channels");
add(rootChannelsDir() + "/nixpkgs", "nixpkgs");
add(rootChannelsDir());
@ -94,16 +95,12 @@ std::string EvalSettings::resolvePseudoUrl(std::string_view url)
return std::string(url);
}
const std::string & EvalSettings::getCurrentSystem()
const std::string & EvalSettings::getCurrentSystem() const
{
const auto & evalSystem = currentSystem.get();
return evalSystem != "" ? evalSystem : settings.thisSystem.get();
}
EvalSettings evalSettings;
static GlobalConfig::Register rEvalSettings(&evalSettings);
Path getNixDefExpr()
{
return settings.useXDGBaseDirectories

View file

@ -7,9 +7,11 @@ namespace nix {
struct EvalSettings : Config
{
EvalSettings();
EvalSettings(bool & readOnlyMode);
static Strings getDefaultNixPath();
bool & readOnlyMode;
Strings getDefaultNixPath() const;
static bool isPseudoUrl(std::string_view s);
@ -74,7 +76,7 @@ struct EvalSettings : Config
* Implements the `eval-system` vs `system` defaulting logic
* described for `eval-system`.
*/
const std::string & getCurrentSystem();
const std::string & getCurrentSystem() const;
Setting<bool> restrictEval{
this, false, "restrict-eval",
@ -193,8 +195,6 @@ struct EvalSettings : Config
)"};
};
extern EvalSettings evalSettings;
/**
* Conventionally part of the default nix path in impure mode.
*/

View file

@ -9,7 +9,6 @@
#include "store-api.hh"
#include "derivations.hh"
#include "downstream-placeholder.hh"
#include "globals.hh"
#include "eval-inline.hh"
#include "filetransfer.hh"
#include "function-trace.hh"
@ -219,8 +218,10 @@ static constexpr size_t BASE_ENV_SIZE = 128;
EvalState::EvalState(
const LookupPath & _lookupPath,
ref<Store> store,
const EvalSettings & settings,
std::shared_ptr<Store> buildStore)
: sWith(symbols.create("<with>"))
: settings{settings}
, sWith(symbols.create("<with>"))
, sOutPath(symbols.create("outPath"))
, sDrvPath(symbols.create("drvPath"))
, sType(symbols.create("type"))
@ -276,10 +277,10 @@ EvalState::EvalState(
, repair(NoRepair)
, emptyBindings(0)
, rootFS(
evalSettings.restrictEval || evalSettings.pureEval
settings.restrictEval || settings.pureEval
? ref<SourceAccessor>(AllowListSourceAccessor::create(getFSSourceAccessor(), {},
[](const CanonPath & path) -> RestrictedPathError {
auto modeInformation = evalSettings.pureEval
[&settings](const CanonPath & path) -> RestrictedPathError {
auto modeInformation = settings.pureEval
? "in pure evaluation mode (use '--impure' to override)"
: "in restricted mode";
throw RestrictedPathError("access to absolute path '%1%' is forbidden %2%", path, modeInformation);
@ -330,10 +331,10 @@ EvalState::EvalState(
vStringUnknown.mkString("unknown");
/* Initialise the Nix expression search path. */
if (!evalSettings.pureEval) {
if (!settings.pureEval) {
for (auto & i : _lookupPath.elements)
lookupPath.elements.emplace_back(LookupPath::Elem {i});
for (auto & i : evalSettings.nixPath.get())
for (auto & i : settings.nixPath.get())
lookupPath.elements.emplace_back(LookupPath::Elem::parse(i));
}
@ -411,9 +412,9 @@ bool isAllowedURI(std::string_view uri, const Strings & allowedUris)
void EvalState::checkURI(const std::string & uri)
{
if (!evalSettings.restrictEval) return;
if (!settings.restrictEval) return;
if (isAllowedURI(uri, evalSettings.allowedUris.get())) return;
if (isAllowedURI(uri, settings.allowedUris.get())) return;
/* If the URI is a path, then check it against allowedPaths as
well. */
@ -458,7 +459,7 @@ void EvalState::addConstant(const std::string & name, Value * v, Constant info)
constantInfos.push_back({name2, info});
if (!(evalSettings.pureEval && info.impureOnly)) {
if (!(settings.pureEval && info.impureOnly)) {
/* Check the type, if possible.
We might know the type of a thunk in advance, so be allowed
@ -1413,11 +1414,11 @@ public:
void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const PosIdx pos)
{
if (callDepth > evalSettings.maxCallDepth)
if (callDepth > settings.maxCallDepth)
error<EvalError>("stack overflow; max-call-depth exceeded").atPos(pos).debugThrow();
CallDepth _level(callDepth);
auto trace = evalSettings.traceFunctionCalls
auto trace = settings.traceFunctionCalls
? std::make_unique<FunctionCallTrace>(positions[pos])
: nullptr;
@ -2745,7 +2746,7 @@ SourcePath EvalState::findFile(const LookupPath & lookupPath, const std::string_
return {corepkgsFS, CanonPath(path.substr(3))};
error<ThrownError>(
evalSettings.pureEval
settings.pureEval
? "cannot look up '<%s>' in pure evaluation mode (use '--impure' to override)"
: "file '%s' was not found in the Nix search path (add it using $NIX_PATH or -I)",
path
@ -2825,7 +2826,7 @@ Expr * EvalState::parse(
const SourcePath & basePath,
std::shared_ptr<StaticEnv> & staticEnv)
{
auto result = parseExprFromBuf(text, length, origin, basePath, symbols, positions, rootFS, exprSymbols);
auto result = parseExprFromBuf(text, length, origin, basePath, symbols, settings, positions, rootFS, exprSymbols);
result->bindVars(*this, staticEnv);

View file

@ -30,6 +30,7 @@ namespace nix {
constexpr size_t maxPrimOpArity = 8;
class Store;
struct EvalSettings;
class EvalState;
class StorePath;
struct SingleDerivedPath;
@ -39,7 +40,6 @@ namespace eval_cache {
class EvalCache;
}
/**
* Function that implements a primop.
*/
@ -162,6 +162,7 @@ struct DebugTrace {
class EvalState : public std::enable_shared_from_this<EvalState>
{
public:
const EvalSettings & settings;
SymbolTable symbols;
PosTable positions;
@ -352,6 +353,7 @@ public:
EvalState(
const LookupPath & _lookupPath,
ref<Store> store,
const EvalSettings & settings,
std::shared_ptr<Store> buildStore = nullptr);
~EvalState();

View file

@ -1,6 +1,5 @@
#include "users.hh"
#include "config-global.hh"
#include "globals.hh"
#include "fetch-settings.hh"
#include "flake.hh"

View file

@ -803,7 +803,7 @@ static void prim_getFlake(EvalState & state, const PosIdx pos, Value * * args, V
{
std::string flakeRefS(state.forceStringNoCtx(*args[0], pos, "while evaluating the argument passed to builtins.getFlake"));
auto flakeRef = parseFlakeRef(flakeRefS, {}, true);
if (evalSettings.pureEval && !flakeRef.input.isLocked())
if (state.settings.pureEval && !flakeRef.input.isLocked())
throw Error("cannot call 'getFlake' on unlocked flake reference '%s', at %s (use --impure to override)", flakeRefS, state.positions[pos]);
callFlake(state,
@ -811,8 +811,8 @@ static void prim_getFlake(EvalState & state, const PosIdx pos, Value * * args, V
LockFlags {
.updateLockFile = false,
.writeLockFile = false,
.useRegistries = !evalSettings.pureEval && fetchSettings.useRegistries,
.allowUnlocked = !evalSettings.pureEval,
.useRegistries = !state.settings.pureEval && fetchSettings.useRegistries,
.allowUnlocked = !state.settings.pureEval,
}),
v);
}

View file

@ -46,6 +46,7 @@ struct ParserState
PosTable::Origin origin;
const ref<SourceAccessor> rootFS;
const Expr::AstSymbols & s;
const EvalSettings & settings;
void dupAttr(const AttrPath & attrPath, const PosIdx pos, const PosIdx prevPos);
void dupAttr(Symbol attr, const PosIdx pos, const PosIdx prevPos);

View file

@ -25,7 +25,6 @@
#include "nixexpr.hh"
#include "eval.hh"
#include "eval-settings.hh"
#include "globals.hh"
#include "parser-state.hh"
#define YYLTYPE ::nix::ParserLocation
@ -40,6 +39,7 @@ Expr * parseExprFromBuf(
Pos::Origin origin,
const SourcePath & basePath,
SymbolTable & symbols,
const EvalSettings & settings,
PosTable & positions,
const ref<SourceAccessor> rootFS,
const Expr::AstSymbols & astSymbols);
@ -294,7 +294,7 @@ path_start
$$ = new ExprPath(ref<SourceAccessor>(state->rootFS), std::move(path));
}
| HPATH {
if (evalSettings.pureEval) {
if (state->settings.pureEval) {
throw Error(
"the path '%s' can not be resolved in pure mode",
std::string_view($1.p, $1.l)
@ -429,6 +429,7 @@ Expr * parseExprFromBuf(
Pos::Origin origin,
const SourcePath & basePath,
SymbolTable & symbols,
const EvalSettings & settings,
PosTable & positions,
const ref<SourceAccessor> rootFS,
const Expr::AstSymbols & astSymbols)
@ -441,6 +442,7 @@ Expr * parseExprFromBuf(
.origin = positions.addOrigin(origin, length),
.rootFS = rootFS,
.s = astSymbols,
.settings = settings,
};
yylex_init(&scanner);

View file

@ -5,7 +5,6 @@
#include "eval.hh"
#include "eval-settings.hh"
#include "gc-small-vector.hh"
#include "globals.hh"
#include "json-to-value.hh"
#include "names.hh"
#include "path-references.hh"
@ -78,7 +77,7 @@ StringMap EvalState::realiseContext(const NixStringContext & context, StorePathS
if (drvs.empty()) return {};
if (isIFD && !evalSettings.enableImportFromDerivation)
if (isIFD && !settings.enableImportFromDerivation)
error<EvalError>(
"cannot build '%1%' during evaluation because the option 'allow-import-from-derivation' is disabled",
drvs.begin()->to_string(*store)
@ -901,7 +900,7 @@ static void prim_tryEval(EvalState & state, const PosIdx pos, Value * * args, Va
MaintainCount trylevel(state.trylevel);
ReplExitStatus (* savedDebugRepl)(ref<EvalState> es, const ValMap & extraEnv) = nullptr;
if (state.debugRepl && evalSettings.ignoreExceptionsDuringTry)
if (state.debugRepl && state.settings.ignoreExceptionsDuringTry)
{
/* to prevent starting the repl from exceptions withing a tryEval, null it. */
savedDebugRepl = state.debugRepl;
@ -950,7 +949,7 @@ static RegisterPrimOp primop_tryEval({
static void prim_getEnv(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
std::string name(state.forceStringNoCtx(*args[0], pos, "while evaluating the first argument passed to builtins.getEnv"));
v.mkString(evalSettings.restrictEval || evalSettings.pureEval ? "" : getEnv(name).value_or(""));
v.mkString(state.settings.restrictEval || state.settings.pureEval ? "" : getEnv(name).value_or(""));
}
static RegisterPrimOp primop_getEnv({
@ -1017,7 +1016,7 @@ static void prim_trace(EvalState & state, const PosIdx pos, Value * * args, Valu
printError("trace: %1%", args[0]->string_view());
else
printError("trace: %1%", ValuePrinter(state, *args[0]));
if (evalSettings.builtinsTraceDebugger) {
if (state.settings.builtinsTraceDebugger) {
state.runDebugRepl(nullptr);
}
state.forceValue(*args[1], pos);
@ -1056,11 +1055,11 @@ static void prim_warn(EvalState & state, const PosIdx pos, Value * * args, Value
logWarning(info);
}
if (evalSettings.builtinsAbortOnWarn) {
if (state.settings.builtinsAbortOnWarn) {
// Not an EvalError or subclass, which would cause the error to be stored in the eval cache.
state.error<EvalBaseError>("aborting to reveal stack trace of warning, as abort-on-warn is set").setIsFromExpr().debugThrow();
}
if (evalSettings.builtinsTraceDebugger || evalSettings.builtinsDebuggerOnWarn) {
if (state.settings.builtinsTraceDebugger || state.settings.builtinsDebuggerOnWarn) {
state.runDebugRepl(nullptr);
}
state.forceValue(*args[1], pos);
@ -1578,7 +1577,7 @@ static RegisterPrimOp primop_toPath({
corner cases. */
static void prim_storePath(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
if (evalSettings.pureEval)
if (state.settings.pureEval)
state.error<EvalError>(
"'%s' is not allowed in pure evaluation mode",
"builtins.storePath"
@ -4562,7 +4561,7 @@ void EvalState::createBaseEnv()
)",
});
if (!evalSettings.pureEval) {
if (!settings.pureEval) {
v.mkInt(time(0));
}
addConstant("__currentTime", v, {
@ -4589,8 +4588,8 @@ void EvalState::createBaseEnv()
.impureOnly = true,
});
if (!evalSettings.pureEval)
v.mkString(evalSettings.getCurrentSystem());
if (!settings.pureEval)
v.mkString(settings.getCurrentSystem());
addConstant("__currentSystem", v, {
.type = nString,
.doc = R"(
@ -4670,7 +4669,7 @@ void EvalState::createBaseEnv()
#ifndef _WIN32 // TODO implement on Windows
// Miscellaneous
if (evalSettings.enableNativeCode) {
if (settings.enableNativeCode) {
addPrimOp({
.name = "__importNative",
.arity = 2,
@ -4693,7 +4692,7 @@ void EvalState::createBaseEnv()
error if `--trace-verbose` is enabled. Then return *e2*. This function
is useful for debugging.
)",
.fun = evalSettings.traceVerbose ? prim_trace : prim_second,
.fun = settings.traceVerbose ? prim_trace : prim_second,
});
/* Add a value containing the current Nix expression search path. */

View file

@ -53,7 +53,7 @@ static void prim_fetchMercurial(EvalState & state, const PosIdx pos, Value * * a
// whitelist. Ah well.
state.checkURI(url);
if (evalSettings.pureEval && !rev)
if (state.settings.pureEval && !rev)
throw Error("in pure evaluation mode, 'fetchMercurial' requires a Mercurial revision");
fetchers::Attrs attrs;

View file

@ -171,10 +171,10 @@ static void fetchTree(
}
}
if (!evalSettings.pureEval && !input.isDirect() && experimentalFeatureSettings.isEnabled(Xp::Flakes))
if (!state.settings.pureEval && !input.isDirect() && experimentalFeatureSettings.isEnabled(Xp::Flakes))
input = lookupInRegistries(state.store, input).first;
if (evalSettings.pureEval && !input.isLocked()) {
if (state.settings.pureEval && !input.isLocked()) {
auto fetcher = "fetchTree";
if (params.isFetchGit)
fetcher = "fetchGit";
@ -453,14 +453,14 @@ static void fetch(EvalState & state, const PosIdx pos, Value * * args, Value & v
url = state.forceStringNoCtx(*args[0], pos, "while evaluating the url we should fetch");
if (who == "fetchTarball")
url = evalSettings.resolvePseudoUrl(*url);
url = state.settings.resolvePseudoUrl(*url);
state.checkURI(*url);
if (name == "")
name = baseNameOf(*url);
if (evalSettings.pureEval && !expectedHash)
if (state.settings.pureEval && !expectedHash)
state.error<EvalError>("in pure evaluation mode, '%s' requires a 'sha256' argument", who).atPos(pos).debugThrow();
// early exit if pinned and already in the store