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

Commit 4ddfbd2

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 bfac42e commit 4ddfbd2

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
@@ -6839,7 +6839,7 @@ trim_array(PG_FUNCTION_ARGS)
68396839
{
68406840
ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
68416841
int n = PG_GETARG_INT32(1);
6842-
int array_length = ARR_DIMS(v)[0];
6842+
int array_length = (ARR_NDIM(v) > 0) ? ARR_DIMS(v)[0] : 0;
68436843
int16 elmlen;
68446844
bool elmbyval;
68456845
char elmalign;
@@ -6859,8 +6859,11 @@ trim_array(PG_FUNCTION_ARGS)
68596859
/* Set all the bounds as unprovided except the first upper bound */
68606860
memset(lowerProvided, false, sizeof(lowerProvided));
68616861
memset(upperProvided, false, sizeof(upperProvided));
6862-
upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6863-
upperProvided[0] = true;
6862+
if (ARR_NDIM(v) > 0)
6863+
{
6864+
upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6865+
upperProvided[0] = true;
6866+
}
68646867

68656868
/* Fetch the needed information about the element type */
68666869
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)