Recently, I notice a security risk when calling a function, it's strange but also interesting. E.g.
`array_to_text_null` is a bultin function with 3 args. Normally, the function is working well. **BUT**
if we create another version `array_to_text_null` function, say `harmful_array_to_string`, but with 2 args:
```
CREATE OR REPLACE FUNCTION harmful_array_to_string(anyarray, text)
RETURNS text
LANGUAGE internal
STABLE PARALLEL SAFE STRICT
AS $function$array_to_text_null$function$;
```
And the we call the new function:
```
postgres=# SELECT harmful_array_to_string(ARRAY[1,2], 'HARMFUL');
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```
It will cause the server crash~
The reason is there is a if statement in `array_to_text_null`
```
Datum
array_to_text_null(PG_FUNCTION_ARGS)
{
...
/* NULL null string is passed through as a null pointer */
if (!PG_ARGISNULL(2))
null_string = text_to_cstring(PG_GETARG_TEXT_PP(2));
...
}
```
to determine wheather the 3rd arg is NULL or not. And we only pass 2 args to the function, but the
if statement here return TRUE, so it tries to get the 3rd arg, and cause the segmentfault.
The strange but interesting thing's here, if we change the code to:
```
Datum
array_to_text_null(PG_FUNCTION_ARGS)
{
...
/* NULL null string is passed through as a null pointer */
if (PG_ARGISNULL(2))
null_string = text_to_cstring(PG_GETARG_TEXT_PP(2));
...
}
```
Will this code work well?
NO! The if statement still return TRUE! So still cause the segmentfault.
Not only `array_to_text_null`, other functions also having such problem, like `array_prepend`, we can
create a function:
```
CREATE OR REPLACE FUNCTION harmful_array_prepend(anycompatible)
RETURNS anycompatiblearray
LANGUAGE internal
IMMUTABLE PARALLEL SAFE
AS $function$array_prepend$function$;
```
to cause the server crash easily.
This issue can be reproduction when compiled with "-O0". And when compiled with "-O2", although will not cause the server crash, but potential security risk arised as it will access an unknow memory.
A simple patch provided to prevent to access unknow args memory.
Jet