Uninitialized heap memory returned by pg_event_trigger_table_rewrite_reason()

From: zengman <zengman(at)halodbtech(dot)com>
To: pgsql-hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Uninitialized heap memory returned by pg_event_trigger_table_rewrite_reason()
Date: 2026-08-18 06:27:17
Message-ID: tencent_0C511CAE082BF9D242F8C140@qq.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

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

Browse pgsql-hackers by date

  From Date Subject
Next Message Andrei Lepikhov 2026-08-18 06:31:44 Re: Allow a prosupport function to be attached to an aggregate
Previous Message Michael Paquier 2026-08-18 06:07:22 Re: [BUG] hstore integer overflow when constructing large values