From ef54f5da9fa30b5c302f2a49595ee5d041f9706a Mon Sep 17 00:00:00 2001 From: Kane York Date: Fri, 24 Jul 2020 21:09:44 -0700 Subject: fix(3p/nix): apply all clang-tidy fixes Change-Id: I265e763393422ee1881653527c91024458060825 Reviewed-on: https://cl.tvl.fyi/c/depot/+/1432 Tested-by: BuildkiteCI Reviewed-by: tazjin --- third_party/nix/.clang-tidy | 2 +- third_party/nix/src/build-remote/build-remote.cc | 1 - third_party/nix/src/libexpr/attr-path.cc | 2 +- third_party/nix/src/libexpr/eval.cc | 61 +++++++++--------- third_party/nix/src/libexpr/get-drvs.cc | 7 +- third_party/nix/src/libexpr/names.cc | 4 +- third_party/nix/src/libexpr/names.hh | 2 +- third_party/nix/src/libexpr/nixexpr.cc | 14 ++-- third_party/nix/src/libexpr/parser.cc | 19 +++--- third_party/nix/src/libexpr/primops.cc | 45 +++++++------ third_party/nix/src/libexpr/primops/context.cc | 13 ++-- third_party/nix/src/libexpr/primops/fetchGit.cc | 32 +++++---- .../nix/src/libexpr/primops/fetchMercurial.cc | 20 +++--- third_party/nix/src/libexpr/primops/fromTOML.cc | 26 +++++--- third_party/nix/src/libmain/shared.cc | 10 +-- third_party/nix/src/libmain/stack.cc | 10 +-- third_party/nix/src/libstore/binary-cache-store.cc | 15 +++-- third_party/nix/src/libstore/build.cc | 75 +++++++++++----------- third_party/nix/src/libstore/builtins/buildenv.cc | 44 ++++++++----- third_party/nix/src/libstore/builtins/fetchurl.cc | 18 ++++-- third_party/nix/src/libstore/crypto.cc | 13 ++-- third_party/nix/src/libstore/derivations.cc | 6 +- third_party/nix/src/libstore/download.cc | 35 +++++----- third_party/nix/src/libstore/gc.cc | 33 +++++----- third_party/nix/src/libstore/legacy-ssh-store.cc | 4 +- third_party/nix/src/libstore/local-fs-store.cc | 4 +- third_party/nix/src/libstore/local-store.cc | 34 +++++----- third_party/nix/src/libstore/nar-accessor.cc | 2 +- .../nix/src/libstore/nar-info-disk-cache.cc | 16 +++-- third_party/nix/src/libstore/optimise-store.cc | 10 +-- third_party/nix/src/libstore/pathlocks.cc | 4 +- third_party/nix/src/libstore/profiles.cc | 20 +++--- third_party/nix/src/libstore/references.cc | 24 +++---- third_party/nix/src/libstore/remote-fs-accessor.cc | 6 +- third_party/nix/src/libstore/remote-store.cc | 8 +-- third_party/nix/src/libstore/sqlite.cc | 4 +- third_party/nix/src/libstore/ssh.cc | 2 +- third_party/nix/src/libstore/store-api.cc | 9 +-- third_party/nix/src/libutil/archive.cc | 14 ++-- third_party/nix/src/libutil/args.cc | 4 +- third_party/nix/src/libutil/compression.cc | 22 +++---- third_party/nix/src/libutil/hash.cc | 15 +++-- third_party/nix/src/libutil/json.cc | 2 +- third_party/nix/src/libutil/serialise.cc | 20 +++--- third_party/nix/src/libutil/util.cc | 47 +++++++------- third_party/nix/src/libutil/util.hh | 2 +- third_party/nix/src/nix-build/nix-build.cc | 16 ++--- third_party/nix/src/nix-channel/nix-channel.cc | 6 +- .../nix/src/nix-copy-closure/nix-copy-closure.cc | 2 +- third_party/nix/src/nix-daemon/nix-daemon-proto.cc | 7 +- third_party/nix/src/nix-daemon/nix-daemon.cc | 56 ++++++++-------- third_party/nix/src/nix-env/nix-env.cc | 50 +++++++-------- third_party/nix/src/nix-env/user-env.cc | 10 +-- .../nix/src/nix-instantiate/nix-instantiate.cc | 4 +- .../nix/src/nix-prefetch-url/nix-prefetch-url.cc | 8 +-- third_party/nix/src/nix-store/nix-store.cc | 26 ++++---- third_party/nix/src/nix/edit.cc | 4 +- third_party/nix/src/nix/main.cc | 5 +- third_party/nix/src/nix/path-info.cc | 4 +- third_party/nix/src/nix/repl.cc | 40 ++++++------ third_party/nix/src/nix/search.cc | 6 +- third_party/nix/src/nix/verify.cc | 3 +- third_party/nix/src/tests/attr-set.cc | 6 +- third_party/nix/src/tests/language-tests.cc | 4 +- third_party/nix/src/tests/value-to-json.cc | 40 ++++++------ 65 files changed, 580 insertions(+), 497 deletions(-) (limited to 'third_party/nix') diff --git a/third_party/nix/.clang-tidy b/third_party/nix/.clang-tidy index ca2de10837fa..5b22be767fea 100644 --- a/third_party/nix/.clang-tidy +++ b/third_party/nix/.clang-tidy @@ -1,4 +1,4 @@ --- -Checks: 'abseil-c*,clang-analyzer-security-*,bugprone-*,google-*,modernize-*,cppcoreguidelines-*,misc-*' +Checks: 'abseil-c*,clang-analyzer-security-*,bugprone-*,google-*,modernize-*,cppcoreguidelines-*,misc-*,-modernize-use-trailing-return-type' WarningsAsErrors: 'abseil-*,clang-analyzer-security*' ... diff --git a/third_party/nix/src/build-remote/build-remote.cc b/third_party/nix/src/build-remote/build-remote.cc index 0aeadd0510d2..abf1270b706d 100644 --- a/third_party/nix/src/build-remote/build-remote.cc +++ b/third_party/nix/src/build-remote/build-remote.cc @@ -22,7 +22,6 @@ #include "nix/legacy.hh" using namespace nix; -using std::cin; static void handleAlarm(int sig) {} diff --git a/third_party/nix/src/libexpr/attr-path.cc b/third_party/nix/src/libexpr/attr-path.cc index a267e82b6ebe..07ffebff1ad3 100644 --- a/third_party/nix/src/libexpr/attr-path.cc +++ b/third_party/nix/src/libexpr/attr-path.cc @@ -51,7 +51,7 @@ Value* findAlongAttrPath(EvalState& state, const std::string& attrPath, for (auto& attr : tokens) { /* Is i an index (integer) or a normal attribute name? */ enum { apAttr, apIndex } apType = apAttr; - unsigned int attrIndex; + unsigned int attrIndex = 0; if (absl::SimpleAtoi(attr, &attrIndex)) { apType = apIndex; } diff --git a/third_party/nix/src/libexpr/eval.cc b/third_party/nix/src/libexpr/eval.cc index 5f267f2053fb..a762571fca2d 100644 --- a/third_party/nix/src/libexpr/eval.cc +++ b/third_party/nix/src/libexpr/eval.cc @@ -35,7 +35,7 @@ namespace nix { static char* dupString(const char* s) { - char* t; + char* t = nullptr; t = GC_STRDUP(s); if (t == nullptr) { throw std::bad_alloc(); @@ -195,7 +195,7 @@ static Symbol getName(const AttrName& name, EvalState& state, Env& env) { return std::visit( util::overloaded{[&](const Symbol& name) -> Symbol { return name; }, [&](Expr* expr) -> Symbol { - Value nameValue; + Value nameValue{}; expr->eval(state, env, nameValue); state.forceStringNoCtx(nameValue); return state.symbols.Create(nameValue.string.s); @@ -474,7 +474,7 @@ Value* EvalState::addConstant(const std::string& name, Value& v) { Value* EvalState::addPrimOp(const std::string& name, size_t arity, PrimOpFun primOp) { if (arity == 0) { - Value v; + Value v{}; primOp(*this, noPos, nullptr, v); return addConstant(name, v); } @@ -572,8 +572,8 @@ Value& mkString(Value& v, const std::string& s, const PathSet& context) { mkString(v, s.c_str()); if (!context.empty()) { size_t n = 0; - v.string.context = - (const char**)allocBytes((context.size() + 1) * sizeof(char*)); + v.string.context = static_cast( + allocBytes((context.size() + 1) * sizeof(char*))); for (auto& i : context) { v.string.context[n++] = dupString(i.c_str()); } @@ -599,7 +599,7 @@ inline Value* EvalState::lookupVar(Env* env, const ExprVar& var, bool noEval) { return nullptr; } Value* v = allocValue(); - evalAttrs(*env->up, (Expr*)env->values[0], *v); + evalAttrs(*env->up, reinterpret_cast(env->values[0]), *v); env->values[0] = v; env->type = Env::HasWithAttrs; } @@ -763,7 +763,7 @@ void EvalState::resetFileCache() { void EvalState::eval(Expr* e, Value& v) { e->eval(*this, baseEnv, v); } inline bool EvalState::evalBool(Env& env, Expr* e) { - Value v; + Value v{}; e->eval(*this, env, v); if (v.type != tBool) { throwTypeError("value is %1% while a Boolean was expected", v); @@ -772,7 +772,7 @@ inline bool EvalState::evalBool(Env& env, Expr* e) { } inline bool EvalState::evalBool(Env& env, Expr* e, const Pos& pos) { - Value v; + Value v{}; e->eval(*this, env, v); if (v.type != tBool) { throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos); @@ -813,7 +813,7 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& value) { in the original environment. */ size_t displ = 0; for (auto& attr : attrs) { - Value* vAttr; + Value* vAttr = nullptr; vAttr = attr.second.e->maybeThunk(state, attr.second.inherited ? env : env2); env2.values[displ++] = vAttr; @@ -829,7 +829,7 @@ void ExprAttrs::eval(EvalState& state, Env& env, Value& value) { /* Dynamic attrs apply *after* rec. */ for (auto& i : dynamicAttrs) { - Value nameVal; + Value nameVal{}; i.nameExpr->eval(state, *dynamicEnv, nameVal); state.forceValue(nameVal, i.pos); if (nameVal.type == tNull) { @@ -897,7 +897,7 @@ static std::string showAttrPath(EvalState& state, Env& env, unsigned long nrLookups = 0; void ExprSelect::eval(EvalState& state, Env& env, Value& v) { - Value vTmp; + Value vTmp{}; Pos* pos2 = nullptr; Value* vAttrs = &vTmp; @@ -948,7 +948,7 @@ void ExprSelect::eval(EvalState& state, Env& env, Value& v) { } void ExprOpHasAttr::eval(EvalState& state, Env& env, Value& v) { - Value vTmp; + Value vTmp{}; Value* vAttrs = &vTmp; e->eval(state, env, vTmp); @@ -976,7 +976,7 @@ void ExprLambda::eval(EvalState& state, Env& env, Value& v) { void ExprApp::eval(EvalState& state, Env& env, Value& v) { /* FIXME: vFun prevents GCC from doing tail call optimisation. */ - Value vFun; + Value vFun{}; e1->eval(state, env, vFun); state.callFunction(vFun, *(e2->maybeThunk(state, env)), v, pos); } @@ -1044,7 +1044,7 @@ void EvalState::callFunction(Value& fun, Value& arg, Value& v, const Pos& pos) { auto& fun2 = *allocValue(); fun2 = fun; /* !!! Should we use the attr pos here? */ - Value v2; + Value v2{}; // functors are called with the element itself as the first // parameter, which is partially applied here callFunction(*found->second.value, fun2, v2, pos); @@ -1176,7 +1176,9 @@ void ExprWith::eval(EvalState& state, Env& env, Value& v) { env2.up = &env; env2.prevWith = prevWith; env2.type = Env::HasWithExpr; - env2.values[0] = (Value*)attrs; + // TODO(kanepyork): Figure out what's going on here. `Expr* attrs` is not + // layout-compatible with Value*. + env2.values[0] = reinterpret_cast(attrs); body->eval(state, env2, v); } @@ -1199,17 +1201,17 @@ void ExprOpNot::eval(EvalState& state, Env& env, Value& v) { } void ExprOpEq::eval(EvalState& state, Env& env, Value& v) { - Value v1; + Value v1{}; e1->eval(state, env, v1); - Value v2; + Value v2{}; e2->eval(state, env, v2); mkBool(v, state.eqValues(v1, v2)); } void ExprOpNEq::eval(EvalState& state, Env& env, Value& v) { - Value v1; + Value v1{}; e1->eval(state, env, v1); - Value v2; + Value v2{}; e2->eval(state, env, v2); mkBool(v, !state.eqValues(v1, v2)); } @@ -1227,8 +1229,8 @@ void ExprOpImpl::eval(EvalState& state, Env& env, Value& v) { } void ExprOpUpdate::eval(EvalState& state, Env& env, Value& dest) { - Value v1; - Value v2; + Value v1{}; + Value v2{}; state.evalAttrs(env, e1, v1); state.evalAttrs(env, e2, v2); @@ -1240,9 +1242,9 @@ void ExprOpUpdate::eval(EvalState& state, Env& env, Value& dest) { } void ExprOpConcatLists::eval(EvalState& state, Env& env, Value& v) { - Value v1; + Value v1{}; e1->eval(state, env, v1); - Value v2; + Value v2{}; e2->eval(state, env, v2); state.concatLists(v, {&v1, &v2}, pos); } @@ -1270,7 +1272,7 @@ void ExprConcatStrings::eval(EvalState& state, Env& env, Value& v) { ValueType firstType = tString; for (auto& i : *es) { - Value vTmp; + Value vTmp{}; i->eval(state, env, vTmp); /* If the first element is a path, then the result will also @@ -1471,7 +1473,7 @@ std::optional EvalState::tryAttrsToString(const Pos& pos, Value& v, bool copyToStore) { auto i = v.attrs->find(sToString); if (i != v.attrs->end()) { - Value v1; + Value v1{}; callFunction(*i->second.value, v, v1, pos); return coerceToString(pos, v1, context, coerceMore, copyToStore); } @@ -1691,9 +1693,10 @@ bool EvalState::eqValues(Value& v1, Value& v2) { void EvalState::printStats() { bool showStats = getEnv("NIX_SHOW_STATS", "0") != "0"; - struct rusage buf; + struct rusage buf {}; getrusage(RUSAGE_SELF, &buf); - float cpuTime = buf.ru_utime.tv_sec + ((float)buf.ru_utime.tv_usec / 1000000); + float cpuTime = buf.ru_utime.tv_sec + + (static_cast(buf.ru_utime.tv_usec) / 1000000); uint64_t bEnvs = nrEnvs * sizeof(Env) + nrValuesInEnvs * sizeof(Value*); uint64_t bLists = nrListElems * sizeof(Value*); @@ -1702,8 +1705,8 @@ void EvalState::printStats() { nrAttrsets * sizeof(Bindings) + nrAttrsInAttrsets * sizeof(Attr); #if HAVE_BOEHMGC - GC_word heapSize; - GC_word totalBytes; + GC_word heapSize = 0; + GC_word totalBytes = 0; GC_get_heap_usage_safe(&heapSize, nullptr, nullptr, nullptr, &totalBytes); #endif if (showStats) { diff --git a/third_party/nix/src/libexpr/get-drvs.cc b/third_party/nix/src/libexpr/get-drvs.cc index 02ddae1f886c..fb5ada54c860 100644 --- a/third_party/nix/src/libexpr/get-drvs.cc +++ b/third_party/nix/src/libexpr/get-drvs.cc @@ -6,6 +6,7 @@ #include #include +#include #include "libexpr/eval-inline.hh" #include "libstore/derivations.hh" @@ -243,7 +244,7 @@ NixInt DrvInfo::queryMetaInt(const std::string& name, NixInt def) { if (v->type == tString) { /* Backwards compatibility with before we had support for integer meta fields. */ - NixInt n; + NixInt n = 0; if (absl::SimpleAtoi(v->string.s, &n)) { return n; } @@ -262,7 +263,7 @@ NixFloat DrvInfo::queryMetaFloat(const std::string& name, NixFloat def) { if (v->type == tString) { /* Backwards compatibility with before we had support for float meta fields. */ - NixFloat n; + NixFloat n = NAN; if (string2Float(v->string.s, n)) { return n; } @@ -367,7 +368,7 @@ static void getDerivations(EvalState& state, Value& vIn, const std::string& pathPrefix, Bindings& autoArgs, DrvInfos& drvs, Done& done, bool ignoreAssertionFailures) { - Value v; + Value v{}; state.autoCallFunction(autoArgs, vIn, v); /* Process the expression. */ diff --git a/third_party/nix/src/libexpr/names.cc b/third_party/nix/src/libexpr/names.cc index 1e9c2f2f4aac..84329d7c02c0 100644 --- a/third_party/nix/src/libexpr/names.cc +++ b/third_party/nix/src/libexpr/names.cc @@ -68,8 +68,8 @@ std::string nextComponent(std::string::const_iterator& p, } static bool componentsLT(const std::string& c1, const std::string& c2) { - int n1; - int n2; + int n1 = 0; + int n2 = 0; bool c1Num = absl::SimpleAtoi(c1, &n1); bool c2Num = absl::SimpleAtoi(c2, &n2); diff --git a/third_party/nix/src/libexpr/names.hh b/third_party/nix/src/libexpr/names.hh index 061388d517cd..e820995b84a6 100644 --- a/third_party/nix/src/libexpr/names.hh +++ b/third_party/nix/src/libexpr/names.hh @@ -11,7 +11,7 @@ struct DrvName { std::string fullName; std::string name; std::string version; - unsigned int hits; + unsigned int hits{}; DrvName(); DrvName(const std::string& s); diff --git a/third_party/nix/src/libexpr/nixexpr.cc b/third_party/nix/src/libexpr/nixexpr.cc index 94e7d335cff0..faf1020f8573 100644 --- a/third_party/nix/src/libexpr/nixexpr.cc +++ b/third_party/nix/src/libexpr/nixexpr.cc @@ -18,7 +18,7 @@ std::ostream& operator<<(std::ostream& str, const Expr& e) { static void showString(std::ostream& str, const std::string& s) { str << '"'; - for (auto c : (std::string)s) { + for (auto c : std::string(s)) { if (c == '"' || c == '\\' || c == '$') { str << "\\" << c; } else if (c == '\n') { @@ -191,7 +191,7 @@ std::ostream& operator<<(std::ostream& str, const Pos& pos) { str << "undefined position"; } else { str << (format(ANSI_BOLD "%1%" ANSI_NORMAL ":%2%:%3%") % - (std::string)pos.file.value() % pos.line % pos.column) + std::string(pos.file.value()) % pos.line % pos.column) .str(); } return str; @@ -232,8 +232,8 @@ void ExprPath::bindVars(const StaticEnv& env) {} void ExprVar::bindVars(const StaticEnv& env) { /* Check whether the variable appears in the environment. If so, set its level and displacement. */ - const StaticEnv* curEnv; - unsigned int level; + const StaticEnv* curEnv = nullptr; + unsigned int level = 0; int withLevel = -1; for (curEnv = &env, level = 0; curEnv != nullptr; curEnv = curEnv->up, level++) { @@ -363,8 +363,8 @@ void ExprWith::bindVars(const StaticEnv& env) { /* Does this `with' have an enclosing `with'? If so, record its level so that `lookupVar' can look up variables in the previous `with' if this one doesn't contain the desired attribute. */ - const StaticEnv* curEnv; - unsigned int level; + const StaticEnv* curEnv = nullptr; + unsigned int level = 0; prevWith = 0; for (curEnv = &env, level = 1; curEnv != nullptr; curEnv = curEnv->up, level++) { @@ -405,7 +405,7 @@ void ExprLambda::setName(Symbol& name) { this->name = name; } std::string ExprLambda::showNamePos() const { return (format("%1% at %2%") % - (name.has_value() ? "'" + (std::string)name.value() + "'" + (name.has_value() ? "'" + std::string(name.value()) + "'" : "anonymous function") % pos) .str(); diff --git a/third_party/nix/src/libexpr/parser.cc b/third_party/nix/src/libexpr/parser.cc index a96d345cc126..7b477f3eae0a 100644 --- a/third_party/nix/src/libexpr/parser.cc +++ b/third_party/nix/src/libexpr/parser.cc @@ -85,9 +85,10 @@ void addAttr(ExprAttrs* attrs, AttrPath& attrPath, Expr* e, const Pos& pos) { } void addFormal(const Pos& pos, Formals* formals, const Formal& formal) { - if (formals->argNames.find(formal.name) != formals->argNames.end()) + if (formals->argNames.find(formal.name) != formals->argNames.end()) { throw ParseError(format("duplicate formal function argument '%1%' at %2%") % formal.name % pos); + } formals->formals.push_front(formal); formals->argNames.insert(formal.name); } @@ -118,9 +119,9 @@ Expr* stripIndentation(const Pos& pos, SymbolTable& symbols, } for (size_t j = 0; j < e->s.size(); ++j) { if (atStartOfLine) { - if (e->s[j] == ' ') + if (e->s[j] == ' ') { curIndent++; - else if (e->s[j] == '\n') { + } else if (e->s[j] == '\n') { /* Empty line, doesn't influence minimum indentation. */ curIndent = 0; @@ -196,10 +197,11 @@ Path resolveExprPath(Path path) { /* If `path' is a symlink, follow it. This is so that relative path references work. */ - struct stat st; + struct stat st {}; while (true) { - if (lstat(path.c_str(), &st)) + if (lstat(path.c_str(), &st)) { throw SysError(format("getting status of '%1%'") % path); + } if (!S_ISLNK(st.st_mode)) { break; } @@ -260,13 +262,14 @@ Path EvalState::findFile(SearchPath& searchPath, const std::string& path, const Pos& pos) { for (auto& i : searchPath) { std::string suffix; - if (i.first.empty()) + if (i.first.empty()) { suffix = "/" + path; - else { + } else { auto s = i.first.size(); if (path.compare(0, s, i.first) != 0 || - (path.size() > s && path[s] != '/')) + (path.size() > s && path[s] != '/')) { continue; + } suffix = path.size() == s ? "" : "/" + std::string(path, s); } auto r = resolveSearchPathElem(i); diff --git a/third_party/nix/src/libexpr/primops.cc b/third_party/nix/src/libexpr/primops.cc index 06b9788bdf09..c754f0392b89 100644 --- a/third_party/nix/src/libexpr/primops.cc +++ b/third_party/nix/src/libexpr/primops.cc @@ -86,8 +86,8 @@ void EvalState::realiseContext(const PathSet& context) { PathSet willBuild; PathSet willSubstitute; PathSet unknown; - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; store->queryMissing(drvs, willBuild, willSubstitute, unknown, downloadSize, narSize); store->buildPaths(drvs); @@ -130,7 +130,7 @@ static void prim_scopedImport(EvalState& state, const Pos& pos, Value** args, mkString(*((*outputsVal->list)[outputs_index++]), o.first); } - Value fun; + Value fun{}; state.evalFile( settings.nixDataDir + "/nix/corepkgs/imported-drv-to-derivation.nix", fun); @@ -216,7 +216,7 @@ static void prim_isNull(EvalState& state, const Pos& pos, Value** args, static void prim_isFunction(EvalState& state, const Pos& pos, Value** args, Value& v) { state.forceValue(*args[0]); - bool res; + bool res = 0; switch (args[0]->type) { case tLambda: case tPrimOp: @@ -350,7 +350,7 @@ static void prim_genericClosure(EvalState& state, const Pos& pos, Value** args, res.push_back(e); /* Call the `operator' function with `e' as argument. */ - Value call; + Value call{}; mkApp(call, *op->second.value, *e); state.forceList(call, pos); @@ -877,7 +877,7 @@ static void prim_readFile(EvalState& state, const Pos& pos, Value** args, } std::string s = readFile(state.checkSourcePath(state.toRealPath(path, context))); - if (s.find((char)0) != std::string::npos) { + if (s.find('\0') != std::string::npos) { throw Error(format("the contents of the file '%1%' cannot be represented " "as a Nix string") % path); @@ -1050,13 +1050,13 @@ static void addPath(EvalState& state, const Pos& pos, const std::string& name, /* Call the filter function. The first argument is the path, the second is a string indicating the type of the file. */ - Value arg1; + Value arg1{}; mkString(arg1, path); - Value fun2; + Value fun2{}; state.callFunction(*filterFun, arg1, fun2, noPos); - Value arg2; + Value arg2{}; mkString(arg2, S_ISREG(st.st_mode) ? "regular" : S_ISDIR(st.st_mode) @@ -1065,7 +1065,7 @@ static void addPath(EvalState& state, const Pos& pos, const std::string& name, ? "symlink" : "unknown" /* not supported, will fail! */); - Value res; + Value res{}; state.callFunction(fun2, arg2, res, noPos); return state.forceBool(res, pos); @@ -1421,7 +1421,7 @@ static void prim_isList(EvalState& state, const Pos& pos, Value** args, static void elemAt(EvalState& state, const Pos& pos, Value& list, int n, Value& v) { state.forceList(list, pos); - if (n < 0 || (unsigned int)n >= list.listSize()) { + if (n < 0 || static_cast(n) >= list.listSize()) { throw Error(format("list index %1% is out of bounds, at %2%") % n % pos); } state.forceValue(*(*list.list)[n]); @@ -1480,7 +1480,7 @@ static void prim_filter(EvalState& state, const Pos& pos, Value** args, bool same = true; for (unsigned int n = 0; n < args[1]->listSize(); ++n) { - Value res; + Value res{}; state.callFunction(*args[0], *(*args[1]->list)[n], res, noPos); if (state.forceBool(res, pos)) { vs[k++] = (*args[1]->list)[n]; @@ -1538,7 +1538,7 @@ static void prim_foldlStrict(EvalState& state, const Pos& pos, Value** args, Value* vCur = args[1]; for (unsigned int n = 0; n < args[2]->listSize(); ++n) { - Value vTmp; + Value vTmp{}; state.callFunction(*args[0], *vCur, vTmp, pos); vCur = n == args[2]->listSize() - 1 ? &v : state.allocValue(); state.callFunction(vTmp, *(*args[2]->list)[n], *vCur, pos); @@ -1555,7 +1555,7 @@ static void anyOrAll(bool any, EvalState& state, const Pos& pos, Value** args, state.forceFunction(*args[0], pos); state.forceList(*args[1], pos); - Value vTmp; + Value vTmp{}; for (unsigned int n = 0; n < args[1]->listSize(); ++n) { state.callFunction(*args[0], *(*args[1]->list)[n], vTmp, pos); bool res = state.forceBool(vTmp, pos); @@ -1587,7 +1587,7 @@ static void prim_genList(EvalState& state, const Pos& pos, Value** args, state.mkList(v, len); - for (unsigned int n = 0; n < (unsigned int)len; ++n) { + for (unsigned int n = 0; n < static_cast(len); ++n) { Value* arg = state.allocValue(); mkInt(*arg, n); mkApp(*((*v.list)[n] = state.allocValue()), *args[0], *arg); @@ -1615,8 +1615,8 @@ static void prim_sort(EvalState& state, const Pos& pos, Value** args, return CompareValues()(a, b); } - Value vTmp1; - Value vTmp2; + Value vTmp1{}; + Value vTmp2{}; state.callFunction(*args[0], *a, vTmp1, pos); state.callFunction(vTmp1, *b, vTmp2, pos); return state.forceBool(vTmp2, pos); @@ -1639,7 +1639,7 @@ static void prim_partition(EvalState& state, const Pos& pos, Value** args, for (Value* elem : *args[1]->list) { state.forceValue(*elem, pos); - Value res; + Value res{}; state.callFunction(*args[0], *elem, res, pos); if (state.forceBool(res, pos)) { right->push_back(elem); @@ -1790,7 +1790,10 @@ static void prim_substring(EvalState& state, const Pos& pos, Value** args, pos); } - mkString(v, (unsigned int)start >= s.size() ? "" : std::string(s, start, len), + mkString(v, + static_cast(start) >= s.size() + ? "" + : std::string(s, start, len), context); } @@ -1875,7 +1878,7 @@ static void prim_split(EvalState& state, const Pos& pos, Value** args, const size_t len = std::distance(begin, end); state.mkList(v, 2 * len + 1); size_t idx = 0; - Value* elem; + Value* elem = nullptr; if (len == 0) { (*v.list)[idx++] = args[1]; @@ -2138,7 +2141,7 @@ void EvalState::createBaseEnv() { baseEnv.up = nullptr; /* Add global constants such as `true' to the base environment. */ - Value v; + Value v{}; /* `builtins' must be first! */ mkAttrs(v, 128); diff --git a/third_party/nix/src/libexpr/primops/context.cc b/third_party/nix/src/libexpr/primops/context.cc index 841a45c61c03..fb8879ead16d 100644 --- a/third_party/nix/src/libexpr/primops/context.cc +++ b/third_party/nix/src/libexpr/primops/context.cc @@ -97,12 +97,13 @@ static void prim_getContext(EvalState& state, const Pos& pos, Value** args, ContextInfo{isPath, isAllOutputs, output.empty() ? Strings{} : Strings{std::move(output)}}); } else { - if (isPath) + if (isPath) { iter->second.path = true; - else if (isAllOutputs) + } else if (isAllOutputs) { iter->second.allOutputs = true; - else + } else { iter->second.outputs.emplace_back(std::move(output)); + } } } @@ -116,8 +117,9 @@ static void prim_getContext(EvalState& state, const Pos& pos, Value** args, if (info.second.path) { mkBool(*state.allocAttr(infoVal, sPath), true); } - if (info.second.allOutputs) + if (info.second.allOutputs) { mkBool(*state.allocAttr(infoVal, sAllOutputs), true); + } if (!info.second.outputs.empty()) { auto& outputsVal = *state.allocAttr(infoVal, state.sOutputs); state.mkList(outputsVal, info.second.outputs.size()); @@ -147,9 +149,10 @@ static void prim_appendContext(EvalState& state, const Pos& pos, Value** args, auto sAllOutputs = state.symbols.Create("allOutputs"); for (const auto& attr_iter : *args[1]->attrs) { const Attr* i = &attr_iter.second; // TODO(tazjin): get rid of this - if (!state.store->isStorePath(i->name)) + if (!state.store->isStorePath(i->name)) { throw EvalError("Context key '%s' is not a store path, at %s", i->name, i->pos); + } if (!settings.readOnlyMode) { state.store->ensurePath(i->name); } diff --git a/third_party/nix/src/libexpr/primops/fetchGit.cc b/third_party/nix/src/libexpr/primops/fetchGit.cc index 7262a291559f..839094b72b53 100644 --- a/third_party/nix/src/libexpr/primops/fetchGit.cc +++ b/third_party/nix/src/libexpr/primops/fetchGit.cc @@ -30,8 +30,9 @@ std::regex revRegex("^[0-9a-fA-F]{40}$"); GitInfo exportGit(ref store, const std::string& uri, std::optional ref, std::string rev, const std::string& name) { - if (evalSettings.pureEval && rev == "") + if (evalSettings.pureEval && rev == "") { throw Error("in pure evaluation mode, 'fetchGit' requires a Git revision"); + } if (!ref && rev == "" && absl::StartsWith(uri, "/") && pathExists(uri + "/.git")) { @@ -90,8 +91,9 @@ GitInfo exportGit(ref store, const std::string& uri, ref = "HEAD"s; } - if (rev != "" && !std::regex_match(rev, revRegex)) + if (rev != "" && !std::regex_match(rev, revRegex)) { throw Error("invalid Git revision '%s'", rev); + } deletePath(getCacheDir() + "/nix/git"); @@ -104,12 +106,13 @@ GitInfo exportGit(ref store, const std::string& uri, } Path localRefFile; - if (ref->compare(0, 5, "refs/") == 0) + if (ref->compare(0, 5, "refs/") == 0) { localRefFile = cacheDir + "/" + *ref; - else + } else { localRefFile = cacheDir + "/refs/heads/" + *ref; + } - bool doFetch; + bool doFetch = 0; time_t now = time(0); /* If a rev was specified, we need to fetch if it's not in the repo. */ @@ -127,9 +130,10 @@ GitInfo exportGit(ref store, const std::string& uri, } else { /* If the local ref is older than ‘tarball-ttl’ seconds, do a git fetch to update the local ref to the remote ref. */ - struct stat st; + struct stat st {}; doFetch = stat(localRefFile.c_str(), &st) != 0 || - (uint64_t)st.st_mtime + settings.tarballTtl <= (uint64_t)now; + static_cast(st.st_mtime) + settings.tarballTtl <= + static_cast(now); } if (doFetch) { DLOG(INFO) << "fetching Git repository '" << uri << "'"; @@ -225,22 +229,24 @@ static void prim_fetchGit(EvalState& state, const Pos& pos, Value** args, for (auto& attr_iter : *args[0]->attrs) { auto& attr = attr_iter.second; std::string n(attr.name); - if (n == "url") + if (n == "url") { url = state.coerceToString(*attr.pos, *attr.value, context, false, false); - else if (n == "ref") + } else if (n == "ref") { ref = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (n == "rev") + } else if (n == "rev") { rev = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (n == "name") + } else if (n == "name") { name = state.forceStringNoCtx(*attr.value, *attr.pos); - else + } else { throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos); + } } - if (url.empty()) + if (url.empty()) { throw EvalError(format("'url' argument required, at %1%") % pos); + } } else { url = state.coerceToString(pos, *args[0], context, false, false); diff --git a/third_party/nix/src/libexpr/primops/fetchMercurial.cc b/third_party/nix/src/libexpr/primops/fetchMercurial.cc index 3ece094e6a8d..05a3d66ae7ca 100644 --- a/third_party/nix/src/libexpr/primops/fetchMercurial.cc +++ b/third_party/nix/src/libexpr/primops/fetchMercurial.cc @@ -28,10 +28,11 @@ std::regex commitHashRegex("^[0-9a-fA-F]{40}$"); HgInfo exportMercurial(ref store, const std::string& uri, std::string rev, const std::string& name) { - if (evalSettings.pureEval && rev == "") + if (evalSettings.pureEval && rev == "") { throw Error( "in pure evaluation mode, 'fetchMercurial' requires a Mercurial " "revision"); + } if (rev == "" && absl::StartsWith(uri, "/") && pathExists(uri + "/.hg")) { bool clean = runProgram("hg", true, @@ -90,9 +91,10 @@ HgInfo exportMercurial(ref store, const std::string& uri, /* If we haven't pulled this repo less than ‘tarball-ttl’ seconds, do so now. */ time_t now = time(0); - struct stat st; + struct stat st {}; if (stat(stampFile.c_str(), &st) != 0 || - (uint64_t)st.st_mtime + settings.tarballTtl <= (uint64_t)now) { + static_cast(st.st_mtime) + settings.tarballTtl <= + static_cast(now)) { /* Except that if this is a commit hash that we already have, we don't have to pull again. */ if (!(std::regex_match(rev, commitHashRegex) && pathExists(cacheDir) && @@ -198,20 +200,22 @@ static void prim_fetchMercurial(EvalState& state, const Pos& pos, Value** args, for (auto& attr_iter : *args[0]->attrs) { auto& attr = attr_iter.second; std::string n(attr.name); - if (n == "url") + if (n == "url") { url = state.coerceToString(*attr.pos, *attr.value, context, false, false); - else if (n == "rev") + } else if (n == "rev") { rev = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (n == "name") + } else if (n == "name") { name = state.forceStringNoCtx(*attr.value, *attr.pos); - else + } else { throw EvalError("unsupported argument '%s' to 'fetchMercurial', at %s", attr.name, *attr.pos); + } } - if (url.empty()) + if (url.empty()) { throw EvalError(format("'url' argument required, at %1%") % pos); + } } else { url = state.coerceToString(pos, *args[0], context, false, false); diff --git a/third_party/nix/src/libexpr/primops/fromTOML.cc b/third_party/nix/src/libexpr/primops/fromTOML.cc index 389ac080677a..e3d2a4940769 100644 --- a/third_party/nix/src/libexpr/primops/fromTOML.cc +++ b/third_party/nix/src/libexpr/primops/fromTOML.cc @@ -30,10 +30,12 @@ static void prim_fromTOML(EvalState& state, const Pos& pos, Value** args, if (auto i2 = i.second->as_table_array()) { size_t size2 = i2->get().size(); state.mkList(v2, size2); - for (size_t j = 0; j < size2; ++j) + for (size_t j = 0; j < size2; ++j) { visit(*((*v2.list)[j] = state.allocValue()), i2->get()[j]); - } else + } + } else { visit(v2, i.second); + } } } @@ -42,8 +44,9 @@ static void prim_fromTOML(EvalState& state, const Pos& pos, Value** args, state.mkList(v, size); - for (size_t i = 0; i < size; ++i) + for (size_t i = 0; i < size; ++i) { visit(*((*v.list)[i] = state.allocValue()), t2->get()[i]); + } } // Handle cases like 'a = [[{ a = true }]]', which IMHO should be @@ -55,25 +58,28 @@ static void prim_fromTOML(EvalState& state, const Pos& pos, Value** args, state.mkList(v, size); - for (size_t j = 0; j < size; ++j) + for (size_t j = 0; j < size; ++j) { visit(*((*v.list)[j] = state.allocValue()), t2->get()[j]); + } } else if (t->is_value()) { - if (auto val = t->as()) + if (auto val = t->as()) { mkInt(v, val->get()); - else if (auto val = t->as()) + } else if (auto val = t->as()) { mkFloat(v, val->get()); - else if (auto val = t->as()) + } else if (auto val = t->as()) { mkBool(v, val->get()); - else if (auto val = t->as()) + } else if (auto val = t->as()) { mkString(v, val->get()); - else + } else { throw EvalError("unsupported value type in TOML"); + } } - else + else { abort(); + } }; try { diff --git a/third_party/nix/src/libmain/shared.cc b/third_party/nix/src/libmain/shared.cc index b04bd279b95a..8b1b96140559 100644 --- a/third_party/nix/src/libmain/shared.cc +++ b/third_party/nix/src/libmain/shared.cc @@ -37,8 +37,8 @@ void printGCWarning() { } void printMissing(const ref& store, const PathSet& paths) { - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; PathSet willBuild; PathSet willSubstitute; PathSet unknown; @@ -128,7 +128,7 @@ void initNix() { startSignalHandlerThread(); /* Reset SIGCHLD to its default. */ - struct sigaction act; + struct sigaction act {}; sigemptyset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; @@ -151,7 +151,7 @@ void initNix() { umask(0022); /* Initialise the PRNG. */ - struct timeval tv; + struct timeval tv {}; gettimeofday(&tv, nullptr); srandom(tv.tv_usec); } @@ -327,7 +327,7 @@ RunPager::RunPager() { if (pager == nullptr) { pager = getenv("PAGER"); } - if (pager && ((std::string)pager == "" || (std::string)pager == "cat")) { + if (pager && (std::string(pager) == "" || std::string(pager) == "cat")) { return; } diff --git a/third_party/nix/src/libmain/stack.cc b/third_party/nix/src/libmain/stack.cc index c7744f69c82c..c60a53968f8f 100644 --- a/third_party/nix/src/libmain/stack.cc +++ b/third_party/nix/src/libmain/stack.cc @@ -9,14 +9,14 @@ namespace nix { -static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) { +static void sigsegvHandler(int _signo, siginfo_t* info, void* ctx) { /* Detect stack overflows by comparing the faulting address with the stack pointer. Unfortunately, getting the stack pointer is not portable. */ bool haveSP = true; char* sp = nullptr; #if defined(__x86_64__) && defined(REG_RSP) - sp = (char*)((ucontext_t*)ctx)->uc_mcontext.gregs[REG_RSP]; + sp = (char*)(static_cast(ctx))->uc_mcontext.gregs[REG_RSP]; #elif defined(REG_ESP) sp = (char*)((ucontext_t*)ctx)->uc_mcontext.gregs[REG_ESP]; #else @@ -24,7 +24,7 @@ static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) { #endif if (haveSP) { - ptrdiff_t diff = (char*)info->si_addr - sp; + ptrdiff_t diff = static_cast(info->si_addr) - sp; if (diff < 0) { diff = -diff; } @@ -36,7 +36,7 @@ static void sigsegvHandler(int signo, siginfo_t* info, void* ctx) { } /* Restore default behaviour (i.e. segfault and dump core). */ - struct sigaction act; + struct sigaction act {}; sigfillset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; @@ -62,7 +62,7 @@ void detectStackOverflow() { throw SysError("cannot set alternative stack"); } - struct sigaction act; + struct sigaction act {}; sigfillset(&act.sa_mask); act.sa_sigaction = sigsegvHandler; act.sa_flags = SA_SIGINFO | SA_ONSTACK; diff --git a/third_party/nix/src/libstore/binary-cache-store.cc b/third_party/nix/src/libstore/binary-cache-store.cc index b862ea005870..677500a0112b 100644 --- a/third_party/nix/src/libstore/binary-cache-store.cc +++ b/third_party/nix/src/libstore/binary-cache-store.cc @@ -87,7 +87,7 @@ void BinaryCacheStore::getFile(const std::string& path, Sink& sink) { } }}); auto data = promise.get_future().get(); - sink((unsigned char*)data->data(), data->size()); + sink(reinterpret_cast(data->data()), data->size()); } std::shared_ptr BinaryCacheStore::getFile( @@ -205,7 +205,9 @@ void BinaryCacheStore::addToStore(const ValidPathInfo& info, .count(); DLOG(INFO) << "copying path '" << narInfo->path << "' (" << narInfo->narSize << " bytes, compressed " - << ((1.0 - (double)narCompressed->size() / nar->size()) * 100.0) + << ((1.0 - + static_cast(narCompressed->size()) / nar->size()) * + 100.0) << "% in " << duration << "ms) to binary cache"; /* Atomically write the NAR file. */ @@ -287,9 +289,8 @@ void BinaryCacheStore::queryPathInfoUncached( stats.narInfoRead++; - (*callbackPtr)( - (std::shared_ptr)std::make_shared( - *this, *data, narInfoFile)); + (*callbackPtr)(std::shared_ptr( + std::make_shared(*this, *data, narInfoFile))); } catch (...) { callbackPtr->rethrow(); @@ -353,7 +354,9 @@ void BinaryCacheStore::addSignatures(const Path& storePath, when addSignatures() is called sequentially on a path, because S3 might return an outdated cached version. */ - auto narInfo = make_ref((NarInfo&)*queryPathInfo(storePath)); + // TODO(kanepyork): what is going on here + auto narInfo = make_ref(const_cast( + dynamic_cast(*queryPathInfo(storePath)))); narInfo->sigs.insert(sigs.begin(), sigs.end()); diff --git a/third_party/nix/src/libstore/build.cc b/third_party/nix/src/libstore/build.cc index 74db67e862a7..13a8b21dd180 100644 --- a/third_party/nix/src/libstore/build.cc +++ b/third_party/nix/src/libstore/build.cc @@ -185,10 +185,10 @@ using steady_time_point = std::chrono::time_point; path creation commands. */ struct Child { WeakGoalPtr goal; - Goal* goal2; // ugly hackery + Goal* goal2{}; // ugly hackery std::set fds; - bool respectTimeouts; - bool inBuildSlot; + bool respectTimeouts = false; + bool inBuildSlot = false; steady_time_point lastOutput; /* time we last got output on stdout/stderr */ steady_time_point timeStarted; }; @@ -732,7 +732,7 @@ class SubstitutionGoal; class DerivationGoal : public Goal { private: /* Whether to use an on-disk .drv file. */ - bool useDerivation; + bool useDerivation = false; /* The path of the derivation. */ Path drvPath; @@ -746,7 +746,7 @@ class DerivationGoal : public Goal { /* Whether to retry substituting the outputs after building the inputs. */ - bool retrySubstitution; + bool retrySubstitution = false; /* The derivation stored at drvPath. */ std::unique_ptr drv; @@ -789,7 +789,7 @@ class DerivationGoal : public Goal { std::shared_ptr logFileSink, logSink; /* Number of bytes received from the builder's stdout/stderr. */ - unsigned long logSize; + unsigned long logSize = 0; /* The most recent log lines. */ std::list logTail; @@ -817,7 +817,7 @@ class DerivationGoal : public Goal { std::shared_ptr autoDelChroot; /* Whether this is a fixed-output derivation. */ - bool fixedOutput; + bool fixedOutput = false; /* Whether to run the build in a private network namespace. */ bool privateNetwork = false; @@ -856,7 +856,7 @@ class DerivationGoal : public Goal { /* The current round, if we're building multiple times. */ size_t curRound = 1; - size_t nrRounds; + size_t nrRounds = 0; /* Path registration info from the previous round, if we're building multiple times. Since this contains the hash, it @@ -1585,13 +1585,15 @@ MakeError(NotDeterministic, BuildError) #if HAVE_STATVFS unsigned long long required = 8ULL * 1024 * 1024; // FIXME: make configurable - struct statvfs st; + struct statvfs st {}; if (statvfs(worker.store.realStoreDir.c_str(), &st) == 0 && - (unsigned long long)st.f_bavail * st.f_bsize < required) { + static_cast(st.f_bavail) * st.f_bsize < + required) { diskFull = true; } if (statvfs(tmpDir.c_str(), &st) == 0 && - (unsigned long long)st.f_bavail * st.f_bsize < required) { + static_cast(st.f_bavail) * st.f_bsize < + required) { diskFull = true; } #endif @@ -1830,7 +1832,7 @@ void chmod_(const Path& path, mode_t mode) { } int childEntry(void* arg) { - ((DerivationGoal*)arg)->runChild(); + (static_cast(arg))->runChild(); return 1; } @@ -2135,7 +2137,7 @@ void DerivationGoal::startBuilder() { for (auto& i : inputPaths) { Path r = worker.store.toRealPath(i); - struct stat st; + struct stat st {}; if (lstat(r.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % i); } @@ -2284,7 +2286,7 @@ void DerivationGoal::startBuilder() { } // Put the pt into raw mode to prevent \n -> \r\n translation. - struct termios term; + struct termios term {}; if (tcgetattr(builderOut.writeSide.get(), &term) != 0) { throw SysError("getting pseudoterminal attributes"); } @@ -2357,9 +2359,9 @@ void DerivationGoal::startBuilder() { } size_t stackSize = 1 * 1024 * 1024; - char* stack = - (char*)mmap(nullptr, stackSize, PROT_WRITE | PROT_READ, - MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); + char* stack = static_cast( + mmap(nullptr, stackSize, PROT_WRITE | PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0)); if (stack == MAP_FAILED) { throw SysError("allocating stack"); } @@ -2412,7 +2414,7 @@ void DerivationGoal::startBuilder() { userNamespaceSync.readSide = -1; - pid_t tmp; + pid_t tmp = 0; if (!absl::SimpleAtoi(readLine(builderOut.readSide.get()), &tmp)) { abort(); } @@ -2709,7 +2711,7 @@ void setupSeccomp() { return; } #if HAVE_SECCOMP - scmp_filter_ctx ctx; + scmp_filter_ctx ctx = nullptr; if ((ctx = seccomp_init(SCMP_ACT_ALLOW)) == nullptr) { throw SysError("unable to initialize seccomp mode 2"); @@ -2829,7 +2831,7 @@ void DerivationGoal::runChild() { throw SysError("cannot open IP socket"); } - struct ifreq ifr; + struct ifreq ifr {}; strncpy(ifr.ifr_name, "lo", sizeof("lo")); ifr.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING; if (ioctl(fd.get(), SIOCSIFFLAGS, &ifr) == -1) { @@ -2918,7 +2920,7 @@ void DerivationGoal::runChild() { auto doBind = [&](const Path& source, const Path& target, bool optional = false) { DLOG(INFO) << "bind mounting '" << source << "' to '" << target << "'"; - struct stat st; + struct stat st {}; if (stat(source.c_str(), &st) == -1) { if (optional && errno == ENOENT) { return; @@ -3035,7 +3037,7 @@ void DerivationGoal::runChild() { #if __linux__ /* Change the personality to 32-bit if we're doing an i686-linux build on an x86_64-linux machine. */ - struct utsname utsbuf; + struct utsname utsbuf {}; uname(&utsbuf); if (drv->platform == "i686-linux" && (settings.thisSystem == "x86_64-linux" || @@ -3247,7 +3249,7 @@ void DerivationGoal::registerOutputs() { } } - struct stat st; + struct stat st {}; if (lstat(actualPath.c_str(), &st) == -1) { if (errno == ENOENT) { throw BuildError( @@ -3296,7 +3298,7 @@ void DerivationGoal::registerOutputs() { outputs (i.e., the content hash should match the specified hash). */ if (fixedOutput) { - bool recursive; + bool recursive = 0; Hash h; i.second.parseHashInfo(recursive, h); @@ -4451,7 +4453,7 @@ void Worker::waitForInput() { terminated. */ bool useTimeout = false; - struct timeval timeout; + struct timeval timeout {}; timeout.tv_usec = 0; auto before = steady_time_point::clock::now(); @@ -4478,9 +4480,9 @@ void Worker::waitForInput() { } if (nearest != steady_time_point::max()) { timeout.tv_sec = std::max( - 1L, - (long)std::chrono::duration_cast(nearest - before) - .count()); + 1L, static_cast(std::chrono::duration_cast( + nearest - before) + .count())); useTimeout = true; } @@ -4495,10 +4497,11 @@ void Worker::waitForInput() { lastWokenUp = before; } timeout.tv_sec = std::max( - 1L, - (long)std::chrono::duration_cast( - lastWokenUp + std::chrono::seconds(settings.pollInterval) - before) - .count()); + 1L, static_cast(std::chrono::duration_cast( + lastWokenUp + + std::chrono::seconds(settings.pollInterval) - + before) + .count())); } else { lastWokenUp = steady_time_point::min(); } @@ -4563,7 +4566,7 @@ void Worker::waitForInput() { } } else { DLOG(INFO) << goal->getName() << ": read " << rd << " bytes"; - std::string data((char*)buffer.data(), rd); + std::string data(reinterpret_cast(buffer.data()), rd); j->lastOutput = after; goal->handleChildOutput(k, data); } @@ -4638,7 +4641,7 @@ bool Worker::pathContentsGood(const Path& path) { } LOG(INFO) << "checking path '" << path << "'..."; auto info = store.queryPathInfo(path); - bool res; + bool res = 0; if (!pathExists(path)) { res = false; } else { @@ -4663,8 +4666,8 @@ static void primeCache(Store& store, const PathSet& paths) { PathSet willBuild; PathSet willSubstitute; PathSet unknown; - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; store.queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); diff --git a/third_party/nix/src/libstore/builtins/buildenv.cc b/third_party/nix/src/libstore/builtins/buildenv.cc index 95f915227bb1..9413c4b03635 100644 --- a/third_party/nix/src/libstore/builtins/buildenv.cc +++ b/third_party/nix/src/libstore/builtins/buildenv.cc @@ -35,15 +35,17 @@ static void createLinks(const Path& srcDir, const Path& dstDir, int priority) { } for (const auto& ent : srcFiles) { - if (ent.name[0] == '.') /* not matched by glob */ + if (ent.name[0] == '.') { /* not matched by glob */ continue; + } auto srcFile = srcDir + "/" + ent.name; auto dstFile = dstDir + "/" + ent.name; - struct stat srcSt; + struct stat srcSt {}; try { - if (stat(srcFile.c_str(), &srcSt) == -1) + if (stat(srcFile.c_str(), &srcSt) == -1) { throw SysError("getting status of '%1%'", srcFile); + } } catch (SysError& e) { if (e.errNo == ENOENT || e.errNo == ENOTDIR) { LOG(ERROR) << "warning: skipping dangling symlink '" << dstFile << "'"; @@ -61,11 +63,12 @@ static void createLinks(const Path& srcDir, const Path& dstDir, int priority) { if (absl::EndsWith(srcFile, "/propagated-build-inputs") || absl::EndsWith(srcFile, "/nix-support") || absl::EndsWith(srcFile, "/perllocal.pod") || - absl::EndsWith(srcFile, "/info/dir") || absl::EndsWith(srcFile, "/log")) + absl::EndsWith(srcFile, "/info/dir") || + absl::EndsWith(srcFile, "/log")) { continue; - else if (S_ISDIR(srcSt.st_mode)) { - struct stat dstSt; + } else if (S_ISDIR(srcSt.st_mode)) { + struct stat dstSt {}; auto res = lstat(dstFile.c_str(), &dstSt); if (res == 0) { if (S_ISDIR(dstSt.st_mode)) { @@ -73,45 +76,53 @@ static void createLinks(const Path& srcDir, const Path& dstDir, int priority) { continue; } else if (S_ISLNK(dstSt.st_mode)) { auto target = canonPath(dstFile, true); - if (!S_ISDIR(lstat(target).st_mode)) + if (!S_ISDIR(lstat(target).st_mode)) { throw Error("collision between '%1%' and non-directory '%2%'", srcFile, target); - if (unlink(dstFile.c_str()) == -1) + } + if (unlink(dstFile.c_str()) == -1) { throw SysError(format("unlinking '%1%'") % dstFile); - if (mkdir(dstFile.c_str(), 0755) == -1) + } + if (mkdir(dstFile.c_str(), 0755) == -1) { throw SysError(format("creating directory '%1%'")); + } createLinks(target, dstFile, priorities[dstFile]); createLinks(srcFile, dstFile, priority); continue; } - } else if (errno != ENOENT) + } else if (errno != ENOENT) { throw SysError(format("getting status of '%1%'") % dstFile); + } } else { - struct stat dstSt; + struct stat dstSt {}; auto res = lstat(dstFile.c_str(), &dstSt); if (res == 0) { if (S_ISLNK(dstSt.st_mode)) { auto prevPriority = priorities[dstFile]; - if (prevPriority == priority) + if (prevPriority == priority) { throw Error( "packages '%1%' and '%2%' have the same priority %3%; " "use 'nix-env --set-flag priority NUMBER INSTALLED_PKGNAME' " "to change the priority of one of the conflicting packages" " (0 being the highest priority)", srcFile, readLink(dstFile), priority); + } if (prevPriority < priority) { continue; } - if (unlink(dstFile.c_str()) == -1) + if (unlink(dstFile.c_str()) == -1) { throw SysError(format("unlinking '%1%'") % dstFile); - } else if (S_ISDIR(dstSt.st_mode)) + } + } else if (S_ISDIR(dstSt.st_mode)) { throw Error( "collision between non-directory '%1%' and directory '%2%'", srcFile, dstFile); - } else if (errno != ENOENT) + } + } else if (errno != ENOENT) { throw SysError(format("getting status of '%1%'") % dstFile); + } } createSymlink(srcFile, dstFile); @@ -201,10 +212,11 @@ void builtinBuildenv(const BasicDerivation& drv) { return a.priority < b.priority || (a.priority == b.priority && a.path < b.path); }); - for (const auto& pkg : pkgs) + for (const auto& pkg : pkgs) { if (pkg.active) { addPkg(pkg.path, pkg.priority); } + } /* Symlink to the packages that have been "propagated" by packages * installed by the user (i.e., package X declares that it wants Y diff --git a/third_party/nix/src/libstore/builtins/fetchurl.cc b/third_party/nix/src/libstore/builtins/fetchurl.cc index 867a120e8d4a..f7857b543d55 100644 --- a/third_party/nix/src/libstore/builtins/fetchurl.cc +++ b/third_party/nix/src/libstore/builtins/fetchurl.cc @@ -20,8 +20,9 @@ void builtinFetchurl(const BasicDerivation& drv, const std::string& netrcData) { auto getAttr = [&](const std::string& name) { auto i = drv.env.find(name); - if (i == drv.env.end()) + if (i == drv.env.end()) { throw Error(format("attribute '%s' missing") % name); + } return i->second; }; @@ -47,21 +48,24 @@ void builtinFetchurl(const BasicDerivation& drv, const std::string& netrcData) { decompressor->finish(); }); - if (unpack) + if (unpack) { restorePath(storePath, *source); - else + } else { writeFile(storePath, *source); + } auto executable = drv.env.find("executable"); if (executable != drv.env.end() && executable->second == "1") { - if (chmod(storePath.c_str(), 0755) == -1) + if (chmod(storePath.c_str(), 0755) == -1) { throw SysError(format("making '%1%' executable") % storePath); + } } }; /* Try the hashed mirrors first. */ - if (getAttr("outputHashMode") == "flat") - for (auto hashedMirror : settings.hashedMirrors.get()) try { + if (getAttr("outputHashMode") == "flat") { + for (auto hashedMirror : settings.hashedMirrors.get()) { + try { if (!absl::EndsWith(hashedMirror, "/")) { hashedMirror += '/'; } @@ -73,6 +77,8 @@ void builtinFetchurl(const BasicDerivation& drv, const std::string& netrcData) { } catch (Error& e) { LOG(ERROR) << e.what(); } + } + } /* Otherwise try the specified URL. */ fetch(mainUrl); diff --git a/third_party/nix/src/libstore/crypto.cc b/third_party/nix/src/libstore/crypto.cc index bec0b08c67c1..2a03f825a712 100644 --- a/third_party/nix/src/libstore/crypto.cc +++ b/third_party/nix/src/libstore/crypto.cc @@ -54,10 +54,11 @@ SecretKey::SecretKey(const std::string& s) : Key(s) { std::string SecretKey::signDetached(const std::string& data) const { #if HAVE_SODIUM unsigned char sig[crypto_sign_BYTES]; - unsigned long long sigLen; + unsigned long long sigLen = 0; crypto_sign_detached(sig, &sigLen, (unsigned char*)data.data(), data.size(), (unsigned char*)key.data()); - return name + ":" + absl::Base64Escape(std::string((char*)sig, sigLen)); + return name + ":" + + absl::Base64Escape(std::string(reinterpret_cast(sig), sigLen)); #else noSodium(); #endif @@ -67,7 +68,8 @@ PublicKey SecretKey::toPublicKey() const { #if HAVE_SODIUM unsigned char pk[crypto_sign_PUBLICKEYBYTES]; crypto_sign_ed25519_sk_to_pk(pk, (unsigned char*)key.data()); - return PublicKey(name, std::string((char*)pk, crypto_sign_PUBLICKEYBYTES)); + return PublicKey(name, std::string(reinterpret_cast(pk), + crypto_sign_PUBLICKEYBYTES)); #else noSodium(); #endif @@ -101,8 +103,9 @@ bool verifyDetached(const std::string& data, const std::string& sig, } return crypto_sign_verify_detached( - (unsigned char*)sig2.data(), (unsigned char*)data.data(), - data.size(), (unsigned char*)key->second.key.data()) == 0; + reinterpret_cast(sig2.data()), + (unsigned char*)data.data(), data.size(), + (unsigned char*)key->second.key.data()) == 0; #else noSodium(); #endif diff --git a/third_party/nix/src/libstore/derivations.cc b/third_party/nix/src/libstore/derivations.cc index 18b313385ca5..208e7e981c4a 100644 --- a/third_party/nix/src/libstore/derivations.cc +++ b/third_party/nix/src/libstore/derivations.cc @@ -94,7 +94,7 @@ static void expect(std::istream& str, const std::string& s) { static std::string parseString(std::istream& str) { std::string res; expect(str, "\""); - int c; + int c = 0; while ((c = str.get()) != '"') { if (c == '\\') { c = str.get(); @@ -105,10 +105,10 @@ static std::string parseString(std::istream& str) { } else if (c == 't') { res += '\t'; } else { - res += c; + res += std::to_string(c); } } else { - res += c; + res += std::to_string(c); } } return res; diff --git a/third_party/nix/src/libstore/download.cc b/third_party/nix/src/libstore/download.cc index e73181e73109..dfa72e3eb09f 100644 --- a/third_party/nix/src/libstore/download.cc +++ b/third_party/nix/src/libstore/download.cc @@ -160,7 +160,7 @@ struct CurlDownloader : public Downloader { decompressionSink = makeDecompressionSink(encoding, finalSink); } - (*decompressionSink)((unsigned char*)contents, realSize); + (*decompressionSink)(static_cast(contents), realSize); return realSize; } catch (...) { @@ -171,12 +171,13 @@ struct CurlDownloader : public Downloader { static size_t writeCallbackWrapper(void* contents, size_t size, size_t nmemb, void* userp) { - return ((DownloadItem*)userp)->writeCallback(contents, size, nmemb); + return (static_cast(userp)) + ->writeCallback(contents, size, nmemb); } size_t headerCallback(void* contents, size_t size, size_t nmemb) { size_t realSize = size * nmemb; - std::string line((char*)contents, realSize); + std::string line(static_cast(contents), realSize); DLOG(INFO) << "got header for '" << request.uri << "': " << absl::StripAsciiWhitespace(line); if (line.compare(0, 5, "HTTP/") == 0) { // new response starts @@ -218,7 +219,8 @@ struct CurlDownloader : public Downloader { static size_t headerCallbackWrapper(void* contents, size_t size, size_t nmemb, void* userp) { - return ((DownloadItem*)userp)->headerCallback(contents, size, nmemb); + return (static_cast(userp)) + ->headerCallback(contents, size, nmemb); } static int debugCallback(CURL* handle, curl_infotype type, char* data, @@ -245,7 +247,8 @@ struct CurlDownloader : public Downloader { static size_t readCallbackWrapper(char* buffer, size_t size, size_t nitems, void* userp) { - return ((DownloadItem*)userp)->readCallback(buffer, size, nitems); + return (static_cast(userp)) + ->readCallback(buffer, size, nitems); } void init() { @@ -337,7 +340,7 @@ struct CurlDownloader : public Downloader { long httpStatus = 0; curl_easy_getinfo(req, CURLINFO_RESPONSE_CODE, &httpStatus); - char* effectiveUriCStr; + char* effectiveUriCStr = nullptr; curl_easy_getinfo(req, CURLINFO_EFFECTIVE_URL, &effectiveUriCStr); if (effectiveUriCStr != nullptr) { result.effectiveUri = effectiveUriCStr; @@ -546,7 +549,7 @@ struct CurlDownloader : public Downloader { checkInterrupt(); /* Let curl do its thing. */ - int running; + int running = 0; CURLMcode mc = curl_multi_perform(curlm, &running); if (mc != CURLM_OK) { throw nix::Error( @@ -555,8 +558,8 @@ struct CurlDownloader : public Downloader { } /* Set the promises of any finished requests. */ - CURLMsg* msg; - int left; + CURLMsg* msg = nullptr; + int left = 0; while ((msg = curl_multi_info_read(curlm, &left)) != nullptr) { if (msg->msg == CURLMSG_DONE) { auto i = items.find(msg->easy_handle); @@ -579,9 +582,10 @@ struct CurlDownloader : public Downloader { nextWakeup != std::chrono::steady_clock::time_point() ? std::max( 0, - (int)std::chrono::duration_cast( - nextWakeup - std::chrono::steady_clock::now()) - .count()) + static_cast( + std::chrono::duration_cast( + nextWakeup - std::chrono::steady_clock::now()) + .count())) : maxSleepTimeMs; DLOG(INFO) << "download thread waiting for " << sleepTimeMs << " ms"; mc = curl_multi_wait(curlm, extraFDs, 1, sleepTimeMs, &numfds); @@ -844,7 +848,7 @@ void Downloader::download(DownloadRequest&& request, Sink& sink) { if it's blocked on a full buffer. We don't hold the state lock while doing this to prevent blocking the download thread if sink() takes a long time. */ - sink((unsigned char*)chunk.data(), chunk.size()); + sink(reinterpret_cast(chunk.data()), chunk.size()); } } @@ -898,9 +902,10 @@ CachedDownloadResult Downloader::downloadCached( std::vector ss = absl::StrSplit(readFile(dataFile), absl::ByChar('\n')); if (ss.size() >= 3 && ss[0] == url) { - time_t lastChecked; + time_t lastChecked = 0; if (absl::SimpleAtoi(ss[2], &lastChecked) && - (uint64_t)lastChecked + request.ttl >= (uint64_t)time(nullptr)) { + static_cast(lastChecked) + request.ttl >= + static_cast(time(nullptr))) { skip = true; result.effectiveUri = request.uri; result.etag = ss[1]; diff --git a/third_party/nix/src/libstore/gc.cc b/third_party/nix/src/libstore/gc.cc index 9a6d97eb73c9..85f7f1dba95d 100644 --- a/third_party/nix/src/libstore/gc.cc +++ b/third_party/nix/src/libstore/gc.cc @@ -167,7 +167,7 @@ void LocalStore::addTempRoot(const Path& path) { /* Check whether the garbage collector didn't get in our way. */ - struct stat st; + struct stat st {}; if (fstat(state->fdTempRoots.get(), &st) == -1) { throw SysError(format("statting '%1%'") % fnTempRoots); } @@ -239,9 +239,10 @@ void LocalStore::findTempRoots(FDs& fds, Roots& tempRoots, bool censor) { /* Extract the roots. */ std::string::size_type pos = 0; - std::string::size_type end; + std::string::size_type end = 0; - while ((end = contents.find((char)0, pos)) != std::string::npos) { + while ((end = contents.find(static_cast(0), pos)) != + std::string::npos) { Path root(contents, pos, end - pos); DLOG(INFO) << "got temporary root " << root; assertStorePath(root); @@ -387,7 +388,7 @@ void LocalStore::findRuntimeRoots(Roots& roots, bool censor) { auto procDir = AutoCloseDir{opendir("/proc")}; if (procDir) { - struct dirent* ent; + struct dirent* ent = nullptr; auto digitsRegex = std::regex(R"(^\d+$)"); auto mapRegex = std::regex(R"(^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(/\S+)\s*$)"); @@ -407,7 +408,7 @@ void LocalStore::findRuntimeRoots(Roots& roots, bool censor) { } throw SysError(format("opening %1%") % fdStr); } - struct dirent* fd_ent; + struct dirent* fd_ent = nullptr; while (errno = 0, fd_ent = readdir(fdDir.get())) { if (fd_ent->d_name[0] != '.') { readProcLink(fmt("%s/%s", fdStr, fd_ent->d_name), unchecked); @@ -481,11 +482,11 @@ struct LocalStore::GCState { PathSet tempRoots; PathSet dead; PathSet alive; - bool gcKeepOutputs; - bool gcKeepDerivations; + bool gcKeepOutputs{}; + bool gcKeepDerivations{}; unsigned long long bytesInvalidated; bool moveToTrash = true; - bool shouldDelete; + bool shouldDelete{}; explicit GCState(GCResults& results_) : results(results_), bytesInvalidated(0) {} }; @@ -498,7 +499,7 @@ bool LocalStore::isActiveTempFile(const GCState& state, const Path& path, } void LocalStore::deleteGarbage(GCState& state, const Path& path) { - unsigned long long bytesFreed; + unsigned long long bytesFreed = 0; deletePath(path, bytesFreed); state.results.bytesFreed += bytesFreed; } @@ -522,7 +523,7 @@ void LocalStore::deletePathRecursive(GCState& state, const Path& path) { Path realPath = realStoreDir + "/" + baseNameOf(path); - struct stat st; + struct stat st {}; if (lstat(realPath.c_str(), &st) != 0) { if (errno == ENOENT) { return; @@ -697,7 +698,7 @@ void LocalStore::removeUnusedLinks(const GCState& state) { long long actualSize = 0; long long unsharedSize = 0; - struct dirent* dirent; + struct dirent* dirent = nullptr; while (errno = 0, dirent = readdir(dir.get())) { checkInterrupt(); std::string name = dirent->d_name; @@ -706,7 +707,7 @@ void LocalStore::removeUnusedLinks(const GCState& state) { } Path path = linksDir + "/" + name; - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) == -1) { throw SysError(format("statting '%1%'") % path); } @@ -726,7 +727,7 @@ void LocalStore::removeUnusedLinks(const GCState& state) { state.results.bytesFreed += st.st_size; } - struct stat st; + struct stat st {}; if (stat(linksDir.c_str(), &st) == -1) { throw SysError(format("statting '%1%'") % linksDir); } @@ -840,7 +841,7 @@ void LocalStore::collectGarbage(const GCOptions& options, GCResults& results) { again. We don't use readDirectory() here so that GCing can start faster. */ Paths entries; - struct dirent* dirent; + struct dirent* dirent = nullptr; while (errno = 0, dirent = readdir(dir.get())) { checkInterrupt(); std::string name = dirent->d_name; @@ -911,12 +912,12 @@ void LocalStore::autoGC(bool sync) { return std::stoll(readFile(fakeFreeSpaceFile)); } - struct statvfs st; + struct statvfs st {}; if (statvfs(realStoreDir.c_str(), &st) != 0) { throw SysError("getting filesystem info about '%s'", realStoreDir); } - return (uint64_t)st.f_bavail * st.f_bsize; + return static_cast(st.f_bavail) * st.f_bsize; }; std::shared_future future; diff --git a/third_party/nix/src/libstore/legacy-ssh-store.cc b/third_party/nix/src/libstore/legacy-ssh-store.cc index 332f6676b26e..abff734efc48 100644 --- a/third_party/nix/src/libstore/legacy-ssh-store.cc +++ b/third_party/nix/src/libstore/legacy-ssh-store.cc @@ -34,7 +34,7 @@ struct LegacySSHStore : public Store { std::unique_ptr sshConn; FdSink to; FdSource from; - int remoteVersion; + int remoteVersion{}; bool good = true; }; @@ -209,7 +209,7 @@ struct LegacySSHStore : public Store { conn->to.flush(); BuildResult status; - status.status = (BuildResult::Status)readInt(conn->from); + status.status = static_cast(readInt(conn->from)); conn->from >> status.errorMsg; if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3) { diff --git a/third_party/nix/src/libstore/local-fs-store.cc b/third_party/nix/src/libstore/local-fs-store.cc index 2dd09093d5f8..8e5d3e211963 100644 --- a/third_party/nix/src/libstore/local-fs-store.cc +++ b/third_party/nix/src/libstore/local-fs-store.cc @@ -26,7 +26,7 @@ struct LocalStoreAccessor : public FSAccessor { FSAccessor::Stat stat(const Path& path) override { auto realPath = toRealPath(path); - struct stat st; + struct stat st {}; if (lstat(realPath.c_str(), &st) != 0) { if (errno == ENOENT || errno == ENOTDIR) { return {Type::tMissing, 0, false}; @@ -41,7 +41,7 @@ struct LocalStoreAccessor : public FSAccessor { return {S_ISREG(st.st_mode) ? Type::tRegular : S_ISLNK(st.st_mode) ? Type::tSymlink : Type::tDirectory, - S_ISREG(st.st_mode) ? (uint64_t)st.st_size : 0, + S_ISREG(st.st_mode) ? static_cast(st.st_size) : 0, S_ISREG(st.st_mode) && ((st.st_mode & S_IXUSR) != 0u)}; } diff --git a/third_party/nix/src/libstore/local-store.cc b/third_party/nix/src/libstore/local-store.cc index 8c0a28a61647..c513e3ac4e9d 100644 --- a/third_party/nix/src/libstore/local-store.cc +++ b/third_party/nix/src/libstore/local-store.cc @@ -88,7 +88,7 @@ LocalStore::LocalStore(const Params& params) LOG(ERROR) << "warning: the group '" << settings.buildUsersGroup << "' specified in 'build-users-group' does not exist"; } else { - struct stat st; + struct stat st {}; if (stat(realStoreDir.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % realStoreDir); @@ -111,7 +111,7 @@ LocalStore::LocalStore(const Params& params) /* Ensure that the store and its parents are not symlinks. */ if (getEnv("NIX_IGNORE_SYMLINK_STORE") != "1") { Path path = realStoreDir; - struct stat st; + struct stat st {}; while (path != "/") { if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting status of '%1%'") % path); @@ -131,7 +131,7 @@ LocalStore::LocalStore(const Params& params) needed, we reserve some dummy space that we can free just before doing a garbage collection. */ try { - struct stat st; + struct stat st {}; if (stat(reservedPath.c_str(), &st) == -1 || st.st_size != settings.reservedSize) { AutoCloseFD fd = @@ -349,7 +349,8 @@ void LocalStore::openDB(State& state, bool create) { if (sqlite3_step(stmt) != SQLITE_ROW) { throwSQLiteError(db, "querying journal mode"); } - prevMode = std::string((const char*)sqlite3_column_text(stmt, 0)); + prevMode = std::string( + reinterpret_cast(sqlite3_column_text(stmt, 0))); } if (prevMode != mode && sqlite3_exec(db, ("pragma main.journal_mode = " + mode + ";").c_str(), @@ -378,7 +379,7 @@ void LocalStore::makeStoreWritable() { return; } /* Check if /nix/store is on a read-only mount. */ - struct statvfs stat; + struct statvfs stat {}; if (statvfs(realStoreDir.c_str(), &stat) != 0) { throw SysError("getting info about the Nix store mount point"); } @@ -432,7 +433,7 @@ static void canonicaliseTimestampAndPermissions(const Path& path, } // namespace nix void canonicaliseTimestampAndPermissions(const Path& path) { - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % path); } @@ -443,7 +444,7 @@ static void canonicalisePathMetaData_(const Path& path, uid_t fromUid, InodesSeen& inodesSeen) { checkInterrupt(); - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % path); } @@ -488,7 +489,7 @@ static void canonicalisePathMetaData_(const Path& path, uid_t fromUid, However, ignore files that we chown'ed ourselves previously to ensure that we don't fail on hard links within the same build (i.e. "touch $out/foo; ln $out/foo $out/bar"). */ - if (fromUid != (uid_t)-1 && st.st_uid != fromUid) { + if (fromUid != static_cast(-1) && st.st_uid != fromUid) { if (S_ISDIR(st.st_mode)) { throw BuildError(format("invalid file '%1%': is a directory") % path); } @@ -543,7 +544,7 @@ void canonicalisePathMetaData(const Path& path, uid_t fromUid, /* On platforms that don't have lchown(), the top-level path can't be a symlink, since we can't change its ownership. */ - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % path); } @@ -573,7 +574,7 @@ void LocalStore::checkDerivationOutputs(const Path& drvPath, drvPath); } - bool recursive; + bool recursive = 0; Hash h; out->second.parseHashInfo(recursive, h); Path outPath = makeFixedOutputPath(recursive, h, drvName); @@ -688,7 +689,8 @@ void LocalStore::queryPathInfoUncached( info->registrationTime = useQueryPathInfo.getInt(2); - auto s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 3); + auto s = reinterpret_cast( + sqlite3_column_text(state->stmtQueryPathInfo, 3)); if (s != nullptr) { info->deriver = s; } @@ -698,12 +700,14 @@ void LocalStore::queryPathInfoUncached( info->ultimate = useQueryPathInfo.getInt(5) == 1; - s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 6); + s = reinterpret_cast( + sqlite3_column_text(state->stmtQueryPathInfo, 6)); if (s != nullptr) { info->sigs = absl::StrSplit(s, absl::ByChar(' ')); } - s = (const char*)sqlite3_column_text(state->stmtQueryPathInfo, 7); + s = reinterpret_cast( + sqlite3_column_text(state->stmtQueryPathInfo, 7)); if (s != nullptr) { info->ca = s; } @@ -858,8 +862,8 @@ Path LocalStore::queryPathFromHashPart(const std::string& hashPart) { return ""; } - const char* s = - (const char*)sqlite3_column_text(state->stmtQueryPathFromHashPart, 0); + const char* s = reinterpret_cast( + sqlite3_column_text(state->stmtQueryPathFromHashPart, 0)); return (s != nullptr) && prefix.compare(0, prefix.size(), s, prefix.size()) == 0 ? s diff --git a/third_party/nix/src/libstore/nar-accessor.cc b/third_party/nix/src/libstore/nar-accessor.cc index 49fa1bd1d61c..cfd3d50b32bc 100644 --- a/third_party/nix/src/libstore/nar-accessor.cc +++ b/third_party/nix/src/libstore/nar-accessor.cc @@ -76,7 +76,7 @@ struct NarAccessor : public FSAccessor { void preallocateContents(unsigned long long size) override { currentStart = std::string(s, pos, 16); assert(size <= std::numeric_limits::max()); - parents.top()->size = (size_t)size; + parents.top()->size = static_cast(size); parents.top()->start = pos; } 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 be2ad8f2dac1..8f723a810906 100644 --- a/third_party/nix/src/libstore/nar-info-disk-cache.cc +++ b/third_party/nix/src/libstore/nar-info-disk-cache.cc @@ -55,10 +55,10 @@ class NarInfoDiskCacheImpl final : public NarInfoDiskCache { const int purgeInterval = 24 * 3600; struct Cache { - int id; + int id{}; Path storeDir; - bool wantMassQuery; - int priority; + bool wantMassQuery{}; + int priority{}; }; struct State { @@ -164,8 +164,9 @@ class NarInfoDiskCacheImpl final : public NarInfoDiskCache { static_cast(wantMassQuery))(priority) .exec(); assert(sqlite3_changes(state->db) == 1); - state->caches[uri] = Cache{(int)sqlite3_last_insert_rowid(state->db), - storeDir, wantMassQuery, priority}; + state->caches[uri] = + Cache{static_cast(sqlite3_last_insert_rowid(state->db)), + storeDir, wantMassQuery, priority}; }); } @@ -181,8 +182,9 @@ class NarInfoDiskCacheImpl final : public NarInfoDiskCache { return false; } state->caches.emplace( - uri, Cache{(int)queryCache.getInt(0), queryCache.getStr(1), - queryCache.getInt(2) != 0, (int)queryCache.getInt(3)}); + uri, Cache{static_cast(queryCache.getInt(0)), + queryCache.getStr(1), queryCache.getInt(2) != 0, + static_cast(queryCache.getInt(3))}); } auto& cache(getCache(*state, uri)); diff --git a/third_party/nix/src/libstore/optimise-store.cc b/third_party/nix/src/libstore/optimise-store.cc index eb24633c181c..af67d5e19ac2 100644 --- a/third_party/nix/src/libstore/optimise-store.cc +++ b/third_party/nix/src/libstore/optimise-store.cc @@ -17,7 +17,7 @@ namespace nix { static void makeWritable(const Path& path) { - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % path); } @@ -50,7 +50,7 @@ LocalStore::InodeHash LocalStore::loadInodeHash() { throw SysError(format("opening directory '%1%'") % linksDir); } - struct dirent* dirent; + struct dirent* dirent = nullptr; while (errno = 0, dirent = readdir(dir.get())) { /* sic */ checkInterrupt(); // We don't care if we hit non-hash files, anything goes @@ -74,7 +74,7 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path& path, throw SysError(format("opening directory '%1%'") % path); } - struct dirent* dirent; + struct dirent* dirent = nullptr; while (errno = 0, dirent = readdir(dir.get())) { /* sic */ checkInterrupt(); @@ -100,7 +100,7 @@ void LocalStore::optimisePath_(OptimiseStats& stats, const Path& path, InodeHash& inodeHash) { checkInterrupt(); - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % path); } @@ -183,7 +183,7 @@ retry: /* Yes! We've seen a file with the same contents. Replace the current file with a hard link to that file. */ - struct stat stLink; + struct stat stLink {}; if (lstat(linkPath.c_str(), &stLink) != 0) { throw SysError(format("getting attributes of path '%1%'") % linkPath); } diff --git a/third_party/nix/src/libstore/pathlocks.cc b/third_party/nix/src/libstore/pathlocks.cc index 4b153856d283..7c528e876eed 100644 --- a/third_party/nix/src/libstore/pathlocks.cc +++ b/third_party/nix/src/libstore/pathlocks.cc @@ -37,7 +37,7 @@ void deleteLockFile(const Path& path, int fd) { } bool lockFile(int fd, LockType lockType, bool wait) { - int type; + int type = 0; if (lockType == ltRead) { type = LOCK_SH; } else if (lockType == ltWrite) { @@ -119,7 +119,7 @@ bool PathLocks::lockPaths(const PathSet& paths, const std::string& waitMsg, /* Check that the lock file hasn't become stale (i.e., hasn't been unlinked). */ - struct stat st; + struct stat st {}; if (fstat(fd.get(), &st) == -1) { throw SysError(format("statting lock file '%1%'") % lockPath); } diff --git a/third_party/nix/src/libstore/profiles.cc b/third_party/nix/src/libstore/profiles.cc index 0d44c60cc4e9..c2a965e2edae 100644 --- a/third_party/nix/src/libstore/profiles.cc +++ b/third_party/nix/src/libstore/profiles.cc @@ -30,7 +30,7 @@ static int parseName(absl::string_view profileName, absl::string_view name) { return -1; } - int n; + int n = 0; if (!absl::SimpleAtoi(name, &n) || n < 0) { return -1; } @@ -45,12 +45,12 @@ Generations findGenerations(const Path& profile, int& curGen) { std::string profileName = baseNameOf(profile); for (auto& i : readDirectory(profileDir)) { - int n; + int n = 0; if ((n = parseName(profileName, i.name)) != -1) { Generation gen; gen.path = profileDir + "/" + i.name; gen.number = n; - struct stat st; + struct stat st {}; if (lstat(gen.path.c_str(), &st) != 0) { throw SysError(format("statting '%1%'") % gen.path); } @@ -75,10 +75,10 @@ Path createGeneration(const ref& store, const Path& profile, const Path& outPath) { /* The new generation number should be higher than old the previous ones. */ - int dummy; + int dummy = 0; Generations gens = findGenerations(profile, dummy); - unsigned int num; + unsigned int num = 0; if (!gens.empty()) { Generation last = gens.back(); @@ -138,7 +138,7 @@ void deleteGenerations(const Path& profile, PathLocks lock; lockProfile(lock, profile); - int curGen; + int curGen = 0; Generations gens = findGenerations(profile, curGen); if (gensToDelete.find(curGen) != gensToDelete.end()) { @@ -158,7 +158,7 @@ void deleteGenerationsGreaterThan(const Path& profile, int max, bool dryRun) { PathLocks lock; lockProfile(lock, profile); - int curGen; + int curGen = 0; bool fromCurGen = false; Generations gens = findGenerations(profile, curGen); for (auto i = gens.rbegin(); i != gens.rend(); ++i) { @@ -181,7 +181,7 @@ void deleteOldGenerations(const Path& profile, bool dryRun) { PathLocks lock; lockProfile(lock, profile); - int curGen; + int curGen = 0; Generations gens = findGenerations(profile, curGen); for (auto& i : gens) { @@ -195,7 +195,7 @@ void deleteGenerationsOlderThan(const Path& profile, time_t t, bool dryRun) { PathLocks lock; lockProfile(lock, profile); - int curGen; + int curGen = 0; Generations gens = findGenerations(profile, curGen); bool canDelete = false; @@ -219,7 +219,7 @@ void deleteGenerationsOlderThan(const Path& profile, const std::string& timeSpec, bool dryRun) { time_t curTime = time(nullptr); std::string strDays = std::string(timeSpec, 0, timeSpec.size() - 1); - int days; + int days = 0; if (!absl::SimpleAtoi(strDays, &days) || days < 1) { throw Error(format("invalid number of days specifier '%1%'") % timeSpec); diff --git a/third_party/nix/src/libstore/references.cc b/third_party/nix/src/libstore/references.cc index ea9ce44275a0..b70d282e8df8 100644 --- a/third_party/nix/src/libstore/references.cc +++ b/third_party/nix/src/libstore/references.cc @@ -22,16 +22,16 @@ static void search(const unsigned char* s, size_t len, StringSet& hashes, i = false; } for (char base32Char : base32Chars) { - isBase32[(unsigned char)base32Char] = true; + isBase32[static_cast(base32Char)] = true; } initialised = true; } for (size_t i = 0; i + refLength <= len;) { - int j; + int j = 0; bool match = true; for (j = refLength - 1; j >= 0; --j) { - if (!isBase32[(unsigned char)s[i + j]]) { + if (!isBase32[s[i + j]]) { i += j + 1; match = false; break; @@ -40,7 +40,7 @@ static void search(const unsigned char* s, size_t len, StringSet& hashes, if (!match) { continue; } - std::string ref((const char*)s + i, refLength); + std::string ref(reinterpret_cast(s) + i, refLength); if (hashes.find(ref) != hashes.end()) { DLOG(INFO) << "found reference to '" << ref << "' at offset " << i; seen.insert(ref); @@ -68,17 +68,19 @@ void RefScanSink::operator()(const unsigned char* data, size_t len) { /* It's possible that a reference spans the previous and current fragment, so search in the concatenation of the tail of the previous fragment and the start of the current fragment. */ - std::string s = - tail + std::string((const char*)data, len > refLength ? refLength : len); - search((const unsigned char*)s.data(), s.size(), hashes, seen); + std::string s = tail + std::string(reinterpret_cast(data), + len > refLength ? refLength : len); + search(reinterpret_cast(s.data()), s.size(), hashes, + seen); search(data, len, hashes, seen); size_t tailLen = len <= refLength ? len : refLength; - tail = std::string(tail, tail.size() < refLength - tailLen - ? 0 - : tail.size() - (refLength - tailLen)) + - std::string((const char*)data + len - tailLen, tailLen); + tail = + std::string(tail, tail.size() < refLength - tailLen + ? 0 + : tail.size() - (refLength - tailLen)) + + std::string(reinterpret_cast(data) + len - tailLen, tailLen); } PathSet scanForReferences(const std::string& path, const PathSet& refs, diff --git a/third_party/nix/src/libstore/remote-fs-accessor.cc b/third_party/nix/src/libstore/remote-fs-accessor.cc index 2917f01f7939..d5b20288479c 100644 --- a/third_party/nix/src/libstore/remote-fs-accessor.cc +++ b/third_party/nix/src/libstore/remote-fs-accessor.cc @@ -75,12 +75,14 @@ std::pair, Path> RemoteFSAccessor::fetch(const Path& path_) { throw SysError("opening NAR cache file '%s'", cacheFile); } - if (lseek(fd.get(), offset, SEEK_SET) != (off_t)offset) { + if (lseek(fd.get(), offset, SEEK_SET) != + static_cast(offset)) { throw SysError("seeking in '%s'", cacheFile); } std::string buf(length, 0); - readFull(fd.get(), (unsigned char*)buf.data(), length); + readFull(fd.get(), reinterpret_cast(buf.data()), + length); return buf; }); diff --git a/third_party/nix/src/libstore/remote-store.cc b/third_party/nix/src/libstore/remote-store.cc index 33a6ec310ac1..b2e660dc2af9 100644 --- a/third_party/nix/src/libstore/remote-store.cc +++ b/third_party/nix/src/libstore/remote-store.cc @@ -97,7 +97,7 @@ ref UDSRemoteStore::openConnection() { std::string socketPath = path ? *path : settings.nixDaemonSocketFile; - struct sockaddr_un addr; + struct sockaddr_un addr {}; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socketPath.c_str(), sizeof(addr.sun_path)); if (addr.sun_path[sizeof(addr.sun_path) - 1] != '\0') { @@ -347,7 +347,7 @@ void RemoteStore::queryPathInfoUncached( throw; } if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 17) { - bool valid; + bool valid = 0; conn->from >> valid; if (!valid) { throw InvalidPath(format("path '%s' is not valid") % path); @@ -543,9 +543,9 @@ BuildResult RemoteStore::buildDerivation(const Path& drvPath, conn->to << wopBuildDerivation << drvPath << drv << buildMode; conn.processStderr(); BuildResult res; - unsigned int status; + unsigned int status = 0; conn->from >> status >> res.errorMsg; - res.status = (BuildResult::Status)status; + res.status = static_cast(status); return res; } diff --git a/third_party/nix/src/libstore/sqlite.cc b/third_party/nix/src/libstore/sqlite.cc index b6ecfce924a1..0ed77a51bf46 100644 --- a/third_party/nix/src/libstore/sqlite.cc +++ b/third_party/nix/src/libstore/sqlite.cc @@ -133,7 +133,7 @@ bool SQLiteStmt::Use::next() { } std::string SQLiteStmt::Use::getStr(int col) { - auto s = (const char*)sqlite3_column_text(stmt, col); + auto s = reinterpret_cast(sqlite3_column_text(stmt, col)); assert(s); return s; } @@ -186,7 +186,7 @@ void handleSQLiteBusy(const SQLiteBusy& e) { /* Sleep for a while since retrying the transaction right away is likely to fail again. */ checkInterrupt(); - struct timespec t; + struct timespec t {}; t.tv_sec = 0; t.tv_nsec = (random() % 100) * 1000 * 1000; /* <= 0.1s */ nanosleep(&t, nullptr); diff --git a/third_party/nix/src/libstore/ssh.cc b/third_party/nix/src/libstore/ssh.cc index e84944c4c9cd..d28e44e138c3 100644 --- a/third_party/nix/src/libstore/ssh.cc +++ b/third_party/nix/src/libstore/ssh.cc @@ -110,7 +110,7 @@ Path SSHMaster::startMaster() { state->tmpDir = std::make_unique(createTempDir("", "nix", true, true, 0700)); - state->socketPath = (Path)*state->tmpDir + "/ssh.sock"; + state->socketPath = Path(*state->tmpDir) + "/ssh.sock"; Pipe out; out.create(); diff --git a/third_party/nix/src/libstore/store-api.cc b/third_party/nix/src/libstore/store-api.cc index 12c60dffca35..f6fef4b912f2 100644 --- a/third_party/nix/src/libstore/store-api.cc +++ b/third_party/nix/src/libstore/store-api.cc @@ -262,7 +262,7 @@ Path Store::makeFixedOutputPath(bool recursive, const Hash& hash, "output:out", hashString( htSHA256, - "fixed:out:" + (recursive ? (std::string) "r:" : "") + + "fixed:out:" + (recursive ? std::string("r:") : "") + hash.to_string(Base16) + ":"), name); } @@ -782,7 +782,7 @@ ValidPathInfo decodeValidPathInfo(std::istream& str, bool hashGiven) { } getline(str, info.deriver); std::string s; - int n; + int n = 0; getline(str, s); if (!absl::SimpleAtoi(s, &n)) { throw Error("number expected"); @@ -880,7 +880,7 @@ Strings ValidPathInfo::shortRefs() const { } std::string makeFixedOutputCA(bool recursive, const Hash& hash) { - return "fixed:" + (recursive ? (std::string) "r:" : "") + hash.to_string(); + return "fixed:" + (recursive ? std::string("r:") : "") + hash.to_string(); } void Store::addToStore(const ValidPathInfo& info, Source& narSource, @@ -926,7 +926,8 @@ std::pair splitUriAndParams( throw Error("invalid URI parameter '%s'", value); } try { - decoded += std::stoul(std::string(value, i + 1, 2), nullptr, 16); + decoded += std::to_string( + 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 40898093212a..c26bf8257e63 100644 --- a/third_party/nix/src/libutil/archive.cc +++ b/third_party/nix/src/libutil/archive.cc @@ -66,7 +66,7 @@ static void dumpContents(const Path& path, size_t size, Sink& sink) { static void dump(const Path& path, Sink& sink, PathFilter& filter) { checkInterrupt(); - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting attributes of path '%1%'") % path); } @@ -80,7 +80,7 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) { sink << "executable" << ""; } - dumpContents(path, (size_t)st.st_size, sink); + dumpContents(path, static_cast(st.st_size), sink); } else if (S_ISDIR(st.st_mode)) { @@ -159,7 +159,7 @@ static void skipGeneric(Source & source) } #endif -static void parseContents(ParseSink& sink, Source& source, const Path& path) { +static void parseContents(ParseSink& sink, Source& source) { unsigned long long size = readLongLong(source); sink.preallocateContents(size); @@ -170,7 +170,7 @@ static void parseContents(ParseSink& sink, Source& source, const Path& path) { while (left != 0u) { checkInterrupt(); auto n = buf.size(); - if ((unsigned long long)n > left) { + if (static_cast(n) > left) { n = left; } source(buf.data(), n); @@ -235,7 +235,7 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { } else if (s == "contents" && type == tpRegular) { - parseContents(sink, source, path); + parseContents(sink, source); } else if (s == "executable" && type == tpRegular) { @@ -267,7 +267,7 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { name = readString(source); if (name.empty() || name == "." || name == ".." || name.find('/') != std::string::npos || - name.find((char)0) != std::string::npos) { + name.find('\0') != std::string::npos) { throw Error(format("NAR contains invalid file name '%1%'") % name); } if (name <= prevName) { @@ -341,7 +341,7 @@ struct RestoreSink : ParseSink { } void isExecutable() override { - struct stat st; + struct stat st {}; if (fstat(fd.get(), &st) == -1) { throw SysError("fstat"); } diff --git a/third_party/nix/src/libutil/args.cc b/third_party/nix/src/libutil/args.cc index c56383ef88cc..2be8a1b0ce2a 100644 --- a/third_party/nix/src/libutil/args.cc +++ b/third_party/nix/src/libutil/args.cc @@ -27,12 +27,12 @@ void Args::parseCmdline(const Strings& _cmdline) { `-j3` -> `-j 3`). */ if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && (isalpha(arg[1]) != 0)) { - *pos = (std::string) "-" + arg[1]; + *pos = std::string("-") + arg[1]; auto next = pos; ++next; for (unsigned int j = 2; j < arg.length(); j++) { if (isalpha(arg[j]) != 0) { - cmdline.insert(next, (std::string) "-" + arg[j]); + cmdline.insert(next, std::string("-") + arg[j]); } else { cmdline.insert(next, std::string(arg, j)); break; diff --git a/third_party/nix/src/libutil/compression.cc b/third_party/nix/src/libutil/compression.cc index 779d326eb204..b598927c88f7 100644 --- a/third_party/nix/src/libutil/compression.cc +++ b/third_party/nix/src/libutil/compression.cc @@ -17,7 +17,7 @@ namespace nix { // Don't feed brotli too much at once. struct ChunkedCompressionSink : CompressionSink { - uint8_t outbuf[32 * 1024]; + uint8_t outbuf[32 * 1024]{}; void write(const unsigned char* data, size_t len) override { const size_t CHUNK_SIZE = sizeof(outbuf) << 2; @@ -43,7 +43,7 @@ struct NoneSink : CompressionSink { struct XzDecompressionSink : CompressionSink { Sink& nextSink; - uint8_t outbuf[BUFSIZ]; + uint8_t outbuf[BUFSIZ]{}; lzma_stream strm = LZMA_STREAM_INIT; bool finished = false; @@ -89,7 +89,7 @@ struct XzDecompressionSink : CompressionSink { struct BzipDecompressionSink : ChunkedCompressionSink { Sink& nextSink; - bz_stream strm; + bz_stream strm{}; bool finished = false; explicit BzipDecompressionSink(Sink& nextSink) : nextSink(nextSink) { @@ -99,7 +99,7 @@ struct BzipDecompressionSink : ChunkedCompressionSink { throw CompressionError("unable to initialise bzip2 decoder"); } - strm.next_out = (char*)outbuf; + strm.next_out = reinterpret_cast(outbuf); strm.avail_out = sizeof(outbuf); } @@ -128,7 +128,7 @@ struct BzipDecompressionSink : ChunkedCompressionSink { if (strm.avail_out < sizeof(outbuf) || strm.avail_in == 0) { nextSink(outbuf, sizeof(outbuf) - strm.avail_out); - strm.next_out = (char*)outbuf; + strm.next_out = reinterpret_cast(outbuf); strm.avail_out = sizeof(outbuf); } } @@ -205,12 +205,12 @@ ref makeDecompressionSink(const std::string& method, struct XzCompressionSink : CompressionSink { Sink& nextSink; - uint8_t outbuf[BUFSIZ]; + uint8_t outbuf[BUFSIZ]{}; lzma_stream strm = LZMA_STREAM_INIT; bool finished = false; XzCompressionSink(Sink& nextSink, bool parallel) : nextSink(nextSink) { - lzma_ret ret; + lzma_ret ret{}; bool done = false; if (parallel) { @@ -277,7 +277,7 @@ struct XzCompressionSink : CompressionSink { struct BzipCompressionSink : ChunkedCompressionSink { Sink& nextSink; - bz_stream strm; + bz_stream strm{}; bool finished = false; explicit BzipCompressionSink(Sink& nextSink) : nextSink(nextSink) { @@ -287,7 +287,7 @@ struct BzipCompressionSink : ChunkedCompressionSink { throw CompressionError("unable to initialise bzip2 encoder"); } - strm.next_out = (char*)outbuf; + strm.next_out = reinterpret_cast(outbuf); strm.avail_out = sizeof(outbuf); } @@ -316,7 +316,7 @@ struct BzipCompressionSink : ChunkedCompressionSink { if (strm.avail_out < sizeof(outbuf) || strm.avail_in == 0) { nextSink(outbuf, sizeof(outbuf) - strm.avail_out); - strm.next_out = (char*)outbuf; + strm.next_out = reinterpret_cast(outbuf); strm.avail_out = sizeof(outbuf); } } @@ -325,7 +325,7 @@ struct BzipCompressionSink : ChunkedCompressionSink { struct BrotliCompressionSink : ChunkedCompressionSink { Sink& nextSink; - uint8_t outbuf[BUFSIZ]; + uint8_t outbuf[BUFSIZ]{}; BrotliEncoderState* state; bool finished = false; diff --git a/third_party/nix/src/libutil/hash.cc b/third_party/nix/src/libutil/hash.cc index 0d80972cceda..9165182ed70f 100644 --- a/third_party/nix/src/libutil/hash.cc +++ b/third_party/nix/src/libutil/hash.cc @@ -86,7 +86,7 @@ static std::string printHash32(const Hash& hash) { std::string s; s.reserve(len); - for (int n = (int)len - 1; n >= 0; n--) { + for (int n = static_cast(len) - 1; n >= 0; n--) { unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; @@ -119,7 +119,8 @@ std::string Hash::to_string(Base base, bool includeType) const { case Base64: case SRI: std::string b64; - absl::Base64Escape(std::string((const char*)hash, hashSize), &b64); + absl::Base64Escape( + std::string(reinterpret_cast(hash), hashSize), &b64); s += b64; break; } @@ -179,7 +180,7 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { else if (!isSRI && size == base32Len()) { for (unsigned int n = 0; n < size; ++n) { char c = s[pos + size - n - 1]; - unsigned char digit; + unsigned char digit = 0; for (digit = 0; digit < base32Chars.size(); ++digit) { /* !!! slow */ if (base32Chars[digit] == c) { break; @@ -267,16 +268,16 @@ static void finish(HashType ht, Ctx& ctx, unsigned char* hash) { } Hash hashString(HashType ht, const std::string& s) { - Ctx ctx; + Ctx ctx{}; Hash hash(ht); start(ht, ctx); - update(ht, ctx, (const unsigned char*)s.data(), s.length()); + update(ht, ctx, reinterpret_cast(s.data()), s.length()); finish(ht, ctx, hash.hash); return hash; } Hash hashFile(HashType ht, const Path& path) { - Ctx ctx; + Ctx ctx{}; Hash hash(ht); start(ht, ctx); @@ -286,7 +287,7 @@ Hash hashFile(HashType ht, const Path& path) { } std::vector buf(8192); - ssize_t n; + ssize_t n = 0; while ((n = read(fd.get(), buf.data(), buf.size())) != 0) { checkInterrupt(); if (n == -1) { diff --git a/third_party/nix/src/libutil/json.cc b/third_party/nix/src/libutil/json.cc index da636e7be9c3..59ff74f5796f 100644 --- a/third_party/nix/src/libutil/json.cc +++ b/third_party/nix/src/libutil/json.cc @@ -18,7 +18,7 @@ void toJSON(std::ostream& str, const char* start, const char* end) { str << "\\t"; } else if (*i >= 0 && *i < 32) { str << "\\u" << std::setfill('0') << std::setw(4) << std::hex - << (uint16_t)*i << std::dec; + << static_cast(*i) << std::dec; } else { str << *i; } diff --git a/third_party/nix/src/libutil/serialise.cc b/third_party/nix/src/libutil/serialise.cc index d02a0205af0d..26ab9be959dc 100644 --- a/third_party/nix/src/libutil/serialise.cc +++ b/third_party/nix/src/libutil/serialise.cc @@ -93,10 +93,10 @@ std::string Source::drain() { std::string s; std::vector buf(8192); while (true) { - size_t n; + size_t n = 0; try { n = read(buf.data(), buf.size()); - s.append((char*)buf.data(), n); + s.append(reinterpret_cast(buf.data()), n); } catch (EndOfFile&) { break; } @@ -126,10 +126,10 @@ size_t BufferedSource::read(unsigned char* data, size_t len) { bool BufferedSource::hasData() { return bufPosOut < bufPosIn; } size_t FdSource::readUnbuffered(unsigned char* data, size_t len) { - ssize_t n; + ssize_t n = 0; do { checkInterrupt(); - n = ::read(fd, (char*)data, len); + n = ::read(fd, reinterpret_cast(data), len); } while (n == -1 && errno == EINTR); if (n == -1) { _good = false; @@ -149,7 +149,7 @@ size_t StringSource::read(unsigned char* data, size_t len) { if (pos == s.size()) { throw EndOfFile("end of string reached"); } - size_t n = s.copy((char*)data, len, pos); + size_t n = s.copy(reinterpret_cast(data), len, pos); pos += n; return n; } @@ -179,7 +179,7 @@ std::unique_ptr sinkToSource(const std::function& fun, coro = coro_t::pull_type([&](coro_t::push_type& yield) { LambdaSink sink([&](const unsigned char* data, size_t len) { if (len != 0u) { - yield(std::string((const char*)data, len)); + yield(std::string(reinterpret_cast(data), len)); } }); fun(sink); @@ -200,7 +200,7 @@ std::unique_ptr sinkToSource(const std::function& fun, } auto n = std::min(cur.size() - pos, len); - memcpy(data, (unsigned char*)cur.data() + pos, n); + memcpy(data, reinterpret_cast(cur.data()) + pos, n); pos += n; return n; @@ -225,7 +225,7 @@ void writeString(const unsigned char* buf, size_t len, Sink& sink) { } Sink& operator<<(Sink& sink, const std::string& s) { - writeString((const unsigned char*)s.data(), s.size(), sink); + writeString(reinterpret_cast(s.data()), s.size(), sink); return sink; } @@ -276,7 +276,7 @@ std::string readString(Source& source, size_t max) { throw SerialisationError("string is too long"); } std::string res(len, 0); - source((unsigned char*)res.data(), len); + source(reinterpret_cast(res.data()), len); readPadding(len, source); return res; } @@ -305,7 +305,7 @@ void StringSink::operator()(const unsigned char* data, size_t len) { warnLargeDump(); warned = true; } - s->append((const char*)data, len); + s->append(reinterpret_cast(data), len); } } // namespace nix diff --git a/third_party/nix/src/libutil/util.cc b/third_party/nix/src/libutil/util.cc index 75a8e73eac77..f2580f7b26af 100644 --- a/third_party/nix/src/libutil/util.cc +++ b/third_party/nix/src/libutil/util.cc @@ -207,7 +207,7 @@ bool isDirOrInDir(const Path& path, const Path& dir) { } struct stat lstat(const Path& path) { - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) != 0) { throw SysError(format("getting status of '%1%'") % path); } @@ -215,8 +215,8 @@ struct stat lstat(const Path& path) { } bool pathExists(const Path& path) { - int res; - struct stat st; + int res = 0; + struct stat st {}; res = lstat(path.c_str(), &st); if (res == 0) { return true; @@ -254,7 +254,7 @@ DirEntries readDirectory(DIR* dir, const Path& path) { DirEntries entries; entries.reserve(64); - struct dirent* dirent; + struct dirent* dirent = nullptr; while (errno = 0, dirent = readdir(dir)) { /* sic */ checkInterrupt(); std::string name = dirent->d_name; @@ -300,7 +300,7 @@ unsigned char getFileType(const Path& path) { } std::string readFile(int fd) { - struct stat st; + struct stat st {}; if (fstat(fd, &st) == -1) { throw SysError("statting file"); } @@ -308,7 +308,7 @@ std::string readFile(int fd) { std::vector buf(st.st_size); readFull(fd, buf.data(), st.st_size); - return std::string((char*)buf.data(), st.st_size); + return std::string(reinterpret_cast(buf.data()), st.st_size); } std::string readFile(absl::string_view path, bool drain) { @@ -349,7 +349,7 @@ void writeFile(const Path& path, Source& source, mode_t mode) { while (true) { try { auto n = source.read(buf.data(), buf.size()); - writeFull(fd.get(), (unsigned char*)buf.data(), n); + writeFull(fd.get(), static_cast(buf.data()), n); } catch (EndOfFile&) { break; } @@ -360,7 +360,7 @@ std::string readLine(int fd) { std::string s; while (true) { checkInterrupt(); - char ch; + char ch = 0; // FIXME: inefficient ssize_t rd = read(fd, &ch, 1); if (rd == -1) { @@ -389,7 +389,7 @@ static void _deletePath(int parentfd, const Path& path, std::string name(baseNameOf(path)); - struct stat st; + struct stat st {}; if (fstatat(parentfd, name.c_str(), &st, AT_SYMLINK_NOFOLLOW) == -1) { if (errno == ENOENT) { return; @@ -449,7 +449,7 @@ static void _deletePath(const Path& path, unsigned long long& bytesFreed) { } void deletePath(const Path& path) { - unsigned long long dummy; + unsigned long long dummy = 0; deletePath(path, dummy); } @@ -514,8 +514,8 @@ static Lazy getHome2([]() { Path homeDir = getEnv("HOME"); if (homeDir.empty()) { std::vector buf(16384); - struct passwd pwbuf; - struct passwd* pw; + struct passwd pwbuf {}; + struct passwd* pw = nullptr; if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) != 0 || (pw == nullptr) || (pw->pw_dir == nullptr) || (pw->pw_dir[0] == 0)) { throw Error("cannot determine user's home directory"); @@ -567,7 +567,7 @@ Paths createDirs(const Path& path) { return created; } - struct stat st; + struct stat st {}; if (lstat(path.c_str(), &st) == -1) { created = createDirs(dirOf(path)); if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST) { @@ -619,7 +619,7 @@ void replaceSymlink(const Path& target, const Path& link) { void readFull(int fd, unsigned char* buf, size_t count) { while (count != 0u) { checkInterrupt(); - ssize_t res = read(fd, (char*)buf, count); + ssize_t res = read(fd, reinterpret_cast(buf), count); if (res == -1) { if (errno == EINTR) { continue; @@ -652,7 +652,8 @@ void writeFull(int fd, const unsigned char* buf, size_t count, } void writeFull(int fd, const std::string& s, bool allowInterrupts) { - writeFull(fd, (const unsigned char*)s.data(), s.size(), allowInterrupts); + writeFull(fd, reinterpret_cast(s.data()), s.size(), + allowInterrupts); } std::string drainFD(int fd, bool block) { @@ -662,7 +663,7 @@ std::string drainFD(int fd, bool block) { } void drainFD(int fd, Sink& sink, bool block) { - int saved; + int saved = 0; Finally finally([&]() { if (!block) { @@ -829,7 +830,7 @@ int Pid::kill() { int Pid::wait() { assert(pid != -1); while (true) { - int status; + int status = 0; int res = waitpid(pid, &status, 0); if (res == pid) { pid = -1; @@ -954,7 +955,7 @@ pid_t startProcess(std::function fun, const ProcessOptions& options) { std::vector stringsToCharPtrs(const Strings& ss) { std::vector res; for (auto& s : ss) { - res.push_back((char*)s.c_str()); + res.push_back(const_cast(s.c_str())); } res.push_back(nullptr); return res; @@ -1085,7 +1086,7 @@ void runProgram2(const RunOptions& options) { try { std::vector buf(8 * 1024); while (true) { - size_t n; + size_t n = 0; try { n = source->read(buf.data(), buf.size()); } catch (EndOfFile&) { @@ -1144,7 +1145,7 @@ void closeMostFDs(const std::set& exceptions) { } void closeOnExec(int fd) { - int prev; + int prev = 0; if ((prev = fcntl(fd, F_GETFD, 0)) == -1 || fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1) { throw SysError("setting close-on-exec flag"); @@ -1270,7 +1271,7 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll, size_t w = 0; auto i = s.begin(); - while (w < (size_t)width && i != s.end()) { + while (w < static_cast(width) && i != s.end()) { if (*i == '\e') { std::string e; e += *i++; @@ -1305,7 +1306,7 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll, i++; t += ' '; w++; - while (w < (size_t)width && ((w % 8) != 0u)) { + while (w < static_cast(width) && ((w % 8) != 0u)) { t += ' '; w++; } @@ -1337,7 +1338,7 @@ void callFailure(const std::function& failure, static Sync> windowSize{{0, 0}}; static void updateWindowSize() { - struct winsize ws; + struct winsize ws {}; if (ioctl(2, TIOCGWINSZ, &ws) == 0) { auto windowSize_(windowSize.lock()); windowSize_->first = ws.ws_row; diff --git a/third_party/nix/src/libutil/util.hh b/third_party/nix/src/libutil/util.hh index d9fc1a27b134..09f23706063a 100644 --- a/third_party/nix/src/libutil/util.hh +++ b/third_party/nix/src/libutil/util.hh @@ -163,7 +163,7 @@ void drainFD(int fd, Sink& sink, bool block = true); class AutoDelete { Path path; bool del; - bool recursive; + bool recursive{}; public: AutoDelete(); diff --git a/third_party/nix/src/nix-build/nix-build.cc b/third_party/nix/src/nix-build/nix-build.cc index 7ebb14e1f319..d2a4a23cca26 100644 --- a/third_party/nix/src/nix-build/nix-build.cc +++ b/third_party/nix/src/nix-build/nix-build.cc @@ -155,7 +155,7 @@ static void _main(int argc, char** argv) { ; // obsolete } else if (*arg == "--no-out-link" || *arg == "--no-link") { - outLink = (Path)tmpDir + "/result"; + outLink = Path(tmpDir) + "/result"; } else if (*arg == "--attr" || *arg == "-A") { attrPaths.push_back(getArg(*arg, arg, end)); @@ -328,7 +328,7 @@ static void _main(int argc, char** argv) { } for (auto e : exprs) { - Value vRoot; + Value vRoot{}; state->eval(e, vRoot); for (auto& i : attrPaths) { @@ -343,8 +343,8 @@ static void _main(int argc, char** argv) { auto buildPaths = [&](const PathSet& paths) { /* Note: we do this even when !printMissing to efficiently fetch binary cache data. */ - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; PathSet willBuild; PathSet willSubstitute; PathSet unknown; @@ -381,7 +381,7 @@ static void _main(int argc, char** argv) { auto expr = state->parseExprFromString( "(import {}).bashInteractive", absPath(".")); - Value v; + Value v{}; state->eval(expr, v); auto drv = getDerivation(*state, v, false); @@ -453,7 +453,7 @@ static void _main(int argc, char** argv) { if (passAsFile.count(var.first) != 0u) { keepTmp = true; std::string fn = ".attr-" + std::to_string(fileNr++); - Path p = (Path)tmpDir + "/" + fn; + Path p = Path(tmpDir) + "/" + fn; writeFile(p, var.second); env[var.first + "Path"] = p; } else { @@ -467,7 +467,7 @@ static void _main(int argc, char** argv) { convenience, source $stdenv/setup to setup additional environment variables and shell functions. Also don't lose the current $PATH directories. */ - auto rcfile = (Path)tmpDir + "/rc"; + auto rcfile = Path(tmpDir) + "/rc"; writeFile( rcfile, fmt((keepTmp ? "" : "rm -rf '%1%'; "s) + @@ -486,7 +486,7 @@ static void _main(int argc, char** argv) { "shopt -u nullglob; " "unset TZ; %6%" "%7%", - (Path)tmpDir, (pure ? "" : "p=$PATH; "), + Path(tmpDir), (pure ? "" : "p=$PATH; "), (pure ? "" : "PATH=$PATH:$p; unset p; "), dirOf(shell), shell, (getenv("TZ") != nullptr ? (std::string("export TZ='") + getenv("TZ") + "'; ") diff --git a/third_party/nix/src/nix-channel/nix-channel.cc b/third_party/nix/src/nix-channel/nix-channel.cc index 837fb861d309..7d60752e3f6e 100644 --- a/third_party/nix/src/nix-channel/nix-channel.cc +++ b/third_party/nix/src/nix-channel/nix-channel.cc @@ -112,7 +112,7 @@ static void update(const StringSet& channelNames) { std::smatch match; auto urlBase = baseNameOf(url); if (std::regex_search(urlBase, match, std::regex("(-\\d.*)$"))) { - cname = cname + (std::string)match[1]; + cname = cname + std::string(match[1]); } std::string extraAttrs; @@ -163,7 +163,7 @@ static void update(const StringSet& channelNames) { runProgram(settings.nixBinDir + "/nix-env", false, envArgs); // Make the channels appear in nix-env. - struct stat st; + struct stat st {}; if (lstat(nixDefExpr.c_str(), &st) == 0) { if (S_ISLNK(st.st_mode)) { // old-skool ~/.nix-defexpr @@ -193,7 +193,7 @@ static int _main(int argc, char** argv) { enum { cNone, cAdd, cRemove, cList, cUpdate, cRollback } cmd = cNone; std::vector args; parseCmdLine(argc, argv, - [&](Strings::iterator& arg, const Strings::iterator& end) { + [&](Strings::iterator& arg, const Strings::iterator& _end) { if (*arg == "--help") { showManPage("nix-channel"); } else if (*arg == "--version") { diff --git a/third_party/nix/src/nix-copy-closure/nix-copy-closure.cc b/third_party/nix/src/nix-copy-closure/nix-copy-closure.cc index 3dbe29f2240f..75768d313c65 100644 --- a/third_party/nix/src/nix-copy-closure/nix-copy-closure.cc +++ b/third_party/nix/src/nix-copy-closure/nix-copy-closure.cc @@ -17,7 +17,7 @@ static int _main(int argc, char** argv) { PathSet storePaths; parseCmdLine( - argc, argv, [&](Strings::iterator& arg, const Strings::iterator& end) { + argc, argv, [&](Strings::iterator& arg, const Strings::iterator& _end) { if (*arg == "--help") { showManPage("nix-copy-closure"); } else if (*arg == "--version") { diff --git a/third_party/nix/src/nix-daemon/nix-daemon-proto.cc b/third_party/nix/src/nix-daemon/nix-daemon-proto.cc index d382964a71d8..79b7a9f16b61 100644 --- a/third_party/nix/src/nix-daemon/nix-daemon-proto.cc +++ b/third_party/nix/src/nix-daemon/nix-daemon-proto.cc @@ -15,7 +15,6 @@ namespace nix::daemon { using ::grpc::Status; -using ::nix::proto::BuildStatus; using ::nix::proto::PathInfo; using ::nix::proto::StorePath; using ::nix::proto::StorePaths; @@ -26,7 +25,7 @@ static Status INVALID_STORE_PATH = class WorkerServiceImpl final : public WorkerService::Service { public: - WorkerServiceImpl(nix::Store& store) : store_(&store) {} + explicit WorkerServiceImpl(nix::Store& store) : store_(&store) {} Status IsValidPath(grpc::ServerContext* context, const StorePath* request, nix::proto::IsValidPathResponse* response) override { @@ -261,8 +260,8 @@ class WorkerServiceImpl final : public WorkerService::Service { PathSet will_substitute; PathSet unknown; // TODO(grfn): Switch to concrete size type - unsigned long long download_size; - unsigned long long nar_size; + unsigned long long download_size = 0; + unsigned long long nar_size = 0; store_->queryMissing(targets, will_build, will_substitute, unknown, download_size, nar_size); diff --git a/third_party/nix/src/nix-daemon/nix-daemon.cc b/third_party/nix/src/nix-daemon/nix-daemon.cc index 2570179d42f1..caff57851f93 100644 --- a/third_party/nix/src/nix-daemon/nix-daemon.cc +++ b/third_party/nix/src/nix-daemon/nix-daemon.cc @@ -183,7 +183,7 @@ struct RetrieveRegularNARSink : ParseSink { void createDirectory(const Path& path) override { regular = false; } void receiveContents(unsigned char* data, unsigned int len) override { - s.append((const char*)data, len); + s.append(reinterpret_cast(data), len); } void createSymlink(const Path& path, const std::string& target) override { @@ -296,8 +296,8 @@ static void performOp(TunnelLogger* logger, const ref& store, } case wopAddToStore: { - bool fixed; - bool recursive; + bool fixed = 0; + bool recursive = 0; std::string s; std::string baseName; from >> baseName >> fixed /* obsolete */ >> recursive >> s; @@ -376,7 +376,7 @@ static void performOp(TunnelLogger* logger, const ref& store, auto drvs = readStorePaths(*store, from); BuildMode mode = bmNormal; if (GET_PROTOCOL_MINOR(clientVersion) >= 15) { - mode = (BuildMode)readInt(from); + mode = static_cast(readInt(from)); /* Repairing is not atomic, so disallowed for "untrusted" clients. */ @@ -397,7 +397,7 @@ static void performOp(TunnelLogger* logger, const ref& store, Path drvPath = readStorePath(*store, from); BasicDerivation drv; readDerivation(from, *store, drv); - auto buildMode = (BuildMode)readInt(from); + auto buildMode = static_cast(readInt(from)); logger->startWork(); if (!trusted) { throw Error("you are not privileged to build derivations"); @@ -466,7 +466,7 @@ static void performOp(TunnelLogger* logger, const ref& store, case wopCollectGarbage: { GCOptions options; - options.action = (GCOptions::GCAction)readInt(from); + options.action = static_cast(readInt(from)); options.pathsToDelete = readStorePaths(*store, from); from >> options.ignoreLiveness >> options.maxFreed; // obsolete fields @@ -639,14 +639,15 @@ static void performOp(TunnelLogger* logger, const ref& store, } case wopVerifyStore: { - bool checkContents; - bool repair; + bool checkContents = 0; + bool repair = 0; from >> checkContents >> repair; logger->startWork(); if (repair && !trusted) { throw Error("you are not privileged to repair paths"); } - bool errors = store->verifyStore(checkContents, (RepairFlag)repair); + bool errors = + store->verifyStore(checkContents, static_cast(repair)); logger->stopWork(); to << static_cast(errors); break; @@ -674,8 +675,8 @@ static void performOp(TunnelLogger* logger, const ref& store, } case wopAddToStoreNar: { - bool repair; - bool dontCheckSigs; + bool repair = 0; + bool dontCheckSigs = 0; ValidPathInfo info; info.path = readStorePath(*store, from); from >> info.deriver; @@ -708,7 +709,7 @@ static void performOp(TunnelLogger* logger, const ref& store, logger->startWork(); // FIXME: race if addToStore doesn't read source? - store->addToStore(info, *source, (RepairFlag)repair, + store->addToStore(info, *source, static_cast(repair), dontCheckSigs ? NoCheckSigs : CheckSigs, nullptr); logger->stopWork(); @@ -721,8 +722,8 @@ static void performOp(TunnelLogger* logger, const ref& store, PathSet willBuild; PathSet willSubstitute; PathSet unknown; - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; store->queryMissing(targets, willBuild, willSubstitute, unknown, downloadSize, narSize); logger->stopWork(); @@ -795,9 +796,9 @@ static void processConnection(bool trusted, const std::string& userName, /* Process client requests. */ while (true) { - WorkerOp op; + WorkerOp op{}; try { - op = (WorkerOp)readInt(from); + op = static_cast(readInt(from)); } catch (Interrupted& e) { break; } catch (EndOfFile& e) { @@ -847,8 +848,8 @@ static void sigChldHandler(int sigNo) { } static void setSigChldAction(bool autoReap) { - struct sigaction act; - struct sigaction oact; + struct sigaction act {}; + struct sigaction oact {}; act.sa_handler = autoReap ? sigChldHandler : SIG_DFL; sigfillset(&act.sa_mask); act.sa_flags = 0; @@ -902,7 +903,7 @@ static PeerInfo getPeerInfo(int remote) { #if defined(SO_PEERCRED) - ucred cred; + ucred cred{}; socklen_t credLen = sizeof(cred); if (getsockopt(remote, SOL_SOCKET, SO_PEERCRED, &cred, &credLen) == -1) { throw SysError("getting peer credentials"); @@ -968,7 +969,7 @@ static void daemonLoop(char** argv) { } Path socketPathRel = "./" + baseNameOf(socketPath); - struct sockaddr_un addr; + struct sockaddr_un addr {}; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socketPathRel.c_str(), sizeof(addr.sun_path)); if (addr.sun_path[sizeof(addr.sun_path) - 1] != '\0') { @@ -981,7 +982,8 @@ static void daemonLoop(char** argv) { (everybody can connect --- provided they have access to the directory containing the socket). */ mode_t oldMode = umask(0111); - int res = bind(fdSocket.get(), (struct sockaddr*)&addr, sizeof(addr)); + int res = bind(fdSocket.get(), reinterpret_cast(&addr), + sizeof(addr)); umask(oldMode); if (res == -1) { throw SysError(format("cannot bind to socket '%1%'") % socketPath); @@ -1002,11 +1004,12 @@ static void daemonLoop(char** argv) { while (true) { try { /* Accept a connection. */ - struct sockaddr_un remoteAddr; + struct sockaddr_un remoteAddr {}; socklen_t remoteAddrLen = sizeof(remoteAddr); - AutoCloseFD remote = - accept(fdSocket.get(), (struct sockaddr*)&remoteAddr, &remoteAddrLen); + AutoCloseFD remote = accept( + fdSocket.get(), reinterpret_cast(&remoteAddr), + &remoteAddrLen); checkInterrupt(); if (!remote) { if (errno == EINTR) { @@ -1091,7 +1094,7 @@ static int _main(int argc, char** argv) { auto stdio = false; parseCmdLine(argc, argv, - [&](Strings::iterator& arg, const Strings::iterator& end) { + [&](Strings::iterator& arg, const Strings::iterator& _end) { if (*arg == "--daemon") { ; /* ignored for backwards compatibility */ } else if (*arg == "--help") { @@ -1129,7 +1132,8 @@ static int _main(int argc, char** argv) { throw Error(format("socket name %1% is too long") % socketName); } - if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == -1) { + if (connect(s, reinterpret_cast(&addr), + sizeof(addr)) == -1) { throw SysError(format("cannot connect to daemon at %1%") % socketPath); } diff --git a/third_party/nix/src/nix-env/nix-env.cc b/third_party/nix/src/nix-env/nix-env.cc index 585cfbe3f722..e01ae02978e9 100644 --- a/third_party/nix/src/nix-env/nix-env.cc +++ b/third_party/nix/src/nix-env/nix-env.cc @@ -45,18 +45,18 @@ struct InstallSourceInfo { Path nixExprPath; /* for srcNixExprDrvs, srcNixExprs */ Path profile; /* for srcProfile */ std::string systemFilter; /* for srcNixExprDrvs */ - Bindings* autoArgs; + Bindings* autoArgs{}; }; struct Globals : public gc { InstallSourceInfo instSource; Path profile; std::shared_ptr state; - bool dryRun; - bool preserveInstalled; - bool removeAll; + bool dryRun{}; + bool preserveInstalled{}; + bool removeAll{}; std::string forceName; - bool prebuiltOnly; + bool prebuiltOnly{}; }; using Operation = void (*)(Globals&, Strings, Strings); @@ -106,7 +106,7 @@ static void getAllExprs(EvalState& state, const Path& path, StringSet& attrs, Path path2 = path + "/" + i; - struct stat st; + struct stat st {}; if (stat(path2.c_str(), &st) == -1) { continue; // ignore dangling symlinks in ~/.nix-defexpr } @@ -141,7 +141,7 @@ static void getAllExprs(EvalState& state, const Path& path, StringSet& attrs, } static void loadSourceExpr(EvalState& state, const Path& path, Value& v) { - struct stat st; + struct stat st {}; if (stat(path.c_str(), &st) == -1) { throw SysError(format("getting information about '%1%'") % path); } @@ -171,7 +171,7 @@ static void loadSourceExpr(EvalState& state, const Path& path, Value& v) { static void loadDerivations(EvalState& state, const Path& nixExprPath, const std::string& systemFilter, Bindings& autoArgs, const std::string& pathPrefix, DrvInfos& elems) { - Value vRoot; + Value vRoot{}; loadSourceExpr(state, nixExprPath, vRoot); Value& v(*findAlongAttrPath(state, pathPrefix, autoArgs, vRoot)); @@ -189,12 +189,12 @@ static void loadDerivations(EvalState& state, const Path& nixExprPath, } } -static long getPriority(EvalState& state, DrvInfo& drv) { +static long getPriority(DrvInfo& drv) { return drv.queryMetaInt("priority", 0); } static long comparePriorities(EvalState& state, DrvInfo& drv1, DrvInfo& drv2) { - return getPriority(state, drv2) - getPriority(state, drv1); + return getPriority(drv2) - getPriority(drv1); } // FIXME: this function is rather slow since it checks a single path @@ -346,13 +346,13 @@ static void queryInstSources(EvalState& state, InstallSourceInfo& instSource, argument `x: x.bar' is equivalent to `(x: x.bar) (import ./foo.nix)' = `(import ./foo.nix).bar'. */ case srcNixExprs: { - Value vArg; + Value vArg{}; loadSourceExpr(state, instSource.nixExprPath, vArg); for (auto& i : args) { Expr* eFun = state.parseExprFromString(i, absPath(".")); - Value vFun; - Value vTmp; + Value vFun{}; + Value vTmp{}; state.eval(eFun, vFun); mkApp(vTmp, vFun, vArg); getDerivations(state, vTmp, "", *instSource.autoArgs, elems, true); @@ -406,7 +406,7 @@ static void queryInstSources(EvalState& state, InstallSourceInfo& instSource, } case srcAttrPath: { - Value vRoot; + Value vRoot{}; loadSourceExpr(state, instSource.nixExprPath, vRoot); for (auto& i : args) { Value& v(*findAlongAttrPath(state, i, *instSource.autoArgs, vRoot)); @@ -802,7 +802,7 @@ void printTable(Table& table) { for (auto& i : table) { assert(i.size() == nrColumns); Strings::iterator j; - size_t column; + size_t column = 0; for (j = i.begin(), column = 0; j != i.end(); ++j, ++column) { if (j->size() > widths[column]) { widths[column] = j->size(); @@ -812,7 +812,7 @@ void printTable(Table& table) { for (auto& i : table) { Strings::iterator j; - size_t column; + size_t column = 0; for (j = i.begin(), column = 0; j != i.end(); ++j, ++column) { std::string s = *j; replace(s.begin(), s.end(), '\n', ' '); @@ -1050,7 +1050,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) { attrs["valid"] = isValid ? "1" : "0"; attrs["substitutable"] = hasSubs ? "1" : "0"; } else { - columns.push_back((std::string)(isInstalled ? "I" : "-") + + columns.push_back(std::string(isInstalled ? "I" : "-") + (isValid ? "P" : "-") + (hasSubs ? "S" : "-")); } } @@ -1078,7 +1078,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) { std::string version; VersionDiff diff = compareVersionAgainstSet(i, otherElems, version); - char ch; + char ch = 0; switch (diff) { case cvLess: ch = '>'; @@ -1102,7 +1102,7 @@ static void opQuery(Globals& globals, Strings opFlags, Strings opArgs) { attrs["maxComparedVersion"] = version; } } else { - std::string column = (std::string) "" + ch + " " + version; + std::string column = std::string("") + ch + " " + version; if (diff == cvGreater && tty) { column = ANSI_RED + column + ANSI_NORMAL; } @@ -1266,7 +1266,7 @@ static void switchGeneration(Globals& globals, int dstGen) { PathLocks lock; lockProfile(lock, globals.profile); - int curGen; + int curGen = 0; Generations gens = findGenerations(globals.profile, curGen); Generation dst; @@ -1303,7 +1303,7 @@ static void opSwitchGeneration(Globals& globals, Strings opFlags, throw UsageError(format("exactly one argument expected")); } - int dstGen; + int dstGen = 0; if (!absl::SimpleAtoi(opArgs.front(), &dstGen)) { throw UsageError(format("expected a generation number")); } @@ -1334,13 +1334,13 @@ static void opListGenerations(Globals& globals, Strings opFlags, PathLocks lock; lockProfile(lock, globals.profile); - int curGen; + int curGen = 0; Generations gens = findGenerations(globals.profile, curGen); RunPager pager; for (auto& i : gens) { - tm t; + tm t{}; if (localtime_r(&i.creationTime, &t) == nullptr) { throw Error("cannot convert time"); } @@ -1369,7 +1369,7 @@ static void opDeleteGenerations(Globals& globals, Strings opFlags, opArgs.front()); } std::string str_max = std::string(opArgs.front(), 1, opArgs.front().size()); - int max; + int max = 0; if (!absl::SimpleAtoi(str_max, &max) || max == 0) { throw Error(format("invalid number of generations to keep ‘%1%’") % opArgs.front()); @@ -1378,7 +1378,7 @@ static void opDeleteGenerations(Globals& globals, Strings opFlags, } else { std::set gens; for (auto& i : opArgs) { - unsigned int n; + unsigned int n = 0; if (!absl::SimpleAtoi(i, &n)) { throw UsageError(format("invalid generation number '%1%'") % i); } diff --git a/third_party/nix/src/nix-env/user-env.cc b/third_party/nix/src/nix-env/user-env.cc index 06329e74f340..93dcde96993a 100644 --- a/third_party/nix/src/nix-env/user-env.cc +++ b/third_party/nix/src/nix-env/user-env.cc @@ -17,7 +17,7 @@ DrvInfos queryInstalled(EvalState& state, const Path& userEnv) { DrvInfos elems; Path manifestFile = userEnv + "/manifest.nix"; if (pathExists(manifestFile)) { - Value v; + Value v{}; state.evalFile(manifestFile, v); Bindings& bindings(*Bindings::NewGC()); getDerivations(state, v, "", bindings, elems, false); @@ -42,7 +42,7 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile, /* Construct the whole top level derivation. */ PathSet references; - Value manifest; + Value manifest{}; state.mkList(manifest, elems.size()); unsigned int n = 0; for (auto& i : elems) { @@ -109,13 +109,13 @@ bool createUserEnv(EvalState& state, DrvInfos& elems, const Path& profile, "env-manifest.nix", (format("%1%") % manifest).str(), references); /* Get the environment builder expression. */ - Value envBuilder; + Value envBuilder{}; state.evalFile(state.findFile("nix/buildenv.nix"), envBuilder); /* Construct a Nix expression that calls the user environment builder with the manifest as argument. */ - Value args; - Value topLevel; + Value args{}; + Value topLevel{}; state.mkAttrs(args, 3); mkString(*state.allocAttr(args, state.symbols.Create("manifest")), manifestFile, {manifestFile}); diff --git a/third_party/nix/src/nix-instantiate/nix-instantiate.cc b/third_party/nix/src/nix-instantiate/nix-instantiate.cc index be96943b1234..e963cc145b50 100644 --- a/third_party/nix/src/nix-instantiate/nix-instantiate.cc +++ b/third_party/nix/src/nix-instantiate/nix-instantiate.cc @@ -30,7 +30,7 @@ void processExpr(EvalState& state, const Strings& attrPaths, bool parseOnly, return; } - Value vRoot; + Value vRoot{}; state.eval(e, vRoot); for (auto& i : attrPaths) { @@ -39,7 +39,7 @@ void processExpr(EvalState& state, const Strings& attrPaths, bool parseOnly, PathSet context; if (evalOnly) { - Value vRes; + Value vRes{}; if (autoArgs.empty()) { vRes = v; } else { diff --git a/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc b/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc index dc0dce345bcd..0e5b2ec8a537 100644 --- a/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc +++ b/third_party/nix/src/nix-prefetch-url/nix-prefetch-url.cc @@ -33,7 +33,7 @@ std::string resolveMirrorUri(EvalState& state, std::string uri) { } std::string mirrorName(s, 0, p); - Value vMirrors; + Value vMirrors{}; state.eval( state.parseExprFromString( "import ", "."), @@ -120,7 +120,7 @@ static int _main(int argc, char** argv) { } else { Path path = resolveExprPath(lookupFileArg(*state, args.empty() ? "." : args[0])); - Value vRoot; + Value vRoot{}; state->evalFile(path, vRoot); Value& v(*findAlongAttrPath(*state, attrPath, autoArgs, vRoot)); state->forceAttrs(v); @@ -180,7 +180,7 @@ static int _main(int argc, char** argv) { auto actualUri = resolveMirrorUri(*state, uri); AutoDelete tmpDir(createTempDir(), true); - Path tmpFile = (Path)tmpDir + "/tmp"; + Path tmpFile = Path(tmpDir) + "/tmp"; /* Download the file. */ { @@ -200,7 +200,7 @@ static int _main(int argc, char** argv) { /* Optionally unpack the file. */ if (unpack) { LOG(INFO) << "unpacking..."; - Path unpacked = (Path)tmpDir + "/unpacked"; + Path unpacked = Path(tmpDir) + "/unpacked"; createDirs(unpacked); if (absl::EndsWith(baseNameOf(uri), ".zip")) { runProgram("unzip", true, {"-qq", tmpFile, "-d", unpacked}); diff --git a/third_party/nix/src/nix-store/nix-store.cc b/third_party/nix/src/nix-store/nix-store.cc index 1f1e221fc39c..2183d053e577 100644 --- a/third_party/nix/src/nix-store/nix-store.cc +++ b/third_party/nix/src/nix-store/nix-store.cc @@ -155,8 +155,8 @@ static void opRealise(Strings opFlags, Strings opArgs) { store->followLinksToStorePath(p.first), p.second)); } - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; PathSet willBuild; PathSet willSubstitute; PathSet unknown; @@ -959,9 +959,9 @@ static void opServe(Strings opFlags, Strings opArgs) { }; while (true) { - ServeCommand cmd; + ServeCommand cmd{}; try { - cmd = (ServeCommand)readInt(in); + cmd = static_cast(readInt(in)); } catch (EndOfFile& e) { break; } @@ -988,8 +988,8 @@ static void opServe(Strings opFlags, Strings opArgs) { paths2.insert(path); } } - unsigned long long downloadSize; - unsigned long long narSize; + unsigned long long downloadSize = 0; + unsigned long long narSize = 0; PathSet willBuild; PathSet willSubstitute; PathSet unknown; @@ -1170,13 +1170,15 @@ static void opGenerateBinaryCacheKey(Strings opFlags, Strings opArgs) { throw Error("key generation failed"); } - writeFile(publicKeyFile, keyName + ":" + - absl::Base64Escape(std::string( - (char*)pk, crypto_sign_PUBLICKEYBYTES))); + writeFile(publicKeyFile, + keyName + ":" + + absl::Base64Escape(std::string(reinterpret_cast(pk), + crypto_sign_PUBLICKEYBYTES))); umask(0077); - writeFile(secretKeyFile, keyName + ":" + - absl::Base64Escape(std::string( - (char*)sk, crypto_sign_SECRETKEYBYTES))); + writeFile(secretKeyFile, + keyName + ":" + + absl::Base64Escape(std::string(reinterpret_cast(sk), + crypto_sign_SECRETKEYBYTES))); #else throw Error( "Nix was not compiled with libsodium, required for signed binary cache " diff --git a/third_party/nix/src/nix/edit.cc b/third_party/nix/src/nix/edit.cc index 958e8aec49cc..94a42abb7908 100644 --- a/third_party/nix/src/nix/edit.cc +++ b/third_party/nix/src/nix/edit.cc @@ -28,7 +28,7 @@ struct CmdEdit final : InstallableCommand { auto v = installable->toValue(*state); - Value* v2; + Value* v2 = nullptr; try { auto dummyArgs = Bindings::NewGC(); v2 = findAlongAttrPath(*state, "meta.position", *dummyArgs, *v); @@ -46,7 +46,7 @@ struct CmdEdit final : InstallableCommand { } std::string filename(pos, 0, colon); - int lineno; + int lineno = 0; try { lineno = std::stoi(std::string(pos, colon + 1)); } catch (std::invalid_argument& e) { diff --git a/third_party/nix/src/nix/main.cc b/third_party/nix/src/nix/main.cc index 5536aac53298..fa9ebe37435d 100644 --- a/third_party/nix/src/nix/main.cc +++ b/third_party/nix/src/nix/main.cc @@ -25,7 +25,7 @@ namespace nix { /* Check if we have a non-loopback/link-local network interface. */ static bool haveInternet() { - struct ifaddrs* addrs; + struct ifaddrs* addrs = nullptr; if (getifaddrs(&addrs) != 0) { return true; @@ -38,7 +38,8 @@ static bool haveInternet() { continue; } if (i->ifa_addr->sa_family == AF_INET) { - if (ntohl(((sockaddr_in*)i->ifa_addr)->sin_addr.s_addr) != + if (ntohl( + (reinterpret_cast(i->ifa_addr))->sin_addr.s_addr) != INADDR_LOOPBACK) { return true; } diff --git a/third_party/nix/src/nix/path-info.cc b/third_party/nix/src/nix/path-info.cc index dca08b06adbb..300a588a2ef9 100644 --- a/third_party/nix/src/nix/path-info.cc +++ b/third_party/nix/src/nix/path-info.cc @@ -96,7 +96,9 @@ struct CmdPathInfo final : StorePathsCommand, MixJSON { if (showSize || showClosureSize || showSigs) { std::cout << std::string( - std::max(0, (int)pathLen - (int)storePath.size()), ' '); + std::max(0, static_cast(pathLen) - + static_cast(storePath.size())), + ' '); } if (showSize) { diff --git a/third_party/nix/src/nix/repl.cc b/third_party/nix/src/nix/repl.cc index 7644b7b8c244..91bf500893c3 100644 --- a/third_party/nix/src/nix/repl.cc +++ b/third_party/nix/src/nix/repl.cc @@ -38,14 +38,14 @@ namespace nix { struct NixRepl : gc { std::string curDir; EvalState state; - Bindings* autoArgs; + Bindings* autoArgs{}; Strings loadedFiles; const static int envSize = 32768; StaticEnv staticEnv; - Env* env; - int displ; + Env* env{}; + int displ{}; StringSet varNames; const Path historyFile; @@ -194,7 +194,7 @@ static int listPossibleCallback(char* s, char*** avp) { return p; }; - vp = check((char**)malloc(possible.size() * sizeof(char*))); + vp = check(static_cast(malloc(possible.size() * sizeof(char*)))); for (auto& p : possible) { vp[ac++] = check(strdup(p.c_str())); @@ -272,8 +272,8 @@ void NixRepl::mainLoop(const std::vector& files) { } bool NixRepl::getLine(std::string& input, const std::string& prompt) { - struct sigaction act; - struct sigaction old; + struct sigaction act {}; + struct sigaction old {}; sigset_t savedSignalMask; sigset_t set; @@ -334,8 +334,8 @@ StringSet NixRepl::completePrefix(const std::string& prefix) { cur = std::string(prefix, start + 1); } - size_t slash; - size_t dot; + size_t slash = 0; + size_t dot = 0; if ((slash = cur.rfind('/')) != std::string::npos) { try { @@ -367,7 +367,7 @@ StringSet NixRepl::completePrefix(const std::string& prefix) { std::string cur2 = std::string(cur, dot + 1); Expr* e = parseString(expr); - Value v; + Value v{}; e->eval(state, *env, v); state.forceAttrs(v); @@ -477,7 +477,7 @@ bool NixRepl::processLine(std::string line) { } else if (command == ":a" || command == ":add") { - Value v; + Value v{}; evalString(arg, v); addAttrsToScope(v); } @@ -493,14 +493,14 @@ bool NixRepl::processLine(std::string line) { } else if (command == ":t") { - Value v; + Value v{}; evalString(arg, v); std::cout << showType(v) << std::endl; } else if (command == ":u") { - Value v; - Value f; - Value result; + Value v{}; + Value f{}; + Value result{}; evalString(arg, v); evalString( "drv: (import {}).runCommand \"shell\" { buildInputs = [ drv " @@ -513,7 +513,7 @@ bool NixRepl::processLine(std::string line) { } else if (command == ":b" || command == ":i" || command == ":s") { - Value v; + Value v{}; evalString(arg, v); Path drvPath = getDerivationPath(v); @@ -540,7 +540,7 @@ bool NixRepl::processLine(std::string line) { } else if (command == ":p" || command == ":print") { - Value v; + Value v{}; evalString(arg, v); printValue(std::cout, v, 1000000000) << std::endl; } @@ -563,7 +563,7 @@ bool NixRepl::processLine(std::string line) { v.thunk.expr = e; addVarToScope(state.symbols.Create(name), v); } else { - Value v; + Value v{}; evalString(line, v); printValue(std::cout, v, 1) << std::endl; } @@ -575,8 +575,8 @@ bool NixRepl::processLine(std::string line) { void NixRepl::loadFile(const Path& path) { loadedFiles.remove(path); loadedFiles.push_back(path); - Value v; - Value v2; + Value v{}; + Value v2{}; state.evalFile(lookupFileArg(state, path), v); state.autoCallFunction(*autoArgs, v, v2); addAttrsToScope(v2); @@ -626,7 +626,7 @@ void NixRepl::addVarToScope(const Symbol& name, Value& v) { } staticEnv.vars[name] = displ; env->values[displ++] = &v; - varNames.insert((std::string)name); + varNames.insert(std::string(name)); } Expr* NixRepl::parseString(const std::string& s) { diff --git a/third_party/nix/src/nix/search.cc b/third_party/nix/src/nix/search.cc index 2bfdeac6f7f5..b53f0b50884a 100644 --- a/third_party/nix/src/nix/search.cc +++ b/third_party/nix/src/nix/search.cc @@ -196,8 +196,8 @@ struct CmdSearch final : SourceExprCommand, MixJSON { : nullptr; doExpr(i.second.value, attrPath.empty() - ? (std::string)i.second.name - : attrPath + "." + (std::string)i.second.name, + ? std::string(i.second.name) + : attrPath + "." + std::string(i.second.name), toplevel2 || fromCache, cache2 ? cache2.get() : nullptr); } } @@ -216,7 +216,7 @@ struct CmdSearch final : SourceExprCommand, MixJSON { if (useCache && pathExists(jsonCacheFileName)) { LOG(WARNING) << "using cached results; pass '-u' to update the cache"; - Value vRoot; + Value vRoot{}; parseJSON(*state, readFile(jsonCacheFileName), vRoot); fromCache = true; diff --git a/third_party/nix/src/nix/verify.cc b/third_party/nix/src/nix/verify.cc index a9959d50de1d..6552e3d1a7e0 100644 --- a/third_party/nix/src/nix/verify.cc +++ b/third_party/nix/src/nix/verify.cc @@ -99,7 +99,8 @@ struct CmdVerify final : StorePathsCommand { } else { StringSet sigsSeen; - size_t actualSigsNeeded = std::max(sigsNeeded, (size_t)1); + size_t actualSigsNeeded = + std::max(sigsNeeded, static_cast(1)); size_t validSigs = 0; auto doSigs = [&](const StringSet& sigs) { diff --git a/third_party/nix/src/tests/attr-set.cc b/third_party/nix/src/tests/attr-set.cc index e8ad86664b9d..8ebbbb525cb8 100644 --- a/third_party/nix/src/tests/attr-set.cc +++ b/third_party/nix/src/tests/attr-set.cc @@ -113,7 +113,7 @@ using nix::tests::DummyStore; class AttrSetTest : public ::testing::Test { protected: - EvalState* eval_state_; + EvalState* eval_state_{}; void SetUp() override { nix::initGC(); auto store = std::make_shared(); @@ -122,8 +122,8 @@ class AttrSetTest : public ::testing::Test { } void assert_bindings_equal(nix::Bindings& lhs, nix::Bindings& rhs) { - Value lhs_val; - Value rhs_val; + Value lhs_val{}; + Value rhs_val{}; lhs_val.type = rhs_val.type = ValueType::tAttrs; lhs_val.attrs = &lhs; rhs_val.attrs = &lhs; diff --git a/third_party/nix/src/tests/language-tests.cc b/third_party/nix/src/tests/language-tests.cc index 9fb453e5e537..9616f5e158c9 100644 --- a/third_party/nix/src/tests/language-tests.cc +++ b/third_party/nix/src/tests/language-tests.cc @@ -181,7 +181,7 @@ TEST_P(EvalFailureTest, Fails) { // Again, there are multiple expected exception types and the tests // don't specify which ones they are looking for. try { - Value result; + Value result{}; state.eval(expr, result); state.forceValue(result); std::cout << result; @@ -216,7 +216,7 @@ TEST_P(EvalSuccessTest, Fails) { ASSERT_NO_THROW(expr = state.parseExprFromFile(GetParam().string())) << path.stem().string() << ": should parse successfully"; - Value result; + Value result{}; ASSERT_NO_THROW({ state.eval(expr, result); diff --git a/third_party/nix/src/tests/value-to-json.cc b/third_party/nix/src/tests/value-to-json.cc index 573eb658285d..fbc1fa54d3f5 100644 --- a/third_party/nix/src/tests/value-to-json.cc +++ b/third_party/nix/src/tests/value-to-json.cc @@ -12,9 +12,9 @@ class ValueTest : public ::testing::Test { protected: - static void SetUpTestCase() { nix::initGC(); } + static void SetUpTestSuite() { nix::initGC(); } - static void TearDownTestCase() {} + static void TearDownTestSuite() {} }; class JSONValueTest : public ValueTest {}; @@ -26,7 +26,7 @@ using nix::tests::DummyStore; TEST_F(JSONValueTest, null) { std::stringstream ss; - Value v; + Value v{}; PathSet ps; std::shared_ptr store = std::make_shared(); EvalState s({}, ref(store)); @@ -40,7 +40,7 @@ TEST_F(JSONValueTest, BoolFalse) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkBool(v, false); @@ -52,7 +52,7 @@ TEST_F(JSONValueTest, BoolTrue) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkBool(v, true); @@ -64,7 +64,7 @@ TEST_F(JSONValueTest, IntPositive) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkInt(v, 100); @@ -76,7 +76,7 @@ TEST_F(JSONValueTest, IntNegative) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkInt(v, -100); @@ -88,7 +88,7 @@ TEST_F(JSONValueTest, String) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkString(v, "test"); @@ -100,7 +100,7 @@ TEST_F(JSONValueTest, StringQuotes) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkString(v, "test\""); @@ -112,7 +112,7 @@ TEST_F(JSONValueTest, Path) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkPathNoCopy(v, "/exists-for-tests"); @@ -124,7 +124,7 @@ TEST_F(JSONValueTest, PathNoCopy) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkPathNoCopy(v, "/exists-for-tests"); @@ -141,7 +141,7 @@ TEST_F(JSONValueTest, PathNoCopy) { TEST_F(XMLValueTest, null) { std::stringstream ss; - Value v; + Value v{}; PathSet ps; auto store = std::make_shared(); EvalState s({}, ref(store)); @@ -155,7 +155,7 @@ TEST_F(XMLValueTest, BoolFalse) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkBool(v, false); @@ -167,7 +167,7 @@ TEST_F(XMLValueTest, BoolTrue) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkBool(v, true); @@ -179,7 +179,7 @@ TEST_F(XMLValueTest, IntPositive) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkInt(v, 100); @@ -191,7 +191,7 @@ TEST_F(XMLValueTest, IntNegative) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkInt(v, -100); @@ -203,7 +203,7 @@ TEST_F(XMLValueTest, String) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkString(v, "test-value"); @@ -215,7 +215,7 @@ TEST_F(XMLValueTest, StringQuotes) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkString(v, "test-value\""); @@ -231,7 +231,7 @@ TEST_F(XMLValueTest, Path) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkPath(v, "some-path"); @@ -247,7 +247,7 @@ TEST_F(XMLValueTest, PathNoCopy) { std::stringstream ss; auto store = std::make_shared(); EvalState s({"."}, ref(store)); - Value v; + Value v{}; PathSet ps; mkPathNoCopy(v, "some-other-path"); -- cgit 1.4.1