about summary refs log tree commit diff
path: root/third_party/nix/src
diff options
context:
space:
mode:
Diffstat (limited to 'third_party/nix/src')
-rw-r--r--third_party/nix/src/build-remote/build-remote.cc2
-rw-r--r--third_party/nix/src/libexpr/attr-path.cc2
-rw-r--r--third_party/nix/src/libexpr/eval.cc25
-rw-r--r--third_party/nix/src/libexpr/get-drvs.cc17
-rw-r--r--third_party/nix/src/libexpr/get-drvs.hh2
-rw-r--r--third_party/nix/src/libexpr/json-to-value.cc4
-rw-r--r--third_party/nix/src/libexpr/names.cc5
-rw-r--r--third_party/nix/src/libexpr/nixexpr.cc2
-rw-r--r--third_party/nix/src/libexpr/primops.cc12
-rw-r--r--third_party/nix/src/libmain/shared.cc13
-rw-r--r--third_party/nix/src/libmain/stack.cc10
-rw-r--r--third_party/nix/src/libstore/binary-cache-store.cc4
-rw-r--r--third_party/nix/src/libstore/build.cc101
-rw-r--r--third_party/nix/src/libstore/derivations.cc2
-rw-r--r--third_party/nix/src/libstore/download.cc14
-rw-r--r--third_party/nix/src/libstore/export-import.cc2
-rw-r--r--third_party/nix/src/libstore/gc.cc7
-rw-r--r--third_party/nix/src/libstore/http-binary-cache-store.cc8
-rw-r--r--third_party/nix/src/libstore/legacy-ssh-store.cc2
-rw-r--r--third_party/nix/src/libstore/local-binary-cache-store.cc8
-rw-r--r--third_party/nix/src/libstore/local-store.cc27
-rw-r--r--third_party/nix/src/libstore/misc.cc2
-rw-r--r--third_party/nix/src/libstore/nar-accessor.cc3
-rw-r--r--third_party/nix/src/libstore/nar-info-disk-cache.cc24
-rw-r--r--third_party/nix/src/libstore/optimise-store.cc7
-rw-r--r--third_party/nix/src/libstore/parsed-derivations.cc6
-rw-r--r--third_party/nix/src/libstore/pathlocks.cc4
-rw-r--r--third_party/nix/src/libstore/profiles.cc7
-rw-r--r--third_party/nix/src/libstore/references.cc10
-rw-r--r--third_party/nix/src/libstore/remote-store.cc18
-rw-r--r--third_party/nix/src/libstore/sqlite.cc18
-rw-r--r--third_party/nix/src/libstore/ssh-store.cc4
-rw-r--r--third_party/nix/src/libstore/ssh.cc6
-rw-r--r--third_party/nix/src/libstore/ssh.hh2
-rw-r--r--third_party/nix/src/libstore/store-api.cc13
-rw-r--r--third_party/nix/src/libutil/archive.cc16
-rw-r--r--third_party/nix/src/libutil/compression.cc12
-rw-r--r--third_party/nix/src/libutil/config.cc15
-rw-r--r--third_party/nix/src/libutil/config.hh4
-rw-r--r--third_party/nix/src/libutil/serialise.cc5
-rw-r--r--third_party/nix/src/libutil/util.cc24
-rw-r--r--third_party/nix/src/libutil/util.hh2
-rw-r--r--third_party/nix/src/libutil/xml-writer.cc5
-rw-r--r--third_party/nix/src/nix-build/nix-build.cc2
-rw-r--r--third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc42
-rw-r--r--third_party/nix/src/nix-daemon/nix-daemon.cc47
-rw-r--r--third_party/nix/src/nix-env/nix-env.cc23
-rw-r--r--third_party/nix/src/nix-store/nix-store.cc23
-rw-r--r--third_party/nix/src/nix/command.cc9
-rw-r--r--third_party/nix/src/nix/command.hh2
-rw-r--r--third_party/nix/src/nix/installables.cc12
-rw-r--r--third_party/nix/src/nix/legacy.cc2
-rw-r--r--third_party/nix/src/nix/log.cc2
-rw-r--r--third_party/nix/src/nix/main.cc2
-rw-r--r--third_party/nix/src/nix/optimise-store.cc2
-rw-r--r--third_party/nix/src/nix/repl.cc8
-rw-r--r--third_party/nix/src/nix/run.cc11
-rw-r--r--third_party/nix/src/nix/search.cc5
-rw-r--r--third_party/nix/src/nix/show-config.cc2
59 files changed, 349 insertions, 321 deletions
diff --git a/third_party/nix/src/build-remote/build-remote.cc b/third_party/nix/src/build-remote/build-remote.cc
index fd32b5a63750..70776b132d14 100644
--- a/third_party/nix/src/build-remote/build-remote.cc
+++ b/third_party/nix/src/build-remote/build-remote.cc
@@ -184,7 +184,7 @@ static int _main(int argc, char* argv[]) {
 #if __APPLE__
         futimes(bestSlotLock.get(), NULL);
 #else
-        futimens(bestSlotLock.get(), NULL);
+        futimens(bestSlotLock.get(), nullptr);
 #endif
 
         lock = -1;
diff --git a/third_party/nix/src/libexpr/attr-path.cc b/third_party/nix/src/libexpr/attr-path.cc
index 3d4e9c1e1096..485c240e3a4a 100644
--- a/third_party/nix/src/libexpr/attr-path.cc
+++ b/third_party/nix/src/libexpr/attr-path.cc
@@ -15,7 +15,7 @@ static Strings parseAttrPath(const string& s) {
       cur.clear();
     } else if (*i == '"') {
       ++i;
-      while (1) {
+      while (true) {
         if (i == s.end()) {
           throw Error(format("missing closing quote in selection path '%1%'") %
                       s);
diff --git a/third_party/nix/src/libexpr/eval.cc b/third_party/nix/src/libexpr/eval.cc
index c5329daf5faf..44f55dd68786 100644
--- a/third_party/nix/src/libexpr/eval.cc
+++ b/third_party/nix/src/libexpr/eval.cc
@@ -328,7 +328,7 @@ EvalState::EvalState(const Strings& _searchPath, ref<Store> store)
       repair(NoRepair),
       store(store),
       baseEnv(allocEnv(128)),
-      staticBaseEnv(false, 0) {
+      staticBaseEnv(false, nullptr) {
   countCalls = getEnv("NIX_COUNT_CALLS", "0") != "0";
 
   assert(gcInitialised);
@@ -378,7 +378,7 @@ EvalState::EvalState(const Strings& _searchPath, ref<Store> store)
   createBaseEnv();
 }
 
-EvalState::~EvalState() {}
+EvalState::~EvalState() = default;
 
 Path EvalState::checkSourcePath(const Path& path_) {
   if (!allowedPaths) {
@@ -575,7 +575,7 @@ Value& mkString(Value& v, const string& s, const PathSet& context) {
     for (auto& i : context) {
       v.string.context[n++] = dupString(i.c_str());
     }
-    v.string.context[n] = 0;
+    v.string.context[n] = nullptr;
   }
   return v;
 }
@@ -591,10 +591,10 @@ inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) {
     return env->values[var.displ];
   }
 
-  while (1) {
+  while (true) {
     if (env->type == Env::HasWithExpr) {
       if (noEval) {
-        return 0;
+        return nullptr;
       }
       Value* v = allocValue();
       evalAttrs(*env->up, (Expr*)env->values[0], *v);
@@ -656,7 +656,8 @@ void EvalState::mkList(Value& v, size_t size) {
   } else {
     v.type = tListN;
     v.bigList.size = size;
-    v.bigList.elems = size ? (Value**)allocBytes(size * sizeof(Value*)) : 0;
+    v.bigList.elems =
+        size ? (Value**)allocBytes(size * sizeof(Value*)) : nullptr;
   }
   nrListElems += size;
 }
@@ -822,7 +823,7 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& v) {
     env2.up = &env;
     dynamicEnv = &env2;
 
-    AttrDefs::iterator overrides = attrs.find(state.sOverrides);
+    auto overrides = attrs.find(state.sOverrides);
     bool hasOverrides = overrides != attrs.end();
 
     /* The recursive attributes are evaluated in the new
@@ -858,7 +859,7 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& v) {
         newBnds->push_back(i);
       }
       for (auto& i : *vOverrides->attrs) {
-        AttrDefs::iterator j = attrs.find(i.name);
+        auto j = attrs.find(i.name);
         if (j != attrs.end()) {
           (*newBnds)[j->second.displ] = i;
           env2.values[j->second.displ] = i.value;
@@ -955,7 +956,7 @@ unsigned long nrLookups = 0;
 
 void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
   Value vTmp;
-  Pos* pos2 = 0;
+  Pos* pos2 = nullptr;
   Value* vAttrs = &vTmp;
 
   e->eval(state, env, vTmp);
@@ -985,7 +986,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) {
       }
     }
 
-    state.forceValue(*vAttrs, (pos2 != NULL ? *pos2 : this->pos));
+    state.forceValue(*vAttrs, (pos2 != nullptr ? *pos2 : this->pos));
 
   } catch (Error& e) {
     if (pos2 && pos2->file != state.sDerivationNix) {
@@ -1334,7 +1335,7 @@ void EvalState::concatLists(Value& v, size_t nrLists, Value** lists,
                             const Pos& pos) {
   nrListConcats++;
 
-  Value* nonEmpty = 0;
+  Value* nonEmpty = nullptr;
   size_t len = 0;
   for (size_t n = 0; n < nrLists; ++n) {
     forceList(*lists[n], pos);
@@ -1796,7 +1797,7 @@ void EvalState::printStats() {
 
 #if HAVE_BOEHMGC
   GC_word heapSize, totalBytes;
-  GC_get_heap_usage_safe(&heapSize, 0, 0, 0, &totalBytes);
+  GC_get_heap_usage_safe(&heapSize, nullptr, nullptr, nullptr, &totalBytes);
 #endif
   if (showStats) {
     auto outPath = getEnv("NIX_SHOW_STATS_PATH", "-");
diff --git a/third_party/nix/src/libexpr/get-drvs.cc b/third_party/nix/src/libexpr/get-drvs.cc
index c62e05d4541c..aa73c01fd1f2 100644
--- a/third_party/nix/src/libexpr/get-drvs.cc
+++ b/third_party/nix/src/libexpr/get-drvs.cc
@@ -2,6 +2,7 @@
 
 #include <cstring>
 #include <regex>
+#include <utility>
 
 #include <glog/logging.h>
 
@@ -11,12 +12,12 @@
 
 namespace nix {
 
-DrvInfo::DrvInfo(EvalState& state, const string& attrPath, Bindings* attrs)
-    : state(&state), attrs(attrs), attrPath(attrPath) {}
+DrvInfo::DrvInfo(EvalState& state, string attrPath, Bindings* attrs)
+    : state(&state), attrs(attrs), attrPath(std::move(attrPath)) {}
 
 DrvInfo::DrvInfo(EvalState& state, ref<Store> store,
                  const std::string& drvPathWithOutputs)
-    : state(&state), attrs(nullptr), attrPath("") {
+    : state(&state), attrPath("") {
   auto spec = parseDrvPathWithOutputs(drvPathWithOutputs);
 
   drvPath = spec.first;
@@ -158,11 +159,11 @@ Bindings* DrvInfo::getMeta() {
     return meta;
   }
   if (!attrs) {
-    return 0;
+    return nullptr;
   }
   Bindings::iterator a = attrs->find(state->sMeta);
   if (a == attrs->end()) {
-    return 0;
+    return nullptr;
   }
   state->forceAttrs(*a->value, *a->pos);
   meta = a->value->attrs;
@@ -208,11 +209,11 @@ bool DrvInfo::checkMeta(Value& v) {
 
 Value* DrvInfo::queryMeta(const string& name) {
   if (!getMeta()) {
-    return 0;
+    return nullptr;
   }
   Bindings::iterator a = meta->find(state->symbols.create(name));
   if (a == meta->end() || !checkMeta(*a->value)) {
-    return 0;
+    return nullptr;
   }
   return a->value;
 }
@@ -303,7 +304,7 @@ void DrvInfo::setMeta(const string& name, Value* v) {
 }
 
 /* Cache for already considered attrsets. */
-typedef set<Bindings*> Done;
+using Done = set<Bindings*>;
 
 /* Evaluate value `v'.  If it evaluates to a set of type `derivation',
    then put information about it in `drvs' (unless it's already in `done').
diff --git a/third_party/nix/src/libexpr/get-drvs.hh b/third_party/nix/src/libexpr/get-drvs.hh
index deb0a6d647a9..ef6ecd253e6a 100644
--- a/third_party/nix/src/libexpr/get-drvs.hh
+++ b/third_party/nix/src/libexpr/get-drvs.hh
@@ -33,7 +33,7 @@ struct DrvInfo {
   string attrPath; /* path towards the derivation */
 
   DrvInfo(EvalState& state) : state(&state){};
-  DrvInfo(EvalState& state, const string& attrPath, Bindings* attrs);
+  DrvInfo(EvalState& state, string attrPath, Bindings* attrs);
   DrvInfo(EvalState& state, ref<Store> store,
           const std::string& drvPathWithOutputs);
 
diff --git a/third_party/nix/src/libexpr/json-to-value.cc b/third_party/nix/src/libexpr/json-to-value.cc
index 70628636e16b..122bd2ad3147 100644
--- a/third_party/nix/src/libexpr/json-to-value.cc
+++ b/third_party/nix/src/libexpr/json-to-value.cc
@@ -66,7 +66,7 @@ static void parseJSON(EvalState& state, const char*& s, Value& v) {
     ValueVector values;
     values.reserve(128);
     skipWhitespace(s);
-    while (1) {
+    while (true) {
       if (values.empty() && *s == ']') {
         break;
       }
@@ -92,7 +92,7 @@ static void parseJSON(EvalState& state, const char*& s, Value& v) {
   else if (*s == '{') {
     s++;
     ValueMap attrs;
-    while (1) {
+    while (true) {
       skipWhitespace(s);
       if (attrs.empty() && *s == '}') {
         break;
diff --git a/third_party/nix/src/libexpr/names.cc b/third_party/nix/src/libexpr/names.cc
index 184f30999e6b..ecad90c960af 100644
--- a/third_party/nix/src/libexpr/names.cc
+++ b/third_party/nix/src/libexpr/names.cc
@@ -1,5 +1,7 @@
 #include "names.hh"
 
+#include <memory>
+
 #include "util.hh"
 
 namespace nix {
@@ -26,8 +28,7 @@ DrvName::DrvName(const string& s) : hits(0) {
 bool DrvName::matches(DrvName& n) {
   if (name != "*") {
     if (!regex) {
-      regex = std::unique_ptr<std::regex>(
-          new std::regex(name, std::regex::extended));
+      regex = std::make_unique<std::regex>(name, std::regex::extended);
     }
     if (!std::regex_match(n.name, *regex)) {
       return false;
diff --git a/third_party/nix/src/libexpr/nixexpr.cc b/third_party/nix/src/libexpr/nixexpr.cc
index dc2c2b75e3bc..55b9d545778c 100644
--- a/third_party/nix/src/libexpr/nixexpr.cc
+++ b/third_party/nix/src/libexpr/nixexpr.cc
@@ -239,7 +239,7 @@ void ExprVar::bindVars(const StaticEnv& env) {
         withLevel = level;
       }
     } else {
-      StaticEnv::Vars::const_iterator i = curEnv->vars.find(name);
+      auto i = curEnv->vars.find(name);
       if (i != curEnv->vars.end()) {
         fromWith = false;
         this->level = level;
diff --git a/third_party/nix/src/libexpr/primops.cc b/third_party/nix/src/libexpr/primops.cc
index 6835f03c8b7f..d576d4b61905 100644
--- a/third_party/nix/src/libexpr/primops.cc
+++ b/third_party/nix/src/libexpr/primops.cc
@@ -62,7 +62,7 @@ void EvalState::realiseContext(const PathSet& context) {
          paths. */
       if (allowedPaths) {
         auto drv = store->derivationFromPath(decoded.first);
-        DerivationOutputs::iterator i = drv.outputs.find(decoded.second);
+        auto i = drv.outputs.find(decoded.second);
         if (i == drv.outputs.end()) {
           throw Error("derivation '%s' does not have an output named '%s'",
                       decoded.first, decoded.second);
@@ -160,7 +160,7 @@ static void prim_scopedImport(EvalState& state, const Pos& pos, Value** args,
 
 /* Want reasonable symbol names, so extern C */
 /* !!! Should we pass the Pos or the file name too? */
-extern "C" typedef void (*ValueInitializer)(EvalState& state, Value& v);
+extern "C" using ValueInitializer = void(*)(EvalState&, Value&);
 
 /* Load a ValueInitializer from a DSO and return whatever it initializes */
 void prim_importNative(EvalState& state, const Pos& pos, Value** args,
@@ -186,7 +186,7 @@ void prim_importNative(EvalState& state, const Pos& pos, Value** args,
   }
 
   dlerror();
-  ValueInitializer func = (ValueInitializer)dlsym(handle, sym.c_str());
+  auto func = (ValueInitializer)dlsym(handle, sym.c_str());
   if (!func) {
     char* message = dlerror();
     if (message) {
@@ -2090,7 +2090,7 @@ static void prim_replaceStrings(EvalState& state, const Pos& pos, Value** args,
   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)));
+    to.emplace_back(std::move(s), std::move(ctx));
   }
 
   PathSet context;
@@ -2253,7 +2253,7 @@ RegisterPrimOp::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun) {
 }
 
 void EvalState::createBaseEnv() {
-  baseEnv.up = 0;
+  baseEnv.up = nullptr;
 
   /* Add global constants such as `true' to the base environment. */
   Value v;
@@ -2281,7 +2281,7 @@ void EvalState::createBaseEnv() {
   };
 
   if (!evalSettings.pureEval) {
-    mkInt(v, time(0));
+    mkInt(v, time(nullptr));
     addConstant("__currentTime", v);
   }
 
diff --git a/third_party/nix/src/libmain/shared.cc b/third_party/nix/src/libmain/shared.cc
index f63fe9c11c5a..8ff7cebbee4d 100644
--- a/third_party/nix/src/libmain/shared.cc
+++ b/third_party/nix/src/libmain/shared.cc
@@ -2,14 +2,15 @@
 
 #include <algorithm>
 #include <cctype>
+#include <csignal>
 #include <cstdlib>
 #include <exception>
 #include <iostream>
 #include <mutex>
+#include <utility>
 
 #include <glog/logging.h>
 #include <openssl/crypto.h>
-#include <signal.h>
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <unistd.h>
@@ -128,13 +129,13 @@ void initNix() {
   sigemptyset(&act.sa_mask);
   act.sa_handler = SIG_DFL;
   act.sa_flags = 0;
-  if (sigaction(SIGCHLD, &act, 0)) {
+  if (sigaction(SIGCHLD, &act, nullptr)) {
     throw SysError("resetting SIGCHLD");
   }
 
   /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */
   act.sa_handler = sigHandler;
-  if (sigaction(SIGUSR1, &act, 0)) {
+  if (sigaction(SIGUSR1, &act, nullptr)) {
     throw SysError("handling SIGUSR1");
   }
 
@@ -159,7 +160,7 @@ void initNix() {
 
   /* Initialise the PRNG. */
   struct timeval tv;
-  gettimeofday(&tv, 0);
+  gettimeofday(&tv, nullptr);
   srandom(tv.tv_usec);
 
   /* On macOS, don't use the per-session TMPDIR (as set e.g. by
@@ -175,7 +176,7 @@ LegacyArgs::LegacyArgs(
     const std::string& programName,
     std::function<bool(Strings::iterator& arg, const Strings::iterator& end)>
         parseArg)
-    : MixCommonArgs(programName), parseArg(parseArg) {
+    : MixCommonArgs(programName), parseArg(std::move(parseArg)) {
   mkFlag()
       .longName("no-build-output")
       .shortName('Q')
@@ -395,6 +396,6 @@ PrintFreed::~PrintFreed() {
   }
 }
 
-Exit::~Exit() {}
+Exit::~Exit() = default;
 
 }  // namespace nix
diff --git a/third_party/nix/src/libmain/stack.cc b/third_party/nix/src/libmain/stack.cc
index 27c16f5d1f6b..87018b975c29 100644
--- a/third_party/nix/src/libmain/stack.cc
+++ b/third_party/nix/src/libmain/stack.cc
@@ -1,8 +1,8 @@
+#include <csignal>
 #include <cstddef>
 #include <cstdlib>
 #include <cstring>
 
-#include <signal.h>
 #include <unistd.h>
 
 #include "types.hh"
@@ -14,7 +14,7 @@ static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) {
      the stack pointer.  Unfortunately, getting the stack pointer is
      not portable. */
   bool haveSP = true;
-  char* sp = 0;
+  char* sp = nullptr;
 #if defined(__x86_64__) && defined(REG_RSP)
   sp = (char*)((ucontext_t*)ctx)->uc_mcontext.gregs[REG_RSP];
 #elif defined(REG_ESP)
@@ -40,7 +40,7 @@ static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) {
   sigfillset(&act.sa_mask);
   act.sa_handler = SIG_DFL;
   act.sa_flags = 0;
-  if (sigaction(SIGSEGV, &act, 0)) {
+  if (sigaction(SIGSEGV, &act, nullptr)) {
     abort();
   }
 }
@@ -58,7 +58,7 @@ void detectStackOverflow() {
     throw Error("cannot allocate alternative stack");
   }
   stack.ss_flags = 0;
-  if (sigaltstack(&stack, 0) == -1) {
+  if (sigaltstack(&stack, nullptr) == -1) {
     throw SysError("cannot set alternative stack");
   }
 
@@ -66,7 +66,7 @@ void detectStackOverflow() {
   sigfillset(&act.sa_mask);
   act.sa_sigaction = sigsegvHandler;
   act.sa_flags = SA_SIGINFO | SA_ONSTACK;
-  if (sigaction(SIGSEGV, &act, 0)) {
+  if (sigaction(SIGSEGV, &act, nullptr)) {
     throw SysError("resetting SIGSEGV");
   }
 #endif
diff --git a/third_party/nix/src/libstore/binary-cache-store.cc b/third_party/nix/src/libstore/binary-cache-store.cc
index 10a0ddfc1363..bed4e717eb2f 100644
--- a/third_party/nix/src/libstore/binary-cache-store.cc
+++ b/third_party/nix/src/libstore/binary-cache-store.cc
@@ -2,6 +2,7 @@
 
 #include <chrono>
 #include <future>
+#include <memory>
 
 #include "archive.hh"
 #include "compression.hh"
@@ -20,8 +21,7 @@ namespace nix {
 
 BinaryCacheStore::BinaryCacheStore(const Params& params) : Store(params) {
   if (secretKeyFile != "") {
-    secretKey =
-        std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));
+    secretKey = std::make_unique<SecretKey>(readFile(secretKeyFile));
   }
 
   StringSink sink;
diff --git a/third_party/nix/src/libstore/build.cc b/third_party/nix/src/libstore/build.cc
index 3349e1e8c8e9..efc1e5a1263e 100644
--- a/third_party/nix/src/libstore/build.cc
+++ b/third_party/nix/src/libstore/build.cc
@@ -1,18 +1,19 @@
 #include <algorithm>
+#include <cerrno>
 #include <chrono>
+#include <climits>
 #include <cstring>
 #include <future>
 #include <iostream>
 #include <map>
+#include <memory>
 #include <queue>
 #include <regex>
 #include <sstream>
 #include <thread>
 
-#include <errno.h>
 #include <fcntl.h>
 #include <grp.h>
-#include <limits.h>
 #include <netdb.h>
 #include <pwd.h>
 #include <sys/resource.h>
@@ -67,6 +68,7 @@
 #endif
 
 #include <nlohmann/json.hpp>
+#include <utility>
 
 namespace nix {
 
@@ -81,8 +83,8 @@ struct HookInstance;
 /* A pointer to a goal. */
 class Goal;
 class DerivationGoal;
-typedef std::shared_ptr<Goal> GoalPtr;
-typedef std::weak_ptr<Goal> WeakGoalPtr;
+using GoalPtr = std::shared_ptr<Goal>;
+using WeakGoalPtr = std::weak_ptr<Goal>;
 
 struct CompareGoalPtrs {
   bool operator()(const GoalPtr& a, const GoalPtr& b) const;
@@ -90,7 +92,7 @@ struct CompareGoalPtrs {
 
 /* Set of goals. */
 typedef set<GoalPtr, CompareGoalPtrs> Goals;
-typedef list<WeakGoalPtr> WeakGoals;
+using WeakGoals = list<WeakGoalPtr>;
 
 /* A map of paths to goals (and the other way around). */
 typedef map<Path, WeakGoalPtr> WeakGoalMap;
@@ -174,7 +176,7 @@ bool CompareGoalPtrs::operator()(const GoalPtr& a, const GoalPtr& b) const {
   return s1 < s2;
 }
 
-typedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point;
+using steady_time_point = std::chrono::time_point<std::chrono::steady_clock>;
 
 /* A mapping used to remember for each child process to what goal it
    belongs, and file descriptors for receiving log data and output
@@ -816,7 +818,7 @@ class DerivationGoal : public Goal {
   /* Whether to run the build in a private network namespace. */
   bool privateNetwork = false;
 
-  typedef void (DerivationGoal::*GoalState)();
+  using GoalState = void (DerivationGoal::*)();
   GoalState state;
 
   /* Stuff we need to pass to initChild(). */
@@ -824,7 +826,7 @@ class DerivationGoal : public Goal {
     Path source;
     bool optional;
     explicit ChrootPath(Path source = "", bool optional = false)
-        : source(source), optional(optional) {}
+        : source(std::move(source)), optional(optional) {}
   };
   typedef map<Path, ChrootPath>
       DirsInChroot;  // maps target path to source path
@@ -874,11 +876,11 @@ class DerivationGoal : public Goal {
   std::string machineName;
 
  public:
-  DerivationGoal(const Path& drvPath, const StringSet& wantedOutputs,
-                 Worker& worker, BuildMode buildMode = bmNormal);
+  DerivationGoal(const Path& drvPath, StringSet wantedOutputs, Worker& worker,
+                 BuildMode buildMode = bmNormal);
   DerivationGoal(const Path& drvPath, const BasicDerivation& drv,
                  Worker& worker, BuildMode buildMode = bmNormal);
-  ~DerivationGoal();
+  ~DerivationGoal() override;
 
   /* Whether we need to perform hash rewriting if there are valid output paths.
    */
@@ -982,13 +984,12 @@ class DerivationGoal : public Goal {
 
 const Path DerivationGoal::homeDir = "/homeless-shelter";
 
-DerivationGoal::DerivationGoal(const Path& drvPath,
-                               const StringSet& wantedOutputs, Worker& worker,
-                               BuildMode buildMode)
+DerivationGoal::DerivationGoal(const Path& drvPath, StringSet wantedOutputs,
+                               Worker& worker, BuildMode buildMode)
     : Goal(worker),
       useDerivation(true),
       drvPath(drvPath),
-      wantedOutputs(wantedOutputs),
+      wantedOutputs(std::move(wantedOutputs)),
       buildMode(buildMode) {
   state = &DerivationGoal::getDerivation;
   name = (format("building of '%1%'") % drvPath).str();
@@ -1004,7 +1005,7 @@ DerivationGoal::DerivationGoal(const Path& drvPath, const BasicDerivation& drv,
       useDerivation(false),
       drvPath(drvPath),
       buildMode(buildMode) {
-  this->drv = std::unique_ptr<BasicDerivation>(new BasicDerivation(drv));
+  this->drv = std::make_unique<BasicDerivation>(drv);
   state = &DerivationGoal::haveDerivation;
   name = (format("building of %1%") % showPaths(drv.outputPaths())).str();
   trace("created");
@@ -1473,7 +1474,7 @@ void DerivationGoal::tryToBuild() {
       case rpAccept:
         /* Yes, it has started doing so.  Wait until we get
            EOF from the hook. */
-        result.startTime = time(0);  // inexact
+        result.startTime = time(nullptr);  // inexact
         state = &DerivationGoal::buildDone;
         started();
         return;
@@ -1554,7 +1555,7 @@ MakeError(NotDeterministic, BuildError)
   DLOG(INFO) << "builder process for '" << drvPath << "' finished";
 
   result.timesBuilt++;
-  result.stopTime = time(0);
+  result.stopTime = time(nullptr);
 
   /* So the child is gone now. */
   worker.childTerminated(this);
@@ -1674,7 +1675,7 @@ MakeError(NotDeterministic, BuildError)
           currentLine.clear();
         }
 
-        ~LogSink() {
+        ~LogSink() override {
           if (currentLine != "") {
             currentLine += '\n';
             flushLine();
@@ -1785,7 +1786,7 @@ HookReply DerivationGoal::tryBuildHook() {
       return rpDecline;
     } else if (reply == "decline-permanently") {
       worker.tryBuildHook = false;
-      worker.hook = 0;
+      worker.hook = nullptr;
       return rpDecline;
     } else if (reply == "postpone") {
       return rpPostpone;
@@ -1796,7 +1797,7 @@ HookReply DerivationGoal::tryBuildHook() {
     if (e.errNo == EPIPE) {
       LOG(ERROR) << "build hook died unexpectedly: "
                  << chomp(drainFD(worker.hook->fromHook.readSide.get()));
-      worker.hook = 0;
+      worker.hook = nullptr;
       return rpDecline;
     } else {
       throw;
@@ -1892,10 +1893,10 @@ static void preloadNSS() {
      load its lookup libraries in the parent before any child gets a chance to.
    */
   std::call_once(dns_resolve_flag, []() {
-    struct addrinfo* res = NULL;
+    struct addrinfo* res = nullptr;
 
     if (getaddrinfo("this.pre-initializes.the.dns.resolvers.invalid.", "http",
-                    NULL, &res) != 0) {
+                    nullptr, &res) != 0) {
       if (res) {
         freeaddrinfo(res);
       }
@@ -2000,12 +2001,12 @@ void DerivationGoal::startBuilder() {
        by `nix-store --register-validity'.  However, the deriver
        fields are left empty. */
     string s = get(drv->env, "exportReferencesGraph");
-    Strings ss = tokenizeString<Strings>(s);
+    auto ss = tokenizeString<Strings>(s);
     if (ss.size() % 2 != 0) {
       throw BuildError(
           format("odd number of tokens in 'exportReferencesGraph': '%1%'") % s);
     }
-    for (Strings::iterator i = ss.begin(); i != ss.end();) {
+    for (auto i = ss.begin(); i != ss.end();) {
       string fileName = *i++;
       checkStoreName(fileName); /* !!! abuse of this function */
       Path storePath = *i++;
@@ -2331,7 +2332,7 @@ void DerivationGoal::startBuilder() {
     throw SysError("putting pseudoterminal into raw mode");
   }
 
-  result.startTime = time(0);
+  result.startTime = time(nullptr);
 
   /* Fork a child to build the package. */
   ProcessOptions options;
@@ -2390,13 +2391,13 @@ void DerivationGoal::startBuilder() {
              not seem to be a workaround for this. (But who can tell
              from reading user_namespaces(7)?)
              See also https://lwn.net/Articles/621612/. */
-          if (getuid() == 0 && setgroups(0, 0) == -1) {
+          if (getuid() == 0 && setgroups(0, nullptr) == -1) {
             throw SysError("setgroups failed");
           }
 
           size_t stackSize = 1 * 1024 * 1024;
           char* stack =
-              (char*)mmap(0, stackSize, PROT_WRITE | PROT_READ,
+              (char*)mmap(nullptr, stackSize, PROT_WRITE | PROT_READ,
                           MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
           if (stack == MAP_FAILED) {
             throw SysError("allocating stack");
@@ -2519,8 +2520,7 @@ void DerivationGoal::initTmpDir() {
      needed (attributes are not passed through the environment, so
      there is no size constraint). */
   if (!parsedDrv->getStructuredAttrs()) {
-    StringSet passAsFile =
-        tokenizeString<StringSet>(get(drv->env, "passAsFile"));
+    auto passAsFile = tokenizeString<StringSet>(get(drv->env, "passAsFile"));
     int fileNr = 0;
     for (auto& i : drv->env) {
       if (passAsFile.find(i.first) == passAsFile.end()) {
@@ -2893,14 +2893,14 @@ void DerivationGoal::runChild() {
          outside of the namespace.  Making a subtree private is
          local to the namespace, though, so setting MS_PRIVATE
          does not affect the outside world. */
-      if (mount(0, "/", 0, MS_REC | MS_PRIVATE, 0) == -1) {
+      if (mount(nullptr, "/", nullptr, MS_REC | MS_PRIVATE, nullptr) == -1) {
         throw SysError("unable to make '/' private mount");
       }
 
       /* Bind-mount chroot directory to itself, to treat it as a
          different filesystem from /, as needed for pivot_root. */
-      if (mount(chrootRootDir.c_str(), chrootRootDir.c_str(), 0, MS_BIND, 0) ==
-          -1) {
+      if (mount(chrootRootDir.c_str(), chrootRootDir.c_str(), nullptr, MS_BIND,
+                nullptr) == -1) {
         throw SysError(format("unable to bind mount '%1%'") % chrootRootDir);
       }
 
@@ -2970,8 +2970,8 @@ void DerivationGoal::runChild() {
           createDirs(dirOf(target));
           writeFile(target, "");
         }
-        if (mount(source.c_str(), target.c_str(), "", MS_BIND | MS_REC, 0) ==
-            -1) {
+        if (mount(source.c_str(), target.c_str(), "", MS_BIND | MS_REC,
+                  nullptr) == -1) {
           throw SysError("bind mount from '%1%' to '%2%' failed", source,
                          target);
         }
@@ -2986,8 +2986,8 @@ void DerivationGoal::runChild() {
 
       /* Bind a new instance of procfs on /proc. */
       createDirs(chrootRootDir + "/proc");
-      if (mount("none", (chrootRootDir + "/proc").c_str(), "proc", 0, 0) ==
-          -1) {
+      if (mount("none", (chrootRootDir + "/proc").c_str(), "proc", 0,
+                nullptr) == -1) {
         throw SysError("mounting /proc");
       }
 
@@ -3589,7 +3589,7 @@ void DerivationGoal::registerOutputs() {
     /* For debugging, print out the referenced and unreferenced
        paths. */
     for (auto& i : inputPaths) {
-      PathSet::iterator j = references.find(i);
+      auto j = references.find(i);
       if (j == references.end()) {
         DLOG(INFO) << "unreferenced input: '" << i << "'";
       } else {
@@ -3841,14 +3841,14 @@ void DerivationGoal::checkOutputs(
             auto i = output->find(name);
             if (i != output->end()) {
               Strings res;
-              for (auto j = i->begin(); j != i->end(); ++j) {
-                if (!j->is_string()) {
+              for (auto& j : *i) {
+                if (!j.is_string()) {
                   throw Error(
                       "attribute '%s' of derivation '%s' must be a list of "
                       "strings",
                       name, drvPath);
                 }
-                res.push_back(j->get<std::string>());
+                res.push_back(j.get<std::string>());
               }
               checks.disallowedRequisites = res;
               return res;
@@ -3922,7 +3922,7 @@ void DerivationGoal::closeLogFile() {
   if (logFileSink) {
     logFileSink->flush();
   }
-  logSink = logFileSink = 0;
+  logSink = logFileSink = nullptr;
   fdLogFile = -1;
 }
 
@@ -4099,13 +4099,13 @@ class SubstitutionGoal : public Goal {
       maintainRunningSubstitutions, maintainExpectedNar,
       maintainExpectedDownload;
 
-  typedef void (SubstitutionGoal::*GoalState)();
+  using GoalState = void (SubstitutionGoal::*)();
   GoalState state;
 
  public:
   SubstitutionGoal(const Path& storePath, Worker& worker,
                    RepairFlag repair = NoRepair);
-  ~SubstitutionGoal();
+  ~SubstitutionGoal() override;
 
   void timedOut() override { abort(); };
 
@@ -4459,9 +4459,9 @@ GoalPtr Worker::makeSubstitutionGoal(const Path& path, RepairFlag repair) {
 
 static void removeGoal(GoalPtr goal, WeakGoalMap& goalMap) {
   /* !!! inefficient */
-  for (WeakGoalMap::iterator i = goalMap.begin(); i != goalMap.end();) {
+  for (auto i = goalMap.begin(); i != goalMap.end();) {
     if (i->second.lock() == goal) {
-      WeakGoalMap::iterator j = i;
+      auto j = i;
       ++j;
       goalMap.erase(i);
       i = j;
@@ -4570,7 +4570,7 @@ void Worker::run(const Goals& _topGoals) {
 
   DLOG(INFO) << "entered goal loop";
 
-  while (1) {
+  while (true) {
     checkInterrupt();
 
     store.autoGC(false);
@@ -4704,7 +4704,8 @@ void Worker::waitForInput() {
     }
   }
 
-  if (select(fdMax, &fds, 0, 0, useTimeout ? &timeout : 0) == -1) {
+  if (select(fdMax, &fds, nullptr, nullptr, useTimeout ? &timeout : nullptr) ==
+      -1) {
     if (errno == EINTR) {
       return;
     }
@@ -4810,7 +4811,7 @@ unsigned int Worker::exitStatus() {
 }
 
 bool Worker::pathContentsGood(const Path& path) {
-  std::map<Path, bool>::iterator i = pathContentsGoodCache.find(path);
+  auto i = pathContentsGoodCache.find(path);
   if (i != pathContentsGoodCache.end()) {
     return i->second;
   }
@@ -4874,7 +4875,7 @@ void LocalStore::buildPaths(const PathSet& drvPaths, BuildMode buildMode) {
   PathSet failed;
   for (auto& i : goals) {
     if (i->getExitCode() != Goal::ecSuccess) {
-      DerivationGoal* i2 = dynamic_cast<DerivationGoal*>(i.get());
+      auto* i2 = dynamic_cast<DerivationGoal*>(i.get());
       if (i2) {
         failed.insert(i2->getDrvPath());
       } else {
diff --git a/third_party/nix/src/libstore/derivations.cc b/third_party/nix/src/libstore/derivations.cc
index 1b6f160653c9..2955056e06ea 100644
--- a/third_party/nix/src/libstore/derivations.cc
+++ b/third_party/nix/src/libstore/derivations.cc
@@ -331,7 +331,7 @@ DrvHashes drvHashes;
 Hash hashDerivationModulo(Store& store, Derivation drv) {
   /* Return a fixed hash for fixed-output derivations. */
   if (drv.isFixedOutput()) {
-    DerivationOutputs::const_iterator i = drv.outputs.begin();
+    auto i = drv.outputs.begin();
     return hashString(htSHA256, "fixed:out:" + i->second.hashAlgo + ":" +
                                     i->second.hash + ":" + i->second.path);
   }
diff --git a/third_party/nix/src/libstore/download.cc b/third_party/nix/src/libstore/download.cc
index 4b90a3765724..eb7095ee146a 100644
--- a/third_party/nix/src/libstore/download.cc
+++ b/third_party/nix/src/libstore/download.cc
@@ -45,7 +45,7 @@ std::string resolveUri(const std::string& uri) {
 }
 
 struct CurlDownloader : public Downloader {
-  CURLM* curlm = 0;
+  CURLM* curlm = nullptr;
 
   std::random_device rd;
   std::mt19937 mt19937;
@@ -57,7 +57,7 @@ struct CurlDownloader : public Downloader {
     bool done = false;  // whether either the success or failure function has
                         // been called
     Callback<DownloadResult> callback;
-    CURL* req = 0;
+    CURL* req = nullptr;
     bool active =
         false;  // whether the handle has been added to the multi object
     std::string status;
@@ -68,7 +68,7 @@ struct CurlDownloader : public Downloader {
        has been reached. */
     std::chrono::steady_clock::time_point embargo;
 
-    struct curl_slist* requestHeaders = 0;
+    struct curl_slist* requestHeaders = nullptr;
 
     std::string encoding;
 
@@ -523,7 +523,7 @@ struct CurlDownloader : public Downloader {
     workerThread = std::thread([&]() { workerThreadEntry(); });
   }
 
-  ~CurlDownloader() {
+  ~CurlDownloader() override {
     stopWorkerThread();
 
     workerThread.join();
@@ -909,7 +909,7 @@ CachedDownloadResult Downloader::downloadCached(
       if (ss.size() >= 3 && ss[0] == url) {
         time_t lastChecked;
         if (string2Int(ss[2], lastChecked) &&
-            (uint64_t)lastChecked + request.ttl >= (uint64_t)time(0)) {
+            (uint64_t)lastChecked + request.ttl >= (uint64_t)time(nullptr)) {
           skip = true;
           result.effectiveUri = request.uri;
           result.etag = ss[1];
@@ -949,8 +949,8 @@ CachedDownloadResult Downloader::downloadCached(
       assert(!storePath.empty());
       replaceSymlink(storePath, fileLink);
 
-      writeFile(dataFile,
-                url + "\n" + res.etag + "\n" + std::to_string(time(0)) + "\n");
+      writeFile(dataFile, url + "\n" + res.etag + "\n" +
+                              std::to_string(time(nullptr)) + "\n");
     } catch (DownloadError& e) {
       if (storePath.empty()) {
         throw;
diff --git a/third_party/nix/src/libstore/export-import.cc b/third_party/nix/src/libstore/export-import.cc
index d50638d5b0f7..de68304e3141 100644
--- a/third_party/nix/src/libstore/export-import.cc
+++ b/third_party/nix/src/libstore/export-import.cc
@@ -11,7 +11,7 @@ struct HashAndWriteSink : Sink {
   HashSink hashSink;
   explicit HashAndWriteSink(Sink& writeSink)
       : writeSink(writeSink), hashSink(htSHA256) {}
-  virtual void operator()(const unsigned char* data, size_t len) {
+  void operator()(const unsigned char* data, size_t len) override {
     writeSink(data, len);
     hashSink(data, len);
   }
diff --git a/third_party/nix/src/libstore/gc.cc b/third_party/nix/src/libstore/gc.cc
index 2241c58c419c..a0c84dc0a518 100644
--- a/third_party/nix/src/libstore/gc.cc
+++ b/third_party/nix/src/libstore/gc.cc
@@ -1,11 +1,11 @@
 #include <algorithm>
+#include <cerrno>
 #include <climits>
 #include <functional>
 #include <queue>
 #include <random>
 #include <regex>
 
-#include <errno.h>
 #include <fcntl.h>
 #include <sys/stat.h>
 #include <sys/statvfs.h>
@@ -147,7 +147,7 @@ void LocalStore::addTempRoot(const Path& path) {
 
   /* Create the temporary roots file for this process. */
   if (!state->fdTempRoots) {
-    while (1) {
+    while (true) {
       AutoCloseFD fdGCLock = openGCLock(ltRead);
 
       if (pathExists(fnTempRoots)) {
@@ -505,7 +505,8 @@ struct LocalStore::GCState {
   unsigned long long bytesInvalidated;
   bool moveToTrash = true;
   bool shouldDelete;
-  explicit GCState(GCResults& results_) : results(results_), bytesInvalidated(0) {}
+  explicit GCState(GCResults& results_)
+      : results(results_), bytesInvalidated(0) {}
 };
 
 bool LocalStore::isActiveTempFile(const GCState& state, const Path& path,
diff --git a/third_party/nix/src/libstore/http-binary-cache-store.cc b/third_party/nix/src/libstore/http-binary-cache-store.cc
index d3b551f08caa..1a46423b3542 100644
--- a/third_party/nix/src/libstore/http-binary-cache-store.cc
+++ b/third_party/nix/src/libstore/http-binary-cache-store.cc
@@ -1,3 +1,5 @@
+#include <utility>
+
 #include <glog/logging.h>
 
 #include "binary-cache-store.hh"
@@ -21,8 +23,8 @@ class HttpBinaryCacheStore : public BinaryCacheStore {
   Sync<State> _state;
 
  public:
-  HttpBinaryCacheStore(const Params& params, const Path& _cacheUri)
-      : BinaryCacheStore(params), cacheUri(_cacheUri) {
+  HttpBinaryCacheStore(const Params& params, Path _cacheUri)
+      : BinaryCacheStore(params), cacheUri(std::move(_cacheUri)) {
     if (cacheUri.back() == '/') {
       cacheUri.pop_back();
     }
@@ -157,7 +159,7 @@ static RegisterStoreImplementation regStore(
           std::string(uri, 0, 8) != "https://" &&
           (getEnv("_NIX_FORCE_HTTP_BINARY_CACHE_STORE") != "1" ||
            std::string(uri, 0, 7) != "file://")) {
-        return 0;
+        return nullptr;
       }
       auto store = std::make_shared<HttpBinaryCacheStore>(params, uri);
       store->init();
diff --git a/third_party/nix/src/libstore/legacy-ssh-store.cc b/third_party/nix/src/libstore/legacy-ssh-store.cc
index 0cfe1bfe5d49..7723581136d8 100644
--- a/third_party/nix/src/libstore/legacy-ssh-store.cc
+++ b/third_party/nix/src/libstore/legacy-ssh-store.cc
@@ -262,7 +262,7 @@ static RegisterStoreImplementation regStore(
     [](const std::string& uri,
        const Store::Params& params) -> std::shared_ptr<Store> {
       if (std::string(uri, 0, uriScheme.size()) != uriScheme) {
-        return 0;
+        return nullptr;
       }
       return std::make_shared<LegacySSHStore>(
           std::string(uri, uriScheme.size()), params);
diff --git a/third_party/nix/src/libstore/local-binary-cache-store.cc b/third_party/nix/src/libstore/local-binary-cache-store.cc
index 29c74cedd834..58ce7c091147 100644
--- a/third_party/nix/src/libstore/local-binary-cache-store.cc
+++ b/third_party/nix/src/libstore/local-binary-cache-store.cc
@@ -1,3 +1,5 @@
+#include <utility>
+
 #include "binary-cache-store.hh"
 #include "globals.hh"
 #include "nar-info-disk-cache.hh"
@@ -9,8 +11,8 @@ class LocalBinaryCacheStore : public BinaryCacheStore {
   Path binaryCacheDir;
 
  public:
-  LocalBinaryCacheStore(const Params& params, const Path& binaryCacheDir)
-      : BinaryCacheStore(params), binaryCacheDir(binaryCacheDir) {}
+  LocalBinaryCacheStore(const Params& params, Path binaryCacheDir)
+      : BinaryCacheStore(params), binaryCacheDir(std::move(binaryCacheDir)) {}
 
   void init() override;
 
@@ -78,7 +80,7 @@ static RegisterStoreImplementation regStore(
        const Store::Params& params) -> std::shared_ptr<Store> {
       if (getEnv("_NIX_FORCE_HTTP_BINARY_CACHE_STORE") == "1" ||
           std::string(uri, 0, 7) != "file://") {
-        return 0;
+        return nullptr;
       }
       auto store =
           std::make_shared<LocalBinaryCacheStore>(params, std::string(uri, 7));
diff --git a/third_party/nix/src/libstore/local-store.cc b/third_party/nix/src/libstore/local-store.cc
index 020813a35669..1fa5cb904181 100644
--- a/third_party/nix/src/libstore/local-store.cc
+++ b/third_party/nix/src/libstore/local-store.cc
@@ -1,19 +1,19 @@
 #include "local-store.hh"
 
 #include <algorithm>
+#include <cerrno>
+#include <cstdio>
 #include <cstring>
+#include <ctime>
 #include <iostream>
 
-#include <errno.h>
 #include <fcntl.h>
 #include <glog/logging.h>
 #include <grp.h>
-#include <stdio.h>
 #include <sys/select.h>
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <sys/types.h>
-#include <time.h>
 #include <unistd.h>
 #include <utime.h>
 
@@ -321,7 +321,7 @@ void LocalStore::openDB(State& state, bool create) {
   auto& db(state.db);
   if (sqlite3_open_v2(dbPath.c_str(), &db.db,
                       SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0),
-                      0) != SQLITE_OK) {
+                      nullptr) != SQLITE_OK) {
     throw Error(format("cannot open Nix database '%1%'") % dbPath);
   }
 
@@ -364,16 +364,16 @@ void LocalStore::openDB(State& state, bool create) {
     prevMode = string((const char*)sqlite3_column_text(stmt, 0));
   }
   if (prevMode != mode &&
-      sqlite3_exec(db, ("pragma main.journal_mode = " + mode + ";").c_str(), 0,
-                   0, 0) != SQLITE_OK) {
+      sqlite3_exec(db, ("pragma main.journal_mode = " + mode + ";").c_str(),
+                   nullptr, nullptr, nullptr) != SQLITE_OK) {
     throwSQLiteError(db, "setting journal mode");
   }
 
   /* Increase the auto-checkpoint interval to 40000 pages.  This
      seems enough to ensure that instantiating the NixOS system
      derivation is done in a single fsync(). */
-  if (mode == "wal" && sqlite3_exec(db, "pragma wal_autocheckpoint = 40000;", 0,
-                                    0, 0) != SQLITE_OK) {
+  if (mode == "wal" && sqlite3_exec(db, "pragma wal_autocheckpoint = 40000;",
+                                    nullptr, nullptr, nullptr) != SQLITE_OK) {
     throwSQLiteError(db, "setting autocheckpoint interval");
   }
 
@@ -404,7 +404,8 @@ void LocalStore::makeStoreWritable() {
       throw SysError("setting up a private mount namespace");
     }
 
-    if (mount(0, realStoreDir.c_str(), "none", MS_REMOUNT | MS_BIND, 0) == -1) {
+    if (mount(nullptr, realStoreDir.c_str(), "none", MS_REMOUNT | MS_BIND,
+              nullptr) == -1) {
       throw SysError(format("remounting %1% writable") % realStoreDir);
     }
   }
@@ -585,7 +586,7 @@ void LocalStore::checkDerivationOutputs(const Path& drvPath,
   drvName = string(drvName, 0, drvName.size() - drvExtension.size());
 
   if (drv.isFixedOutput()) {
-    DerivationOutputs::const_iterator out = drv.outputs.find("out");
+    auto out = drv.outputs.find("out");
     if (out == drv.outputs.end()) {
       throw Error(
           format("derivation '%1%' does not have an output named 'out'") %
@@ -597,7 +598,7 @@ void LocalStore::checkDerivationOutputs(const Path& drvPath,
     out->second.parseHashInfo(recursive, h);
     Path outPath = makeFixedOutputPath(recursive, h, drvName);
 
-    StringPairs::const_iterator j = drv.env.find("out");
+    auto j = drv.env.find("out");
     if (out->second.path != outPath || j == drv.env.end() ||
         j->second != outPath) {
       throw Error(
@@ -618,7 +619,7 @@ void LocalStore::checkDerivationOutputs(const Path& drvPath,
 
     for (auto& i : drv.outputs) {
       Path outPath = makeOutputPath(i.first, h, drvName);
-      StringPairs::const_iterator j = drv.env.find(i.first);
+      auto j = drv.env.find(i.first);
       if (i.second.path != outPath || j == drv.env.end() ||
           j->second != outPath) {
         throw Error(format("derivation '%1%' has incorrect output '%2%', "
@@ -640,7 +641,7 @@ uint64_t LocalStore::addValidPath(State& state, const ValidPathInfo& info,
 
   state.stmtRegisterValidPath
       .use()(info.path)(info.narHash.to_string(Base16))(
-          info.registrationTime == 0 ? time(0) : info.registrationTime)(
+          info.registrationTime == 0 ? time(nullptr) : info.registrationTime)(
           info.deriver, info.deriver != "")(info.narSize, info.narSize != 0)(
           info.ultimate ? 1 : 0, info.ultimate)(
           concatStringsSep(" ", info.sigs), !info.sigs.empty())(
diff --git a/third_party/nix/src/libstore/misc.cc b/third_party/nix/src/libstore/misc.cc
index 0ef0e559876d..23abaecba050 100644
--- a/third_party/nix/src/libstore/misc.cc
+++ b/third_party/nix/src/libstore/misc.cc
@@ -18,7 +18,7 @@ void Store::computeFSClosure(const PathSet& startPaths, PathSet& paths_,
     std::exception_ptr exc;
   };
 
-  Sync<State> state_(State{0, paths_, 0});
+  Sync<State> state_(State{0, paths_, nullptr});
 
   std::function<void(const Path&)> enqueue;
 
diff --git a/third_party/nix/src/libstore/nar-accessor.cc b/third_party/nix/src/libstore/nar-accessor.cc
index ffbf7c1a89d5..ac286374b8bd 100644
--- a/third_party/nix/src/libstore/nar-accessor.cc
+++ b/third_party/nix/src/libstore/nar-accessor.cc
@@ -4,6 +4,7 @@
 #include <map>
 #include <nlohmann/json.hpp>
 #include <stack>
+#include <utility>
 
 #include "archive.hh"
 #include "json.hh"
@@ -99,7 +100,7 @@ struct NarAccessor : public FSAccessor {
   }
 
   NarAccessor(const std::string& listing, GetNarBytes getNarBytes)
-      : getNarBytes(getNarBytes) {
+      : getNarBytes(std::move(getNarBytes)) {
     using json = nlohmann::json;
 
     std::function<void(NarMember&, json&)> recurse;
diff --git a/third_party/nix/src/libstore/nar-info-disk-cache.cc b/third_party/nix/src/libstore/nar-info-disk-cache.cc
index 3adda508d081..7ef178ab4388 100644
--- a/third_party/nix/src/libstore/nar-info-disk-cache.cc
+++ b/third_party/nix/src/libstore/nar-info-disk-cache.cc
@@ -116,7 +116,7 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
 
     /* Periodically purge expired entries from the database. */
     retrySQLite<void>([&]() {
-      auto now = time(0);
+      auto now = time(nullptr);
 
       SQLiteStmt queryLastPurge(state->db, "select value from LastPurge");
       auto queryLastPurge_(queryLastPurge.use());
@@ -157,7 +157,8 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
 
       // FIXME: race
 
-      state->insertCache.use()(uri)(time(0))(storeDir)(wantMassQuery)(priority)
+      state->insertCache
+          .use()(uri)(time(nullptr))(storeDir)(wantMassQuery)(priority)
           .exec();
       assert(sqlite3_changes(state->db) == 1);
       state->caches[uri] = Cache{(int)sqlite3_last_insert_rowid(state->db),
@@ -198,18 +199,18 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
 
           auto& cache(getCache(*state, uri));
 
-          auto now = time(0);
+          auto now = time(nullptr);
 
           auto queryNAR(state->queryNAR.use()(cache.id)(hashPart)(
               now - settings.ttlNegativeNarInfoCache)(
               now - settings.ttlPositiveNarInfoCache));
 
           if (!queryNAR.next()) {
-            return {oUnknown, 0};
+            return {oUnknown, nullptr};
           }
 
           if (!queryNAR.getInt(0)) {
-            return {oInvalid, 0};
+            return {oInvalid, nullptr};
           }
 
           auto narInfo = make_ref<NarInfo>();
@@ -254,21 +255,22 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache {
 
         state->insertNAR
             .use()(cache.id)(hashPart)(storePathToName(info->path))(
-                narInfo ? narInfo->url : "", narInfo != 0)(
-                narInfo ? narInfo->compression : "", narInfo != 0)(
+                narInfo ? narInfo->url : "", narInfo != nullptr)(
+                narInfo ? narInfo->compression : "", narInfo != nullptr)(
                 narInfo && narInfo->fileHash ? narInfo->fileHash.to_string()
                                              : "",
                 narInfo && narInfo->fileHash)(
                 narInfo ? narInfo->fileSize : 0,
-                narInfo != 0 && narInfo->fileSize)(info->narHash.to_string())(
+                narInfo != nullptr &&
+                    narInfo->fileSize)(info->narHash.to_string())(
                 info->narSize)(concatStringsSep(" ", info->shortRefs()))(
                 info->deriver != "" ? baseNameOf(info->deriver) : "",
-                info->deriver !=
-                    "")(concatStringsSep(" ", info->sigs))(info->ca)(time(0))
+                info->deriver != "")(concatStringsSep(" ", info->sigs))(
+                info->ca)(time(nullptr))
             .exec();
 
       } else {
-        state->insertMissingNAR.use()(cache.id)(hashPart)(time(0)).exec();
+        state->insertMissingNAR.use()(cache.id)(hashPart)(time(nullptr)).exec();
       }
     });
   }
diff --git a/third_party/nix/src/libstore/optimise-store.cc b/third_party/nix/src/libstore/optimise-store.cc
index 7febe1b145f7..9eaf4cdc3c9e 100644
--- a/third_party/nix/src/libstore/optimise-store.cc
+++ b/third_party/nix/src/libstore/optimise-store.cc
@@ -1,9 +1,10 @@
+#include <cerrno>
+#include <cstdio>
 #include <cstdlib>
 #include <cstring>
 #include <regex>
+#include <utility>
 
-#include <errno.h>
-#include <stdio.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -27,7 +28,7 @@ static void makeWritable(const Path& path) {
 
 struct MakeReadOnly {
   Path path;
-  explicit MakeReadOnly(const Path& path) : path(path) {}
+  explicit MakeReadOnly(Path path) : path(std::move(path)) {}
   ~MakeReadOnly() {
     try {
       /* This will make the path read-only. */
diff --git a/third_party/nix/src/libstore/parsed-derivations.cc b/third_party/nix/src/libstore/parsed-derivations.cc
index 72ed36d32da6..ec158e0ab1a0 100644
--- a/third_party/nix/src/libstore/parsed-derivations.cc
+++ b/third_party/nix/src/libstore/parsed-derivations.cc
@@ -74,13 +74,13 @@ std::optional<Strings> ParsedDerivation::getStringsAttr(
             drvPath);
       }
       Strings res;
-      for (auto j = i->begin(); j != i->end(); ++j) {
-        if (!j->is_string()) {
+      for (const auto& j : *i) {
+        if (!j.is_string()) {
           throw Error(
               "attribute '%s' of derivation '%s' must be a list of strings",
               name, drvPath);
         }
-        res.push_back(j->get<std::string>());
+        res.push_back(j.get<std::string>());
       }
       return res;
     }
diff --git a/third_party/nix/src/libstore/pathlocks.cc b/third_party/nix/src/libstore/pathlocks.cc
index a0d7b721ec98..ac6d260f8414 100644
--- a/third_party/nix/src/libstore/pathlocks.cc
+++ b/third_party/nix/src/libstore/pathlocks.cc
@@ -97,7 +97,7 @@ bool PathLocks::lockPaths(const PathSet& paths, const string& waitMsg,
 
     AutoCloseFD fd;
 
-    while (1) {
+    while (true) {
       /* Open/create the lock file. */
       fd = openLockFile(lockPath, true);
 
@@ -136,7 +136,7 @@ bool PathLocks::lockPaths(const PathSet& paths, const string& waitMsg,
     }
 
     /* Use borrow so that the descriptor isn't closed. */
-    fds.push_back(FDPair(fd.release(), lockPath));
+    fds.emplace_back(fd.release(), lockPath);
   }
 
   return true;
diff --git a/third_party/nix/src/libstore/profiles.cc b/third_party/nix/src/libstore/profiles.cc
index 38ad0c01e461..3abdfaf1389f 100644
--- a/third_party/nix/src/libstore/profiles.cc
+++ b/third_party/nix/src/libstore/profiles.cc
@@ -1,8 +1,9 @@
 #include "profiles.hh"
 
-#include <errno.h>
+#include <cerrno>
+#include <cstdio>
+
 #include <glog/logging.h>
-#include <stdio.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -213,7 +214,7 @@ void deleteGenerationsOlderThan(const Path& profile, time_t t, bool dryRun) {
 
 void deleteGenerationsOlderThan(const Path& profile, const string& timeSpec,
                                 bool dryRun) {
-  time_t curTime = time(0);
+  time_t curTime = time(nullptr);
   string strDays = string(timeSpec, 0, timeSpec.size() - 1);
   int days;
 
diff --git a/third_party/nix/src/libstore/references.cc b/third_party/nix/src/libstore/references.cc
index 64b997ce3e68..c8cebaec08f3 100644
--- a/third_party/nix/src/libstore/references.cc
+++ b/third_party/nix/src/libstore/references.cc
@@ -18,11 +18,11 @@ static void search(const unsigned char* s, size_t len, StringSet& hashes,
   static bool initialised = false;
   static bool isBase32[256];
   if (!initialised) {
-    for (unsigned int i = 0; i < 256; ++i) {
-      isBase32[i] = false;
+    for (bool& i : isBase32) {
+      i = false;
     }
-    for (unsigned int i = 0; i < base32Chars.size(); ++i) {
-      isBase32[(unsigned char)base32Chars[i]] = true;
+    for (char base32Char : base32Chars) {
+      isBase32[(unsigned char)base32Char] = true;
     }
     initialised = true;
   }
@@ -59,7 +59,7 @@ struct RefScanSink : Sink {
 
   RefScanSink() : hashSink(htSHA256) {}
 
-  void operator()(const unsigned char* data, size_t len);
+  void operator()(const unsigned char* data, size_t len) override;
 };
 
 void RefScanSink::operator()(const unsigned char* data, size_t len) {
diff --git a/third_party/nix/src/libstore/remote-store.cc b/third_party/nix/src/libstore/remote-store.cc
index e1fcb749a3fe..564ba444d242 100644
--- a/third_party/nix/src/libstore/remote-store.cc
+++ b/third_party/nix/src/libstore/remote-store.cc
@@ -1,8 +1,8 @@
 #include "remote-store.hh"
 
+#include <cerrno>
 #include <cstring>
 
-#include <errno.h>
 #include <fcntl.h>
 #include <glog/logging.h>
 #include <sys/socket.h>
@@ -230,7 +230,7 @@ struct ConnectionHandle {
 
   RemoteStore::Connection* operator->() { return &*handle; }
 
-  void processStderr(Sink* sink = 0, Source* source = 0) {
+  void processStderr(Sink* sink = nullptr, Source* source = nullptr) {
     auto ex = handle->processStderr(sink, source);
     if (ex) {
       daemonException = true;
@@ -324,7 +324,7 @@ void RemoteStore::querySubstitutablePathInfos(const PathSet& paths,
   } else {
     conn->to << wopQuerySubstitutablePathInfos << paths;
     conn.processStderr();
-    size_t count = readNum<size_t>(conn->from);
+    auto count = readNum<size_t>(conn->from);
     for (size_t n = 0; n < count; n++) {
       Path path = readStorePath(*this, conn->from);
       SubstitutablePathInfo& info(infos[path]);
@@ -388,7 +388,7 @@ void RemoteStore::queryReferrers(const Path& path, PathSet& referrers) {
   auto conn(getConnection());
   conn->to << wopQueryReferrers << path;
   conn.processStderr();
-  PathSet referrers2 = readStorePaths<PathSet>(*this, conn->from);
+  auto referrers2 = readStorePaths<PathSet>(*this, conn->from);
   referrers.insert(referrers2.begin(), referrers2.end());
 }
 
@@ -442,7 +442,7 @@ void RemoteStore::addToStore(const ValidPathInfo& info, Source& source,
           ;
     });
 
-    conn.processStderr(0, source2.get());
+    conn.processStderr(nullptr, source2.get());
 
     auto importedPaths = readStorePaths<PathSet>(*this, conn->from);
     assert(importedPaths.size() <= 1);
@@ -457,7 +457,7 @@ void RemoteStore::addToStore(const ValidPathInfo& info, Source& source,
     if (!tunnel) {
       copyNAR(source, conn->to);
     }
-    conn.processStderr(0, tunnel ? &source : nullptr);
+    conn.processStderr(nullptr, tunnel ? &source : nullptr);
   }
 }
 
@@ -591,7 +591,7 @@ Roots RemoteStore::findRoots(bool censor) {
   auto conn(getConnection());
   conn->to << wopFindRoots;
   conn.processStderr();
-  size_t count = readNum<size_t>(conn->from);
+  auto count = readNum<size_t>(conn->from);
   Roots result;
   while (count--) {
     Path link = readString(conn->from);
@@ -704,7 +704,7 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink* sink,
       if (!source) {
         throw Error("no source");
       }
-      size_t len = readNum<size_t>(from);
+      auto len = readNum<size_t>(from);
       auto buf = std::make_unique<unsigned char[]>(len);
       writeString(buf.get(), source->read(buf.get(), len), to);
       to.flush();
@@ -742,7 +742,7 @@ static RegisterStoreImplementation regStore(
     [](const std::string& uri,
        const Store::Params& params) -> std::shared_ptr<Store> {
       if (std::string(uri, 0, uriScheme.size()) != uriScheme) {
-        return 0;
+        return nullptr;
       }
       return std::make_shared<UDSRemoteStore>(
           std::string(uri, uriScheme.size()), params);
diff --git a/third_party/nix/src/libstore/sqlite.cc b/third_party/nix/src/libstore/sqlite.cc
index f2650ed75337..2288277659a3 100644
--- a/third_party/nix/src/libstore/sqlite.cc
+++ b/third_party/nix/src/libstore/sqlite.cc
@@ -31,7 +31,7 @@ namespace nix {
 SQLite::SQLite(const Path& path) {
   if (sqlite3_open_v2(path.c_str(), &db,
                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
-                      0) != SQLITE_OK) {
+                      nullptr) != SQLITE_OK) {
     throw Error(format("cannot open SQLite database '%s'") % path);
   }
 }
@@ -48,7 +48,8 @@ SQLite::~SQLite() {
 
 void SQLite::exec(const std::string& stmt) {
   retrySQLite<void>([&]() {
-    if (sqlite3_exec(db, stmt.c_str(), 0, 0, 0) != SQLITE_OK) {
+    if (sqlite3_exec(db, stmt.c_str(), nullptr, nullptr, nullptr) !=
+        SQLITE_OK) {
       throwSQLiteError(db, format("executing SQLite statement '%s'") % stmt);
     }
   });
@@ -57,7 +58,7 @@ void SQLite::exec(const std::string& stmt) {
 void SQLiteStmt::create(sqlite3* db, const string& sql) {
   checkInterrupt();
   assert(!stmt);
-  if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, 0) != SQLITE_OK) {
+  if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr) != SQLITE_OK) {
     throwSQLiteError(db, fmt("creating statement '%s'", sql));
   }
   this->db = db;
@@ -149,14 +150,14 @@ bool SQLiteStmt::Use::isNull(int col) {
 
 SQLiteTxn::SQLiteTxn(sqlite3* db) {
   this->db = db;
-  if (sqlite3_exec(db, "begin;", 0, 0, 0) != SQLITE_OK) {
+  if (sqlite3_exec(db, "begin;", nullptr, nullptr, nullptr) != SQLITE_OK) {
     throwSQLiteError(db, "starting transaction");
   }
   active = true;
 }
 
 void SQLiteTxn::commit() {
-  if (sqlite3_exec(db, "commit;", 0, 0, 0) != SQLITE_OK) {
+  if (sqlite3_exec(db, "commit;", nullptr, nullptr, nullptr) != SQLITE_OK) {
     throwSQLiteError(db, "committing transaction");
   }
   active = false;
@@ -164,7 +165,8 @@ void SQLiteTxn::commit() {
 
 SQLiteTxn::~SQLiteTxn() {
   try {
-    if (active && sqlite3_exec(db, "rollback;", 0, 0, 0) != SQLITE_OK) {
+    if (active &&
+        sqlite3_exec(db, "rollback;", nullptr, nullptr, nullptr) != SQLITE_OK) {
       throwSQLiteError(db, "aborting transaction");
     }
   } catch (...) {
@@ -175,7 +177,7 @@ SQLiteTxn::~SQLiteTxn() {
 void handleSQLiteBusy(const SQLiteBusy& e) {
   static std::atomic<time_t> lastWarned{0};
 
-  time_t now = time(0);
+  time_t now = time(nullptr);
 
   if (now > lastWarned + 10) {
     lastWarned = now;
@@ -188,7 +190,7 @@ void handleSQLiteBusy(const SQLiteBusy& e) {
   struct timespec t;
   t.tv_sec = 0;
   t.tv_nsec = (random() % 100) * 1000 * 1000; /* <= 0.1s */
-  nanosleep(&t, 0);
+  nanosleep(&t, nullptr);
 }
 
 }  // namespace nix
diff --git a/third_party/nix/src/libstore/ssh-store.cc b/third_party/nix/src/libstore/ssh-store.cc
index 7728e00ec80c..9c49babcf2b2 100644
--- a/third_party/nix/src/libstore/ssh-store.cc
+++ b/third_party/nix/src/libstore/ssh-store.cc
@@ -27,7 +27,7 @@ class SSHStore : public RemoteStore {
 
   std::string getUri() override { return uriScheme + host; }
 
-  bool sameMachine() { return false; }
+  bool sameMachine() override { return false; }
 
   void narFromPath(const Path& path, Sink& sink) override;
 
@@ -78,7 +78,7 @@ static RegisterStoreImplementation regStore([](const std::string& uri,
                                                const Store::Params& params)
                                                 -> std::shared_ptr<Store> {
   if (std::string(uri, 0, uriScheme.size()) != uriScheme) {
-    return 0;
+    return nullptr;
   }
   return std::make_shared<SSHStore>(std::string(uri, uriScheme.size()), params);
 });
diff --git a/third_party/nix/src/libstore/ssh.cc b/third_party/nix/src/libstore/ssh.cc
index 1783732a1db5..d549d5c3657b 100644
--- a/third_party/nix/src/libstore/ssh.cc
+++ b/third_party/nix/src/libstore/ssh.cc
@@ -1,12 +1,14 @@
 #include "ssh.hh"
 
+#include <utility>
+
 namespace nix {
 
-SSHMaster::SSHMaster(const std::string& host, const std::string& keyFile,
+SSHMaster::SSHMaster(const std::string& host, std::string keyFile,
                      bool useMaster, bool compress, int logFD)
     : host(host),
       fakeSSH(host == "localhost"),
-      keyFile(keyFile),
+      keyFile(std::move(keyFile)),
       useMaster(useMaster && !fakeSSH),
       compress(compress),
       logFD(logFD) {
diff --git a/third_party/nix/src/libstore/ssh.hh b/third_party/nix/src/libstore/ssh.hh
index 7cdc69e0abe0..23952ccb1293 100644
--- a/third_party/nix/src/libstore/ssh.hh
+++ b/third_party/nix/src/libstore/ssh.hh
@@ -25,7 +25,7 @@ class SSHMaster {
   void addCommonSSHOpts(Strings& args);
 
  public:
-  SSHMaster(const std::string& host, const std::string& keyFile, bool useMaster,
+  SSHMaster(const std::string& host, std::string keyFile, bool useMaster,
             bool compress, int logFD = -1);
 
   struct Connection {
diff --git a/third_party/nix/src/libstore/store-api.cc b/third_party/nix/src/libstore/store-api.cc
index 7658a5110092..84b5841a82e6 100644
--- a/third_party/nix/src/libstore/store-api.cc
+++ b/third_party/nix/src/libstore/store-api.cc
@@ -251,7 +251,7 @@ bool Store::isValidPath(const Path& storePath) {
     auto res = state_->pathInfoCache.get(hashPart);
     if (res) {
       stats.narInfoReadAverted++;
-      return *res != 0;
+      return *res != nullptr;
     }
   }
 
@@ -261,7 +261,8 @@ bool Store::isValidPath(const Path& storePath) {
       stats.narInfoReadAverted++;
       auto state_(state.lock());
       state_->pathInfoCache.upsert(
-          hashPart, res.first == NarInfoDiskCache::oInvalid ? 0 : res.second);
+          hashPart,
+          res.first == NarInfoDiskCache::oInvalid ? nullptr : res.second);
       return res.first == NarInfoDiskCache::oValid;
     }
   }
@@ -270,7 +271,7 @@ bool Store::isValidPath(const Path& storePath) {
 
   if (diskCache && !valid) {
     // FIXME: handle valid = true case.
-    diskCache->upsertNarInfo(getUri(), hashPart, 0);
+    diskCache->upsertNarInfo(getUri(), hashPart, nullptr);
   }
 
   return valid;
@@ -329,7 +330,7 @@ void Store::queryPathInfo(const Path& storePath,
           auto state_(state.lock());
           state_->pathInfoCache.upsert(
               hashPart,
-              res.first == NarInfoDiskCache::oInvalid ? 0 : res.second);
+              res.first == NarInfoDiskCache::oInvalid ? nullptr : res.second);
           if (res.first == NarInfoDiskCache::oInvalid ||
               (res.second->path != storePath &&
                storePathToName(storePath) != "")) {
@@ -842,7 +843,7 @@ void Store::addToStore(const ValidPathInfo& info, const ref<std::string>& nar,
 namespace nix {
 
 RegisterStoreImplementation::Implementations*
-    RegisterStoreImplementation::implementations = 0;
+    RegisterStoreImplementation::implementations = nullptr;
 
 /* Split URI into protocol+hierarchy part and its parameter set. */
 std::pair<std::string, Store::Params> splitUriAndParams(
@@ -862,7 +863,7 @@ std::pair<std::string, Store::Params> splitUriAndParams(
               throw Error("invalid URI parameter '%s'", value);
             }
             try {
-              decoded += std::stoul(std::string(value, i + 1, 2), 0, 16);
+              decoded += std::stoul(std::string(value, i + 1, 2), nullptr, 16);
               i += 3;
             } catch (...) {
               throw Error("invalid URI parameter '%s'", value);
diff --git a/third_party/nix/src/libutil/archive.cc b/third_party/nix/src/libutil/archive.cc
index 855a3c465838..a316336ec73f 100644
--- a/third_party/nix/src/libutil/archive.cc
+++ b/third_party/nix/src/libutil/archive.cc
@@ -199,7 +199,7 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
 
   std::map<Path, int, CaseInsensitiveCompare> names;
 
-  while (1) {
+  while (true) {
     checkInterrupt();
 
     s = readString(source);
@@ -254,7 +254,7 @@ static void parse(ParseSink& sink, Source& source, const Path& path) {
         throw badArchive("expected open tag");
       }
 
-      while (1) {
+      while (true) {
         checkInterrupt();
 
         s = readString(source);
@@ -323,14 +323,14 @@ struct RestoreSink : ParseSink {
   Path dstPath;
   AutoCloseFD fd;
 
-  void createDirectory(const Path& path) {
+  void createDirectory(const Path& path) override {
     Path p = dstPath + path;
     if (mkdir(p.c_str(), 0777) == -1) {
       throw SysError(format("creating directory '%1%'") % p);
     }
   };
 
-  void createRegularFile(const Path& path) {
+  void createRegularFile(const Path& path) override {
     Path p = dstPath + path;
     fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666);
     if (!fd) {
@@ -338,7 +338,7 @@ struct RestoreSink : ParseSink {
     }
   }
 
-  void isExecutable() {
+  void isExecutable() override {
     struct stat st;
     if (fstat(fd.get(), &st) == -1) {
       throw SysError("fstat");
@@ -348,7 +348,7 @@ struct RestoreSink : ParseSink {
     }
   }
 
-  void preallocateContents(unsigned long long len) {
+  void preallocateContents(unsigned long long len) override {
 #if HAVE_POSIX_FALLOCATE
     if (len) {
       errno = posix_fallocate(fd.get(), 0, len);
@@ -363,11 +363,11 @@ struct RestoreSink : ParseSink {
 #endif
   }
 
-  void receiveContents(unsigned char* data, unsigned int len) {
+  void receiveContents(unsigned char* data, unsigned int len) override {
     writeFull(fd.get(), data, len);
   }
 
-  void createSymlink(const Path& path, const string& target) {
+  void createSymlink(const Path& path, const string& target) override {
     Path p = dstPath + path;
     nix::createSymlink(target, p);
   }
diff --git a/third_party/nix/src/libutil/compression.cc b/third_party/nix/src/libutil/compression.cc
index 93e2360bd58c..851a7f817994 100644
--- a/third_party/nix/src/libutil/compression.cc
+++ b/third_party/nix/src/libutil/compression.cc
@@ -57,7 +57,7 @@ struct XzDecompressionSink : CompressionSink {
     strm.avail_out = sizeof(outbuf);
   }
 
-  ~XzDecompressionSink() { lzma_end(&strm); }
+  ~XzDecompressionSink() override { lzma_end(&strm); }
 
   void finish() override {
     CompressionSink::flush();
@@ -103,7 +103,7 @@ struct BzipDecompressionSink : ChunkedCompressionSink {
     strm.avail_out = sizeof(outbuf);
   }
 
-  ~BzipDecompressionSink() { BZ2_bzDecompressEnd(&strm); }
+  ~BzipDecompressionSink() override { BZ2_bzDecompressEnd(&strm); }
 
   void finish() override {
     flush();
@@ -147,7 +147,7 @@ struct BrotliDecompressionSink : ChunkedCompressionSink {
     }
   }
 
-  ~BrotliDecompressionSink() { BrotliDecoderDestroyInstance(state); }
+  ~BrotliDecompressionSink() override { BrotliDecoderDestroyInstance(state); }
 
   void finish() override {
     flush();
@@ -249,7 +249,7 @@ struct XzCompressionSink : CompressionSink {
     strm.avail_out = sizeof(outbuf);
   }
 
-  ~XzCompressionSink() { lzma_end(&strm); }
+  ~XzCompressionSink() override { lzma_end(&strm); }
 
   void finish() override {
     CompressionSink::flush();
@@ -295,7 +295,7 @@ struct BzipCompressionSink : ChunkedCompressionSink {
     strm.avail_out = sizeof(outbuf);
   }
 
-  ~BzipCompressionSink() { BZ2_bzCompressEnd(&strm); }
+  ~BzipCompressionSink() override { BZ2_bzCompressEnd(&strm); }
 
   void finish() override {
     flush();
@@ -340,7 +340,7 @@ struct BrotliCompressionSink : ChunkedCompressionSink {
     }
   }
 
-  ~BrotliCompressionSink() { BrotliEncoderDestroyInstance(state); }
+  ~BrotliCompressionSink() override { BrotliEncoderDestroyInstance(state); }
 
   void finish() override {
     flush();
diff --git a/third_party/nix/src/libutil/config.cc b/third_party/nix/src/libutil/config.cc
index 9c8c6cf4b255..56f0c8c3e7cd 100644
--- a/third_party/nix/src/libutil/config.cc
+++ b/third_party/nix/src/libutil/config.cc
@@ -1,6 +1,8 @@
 #define GOOGLE_STRIP_LOG 0
 #include "config.hh"
 
+#include <utility>
+
 #include <glog/logging.h>
 
 #include "args.hh"
@@ -96,7 +98,7 @@ void AbstractConfig::applyConfigFile(const Path& path) {
         line = string(line, 0, hash);
       }
 
-      vector<string> tokens = tokenizeString<vector<string> >(line);
+      auto tokens = tokenizeString<vector<string> >(line);
       if (tokens.empty()) {
         continue;
       }
@@ -136,7 +138,7 @@ void AbstractConfig::applyConfigFile(const Path& path) {
 
       string name = tokens[0];
 
-      vector<string>::iterator i = tokens.begin();
+      auto i = tokens.begin();
       advance(i, 2);
 
       set(name,
@@ -171,10 +173,11 @@ void Config::convertToArgs(Args& args, const std::string& category) {
   }
 }
 
-AbstractSetting::AbstractSetting(const std::string& name,
-                                 const std::string& description,
-                                 const std::set<std::string>& aliases)
-    : name(name), description(description), aliases(aliases) {}
+AbstractSetting::AbstractSetting(std::string name, std::string description,
+                                 std::set<std::string> aliases)
+    : name(std::move(name)),
+      description(std::move(description)),
+      aliases(std::move(aliases)) {}
 
 void AbstractSetting::toJSON(JSONPlaceholder& out) { out.write(to_string()); }
 
diff --git a/third_party/nix/src/libutil/config.hh b/third_party/nix/src/libutil/config.hh
index 9735569d1084..f8055d4d3690 100644
--- a/third_party/nix/src/libutil/config.hh
+++ b/third_party/nix/src/libutil/config.hh
@@ -103,8 +103,8 @@ class AbstractSetting {
   bool overriden = false;
 
  protected:
-  AbstractSetting(const std::string& name, const std::string& description,
-                  const std::set<std::string>& aliases);
+  AbstractSetting(std::string name, std::string description,
+                  std::set<std::string> aliases);
 
   virtual ~AbstractSetting() {
     // Check against a gcc miscompilation causing our constructor
diff --git a/third_party/nix/src/libutil/serialise.cc b/third_party/nix/src/libutil/serialise.cc
index b51ed2105b4d..0d9b069a2887 100644
--- a/third_party/nix/src/libutil/serialise.cc
+++ b/third_party/nix/src/libutil/serialise.cc
@@ -4,6 +4,7 @@
 #include <cerrno>
 #include <cstring>
 #include <memory>
+#include <utility>
 
 #include "glog/logging.h"
 #include "util.hh"
@@ -159,7 +160,7 @@ size_t StringSource::read(unsigned char* data, size_t len) {
 std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
                                      std::function<void()> eof) {
   struct SinkToSource : Source {
-    typedef boost::coroutines2::coroutine<std::string> coro_t;
+    using coro_t = boost::coroutines2::coroutine<std::string>;
 
     std::function<void(Sink&)> fun;
     std::function<void()> eof;
@@ -167,7 +168,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun,
     bool started = false;
 
     SinkToSource(std::function<void(Sink&)> fun, std::function<void()> eof)
-        : fun(fun), eof(eof) {}
+        : fun(std::move(fun)), eof(std::move(eof)) {}
 
     std::string cur;
     size_t pos = 0;
diff --git a/third_party/nix/src/libutil/util.cc b/third_party/nix/src/libutil/util.cc
index 213a9a0d6ab9..a4e382f12ebe 100644
--- a/third_party/nix/src/libutil/util.cc
+++ b/third_party/nix/src/libutil/util.cc
@@ -2,6 +2,7 @@
 
 #include <cctype>
 #include <cerrno>
+#include <climits>
 #include <cstdio>
 #include <cstdlib>
 #include <cstring>
@@ -9,10 +10,10 @@
 #include <iostream>
 #include <sstream>
 #include <thread>
+#include <utility>
 
 #include <fcntl.h>
 #include <grp.h>
-#include <limits.h>
 #include <pwd.h>
 #include <sys/ioctl.h>
 #include <sys/types.h>
@@ -122,7 +123,7 @@ Path canonPath(const Path& path, bool resolveSymlinks) {
      arbitrary (but high) limit to prevent infinite loops. */
   unsigned int followCount = 0, maxFollow = 1024;
 
-  while (1) {
+  while (true) {
     /* Skip slashes. */
     while (i != end && *i == '/') {
       i++;
@@ -354,7 +355,7 @@ void writeFile(const Path& path, Source& source, mode_t mode) {
 
 string readLine(int fd) {
   string s;
-  while (1) {
+  while (true) {
     checkInterrupt();
     char ch;
     // FIXME: inefficient
@@ -446,7 +447,7 @@ Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid,
   int localCounter = 0;
   int& counter(useGlobalCounter ? globalCounter : localCounter);
 
-  while (1) {
+  while (true) {
     checkInterrupt();
     Path tmpDir = tempName(tmpRoot, prefix, includePid, counter);
     if (mkdir(tmpDir.c_str(), mode) == 0) {
@@ -515,8 +516,7 @@ Path getConfigDir() {
 std::vector<Path> getConfigDirs() {
   Path configHome = getConfigDir();
   string configDirs = getEnv("XDG_CONFIG_DIRS");
-  std::vector<Path> result =
-      tokenizeString<std::vector<string>>(configDirs, ":");
+  auto result = tokenizeString<std::vector<string>>(configDirs, ":");
   result.insert(result.begin(), configHome);
   return result;
 }
@@ -648,7 +648,7 @@ void drainFD(int fd, Sink& sink, bool block) {
   }
 
   std::vector<unsigned char> buf(64 * 1024);
-  while (1) {
+  while (true) {
     checkInterrupt();
     ssize_t rd = read(fd, buf.data(), buf.size());
     if (rd == -1) {
@@ -670,7 +670,7 @@ void drainFD(int fd, Sink& sink, bool block) {
 
 AutoDelete::AutoDelete() : del{false} {}
 
-AutoDelete::AutoDelete(const string& p, bool recursive) : path(p) {
+AutoDelete::AutoDelete(string p, bool recursive) : path(std::move(p)) {
   del = true;
   this->recursive = recursive;
 }
@@ -759,7 +759,7 @@ void Pipe::create() {
 
 //////////////////////////////////////////////////////////////////////
 
-Pid::Pid() {}
+Pid::Pid() = default;
 
 Pid::Pid(pid_t pid) : pid(pid) {}
 
@@ -802,7 +802,7 @@ int Pid::kill() {
 
 int Pid::wait() {
   assert(pid != -1);
-  while (1) {
+  while (true) {
     int status;
     int res = waitpid(pid, &status, 0);
     if (res == pid) {
@@ -939,7 +939,7 @@ std::vector<char*> stringsToCharPtrs(const Strings& ss) {
   for (auto& s : ss) {
     res.push_back((char*)s.c_str());
   }
-  res.push_back(0);
+  res.push_back(nullptr);
   return res;
 }
 
@@ -1031,7 +1031,7 @@ void runProgram2(const RunOptions& options) {
           throw SysError("setgid failed");
         }
         /* Drop all other groups if we're setgid. */
-        if (options.gid && setgroups(0, 0) == -1) {
+        if (options.gid && setgroups(0, nullptr) == -1) {
           throw SysError("setgroups failed");
         }
         if (options.uid && setuid(*options.uid) == -1) {
diff --git a/third_party/nix/src/libutil/util.hh b/third_party/nix/src/libutil/util.hh
index a7e9b20fd560..2439b3da5373 100644
--- a/third_party/nix/src/libutil/util.hh
+++ b/third_party/nix/src/libutil/util.hh
@@ -173,7 +173,7 @@ class AutoDelete {
 
  public:
   AutoDelete();
-  AutoDelete(const Path& p, bool recursive = true);
+  AutoDelete(Path p, bool recursive = true);
   ~AutoDelete();
   void cancel();
   void reset(const Path& p, bool recursive = true);
diff --git a/third_party/nix/src/libutil/xml-writer.cc b/third_party/nix/src/libutil/xml-writer.cc
index ed41286cc1a3..11cd632399ad 100644
--- a/third_party/nix/src/libutil/xml-writer.cc
+++ b/third_party/nix/src/libutil/xml-writer.cc
@@ -1,6 +1,6 @@
 #include "xml-writer.hh"
 
-#include <assert.h>
+#include <cassert>
 
 namespace nix {
 
@@ -68,8 +68,7 @@ void XMLWriter::writeEmptyElement(const string& name, const XMLAttrs& attrs) {
 void XMLWriter::writeAttrs(const XMLAttrs& attrs) {
   for (auto& i : attrs) {
     output << " " << i.first << "=\"";
-    for (size_t j = 0; j < i.second.size(); ++j) {
-      char c = i.second[j];
+    for (char c : i.second) {
       if (c == '"') {
         output << "&quot;";
       } else if (c == '<') {
diff --git a/third_party/nix/src/nix-build/nix-build.cc b/third_party/nix/src/nix-build/nix-build.cc
index bf20d50dbb20..b2cc303ba816 100644
--- a/third_party/nix/src/nix-build/nix-build.cc
+++ b/third_party/nix/src/nix-build/nix-build.cc
@@ -118,7 +118,7 @@ static void _main(int argc, char** argv) {
         lines.pop_front();
         inShebang = true;
         for (int i = 2; i < argc; ++i) {
-          savedArgs.push_back(argv[i]);
+          savedArgs.emplace_back(argv[i]);
         }
         args.clear();
         for (auto line : lines) {
diff --git a/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc b/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc
index 29c68e963716..dee803ada38f 100644
--- a/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc
+++ b/third_party/nix/src/nix-collect-garbage/nix-collect-garbage.cc
@@ -60,27 +60,27 @@ static int _main(int argc, char** argv) {
 
     GCOptions options;
 
-    parseCmdLine(
-        argc, argv, [&](Strings::iterator& arg, const Strings::iterator& end) {
-          if (*arg == "--help") {
-            showManPage("nix-collect-garbage");
-          } else if (*arg == "--version") {
-            printVersion("nix-collect-garbage");
-          } else if (*arg == "--delete-old" || *arg == "-d") {
-            removeOld = true;
-          } else if (*arg == "--delete-older-than") {
-            removeOld = true;
-            deleteOlderThan = getArg(*arg, arg, end);
-          } else if (*arg == "--dry-run") {
-            dryRun = true;
-          } else if (*arg == "--max-freed") {
-            long long maxFreed = getIntArg<long long>(*arg, arg, end, true);
-            options.maxFreed = maxFreed >= 0 ? maxFreed : 0;
-          } else {
-            return false;
-          }
-          return true;
-        });
+    parseCmdLine(argc, argv,
+                 [&](Strings::iterator& arg, const Strings::iterator& end) {
+                   if (*arg == "--help") {
+                     showManPage("nix-collect-garbage");
+                   } else if (*arg == "--version") {
+                     printVersion("nix-collect-garbage");
+                   } else if (*arg == "--delete-old" || *arg == "-d") {
+                     removeOld = true;
+                   } else if (*arg == "--delete-older-than") {
+                     removeOld = true;
+                     deleteOlderThan = getArg(*arg, arg, end);
+                   } else if (*arg == "--dry-run") {
+                     dryRun = true;
+                   } else if (*arg == "--max-freed") {
+                     auto maxFreed = getIntArg<long long>(*arg, arg, end, true);
+                     options.maxFreed = maxFreed >= 0 ? maxFreed : 0;
+                   } else {
+                     return false;
+                   }
+                   return true;
+                 });
 
     initPlugins();
 
diff --git a/third_party/nix/src/nix-daemon/nix-daemon.cc b/third_party/nix/src/nix-daemon/nix-daemon.cc
index e3ebb4767894..14c3eb7ed278 100644
--- a/third_party/nix/src/nix-daemon/nix-daemon.cc
+++ b/third_party/nix/src/nix-daemon/nix-daemon.cc
@@ -1,13 +1,13 @@
 #include <algorithm>
+#include <cerrno>
+#include <climits>
+#include <csignal>
 #include <cstring>
 
-#include <errno.h>
 #include <fcntl.h>
 #include <glog/logging.h>
 #include <grp.h>
-#include <limits.h>
 #include <pwd.h>
-#include <signal.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
@@ -74,7 +74,8 @@ struct TunnelLogger {
 
   unsigned int clientVersion;
 
-  explicit TunnelLogger(unsigned int clientVersion) : clientVersion(clientVersion) {}
+  explicit TunnelLogger(unsigned int clientVersion)
+      : clientVersion(clientVersion) {}
 
   void enqueueMsg(const std::string& s) {
     auto state(state_.lock());
@@ -152,7 +153,7 @@ struct TunnelLogger {
 struct TunnelSink : Sink {
   Sink& to;
   explicit TunnelSink(Sink& to) : to(to) {}
-  virtual void operator()(const unsigned char* data, size_t len) {
+  void operator()(const unsigned char* data, size_t len) override {
     to << STDERR_WRITE;
     writeString(data, len, to);
   }
@@ -177,18 +178,18 @@ struct TunnelSource : BufferedSource {
 /* If the NAR archive contains a single file at top-level, then save
    the contents of the file to `s'.  Otherwise barf. */
 struct RetrieveRegularNARSink : ParseSink {
-  bool regular;
+  bool regular{true};
   string s;
 
-  RetrieveRegularNARSink() : regular(true) {}
+  RetrieveRegularNARSink() {}
 
-  void createDirectory(const Path& path) { regular = false; }
+  void createDirectory(const Path& path) override { regular = false; }
 
-  void receiveContents(unsigned char* data, unsigned int len) {
+  void receiveContents(unsigned char* data, unsigned int len) override {
     s.append((const char*)data, len);
   }
 
-  void createSymlink(const Path& path, const string& target) {
+  void createSymlink(const Path& path, const string& target) override {
     regular = false;
   }
 };
@@ -213,7 +214,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopQueryValidPaths: {
-      PathSet paths = readStorePaths<PathSet>(*store, from);
+      auto paths = readStorePaths<PathSet>(*store, from);
       logger->startWork();
       PathSet res = store->queryValidPaths(paths);
       logger->stopWork();
@@ -231,7 +232,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopQuerySubstitutablePaths: {
-      PathSet paths = readStorePaths<PathSet>(*store, from);
+      auto paths = readStorePaths<PathSet>(*store, from);
       logger->startWork();
       PathSet res = store->querySubstitutablePaths(paths);
       logger->stopWork();
@@ -343,7 +344,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     case wopAddTextToStore: {
       string suffix = readString(from);
       string s = readString(from);
-      PathSet refs = readStorePaths<PathSet>(*store, from);
+      auto refs = readStorePaths<PathSet>(*store, from);
       logger->startWork();
       Path path = store->addTextToStore(suffix, s, refs, NoRepair);
       logger->stopWork();
@@ -373,7 +374,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopBuildPaths: {
-      PathSet drvs = readStorePaths<PathSet>(*store, from);
+      auto drvs = readStorePaths<PathSet>(*store, from);
       BuildMode mode = bmNormal;
       if (GET_PROTOCOL_MINOR(clientVersion) >= 15) {
         mode = (BuildMode)readInt(from);
@@ -397,7 +398,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       Path drvPath = readStorePath(*store, from);
       BasicDerivation drv;
       readDerivation(from, *store, drv);
-      BuildMode buildMode = (BuildMode)readInt(from);
+      auto buildMode = (BuildMode)readInt(from);
       logger->startWork();
       if (!trusted) {
         throw Error("you are not privileged to build derivations");
@@ -570,7 +571,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
       SubstitutablePathInfos infos;
       store->querySubstitutablePathInfos({path}, infos);
       logger->stopWork();
-      SubstitutablePathInfos::iterator i = infos.find(path);
+      auto i = infos.find(path);
       if (i == infos.end()) {
         to << 0;
       } else {
@@ -581,7 +582,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopQuerySubstitutablePathInfos: {
-      PathSet paths = readStorePaths<PathSet>(*store, from);
+      auto paths = readStorePaths<PathSet>(*store, from);
       logger->startWork();
       SubstitutablePathInfos infos;
       store->querySubstitutablePathInfos(paths, infos);
@@ -652,7 +653,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
 
     case wopAddSignatures: {
       Path path = readStorePath(*store, from);
-      StringSet sigs = readStrings<StringSet>(from);
+      auto sigs = readStrings<StringSet>(from);
       logger->startWork();
       if (!trusted) {
         throw Error("you are not privileged to add signatures");
@@ -713,7 +714,7 @@ static void performOp(TunnelLogger* logger, ref<Store> store, bool trusted,
     }
 
     case wopQueryMissing: {
-      PathSet targets = readStorePaths<PathSet>(*store, from);
+      auto targets = readStorePaths<PathSet>(*store, from);
       logger->startWork();
       PathSet willBuild, willSubstitute, unknown;
       unsigned long long downloadSize, narSize;
@@ -834,7 +835,7 @@ static void sigChldHandler(int sigNo) {
   // Ensure we don't modify errno of whatever we've interrupted
   auto saved_errno = errno;
   /* Reap all dead children. */
-  while (waitpid(-1, 0, WNOHANG) > 0) {
+  while (waitpid(-1, nullptr, WNOHANG) > 0) {
     ;
   }
   errno = saved_errno;
@@ -991,7 +992,7 @@ static void daemonLoop(char** argv) {
   closeOnExec(fdSocket.get());
 
   /* Loop accepting connections. */
-  while (1) {
+  while (true) {
     try {
       /* Accept a connection. */
       struct sockaddr_un remoteAddr;
@@ -1012,10 +1013,10 @@ static void daemonLoop(char** argv) {
       bool trusted = false;
       PeerInfo peer = getPeerInfo(remote.get());
 
-      struct passwd* pw = peer.uidKnown ? getpwuid(peer.uid) : 0;
+      struct passwd* pw = peer.uidKnown ? getpwuid(peer.uid) : nullptr;
       string user = pw ? pw->pw_name : std::to_string(peer.uid);
 
-      struct group* gr = peer.gidKnown ? getgrgid(peer.gid) : 0;
+      struct group* gr = peer.gidKnown ? getgrgid(peer.gid) : nullptr;
       string group = gr ? gr->gr_name : std::to_string(peer.gid);
 
       Strings trustedUsers = settings.trustedUsers;
diff --git a/third_party/nix/src/nix-env/nix-env.cc b/third_party/nix/src/nix-env/nix-env.cc
index 2a4f94bfafe8..86340d5c9138 100644
--- a/third_party/nix/src/nix-env/nix-env.cc
+++ b/third_party/nix/src/nix-env/nix-env.cc
@@ -57,7 +57,7 @@ struct Globals {
   bool prebuiltOnly;
 };
 
-typedef void (*Operation)(Globals& globals, Strings opFlags, Strings opArgs);
+using Operation = void (*)(Globals&, Strings, Strings);
 
 static string needArg(Strings::iterator& i, Strings& args, const string& arg) {
   if (i == args.end()) {
@@ -234,8 +234,7 @@ static DrvInfos filterBySelector(EvalState& state, const DrvInfos& allElems,
     typedef list<std::pair<DrvInfo, unsigned int> > Matches;
     Matches matches;
     unsigned int n = 0;
-    for (DrvInfos::const_iterator j = allElems.begin(); j != allElems.end();
-         ++j, ++n) {
+    for (auto j = allElems.begin(); j != allElems.end(); ++j, ++n) {
       DrvName drvName(j->queryName());
       if (i.matches(drvName)) {
         i.hits++;
@@ -260,7 +259,7 @@ static DrvInfos filterBySelector(EvalState& state, const DrvInfos& allElems,
         DrvName drvName(j.first.queryName());
         long d = 1;
 
-        Newest::iterator k = newest.find(drvName.name);
+        auto k = newest.find(drvName.name);
 
         if (k != newest.end()) {
           d = j.first.querySystem() == k->second.first.querySystem()
@@ -499,7 +498,7 @@ static void installDerivations(Globals& globals, const Strings& args,
 }
 
 static void opInstall(Globals& globals, Strings opFlags, Strings opArgs) {
-  for (Strings::iterator i = opFlags.begin(); i != opFlags.end();) {
+  for (auto i = opFlags.begin(); i != opFlags.end();) {
     string arg = *i++;
     if (parseInstallSourceOptions(globals, i, opFlags, arg)) {
       ;
@@ -554,7 +553,7 @@ static void upgradeDerivations(Globals& globals, const Strings& args,
            priority.  If there are still multiple matches,
            take the one with the highest version.
            Do not upgrade if it would decrease the priority. */
-        DrvInfos::iterator bestElem = availElems.end();
+        auto bestElem = availElems.end();
         string bestVersion;
         for (auto j = availElems.begin(); j != availElems.end(); ++j) {
           if (comparePriorities(*globals.state, i, *j) > 0) {
@@ -617,7 +616,7 @@ static void upgradeDerivations(Globals& globals, const Strings& args,
 
 static void opUpgrade(Globals& globals, Strings opFlags, Strings opArgs) {
   UpgradeType upgradeType = utLt;
-  for (Strings::iterator i = opFlags.begin(); i != opFlags.end();) {
+  for (auto i = opFlags.begin(); i != opFlags.end();) {
     string arg = *i++;
     if (parseInstallSourceOptions(globals, i, opFlags, arg)) {
       ;
@@ -652,7 +651,7 @@ static void opSetFlag(Globals& globals, Strings opFlags, Strings opArgs) {
     throw UsageError("not enough arguments to '--set-flag'");
   }
 
-  Strings::iterator arg = opArgs.begin();
+  auto arg = opArgs.begin();
   string flagName = *arg++;
   string flagValue = *arg++;
   DrvNames selectors = drvNamesFromArgs(Strings(arg, opArgs.end()));
@@ -691,7 +690,7 @@ static void opSet(Globals& globals, Strings opFlags, Strings opArgs) {
     throw Error("--set is not supported for this Nix store");
   }
 
-  for (Strings::iterator i = opFlags.begin(); i != opFlags.end();) {
+  for (auto i = opFlags.begin(); i != opFlags.end();) {
     string arg = *i++;
     if (parseInstallSourceOptions(globals, i, opFlags, arg)) {
       ;
@@ -790,7 +789,7 @@ static bool cmpElemByName(const DrvInfo& a, const DrvInfo& b) {
                                  b_name.end(), cmpChars);
 }
 
-typedef list<Strings> Table;
+using Table = list<Strings>;
 
 void printTable(Table& table) {
   auto nrColumns = table.size() > 0 ? table.front().size() : 0;
@@ -911,7 +910,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) {
 
   settings.readOnlyMode = true; /* makes evaluation a bit faster */
 
-  for (Strings::iterator i = opFlags.begin(); i != opFlags.end();) {
+  for (auto i = opFlags.begin(); i != opFlags.end();) {
     string arg = *i++;
     if (arg == "--status" || arg == "-s") {
       printStatus = true;
@@ -1392,7 +1391,7 @@ static void opVersion(Globals& globals, Strings opFlags, Strings opArgs) {
 static int _main(int argc, char** argv) {
   {
     Strings opFlags, opArgs;
-    Operation op = 0;
+    Operation op = nullptr;
     RepairFlag repair = NoRepair;
     string file;
 
diff --git a/third_party/nix/src/nix-store/nix-store.cc b/third_party/nix/src/nix-store/nix-store.cc
index 75cbae3f0f25..c6028ea3e7bc 100644
--- a/third_party/nix/src/nix-store/nix-store.cc
+++ b/third_party/nix/src/nix-store/nix-store.cc
@@ -28,7 +28,7 @@ using namespace nix;
 using std::cin;
 using std::cout;
 
-typedef void (*Operation)(Strings opFlags, Strings opArgs);
+using Operation = void (*)(Strings, Strings);
 
 static Path gcRoot;
 static int rootNr = 0;
@@ -77,7 +77,7 @@ static PathSet realisePath(Path path, bool build = true) {
 
     PathSet outputs;
     for (auto& j : p.second) {
-      DerivationOutputs::iterator i = drv.outputs.find(j);
+      auto i = drv.outputs.find(j);
       if (i == drv.outputs.end()) {
         throw Error(
             format("derivation '%1%' does not have an output named '%2%'") %
@@ -246,7 +246,7 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs) {
     throw UsageError(format("'--print-fixed-path' requires three arguments"));
   }
 
-  Strings::iterator i = opArgs.begin();
+  auto i = opArgs.begin();
   HashType hashAlgo = parseHashType(*i++);
   string hash = *i++;
   string name = *i++;
@@ -427,8 +427,7 @@ static void opQuery(Strings opFlags, Strings opArgs) {
         }
       }
       Paths sorted = store->topoSortPaths(paths);
-      for (Paths::reverse_iterator i = sorted.rbegin(); i != sorted.rend();
-           ++i) {
+      for (auto i = sorted.rbegin(); i != sorted.rend(); ++i) {
         cout << format("%s\n") % *i;
       }
       break;
@@ -446,7 +445,7 @@ static void opQuery(Strings opFlags, Strings opArgs) {
       for (auto& i : opArgs) {
         Path path = useDeriver(store->followLinksToStorePath(i));
         Derivation drv = store->derivationFromPath(path);
-        StringPairs::iterator j = drv.env.find(bindingName);
+        auto j = drv.env.find(bindingName);
         if (j == drv.env.end()) {
           throw Error(
               format(
@@ -607,7 +606,7 @@ static void registerValidity(bool reregister, bool hashGiven,
                              bool canonicalise) {
   ValidPathInfos infos;
 
-  while (1) {
+  while (true) {
     ValidPathInfo info = decodeValidPathInfo(cin, hashGiven);
     if (info.path == "") {
       break;
@@ -701,7 +700,7 @@ static void opGC(Strings opFlags, Strings opArgs) {
     } else if (*i == "--delete") {
       options.action = GCOptions::gcDeleteDead;
     } else if (*i == "--max-freed") {
-      long long maxFreed = getIntArg<long long>(*i, i, opFlags.end(), true);
+      auto maxFreed = getIntArg<long long>(*i, i, opFlags.end(), true);
       options.maxFreed = maxFreed >= 0 ? maxFreed : 0;
     } else {
       throw UsageError(format("bad sub-operation '%1%' in GC") % *i);
@@ -966,7 +965,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
       case cmdQueryValidPaths: {
         bool lock = readInt(in);
         bool substitute = readInt(in);
-        PathSet paths = readStorePaths<PathSet>(*store, in);
+        auto paths = readStorePaths<PathSet>(*store, in);
         if (lock && writeAllowed) {
           for (auto& path : paths) {
             store->addTempRoot(path);
@@ -1004,7 +1003,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
       }
 
       case cmdQueryPathInfos: {
-        PathSet paths = readStorePaths<PathSet>(*store, in);
+        auto paths = readStorePaths<PathSet>(*store, in);
         // !!! Maybe we want a queryPathInfos?
         for (auto& i : paths) {
           try {
@@ -1048,7 +1047,7 @@ static void opServe(Strings opFlags, Strings opArgs) {
         if (!writeAllowed) {
           throw Error("building paths is not allowed");
         }
-        PathSet paths = readStorePaths<PathSet>(*store, in);
+        auto paths = readStorePaths<PathSet>(*store, in);
 
         getBuildSettings();
 
@@ -1186,7 +1185,7 @@ static void opVersion(Strings opFlags, Strings opArgs) {
 static int _main(int argc, char** argv) {
   {
     Strings opFlags, opArgs;
-    Operation op = 0;
+    Operation op = nullptr;
 
     parseCmdLine(argc, argv,
                  [&](Strings::iterator& arg, const Strings::iterator& end) {
diff --git a/third_party/nix/src/nix/command.cc b/third_party/nix/src/nix/command.cc
index b35fb1be9898..b0efcb823dd6 100644
--- a/third_party/nix/src/nix/command.cc
+++ b/third_party/nix/src/nix/command.cc
@@ -1,11 +1,13 @@
 #include "command.hh"
 
+#include <utility>
+
 #include "derivations.hh"
 #include "store-api.hh"
 
 namespace nix {
 
-Commands* RegisterCommand::commands = 0;
+Commands* RegisterCommand::commands = nullptr;
 
 void Command::printHelp(const string& programName, std::ostream& out) {
   Args::printHelp(programName, out);
@@ -22,7 +24,8 @@ void Command::printHelp(const string& programName, std::ostream& out) {
   }
 }
 
-MultiCommand::MultiCommand(const Commands& _commands) : commands(_commands) {
+MultiCommand::MultiCommand(Commands _commands)
+    : commands(std::move(_commands)) {
   expectedArgs.push_back(ExpectedArg{
       "command", 1, true, [=](std::vector<std::string> ss) {
         assert(!command);
@@ -82,7 +85,7 @@ bool MultiCommand::processArgs(const Strings& args, bool finish) {
   }
 }
 
-StoreCommand::StoreCommand() {}
+StoreCommand::StoreCommand() = default;
 
 ref<Store> StoreCommand::getStore() {
   if (!_store) {
diff --git a/third_party/nix/src/nix/command.hh b/third_party/nix/src/nix/command.hh
index a86f4782133f..829ce080d3a2 100644
--- a/third_party/nix/src/nix/command.hh
+++ b/third_party/nix/src/nix/command.hh
@@ -149,7 +149,7 @@ class MultiCommand : virtual Args {
 
   std::shared_ptr<Command> command;
 
-  MultiCommand(const Commands& commands);
+  MultiCommand(Commands commands);
 
   void printHelp(const string& programName, std::ostream& out) override;
 
diff --git a/third_party/nix/src/nix/installables.cc b/third_party/nix/src/nix/installables.cc
index 2d896e3bb9bb..06419f1f122d 100644
--- a/third_party/nix/src/nix/installables.cc
+++ b/third_party/nix/src/nix/installables.cc
@@ -1,4 +1,5 @@
 #include <regex>
+#include <utility>
 
 #include "attr-path.hh"
 #include "command.hh"
@@ -100,7 +101,8 @@ Buildable Installable::toBuildable() {
 struct InstallableStorePath : Installable {
   Path storePath;
 
-  explicit InstallableStorePath(const Path& storePath) : storePath(storePath) {}
+  explicit InstallableStorePath(Path storePath)
+      : storePath(std::move(storePath)) {}
 
   std::string what() override { return storePath; }
 
@@ -160,8 +162,8 @@ struct InstallableValue : Installable {
 struct InstallableExpr : InstallableValue {
   std::string text;
 
-  InstallableExpr(SourceExprCommand& cmd, const std::string& text)
-      : InstallableValue(cmd), text(text) {}
+  InstallableExpr(SourceExprCommand& cmd, std::string text)
+      : InstallableValue(cmd), text(std::move(text)) {}
 
   std::string what() override { return text; }
 
@@ -175,8 +177,8 @@ struct InstallableExpr : InstallableValue {
 struct InstallableAttrPath : InstallableValue {
   std::string attrPath;
 
-  InstallableAttrPath(SourceExprCommand& cmd, const std::string& attrPath)
-      : InstallableValue(cmd), attrPath(attrPath) {}
+  InstallableAttrPath(SourceExprCommand& cmd, std::string attrPath)
+      : InstallableValue(cmd), attrPath(std::move(attrPath)) {}
 
   std::string what() override { return attrPath; }
 
diff --git a/third_party/nix/src/nix/legacy.cc b/third_party/nix/src/nix/legacy.cc
index 2860afe53a49..b851392b4276 100644
--- a/third_party/nix/src/nix/legacy.cc
+++ b/third_party/nix/src/nix/legacy.cc
@@ -2,6 +2,6 @@
 
 namespace nix {
 
-RegisterLegacyCommand::Commands* RegisterLegacyCommand::commands = 0;
+RegisterLegacyCommand::Commands* RegisterLegacyCommand::commands = nullptr;
 
 }
diff --git a/third_party/nix/src/nix/log.cc b/third_party/nix/src/nix/log.cc
index 29107bbdcdff..86f133e94a7a 100644
--- a/third_party/nix/src/nix/log.cc
+++ b/third_party/nix/src/nix/log.cc
@@ -8,7 +8,7 @@
 using namespace nix;
 
 struct CmdLog : InstallableCommand {
-  CmdLog() {}
+  CmdLog() = default;
 
   std::string name() override { return "log"; }
 
diff --git a/third_party/nix/src/nix/main.cc b/third_party/nix/src/nix/main.cc
index 23bc62887a88..54285bfa9313 100644
--- a/third_party/nix/src/nix/main.cc
+++ b/third_party/nix/src/nix/main.cc
@@ -179,7 +179,7 @@ void mainWrapped(int argc, char** argv) {
 }  // namespace nix
 
 int main(int argc, char* argv[]) {
-  FLAGS_logtostderr = 1;
+  FLAGS_logtostderr = true;
   google::InitGoogleLogging(argv[0]);
 
   return nix::handleExceptions(argv[0],
diff --git a/third_party/nix/src/nix/optimise-store.cc b/third_party/nix/src/nix/optimise-store.cc
index 7814a1bcabf0..5fdcfb742465 100644
--- a/third_party/nix/src/nix/optimise-store.cc
+++ b/third_party/nix/src/nix/optimise-store.cc
@@ -7,7 +7,7 @@
 using namespace nix;
 
 struct CmdOptimiseStore : StoreCommand {
-  CmdOptimiseStore() {}
+  CmdOptimiseStore() = default;
 
   std::string name() override { return "optimise-store"; }
 
diff --git a/third_party/nix/src/nix/repl.cc b/third_party/nix/src/nix/repl.cc
index 80921f77dcfb..9567ad4315db 100644
--- a/third_party/nix/src/nix/repl.cc
+++ b/third_party/nix/src/nix/repl.cc
@@ -1,10 +1,10 @@
 #include <climits>
+#include <csetjmp>
 #include <cstdlib>
 #include <cstring>
 #include <iostream>
 
 #include <glog/logging.h>
-#include <setjmp.h>
 
 #ifdef READLINE
 #include <readline/history.h>
@@ -73,7 +73,7 @@ struct NixRepl {
   Expr* parseString(string s);
   void evalString(string s, Value& v);
 
-  typedef set<Value*> ValuesSeen;
+  using ValuesSeen = set<Value*>;
   std::ostream& printValue(std::ostream& str, Value& v, unsigned int maxDepth);
   std::ostream& printValue(std::ostream& str, Value& v, unsigned int maxDepth,
                            ValuesSeen& seen);
@@ -306,7 +306,7 @@ bool NixRepl::getLine(string& input, const std::string& prompt) {
       throw SysError("restoring signals");
     }
 
-    if (sigaction(SIGINT, &old, 0)) {
+    if (sigaction(SIGINT, &old, nullptr)) {
       throw SysError("restoring handler for SIGINT");
     }
   };
@@ -358,7 +358,7 @@ StringSet NixRepl::completePrefix(string prefix) {
     }
   } else if ((dot = cur.rfind('.')) == string::npos) {
     /* This is a variable name; look it up in the current scope. */
-    StringSet::iterator i = varNames.lower_bound(cur);
+    auto i = varNames.lower_bound(cur);
     while (i != varNames.end()) {
       if (string(*i, 0, cur.size()) != cur) {
         break;
diff --git a/third_party/nix/src/nix/run.cc b/third_party/nix/src/nix/run.cc
index 523aa87472d6..5459c38952d4 100644
--- a/third_party/nix/src/nix/run.cc
+++ b/third_party/nix/src/nix/run.cc
@@ -225,7 +225,7 @@ void chrootHelper(int argc, char** argv) {
     createDirs(tmpDir + storeDir);
 
     if (mount(realStoreDir.c_str(), (tmpDir + storeDir).c_str(), "", MS_BIND,
-              0) == -1) {
+              nullptr) == -1) {
       throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir);
     }
 
@@ -242,12 +242,13 @@ void chrootHelper(int argc, char** argv) {
       if (mkdir(dst.c_str(), 0700) == -1) {
         throw SysError("creating directory '%s'", dst);
       }
-      if (mount(src.c_str(), dst.c_str(), "", MS_BIND | MS_REC, 0) == -1) {
+      if (mount(src.c_str(), dst.c_str(), "", MS_BIND | MS_REC, nullptr) ==
+          -1) {
         throw SysError("mounting '%s' on '%s'", src, dst);
       }
     }
 
-    char* cwd = getcwd(0, 0);
+    char* cwd = getcwd(nullptr, 0);
     if (!cwd) {
       throw SysError("getting current directory");
     }
@@ -260,8 +261,8 @@ void chrootHelper(int argc, char** argv) {
     if (chdir(cwd) == -1) {
       throw SysError(format("chdir to '%s' in chroot") % cwd);
     }
-  } else if (mount(realStoreDir.c_str(), storeDir.c_str(), "", MS_BIND, 0) ==
-             -1) {
+  } else if (mount(realStoreDir.c_str(), storeDir.c_str(), "", MS_BIND,
+                   nullptr) == -1) {
     throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir);
   }
 
diff --git a/third_party/nix/src/nix/search.cc b/third_party/nix/src/nix/search.cc
index 5978d197fec6..78a1f21bc1e2 100644
--- a/third_party/nix/src/nix/search.cc
+++ b/third_party/nix/src/nix/search.cc
@@ -76,15 +76,14 @@ struct CmdSearch : SourceExprCommand, MixJSON {
     // Use "^" here instead of ".*" due to differences in resulting highlighting
     // (see #1893 -- libc++ claims empty search string is not in POSIX grammar)
     if (res.empty()) {
-      res.push_back("^");
+      res.emplace_back("^");
     }
 
     std::vector<std::regex> regexes;
     regexes.reserve(res.size());
 
     for (auto& re : res) {
-      regexes.push_back(
-          std::regex(re, std::regex::extended | std::regex::icase));
+      regexes.emplace_back(re, std::regex::extended | std::regex::icase);
     }
 
     auto state = getEvalState();
diff --git a/third_party/nix/src/nix/show-config.cc b/third_party/nix/src/nix/show-config.cc
index 85b3c330cddb..51f02ed61bbe 100644
--- a/third_party/nix/src/nix/show-config.cc
+++ b/third_party/nix/src/nix/show-config.cc
@@ -7,7 +7,7 @@
 using namespace nix;
 
 struct CmdShowConfig : Command, MixJSON {
-  CmdShowConfig() {}
+  CmdShowConfig() = default;
 
   std::string name() override { return "show-config"; }