ScriptOpt: Ensure global statements have non-null scope

The ProfileFunc() logic assumed that GetScope() returned a non-nullptr.
This holds except for the synthetic global statements function.

Fix the latter and add an assert, also add a name to the type so it's
easier to recognize in a debugger what's going on, otherwise the name
is "".

This was found by UBSAN due to it seeing the ->OrderedVars() call on a
nullptr. Elsewhere, num_params == 0 shielded from that access and so
didn't lead to crashes.
This commit is contained in:
Arne Welzel 2024-08-16 13:59:21 +02:00
parent ec1088c3ef
commit 9d1d4e28b3
2 changed files with 4 additions and 0 deletions

View file

@ -80,6 +80,8 @@ ProfileFunc::ProfileFunc(const Expr* e, bool _abs_rec_fields) {
void ProfileFunc::Profile(const FuncType* ft, const StmtPtr& body) { void ProfileFunc::Profile(const FuncType* ft, const StmtPtr& body) {
num_params = ft->Params()->NumFields(); num_params = ft->Params()->NumFields();
assert(profiled_scope != nullptr);
auto& ov = profiled_scope->OrderedVars(); auto& ov = profiled_scope->OrderedVars();
for ( int i = 0; i < num_params; ++i ) for ( int i = 0; i < num_params; ++i )
params.insert(ov[i].get()); params.insert(ov[i].get());

View file

@ -66,12 +66,14 @@ void analyze_global_stmts(Stmt* stmts) {
auto id = install_ID("<global-stmts>", GLOBAL_MODULE_NAME, true, false); auto id = install_ID("<global-stmts>", GLOBAL_MODULE_NAME, true, false);
auto empty_args_t = make_intrusive<RecordType>(nullptr); auto empty_args_t = make_intrusive<RecordType>(nullptr);
auto func_t = make_intrusive<FuncType>(empty_args_t, nullptr, FUNC_FLAVOR_FUNCTION); auto func_t = make_intrusive<FuncType>(empty_args_t, nullptr, FUNC_FLAVOR_FUNCTION);
func_t->SetName("<global-stmts>");
id->SetType(func_t); id->SetType(func_t);
auto sc = current_scope(); auto sc = current_scope();
std::vector<IDPtr> empty_inits; std::vector<IDPtr> empty_inits;
global_stmts = make_intrusive<ScriptFunc>(id); global_stmts = make_intrusive<ScriptFunc>(id);
global_stmts->AddBody(stmts->ThisPtr(), empty_inits, sc->Length()); global_stmts->AddBody(stmts->ThisPtr(), empty_inits, sc->Length());
global_stmts->SetScope(sc);
global_stmts_ind = funcs.size(); global_stmts_ind = funcs.size();
funcs.emplace_back(global_stmts, sc, stmts->ThisPtr(), 0); funcs.emplace_back(global_stmts, sc, stmts->ThisPtr(), 0);