Skip to content

Commit 7f69ed4

Browse files
committed
pg_trgm: fix crash in 2-item picksplit
Whether from size overflow in gistSplit or from secondary splits, picksplit is (rarely) called with exactly two items to split. Formerly, due to special-case handling of the last item, this would lead to access to an uninitialized cache entry; prior to PG 13 this might have been harmless or at worst led to an incorrect union datum, but in 13 onwards it can cause a backend crash from using an uninitialized pointer. Repair by removing the special case, which was deemed not to have been appropriate anyway. Backpatch all the way, because this bug has existed since pg_trgm was added. Per report on IRC from user "ftzdomino". Analysis and testing by me, patch from Alexander Korotkov. Discussion: https://postgr.es/m/87k0usfdxg.fsf@news-spur.riddles.org.uk
1 parent 0d0626e commit 7f69ed4

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

contrib/pg_trgm/trgm_gist.c

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -760,7 +760,7 @@ Datum
760760
gtrgm_picksplit(PG_FUNCTION_ARGS)
761761
{
762762
GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
763-
OffsetNumber maxoff = entryvec->n - 2;
763+
OffsetNumber maxoff = entryvec->n - 1;
764764
GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
765765
OffsetNumber k,
766766
j;
@@ -783,7 +783,7 @@ gtrgm_picksplit(PG_FUNCTION_ARGS)
783783
SPLITCOST *costvector;
784784

785785
/* cache the sign data for each existing item */
786-
cache = (CACHESIGN *) palloc(sizeof(CACHESIGN) * (maxoff + 2));
786+
cache = (CACHESIGN *) palloc(sizeof(CACHESIGN) * (maxoff + 1));
787787
for (k = FirstOffsetNumber; k <= maxoff; k = OffsetNumberNext(k))
788788
fillcache(&cache[k], GETENTRY(entryvec, k));
789789

@@ -810,7 +810,7 @@ gtrgm_picksplit(PG_FUNCTION_ARGS)
810810
}
811811

812812
/* initialize the result vectors */
813-
nbytes = (maxoff + 2) * sizeof(OffsetNumber);
813+
nbytes = maxoff * sizeof(OffsetNumber);
814814
v->spl_left = left = (OffsetNumber *) palloc(nbytes);
815815
v->spl_right = right = (OffsetNumber *) palloc(nbytes);
816816
v->spl_nleft = 0;
@@ -846,8 +846,7 @@ gtrgm_picksplit(PG_FUNCTION_ARGS)
846846

847847
union_l = GETSIGN(datum_l);
848848
union_r = GETSIGN(datum_r);
849-
maxoff = OffsetNumberNext(maxoff);
850-
fillcache(&cache[maxoff], GETENTRY(entryvec, maxoff));
849+
851850
/* sort before ... */
852851
costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
853852
for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
@@ -933,7 +932,6 @@ gtrgm_picksplit(PG_FUNCTION_ARGS)
933932
}
934933
}
935934

936-
*right = *left = FirstOffsetNumber;
937935
v->spl_ldatum = PointerGetDatum(datum_l);
938936
v->spl_rdatum = PointerGetDatum(datum_r);
939937

0 commit comments

Comments
 (0)