diff options
Diffstat (limited to 'third_party/nix/src/libutil')
-rw-r--r-- | third_party/nix/src/libutil/archive.cc | 47 | ||||
-rw-r--r-- | third_party/nix/src/libutil/args.cc | 20 | ||||
-rw-r--r-- | third_party/nix/src/libutil/compression.cc | 49 | ||||
-rw-r--r-- | third_party/nix/src/libutil/config.cc | 58 | ||||
-rw-r--r-- | third_party/nix/src/libutil/hash.cc | 64 | ||||
-rw-r--r-- | third_party/nix/src/libutil/json.cc | 21 | ||||
-rw-r--r-- | third_party/nix/src/libutil/serialise.cc | 14 | ||||
-rw-r--r-- | third_party/nix/src/libutil/thread-pool.cc | 6 | ||||
-rw-r--r-- | third_party/nix/src/libutil/util.cc | 203 | ||||
-rw-r--r-- | third_party/nix/src/libutil/xml-writer.cc | 21 |
10 files changed, 316 insertions, 187 deletions
diff --git a/third_party/nix/src/libutil/archive.cc b/third_party/nix/src/libutil/archive.cc index a86170b315e6..855a3c465838 100644 --- a/third_party/nix/src/libutil/archive.cc +++ b/third_party/nix/src/libutil/archive.cc @@ -76,9 +76,10 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) { if (S_ISREG(st.st_mode)) { sink << "type" << "regular"; - if (st.st_mode & S_IXUSR) + if (st.st_mode & S_IXUSR) { sink << "executable" << ""; + } dumpContents(path, (size_t)st.st_size, sink); } @@ -89,7 +90,7 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) { /* If we're on a case-insensitive system like macOS, undo the case hack applied by restorePath(). */ std::map<string, string> unhacked; - for (auto& i : readDirectory(path)) + for (auto& i : readDirectory(path)) { if (archiveSettings.useCaseHack) { string name(i.name); size_t pos = i.name.find(caseHackSuffix); @@ -99,14 +100,17 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) { name.erase(pos); } - if (unhacked.find(name) != unhacked.end()) + if (unhacked.find(name) != unhacked.end()) { throw Error(format("file name collision in between '%1%' and '%2%'") % (path + "/" + unhacked[name]) % (path + "/" + i.name)); + } unhacked[name] = i.name; - } else + } else { unhacked[i.name] = i.name; + } + } - for (auto& i : unhacked) + for (auto& i : unhacked) { if (filter(path + "/" + i.first)) { sink << "entry" << "(" @@ -114,15 +118,17 @@ static void dump(const Path& path, Sink& sink, PathFilter& filter) { dump(path + "/" + i.second, sink, filter); sink << ")"; } + } } - else if (S_ISLNK(st.st_mode)) + else if (S_ISLNK(st.st_mode)) { sink << "type" << "symlink" << "target" << readLink(path); - else + } else { throw Error(format("file '%1%' has an unsupported type") % path); + } sink << ")"; } @@ -222,8 +228,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { type = tpSymlink; } - else + else { throw badArchive("unknown file type " + t); + } } @@ -258,8 +265,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { name = readString(source); if (name.empty() || name == "." || name == ".." || name.find('/') != string::npos || - name.find((char)0) != string::npos) + name.find((char)0) != string::npos) { throw Error(format("NAR contains invalid file name '%1%'") % name); + } if (name <= prevName) { throw Error("NAR directory is not sorted"); } @@ -271,16 +279,18 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { << name << "'"; name += caseHackSuffix; name += std::to_string(++i->second); - } else + } else { names[name] = 0; + } } } else if (s == "node") { if (s.empty()) { throw badArchive("entry name missing"); } parse(sink, source, path + "/" + name); - } else + } else { throw badArchive("unknown field " + s); + } } } @@ -289,8 +299,9 @@ static void parse(ParseSink& sink, Source& source, const Path& path) { sink.createSymlink(path, target); } - else + else { throw badArchive("unknown field " + s); + } } } @@ -302,8 +313,9 @@ void parseDump(ParseSink& sink, Source& source) { /* This generally means the integer at the start couldn't be decoded. Ignore and throw the exception below. */ } - if (version != narVersionMagic1) + if (version != narVersionMagic1) { throw badArchive("input doesn't look like a Nix archive"); + } parse(sink, source, ""); } @@ -313,8 +325,9 @@ struct RestoreSink : ParseSink { void createDirectory(const Path& path) { Path p = dstPath + path; - if (mkdir(p.c_str(), 0777) == -1) + if (mkdir(p.c_str(), 0777) == -1) { throw SysError(format("creating directory '%1%'") % p); + } }; void createRegularFile(const Path& path) { @@ -330,8 +343,9 @@ struct RestoreSink : ParseSink { if (fstat(fd.get(), &st) == -1) { throw SysError("fstat"); } - if (fchmod(fd.get(), st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1) + if (fchmod(fd.get(), st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1) { throw SysError("fchmod"); + } } void preallocateContents(unsigned long long len) { @@ -342,8 +356,9 @@ struct RestoreSink : ParseSink { filesystem doesn't support preallocation (e.g. on OpenSolaris). Since preallocation is just an optimisation, ignore it. */ - if (errno && errno != EINVAL && errno != EOPNOTSUPP && errno != ENOSYS) + if (errno && errno != EINVAL && errno != EOPNOTSUPP && errno != ENOSYS) { throw SysError(format("preallocating file of %1% bytes") % len); + } } #endif } diff --git a/third_party/nix/src/libutil/args.cc b/third_party/nix/src/libutil/args.cc index be1d915819e3..92343d88e5a3 100644 --- a/third_party/nix/src/libutil/args.cc +++ b/third_party/nix/src/libutil/args.cc @@ -30,13 +30,14 @@ void Args::parseCmdline(const Strings& _cmdline) { *pos = (string) "-" + arg[1]; auto next = pos; ++next; - for (unsigned int j = 2; j < arg.length(); j++) - if (isalpha(arg[j])) + for (unsigned int j = 2; j < arg.length(); j++) { + if (isalpha(arg[j])) { cmdline.insert(next, (string) "-" + arg[j]); - else { + } else { cmdline.insert(next, string(arg, j)); break; } + } arg = *pos; } @@ -44,8 +45,9 @@ void Args::parseCmdline(const Strings& _cmdline) { dashDash = true; ++pos; } else if (!dashDash && std::string(arg, 0, 1) == "-") { - if (!processFlag(pos, cmdline.end())) + if (!processFlag(pos, cmdline.end())) { throw UsageError(format("unrecognised flag '%1%'") % arg); + } } else { pendingArgs.push_back(*pos++); if (processArgs(pendingArgs, false)) { @@ -141,8 +143,9 @@ bool Args::processFlag(Strings::iterator& pos, Strings::iterator end) { bool Args::processArgs(const Strings& args, bool finish) { if (expectedArgs.empty()) { - if (!args.empty()) + if (!args.empty()) { throw UsageError(format("unexpected argument '%1%'") % args.front()); + } return true; } @@ -161,8 +164,9 @@ bool Args::processArgs(const Strings& args, bool finish) { res = true; } - if (finish && !expectedArgs.empty() && !expectedArgs.front().optional) + if (finish && !expectedArgs.empty() && !expectedArgs.front().optional) { throw UsageError("more arguments are required"); + } return res; } @@ -184,7 +188,9 @@ Strings argvToStrings(int argc, char** argv) { Strings args; argc--; argv++; - while (argc--) args.push_back(*argv++); + while (argc--) { + args.push_back(*argv++); + } return args; } diff --git a/third_party/nix/src/libutil/compression.cc b/third_party/nix/src/libutil/compression.cc index 219d9046fa65..e13ffcec74d8 100644 --- a/third_party/nix/src/libutil/compression.cc +++ b/third_party/nix/src/libutil/compression.cc @@ -49,8 +49,9 @@ struct XzDecompressionSink : CompressionSink { XzDecompressionSink(Sink& nextSink) : nextSink(nextSink) { lzma_ret ret = lzma_stream_decoder(&strm, UINT64_MAX, LZMA_CONCATENATED); - if (ret != LZMA_OK) + if (ret != LZMA_OK) { throw CompressionError("unable to initialise lzma decoder"); + } strm.next_out = outbuf; strm.avail_out = sizeof(outbuf); @@ -71,8 +72,9 @@ struct XzDecompressionSink : CompressionSink { checkInterrupt(); lzma_ret ret = lzma_code(&strm, data ? LZMA_RUN : LZMA_FINISH); - if (ret != LZMA_OK && ret != LZMA_STREAM_END) + if (ret != LZMA_OK && ret != LZMA_STREAM_END) { throw CompressionError("error %d while decompressing xz file", ret); + } finished = ret == LZMA_STREAM_END; @@ -93,8 +95,9 @@ struct BzipDecompressionSink : ChunkedCompressionSink { BzipDecompressionSink(Sink& nextSink) : nextSink(nextSink) { memset(&strm, 0, sizeof(strm)); int ret = BZ2_bzDecompressInit(&strm, 0, 0); - if (ret != BZ_OK) + if (ret != BZ_OK) { throw CompressionError("unable to initialise bzip2 decoder"); + } strm.next_out = (char*)outbuf; strm.avail_out = sizeof(outbuf); @@ -117,8 +120,9 @@ struct BzipDecompressionSink : ChunkedCompressionSink { checkInterrupt(); int ret = BZ2_bzDecompress(&strm); - if (ret != BZ_OK && ret != BZ_STREAM_END) + if (ret != BZ_OK && ret != BZ_STREAM_END) { throw CompressionError("error while decompressing bzip2 file"); + } finished = ret == BZ_STREAM_END; @@ -160,8 +164,9 @@ struct BrotliDecompressionSink : ChunkedCompressionSink { checkInterrupt(); if (!BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out, - &next_out, nullptr)) + &next_out, nullptr)) { throw CompressionError("error while decompressing brotli file"); + } if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink(outbuf, sizeof(outbuf) - avail_out); @@ -184,16 +189,17 @@ ref<std::string> decompress(const std::string& method, const std::string& in) { ref<CompressionSink> makeDecompressionSink(const std::string& method, Sink& nextSink) { - if (method == "none" || method == "") + if (method == "none" || method == "") { return make_ref<NoneSink>(nextSink); - else if (method == "xz") + } else if (method == "xz") { return make_ref<XzDecompressionSink>(nextSink); - else if (method == "bzip2") + } else if (method == "bzip2") { return make_ref<BzipDecompressionSink>(nextSink); - else if (method == "br") + } else if (method == "br") { return make_ref<BrotliDecompressionSink>(nextSink); - else + } else { throw UnknownCompressionMethod("unknown compression method '%s'", method); + } } struct XzCompressionSink : CompressionSink { @@ -258,8 +264,9 @@ struct XzCompressionSink : CompressionSink { checkInterrupt(); lzma_ret ret = lzma_code(&strm, data ? LZMA_RUN : LZMA_FINISH); - if (ret != LZMA_OK && ret != LZMA_STREAM_END) + if (ret != LZMA_OK && ret != LZMA_STREAM_END) { throw CompressionError("error %d while compressing xz file", ret); + } finished = ret == LZMA_STREAM_END; @@ -280,8 +287,9 @@ struct BzipCompressionSink : ChunkedCompressionSink { BzipCompressionSink(Sink& nextSink) : nextSink(nextSink) { memset(&strm, 0, sizeof(strm)); int ret = BZ2_bzCompressInit(&strm, 9, 0, 30); - if (ret != BZ_OK) + if (ret != BZ_OK) { throw CompressionError("unable to initialise bzip2 encoder"); + } strm.next_out = (char*)outbuf; strm.avail_out = sizeof(outbuf); @@ -304,8 +312,9 @@ struct BzipCompressionSink : ChunkedCompressionSink { checkInterrupt(); int ret = BZ2_bzCompress(&strm, data ? BZ_RUN : BZ_FINISH); - if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK && ret != BZ_STREAM_END) + if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK && ret != BZ_STREAM_END) { throw CompressionError("error %d while compressing bzip2 file", ret); + } finished = ret == BZ_STREAM_END; @@ -349,8 +358,9 @@ struct BrotliCompressionSink : ChunkedCompressionSink { if (!BrotliEncoderCompressStream( state, data ? BROTLI_OPERATION_PROCESS : BROTLI_OPERATION_FINISH, - &avail_in, &next_in, &avail_out, &next_out, nullptr)) + &avail_in, &next_in, &avail_out, &next_out, nullptr)) { throw CompressionError("error while compressing brotli compression"); + } if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink(outbuf, sizeof(outbuf) - avail_out); @@ -365,17 +375,18 @@ struct BrotliCompressionSink : ChunkedCompressionSink { ref<CompressionSink> makeCompressionSink(const std::string& method, Sink& nextSink, const bool parallel) { - if (method == "none") + if (method == "none") { return make_ref<NoneSink>(nextSink); - else if (method == "xz") + } else if (method == "xz") { return make_ref<XzCompressionSink>(nextSink, parallel); - else if (method == "bzip2") + } else if (method == "bzip2") { return make_ref<BzipCompressionSink>(nextSink); - else if (method == "br") + } else if (method == "br") { return make_ref<BrotliCompressionSink>(nextSink); - else + } else { throw UnknownCompressionMethod(format("unknown compression method '%s'") % method); + } } ref<std::string> compress(const std::string& method, const std::string& in, diff --git a/third_party/nix/src/libutil/config.cc b/third_party/nix/src/libutil/config.cc index 0b01f6ae8a83..9c8c6cf4b255 100644 --- a/third_party/nix/src/libutil/config.cc +++ b/third_party/nix/src/libutil/config.cc @@ -21,8 +21,9 @@ bool Config::set(const std::string& name, const std::string& value) { void Config::addSetting(AbstractSetting* setting) { _settings.emplace(setting->name, Config::SettingData(false, setting)); - for (auto& alias : setting->aliases) + for (auto& alias : setting->aliases) { _settings.emplace(alias, Config::SettingData(true, setting)); + } bool set = false; @@ -68,11 +69,13 @@ void AbstractConfig::reapplyUnknownSettings() { void Config::getSettings(std::map<std::string, SettingInfo>& res, bool overridenOnly) { - for (auto& opt : _settings) + for (auto& opt : _settings) { if (!opt.second.isAlias && - (!overridenOnly || opt.second.setting->overriden)) + (!overridenOnly || opt.second.setting->overriden)) { res.emplace(opt.first, SettingInfo{opt.second.setting->to_string(), opt.second.setting->description}); + } + } } void AbstractConfig::applyConfigFile(const Path& path) { @@ -83,8 +86,9 @@ void AbstractConfig::applyConfigFile(const Path& path) { while (pos < contents.size()) { string line; - while (pos < contents.size() && contents[pos] != '\n') + while (pos < contents.size() && contents[pos] != '\n') { line += contents[pos++]; + } pos++; string::size_type hash = line.find('#'); @@ -97,23 +101,25 @@ void AbstractConfig::applyConfigFile(const Path& path) { continue; } - if (tokens.size() < 2) + if (tokens.size() < 2) { throw UsageError("illegal configuration line '%1%' in '%2%'", line, path); + } auto include = false; auto ignoreMissing = false; - if (tokens[0] == "include") + if (tokens[0] == "include") { include = true; - else if (tokens[0] == "!include") { + } else if (tokens[0] == "!include") { include = true; ignoreMissing = true; } if (include) { - if (tokens.size() != 2) + if (tokens.size() != 2) { throw UsageError("illegal configuration line '%1%' in '%2%'", line, path); + } auto p = absPath(tokens[1], dirOf(path)); if (pathExists(p)) { applyConfigFile(p); @@ -123,9 +129,10 @@ void AbstractConfig::applyConfigFile(const Path& path) { continue; } - if (tokens[1] != "=") + if (tokens[1] != "=") { throw UsageError("illegal configuration line '%1%' in '%2%'", line, path); + } string name = tokens[0]; @@ -146,20 +153,22 @@ void Config::resetOverriden() { } void Config::toJSON(JSONObject& out) { - for (auto& s : _settings) + for (auto& s : _settings) { if (!s.second.isAlias) { JSONObject out2(out.object(s.first)); out2.attr("description", s.second.setting->description); JSONPlaceholder out3(out2.placeholder("value")); s.second.setting->toJSON(out3); } + } } void Config::convertToArgs(Args& args, const std::string& category) { - for (auto& s : _settings) + for (auto& s : _settings) { if (!s.second.isAlias) { s.second.setting->convertToArg(args, category); } + } } AbstractSetting::AbstractSetting(const std::string& name, @@ -202,8 +211,9 @@ std::string BaseSetting<std::string>::to_string() { template <typename T> void BaseSetting<T>::set(const std::string& str) { static_assert(std::is_integral<T>::value, "Integer required."); - if (!string2Int(str, value)) + if (!string2Int(str, value)) { throw UsageError("setting '%s' has invalid value '%s'", name, str); + } } template <typename T> @@ -214,12 +224,13 @@ std::string BaseSetting<T>::to_string() { template <> void BaseSetting<bool>::set(const std::string& str) { - if (str == "true" || str == "yes" || str == "1") + if (str == "true" || str == "yes" || str == "1") { value = true; - else if (str == "false" || str == "no" || str == "0") + } else if (str == "false" || str == "no" || str == "0") { value = false; - else + } else { throw UsageError("Boolean setting '%s' has invalid value '%s'", name, str); + } } template <> @@ -290,19 +301,22 @@ template class BaseSetting<StringSet>; void PathSetting::set(const std::string& str) { if (str == "") { - if (allowEmpty) + if (allowEmpty) { value = ""; - else + } else { throw UsageError("setting '%s' cannot be empty", name); - } else + } + } else { value = canonPath(str); + } } bool GlobalConfig::set(const std::string& name, const std::string& value) { - for (auto& config : *configRegistrations) + for (auto& config : *configRegistrations) { if (config->set(name, value)) { return true; } + } unknownSettings.emplace(name, value); @@ -311,8 +325,9 @@ bool GlobalConfig::set(const std::string& name, const std::string& value) { void GlobalConfig::getSettings(std::map<std::string, SettingInfo>& res, bool overridenOnly) { - for (auto& config : *configRegistrations) + for (auto& config : *configRegistrations) { config->getSettings(res, overridenOnly); + } } void GlobalConfig::resetOverriden() { @@ -328,8 +343,9 @@ void GlobalConfig::toJSON(JSONObject& out) { } void GlobalConfig::convertToArgs(Args& args, const std::string& category) { - for (auto& config : *configRegistrations) + for (auto& config : *configRegistrations) { config->convertToArgs(args, category); + } } GlobalConfig globalConfig; diff --git a/third_party/nix/src/libutil/hash.cc b/third_party/nix/src/libutil/hash.cc index 0a0869dd4e8c..e33c76cc9093 100644 --- a/third_party/nix/src/libutil/hash.cc +++ b/third_party/nix/src/libutil/hash.cc @@ -132,8 +132,9 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { sep = s.find('-'); if (sep != string::npos) { isSRI = true; - } else if (type == htUnknown) + } else if (type == htUnknown) { throw BadHash("hash '%s' does not include a type", s); + } } if (sep != string::npos) { @@ -142,8 +143,9 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { if (this->type == htUnknown) { throw BadHash("unknown hash type '%s'", hts); } - if (type != htUnknown && type != this->type) + if (type != htUnknown && type != this->type) { throw BadHash("hash '%s' should have type '%s'", s, printHashType(type)); + } pos = sep + 1; } @@ -175,10 +177,11 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { for (unsigned int n = 0; n < size; ++n) { char c = s[pos + size - n - 1]; unsigned char digit; - for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */ + for (digit = 0; digit < base32Chars.size(); ++digit) { /* !!! slow */ if (base32Chars[digit] == c) { break; } + } if (digit >= 32) { throw BadHash("invalid base-32 hash '%s'", s); } @@ -199,15 +202,17 @@ Hash::Hash(const std::string& s, HashType type) : type(type) { else if (isSRI || size == base64Len()) { auto d = base64Decode(std::string(s, pos)); - if (d.size() != hashSize) + if (d.size() != hashSize) { throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", s); + } assert(hashSize); memcpy(hash, d.data(), hashSize); } - else + else { throw BadHash("hash '%s' has wrong length for hash type '%s'", s, printHashType(type)); + } } union Ctx { @@ -218,37 +223,40 @@ union Ctx { }; static void start(HashType ht, Ctx& ctx) { - if (ht == htMD5) + if (ht == htMD5) { MD5_Init(&ctx.md5); - else if (ht == htSHA1) + } else if (ht == htSHA1) { SHA1_Init(&ctx.sha1); - else if (ht == htSHA256) + } else if (ht == htSHA256) { SHA256_Init(&ctx.sha256); - else if (ht == htSHA512) + } else if (ht == htSHA512) { SHA512_Init(&ctx.sha512); + } } static void update(HashType ht, Ctx& ctx, const unsigned char* bytes, size_t len) { - if (ht == htMD5) + if (ht == htMD5) { MD5_Update(&ctx.md5, bytes, len); - else if (ht == htSHA1) + } else if (ht == htSHA1) { SHA1_Update(&ctx.sha1, bytes, len); - else if (ht == htSHA256) + } else if (ht == htSHA256) { SHA256_Update(&ctx.sha256, bytes, len); - else if (ht == htSHA512) + } else if (ht == htSHA512) { SHA512_Update(&ctx.sha512, bytes, len); + } } static void finish(HashType ht, Ctx& ctx, unsigned char* hash) { - if (ht == htMD5) + if (ht == htMD5) { MD5_Final(hash, &ctx.md5); - else if (ht == htSHA1) + } else if (ht == htSHA1) { SHA1_Final(hash, &ctx.sha1); - else if (ht == htSHA256) + } else if (ht == htSHA256) { SHA256_Final(hash, &ctx.sha256); - else if (ht == htSHA512) + } else if (ht == htSHA512) { SHA512_Final(hash, &ctx.sha512); + } } Hash hashString(HashType ht, const string& s) { @@ -331,29 +339,31 @@ Hash compressHash(const Hash& hash, unsigned int newSize) { } HashType parseHashType(const string& s) { - if (s == "md5") + if (s == "md5") { return htMD5; - else if (s == "sha1") + } else if (s == "sha1") { return htSHA1; - else if (s == "sha256") + } else if (s == "sha256") { return htSHA256; - else if (s == "sha512") + } else if (s == "sha512") { return htSHA512; - else + } else { return htUnknown; + } } string printHashType(HashType ht) { - if (ht == htMD5) + if (ht == htMD5) { return "md5"; - else if (ht == htSHA1) + } else if (ht == htSHA1) { return "sha1"; - else if (ht == htSHA256) + } else if (ht == htSHA256) { return "sha256"; - else if (ht == htSHA512) + } else if (ht == htSHA512) { return "sha512"; - else + } else { abort(); + } } } // namespace nix diff --git a/third_party/nix/src/libutil/json.cc b/third_party/nix/src/libutil/json.cc index 7965f4725ba4..c5f52ae8ef3f 100644 --- a/third_party/nix/src/libutil/json.cc +++ b/third_party/nix/src/libutil/json.cc @@ -7,28 +7,31 @@ namespace nix { void toJSON(std::ostream& str, const char* start, const char* end) { str << '"'; - for (auto i = start; i != end; i++) - if (*i == '\"' || *i == '\\') + for (auto i = start; i != end; i++) { + if (*i == '\"' || *i == '\\') { str << '\\' << *i; - else if (*i == '\n') + } else if (*i == '\n') { str << "\\n"; - else if (*i == '\r') + } else if (*i == '\r') { str << "\\r"; - else if (*i == '\t') + } else if (*i == '\t') { str << "\\t"; - else if (*i >= 0 && *i < 32) + } else if (*i >= 0 && *i < 32) { str << "\\u" << std::setfill('0') << std::setw(4) << std::hex << (uint16_t)*i << std::dec; - else + } else { str << *i; + } + } str << '"'; } void toJSON(std::ostream& str, const char* s) { - if (!s) + if (!s) { str << "null"; - else + } else { toJSON(str, s, s + strlen(s)); + } } template <> diff --git a/third_party/nix/src/libutil/serialise.cc b/third_party/nix/src/libutil/serialise.cc index 760d19ed4cf3..b51ed2105b4d 100644 --- a/third_party/nix/src/libutil/serialise.cc +++ b/third_party/nix/src/libutil/serialise.cc @@ -173,7 +173,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun, size_t pos = 0; size_t read(unsigned char* data, size_t len) override { - if (!coro) + if (!coro) { coro = coro_t::pull_type([&](coro_t::push_type& yield) { LambdaSink sink([&](const unsigned char* data, size_t len) { if (len) { @@ -182,6 +182,7 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun, }); fun(sink); }); + } if (!*coro) { eof(); @@ -189,7 +190,9 @@ std::unique_ptr<Source> sinkToSource(std::function<void(Sink&)> fun, } if (pos == cur.size()) { - if (!cur.empty()) (*coro)(); + if (!cur.empty()) { + (*coro)(); + } cur = coro->get(); pos = 0; } @@ -247,10 +250,11 @@ void readPadding(size_t len, Source& source) { unsigned char zero[8]; size_t n = 8 - (len % 8); source(zero, n); - for (unsigned int i = 0; i < n; i++) + for (unsigned int i = 0; i < n; i++) { if (zero[i]) { throw SerialisationError("non-zero padding"); } + } } } @@ -284,7 +288,9 @@ template <class T> T readStrings(Source& source) { auto count = readNum<size_t>(source); T ss; - while (count--) ss.insert(ss.end(), readString(source)); + while (count--) { + ss.insert(ss.end(), readString(source)); + } return ss; } diff --git a/third_party/nix/src/libutil/thread-pool.cc b/third_party/nix/src/libutil/thread-pool.cc index a16f4c2b6033..d0042c6df195 100644 --- a/third_party/nix/src/libutil/thread-pool.cc +++ b/third_party/nix/src/libutil/thread-pool.cc @@ -50,8 +50,9 @@ void ThreadPool::enqueue(const work_t& t) { state->pending.push(t); /* Note: process() also executes items, so count it as a worker. */ if (state->pending.size() > state->workers.size() + 1 && - state->workers.size() + 1 < maxThreads) + state->workers.size() + 1 < maxThreads) { state->workers.emplace_back(&ThreadPool::doWork, this, false); + } work.notify_one(); } @@ -111,8 +112,9 @@ void ThreadPool::doWork(bool mainThread) { std::rethrow_exception(exc); } catch (std::exception& e) { if (!dynamic_cast<Interrupted*>(&e) && - !dynamic_cast<ThreadPoolShutDown*>(&e)) + !dynamic_cast<ThreadPoolShutDown*>(&e)) { ignoreException(); + } } catch (...) { } } diff --git a/third_party/nix/src/libutil/util.cc b/third_party/nix/src/libutil/util.cc index 3cc8563a8651..213a9a0d6ab9 100644 --- a/third_party/nix/src/libutil/util.cc +++ b/third_party/nix/src/libutil/util.cc @@ -60,9 +60,10 @@ std::map<std::string, std::string> getEnv() { for (size_t i = 0; environ[i]; ++i) { auto s = environ[i]; auto eq = strchr(s, '='); - if (!eq) + if (!eq) { // invalid env, just keep going continue; + } env.emplace(std::string(s, eq), std::string(eq + 1)); } return env; @@ -91,18 +92,19 @@ Path absPath(Path path, Path dir) { if (buf == NULL) #else char buf[PATH_MAX]; - if (!getcwd(buf, sizeof(buf))) + if (!getcwd(buf, sizeof(buf))) { #endif throw SysError("cannot get cwd"); - dir = buf; + } + dir = buf; #ifdef __GNU__ - free(buf); + free(buf); #endif - } - path = dir + "/" + path; } - return canonPath(path); + path = dir + "/" + path; } +return canonPath(path); +} // namespace nix Path canonPath(const Path& path, bool resolveSymlinks) { assert(path != ""); @@ -122,7 +124,9 @@ Path canonPath(const Path& path, bool resolveSymlinks) { while (1) { /* Skip slashes. */ - while (i != end && *i == '/') i++; + while (i != end && *i == '/') { + i++; + } if (i == end) { break; } @@ -144,14 +148,17 @@ Path canonPath(const Path& path, bool resolveSymlinks) { /* Normal component; copy it. */ else { s += '/'; - while (i != end && *i != '/') s += *i++; + while (i != end && *i != '/') { + s += *i++; + } /* If s points to a symlink, resolve it and restart (since the symlink target might contain new symlinks). */ if (resolveSymlinks && isLink(s)) { - if (++followCount >= maxFollow) + if (++followCount >= maxFollow) { throw Error(format("infinite symlink recursion in path '%1%'") % path); + } temp = absPath(readLink(s), dirOf(s)) + string(i, end); i = temp.begin(); /* restart */ end = temp.end(); @@ -182,10 +189,11 @@ string baseNameOf(const Path& path) { } Path::size_type pos = path.rfind('/', last); - if (pos == string::npos) + if (pos == string::npos) { pos = 0; - else + } else { pos += 1; + } return string(path, pos, last - pos + 1); } @@ -201,8 +209,9 @@ bool isDirOrInDir(const Path& path, const Path& dir) { struct stat lstat(const Path& path) { struct stat st; - if (lstat(path.c_str(), &st)) + if (lstat(path.c_str(), &st)) { throw SysError(format("getting status of '%1%'") % path); + } return st; } @@ -213,8 +222,9 @@ bool pathExists(const Path& path) { if (!res) { return true; } - if (errno != ENOENT && errno != ENOTDIR) + if (errno != ENOENT && errno != ENOTDIR) { throw SysError(format("getting status of %1%") % path); + } return false; } @@ -224,13 +234,15 @@ Path readLink(const Path& path) { for (ssize_t bufSize = PATH_MAX / 4; true; bufSize += bufSize / 2) { buf.resize(bufSize); ssize_t rlSize = readlink(path.c_str(), buf.data(), bufSize); - if (rlSize == -1) - if (errno == EINVAL) + if (rlSize == -1) { + if (errno == EINVAL) { throw Error("'%1%' is not a symlink", path); - else + } else { throw SysError("reading symbolic link '%1%'", path); - else if (rlSize < bufSize) + } + } else if (rlSize < bufSize) { return string(buf.data(), rlSize); + } } } @@ -351,9 +363,9 @@ string readLine(int fd) { if (errno != EINTR) { throw SysError("reading a line"); } - } else if (rd == 0) + } else if (rd == 0) { throw EndOfFile("unexpected EOF reading a line"); - else { + } else { if (ch == '\n') { return s; } @@ -386,12 +398,14 @@ static void _deletePath(const Path& path, unsigned long long& bytesFreed) { /* Make the directory accessible. */ const auto PERM_MASK = S_IRUSR | S_IWUSR | S_IXUSR; if ((st.st_mode & PERM_MASK) != PERM_MASK) { - if (chmod(path.c_str(), st.st_mode | PERM_MASK) == -1) + if (chmod(path.c_str(), st.st_mode | PERM_MASK) == -1) { throw SysError(format("chmod '%1%'") % path); + } } - for (auto& i : readDirectory(path)) + for (auto& i : readDirectory(path)) { _deletePath(path + "/" + i.name, bytesFreed); + } } if (remove(path.c_str()) == -1) { @@ -418,11 +432,12 @@ static Path tempName(Path tmpRoot, const Path& prefix, bool includePid, int& counter) { tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR", "/tmp") : tmpRoot, true); - if (includePid) + if (includePid) { return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++) .str(); - else + } else { return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str(); + } } Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid, @@ -449,8 +464,9 @@ Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid, #endif return tmpDir; } - if (errno != EEXIST) + if (errno != EEXIST) { throw SysError(format("creating directory '%1%'") % tmpDir); + } } } @@ -470,8 +486,9 @@ static Lazy<Path> getHome2([]() { struct passwd pwbuf; struct passwd* pw; if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) != 0 || - !pw || !pw->pw_dir || !pw->pw_dir[0]) + !pw || !pw->pw_dir || !pw->pw_dir[0]) { throw Error("cannot determine user's home directory"); + } homeDir = pw->pw_dir; } return homeDir; @@ -521,25 +538,29 @@ Paths createDirs(const Path& path) { struct stat st; if (lstat(path.c_str(), &st) == -1) { created = createDirs(dirOf(path)); - if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST) + if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST) { throw SysError(format("creating directory '%1%'") % path); + } st = lstat(path); created.push_back(path); } - if (S_ISLNK(st.st_mode) && stat(path.c_str(), &st) == -1) + if (S_ISLNK(st.st_mode) && stat(path.c_str(), &st) == -1) { throw SysError(format("statting symlink '%1%'") % path); + } - if (!S_ISDIR(st.st_mode)) + if (!S_ISDIR(st.st_mode)) { throw Error(format("'%1%' is not a directory") % path); + } return created; } void createSymlink(const Path& target, const Path& link) { - if (symlink(target.c_str(), link.c_str())) + if (symlink(target.c_str(), link.c_str())) { throw SysError(format("creating symlink from '%1%' to '%2%'") % link % target); + } } void replaceSymlink(const Path& target, const Path& link) { @@ -555,8 +576,9 @@ void replaceSymlink(const Path& target, const Path& link) { throw; } - if (rename(tmp.c_str(), link.c_str()) != 0) + if (rename(tmp.c_str(), link.c_str()) != 0) { throw SysError(format("renaming '%1%' to '%2%'") % tmp % link); + } break; } @@ -612,15 +634,17 @@ void drainFD(int fd, Sink& sink, bool block) { Finally finally([&]() { if (!block) { - if (fcntl(fd, F_SETFL, saved) == -1) + if (fcntl(fd, F_SETFL, saved) == -1) { throw SysError("making file descriptor blocking"); + } } }); if (!block) { saved = fcntl(fd, F_GETFL); - if (fcntl(fd, F_SETFL, saved | O_NONBLOCK) == -1) + if (fcntl(fd, F_SETFL, saved | O_NONBLOCK) == -1) { throw SysError("making file descriptor non-blocking"); + } } std::vector<unsigned char> buf(64 * 1024); @@ -634,10 +658,11 @@ void drainFD(int fd, Sink& sink, bool block) { if (errno != EINTR) { throw SysError("reading from file"); } - } else if (rd == 0) + } else if (rd == 0) { break; - else + } else { sink(buf.data(), rd); + } } } @@ -656,8 +681,9 @@ AutoDelete::~AutoDelete() { if (recursive) { deletePath(path); } else { - if (remove(path.c_str()) == -1) + if (remove(path.c_str()) == -1) { throw SysError(format("cannot unlink '%1%'") % path); + } } } } catch (...) { @@ -700,8 +726,9 @@ int AutoCloseFD::get() const { return fd; } void AutoCloseFD::close() { if (fd != -1) { - if (::close(fd) == -1) /* This should never happen. */ + if (::close(fd) == -1) { /* This should never happen. */ throw SysError(format("closing file descriptor %1%") % fd); + } } } @@ -835,8 +862,9 @@ void killUser(uid_t uid) { if (errno == ESRCH) { break; } /* no more processes */ - if (errno != EINTR) + if (errno != EINTR) { throw SysError(format("cannot kill processes for uid '%1%'") % uid); + } } _exit(0); @@ -844,9 +872,10 @@ void killUser(uid_t uid) { options); int status = pid.wait(); - if (status != 0) + if (status != 0) { throw Error(format("cannot kill processes for uid '%1%': %2%") % uid % statusToString(status)); + } /* !!! We should really do some check to make sure that there are no processes left running under `uid', but there is no portable @@ -877,8 +906,9 @@ pid_t startProcess(std::function<void()> fun, const ProcessOptions& options) { auto wrapper = [&]() { try { #if __linux__ - if (options.dieWithParent && prctl(PR_SET_PDEATHSIG, SIGKILL) == -1) + if (options.dieWithParent && prctl(PR_SET_PDEATHSIG, SIGKILL) == -1) { throw SysError("setting death signal"); + } #endif restoreAffinity(); fun(); @@ -889,10 +919,11 @@ pid_t startProcess(std::function<void()> fun, const ProcessOptions& options) { } } catch (...) { } - if (options.runExitHandlers) + if (options.runExitHandlers) { exit(1); - else + } else { _exit(1); + } }; pid_t pid = doFork(options.allowVfork, wrapper); @@ -920,9 +951,10 @@ string runProgram(Path program, bool searchPath, const Strings& args, auto res = runProgram(opts); - if (!statusOk(res.first)) + if (!statusOk(res.first)) { throw ExecError(res.first, fmt("program '%1%' %2%", program, statusToString(res.first))); + } return res.second; } @@ -980,33 +1012,42 @@ void runProgram2(const RunOptions& options) { replaceEnv(*options.environment); } if (options.standardOut && - dup2(out.writeSide.get(), STDOUT_FILENO) == -1) + dup2(out.writeSide.get(), STDOUT_FILENO) == -1) { throw SysError("dupping stdout"); - if (options.mergeStderrToStdout) - if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1) + } + if (options.mergeStderrToStdout) { + if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1) { throw SysError("cannot dup stdout into stderr"); - if (source && dup2(in.readSide.get(), STDIN_FILENO) == -1) + } + } + if (source && dup2(in.readSide.get(), STDIN_FILENO) == -1) { throw SysError("dupping stdin"); + } - if (options.chdir && chdir((*options.chdir).c_str()) == -1) + if (options.chdir && chdir((*options.chdir).c_str()) == -1) { throw SysError("chdir failed"); - if (options.gid && setgid(*options.gid) == -1) + } + if (options.gid && setgid(*options.gid) == -1) { throw SysError("setgid failed"); + } /* Drop all other groups if we're setgid. */ - if (options.gid && setgroups(0, 0) == -1) + if (options.gid && setgroups(0, 0) == -1) { throw SysError("setgroups failed"); - if (options.uid && setuid(*options.uid) == -1) + } + if (options.uid && setuid(*options.uid) == -1) { throw SysError("setuid failed"); + } Strings args_(options.args); args_.push_front(options.program); restoreSignals(); - if (options.searchPath) + if (options.searchPath) { execvp(options.program.c_str(), stringsToCharPtrs(args_).data()); - else + } else { execv(options.program.c_str(), stringsToCharPtrs(args_).data()); + } throw SysError("executing '%1%'", options.program); }, @@ -1058,9 +1099,10 @@ void runProgram2(const RunOptions& options) { promise.get_future().get(); } - if (status) + if (status) { throw ExecError(status, fmt("program '%1%' %2%", options.program, statusToString(status))); + } } void closeMostFDs(const set<int>& exceptions) { @@ -1080,17 +1122,19 @@ void closeMostFDs(const set<int>& exceptions) { int maxFD = 0; maxFD = sysconf(_SC_OPEN_MAX); - for (int fd = 0; fd < maxFD; ++fd) + for (int fd = 0; fd < maxFD; ++fd) { if (!exceptions.count(fd)) { close(fd); } /* ignore result */ + } } void closeOnExec(int fd) { int prev; if ((prev = fcntl(fd, F_GETFD, 0)) == -1 || - fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1) + fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1) { throw SysError("setting close-on-exec flag"); + } } ////////////////////////////////////////////////////////////////////// @@ -1187,9 +1231,9 @@ string replaceStrings(const std::string& s, const std::string& from, string statusToString(int status) { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { - if (WIFEXITED(status)) + if (WIFEXITED(status)) { return (format("failed with exit code %1%") % WEXITSTATUS(status)).str(); - else if (WIFSIGNALED(status)) { + } else if (WIFSIGNALED(status)) { int sig = WTERMSIG(status); #if HAVE_STRSIGNAL const char* description = strsignal(sig); @@ -1198,10 +1242,12 @@ string statusToString(int status) { #else return (format("failed due to signal %1%") % sig).str(); #endif - } else + } else { return "died abnormally"; - } else + } + } else { return "succeeded"; + } } bool statusOk(int status) { @@ -1227,11 +1273,13 @@ std::string toLower(const std::string& s) { std::string shellEscape(const std::string& s) { std::string r = "'"; - for (auto& i : s) - if (i == '\'') + for (auto& i : s) { + if (i == '\'') { r += "'\\''"; - else + } else { r += i; + } + } r += '\''; return r; } @@ -1259,9 +1307,13 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll, if (i != s.end() && *i == '[') { e += *i++; // eat parameter bytes - while (i != s.end() && *i >= 0x30 && *i <= 0x3f) e += *i++; + while (i != s.end() && *i >= 0x30 && *i <= 0x3f) { + e += *i++; + } // eat intermediate bytes - while (i != s.end() && *i >= 0x20 && *i <= 0x2f) e += *i++; + while (i != s.end() && *i >= 0x20 && *i <= 0x2f) { + e += *i++; + } // eat final byte if (i != s.end() && *i >= 0x40 && *i <= 0x7e) { e += last = *i++; @@ -1287,11 +1339,11 @@ std::string filterANSIEscapes(const std::string& s, bool filterAll, } } - else if (*i == '\r') + else if (*i == '\r') { // do nothing for now i++; - else { + } else { t += *i++; w++; } @@ -1319,7 +1371,9 @@ string base64Encode(const string& s) { if (nbits) { res.push_back(base64Chars[data << (6 - nbits) & 0x3f]); } - while (res.size() % 4) res.push_back('='); + while (res.size() % 4) { + res.push_back('='); + } return res; } @@ -1395,10 +1449,10 @@ static void signalHandlerThread(sigset_t set) { int signal = 0; sigwait(&set, &signal); - if (signal == SIGINT || signal == SIGTERM || signal == SIGHUP) + if (signal == SIGINT || signal == SIGTERM || signal == SIGHUP) { triggerInterrupt(); - else if (signal == SIGWINCH) { + } else if (signal == SIGWINCH) { updateWindowSize(); } } @@ -1424,8 +1478,9 @@ static sigset_t savedSignalMask; void startSignalHandlerThread() { updateWindowSize(); - if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask)) + if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask)) { throw SysError("quering signal mask"); + } sigset_t set; sigemptyset(&set); @@ -1434,15 +1489,17 @@ void startSignalHandlerThread() { sigaddset(&set, SIGHUP); sigaddset(&set, SIGPIPE); sigaddset(&set, SIGWINCH); - if (pthread_sigmask(SIG_BLOCK, &set, nullptr)) + if (pthread_sigmask(SIG_BLOCK, &set, nullptr)) { throw SysError("blocking signals"); + } std::thread(signalHandlerThread, set).detach(); } void restoreSignals() { - if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) + if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) { throw SysError("restoring signals"); + } } /* RAII helper to automatically deregister a callback. */ diff --git a/third_party/nix/src/libutil/xml-writer.cc b/third_party/nix/src/libutil/xml-writer.cc index e07dd92f021e..ed41286cc1a3 100644 --- a/third_party/nix/src/libutil/xml-writer.cc +++ b/third_party/nix/src/libutil/xml-writer.cc @@ -16,7 +16,9 @@ void XMLWriter::close() { if (closed) { return; } - while (!pendingElems.empty()) closeElement(); + while (!pendingElems.empty()) { + closeElement(); + } closed = true; } @@ -68,20 +70,21 @@ void XMLWriter::writeAttrs(const XMLAttrs& attrs) { output << " " << i.first << "=\""; for (size_t j = 0; j < i.second.size(); ++j) { char c = i.second[j]; - if (c == '"') + if (c == '"') { output << """; - else if (c == '<') + } else if (c == '<') { output << "<"; - else if (c == '>') + } else if (c == '>') { output << ">"; - else if (c == '&') + } else if (c == '&') { output << "&"; - /* Escape newlines to prevent attribute normalisation (see - XML spec, section 3.3.3. */ - else if (c == '\n') + /* Escape newlines to prevent attribute normalisation (see + XML spec, section 3.3.3. */ + } else if (c == '\n') { output << "
"; - else + } else { output << c; + } } output << "\""; } |