Skip to content

Commit fe0e1a6

Browse files
committed
Fix PQsetvalue() to avoid possible crash when adding a new tuple.
PQsetvalue unnecessarily duplicated the logic in pqAddTuple, and didn't duplicate it exactly either --- pqAddTuple does not care what is in the tuple-pointer array positions beyond the last valid entry, whereas the code in PQsetvalue assumed such positions would contain NULL. This led to possible crashes if PQsetvalue was applied to a PGresult that had previously been enlarged with pqAddTuple, for instance one built from a server query. Fix by relying on pqAddTuple instead of duplicating logic, and not assuming anything about the contents of res->tuples[res->ntups]. Back-patch to 8.4, where PQsetvalue was introduced. Andrew Chernow
1 parent 431b7b8 commit fe0e1a6

File tree

1 file changed

+4
-23
lines changed

1 file changed

+4
-23
lines changed

src/interfaces/libpq/fe-exec.c

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -422,28 +422,8 @@ PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
422422
if (tup_num < 0 || tup_num > res->ntups)
423423
return FALSE;
424424

425-
/* need to grow the tuple table? */
426-
if (res->ntups >= res->tupArrSize)
427-
{
428-
int n = res->tupArrSize ? res->tupArrSize * 2 : 128;
429-
PGresAttValue **tups;
430-
431-
if (res->tuples)
432-
tups = (PGresAttValue **) realloc(res->tuples, n * sizeof(PGresAttValue *));
433-
else
434-
tups = (PGresAttValue **) malloc(n * sizeof(PGresAttValue *));
435-
436-
if (!tups)
437-
return FALSE;
438-
439-
memset(tups + res->tupArrSize, 0,
440-
(n - res->tupArrSize) * sizeof(PGresAttValue *));
441-
res->tuples = tups;
442-
res->tupArrSize = n;
443-
}
444-
445425
/* need to allocate a new tuple? */
446-
if (tup_num == res->ntups && !res->tuples[tup_num])
426+
if (tup_num == res->ntups)
447427
{
448428
PGresAttValue *tup;
449429
int i;
@@ -462,8 +442,9 @@ PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
462442
tup[i].value = res->null_field;
463443
}
464444

465-
res->tuples[tup_num] = tup;
466-
res->ntups++;
445+
/* add it to the array */
446+
if (!pqAddTuple(res, tup))
447+
return FALSE;
467448
}
468449

469450
attval = &res->tuples[tup_num][field_num];

0 commit comments

Comments
 (0)