Make abort() call sites log first

This commit is contained in:
Robert Hensing 2024-07-20 22:46:09 +02:00
parent e48e0cbab0
commit 3172e88af5
35 changed files with 88 additions and 45 deletions

View File

@ -217,7 +217,7 @@ ReplExitStatus NixRepl::mainLoop()
case ProcessLineResult::PromptAgain: case ProcessLineResult::PromptAgain:
break; break;
default: default:
abort(); unreachable();
} }
} catch (ParseError & e) { } catch (ParseError & e) {
if (e.msg().find("unexpected end of file") != std::string::npos) { if (e.msg().find("unexpected end of file") != std::string::npos) {

View File

@ -134,7 +134,7 @@ std::pair<SourcePath, uint32_t> findPackageFilename(EvalState & state, Value & v
return {SourcePath{path.accessor, CanonPath(fn.substr(0, colon))}, lineno}; return {SourcePath{path.accessor, CanonPath(fn.substr(0, colon))}, lineno};
} catch (std::invalid_argument & e) { } catch (std::invalid_argument & e) {
fail(); fail();
abort(); unreachable();
} }
} }

View File

@ -149,7 +149,7 @@ std::string_view showType(ValueType type, bool withArticle)
case nFloat: return WA("a", "float"); case nFloat: return WA("a", "float");
case nThunk: return WA("a", "thunk"); case nThunk: return WA("a", "thunk");
} }
abort(); unreachable();
} }
@ -771,7 +771,7 @@ void EvalState::runDebugRepl(const Error * error, const Env & env, const Expr &
case ReplExitStatus::Continue: case ReplExitStatus::Continue:
break; break;
default: default:
abort(); unreachable();
} }
} }
} }
@ -1140,7 +1140,7 @@ inline void EvalState::evalAttrs(Env & env, Expr * e, Value & v, const PosIdx po
void Expr::eval(EvalState & state, Env & env, Value & v) void Expr::eval(EvalState & state, Env & env, Value & v)
{ {
abort(); unreachable();
} }
@ -1573,7 +1573,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
.withFrame(*fun.payload.lambda.env, lambda) .withFrame(*fun.payload.lambda.env, lambda)
.debugThrow(); .debugThrow();
} }
abort(); // can't happen unreachable();
} }
} }

View File

@ -25,7 +25,7 @@ std::ostream & operator <<(std::ostream & str, const SymbolStr & symbol)
void Expr::show(const SymbolTable & symbols, std::ostream & str) const void Expr::show(const SymbolTable & symbols, std::ostream & str) const
{ {
abort(); unreachable();
} }
void ExprInt::show(const SymbolTable & symbols, std::ostream & str) const void ExprInt::show(const SymbolTable & symbols, std::ostream & str) const
@ -271,7 +271,7 @@ std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath)
void Expr::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) void Expr::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{ {
abort(); unreachable();
} }
void ExprInt::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) void ExprInt::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)

View File

@ -426,7 +426,7 @@ static void prim_typeOf(EvalState & state, const PosIdx pos, Value * * args, Val
t = args[0]->external()->typeOf(); t = args[0]->external()->typeOf();
break; break;
case nFloat: t = "float"; break; case nFloat: t = "float"; break;
case nThunk: abort(); case nThunk: unreachable();
} }
v.mkString(t); v.mkString(t);
} }

View File

@ -94,7 +94,7 @@ void printAmbiguous(
break; break;
default: default:
printError("Nix evaluator internal error: printAmbiguous: invalid value type"); printError("Nix evaluator internal error: printAmbiguous: invalid value type");
abort(); unreachable();
} }
} }

View File

@ -475,7 +475,7 @@ private:
else else
output << "primop"; output << "primop";
} else { } else {
abort(); unreachable();
} }
output << "»"; output << "»";
@ -504,7 +504,7 @@ private:
if (options.ansiColors) if (options.ansiColors)
output << ANSI_NORMAL; output << ANSI_NORMAL;
} else { } else {
abort(); unreachable();
} }
} }

View File

