Skip to content

Commit e71d425

Browse files
committed
Fix trim_array() for zero-dimensional array argument.
The code tried to access ARR_DIMS(v)[0] and ARR_LBOUND(v)[0] whether or not those values exist. This made the range check on the "n" argument unstable --- it might or might not fail, and if it did it would report garbage for the allowed upper limit. These bogus accesses would probably annoy Valgrind, and if you were very unlucky even lead to SIGSEGV. Report and fix by Martin Kalcher. Back-patch to v14 where this function was added. Discussion: https://postgr.es/m/baaeb413-b8a8-4656-5757-ef347e5ec11f@aboutsource.net
1 parent e90c4fc commit e71d425

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

src/backend/utils/adt/arrayfuncs.c

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6684,7 +6684,7 @@ trim_array(PG_FUNCTION_ARGS)
66846684
{
66856685
ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
66866686
int n = PG_GETARG_INT32(1);
6687-
int array_length = ARR_DIMS(v)[0];
6687+
int array_length = (ARR_NDIM(v) > 0) ? ARR_DIMS(v)[0] : 0;
66886688
int16 elmlen;
66896689
bool elmbyval;
66906690
char elmalign;
@@ -6704,8 +6704,11 @@ trim_array(PG_FUNCTION_ARGS)
67046704
/* Set all the bounds as unprovided except the first upper bound */
67056705
memset(lowerProvided, false, sizeof(lowerProvided));
67066706
memset(upperProvided, false, sizeof(upperProvided));
6707-
upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6708-
upperProvided[0] = true;
6707+
if (ARR_NDIM(v) > 0)
6708+
{
6709+
upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6710+
upperProvided[0] = true;
6711+
}
67096712

67106713
/* Fetch the needed information about the element type */
67116714
get_typlenbyvalalign(ARR_ELEMTYPE(v), &elmlen, &elmbyval, &elmalign);

src/test/regress/expected/arrays.out

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2432,3 +2432,5 @@ SELECT trim_array(ARRAY[1, 2, 3], -1); -- fail
24322432
ERROR: number of elements to trim must be between 0 and 3
24332433
SELECT trim_array(ARRAY[1, 2, 3], 10); -- fail
24342434
ERROR: number of elements to trim must be between 0 and 3
2435+
SELECT trim_array(ARRAY[]::int[], 1); -- fail
2436+
ERROR: number of elements to trim must be between 0 and 0

src/test/regress/sql/arrays.sql

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -737,3 +737,4 @@ FROM
737737

738738
SELECT trim_array(ARRAY[1, 2, 3], -1); -- fail
739739
SELECT trim_array(ARRAY[1, 2, 3], 10); -- fail
740+
SELECT trim_array(ARRAY[]::int[], 1); -- fail

0 commit comments

Comments
 (0)