diff options
Diffstat (limited to 'src')
43 files changed, 1359 insertions, 355 deletions
diff --git a/src/buildenv/buildenv.cc b/src/buildenv/buildenv.cc new file mode 100644 index 000000000000..f997096eddbb --- /dev/null +++ b/src/buildenv/buildenv.cc @@ -0,0 +1,186 @@ +#include "shared.hh" +#include <sys/stat.h> +#include <sys/types.h> +#include <fcntl.h> +#include <algorithm> + +using namespace nix; + +typedef std::map<Path,int> Priorities; + +static bool isDirectory (const Path & path) +{ + struct stat st; + if (stat(path.c_str(), &st) == -1) + throw SysError(format("getting status of ‘%1%’") % path); + return S_ISDIR(st.st_mode); +} + +static auto priorities = Priorities{}; + +static auto symlinks = 0; + +/* For each activated package, create symlinks */ +static void createLinks(const Path & srcDir, const Path & dstDir, int priority) +{ + auto srcFiles = readDirectory(srcDir); + for (const auto & ent : srcFiles) { + if (ent.name[0] == '.') + /* not matched by glob */ + continue; + const auto & srcFile = srcDir + "/" + ent.name; + auto dstFile = dstDir + "/" + ent.name; + + /* The files below are special-cased to that they don't show up + * in user profiles, either because they are useless, or + * because they would cauase pointless collisions (e.g., each + * Python package brings its own + * `$out/lib/pythonX.Y/site-packages/easy-install.pth'.) + */ + if (hasSuffix(srcFile, "/propagated-build-inputs") || + hasSuffix(srcFile, "/nix-support") || + hasSuffix(srcFile, "/perllocal.pod") || + hasSuffix(srcFile, "/info/dir") || + hasSuffix(srcFile, "/log")) { + continue; + } else if (isDirectory(srcFile)) { + struct stat dstSt; + auto res = lstat(dstFile.c_str(), &dstSt); + if (res == 0) { + if (S_ISDIR(dstSt.st_mode)) { + createLinks(srcFile, dstFile, priority); + continue; + } else if (S_ISLNK(dstSt.st_mode)) { + auto target = readLink(dstFile); + if (!isDirectory(target)) + throw Error(format("collision between ‘%1%’ and non-directory ‘%2%’") + % srcFile % target); + if (unlink(dstFile.c_str()) == -1) + throw SysError(format("unlinking ‘%1%’") % dstFile); + if (mkdir(dstFile.c_str(), 0755) == -1) + throw SysError(format("creating directory ‘%1%’")); + createLinks(target, dstFile, priorities[dstFile]); + createLinks(srcFile, dstFile, priority); + continue; + } + } else if (errno != ENOENT) + throw SysError(format("getting status of ‘%1%’") % dstFile); + } else { + struct stat dstSt; + auto res = lstat(dstFile.c_str(), &dstSt); + if (res == 0) { + if (S_ISLNK(dstSt.st_mode)) { + auto target = readLink(dstFile); + auto prevPriority = priorities[dstFile]; + if (prevPriority == priority) + throw Error(format( + "collision between ‘%1%’ and ‘%2%’; " + "use ‘nix-env --set-flag priority NUMBER PKGNAME’ " + "to change the priority of one of the conflicting packages" + ) % srcFile % target); + if (prevPriority < priority) + continue; + if (unlink(dstFile.c_str()) == -1) + throw SysError(format("unlinking ‘%1%’") % dstFile); + } + } else if (errno != ENOENT) + throw SysError(format("getting status of ‘%1%’") % dstFile); + } + createSymlink(srcFile, dstFile); + priorities[dstFile] = priority; + symlinks++; + } +} + +typedef std::set<Path> FileProp; + +static auto done = FileProp{}; +static auto postponed = FileProp{}; + +static auto out = string{}; + +static void addPkg(const Path & pkgDir, int priority) +{ + if (done.find(pkgDir) != done.end()) + return; + done.insert(pkgDir); + createLinks(pkgDir, out, priority); + auto propagatedFN = pkgDir + "/nix-support/propagated-user-env-packages"; + auto propagated = string{}; + { + AutoCloseFD fd = open(propagatedFN.c_str(), O_RDONLY | O_CLOEXEC); + if (!fd) { + if (errno == ENOENT) + return; + throw SysError(format("opening ‘%1%’") % propagatedFN); + } + propagated = readLine(fd.get()); + } + for (const auto & p : tokenizeString<std::vector<string>>(propagated, " ")) + if (done.find(p) == done.end()) + postponed.insert(p); +} + +struct Package { + Path path; + bool active; + int priority; + Package(Path path, bool active, int priority) : path{std::move(path)}, active{active}, priority{priority} {} +}; + +typedef std::vector<Package> Packages; + +int main(int argc, char ** argv) +{ + return handleExceptions(argv[0], [&]() { + initNix(); + out = getEnv("out"); + if (mkdir(out.c_str(), 0755) == -1) + throw SysError(format("creating %1%") % out); + + /* Convert the stuff we get from the environment back into a coherent + * data type. + */ + auto pkgs = Packages{}; + auto derivations = tokenizeString<Strings>(getEnv("derivations")); + while (!derivations.empty()) { + /* !!! We're trusting the caller to structure derivations env var correctly */ + auto active = derivations.front(); derivations.pop_front(); + auto priority = stoi(derivations.front()); derivations.pop_front(); + auto outputs = stoi(derivations.front()); derivations.pop_front(); + for (auto n = 0; n < outputs; n++) { + auto path = derivations.front(); derivations.pop_front(); + pkgs.emplace_back(path, active != "false", priority); + } + } + + /* Symlink to the packages that have been installed explicitly by the + * user. Process in priority order to reduce unnecessary + * symlink/unlink steps. + */ + std::sort(pkgs.begin(), pkgs.end(), [](const Package & a, const Package & b) { + return a.priority < b.priority || (a.priority == b.priority && a.path < b.path); + }); + for (const auto & pkg : pkgs) + if (pkg.active) + addPkg(pkg.path, pkg.priority); + + /* Symlink to the packages that have been "propagated" by packages + * installed by the user (i.e., package X declares that it wants Y + * installed as well). We do these later because they have a lower + * priority in case of collisions. + */ + auto priorityCounter = 1000; + while (!postponed.empty()) { + auto pkgDirs = postponed; + postponed = FileProp{}; + for (const auto & pkgDir : pkgDirs) + addPkg(pkgDir, priorityCounter++); + } + + std::cerr << "created " << symlinks << " symlinks in user environment\n"; + + createSymlink(getEnv("manifest"), out + "/manifest.nix"); + }); +} + diff --git a/src/buildenv/local.mk b/src/buildenv/local.mk new file mode 100644 index 000000000000..17ec13b235f4 --- /dev/null +++ b/src/buildenv/local.mk @@ -0,0 +1,9 @@ +programs += buildenv + +buildenv_DIR := $(d) + +buildenv_INSTALL_DIR := $(libexecdir)/nix + +buildenv_LIBS = libmain libstore libutil libformat + +buildenv_SOURCES := $(d)/buildenv.cc diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index 0833603b2a9e..64f3874db614 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -293,6 +293,8 @@ EvalState::EvalState(const Strings & _searchPath, ref<Store> store) , sColumn(symbols.create("column")) , sFunctor(symbols.create("__functor")) , sToString(symbols.create("__toString")) + , sRight(symbols.create("right")) + , sWrong(symbols.create("wrong")) , store(store) , baseEnv(allocEnv(128)) , staticBaseEnv(false, 0) @@ -379,9 +381,9 @@ void EvalState::addPrimOp(const string & name, } -void EvalState::getBuiltin(const string & name, Value & v) +Value & EvalState::getBuiltin(const string & name) { - v = *baseEnv.values[0]->attrs->find(symbols.create(name))->value; + return *baseEnv.values[0]->attrs->find(symbols.create(name))->value; } @@ -462,7 +464,7 @@ void mkString(Value & v, const char * s) } -void mkString(Value & v, const string & s, const PathSet & context) +Value & mkString(Value & v, const string & s, const PathSet & context) { mkString(v, s.c_str()); if (!context.empty()) { @@ -473,6 +475,7 @@ void mkString(Value & v, const string & s, const PathSet & context) v.string.context[n++] = dupString(i.c_str()); v.string.context[n] = 0; } + return v; } @@ -993,11 +996,18 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po if (fun.type == tAttrs) { auto found = fun.attrs->find(sFunctor); if (found != fun.attrs->end()) { + /* fun may be allocated on the stack of the calling function, + * but for functors we may keep a reference, so heap-allocate + * a copy and use that instead. + */ + auto & fun2 = *allocValue(); + fun2 = fun; + /* !!! Should we use the attr pos here? */ forceValue(*found->value, pos); - Value * v2 = allocValue(); - callFunction(*found->value, fun, *v2, pos); - forceValue(*v2, pos); - return callFunction(*v2, arg, v, pos); + Value v2; + callFunction(*found->value, fun2, v2, pos); + forceValue(v2, pos); + return callFunction(v2, arg, v, pos); } } @@ -1368,11 +1378,11 @@ NixFloat EvalState::forceFloat(Value & v, const Pos & pos) } -bool EvalState::forceBool(Value & v) +bool EvalState::forceBool(Value & v, const Pos & pos) { forceValue(v); if (v.type != tBool) - throwTypeError("value is %1% while a Boolean was expected", v); + throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos); return v.boolean; } diff --git a/src/libexpr/eval.hh b/src/libexpr/eval.hh index 80e369f2d68f..195cb0db3acc 100644 --- a/src/libexpr/eval.hh +++ b/src/libexpr/eval.hh @@ -8,10 +8,6 @@ #include <map> -#if HAVE_BOEHMGC -#include <gc/gc_allocator.h> -#endif - namespace nix { @@ -43,7 +39,7 @@ struct Env }; -void mkString(Value & v, const string & s, const PathSet & context = PathSet()); +Value & mkString(Value & v, const string & s, const PathSet & context = PathSet()); void copyContext(const Value & v, PathSet & context); @@ -71,7 +67,8 @@ public: const Symbol sWith, sOutPath, sDrvPath, sType, sMeta, sName, sValue, sSystem, sOverrides, sOutputs, sOutputName, sIgnoreNulls, - sFile, sLine, sColumn, sFunctor, sToString; + sFile, sLine, sColumn, sFunctor, sToString, + sRight, sWrong; Symbol sDerivationNix; /* If set, force copying files to the Nix store even if they @@ -108,6 +105,8 @@ public: void addToSearchPath(const string & s); + SearchPath getSearchPath() { return searchPath; } + Path checkSourcePath(const Path & path); /* Parse a Nix expression from the specified file. */ @@ -154,7 +153,7 @@ public: /* Force `v', and then verify that it has the expected type. */ NixInt forceInt(Value & v, const Pos & pos); NixFloat forceFloat(Value & v, const Pos & pos); - bool forceBool(Value & v); + bool forceBool(Value & v, const Pos & pos); inline void forceAttrs(Value & v); inline void forceAttrs(Value & v, const Pos & pos); inline void forceList(Value & v); @@ -204,7 +203,7 @@ private: public: - void getBuiltin(const string & name, Value & v); + Value & getBuiltin(const string & name); private: diff --git a/src/libexpr/get-drvs.cc b/src/libexpr/get-drvs.cc index b06c539de0fb..dc5def911ca0 100644 --- a/src/libexpr/get-drvs.cc +++ b/src/libexpr/get-drvs.cc @@ -301,7 +301,7 @@ static void getDerivations(EvalState & state, Value & vIn, `recurseForDerivations = true' attribute. */ if (v2.type == tAttrs) { Bindings::iterator j = v2.attrs->find(state.symbols.create("recurseForDerivations")); - if (j != v2.attrs->end() && state.forceBool(*j->value)) + if (j != v2.attrs->end() && state.forceBool(*j->value, *j->pos)) getDerivations(state, v2, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures); } } diff --git a/src/libexpr/json-to-value.cc b/src/libexpr/json-to-value.cc index 1daf84600dca..f671802bcc24 100644 --- a/src/libexpr/json-to-value.cc +++ b/src/libexpr/json-to-value.cc @@ -12,15 +12,6 @@ static void skipWhitespace(const char * & s) } -#if HAVE_BOEHMGC -typedef std::vector<Value *, gc_allocator<Value *> > ValueVector; -typedef std::map<Symbol, Value *, std::less<Symbol>, gc_allocator<Value *> > ValueMap; -#else -typedef std::vector<Value *> ValueVector; -typedef std::map<Symbol, Value *> ValueMap; -#endif - - static string parseJSONString(const char * & s) { string res; diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index c456e9b96a53..3b965f209bb2 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -477,7 +477,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * bool ignoreNulls = false; attr = args[0]->attrs->find(state.sIgnoreNulls); if (attr != args[0]->attrs->end()) - ignoreNulls = state.forceBool(*attr->value); + ignoreNulls = state.forceBool(*attr->value, pos); /* Build the derivation expression by processing the attributes. */ Derivation drv; @@ -673,6 +673,19 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * } +/* Return a placeholder string for the specified output that will be + substituted by the corresponding output path at build time. For + example, ‘placeholder "out"’ returns the string + /1rz4g4znpzjwh1xymhjpm42vipw92pr73vdgl6xs1hycac8kf2n9. At build + time, any occurence of this string in an derivation attribute will + be replaced with the concrete path in the Nix store of the output + ‘out’. */ +static void prim_placeholder(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + mkString(v, hashPlaceholder(state.forceStringNoCtx(*args[0], pos))); +} + + /************************************************************* * Paths *************************************************************/ @@ -912,9 +925,10 @@ struct FilterFromExpr : PathFilter { EvalState & state; Value & filter; + Pos pos; - FilterFromExpr(EvalState & state, Value & filter) - : state(state), filter(filter) + FilterFromExpr(EvalState & state, Value & filter, const Pos & pos) + : state(state), filter(filter), pos(pos) { } @@ -942,7 +956,7 @@ struct FilterFromExpr : PathFilter Value res; state.callFunction(fun2, arg2, res, noPos); - return state.forceBool(res); + return state.forceBool(res, pos); } }; @@ -958,7 +972,7 @@ static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args if (args[0]->type != tLambda) throw TypeError(format("first argument in call to ‘filterSource’ is not a function but %1%, at %2%") % showType(*args[0]) % pos); - FilterFromExpr filter(state, *args[0]); + FilterFromExpr filter(state, *args[0], pos); path = state.checkSourcePath(path); @@ -1278,7 +1292,7 @@ static void prim_filter(EvalState & state, const Pos & pos, Value * * args, Valu for (unsigned int n = 0; n < args[1]->listSize(); ++n) { Value res; state.callFunction(*args[0], *args[1]->listElems()[n], res, noPos); - if (state.forceBool(res)) + if (state.forceBool(res, pos)) vs[k++] = args[1]->listElems()[n]; else same = false; @@ -1354,7 +1368,7 @@ static void anyOrAll(bool any, EvalState & state, const Pos & pos, Value * * arg Value vTmp; for (unsigned int n = 0; n < args[1]->listSize(); ++n) { state.callFunction(*args[0], *args[1]->listElems()[n], vTmp, pos); - bool res = state.forceBool(vTmp); + bool res = state.forceBool(vTmp, pos); if (res == any) { mkBool(v, any); return; @@ -1420,7 +1434,7 @@ static void prim_sort(EvalState & state, const Pos & pos, Value * * args, Value Value vTmp1, vTmp2; state.callFunction(*args[0], *a, vTmp1, pos); state.callFunction(vTmp1, *b, vTmp2, pos); - return state.forceBool(vTmp2); + return state.forceBool(vTmp2, pos); }; /* FIXME: std::sort can segfault if the comparator is not a strict @@ -1430,6 +1444,40 @@ static void prim_sort(EvalState & state, const Pos & pos, Value * * args, Value } +static void prim_partition(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + state.forceFunction(*args[0], pos); + state.forceList(*args[1], pos); + + auto len = args[1]->listSize(); + + ValueVector right, wrong; + + for (unsigned int n = 0; n < len; ++n) { + auto vElem = args[1]->listElems()[n]; + state.forceValue(*vElem); + Value res; + state.callFunction(*args[0], *vElem, res, pos); + if (state.forceBool(res, pos)) + right.push_back(vElem); + else + wrong.push_back(vElem); + } + + state.mkAttrs(v, 2); + + Value * vRight = state.allocAttr(v, state.sRight); + state.mkList(*vRight, right.size()); + memcpy(vRight->listElems(), right.data(), sizeof(Value *) * right.size()); + + Value * vWrong = state.allocAttr(v, state.sWrong); + state.mkList(*vWrong, wrong.size()); + memcpy(vWrong->listElems(), wrong.data(), sizeof(Value *) * wrong.size()); + + v.attrs->sort(); +} + + /************************************************************* * Integer arithmetic *************************************************************/ @@ -1620,13 +1668,18 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar if (args[0]->listSize() != args[1]->listSize()) throw EvalError(format("‘from’ and ‘to’ arguments to ‘replaceStrings’ have different lengths, at %1%") % pos); - Strings from; + vector<string> from; + from.reserve(args[0]->listSize()); for (unsigned int n = 0; n < args[0]->listSize(); ++n) - from.push_back(state.forceStringNoCtx(*args[0]->listElems()[n], pos)); + from.push_back(state.forceString(*args[0]->listElems()[n], pos)); - Strings to; - for (unsigned int n = 0; n < args[1]->listSize(); ++n) - to.push_back(state.forceStringNoCtx(*args[1]->listElems()[n], pos)); + vector<std::pair<string, PathSet>> to; + to.reserve(args[1]->listSize()); + for (unsigned int n = 0; n < args[1]->listSize(); ++n) { + PathSet ctx; + auto s = state.forceString(*args[1]->listElems()[n], ctx, pos); + to.push_back(std::make_pair(std::move(s), std::move(ctx))); + } PathSet context; auto s = state.forceString(*args[2], context, pos); @@ -1634,11 +1687,16 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar string res; for (size_t p = 0; p < s.size(); ) { bool found = false; - for (auto i = from.begin(), j = to.begin(); i != from.end(); ++i, ++j) + auto i = from.begin(); + auto j = to.begin(); + for (; i != from.end(); ++i, ++j) if (s.compare(p, i->size(), *i) == 0) { found = true; p += i->size(); - res += *j; + res += j->first; + for (auto& path : j->second) + context.insert(path); + j->second.clear(); break; } if (!found) res += s[p++]; @@ -1682,6 +1740,7 @@ void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, { string url; Hash expectedHash; + string name; state.forceValue(*args[0]); @@ -1690,11 +1749,13 @@ void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, state.forceAttrs(*args[0], pos); for (auto & attr : *args[0]->attrs) { - string name(attr.name); - if (name == "url") + string n(attr.name); + if (n == "url") url = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (name == "sha256") + else if (n == "sha256") expectedHash = parseHash16or32(htSHA256, state.forceStringNoCtx(*attr.value, *attr.pos)); + else if (n == "name") + name = state.forceStringNoCtx(*attr.value, *attr.pos); else throw EvalError(format("unsupported argument ‘%1%’ to ‘%2%’, at %3%") % attr.name % who % attr.pos); } @@ -1708,7 +1769,7 @@ void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, if (state.restricted && !expectedHash) throw Error(format("‘%1%’ is not allowed in restricted mode") % who); - Path res = makeDownloader()->downloadCached(state.store, url, unpack, expectedHash); + Path res = makeDownloader()->downloadCached(state.store, url, unpack, name, expectedHash); mkString(v, res, PathSet({res})); } @@ -1855,6 +1916,7 @@ void EvalState::createBaseEnv() addPrimOp("__all", 2, prim_all); addPrimOp("__genList", 2, prim_genList); addPrimOp("__sort", 2, prim_sort); + addPrimOp("__partition", 2, prim_partition); // Integer arithmetic addPrimOp("__add", 2, prim_add); @@ -1880,6 +1942,7 @@ void EvalState::createBaseEnv() // Derivations addPrimOp("derivationStrict", 1, prim_derivationStrict); + addPrimOp("placeholder", 1, prim_placeholder); // Networking addPrimOp("__fetchurl", 1, prim_fetchurl); diff --git a/src/libexpr/value-to-json.cc b/src/libexpr/value-to-json.cc index 47ee324a6e4f..72e413e4491e 100644 --- a/src/libexpr/value-to-json.cc +++ b/src/libexpr/value-to-json.cc @@ -1,4 +1,5 @@ #include "value-to-json.hh" +#include "json.hh" #include "eval-inline.hh" #include "util.hh" @@ -8,24 +9,8 @@ namespace nix { - -void escapeJSON(std::ostream & str, const string & s) -{ - str << "\""; - for (auto & i : s) - if (i == '\"' || i == '\\') str << "\\" << i; - else if (i == '\n') str << "\\n"; - else if (i == '\r') str << "\\r"; - else if (i == '\t') str << "\\t"; - else if (i >= 0 && i < 32) - str << "\\u" << std::setfill('0') << std::setw(4) << std::hex << (uint16_t) i << std::dec; - else str << i; - str << "\""; -} - - void printValueAsJSON(EvalState & state, bool strict, - Value & v, std::ostream & str, PathSet & context) + Value & v, JSONPlaceholder & out, PathSet & context) { checkInterrupt(); @@ -34,58 +19,58 @@ void printValueAsJSON(EvalState & state, bool strict, switch (v.type) { case tInt: - str << v.integer; + out.write(v.integer); break; case tBool: - str << (v.boolean ? "true" : "false"); + out.write(v.boolean); break; case tString: copyContext(v, context); - escapeJSON(str, v.string.s); + out.write(v.string.s); break; case tPath: - escapeJSON(str, state.copyPathToStore(context, v.path)); + out.write(state.copyPathToStore(context, v.path)); break; case tNull: - str << "null"; + out.write(nullptr); break; case tAttrs: { Bindings::iterator i = v.attrs->find(state.sOutPath); if (i == v.attrs->end()) { - JSONObject json(str); + auto obj(out.object()); StringSet names; for (auto & j : *v.attrs) names.insert(j.name); for (auto & j : names) { Attr & a(*v.attrs->find(state.symbols.create(j))); - json.attr(j); - printValueAsJSON(state, strict, *a.value, str, context); + auto placeholder(obj.placeholder(j)); + printValueAsJSON(state, strict, *a.value, placeholder, context); } } else - printValueAsJSON(state, strict, *i->value, str, context); + printValueAsJSON(state, strict, *i->value, out, context); break; } case tList1: case tList2: case tListN: { - JSONList json(str); + auto list(out.list()); for (unsigned int n = 0; n < v.listSize(); ++n) { - json.elem(); - printValueAsJSON(state, strict, *v.listElems()[n], str, context); + auto placeholder(list.placeholder()); + printValueAsJSON(state, strict, *v.listElems()[n], placeholder, context); } break; } case tExternal: - v.external->printValueAsJSON(state, strict, str, context); + v.external->printValueAsJSON(state, strict, out, context); break; case tFloat: - str << v.fpoint; + out.write(v.fpoint); break; default: @@ -93,9 +78,15 @@ void printValueAsJSON(EvalState & state, bool strict, } } +void printValueAsJSON(EvalState & state, bool strict, + Value & v, std::ostream & str, PathSet & context) +{ + JSONPlaceholder out(str); + printValueAsJSON(state, strict, v, out, context); +} void ExternalValueBase::printValueAsJSON(EvalState & state, bool strict, - std::ostream & str, PathSet & context) const + JSONPlaceholder & out, PathSet & context) const { throw TypeError(format("cannot convert %1% to JSON") % showType()); } diff --git a/src/libexpr/value-to-json.hh b/src/libexpr/value-to-json.hh index c59caf5641bc..67fed6487dd9 100644 --- a/src/libexpr/value-to-json.hh +++ b/src/libexpr/value-to-json.hh @@ -8,73 +8,12 @@ namespace nix { -void printValueAsJSON(EvalState & state, bool strict, - Value & v, std::ostream & out, PathSet & context); - -void escapeJSON(std::ostream & str, const string & s); +class JSONPlaceholder; -struct JSONObject -{ - std::ostream & str; - bool first; - JSONObject(std::ostream & str) : str(str), first(true) - { - str << "{"; - } - ~JSONObject() - { - str << "}"; - } - void attr(const string & s) - { - if (!first) str << ","; else first = false; - escapeJSON(str, s); - str << ":"; - } - void attr(const string & s, const string & t) - { - attr(s); - escapeJSON(str, t); - } - void attr(const string & s, const char * t) - { - attr(s); - escapeJSON(str, t); - } - void attr(const string & s, bool b) - { - attr(s); - str << (b ? "true" : "false"); - } - template<typename T> - void attr(const string & s, const T & n) - { - attr(s); - str << n; - } -}; +void printValueAsJSON(EvalState & state, bool strict, + Value & v, JSONPlaceholder & out, PathSet & context); -struct JSONList -{ - std::ostream & str; - bool first; - JSONList(std::ostream & str) : str(str), first(true) - { - str << "["; - } - ~JSONList() - { - str << "]"; - } - void elem() - { - if (!first) str << ","; else first = false; - } - void elem(const string & s) - { - elem(); - escapeJSON(str, s); - } -}; +void printValueAsJSON(EvalState & state, bool strict, + Value & v, std::ostream & str, PathSet & context); } diff --git a/src/libexpr/value.hh b/src/libexpr/value.hh index 62bdd9281f08..271e6a1b24a2 100644 --- a/src/libexpr/value.hh +++ b/src/libexpr/value.hh @@ -1,7 +1,12 @@ #pragma once +#include "config.h" #include "symbol-table.hh" +#if HAVE_BOEHMGC +#include <gc/gc_allocator.h> +#endif + namespace nix { @@ -36,6 +41,7 @@ class Symbol; struct Pos; class EvalState; class XMLWriter; +class JSONPlaceholder; typedef long NixInt; @@ -73,7 +79,7 @@ class ExternalValueBase /* Print the value as JSON. Defaults to unconvertable, i.e. throws an error */ virtual void printValueAsJSON(EvalState & state, bool strict, - std::ostream & str, PathSet & context) const; + JSONPlaceholder & out, PathSet & context) const; /* Print the value as XML. Defaults to unevaluated */ virtual void printValueAsXML(EvalState & state, bool strict, bool location, @@ -249,4 +255,13 @@ void mkPath(Value & v, const char * s); size_t valueSize(Value & v); +#if HAVE_BOEHMGC +typedef std::vector<Value *, gc_allocator<Value *> > ValueVector; +typedef std::map<Symbol, Value *, std::less<Symbol>, gc_allocator<Value *> > ValueMap; +#else +typedef std::vector<Value *> ValueVector; +typedef std::map<Symbol, Value *> ValueMap; +#endif + + } diff --git a/src/libmain/shared.cc b/src/libmain/shared.cc index 515d80091de3..5af7c46e86da 100644 --- a/src/libmain/shared.cc +++ b/src/libmain/shared.cc @@ -252,7 +252,6 @@ void printVersion(const string & programName) std::cout << "Configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; std::cout << "Store directory: " << settings.nixStore << "\n"; std::cout << "State directory: " << settings.nixStateDir << "\n"; - std::cout << "Database directory: " << settings.nixDBPath << "\n"; } throw Exit(); } diff --git a/src/libstore/binary-cache-store.cc b/src/libstore/binary-cache-store.cc index 801ecd368a6b..e71ea6a57a34 100644 --- a/src/libstore/binary-cache-store.cc +++ b/src/libstore/binary-cache-store.cc @@ -254,7 +254,7 @@ struct BinaryCacheStoreAccessor : public FSAccessor std::string restPath = std::string(path, storePath.size()); if (!store->isValidPath(storePath)) - throw Error(format("path ‘%1%’ is not a valid store path") % storePath); + throw InvalidPath(format("path ‘%1%’ is not a valid store path") % storePath); auto i = nars.find(storePath); if (i != nars.end()) return {i->second, restPath}; diff --git a/src/libstore/build.cc b/src/libstore/build.cc index 10ae574f9e49..e0eb702a4f82 100644 --- a/src/libstore/build.cc +++ b/src/libstore/build.cc @@ -193,6 +193,7 @@ bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) { struct Child { WeakGoalPtr goal; + Goal * goal2; // ugly hackery set<int> fds; bool respectTimeouts; bool inBuildSlot; @@ -284,7 +285,7 @@ public: false if there is no sense in waking up goals that are sleeping because they can't run yet (e.g., there is no free build slot, or the hook would still say `postpone'). */ - void childTerminated(GoalPtr goal, bool wakeSleepers = true); + void childTerminated(Goal * goal, bool wakeSleepers = true); /* Put `goal' to sleep until a build slot becomes available (which might be right away). */ @@ -652,18 +653,15 @@ HookInstance::~HookInstance() ////////////////////////////////////////////////////////////////////// -typedef map<string, string> HashRewrites; +typedef map<std::string, std::string> StringRewrites; -string rewriteHashes(string s, const HashRewrites & rewrites) +std::string rewriteStrings(std::string s, const StringRewrites & rewrites) { for (auto & i : rewrites) { - assert(i.first.size() == i.second.size()); size_t j = 0; - while ((j = s.find(i.first, j)) != string::npos) { - debug(format("rewriting @ %1%") % j); - s.replace(j, i.second.size(), i.second); - } + while ((j = s.find(i.first, j)) != string::npos) + s.replace(j, i.first.size(), i.second); } return s; } @@ -782,7 +780,7 @@ private: #endif /* Hash rewriting. */ - HashRewrites rewritesToTmp, rewritesFromTmp; + StringRewrites inputRewrites, outputRewrites; typedef map<Path, Path> RedirectedOutputs; RedirectedOutputs redirectedOutputs; @@ -938,7 +936,7 @@ DerivationGoal::~DerivationGoal() void DerivationGoal::killChild() { if (pid != -1) { - worker.childTerminated(shared_from_this()); + worker.childTerminated(this); if (buildUser.enabled()) { /* If we're using a build user, then there is a tricky @@ -1412,7 +1410,7 @@ void DerivationGoal::buildDone() debug(format("builder process for ‘%1%’ finished") % drvPath); /* So the child is gone now. */ - worker.childTerminated(shared_from_this()); + worker.childTerminated(this); /* Close the read side of the logger pipe. */ if (hook) { @@ -1774,6 +1772,10 @@ void DerivationGoal::startBuilder() for (auto & i : varNames) env[i] = getEnv(i); } + /* Substitute output placeholders with the actual output paths. */ + for (auto & output : drv->outputs) + inputRewrites[hashPlaceholder(output.first)] = output.second.path; + /* The `exportReferencesGraph' feature allows the references graph to be passed to a builder. This attribute should be a list of pairs [name1 path1 name2 path2 ...]. The references graph of @@ -2418,7 +2420,7 @@ void DerivationGoal::runChild() /* Fill in the environment. */ Strings envStrs; for (auto & i : env) - envStrs.push_back(rewriteHashes(i.first + "=" + i.second, rewritesToTmp)); + envStrs.push_back(rewriteStrings(i.first + "=" + i.second, inputRewrites)); /* If we are running in `build-users' mode, then switch to the user we allocated above. Make sure that we drop all root @@ -2560,7 +2562,7 @@ void DerivationGoal::runChild() } for (auto & i : drv->args) - args.push_back(rewriteHashes(i, rewritesToTmp)); + args.push_back(rewriteStrings(i, inputRewrites)); restoreSIGPIPE(); @@ -2682,7 +2684,7 @@ void DerivationGoal::registerOutputs() /* Apply hash rewriting if necessary. */ bool rewritten = false; - if (!rewritesFromTmp.empty()) { + if (!outputRewrites.empty()) { printMsg(lvlError, format("warning: rewriting hashes in ‘%1%’; cross fingers") % path); /* Canonicalise first. This ensures that the path we're @@ -2694,7 +2696,7 @@ void DerivationGoal::registerOutputs() StringSink sink; dumpPath(actualPath, sink); deletePath(actualPath); - sink.s = make_ref<std::string>(rewriteHashes(*sink.s, rewritesFromTmp)); + sink.s = make_ref<std::string>(rewriteStrings(*sink.s, outputRewrites)); StringSource source(*sink.s); restorePath(actualPath, source); @@ -2910,7 +2912,7 @@ Path DerivationGoal::openLogFile() string baseName = baseNameOf(drvPath); /* Create a log file. */ - Path dir = (format("%1%/%2%/%3%/") % settings.nixLogDir % drvsLogDir % string(baseName, 0, 2)).str(); + Path dir = (format("%1%/%2%/%3%/") % worker.store.logDir % drvsLogDir % string(baseName, 0, 2)).str(); createDirs(dir); Path logFileName = (format("%1%/%2%%3%") @@ -3033,8 +3035,8 @@ Path DerivationGoal::addHashRewrite(const Path & path) Path p = worker.store.storeDir + "/" + h2 + string(path, worker.store.storeDir.size() + 33); deletePath(p); assert(path.size() == p.size()); - rewritesToTmp[h1] = h2; - rewritesFromTmp[h2] = h1; + inputRewrites[h1] = h2; + outputRewrites[h2] = h1; redirectedOutputs[path] = p; return p; } @@ -3140,8 +3142,9 @@ SubstitutionGoal::~SubstitutionGoal() { try { if (thr.joinable()) { + // FIXME: signal worker thread to quit. thr.join(); - //worker.childTerminated(shared_from_this()); // FIXME + worker.childTerminated(this); } } catch (...) { ignoreException(); @@ -3213,7 +3216,7 @@ void SubstitutionGoal::tryNext() /* Bail out early if this substituter lacks a valid signature. LocalStore::addToStore() also checks for this, but only after we've downloaded the path. */ - if (worker.store.requireSigs && !info->checkSignatures(worker.store.publicKeys)) { + if (worker.store.requireSigs && !info->checkSignatures(worker.store, worker.store.publicKeys)) { printMsg(lvlInfo, format("warning: substituter ‘%s’ does not have a valid signature for path ‘%s’") % sub->getUri() % storePath); tryNext(); @@ -3296,7 +3299,7 @@ void SubstitutionGoal::finished() trace("substitute finished"); thr.join(); - worker.childTerminated(shared_from_this()); + worker.childTerminated(this); try { promise.get_future().get(); @@ -3449,6 +3452,7 @@ void Worker::childStarted(GoalPtr goal, const set<int> & fds, { Child child; child.goal = goal; + child.goal2 = goal.get(); child.fds = fds; child.timeStarted = child.lastOutput = time(0); child.inBuildSlot = inBuildSlot; @@ -3458,10 +3462,10 @@ void Worker::childStarted(GoalPtr goal, const set<int> & fds, } -void Worker::childTerminated(GoalPtr goal, bool wakeSleepers) +void Worker::childTerminated(Goal * goal, bool wakeSleepers) { auto i = std::find_if(children.begin(), children.end(), - [&](const Child & child) { return child.goal.lock() == goal; }); + [&](const Child & child) { return child.goal2 == goal; }); assert(i != children.end()); if (i->inBuildSlot) { diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 7dcf71d468df..f051f10bd018 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -390,4 +390,11 @@ Sink & operator << (Sink & out, const BasicDerivation & drv) } +std::string hashPlaceholder(const std::string & outputName) +{ + // FIXME: memoize? + return "/" + printHash32(hashString(htSHA256, "nix-output:" + outputName)); +} + + } diff --git a/src/libstore/derivations.hh b/src/libstore/derivations.hh index 974de78c58d5..9717a81e469c 100644 --- a/src/libstore/derivations.hh +++ b/src/libstore/derivations.hh @@ -117,4 +117,6 @@ struct Sink; Source & readDerivation(Source & in, Store & store, BasicDerivation & drv); Sink & operator << (Sink & out, const BasicDerivation & drv); +std::string hashPlaceholder(const std::string & outputName); + } diff --git a/src/libstore/download.cc b/src/libstore/download.cc index 9cc433228141..5cb2b497a50a 100644 --- a/src/libstore/download.cc +++ b/src/libstore/download.cc @@ -8,6 +8,7 @@ #include <curl/curl.h> #include <iostream> +#include <thread> namespace nix { @@ -194,9 +195,17 @@ struct CurlDownloader : public Downloader if (res != CURLE_OK) { Error err = httpStatus == 404 ? NotFound : - httpStatus == 403 ? Forbidden : Misc; - throw DownloadError(err, format("unable to download ‘%1%’: %2% (%3%)") - % url % curl_easy_strerror(res) % res); + httpStatus == 403 ? Forbidden : + (httpStatus == 408 || httpStatus == 500 || httpStatus == 503 + || httpStatus == 504 || httpStatus == 522 || httpStatus == 524 + || res == CURLE_COULDNT_RESOLVE_HOST) ? Transient : + Misc; + if (res == CURLE_HTTP_RETURNED_ERROR && httpStatus != -1) + throw DownloadError(err, format("unable to download ‘%s’: HTTP error %d") + % url % httpStatus); + else + throw DownloadError(err, format("unable to download ‘%s’: %s (%d)") + % url % curl_easy_strerror(res) % res); } char *effectiveUrlCStr; @@ -211,15 +220,27 @@ struct CurlDownloader : public Downloader DownloadResult download(string url, const DownloadOptions & options) override { - DownloadResult res; - if (fetch(resolveUri(url), options)) { - res.cached = false; - res.data = data; - } else - res.cached = true; - res.effectiveUrl = effectiveUrl; - res.etag = etag; - return res; + size_t attempt = 0; + + while (true) { + try { + DownloadResult res; + if (fetch(resolveUri(url), options)) { + res.cached = false; + res.data = data; + } else + res.cached = true; + res.effectiveUrl = effectiveUrl; + res.etag = etag; + return res; + } catch (DownloadError & e) { + attempt++; + if (e.error != Transient || attempt >= options.tries) throw; + auto ms = options.baseRetryTimeMs * (1 << (attempt - 1)); + printMsg(lvlError, format("warning: %s; retrying in %d ms") % e.what() % ms); + std::this_thread::sleep_for(std::chrono::milliseconds(ms)); + } + } } }; @@ -228,7 +249,7 @@ ref<Downloader> makeDownloader() return make_ref<CurlDownloader>(); } -Path Downloader::downloadCached(ref<Store> store, const string & url_, bool unpack, const Hash & expectedHash) +Path Downloader::downloadCached(ref<Store> store, const string & url_, bool unpack, string name, const Hash & expectedHash) { string ignored; return downloadCached(store, url_, unpack, ignored, expectedHash); @@ -238,9 +259,10 @@ Path Downloader::downloadCached(ref<Store> store, const string & url_, bool unpa { auto url = resolveUri(url_); - string name; - auto p = url.rfind('/'); - if (p != string::npos) name = string(url, p + 1); + if (name == "") { + auto p = url.rfind('/'); + if (p != string::npos) name = string(url, p + 1); + } Path expectedStorePath; if (expectedHash) { diff --git a/src/libstore/download.hh b/src/libstore/download.hh index d17e14400f1a..cb7de6ef1d99 100644 --- a/src/libstore/download.hh +++ b/src/libstore/download.hh @@ -9,10 +9,12 @@ namespace nix { struct DownloadOptions { - string expectedETag; - bool verifyTLS{true}; - enum { yes, no, automatic } showProgress{yes}; - bool head{false}; + std::string expectedETag; + bool verifyTLS = true; + enum { yes, no, automatic } showProgress = yes; + bool head = false; + size_t tries = 1; + unsigned int baseRetryTimeMs = 100; }; struct DownloadResult @@ -29,7 +31,7 @@ struct Downloader { virtual DownloadResult download(string url, const DownloadOptions & options) = 0; - Path downloadCached(ref<Store> store, const string & url, bool unpack, + Path downloadCached(ref<Store> store, const string & url, bool unpack, string name = "", const Hash & expectedHash = Hash()); /* Need to overload because can't have an rvalue default value for non-const reference */ @@ -37,7 +39,7 @@ struct Downloader Path downloadCached(ref<Store> store, const string & url, bool unpack, string & effectiveUrl, const Hash & expectedHash = Hash()); - enum Error { NotFound, Forbidden, Misc }; + enum Error { NotFound, Forbidden, Misc, Transient }; }; ref<Downloader> makeDownloader(); diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index c12178e4028a..ecf81e8eb38e 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -69,7 +69,6 @@ void Settings::processEnvironment() nixDataDir = canonPath(getEnv("NIX_DATA_DIR", NIX_DATA_DIR)); nixLogDir = canonPath(getEnv("NIX_LOG_DIR", NIX_LOG_DIR)); nixStateDir = canonPath(getEnv("NIX_STATE_DIR", NIX_STATE_DIR)); - nixDBPath = getEnv("NIX_DB_DIR", nixStateDir + "/db"); nixConfDir = canonPath(getEnv("NIX_CONF_DIR", NIX_CONF_DIR)); nixLibexecDir = canonPath(getEnv("NIX_LIBEXEC_DIR", NIX_LIBEXEC_DIR)); nixBinDir = canonPath(getEnv("NIX_BIN_DIR", NIX_BIN_DIR)); @@ -77,7 +76,7 @@ void Settings::processEnvironment() // should be set with the other config options, but depends on nixLibexecDir #ifdef __APPLE__ - preBuildHook = nixLibexecDir + "/nix/resolve-system-dependencies.pl"; + preBuildHook = nixLibexecDir + "/nix/resolve-system-dependencies"; #endif } diff --git a/src/libstore/globals.hh b/src/libstore/globals.hh index 65f763ace3c7..3194193bc842 100644 --- a/src/libstore/globals.hh +++ b/src/libstore/globals.hh @@ -51,9 +51,6 @@ struct Settings { /* The directory where state is stored. */ Path nixStateDir; - /* The directory where we keep the SQLite database. */ - Path nixDBPath; - /* The directory where configuration files are stored. */ Path nixConfDir; diff --git a/src/libstore/http-binary-cache-store.cc b/src/libstore/http-binary-cache-store.cc index da80b636c76c..bdcd2fd3998b 100644 --- a/src/libstore/http-binary-cache-store.cc +++ b/src/libstore/http-binary-cache-store.cc @@ -58,6 +58,7 @@ protected: DownloadOptions options; options.showProgress = DownloadOptions::no; options.head = true; + options.tries = 5; downloader->download(cacheUri + "/" + path, options); return true; } catch (DownloadError & e) { @@ -79,6 +80,8 @@ protected: auto downloader(downloaders.get()); DownloadOptions options; options.showProgress = DownloadOptions::no; + options.tries = 5; + options.baseRetryTimeMs = 1000; try { return downloader->download(cacheUri + "/" + path, options).data; } catch (DownloadError & e) { diff --git a/src/libstore/local-fs-store.cc b/src/libstore/local-fs-store.cc index b1b9dc29e40d..4571a2211cd2 100644 --- a/src/libstore/local-fs-store.cc +++ b/src/libstore/local-fs-store.cc @@ -7,7 +7,9 @@ namespace nix { LocalFSStore::LocalFSStore(const Params & params) : Store(params) - , stateDir(get(params, "state", settings.nixStateDir)) + , rootDir(get(params, "root")) + , stateDir(canonPath(get(params, "state", rootDir != "" ? rootDir + "/nix/var/nix" : settings.nixStateDir))) + , logDir(canonPath(get(params, "log", rootDir != "" ? rootDir + "/nix/var/log/nix" : settings.nixLogDir))) { } @@ -21,7 +23,7 @@ struct LocalStoreAccessor : public FSAccessor { Path storePath = store->toStorePath(path); if (!store->isValidPath(storePath)) - throw Error(format("path ‘%1%’ is not a valid store path") % storePath); + throw InvalidPath(format("path ‘%1%’ is not a valid store path") % storePath); return store->getRealStoreDir() + std::string(path, store->storeDir.size()); } @@ -79,7 +81,7 @@ void LocalFSStore::narFromPath(const Path & path, Sink & sink) { if (!isValidPath(path)) throw Error(format("path ‘%s’ is not valid") % path); - dumpPath(path, sink); + dumpPath(getRealStoreDir() + std::string(path, storeDir.size()), sink); } } diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc index 96ce6a0d893b..10056f2f1fd8 100644 --- a/src/libstore/local-store.cc +++ b/src/libstore/local-store.cc @@ -38,8 +38,8 @@ namespace nix { LocalStore::LocalStore(const Params & params) : LocalFSStore(params) - , realStoreDir(get(params, "real", storeDir)) - , dbDir(get(params, "state", "") != "" ? get(params, "state", "") + "/db" : settings.nixDBPath) + , realStoreDir(get(params, "real", rootDir != "" ? rootDir + "/nix/store" : storeDir)) + , dbDir(stateDir + "/db") , linksDir(realStoreDir + "/.links") , reservedPath(dbDir + "/reserved") , schemaPath(dbDir + "/schema") @@ -181,17 +181,20 @@ LocalStore::LocalStore(const Params & params) if (curSchema < 8) { SQLiteTxn txn(state->db); - if (sqlite3_exec(state->db, "alter table ValidPaths add column ultimate integer", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "upgrading database schema"); - if (sqlite3_exec(state->db, "alter table ValidPaths add column sigs text", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "upgrading database schema"); + state->db.exec("alter table ValidPaths add column ultimate integer"); + state->db.exec("alter table ValidPaths add column sigs text"); txn.commit(); } if (curSchema < 9) { SQLiteTxn txn(state->db); - if (sqlite3_exec(state->db, "drop table FailedPaths", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "upgrading database schema"); + state->db.exec("drop table FailedPaths"); + txn.commit(); + } + + if (curSchema < 10) { + SQLiteTxn txn(state->db); + state->db.exec("alter table ValidPaths add column ca text"); txn.commit(); } @@ -204,13 +207,13 @@ LocalStore::LocalStore(const Params & params) /* Prepare SQL statements. */ state->stmtRegisterValidPath.create(state->db, - "insert into ValidPaths (path, hash, registrationTime, deriver, narSize, ultimate, sigs) values (?, ?, ?, ?, ?, ?, ?);"); + "insert into ValidPaths (path, hash, registrationTime, deriver, narSize, ultimate, sigs, ca) values (?, ?, ?, ?, ?, ?, ?, ?);"); state->stmtUpdatePathInfo.create(state->db, - "update ValidPaths set narSize = ?, hash = ?, ultimate = ?, sigs = ? where path = ?;"); + "update ValidPaths set narSize = ?, hash = ?, ultimate = ?, sigs = ?, ca = ? where path = ?;"); state->stmtAddReference.create(state->db, "insert or replace into Refs (referrer, reference) values (?, ?);"); state->stmtQueryPathInfo.create(state->db, - "select id, hash, registrationTime, deriver, narSize, ultimate, sigs from ValidPaths where path = ?;"); + "select id, hash, registrationTime, deriver, narSize, ultimate, sigs, ca from ValidPaths where path = ?;"); state->stmtQueryReferences.create(state->db, "select path from Refs join ValidPaths on reference = id where referrer = ?;"); state->stmtQueryReferrers.create(state->db, @@ -279,8 +282,7 @@ void LocalStore::openDB(State & state, bool create) if (sqlite3_busy_timeout(db, 60 * 60 * 1000) != SQLITE_OK) throwSQLiteError(db, "setting timeout"); - if (sqlite3_exec(db, "pragma foreign_keys = 1;", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(db, "enabling foreign keys"); + db.exec("pragma foreign_keys = 1"); /* !!! check whether sqlite has been built with foreign key support */ @@ -290,8 +292,7 @@ void LocalStore::openDB(State & state, bool create) all. This can cause database corruption if the system crashes. */ string syncMode = settings.fsyncMetadata ? "normal" : "off"; - if (sqlite3_exec(db, ("pragma synchronous = " + syncMode + ";").c_str(), 0, 0, 0) != SQLITE_OK) - throwSQLiteError(db, "setting synchronous mode"); + db.exec("pragma synchronous = " + syncMode); /* Set the SQLite journal mode. WAL mode is fastest, so it's the default. */ @@ -319,8 +320,7 @@ void LocalStore::openDB(State & state, bool create) const char * schema = #include "schema.sql.hh" ; - if (sqlite3_exec(db, (const char *) schema, 0, 0, 0) != SQLITE_OK) - throwSQLiteError(db, "initialising database schema"); + db.exec(schema); } } @@ -527,6 +527,7 @@ uint64_t LocalStore::addValidPath(State & state, (info.narSize, info.narSize != 0) (info.ultimate ? 1 : 0, info.ultimate) (concatStringsSep(" ", info.sigs), !info.sigs.empty()) + (info.ca, !info.ca.empty()) .exec(); uint64_t id = sqlite3_last_insert_rowid(state.db); @@ -609,6 +610,9 @@ std::shared_ptr<ValidPathInfo> LocalStore::queryPathInfoUncached(const Path & pa s = (const char *) sqlite3_column_text(state->stmtQueryPathInfo, 6); if (s) info->sigs = tokenizeString<StringSet>(s, " "); + s = (const char *) sqlite3_column_text(state->stmtQueryPathInfo, 7); + if (s) info->ca = s; + /* Get the references. */ auto useQueryReferences(state->stmtQueryReferences.use()(info->id)); @@ -628,6 +632,7 @@ void LocalStore::updatePathInfo(State & state, const ValidPathInfo & info) ("sha256:" + printHash(info.narHash)) (info.ultimate ? 1 : 0, info.ultimate) (concatStringsSep(" ", info.sigs), !info.sigs.empty()) + (info.ca, !info.ca.empty()) (info.path) .exec(); } @@ -755,7 +760,7 @@ Path LocalStore::queryPathFromHashPart(const string & hashPart) Path prefix = storeDir + "/" + hashPart; - return retrySQLite<Path>([&]() { + return retrySQLite<Path>([&]() -> std::string { auto state(_state.lock()); auto useQueryPathFromHashPart(state->stmtQueryPathFromHashPart.use()(prefix)); @@ -898,7 +903,7 @@ void LocalStore::addToStore(const ValidPathInfo & info, const std::string & nar, throw Error(format("hash mismatch importing path ‘%s’; expected hash ‘%s’, got ‘%s’") % info.path % info.narHash.to_string() % h.to_string()); - if (requireSigs && !dontCheckSigs && !info.checkSignatures(publicKeys)) + if (requireSigs && !dontCheckSigs && !info.checkSignatures(*this, publicKeys)) throw Error(format("cannot import path ‘%s’ because it lacks a valid signature") % info.path); addTempRoot(info.path); @@ -983,6 +988,7 @@ Path LocalStore::addToStoreFromDump(const string & dump, const string & name, info.narHash = hash.first; info.narSize = hash.second; info.ultimate = true; + info.ca = "fixed:" + (recursive ? (std::string) "r:" : "") + h.to_string(); registerValidPath(info); } @@ -1014,7 +1020,8 @@ Path LocalStore::addToStore(const string & name, const Path & _srcPath, Path LocalStore::addTextToStore(const string & name, const string & s, const PathSet & references, bool repair) { - Path dstPath = computeStorePathForText(name, s, references); + auto hash = hashString(htSHA256, s); + auto dstPath = makeTextPath(name, hash, references); addTempRoot(dstPath); @@ -1034,16 +1041,17 @@ Path LocalStore::addTextToStore(const string & name, const string & s, StringSink sink; dumpString(s, sink); - auto hash = hashString(htSHA256, *sink.s); + auto narHash = hashString(htSHA256, *sink.s); optimisePath(realPath); ValidPathInfo info; info.path = dstPath; - info.narHash = hash; + info.narHash = narHash; info.narSize = sink.s->size(); info.references = references; info.ultimate = true; + info.ca = "text:" + hash.to_string(); registerValidPath(info); } @@ -1282,9 +1290,7 @@ void LocalStore::upgradeStore7() void LocalStore::vacuumDB() { auto state(_state.lock()); - - if (sqlite3_exec(state->db, "vacuum;", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "vacuuming SQLite database"); + state->db.exec("vacuum"); } diff --git a/src/libstore/local-store.hh b/src/libstore/local-store.hh index 7bfc4ad34c3f..5b5960cf245f 100644 --- a/src/libstore/local-store.hh +++ b/src/libstore/local-store.hh @@ -17,8 +17,8 @@ namespace nix { /* Nix store and database schema version. Version 1 (or 0) was Nix <= 0.7. Version 2 was Nix 0.8 and 0.9. Version 3 is Nix 0.10. Version 4 is Nix 0.11. Version 5 is Nix 0.12-0.16. Version 6 is - Nix 1.0. Version 7 is Nix 1.3. Version 9 is 1.12. */ -const int nixSchemaVersion = 9; + Nix 1.0. Version 7 is Nix 1.3. Version 10 is 1.12. */ +const int nixSchemaVersion = 10; extern string drvsLogDir; diff --git a/src/libstore/nar-accessor.cc b/src/libstore/nar-accessor.cc index 8896862be149..ded19c05d2cd 100644 --- a/src/libstore/nar-accessor.cc +++ b/src/libstore/nar-accessor.cc @@ -27,7 +27,7 @@ struct NarIndexer : ParseSink, StringSource Path currentPath; std::string currentStart; - bool isExec; + bool isExec = false; NarIndexer(const std::string & nar) : StringSource(nar) { diff --git a/src/libstore/nar-info-disk-cache.cc b/src/libstore/nar-info-disk-cache.cc index 172a918ff453..d28ff42c7f23 100644 --- a/src/libstore/nar-info-disk-cache.cc +++ b/src/libstore/nar-info-disk-cache.cc @@ -78,21 +78,16 @@ public: Path dbPath = getCacheDir() + "/nix/binary-cache-v5.sqlite"; createDirs(dirOf(dbPath)); - if (sqlite3_open_v2(dbPath.c_str(), &state->db.db, - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0) != SQLITE_OK) - throw Error(format("cannot open store cache ‘%s’") % dbPath); + state->db = SQLite(dbPath); if (sqlite3_busy_timeout(state->db, 60 * 60 * 1000) != SQLITE_OK) throwSQLiteError(state->db, "setting timeout"); // We can always reproduce the cache. - if (sqlite3_exec(state->db, "pragma synchronous = off", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "making database asynchronous"); - if (sqlite3_exec(state->db, "pragma main.journal_mode = truncate", 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "setting journal mode"); + state->db.exec("pragma synchronous = off"); + state->db.exec("pragma main.journal_mode = truncate"); - if (sqlite3_exec(state->db, schema, 0, 0, 0) != SQLITE_OK) - throwSQLiteError(state->db, "initialising database schema"); + state->db.exec(schema); state->insertCache.create(state->db, "insert or replace into BinaryCaches(url, timestamp, storeDir, wantMassQuery, priority) values (?, ?, ?, ?, ?)"); diff --git a/src/libstore/nar-info.cc b/src/libstore/nar-info.cc index b0a8d77c2fba..201cac671a55 100644 --- a/src/libstore/nar-info.cc +++ b/src/libstore/nar-info.cc @@ -67,6 +67,10 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string & system = value; else if (name == "Sig") sigs.insert(value); + else if (name == "CA") { + if (!ca.empty()) corrupt(); + ca = value; + } pos = eol + 1; } @@ -101,6 +105,9 @@ std::string NarInfo::to_string() const for (auto sig : sigs) res += "Sig: " + sig + "\n"; + if (!ca.empty()) + res += "CA: " + ca + "\n"; + return res; } diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc index ab05c3844289..94075f3b9b39 100644 --- a/src/libstore/remote-store.cc +++ b/src/libstore/remote-store.cc @@ -94,6 +94,8 @@ ref<RemoteStore::Connection> RemoteStore::openConnection() conn->daemonVersion = readInt(conn->from); if (GET_PROTOCOL_MAJOR(conn->daemonVersion) != GET_PROTOCOL_MAJOR(PROTOCOL_VERSION)) throw Error("Nix daemon protocol version not supported"); + if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 10) + throw Error("the Nix daemon version is too old"); conn->to << PROTOCOL_VERSION; if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 14) { @@ -127,17 +129,13 @@ void RemoteStore::setOptions(ref<Connection> conn) << settings.tryFallback << verbosity << settings.maxBuildJobs - << settings.maxSilentTime; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 2) - conn->to << settings.useBuildHook; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 4) - conn->to << (settings.verboseBuild ? lvlError : lvlVomit) - << 0 // obsolete log type - << 0 /* obsolete print build trace */; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 6) - conn->to << settings.buildCores; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 10) - conn->to << settings.useSubstitutes; + << settings.maxSilentTime + << settings.useBuildHook + << (settings.verboseBuild ? lvlError : lvlVomit) + << 0 // obsolete log type + << 0 /* obsolete print build trace */ + << settings.buildCores + << settings.useSubstitutes; if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 12) { Settings::SettingsMap overrides = settings.getOverrides(); @@ -213,8 +211,6 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet & paths, auto conn(connections->get()); - if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 3) return; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 12) { for (auto & i : paths) { @@ -227,7 +223,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet & paths, if (info.deriver != "") assertStorePath(info.deriver); info.references = readStorePaths<PathSet>(*this, conn->from); info.downloadSize = readLongLong(conn->from); - info.narSize = GET_PROTOCOL_MINOR(conn->daemonVersion) >= 7 ? readLongLong(conn->from) : 0; + info.narSize = readLongLong(conn->from); infos[i] = info; } @@ -277,6 +273,7 @@ std::shared_ptr<ValidPathInfo> RemoteStore::queryPathInfoUncached(const Path & p if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 16) { info->ultimate = readInt(conn->from) != 0; info->sigs = readStrings<StringSet>(conn->from); + info->ca = readString(conn->from); } return info; } @@ -481,11 +478,11 @@ void RemoteStore::collectGarbage(const GCOptions & options, GCResults & results) { auto conn(connections->get()); - conn->to << wopCollectGarbage << options.action << options.pathsToDelete << options.ignoreLiveness - << options.maxFreed << 0; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 5) + conn->to + << wopCollectGarbage << options.action << options.pathsToDelete << options.ignoreLiveness + << options.maxFreed /* removed options */ - conn->to << 0 << 0; + << 0 << 0 << 0; conn->processStderr(); @@ -562,7 +559,7 @@ void RemoteStore::Connection::processStderr(Sink * sink, Source * source) } if (msg == STDERR_ERROR) { string error = readString(from); - unsigned int status = GET_PROTOCOL_MINOR(daemonVersion) >= 8 ? readInt(from) : 1; + unsigned int status = readInt(from); throw Error(format("%1%") % error, status); } else if (msg != STDERR_LAST) diff --git a/src/libstore/schema.sql b/src/libstore/schema.sql index 91878af1580d..09c71a2b8dd7 100644 --- a/src/libstore/schema.sql +++ b/src/libstore/schema.sql @@ -6,7 +6,8 @@ create table if not exists ValidPaths ( deriver text, narSize integer, ultimate integer, -- null implies "false" - sigs text -- space-separated + sigs text, -- space-separated + ca text -- if not null, an assertion that the path is content-addressed; see ValidPathInfo ); create table if not exists Refs ( diff --git a/src/libstore/sqlite.cc b/src/libstore/sqlite.cc index 816f9984d6eb..ea0b843f5752 100644 --- a/src/libstore/sqlite.cc +++ b/src/libstore/sqlite.cc @@ -35,6 +35,13 @@ namespace nix { throw SQLiteError(format("%1%: %2%") % f.str() % sqlite3_errmsg(db)); } +SQLite::SQLite(const Path & path) +{ + if (sqlite3_open_v2(path.c_str(), &db, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0) != SQLITE_OK) + throw Error(format("cannot open SQLite database ‘%s’") % path); +} + SQLite::~SQLite() { try { @@ -45,6 +52,12 @@ SQLite::~SQLite() } } +void SQLite::exec(const std::string & stmt) +{ + if (sqlite3_exec(db, stmt.c_str(), 0, 0, 0) != SQLITE_OK) + throwSQLiteError(db, format("executing SQLite statement ‘%s’") % stmt); +} + void SQLiteStmt::create(sqlite3 * db, const string & s) { checkInterrupt(); diff --git a/src/libstore/sqlite.hh b/src/libstore/sqlite.hh index d6b4a8d9117b..7c1ed538215c 100644 --- a/src/libstore/sqlite.hh +++ b/src/libstore/sqlite.hh @@ -13,10 +13,16 @@ namespace nix { /* RAII wrapper to close a SQLite database automatically. */ struct SQLite { - sqlite3 * db; - SQLite() { db = 0; } + sqlite3 * db = 0; + SQLite() { } + SQLite(const Path & path); + SQLite(const SQLite & from) = delete; + SQLite& operator = (const SQLite & from) = delete; + SQLite& operator = (SQLite && from) { db = from.db; from.db = 0; return *this; } ~SQLite(); operator sqlite3 * () { return db; } + + void exec(const std::string & stmt); }; /* RAII wrapper to create and destroy SQLite prepared statements. */ diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc index af002dcc8c33..5dd56f905d57 100644 --- a/src/libstore/store-api.cc +++ b/src/libstore/store-api.cc @@ -202,6 +202,22 @@ Path Store::makeFixedOutputPath(bool recursive, } +Path Store::makeTextPath(const string & name, const Hash & hash, + const PathSet & references) const +{ + assert(hash.type == htSHA256); + /* Stuff the references (if any) into the type. This is a bit + hacky, but we can't put them in `s' since that would be + ambiguous. */ + string type = "text"; + for (auto & i : references) { + type += ":"; + type += i; + } + return makeStorePath(type, hash, name); +} + + std::pair<Path, Hash> Store::computeStorePathForPath(const Path & srcPath, bool recursive, HashType hashAlgo, PathFilter & filter) const { @@ -215,16 +231,7 @@ std::pair<Path, Hash> Store::computeStorePathForPath(const Path & srcPath, Path Store::computeStorePathForText(const string & name, const string & s, const PathSet & references) const { - Hash hash = hashString(htSHA256, s); - /* Stuff the references (if any) into the type. This is a bit - hacky, but we can't put them in `s' since that would be - ambiguous. */ - string type = "text"; - for (auto & i : references) { - type += ":"; - type += i; - } - return makeStorePath(type, hash, name); + return makeTextPath(name, hashString(htSHA256, s), references); } @@ -432,9 +439,38 @@ void ValidPathInfo::sign(const SecretKey & secretKey) } -unsigned int ValidPathInfo::checkSignatures(const PublicKeys & publicKeys) const +bool ValidPathInfo::isContentAddressed(const Store & store) const +{ + auto warn = [&]() { + printMsg(lvlError, format("warning: path ‘%s’ claims to be content-addressed but isn't") % path); + }; + + if (hasPrefix(ca, "text:")) { + auto hash = parseHash(std::string(ca, 5)); + if (store.makeTextPath(storePathToName(path), hash, references) == path) + return true; + else + warn(); + } + + else if (hasPrefix(ca, "fixed:")) { + bool recursive = ca.compare(6, 2, "r:") == 0; + auto hash = parseHash(std::string(ca, recursive ? 8 : 6)); + if (store.makeFixedOutputPath(recursive, hash, storePathToName(path)) == path) + return true; + else + warn(); + } + + return false; +} + + +size_t ValidPathInfo::checkSignatures(const Store & store, const PublicKeys & publicKeys) const { - unsigned int good = 0; + if (isContentAddressed(store)) return maxSigs; + + size_t good = 0; for (auto & sig : sigs) if (checkSignature(publicKeys, sig)) good++; diff --git a/src/libstore/store-api.hh b/src/libstore/store-api.hh index 0b80312d6307..41fc58fc48e2 100644 --- a/src/libstore/store-api.hh +++ b/src/libstore/store-api.hh @@ -16,6 +16,13 @@ namespace nix { +struct BasicDerivation; +struct Derivation; +class FSAccessor; +class NarInfoDiskCache; +class Store; + + /* Size of the hash part of store paths, in base-32 characters. */ const size_t storePathHashLen = 32; // i.e. 160 bits @@ -109,6 +116,34 @@ struct ValidPathInfo StringSet sigs; // note: not necessarily verified + /* If non-empty, an assertion that the path is content-addressed, + i.e., that the store path is computed from a cryptographic hash + of the contents of the path, plus some other bits of data like + the "name" part of the path. Such a path doesn't need + signatures, since we don't have to trust anybody's claim that + the path is the output of a particular derivation. (In the + extensional store model, we have to trust that the *contents* + of an output path of a derivation were actually produced by + that derivation. In the intensional model, we have to trust + that a particular output path was produced by a derivation; the + path name then implies the contents.) + + Ideally, the content-addressability assertion would just be a + Boolean, and the store path would be computed from + ‘storePathToName(path)’, ‘narHash’ and ‘references’. However, + 1) we've accumulated several types of content-addressed paths + over the years; and 2) fixed-output derivations support + multiple hash algorithms and serialisation methods (flat file + vs NAR). Thus, ‘ca’ has one of the following forms: + + * ‘text:sha256:<sha256 hash of file contents>’: For paths + computed by makeTextPath() / addTextToStore(). + + * ‘fixed:<r?>:<ht>:<h>’: For paths computed by + makeFixedOutputPath() / addToStore(). + */ + std::string ca; + bool operator == (const ValidPathInfo & i) const { return @@ -117,19 +152,25 @@ struct ValidPathInfo && references == i.references; } - /* Return a fingerprint of the store path to be used in binary - cache signatures. It contains the store path, the base-32 - SHA-256 hash of the NAR serialisation of the path, the size of - the NAR, and the sorted references. The size field is strictly - speaking superfluous, but might prevent endless/excessive data - attacks. */ + /* Return a fingerprint of the store path to be used in binary + cache signatures. It contains the store path, the base-32 + SHA-256 hash of the NAR serialisation of the path, the size of + the NAR, and the sorted references. The size field is strictly + speaking superfluous, but might prevent endless/excessive data + attacks. */ std::string fingerprint() const; void sign(const SecretKey & secretKey); + /* Return true iff the path is verifiably content-addressed. */ + bool isContentAddressed(const Store & store) const; + + static const size_t maxSigs = std::numeric_limits<size_t>::max(); + /* Return the number of signatures on this .narinfo that were - produced by one of the specified keys. */ - unsigned int checkSignatures(const PublicKeys & publicKeys) const; + produced by one of the specified keys, or maxSigs if the path + is content-addressed. */ + size_t checkSignatures(const Store & store, const PublicKeys & publicKeys) const; /* Verify a single signature. */ bool checkSignature(const PublicKeys & publicKeys, const std::string & sig) const; @@ -169,12 +210,6 @@ struct BuildResult }; -struct BasicDerivation; -struct Derivation; -class FSAccessor; -class NarInfoDiskCache; - - class Store : public std::enable_shared_from_this<Store> { public: @@ -234,10 +269,12 @@ public: Path makeFixedOutputPath(bool recursive, const Hash & hash, const string & name) const; - /* This is the preparatory part of addToStore() and - addToStoreFixed(); it computes the store path to which srcPath - is to be copied. Returns the store path and the cryptographic - hash of the contents of srcPath. */ + Path makeTextPath(const string & name, const Hash & hash, + const PathSet & references) const; + + /* This is the preparatory part of addToStore(); it computes the + store path to which srcPath is to be copied. Returns the store + path and the cryptographic hash of the contents of srcPath. */ std::pair<Path, Hash> computeStorePathForPath(const Path & srcPath, bool recursive = true, HashType hashAlgo = htSHA256, PathFilter & filter = defaultPathFilter) const; @@ -491,7 +528,9 @@ protected: class LocalFSStore : public Store { public: + const Path rootDir; const Path stateDir; + const Path logDir; LocalFSStore(const Params & params); diff --git a/src/libutil/json.cc b/src/libutil/json.cc new file mode 100644 index 000000000000..ecc3fdfe514e --- /dev/null +++ b/src/libutil/json.cc @@ -0,0 +1,176 @@ +#include "json.hh" + +#include <iomanip> +#include <cstring> + +namespace nix { + +void toJSON(std::ostream & str, const char * start, const char * end) +{ + str << '"'; + for (auto i = start; i != end; i++) + if (*i == '\"' || *i == '\\') str << '\\' << *i; + else if (*i == '\n') str << "\\n"; + else if (*i == '\r') str << "\\r"; + else if (*i == '\t') str << "\\t"; + else if (*i >= 0 && *i < 32) + str << "\\u" << std::setfill('0') << std::setw(4) << std::hex << (uint16_t) *i << std::dec; + else str << *i; + str << '"'; +} + +void toJSON(std::ostream & str, const std::string & s) +{ + toJSON(str, s.c_str(), s.c_str() + s.size()); +} + +void toJSON(std::ostream & str, const char * s) +{ + if (!s) str << "null"; else toJSON(str, s, s + strlen(s)); +} + +void toJSON(std::ostream & str, unsigned long long n) +{ + str << n; +} + +void toJSON(std::ostream & str, unsigned long n) +{ + str << n; +} + +void toJSON(std::ostream & str, long n) +{ + str << n; +} + +void toJSON(std::ostream & str, double f) +{ + str << f; +} + +void toJSON(std::ostream & str, bool b) +{ + str << (b ? "true" : "false"); +} + +JSONWriter::JSONWriter(std::ostream & str, bool indent) + : state(new JSONState(str, indent)) +{ + state->stack.push_back(this); +} + +JSONWriter::JSONWriter(JSONState * state) + : state(state) +{ + state->stack.push_back(this); +} + +JSONWriter::~JSONWriter() +{ + assertActive(); + state->stack.pop_back(); + if (state->stack.empty()) delete state; +} + +void JSONWriter::comma() +{ + assertActive(); + if (first) { + first = false; + } else { + state->str << ','; + } + if (state->indent) indent(); +} + +void JSONWriter::indent() +{ + state->str << '\n' << std::string(state->depth * 2, ' '); +} + +void JSONList::open() +{ + state->depth++; + state->str << '['; +} + +JSONList::~JSONList() +{ + state->depth--; + if (state->indent && !first) indent(); + state->str << "]"; +} + +JSONList JSONList::list() +{ + comma(); + return JSONList(state); +} + +JSONObject JSONList::object() +{ + comma(); + return JSONObject(state); +} + +JSONPlaceholder JSONList::placeholder() +{ + comma(); + return JSONPlaceholder(state); +} + +void JSONObject::open() +{ + state->depth++; + state->str << '{'; +} + +JSONObject::~JSONObject() +{ + state->depth--; + if (state->indent && !first) indent(); + state->str << "}"; +} + +void JSONObject::attr(const std::string & s) +{ + comma(); + toJSON(state->str, s); + state->str << ':'; + if (state->indent) state->str << ' '; +} + +JSONList JSONObject::list(const std::string & name) +{ + attr(name); + return JSONList(state); +} + +JSONObject JSONObject::object(const std::string & name) +{ + attr(name); + return JSONObject(state); +} + +JSONPlaceholder JSONObject::placeholder(const std::string & name) +{ + attr(name); + return JSONPlaceholder(state); +} + +JSONList JSONPlaceholder::list() +{ + assertValid(); + first = false; + return JSONList(state); +} + +JSONObject JSONPlaceholder::object() +{ + assertValid(); + first = false; + return JSONObject(state); +} + +} diff --git a/src/libutil/json.hh b/src/libutil/json.hh new file mode 100644 index 000000000000..aec456845056 --- /dev/null +++ b/src/libutil/json.hh @@ -0,0 +1,184 @@ +#pragma once + +#include <iostream> +#include <vector> +#include <cassert> + +namespace nix { + +void toJSON(std::ostream & str, const char * start, const char * end); +void toJSON(std::ostream & str, const std::string & s); +void toJSON(std::ostream & str, const char * s); +void toJSON(std::ostream & str, unsigned long long n); +void toJSON(std::ostream & str, unsigned long n); +void toJSON(std::ostream & str, long n); +void toJSON(std::ostream & str, double f); +void toJSON(std::ostream & str, bool b); + +class JSONWriter +{ +protected: + + struct JSONState + { + std::ostream & str; + bool indent; + size_t depth = 0; + std::vector<JSONWriter *> stack; + JSONState(std::ostream & str, bool indent) : str(str), indent(indent) { } + ~JSONState() + { + assert(stack.empty()); + } + }; + + JSONState * state; + + bool first = true; + + JSONWriter(std::ostream & str, bool indent); + + JSONWriter(JSONState * state); + + ~JSONWriter(); + + void assertActive() + { + assert(!state->stack.empty() && state->stack.back() == this); + } + + void comma(); + + void indent(); +}; + +class JSONObject; +class JSONPlaceholder; + +class JSONList : JSONWriter +{ +private: + + friend class JSONObject; + friend class JSONPlaceholder; + + void open(); + + JSONList(JSONState * state) + : JSONWriter(state) + { + open(); + } + +public: + + JSONList(std::ostream & str, bool indent = false) + : JSONWriter(str, indent) + { + open(); + } + + ~JSONList(); + + template<typename T> + JSONList & elem(const T & v) + { + comma(); + toJSON(state->str, v); + return *this; + } + + JSONList list(); + + JSONObject object(); + + JSONPlaceholder placeholder(); +}; + +class JSONObject : JSONWriter +{ +private: + + friend class JSONList; + friend class JSONPlaceholder; + + void open(); + + JSONObject(JSONState * state) + : JSONWriter(state) + { + open(); + } + + void attr(const std::string & s); + +public: + + JSONObject(std::ostream & str, bool indent = false) + : JSONWriter(str, indent) + { + open(); + } + + ~JSONObject(); + + template<typename T> + JSONObject & attr(const std::string & name, const T & v) + { + attr(name); + toJSON(state->str, v); + return *this; + } + + JSONList list(const std::string & name); + + JSONObject object(const std::string & name); + + JSONPlaceholder placeholder(const std::string & name); +}; + +class JSONPlaceholder : JSONWriter +{ + +private: + + friend class JSONList; + friend class JSONObject; + + JSONPlaceholder(JSONState * state) + : JSONWriter(state) + { + } + + void assertValid() + { + assertActive(); + assert(first); + } + +public: + + JSONPlaceholder(std::ostream & str, bool indent = false) + : JSONWriter(str, indent) + { + } + + ~JSONPlaceholder() + { + assert(!first || std::uncaught_exception()); + } + + template<typename T> + void write(const T & v) + { + assertValid(); + first = false; + toJSON(state->str, v); + } + + JSONList list(); + + JSONObject object(); +}; + +} diff --git a/src/nix-daemon/nix-daemon.cc b/src/nix-daemon/nix-daemon.cc index 6e0d869f4c87..f2b59c84a858 100644 --- a/src/nix-daemon/nix-daemon.cc +++ b/src/nix-daemon/nix-daemon.cc @@ -413,12 +413,10 @@ static void performOp(ref<LocalStore> store, bool trusted, unsigned int clientVe options.pathsToDelete = readStorePaths<PathSet>(*store, from); options.ignoreLiveness = readInt(from); options.maxFreed = readLongLong(from); - readInt(from); // obsolete field - if (GET_PROTOCOL_MINOR(clientVersion) >= 5) { - /* removed options */ - readInt(from); - readInt(from); - } + // obsolete fields + readInt(from); + readInt(from); + readInt(from); GCResults results; @@ -440,17 +438,12 @@ static void performOp(ref<LocalStore> store, bool trusted, unsigned int clientVe verbosity = (Verbosity) readInt(from); settings.set("build-max-jobs", std::to_string(readInt(from))); settings.set("build-max-silent-time", std::to_string(readInt(from))); - if (GET_PROTOCOL_MINOR(clientVersion) >= 2) - settings.useBuildHook = readInt(from) != 0; - if (GET_PROTOCOL_MINOR(clientVersion) >= 4) { - settings.verboseBuild = lvlError == (Verbosity) readInt(from); - readInt(from); // obsolete logType - readInt(from); // obsolete printBuildTrace - } - if (GET_PROTOCOL_MINOR(clientVersion) >= 6) - settings.set("build-cores", std::to_string(readInt(from))); - if (GET_PROTOCOL_MINOR(clientVersion) >= 10) - settings.set("build-use-substitutes", readInt(from) ? "true" : "false"); + settings.useBuildHook = readInt(from) != 0; + settings.verboseBuild = lvlError == (Verbosity) readInt(from); + readInt(from); // obsolete logType + readInt(from); // obsolete printBuildTrace + settings.set("build-cores", std::to_string(readInt(from))); + settings.set("build-use-substitutes", readInt(from) ? "true" : "false"); if (GET_PROTOCOL_MINOR(clientVersion) >= 12) { unsigned int n = readInt(from); for (unsigned int i = 0; i < n; i++) { @@ -478,9 +471,7 @@ static void performOp(ref<LocalStore> store, bool trusted, unsigned int clientVe if (i == infos.end()) to << 0; else { - to << 1 << i->second.deriver << i->second.references << i->second.downloadSize; - if (GET_PROTOCOL_MINOR(clientVersion) >= 7) - to << i->second.narSize; + to << 1 << i->second.deriver << i->second.references << i->second.downloadSize << i->second.narSize; } break; } @@ -524,7 +515,8 @@ static void performOp(ref<LocalStore> store, bool trusted, unsigned int clientVe << info->registrationTime << info->narSize; if (GET_PROTOCOL_MINOR(clientVersion) >= 16) { to << info->ultimate - << info->sigs; + << info->sigs + << info->ca; } } else { assert(GET_PROTOCOL_MINOR(clientVersion) >= 17); @@ -585,11 +577,13 @@ static void processConnection(bool trusted) to.flush(); unsigned int clientVersion = readInt(from); + if (clientVersion < 0x10a) + throw Error("the Nix client version is too old"); + if (GET_PROTOCOL_MINOR(clientVersion) >= 14 && readInt(from)) setAffinityTo(readInt(from)); - if (GET_PROTOCOL_MINOR(clientVersion) >= 11) - readInt(from); // obsolete reserveSpace + readInt(from); // obsolete reserveSpace /* Send startup error messages to the client. */ startWork(); @@ -636,10 +630,10 @@ static void processConnection(bool trusted) during addTextToStore() / importPath(). If that happens, just send the error message and exit. */ bool errorAllowed = canSendStderr; - stopWork(false, e.msg(), GET_PROTOCOL_MINOR(clientVersion) >= 8 ? e.status : 0); + stopWork(false, e.msg(), e.status); if (!errorAllowed) throw; } catch (std::bad_alloc & e) { - stopWork(false, "Nix daemon out of memory", GET_PROTOCOL_MINOR(clientVersion) >= 8 ? 1 : 0); + stopWork(false, "Nix daemon out of memory", 1); throw; } @@ -653,7 +647,7 @@ static void processConnection(bool trusted) printMsg(lvlDebug, format("%1% operations") % opCount); } catch (Error & e) { - stopWork(false, e.msg(), GET_PROTOCOL_MINOR(clientVersion) >= 8 ? 1 : 0); + stopWork(false, e.msg(), 1); to.flush(); return; } diff --git a/src/nix-env/nix-env.cc b/src/nix-env/nix-env.cc index 3f0486bb6541..6a557e8ac9db 100644 --- a/src/nix-env/nix-env.cc +++ b/src/nix-env/nix-env.cc @@ -10,6 +10,7 @@ #include "store-api.hh" #include "user-env.hh" #include "util.hh" +#include "json.hh" #include "value-to-json.hh" #include "xml-writer.hh" @@ -128,9 +129,8 @@ static void getAllExprs(EvalState & state, } attrs.insert(attrName); /* Load the expression on demand. */ - Value & vFun(*state.allocValue()); + Value & vFun = state.getBuiltin("import"); Value & vArg(*state.allocValue()); - state.getBuiltin("import", vFun); mkString(vArg, path2); if (v.attrs->size() == v.attrs->capacity()) throw Error(format("too many Nix expressions in directory ‘%1%’") % path); @@ -861,26 +861,24 @@ static VersionDiff compareVersionAgainstSet( static void queryJSON(Globals & globals, vector<DrvInfo> & elems) { - JSONObject topObj(cout); + JSONObject topObj(cout, true); for (auto & i : elems) { - topObj.attr(i.attrPath); - JSONObject pkgObj(cout); + JSONObject pkgObj = topObj.object(i.attrPath); pkgObj.attr("name", i.name); pkgObj.attr("system", i.system); - pkgObj.attr("meta"); - JSONObject metaObj(cout); + JSONObject metaObj = pkgObj.object("meta"); StringSet metaNames = i.queryMetaNames(); for (auto & j : metaNames) { - metaObj.attr(j); + auto placeholder = metaObj.placeholder(j); Value * v = i.queryMeta(j); if (!v) { printMsg(lvlError, format("derivation ‘%1%’ has invalid meta attribute ‘%2%’") % i.name % j); - cout << "null"; + placeholder.write(nullptr); } else { PathSet context; - printValueAsJSON(*globals.state, true, *v, cout, context); + printValueAsJSON(*globals.state, true, *v, placeholder, context); } } } diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc index 8532101a174d..e8b56f929b13 100644 --- a/src/nix-store/nix-store.cc +++ b/src/nix-store/nix-store.cc @@ -483,6 +483,10 @@ static void opReadLog(Strings opFlags, Strings opArgs) RunPager pager; + // FIXME: move getting logs into Store. + auto store2 = std::dynamic_pointer_cast<LocalFSStore>(store); + if (!store2) throw Error(format("store ‘%s’ does not support reading logs") % store->getUri()); + for (auto & i : opArgs) { Path path = useDeriver(store->followLinksToStorePath(i)); @@ -493,8 +497,8 @@ static void opReadLog(Strings opFlags, Strings opArgs) Path logPath = j == 0 - ? (format("%1%/%2%/%3%/%4%") % settings.nixLogDir % drvsLogDir % string(baseName, 0, 2) % string(baseName, 2)).str() - : (format("%1%/%2%/%3%") % settings.nixLogDir % drvsLogDir % baseName).str(); + ? (format("%1%/%2%/%3%/%4%") % store2->logDir % drvsLogDir % string(baseName, 0, 2) % string(baseName, 2)).str() + : (format("%1%/%2%/%3%") % store2->logDir % drvsLogDir % baseName).str(); Path logBz2Path = logPath + ".bz2"; if (pathExists(logPath)) { diff --git a/src/nix/installables.cc b/src/nix/installables.cc index 6257c7679af9..8341bbc5a3a4 100644 --- a/src/nix/installables.cc +++ b/src/nix/installables.cc @@ -9,6 +9,41 @@ namespace nix { +Value * MixInstallables::buildSourceExpr(EvalState & state) +{ + Value * vRoot = state.allocValue(); + + if (file != "") { + Expr * e = state.parseExprFromFile(resolveExprPath(lookupFileArg(state, file))); + state.eval(e, *vRoot); + } + + else { + + /* Construct the installation source from $NIX_PATH. */ + + auto searchPath = state.getSearchPath(); + + state.mkAttrs(*vRoot, searchPath.size()); + + std::unordered_set<std::string> seen; + + for (auto & i : searchPath) { + if (i.first == "") continue; + if (seen.count(i.first)) continue; + seen.insert(i.first); + if (!pathExists(i.second)) continue; + mkApp(*state.allocAttr(*vRoot, state.symbols.create(i.first)), + state.getBuiltin("import"), + mkString(*state.allocValue(), i.second)); + } + + vRoot->attrs->sort(); + } + + return vRoot; +} + UserEnvElems MixInstallables::evalInstallables(ref<Store> store) { UserEnvElems res; @@ -46,15 +81,12 @@ UserEnvElems MixInstallables::evalInstallables(ref<Store> store) EvalState state({}, store); - Expr * e = state.parseExprFromFile(resolveExprPath(lookupFileArg(state, file))); - - Value vRoot; - state.eval(e, vRoot); + auto vRoot = buildSourceExpr(state); std::map<string, string> autoArgs_; Bindings & autoArgs(*evalAutoArgs(state, autoArgs_)); - Value & v(*findAlongAttrPath(state, installable, autoArgs, vRoot)); + Value & v(*findAlongAttrPath(state, installable, autoArgs, *vRoot)); state.forceValue(v); DrvInfos drvs; diff --git a/src/nix/installables.hh b/src/nix/installables.hh index 5eb897d46148..a58f7dc59bb4 100644 --- a/src/nix/installables.hh +++ b/src/nix/installables.hh @@ -21,10 +21,13 @@ struct UserEnvElem typedef std::vector<UserEnvElem> UserEnvElems; +struct Value; +class EvalState; + struct MixInstallables : virtual Args { Strings installables; - Path file = "<nixpkgs>"; + Path file; MixInstallables() { @@ -33,6 +36,13 @@ struct MixInstallables : virtual Args } UserEnvElems evalInstallables(ref<Store> store); + + /* Return a value representing the Nix expression from which we + are installing. This is either the file specified by ‘--file’, + or an attribute set constructed from $NIX_PATH, e.g. ‘{ nixpkgs + = import ...; bla = import ...; }’. */ + Value * buildSourceExpr(EvalState & state); + }; } diff --git a/src/nix/path-info.cc b/src/nix/path-info.cc index c61fe7ff1e00..d8b6232d47ca 100644 --- a/src/nix/path-info.cc +++ b/src/nix/path-info.cc @@ -1,6 +1,7 @@ #include "command.hh" #include "shared.hh" #include "store-api.hh" +#include "json.hh" #include <iomanip> #include <algorithm> @@ -12,12 +13,14 @@ struct CmdPathInfo : StorePathsCommand bool showSize = false; bool showClosureSize = false; bool showSigs = false; + bool json = false; CmdPathInfo() { mkFlag('s', "size", "print size of the NAR dump of each path", &showSize); mkFlag('S', "closure-size", "print sum size of the NAR dumps of the closure of each path", &showClosureSize); mkFlag(0, "sigs", "show signatures", &showSigs); + mkFlag(0, "json", "produce JSON output", &json); } std::string name() override @@ -41,6 +44,10 @@ struct CmdPathInfo : StorePathsCommand "To check the existence of a path in a binary cache:", "nix path-info -r /nix/store/7qvk5c91...-geeqie-1.1 --store https://cache.nixos.org/" }, + Example{ + "To print the 10 most recently added paths (using --json and the jq(1) command):", + "nix path-info --all --json | jq -r 'sort_by(.registrationTime)[-11:-1][].path'" + }, }; } @@ -50,35 +57,85 @@ struct CmdPathInfo : StorePathsCommand for (auto & storePath : storePaths) pathLen = std::max(pathLen, storePath.size()); - for (auto storePath : storePaths) { - auto info = store->queryPathInfo(storePath); - storePath = info->path; // FIXME: screws up padding + auto getClosureSize = [&](const Path & storePath) -> unsigned long long { + unsigned long long totalSize = 0; + PathSet closure; + store->computeFSClosure(storePath, closure, false, false); + for (auto & p : closure) + totalSize += store->queryPathInfo(p)->narSize; + return totalSize; + }; - std::cout << storePath << std::string(std::max(0, (int) pathLen - (int) storePath.size()), ' '); + if (json) { + JSONList jsonRoot(std::cout, true); - if (showSize) { - std::cout << '\t' << std::setw(11) << info->narSize; - } + for (auto storePath : storePaths) { + auto info = store->queryPathInfo(storePath); + storePath = info->path; + + auto jsonPath = jsonRoot.object(); + jsonPath + .attr("path", storePath) + .attr("narHash", info->narHash.to_string()) + .attr("narSize", info->narSize); + + if (showClosureSize) + jsonPath.attr("closureSize", getClosureSize(storePath)); + + if (info->deriver != "") + jsonPath.attr("deriver", info->deriver); + + { + auto jsonRefs = jsonPath.list("references"); + for (auto & ref : info->references) + jsonRefs.elem(ref); + } + + if (info->registrationTime) + jsonPath.attr("registrationTime", info->registrationTime); + + if (info->ultimate) + jsonPath.attr("ultimate", info->ultimate); - if (showClosureSize) { - size_t totalSize = 0; - PathSet closure; - store->computeFSClosure(storePath, closure, false, false); - for (auto & p : closure) - totalSize += store->queryPathInfo(p)->narSize; - std::cout << '\t' << std::setw(11) << totalSize; + if (info->ca != "") + jsonPath.attr("ca", info->ca); + + if (!info->sigs.empty()) { + auto jsonSigs = jsonPath.list("signatures"); + for (auto & sig : info->sigs) + jsonSigs.elem(sig); + } } + } + + else { + + for (auto storePath : storePaths) { + auto info = store->queryPathInfo(storePath); + storePath = info->path; // FIXME: screws up padding + + std::cout << storePath << std::string(std::max(0, (int) pathLen - (int) storePath.size()), ' '); - if (showSigs) { - std::cout << '\t'; - Strings ss; - if (info->ultimate) ss.push_back("ultimate"); - for (auto & sig : info->sigs) ss.push_back(sig); - std::cout << concatStringsSep(" ", ss); + if (showSize) + std::cout << '\t' << std::setw(11) << info->narSize; + + if (showClosureSize) + std::cout << '\t' << std::setw(11) << getClosureSize(storePath); + + if (showSigs) { + std::cout << '\t'; + Strings ss; + if (info->ultimate) ss.push_back("ultimate"); + if (info->ca != "") ss.push_back("ca:" + info->ca); + for (auto & sig : info->sigs) ss.push_back(sig); + std::cout << concatStringsSep(" ", ss); + } + + std::cout << std::endl; } - std::cout << std::endl; } + } }; diff --git a/src/nix/verify.cc b/src/nix/verify.cc index fd904f465687..f2b6acdfbf0b 100644 --- a/src/nix/verify.cc +++ b/src/nix/verify.cc @@ -116,12 +116,16 @@ struct CmdVerify : StorePathsCommand } }; + if (info->isContentAddressed(*store)) validSigs = ValidPathInfo::maxSigs; + doSigs(info->sigs); for (auto & store2 : substituters) { if (validSigs >= actualSigsNeeded) break; try { - doSigs(store2->queryPathInfo(info->path)->sigs); + auto info2 = store2->queryPathInfo(info->path); + if (info2->isContentAddressed(*store)) validSigs = ValidPathInfo::maxSigs; + doSigs(info2->sigs); } catch (InvalidPath &) { } catch (Error & e) { printMsg(lvlError, format(ANSI_RED "error:" ANSI_NORMAL " %s") % e.what()); diff --git a/src/resolve-system-dependencies/local.mk b/src/resolve-system-dependencies/local.mk new file mode 100644 index 000000000000..8792a4a252fa --- /dev/null +++ b/src/resolve-system-dependencies/local.mk @@ -0,0 +1,11 @@ +ifeq ($(OS), Darwin) + programs += resolve-system-dependencies +endif + +resolve-system-dependencies_DIR := $(d) + +resolve-system-dependencies_INSTALL_DIR := $(libexecdir)/nix + +resolve-system-dependencies_LIBS := libstore libmain libutil libformat + +resolve-system-dependencies_SOURCES := $(d)/resolve-system-dependencies.cc diff --git a/src/resolve-system-dependencies/resolve-system-dependencies.cc b/src/resolve-system-dependencies/resolve-system-dependencies.cc new file mode 100644 index 000000000000..a5f0cd7b3b70 --- /dev/null +++ b/src/resolve-system-dependencies/resolve-system-dependencies.cc @@ -0,0 +1,194 @@ +#include "derivations.hh" +#include "globals.hh" +#include "shared.hh" +#include "store-api.hh" +#include <sys/utsname.h> +#include <algorithm> +#include <iostream> +#include <fstream> +#include <sys/mman.h> +#include <fcntl.h> +#include <mach-o/loader.h> +#include <mach-o/swap.h> + +#define DO_SWAP(x, y) ((x) ? OSSwapInt32(y) : (y)) + +using namespace nix; + +static auto cacheDir = Path{}; + +Path resolveCacheFile(Path lib) { + std::replace(lib.begin(), lib.end(), '/', '%'); + return cacheDir + "/" + lib; +} + +std::set<string> readCacheFile(const Path & file) { + return tokenizeString<set<string>>(readFile(file), "\n"); +} + +void writeCacheFile(const Path & file, std::set<string> & deps) { + std::ofstream fp; + fp.open(file); + for (auto & d : deps) { + fp << d << "\n"; + } + fp.close(); +} + +std::string findDylibName(bool should_swap, ptrdiff_t dylib_command_start) { + struct dylib_command *dylc = (struct dylib_command*)dylib_command_start; + return std::string((char*)(dylib_command_start + DO_SWAP(should_swap, dylc->dylib.name.offset))); +} + +std::set<std::string> runResolver(const Path & filename) { + int fd = open(filename.c_str(), O_RDONLY); + struct stat s; + fstat(fd, &s); + void *obj = mmap(NULL, s.st_size, PROT_READ, MAP_SHARED, fd, 0); + + ptrdiff_t mach64_offset = 0; + + uint32_t magic = ((struct mach_header_64*)obj)->magic; + if(magic == FAT_CIGAM || magic == FAT_MAGIC) { + bool should_swap = magic == FAT_CIGAM; + uint32_t narches = DO_SWAP(should_swap, ((struct fat_header*)obj)->nfat_arch); + + for(uint32_t iter = 0; iter < narches; iter++) { + ptrdiff_t header_offset = (ptrdiff_t)obj + sizeof(struct fat_header) * (iter + 1); + struct fat_arch* arch = (struct fat_arch*)header_offset; + if(DO_SWAP(should_swap, arch->cputype) == CPU_TYPE_X86_64) { + mach64_offset = (ptrdiff_t)DO_SWAP(should_swap, arch->offset); + break; + } + } + if (mach64_offset == 0) { + printMsg(lvlError, format("Could not find any mach64 blobs in file ‘%1%’, continuing...") % filename); + return std::set<string>(); + } + } else if (magic == MH_MAGIC_64 || magic == MH_CIGAM_64) { + mach64_offset = 0; + } else { + printMsg(lvlError, format("Object file has unknown magic number ‘%1%’, skipping it...") % magic); + return std::set<string>(); + } + + ptrdiff_t mach_header_offset = (ptrdiff_t)obj + mach64_offset; + struct mach_header_64 *m_header = (struct mach_header_64 *)mach_header_offset; + + bool should_swap = magic == MH_CIGAM_64; + ptrdiff_t cmd_offset = mach_header_offset + sizeof(struct mach_header_64); + + std::set<string> libs; + for(uint32_t i = 0; i < DO_SWAP(should_swap, m_header->ncmds); i++) { + struct load_command *cmd = (struct load_command*)cmd_offset; + switch(DO_SWAP(should_swap, cmd->cmd)) { + case LC_LOAD_UPWARD_DYLIB: + case LC_LOAD_DYLIB: + case LC_REEXPORT_DYLIB: + libs.insert(findDylibName(should_swap, cmd_offset)); + break; + } + cmd_offset += DO_SWAP(should_swap, cmd->cmdsize); + } + + return libs; +} + +bool isSymlink(const Path & path) { + struct stat st; + if(lstat(path.c_str(), &st)) + throw SysError(format("getting attributes of path ‘%1%’") % path); + + return S_ISLNK(st.st_mode); +} + +Path resolveSymlink(const Path & path) { + char buf[PATH_MAX]; + ssize_t len = readlink(path.c_str(), buf, sizeof(buf) - 1); + if(len != -1) { + buf[len] = 0; + return Path(buf); + } else { + throw SysError(format("readlink('%1%')") % path); + } +} + +std::set<string> resolveTree(const Path & path, PathSet & deps) { + std::set<string> results; + if(deps.find(path) != deps.end()) { + return std::set<string>(); + } + deps.insert(path); + for (auto & lib : runResolver(path)) { + results.insert(lib); + for (auto & p : resolveTree(lib, deps)) { + results.insert(p); + } + } + return results; +} + +std::set<string> getPath(const Path & path) { + Path cacheFile = resolveCacheFile(path); + if(pathExists(cacheFile)) { + return readCacheFile(cacheFile); + } + + std::set<string> deps; + std::set<string> paths; + paths.insert(path); + + Path next_path = Path(path); + while(isSymlink(next_path)) { + next_path = resolveSymlink(next_path); + paths.insert(next_path); + } + + for(auto & t : resolveTree(next_path, deps)) { + paths.insert(t); + } + + writeCacheFile(cacheFile, paths); + + return paths; +} + +int main(int argc, char ** argv) { + return handleExceptions(argv[0], [&]() { + initNix(); + + struct utsname _uname; + + uname(&_uname); + + auto cacheParentDir = (format("%1%/dependency-maps") % settings.nixStateDir).str(); + + cacheDir = (format("%1%/%2%-%3%-%4%") + % cacheParentDir + % _uname.machine + % _uname.sysname + % _uname.release).str(); + + mkdir(cacheParentDir.c_str(), 0755); + mkdir(cacheDir.c_str(), 0755); + + auto store = openStore(); + + auto drv = store->derivationFromPath(Path(argv[1])); + Strings impurePaths = tokenizeString<Strings>(get(drv.env, "__impureHostDeps")); + + std::set<string> all_paths; + + for (auto & path : impurePaths) { + for(auto & p : getPath(path)) { + all_paths.insert(p); + } + } + + std::cout << "extra-chroot-dirs" << std::endl; + for(auto & path : all_paths) { + std::cout << path << std::endl; + } + std::cout << std::endl; + }); +} |