@ -7,6 +7,7 @@
#include "types.hh" #include "types.hh"
#include "chunked-vector.hh" #include "chunked-vector.hh"
#include "error.hh"
namespace nix { namespace nix {
@ -113,7 +114,7 @@ public:
SymbolStr operator[](Symbol s) const SymbolStr operator[](Symbol s) const
{ {
if (s.id == 0 || s.id > store.size()) if (s.id == 0 || s.id > store.size())
abort(); unreachable();
return SymbolStr(store[s.id - 1]); return SymbolStr(store[s.id - 1]);
} }

View File

@ -285,7 +285,7 @@ public:
if (invalidIsThunk) if (invalidIsThunk)
return nThunk; return nThunk;
else else
abort(); unreachable();
} }
inline void finishValue(InternalType newType, Payload newPayload) inline void finishValue(InternalType newType, Payload newPayload)

View File

@ -33,7 +33,7 @@ nlohmann::json attrsToJSON(const Attrs & attrs)
json[attr.first] = *v; json[attr.first] = *v;
} else if (auto v = std::get_if<Explicit<bool>>(&attr.second)) { } else if (auto v = std::get_if<Explicit<bool>>(&attr.second)) {
json[attr.first] = v->t; json[attr.first] = v->t;
} else abort(); } else unreachable();
} }
return json; return json;
} }
@ -99,7 +99,7 @@ std::map<std::string, std::string> attrsToQuery(const Attrs & attrs)
query.insert_or_assign(attr.first, *v); query.insert_or_assign(attr.first, *v);
} else if (auto v = std::get_if<Explicit<bool>>(&attr.second)) { } else if (auto v = std::get_if<Explicit<bool>>(&attr.second)) {
query.insert_or_assign(attr.first, v->t ? "1" : "0"); query.insert_or_assign(attr.first, v->t ? "1" : "0");
} else abort(); } else unreachable();
} }
return query; return query;
} }

View File

@ -36,7 +36,7 @@ Logger * makeDefaultLogger() {
return logger; return logger;
} }
default: default:
abort(); unreachable();
} }
} }

View File

@ -36,7 +36,7 @@ public:
Co init() override; Co init() override;
Co realisationFetched(std::shared_ptr<const Realisation> outputInfo, nix::ref<nix::Store> sub); Co realisationFetched(std::shared_ptr<const Realisation> outputInfo, nix::ref<nix::Store> sub);
void timedOut(Error && ex) override { abort(); }; void timedOut(Error && ex) override { unreachable(); };
std::string key() override; std::string key() override;

View File

@ -400,12 +400,12 @@ public:
virtual void handleChildOutput(Descriptor fd, std::string_view data) virtual void handleChildOutput(Descriptor fd, std::string_view data)
{ {
abort(); unreachable();
} }
virtual void handleEOF(Descriptor fd) virtual void handleEOF(Descriptor fd)
{ {
abort(); unreachable();
} }
void trace(std::string_view s); void trace(std::string_view s);

View File

@ -50,7 +50,7 @@ public:
PathSubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt); PathSubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt);
~PathSubstitutionGoal(); ~PathSubstitutionGoal();
void timedOut(Error && ex) override { abort(); }; void timedOut(Error && ex) override { unreachable(); };
/** /**
* We prepend "a$" to the key name to ensure substitution goals * We prepend "a$" to the key name to ensure substitution goals

View File

@ -216,7 +216,7 @@ void Worker::childStarted(GoalPtr goal, const std::set<MuxablePipePollState::Com
nrLocalBuilds++; nrLocalBuilds++;
break; break;
default: default:
abort(); unreachable();
} }
} }
} }
@ -239,7 +239,7 @@ void Worker::childTerminated(Goal * goal, bool wakeSleepers)
nrLocalBuilds--; nrLocalBuilds--;
break; break;
default: default:
abort(); unreachable();
} }
} }

View File

@ -33,7 +33,7 @@ Sink & operator << (Sink & sink, const Logger::Fields & fields)
sink << f.i; sink << f.i;
else if (f.type == Logger::Field::tString) else if (f.type == Logger::Field::tString)
sink << f.s; sink << f.s;
else abort(); else unreachable();
} }
return sink; return sink;
} }

View File

@ -559,7 +559,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
non-blocking flag from the server socket, so non-blocking flag from the server socket, so
explicitly make it blocking. */ explicitly make it blocking. */
if (fcntl(fdClient.get(), F_SETFL, fcntl(fdClient.get(), F_GETFL) & ~O_NONBLOCK) == -1) if (fcntl(fdClient.get(), F_SETFL, fcntl(fdClient.get(), F_GETFL) & ~O_NONBLOCK) == -1)
abort(); panic("Could not set non-blocking flag on client socket");
while (true) { while (true) {
try { try {

View File

@ -297,7 +297,7 @@ template<> std::string BaseSetting<SandboxMode>::to_string() const
if (value == smEnabled) return "true"; if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed"; else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false"; else if (value == smDisabled) return "false";
else abort(); else unreachable();
} }
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category) template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)

