Skip to content

Commit d7056bc

Browse files
committed
Avoid fetching one past the end of translate()'s "to" parameter.
This is usually harmless, but if you were very unlucky it could provoke a segfault due to the "to" string being right up against the end of memory. Found via valgrind testing (so we might've found it earlier, except that our regression tests lacked any exercise of translate()'s deletion feature). Fix by switching the order of the test-for-end-of-string and advance-pointer steps. While here, compute "to_ptr + tolen" just once. (Smarter compilers might figure that out for themselves, but let's just make sure.) Report and fix by Daniil Anisimov, in bug #17816. Discussion: https://postgr.es/m/17816-70f3d2764e88a108@postgresql.org
1 parent 6095069 commit d7056bc

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

src/backend/utils/adt/oracle_compat.c

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -801,7 +801,8 @@ translate(PG_FUNCTION_ARGS)
801801
text *to = PG_GETARG_TEXT_PP(2);
802802
text *result;
803803
char *from_ptr,
804-
*to_ptr;
804+
*to_ptr,
805+
*to_end;
805806
char *source,
806807
*target;
807808
int m,
@@ -823,6 +824,7 @@ translate(PG_FUNCTION_ARGS)
823824
from_ptr = VARDATA_ANY(from);
824825
tolen = VARSIZE_ANY_EXHDR(to);
825826
to_ptr = VARDATA_ANY(to);
827+
to_end = to_ptr + tolen;
826828

827829
/*
828830
* The worst-case expansion is to substitute a max-length character for a
@@ -857,16 +859,16 @@ translate(PG_FUNCTION_ARGS)
857859
}
858860
if (i < fromlen)
859861
{
860-
/* substitute */
862+
/* substitute, or delete if no corresponding "to" character */
861863
char *p = to_ptr;
862864

863865
for (i = 0; i < from_index; i++)
864866
{
865-
p += pg_mblen(p);
866-
if (p >= (to_ptr + tolen))
867+
if (p >= to_end)
867868
break;
869+
p += pg_mblen(p);
868870
}
869-
if (p < (to_ptr + tolen))
871+
if (p < to_end)
870872
{
871873
len = pg_mblen(p);
872874
memcpy(target, p, len);

src/test/regress/expected/strings.out

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2443,6 +2443,12 @@ SELECT translate('12345', '14', 'ax');
24432443
a23x5
24442444
(1 row)
24452445

2446+
SELECT translate('12345', '134', 'a');
2447+
translate
2448+
-----------
2449+
a25
2450+
(1 row)
2451+
24462452
SELECT ascii('x');
24472453
ascii
24482454
-------

src/test/regress/sql/strings.sql

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -787,6 +787,7 @@ SELECT ltrim('zzzytrim', 'xyz');
787787

788788
SELECT translate('', '14', 'ax');
789789
SELECT translate('12345', '14', 'ax');
790+
SELECT translate('12345', '134', 'a');
790791

791792
SELECT ascii('x');
792793
SELECT ascii('');

0 commit comments

Comments
 (0)