Fix use-after-free in jsonb_set_lax for Const NULL new_value

Commit a83586b5543 decided to scribble on the caller's fcinfo but failed
to take into account that const arguments are written once at expression
init and assumed never to change.

The use_json_null branch overwrote fcinfo->args[2] with a jsonb null
built in the per-tuple expression context.  In later rows,
args[2].isnull is still false and args[2].value still holds that
pointer, but the per-tuple context has been reset.  Later rows find
args[2].isnull = false, short-circuit past the NULL handling at the top
of the function, and jump straight to jsonb_set with the stale pointer
regardless of their own null_value_treatment argument, which is never
read.

To fix, call jsonb_set through its own call frame instead.  Arguments 0,
1 and 3 were already checked non-NULL above, so we can use
DirectFunctionCall4.

Add regression tests covering use_json_null followed by delete_key and
return_target, and a multi-row default-treatment query.

Reported-by: Evan Si <[email protected]>
Discussion: 
https://postgr.es/m/CANWCAZY-PS=ev8TiiV1j=nor2xlopel8fdq0fyqzahhip5b...@mail.gmail.com
Backpatch-through: 14

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/e355089a57d6f480cffc2820c46fcf0b5e371cf6

Modified Files
--------------
src/backend/utils/adt/jsonfuncs.c   |  8 +++++---
src/test/regress/expected/jsonb.out | 28 ++++++++++++++++++++++++++++
src/test/regress/sql/jsonb.sql      | 10 ++++++++++
3 files changed, 43 insertions(+), 3 deletions(-)

Reply via email to