Do not allow defining labels outside sections (#2013)

Creating a `Symbol` with `type = SYM_LABEL` but `section = nullptr`
is inconsistent and dangerous. I was not able to cause any buggy
behavior so far, but it's safer and reasonable to not create such
a symbol in the first place.

The main consequence is that `DEF(LabelOutsideSection)` will now
evaluate as 0.
This commit is contained in:
Rangi
2026-07-06 16:18:42 -04:00
committed by GitHub
parent 46a6966b70
commit fe3b238dea
12 changed files with 24 additions and 19 deletions
+2 -2
View File
@@ -227,9 +227,9 @@ static int32_t tryConstMask(Expression const &lhs, Expression const &rhs) {
return -1;
}
assume(sym.isNumeric());
assume(sym.type == SYM_LABEL);
// We can now safely use `expr.value()` and `sym.getSection()`
// We can now safely use `expr.value()`
int32_t mask = expr.value();
// The mask must not cover any unknown bits
+8 -5
View File
@@ -537,6 +537,12 @@ Symbol *sym_AddVar(InternedStr symName, int32_t value) {
static Symbol *addLabel(InternedStr symName) {
assumeAlreadyExpanded(symName);
Section *section = sect_GetSymbolSection();
if (!section) {
error("Cannot define label `%s` outside of a `SECTION`", symName.c_str());
return nullptr;
}
Symbol *sym = sym_FindExactSymbol(symName);
if (!sym) {
@@ -547,6 +553,7 @@ static Symbol *addLabel(InternedStr symName) {
} else {
updateSymbolFilename(*sym);
}
// If the symbol already exists as a ref, just "take over" it
sym->type = SYM_LABEL;
sym->data = static_cast<int32_t>(sect_GetSymbolOffset());
@@ -554,11 +561,7 @@ static Symbol *addLabel(InternedStr symName) {
if (options.exportAll && !symName.str().starts_with('!')) {
sym->isExported = true;
}
sym->section = sect_GetSymbolSection();
if (sym && !sym->section) {
error("Label `%s` created outside of a `SECTION`", symName.c_str());
}
sym->section = section;
return sym;
}