[PATCH] Fix segmentation fault and infinite loop in jsonb_{plperl,plpython}

Aleksander Alekseev <aleksander@tigerdata.com>

From: Aleksander Alekseev <aleksander@tigerdata.com>
To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>
Date: 2026-06-16T14:05:20Z
Lists: pgsql-hackers

Attachments

Hi,

I discovered several bugs in jsonb_plperl and jsonb_plpython.

The first bug causes a segfault when dealing with deeply nested JSONB
values. As an example:

```
$ ./reproduce_stack_overflow.py
plpython3u (depth=100000): SIGSEGV
  2026-06-16 16:42:56.989 MSK [3209763] LOG:  client backend (PID
3209810) was terminated by signal 11: Segmentation fault
  2026-06-16 16:42:56.989 MSK [3209763] DETAIL:  Failed process was
running: SELECT py_deep(100000);
plperl     (depth=100000): SIGSEGV
  2026-06-16 16:42:59.101 MSK [3209763] LOG:  client backend (PID
3209827) was terminated by signal 11: Segmentation fault
  2026-06-16 16:42:59.101 MSK [3209763] DETAIL:  Failed process was
running: SELECT perl_deep(100000);
```

The second bug affects only jsonb_plperl. It's possible to construct a
Perl object with circular references which will cause
SV_to_JsonbValue() to go into an infinite loop here:

```
    while (SvROK(in))
        in = SvRV(in);
```

The attached script reproduce_circular_ref.py reproduces the issue. Be
careful if you decide to run it because the backend will become
unresponsive to pg_cancel_backend() and you will be unable to stop the
cluster in a standard way.

I suggest fixing it by rewriting the while loop into a recursion with
check_stack_depth() call. This will make the behavior consistent with
jsonb_plpython.

Patches are attached. Thoughts?

-- 
Best regards,
Aleksander Alekseev

Commits

  1. hstore_plperl: Add CHECK_FOR_INTERRUPTS() in reference-unwinding loop.

  2. jsonb_plperl, jsonb_plpython: Fix unguarded recursion and loops.