Hi all,

While testing event triggers on PostgreSQL 20devel, I found that 
pg_event_trigger_table_rewrite_reason() may return
uninitialized heap memory. The cause appears to be that 
EventTriggerBeginCompleteQuery() allocates EventTriggerQueryState
with MemoryContextAlloc() and then initializes the fields one by one, but 
misses table_rewrite_reason.

Test SQL:

```sql
CREATE FUNCTION cb() RETURNS event_trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'ddl_command_end context: reason=%', 
pg_event_trigger_table_rewrite_reason();
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'ddl_command_end context: correctly rejected (%)', SQLERRM;
END $$;
CREATE EVENT TRIGGER et_cb ON ddl_command_end EXECUTE FUNCTION cb();
CREATE TABLE tt1(a int);    -- <-- bug fires here
DROP EVENT TRIGGER et_cb; DROP FUNCTION cb; DROP TABLE tt1;
```

Test output:

```
psql (20devel)
Type "help" for help.

postgres=# CREATE FUNCTION cb() RETURNS event_trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'ddl_command_end context: reason=%', 
pg_event_trigger_table_rewrite_reason();
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'ddl_command_end context: correctly rejected (%)', SQLERRM;
END $$;
CREATE FUNCTION
postgres=# CREATE EVENT TRIGGER et_cb ON ddl_command_end EXECUTE FUNCTION cb();
CREATE EVENT TRIGGER
postgres=# CREATE TABLE tt1(a int);    -- <-- bug fires here
NOTICE:  ddl_command_end context: reason=2139062143
CREATE TABLE
```

A one-line initialization fix could be considered:

```diff
diff --git a/src/backend/commands/event_trigger.c 
b/src/backend/commands/event_trigger.c
index adc6eabc0f4..306449e823f 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -1211,6 +1211,7 @@ EventTriggerBeginCompleteQuery(void)
        slist_init(&(state->SQLDropList));
        state->in_sql_drop = false;
        state->table_rewrite_oid = InvalidOid;
+       state->table_rewrite_reason = 0;
 
        state->commandCollectionInhibited = currentEventTriggerState ?
                currentEventTriggerState->commandCollectionInhibited : false;
```

Thoughts?

--
Regards,
Man Zeng

Reply via email to