View File

@ -164,7 +164,7 @@ public:
Cache & getCache(State & state, const std::string & uri) Cache & getCache(State & state, const std::string & uri)
{ {
auto i = state.caches.find(uri); auto i = state.caches.find(uri);
if (i == state.caches.end()) abort(); if (i == state.caches.end()) unreachable();
return i->second; return i->second;
} }
@ -211,7 +211,7 @@ public:
{ {
auto r(state->insertCache.use()(uri)(time(0))(storeDir)(wantMassQuery)(priority)); auto r(state->insertCache.use()(uri)(time(0))(storeDir)(wantMassQuery)(priority));
if (!r.next()) { abort(); } if (!r.next()) { unreachable(); }
ret.id = (int) r.getInt(0); ret.id = (int) r.getInt(0);
} }

View File

@ -165,7 +165,7 @@ void LocalDerivationGoal::killSandbox(bool getStats)
buildResult.cpuSystem = stats.cpuSystem; buildResult.cpuSystem = stats.cpuSystem;
} }
#else #else
abort(); unreachable();
#endif #endif
} }

View File

@ -45,7 +45,7 @@ bool lockFile(Descriptor desc, LockType lockType, bool wait)
if (lockType == ltRead) type = LOCK_SH; if (lockType == ltRead) type = LOCK_SH;
else if (lockType == ltWrite) type = LOCK_EX; else if (lockType == ltWrite) type = LOCK_EX;
else if (lockType == ltNone) type = LOCK_UN; else if (lockType == ltNone) type = LOCK_UN;
else abort(); else unreachable();
if (wait) { if (wait) {
while (flock(desc, type) != 0) { while (flock(desc, type) != 0) {

View File

@ -6,6 +6,8 @@
#include <vector> #include <vector>
#include <limits> #include <limits>
#include "error.hh"
namespace nix { namespace nix {
/** /**
@ -30,7 +32,7 @@ private:
auto & addChunk() auto & addChunk()
{ {
if (size_ >= std::numeric_limits<uint32_t>::max() - ChunkSize) if (size_ >= std::numeric_limits<uint32_t>::max() - ChunkSize)
abort(); unreachable();
chunks.emplace_back(); chunks.emplace_back();
chunks.back().reserve(ChunkSize); chunks.back().reserve(ChunkSize);
return chunks.back(); return chunks.back();

View File

@ -430,4 +430,16 @@ std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool s
return out; return out;
} }
void panic(std::string_view msg)
{
printError(msg);
printError("This was a fatal error, aborting.");
abort();
}
void panic(const char * file, int line, const char * func)
{
panic(std::string("Unexpected condition in ") + func + " at " + file + ":" + std::to_string(line));
}
} }

View File

@ -273,4 +273,28 @@ using NativeSysError =
*/ */
void throwExceptionSelfCheck(); void throwExceptionSelfCheck();
/**
* Print a message and abort().
*
* @note: This assumes that the logger is operational
*/
[[noreturn]]
void panic(std::string_view msg);
/**
* Print a basic error message with source position and abort().
* Use the unreachable macro to call this.
*
* @note: This assumes that the logger is operational
*/
[[noreturn]]
void panic(const char * file, int line, const char * func);
/**
* Print a basic error message with source position and abort().
*
* @note: This assumes that the logger is operational
*/
#define unreachable() (panic(__FILE__, __LINE__, __func__))
} }

View File

@ -63,7 +63,7 @@ std::string_view renderFileIngestionMethod(FileIngestionMethod method)
case FileIngestionMethod::Git: case FileIngestionMethod::Git:
return "git"; return "git";
default: default:
abort(); unreachable();
} }
} }

View File

@ -53,7 +53,7 @@ void copyRecursive(
throw Error("file '%1%' has an unsupported type", from); throw Error("file '%1%' has an unsupported type", from);
default: default:
abort(); unreachable();
} }
} }

