Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d386b75

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 e65f949 commit d386b75

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
@@ -6685,7 +6685,7 @@ trim_array(PG_FUNCTION_ARGS)
66856685
{
66866686
ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
66876687
int n = PG_GETARG_INT32(1);
6688-
int array_length = ARR_DIMS(v)[0];
6688+
int array_length = (ARR_NDIM(v) > 0) ? ARR_DIMS(v)[0] : 0;
66896689
int16 elmlen;
66906690
bool elmbyval;
66916691
char elmalign;
@@ -6705,8 +6705,11 @@ trim_array(PG_FUNCTION_ARGS)
67056705
/* Set all the bounds as unprovided except the first upper bound */
67066706
memset(lowerProvided, false, sizeof(lowerProvided));
67076707
memset(upperProvided, false, sizeof(upperProvided));
6708-
upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6709-
upperProvided[0] = true;
6708+
if (ARR_NDIM(v) > 0)
6709+
{
6710+
upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6711+
upperProvided[0] = true;
6712+
}
67106713

67116714
/* Fetch the needed information about the element type */
67126715
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
@@ -2445,3 +2445,5 @@ SELECT trim_array(ARRAY[1, 2, 3], -1); -- fail
24452445
ERROR: number of elements to trim must be between 0 and 3
24462446
SELECT trim_array(ARRAY[1, 2, 3], 10); -- fail
24472447
ERROR: number of elements to trim must be between 0 and 3
2448+
SELECT trim_array(ARRAY[]::int[], 1); -- fail
2449+
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
@@ -754,3 +754,4 @@ FROM
754754

755755
SELECT trim_array(ARRAY[1, 2, 3], -1); -- fail
756756
SELECT trim_array(ARRAY[1, 2, 3], 10); -- fail
757+
SELECT trim_array(ARRAY[]::int[], 1); -- fail

0 commit comments

Comments
 (0)