View File

@ -201,7 +201,7 @@ std::optional<Mode> convertMode(SourceAccessor::Type type)
case SourceAccessor::tRegular: return Mode::Regular; case SourceAccessor::tRegular: return Mode::Regular;
case SourceAccessor::tDirectory: return Mode::Directory; case SourceAccessor::tDirectory: return Mode::Directory;
case SourceAccessor::tMisc: return std::nullopt; case SourceAccessor::tMisc: return std::nullopt;
default: abort(); default: unreachable();
} }
} }

View File

@ -25,7 +25,7 @@ static size_t regularHashSize(HashAlgorithm type) {
case HashAlgorithm::SHA256: return sha256HashSize; case HashAlgorithm::SHA256: return sha256HashSize;
case HashAlgorithm::SHA512: return sha512HashSize; case HashAlgorithm::SHA512: return sha512HashSize;
} }
abort(); unreachable();
} }

View File

@ -189,7 +189,7 @@ struct JSONLogger : Logger {
else if (f.type == Logger::Field::tString) else if (f.type == Logger::Field::tString)
arr.push_back(f.s); arr.push_back(f.s);
else else
abort(); unreachable();
} }
void write(const nlohmann::json & json) void write(const nlohmann::json & json)

View File

@ -260,7 +260,7 @@ std::unique_ptr<FinishSink> sourceToSink(std::function<void(Source &)> fun)
}); });
} }
if (!*coro) { abort(); } if (!*coro) { unreachable(); }
if (!cur.empty()) { if (!cur.empty()) {
CoroutineContext ctx; CoroutineContext ctx;
@ -271,12 +271,12 @@ std::unique_ptr<FinishSink> sourceToSink(std::function<void(Source &)> fun)
void finish() override void finish() override
{ {
if (!coro) return; if (!coro) return;
if (!*coro) abort(); if (!*coro) unreachable();
{ {
CoroutineContext ctx; CoroutineContext ctx;
(*coro)(true); (*coro)(true);
} }
if (*coro) abort(); if (*coro) unreachable();
} }
}; };
@ -316,7 +316,7 @@ std::unique_ptr<Source> sinkToSource(
}); });
} }
if (!*coro) { eof(); abort(); } if (!*coro) { eof(); unreachable(); }
if (pos == cur.size()) { if (pos == cur.size()) {
if (!cur.empty()) { if (!cur.empty()) {

View File

@ -7,6 +7,8 @@
#include <condition_variable> #include <condition_variable>
#include <cassert> #include <cassert>
#include "error.hh"
namespace nix { namespace nix {
/** /**
@ -47,7 +49,7 @@ public:
friend SyncBase; friend SyncBase;
Lock(SyncBase * s) : s(s), lk(s->mutex) { } Lock(SyncBase * s) : s(s), lk(s->mutex) { }
public: public:
Lock(Lock && l) : s(l.s) { abort(); } Lock(Lock && l) : s(l.s) { unreachable(); }
Lock(const Lock & l) = delete; Lock(const Lock & l) = delete;
~Lock() { } ~Lock() { }

View File

@ -40,7 +40,9 @@ public:
#endif #endif
; ;
auto count = poll(fds, 1, -1); auto count = poll(fds, 1, -1);
if (count == -1) abort(); // can't happen if (count == -1)
unreachable();
/* This shouldn't happen, but can on macOS due to a bug. /* This shouldn't happen, but can on macOS due to a bug.
See rdar://37550628. See rdar://37550628.

View File

@ -182,7 +182,7 @@ static pid_t doFork(bool allowVfork, ChildWrapperFunction & fun)
#endif #endif
if (pid != 0) return pid; if (pid != 0) return pid;
fun(); fun();
abort(); unreachable();
} }

View File

@ -1159,7 +1159,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
case cvEqual: ch = '='; break; case cvEqual: ch = '='; break;
case cvGreater: ch = '<'; break; case cvGreater: ch = '<'; break;
case cvUnavail: ch = '-'; break; case cvUnavail: ch = '-'; break;
default: abort(); default: unreachable();
} }
if (xmlOutput) { if (xmlOutput) {

View File

@ -480,7 +480,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
} }
default: default:
abort(); unreachable();
} }
} }