pg.ddx.io pgsql-bugs@postgresql.org mailing list archive
help / color / mirror / Atom feedPQexec() hangs on OOM
48+ messages / 6 participants
[nested] [flat]
* PQexec() hangs on OOM
@ 2014-11-25 13:15 Heikki Linnakangas <hlinnakangas@vmware.com>
0 siblings, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2014-11-25 13:15 UTC (permalink / raw)
To: pgsql-bugs
Alex Shulgin's find of a missing NULL check after strdup()
(87tx1or3cc.fsf@commandprompt.com) prompted me to do some testing of
libpq, when malloc/strdup returns NULL. To simulate running out of
memory, I wrote a little LD_PRELOAD library that allows causing malloc()
to return NULL, after a particular number of calls. and ran
src/test/examples/testlibpq with that hack.
After fixing all the missing NULL-checks, I found that testlibpq
sometimes just hangs. It happens when this malloc() call in
PQmakeEmptyPGResult() fails:
#3 0x00007f6dc86495c0 in malloc () from /home/heikki/mallocfail.so
#4 0x00007f6dc8423b6e in PQmakeEmptyPGresult (conn=0x1bea040,
status=PGRES_COMMAND_OK) at fe-exec.c:144
#5 0x00007f6dc8430b27 in pqParseInput3 (conn=0x1bea040) at
fe-protocol3.c:204
#6 0x00007f6dc8426468 in parseInput (conn=0x1bea040) at fe-exec.c:1652
#7 0x00007f6dc8426583 in PQgetResult (conn=0x1bea040) at fe-exec.c:1727
#8 0x00007f6dc8426c76 in PQexecFinish (conn=0x1bea040) at fe-exec.c:2000
#9 0x00007f6dc84268ad in PQexec (conn=0x1bea040, query=0x400e32
"BEGIN") at fe-exec.c:1834
#10 0x0000000000400b18 in main (argc=1, argv=0x7fffc9b6a568) at
testlibpq.c:59
When that malloc() returns NULL, parseInput returns without reading any
input. PQgetResult() takes that as a sign that it needs to read more
input from the server, before calling parseInput() again, and that read
never returns because there is no more data coming from the server.
I don't have any immediate plans to fix this, or to continue testing
this. There might well be more cases like this. Patches are welcome.
Attached is the little wrapper library I used to test this. testlibpq
hangs when run with MALLOC_FAIL_AT=110. It's really quick & dirty, sorry
about that. I'm sure there are more sophisticated tools to do similar
testing out there somewhere..
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
mallocfail.c (text/x-csrc, 971B) download
/*
* To compile:
* gcc mallocfail.c -c -fPIC
* ld -ldl mallocfail.o -o mallocfail.so -shared
*
* To run:
* MALLOC_FAIL_AT=110 LD_PRELOAD=mallocfail.so ./testlibpq
*/
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <unistd.h>
static int counter = 0;
static int fail_at = -1;
void dump_core(void)
{
if (!fork())
abort();
}
void *(*orig_malloc)(size_t size);
void *malloc(size_t size)
{
counter++;
if (counter % 10 == 0)
printf("malloc called: %d!\n", counter);
if (counter == fail_at)
{
printf("malloc failing: %d!\n", counter);
create_dump();
return NULL;
}
return orig_malloc(size);
}
void
_init(void)
{
char *fail_at_str = getenv("MALLOC_FAIL_AT");
if (!fail_at_str)
printf("FAIL_AT not set!\n");
else
{
fail_at = atoi(fail_at_str);
printf("FAIL_AT: %d\n", fail_at);
}
printf("loading malloc imposter.\n");
orig_malloc = dlsym(RTLD_NEXT, "malloc");
}
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-06 06:54 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnakangas@vmware.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-04-06 06:54 UTC (permalink / raw)
To: hlinnaka@iki.fi; +Cc: pgsql-bugs
On Tue, Nov 25, 2014 at 10:15 PM, Heikki Linnakangas wrote:
> When that malloc() returns NULL, parseInput returns without reading any
> input. PQgetResult() takes that as a sign that it needs to read more input
> from the server, before calling parseInput() again, and that read never
> returns because there is no more data coming from the server.
>
> I don't have any immediate plans to fix this, or to continue testing this.
> There might well be more cases like this. Patches are welcome.
>
> Attached is the little wrapper library I used to test this. testlibpq
hangs
> when run with MALLOC_FAIL_AT=110. It's really quick & dirty, sorry about
> that. I'm sure there are more sophisticated tools to do similar testing
out
> there somewhere..
With MALLOC_FAIL_AT=84, 86, 92, the backtrace just before the malloc
creating the OOM looks like that:
#0 0x00007f76316964d0 in __poll_nocancel () from /usr/lib/libc.so.6
#1 0x00007f7631971577 in pqSocketPoll (sock=4, forRead=1, forWrite=0,
end_time=-1) at fe-misc.c:1133
#2 0x00007f7631971461 in pqSocketCheck (conn=0x1495040, forRead=1,
forWrite=0, end_time=-1) at fe-misc.c:1075
#3 0x00007f76319712f8 in pqWaitTimed (forRead=1, forWrite=0,
conn=0x1495040, finish_time=-1) at fe-misc.c:1007
#4 0x00007f76319712ca in pqWait (forRead=1, forWrite=0, conn=0x1495040) at
fe-misc.c:990
#5 0x00007f763196d21d in PQgetResult (conn=0x1495040) at fe-exec.c:1711
#6 0x00007f763196d913 in PQexecFinish (conn=0x1495040) at fe-exec.c:1997
#7 0x00007f763196d576 in PQexec (conn=0x1495040, query=0x400ef2 "BEGIN")
at fe-exec.c:1831
#8 0x0000000000400bd8 in main (argc=1, argv=0x7ffd8a2644c8) at
testlibpq.c:5
In this case, as what happens is an OOM related to the allocation of
PGResult, I think that we had better store a status flag in PGConn related
to this OOM, as PGConn->errorMessage may not be empty to take care of the
ambiguity that PGResult == NULL does not necessarily mean wait for more
results. Something like PGResultStatus to avoid any API incompatibility.
Thoughts?
Looking at the other malloc() calls of llibpq, we do not really have this
ambiguity. For example if makeEmptyPGconn() == NULL means OOM. I am
guessing from the code as well that PQmakeEmptyPGresult() == NULL means
OOM, so the error handling problem comes from parseInput and its underlings.
Also in pqSaveParameterStatus, shouldn't we have a better OOM handling
there as well for pstatus?
Regards,
--
Michael
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-06 06:59 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-04-06 06:59 UTC (permalink / raw)
To: hlinnaka@iki.fi; +Cc: pgsql-bugs
On Mon, Apr 6, 2015 at 3:54 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
> In this case, as what happens is an OOM related to the allocation of
> PGResult, I think that we had better store a status flag in PGConn related
> to this OOM, as PGConn->errorMessage may not be empty to take care of the
> ambiguity that PGResult == NULL does not necessarily mean wait for more
> results. Something like PGResultStatus to avoid any API incompatibility.
> Thoughts?
>
Second idea: return a status with parseInput as it is not part of the APIs
of libpq.
--
Michael
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-06 13:46 Tom Lane <tgl@sss.pgh.pa.us>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Tom Lane @ 2015-04-06 13:46 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: pgsql-bugs
Michael Paquier <michael.paquier@gmail.com> writes:
> Second idea: return a status with parseInput as it is not part of the APIs
> of libpq.
Yeah; most subroutines in libpq have a zero-or-EOF return convention,
we can make parseInput do likewise. I'm not sure if that'd need to
propagate further down though ...
regards, tom lane
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-07 06:18 Michael Paquier <michael.paquier@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-04-07 06:18 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-bugs
On Mon, Apr 6, 2015 at 10:46 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Michael Paquier <michael.paquier@gmail.com> writes:
>> Second idea: return a status with parseInput as it is not part of the APIs
>> of libpq.
>
> Yeah; most subroutines in libpq have a zero-or-EOF return convention,
> we can make parseInput do likewise. I'm not sure if that'd need to
> propagate further down though ...
So, I have been looking at that in more details, and finished with the
patch attached that makes the problem go away for me with a nice "out
of memory" error. I have extended parseInput() to have it return a
status code to decide if parsing should be stopped or should continue.
Note that I have tried to be careful to make a clear distinction
between cases where routines return EOF because of not enough data
parsed and actual OOMs.
I have noticed as well that getCopyStart() in fe-protocol3.c needs to
be made a little bit smarter to make the difference between an OOM and
the not-enough-data type of problem.
This problem has a low probability to happen in the field, and no
people complained about that as well, so I think that patching only
HEAD is adapted.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
0001-Improve-OOM-detection-of-parseInput-in-libpq.patch (text/x-patch, 19.2K) download
From c2156c46ea0a35c74c54449f073b9b78adac0355 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Tue, 7 Apr 2015 15:07:45 +0000
Subject: [PATCH] Improve OOM detection of parseInput in libpq
An OOM occurring at the beginning of parseInput() when called at the
beginning of pqGetResult could result in libpq hanging indefinitely.
The probability to face this case is rather low, but let's make the
OOM error handling of parseInput more robust in this area. getCopyStart()
has been made a bit smarter to make the difference between an OOM, meaning
that input parsing should be immediately stopped, and cases where there is
not enough data, meaning that parsing should continue.
---
src/interfaces/libpq/fe-exec.c | 33 +++++++---
src/interfaces/libpq/fe-protocol2.c | 47 ++++++++------
src/interfaces/libpq/fe-protocol3.c | 123 ++++++++++++++++++++++++------------
src/interfaces/libpq/libpq-int.h | 4 +-
4 files changed, 134 insertions(+), 73 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..f979d4f 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -62,7 +62,7 @@ static int PQsendQueryGuts(PGconn *conn,
const int *paramLengths,
const int *paramFormats,
int resultFormat);
-static void parseInput(PGconn *conn);
+static int parseInput(PGconn *conn);
static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
static bool PQexecStart(PGconn *conn);
static PGresult *PQexecFinish(PGconn *conn);
@@ -143,7 +143,11 @@ PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
result = (PGresult *) malloc(sizeof(PGresult));
if (!result)
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
return NULL;
+ }
result->ntups = 0;
result->numAttributes = 0;
@@ -194,6 +198,8 @@ PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
if (!result->events)
{
PQclear(result);
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
return NULL;
}
result->nEvents = conn->nEvents;
@@ -1573,7 +1579,7 @@ pqHandleSendFailure(PGconn *conn)
* Parse any available input messages. Since we are in PGASYNC_IDLE
* state, only NOTICE and NOTIFY messages will be eaten.
*/
- parseInput(conn);
+ (void) parseInput(conn);
}
/*
@@ -1641,14 +1647,16 @@ PQconsumeInput(PGconn *conn)
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF an error should occur.
*/
-static void
+static int
parseInput(PGconn *conn)
{
if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
- pqParseInput3(conn);
+ return pqParseInput3(conn);
else
- pqParseInput2(conn);
+ return pqParseInput2(conn);
}
/*
@@ -1663,7 +1671,8 @@ PQisBusy(PGconn *conn)
return FALSE;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return FALSE;
/* PQgetResult will return immediately in all states except BUSY. */
return conn->asyncStatus == PGASYNC_BUSY;
@@ -1686,7 +1695,8 @@ PQgetResult(PGconn *conn)
return NULL;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
/* If not ready to return something, block until we are. */
while (conn->asyncStatus == PGASYNC_BUSY)
@@ -1721,7 +1731,8 @@ PQgetResult(PGconn *conn)
}
/* Parse it. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
}
/* Return the appropriate thing. */
@@ -2177,7 +2188,8 @@ PQnotifies(PGconn *conn)
return NULL;
/* Parse any available data to see if we can extract NOTIFY messages. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
event = conn->notifyHead;
if (event)
@@ -2217,7 +2229,8 @@ PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
* input data into the input buffer happens down inside pqSendSome, but
* it's not authorized to get rid of the data again.)
*/
- parseInput(conn);
+ if (parseInput(conn))
+ return -1;
if (nbytes > 0)
{
diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
index eeba7f3..aaa1905 100644
--- a/src/interfaces/libpq/fe-protocol2.c
+++ b/src/interfaces/libpq/fe-protocol2.c
@@ -406,8 +406,10 @@ error_return:
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if successfully parsed input.
+ * returns EOF an error should occur.
*/
-void
+int
pqParseInput2(PGconn *conn)
{
char id;
@@ -424,14 +426,14 @@ pqParseInput2(PGconn *conn)
* protocol and have identifying leading characters.)
*/
if (conn->asyncStatus == PGASYNC_COPY_OUT)
- return;
+ return 0;
/*
* OK to try to read a message type code.
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
/*
* NOTIFY and NOTICE messages can happen in any state besides COPY
@@ -447,18 +449,18 @@ pqParseInput2(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
if (pqGetErrorNotice2(conn, false))
- return;
+ return 0;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -471,7 +473,7 @@ pqParseInput2(PGconn *conn)
if (id == 'E')
{
if (pqGetErrorNotice2(conn, false /* treat as notice */ ))
- return;
+ return 0;
}
else
{
@@ -492,13 +494,13 @@ pqParseInput2(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ return EOF;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
@@ -507,7 +509,7 @@ pqParseInput2(PGconn *conn)
break;
case 'E': /* error return */
if (pqGetErrorNotice2(conn, true))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_READY;
break;
case 'Z': /* backend is ready for new query */
@@ -516,7 +518,7 @@ pqParseInput2(PGconn *conn)
case 'I': /* empty query */
/* read and throw away the closing '\0' */
if (pqGetc(&id, conn))
- return;
+ return 0;
if (id != '\0')
pqInternalNotice(&conn->noticeHooks,
"unexpected character %c following empty query response (\"I\" message)",
@@ -534,13 +536,13 @@ pqParseInput2(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'P': /* synchronous (normal) portal */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
/* We pretty much ignore this message type... */
break;
case 'T': /* row descriptions (start of query results) */
@@ -548,7 +550,7 @@ pqParseInput2(PGconn *conn)
{
/* First 'T' in a query sequence */
if (getRowDescriptions(conn))
- return;
+ return 0;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -562,7 +564,7 @@ pqParseInput2(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'D': /* ASCII data tuple */
@@ -570,7 +572,7 @@ pqParseInput2(PGconn *conn)
{
/* Read another tuple of a normal query response */
if (getAnotherTuple(conn, FALSE))
- return;
+ return 0;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -580,7 +582,7 @@ pqParseInput2(PGconn *conn)
"server sent data (\"D\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'B': /* Binary data tuple */
@@ -588,7 +590,7 @@ pqParseInput2(PGconn *conn)
{
/* Read another tuple of a normal query response */
if (getAnotherTuple(conn, TRUE))
- return;
+ return 0;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -598,7 +600,7 @@ pqParseInput2(PGconn *conn)
"server sent binary data (\"B\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'G': /* Start Copy In */
@@ -622,12 +624,15 @@ pqParseInput2(PGconn *conn)
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
} /* switch on protocol character */
}
/* Successfully consumed this message */
conn->inStart = conn->inCursor;
}
+
+ /* we are done */
+ return 0;
}
/*
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index a847f08..f27d193 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -61,8 +61,10 @@ static int build_startup_packet(const PGconn *conn, char *packet,
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF an error should occur.
*/
-void
+int
pqParseInput3(PGconn *conn)
{
char id;
@@ -80,9 +82,9 @@ pqParseInput3(PGconn *conn)
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
if (pqGetInt(&msgLength, 4, conn))
- return;
+ return 0;
/*
* Try to validate message type/length here. A length less than 4 is
@@ -92,12 +94,12 @@ pqParseInput3(PGconn *conn)
if (msgLength < 4)
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
/*
@@ -126,7 +128,7 @@ pqParseInput3(PGconn *conn)
*/
handleSyncLoss(conn, id, msgLength);
}
- return;
+ return 0;
}
/*
@@ -148,18 +150,18 @@ pqParseInput3(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
if (pqGetErrorNotice3(conn, false))
- return;
+ return 0;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -173,12 +175,12 @@ pqParseInput3(PGconn *conn)
if (id == 'E')
{
if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
- return;
+ return 0;
}
else if (id == 'S')
{
if (getParameterStatus(conn))
- return;
+ return 0;
}
else
{
@@ -198,13 +200,13 @@ pqParseInput3(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ return EOF;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
@@ -212,12 +214,12 @@ pqParseInput3(PGconn *conn)
break;
case 'E': /* error return */
if (pqGetErrorNotice3(conn, true))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_READY;
break;
case 'Z': /* backend is ready for new query */
if (getReadyForQuery(conn))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_IDLE;
break;
case 'I': /* empty query */
@@ -226,7 +228,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
if (!conn->result)
- return;
+ return EOF;
}
conn->asyncStatus = PGASYNC_READY;
break;
@@ -239,7 +241,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ return EOF;
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -250,7 +252,7 @@ pqParseInput3(PGconn *conn)
break;
case 'S': /* parameter status */
if (getParameterStatus(conn))
- return;
+ return 0;
break;
case 'K': /* secret key data from the backend */
@@ -260,9 +262,9 @@ pqParseInput3(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'T': /* Row Description */
if (conn->result == NULL ||
@@ -270,7 +272,7 @@ pqParseInput3(PGconn *conn)
{
/* First 'T' in a query sequence */
if (getRowDescriptions(conn, msgLength))
- return;
+ return EOF;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -284,7 +286,7 @@ pqParseInput3(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'n': /* No Data */
@@ -306,14 +308,14 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ return EOF;
}
conn->asyncStatus = PGASYNC_READY;
}
break;
case 't': /* Parameter Description */
if (getParamDescriptions(conn))
- return;
+ return 0;
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -321,7 +323,7 @@ pqParseInput3(PGconn *conn)
{
/* Read another tuple of a normal query response */
if (getAnotherTuple(conn, msgLength))
- return;
+ return EOF;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -345,21 +347,36 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
- return;
- conn->asyncStatus = PGASYNC_COPY_IN;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_IN);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ return EOF;
+ conn->asyncStatus = PGASYNC_COPY_IN;
+ }
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
- return;
- conn->asyncStatus = PGASYNC_COPY_OUT;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_OUT);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ return EOF;
+ conn->asyncStatus = PGASYNC_COPY_OUT;
+ conn->copy_already_done = 0;
+ }
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
- return;
- conn->asyncStatus = PGASYNC_COPY_BOTH;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_BOTH);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ return EOF;
+ conn->asyncStatus = PGASYNC_COPY_BOTH;
+ conn->copy_already_done = 0;
+ }
break;
case 'd': /* Copy Data */
@@ -412,6 +429,9 @@ pqParseInput3(PGconn *conn)
conn->inStart += 5 + msgLength;
}
}
+
+ /* we are done */
+ return 0;
}
/*
@@ -466,7 +486,8 @@ getRowDescriptions(PGconn *conn, int msgLength)
result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
if (!result)
{
- errmsg = NULL; /* means "out of memory", see below */
+ /* Error is already saved by PQmakeEmptyPGresult() */
+ errmsg = conn->errorMessage.data;
goto advance_and_error;
}
@@ -1309,6 +1330,11 @@ getNotify(PGconn *conn)
* CopyBothResponse message
*
* parseInput already read the message type and length.
+ * Returns: 0 in case of success.
+ * -1 if there is not enough data. In this case parsing should
+ * continue later on.
+ * -2 in case of an OOM error. In this case parsing should be
+ * suspended immediately.
*/
static int
getCopyStart(PGconn *conn, ExecStatusType copytype)
@@ -1316,17 +1342,27 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
PGresult *result;
int nfields;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
+ {
+ res = -1;
goto failure;
+ }
result->binary = conn->copy_is_binary;
/* the next two bytes are the number of fields */
if (pqGetInt(&(result->numAttributes), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1335,7 +1371,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1344,7 +1383,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
+ {
+ res = -1;
goto failure;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1356,11 +1398,12 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 2175957..235af89 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -559,7 +559,7 @@ extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput2(PGconn *conn);
+extern int pqParseInput2(PGconn *conn);
extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
extern int pqGetline2(PGconn *conn, char *s, int maxlen);
extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
@@ -573,7 +573,7 @@ extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput3(PGconn *conn);
+extern int pqParseInput3(PGconn *conn);
extern int pqGetErrorNotice3(PGconn *conn, bool isError);
extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
extern int pqGetline3(PGconn *conn, char *s, int maxlen);
--
2.3.5
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-07 18:54 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2015-04-07 18:54 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 04/07/2015 09:18 AM, Michael Paquier wrote:
> @@ -143,7 +143,11 @@ PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
>
> result = (PGresult *) malloc(sizeof(PGresult));
> if (!result)
> + {
> + printfPQExpBuffer(&conn->errorMessage,
> + libpq_gettext("out of memory\n"));
> return NULL;
> + }
>
> result->ntups = 0;
> result->numAttributes = 0;
That's not cool, because PQmakeEmptyPGresult may be called with conn ==
NULL. In general, I'm a bit wary of changing PQmakeEmptyResult so that
it sets the error message. Will have to check all the callers carefully
to see if that would upset any of them. And it might be called by
applications too.
> I have noticed as well that getCopyStart() in fe-protocol3.c needs to
> be made a little bit smarter to make the difference between an OOM and
> the not-enough-data type of problem.
Yeah. getParamDescription still has the issue, with your patch.
> This problem has a low probability to happen in the field, and no
> people complained about that as well, so I think that patching only
> HEAD is adapted.
As long as the patch applies easily, I don't see much reason to not
backpatch.
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-08 04:27 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-04-08 04:27 UTC (permalink / raw)
To: hlinnaka@iki.fi; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Wed, Apr 8, 2015 at 3:54 AM, Heikki Linnakangas wrote:
> On 04/07/2015 09:18 AM, Michael Paquier wrote:
>>
>> @@ -143,7 +143,11 @@ PQmakeEmptyPGresult(PGconn *conn, ExecStatusType
>> status)
>>
>> [...]
>
> That's not cool, because PQmakeEmptyPGresult may be called with conn ==
> NULL. In general, I'm a bit wary of changing PQmakeEmptyResult so that it
> sets the error message. Will have to check all the callers carefully to see
> if that would upset any of them. And it might be called by applications too.
Oops, my mistake. For a patch arguing to not change how libpq routines
behave this is bad, and contrary to what is mentioned in the docs as
well. I moved the error message into parseInput. I guess it makes more
sense there.
>> I have noticed as well that getCopyStart() in fe-protocol3.c needs to
>> be made a little bit smarter to make the difference between an OOM and
>> the not-enough-data type of problem.
>
> Yeah. getParamDescription still has the issue, with your patch.
Check.
>> This problem has a low probability to happen in the field, and no
>> people complained about that as well, so I think that patching only
>> HEAD is adapted.
>
>
> As long as the patch applies easily, I don't see much reason to not
> backpatch.
It applies cleanly down to 9.1. For 9.0 some minor tweaks are visibly needed.
In any case, take two is attached.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
0001-Improve-OOM-detection-of-parseInput-in-libpq.patch (application/x-patch, 21.0K) download
From 1e8e2d2691662a1238632b1732c0f0c0f1d07853 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Wed, 8 Apr 2015 13:16:20 +0900
Subject: [PATCH] Improve OOM detection of parseInput in libpq
An OOM occurring at the beginning of parseInput() when called at the
beginning of pqGetResult could result in libpq hanging indefinitely.
The probability to face this case is rather low, but let's make the
OOM error handling of parseInput more robust in this area. getCopyStart()
and getParamDescriptions() are made a bit smarter to make the difference
between an OOM, meaning that input parsing should be immediately stopped,
and cases where there is not enough data, meaning that parsing should
continue later on.
---
src/interfaces/libpq/fe-exec.c | 27 +++---
src/interfaces/libpq/fe-protocol2.c | 54 +++++++-----
src/interfaces/libpq/fe-protocol3.c | 159 ++++++++++++++++++++++++++----------
src/interfaces/libpq/libpq-int.h | 4 +-
4 files changed, 166 insertions(+), 78 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..754d7f3 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -62,7 +62,7 @@ static int PQsendQueryGuts(PGconn *conn,
const int *paramLengths,
const int *paramFormats,
int resultFormat);
-static void parseInput(PGconn *conn);
+static int parseInput(PGconn *conn);
static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
static bool PQexecStart(PGconn *conn);
static PGresult *PQexecFinish(PGconn *conn);
@@ -1573,7 +1573,7 @@ pqHandleSendFailure(PGconn *conn)
* Parse any available input messages. Since we are in PGASYNC_IDLE
* state, only NOTICE and NOTIFY messages will be eaten.
*/
- parseInput(conn);
+ (void) parseInput(conn);
}
/*
@@ -1641,14 +1641,16 @@ PQconsumeInput(PGconn *conn)
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF if an error occurs.
*/
-static void
+static int
parseInput(PGconn *conn)
{
if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
- pqParseInput3(conn);
+ return pqParseInput3(conn);
else
- pqParseInput2(conn);
+ return pqParseInput2(conn);
}
/*
@@ -1663,7 +1665,8 @@ PQisBusy(PGconn *conn)
return FALSE;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return FALSE;
/* PQgetResult will return immediately in all states except BUSY. */
return conn->asyncStatus == PGASYNC_BUSY;
@@ -1686,7 +1689,8 @@ PQgetResult(PGconn *conn)
return NULL;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
/* If not ready to return something, block until we are. */
while (conn->asyncStatus == PGASYNC_BUSY)
@@ -1721,7 +1725,8 @@ PQgetResult(PGconn *conn)
}
/* Parse it. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
}
/* Return the appropriate thing. */
@@ -2177,7 +2182,8 @@ PQnotifies(PGconn *conn)
return NULL;
/* Parse any available data to see if we can extract NOTIFY messages. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
event = conn->notifyHead;
if (event)
@@ -2217,7 +2223,8 @@ PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
* input data into the input buffer happens down inside pqSendSome, but
* it's not authorized to get rid of the data again.)
*/
- parseInput(conn);
+ if (parseInput(conn))
+ return -1;
if (nbytes > 0)
{
diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
index eeba7f3..66d631e 100644
--- a/src/interfaces/libpq/fe-protocol2.c
+++ b/src/interfaces/libpq/fe-protocol2.c
@@ -406,8 +406,10 @@ error_return:
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if successfully parsed input.
+ * returns EOF if an error occurs.
*/
-void
+int
pqParseInput2(PGconn *conn)
{
char id;
@@ -424,14 +426,14 @@ pqParseInput2(PGconn *conn)
* protocol and have identifying leading characters.)
*/
if (conn->asyncStatus == PGASYNC_COPY_OUT)
- return;
+ return 0;
/*
* OK to try to read a message type code.
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
/*
* NOTIFY and NOTICE messages can happen in any state besides COPY
@@ -447,18 +449,18 @@ pqParseInput2(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
if (pqGetErrorNotice2(conn, false))
- return;
+ return 0;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -471,7 +473,7 @@ pqParseInput2(PGconn *conn)
if (id == 'E')
{
if (pqGetErrorNotice2(conn, false /* treat as notice */ ))
- return;
+ return 0;
}
else
{
@@ -492,13 +494,13 @@ pqParseInput2(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
@@ -507,7 +509,7 @@ pqParseInput2(PGconn *conn)
break;
case 'E': /* error return */
if (pqGetErrorNotice2(conn, true))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_READY;
break;
case 'Z': /* backend is ready for new query */
@@ -516,7 +518,7 @@ pqParseInput2(PGconn *conn)
case 'I': /* empty query */
/* read and throw away the closing '\0' */
if (pqGetc(&id, conn))
- return;
+ return 0;
if (id != '\0')
pqInternalNotice(&conn->noticeHooks,
"unexpected character %c following empty query response (\"I\" message)",
@@ -524,6 +526,8 @@ pqParseInput2(PGconn *conn)
if (conn->result == NULL)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
+ if (conn->result == NULL)
+ goto failure;
conn->asyncStatus = PGASYNC_READY;
break;
case 'K': /* secret key data from the backend */
@@ -534,13 +538,13 @@ pqParseInput2(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'P': /* synchronous (normal) portal */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
/* We pretty much ignore this message type... */
break;
case 'T': /* row descriptions (start of query results) */
@@ -548,7 +552,7 @@ pqParseInput2(PGconn *conn)
{
/* First 'T' in a query sequence */
if (getRowDescriptions(conn))
- return;
+ return 0;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -562,7 +566,7 @@ pqParseInput2(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'D': /* ASCII data tuple */
@@ -570,7 +574,7 @@ pqParseInput2(PGconn *conn)
{
/* Read another tuple of a normal query response */
if (getAnotherTuple(conn, FALSE))
- return;
+ return 0;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -580,7 +584,7 @@ pqParseInput2(PGconn *conn)
"server sent data (\"D\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'B': /* Binary data tuple */
@@ -588,7 +592,7 @@ pqParseInput2(PGconn *conn)
{
/* Read another tuple of a normal query response */
if (getAnotherTuple(conn, TRUE))
- return;
+ return 0;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -598,7 +602,7 @@ pqParseInput2(PGconn *conn)
"server sent binary data (\"B\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'G': /* Start Copy In */
@@ -622,12 +626,20 @@ pqParseInput2(PGconn *conn)
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
} /* switch on protocol character */
}
/* Successfully consumed this message */
conn->inStart = conn->inCursor;
}
+
+ /* we are done */
+ return 0;
+
+failure:
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ return EOF;
}
/*
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index a847f08..17580e6 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -61,8 +61,10 @@ static int build_startup_packet(const PGconn *conn, char *packet,
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF if an error occurs.
*/
-void
+int
pqParseInput3(PGconn *conn)
{
char id;
@@ -80,9 +82,9 @@ pqParseInput3(PGconn *conn)
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
if (pqGetInt(&msgLength, 4, conn))
- return;
+ return 0;
/*
* Try to validate message type/length here. A length less than 4 is
@@ -92,12 +94,12 @@ pqParseInput3(PGconn *conn)
if (msgLength < 4)
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
/*
@@ -126,7 +128,7 @@ pqParseInput3(PGconn *conn)
*/
handleSyncLoss(conn, id, msgLength);
}
- return;
+ return 0;
}
/*
@@ -148,18 +150,18 @@ pqParseInput3(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
if (pqGetErrorNotice3(conn, false))
- return;
+ return 0;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -173,12 +175,12 @@ pqParseInput3(PGconn *conn)
if (id == 'E')
{
if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
- return;
+ return 0;
}
else if (id == 'S')
{
if (getParameterStatus(conn))
- return;
+ return 0;
}
else
{
@@ -198,13 +200,13 @@ pqParseInput3(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
@@ -212,12 +214,12 @@ pqParseInput3(PGconn *conn)
break;
case 'E': /* error return */
if (pqGetErrorNotice3(conn, true))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_READY;
break;
case 'Z': /* backend is ready for new query */
if (getReadyForQuery(conn))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_IDLE;
break;
case 'I': /* empty query */
@@ -226,7 +228,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
break;
@@ -239,7 +241,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -250,7 +252,7 @@ pqParseInput3(PGconn *conn)
break;
case 'S': /* parameter status */
if (getParameterStatus(conn))
- return;
+ return 0;
break;
case 'K': /* secret key data from the backend */
@@ -260,9 +262,9 @@ pqParseInput3(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'T': /* Row Description */
if (conn->result == NULL ||
@@ -270,7 +272,7 @@ pqParseInput3(PGconn *conn)
{
/* First 'T' in a query sequence */
if (getRowDescriptions(conn, msgLength))
- return;
+ return EOF;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -284,7 +286,7 @@ pqParseInput3(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'n': /* No Data */
@@ -306,14 +308,19 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
- return;
+ {
+ int res = getParamDescriptions(conn);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -321,7 +328,7 @@ pqParseInput3(PGconn *conn)
{
/* Read another tuple of a normal query response */
if (getAnotherTuple(conn, msgLength))
- return;
+ return EOF;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -345,21 +352,36 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
- return;
- conn->asyncStatus = PGASYNC_COPY_IN;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_IN);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_IN;
+ }
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
- return;
- conn->asyncStatus = PGASYNC_COPY_OUT;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_OUT);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_OUT;
+ conn->copy_already_done = 0;
+ }
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
- return;
- conn->asyncStatus = PGASYNC_COPY_BOTH;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_BOTH);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_BOTH;
+ conn->copy_already_done = 0;
+ }
break;
case 'd': /* Copy Data */
@@ -412,6 +434,14 @@ pqParseInput3(PGconn *conn)
conn->inStart += 5 + msgLength;
}
}
+
+ /* we are done */
+ return 0;
+
+failure:
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ return EOF;
}
/*
@@ -466,7 +496,8 @@ getRowDescriptions(PGconn *conn, int msgLength)
result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
if (!result)
{
- errmsg = NULL; /* means "out of memory", see below */
+ /* Error is already saved by PQmakeEmptyPGresult() */
+ errmsg = conn->errorMessage.data;
goto advance_and_error;
}
@@ -613,7 +644,9 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message
+ * -1 if not enough data yet.
+ * -2 in case of an OOM error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
@@ -625,15 +658,22 @@ getParamDescriptions(PGconn *conn)
PGresult *result;
int nparams;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -642,7 +682,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -652,17 +695,21 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
+ {
+ res = -1;
goto failure;
+ }
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
@@ -1309,6 +1356,11 @@ getNotify(PGconn *conn)
* CopyBothResponse message
*
* parseInput already read the message type and length.
+ * Returns: 0 in case of success.
+ * -1 if there is not enough data. In this case parsing should
+ * continue later on.
+ * -2 in case of an OOM error. In this case parsing should be
+ * suspended immediately.
*/
static int
getCopyStart(PGconn *conn, ExecStatusType copytype)
@@ -1316,17 +1368,27 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
PGresult *result;
int nfields;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
+ {
+ res = -1;
goto failure;
+ }
result->binary = conn->copy_is_binary;
/* the next two bytes are the number of fields */
if (pqGetInt(&(result->numAttributes), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1335,7 +1397,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1344,7 +1409,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
+ {
+ res = -1;
goto failure;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1356,11 +1424,12 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 2175957..235af89 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -559,7 +559,7 @@ extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput2(PGconn *conn);
+extern int pqParseInput2(PGconn *conn);
extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
extern int pqGetline2(PGconn *conn, char *s, int maxlen);
extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
@@ -573,7 +573,7 @@ extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput3(PGconn *conn);
+extern int pqParseInput3(PGconn *conn);
extern int pqGetErrorNotice3(PGconn *conn, bool isError);
extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
extern int pqGetline3(PGconn *conn, char *s, int maxlen);
--
2.3.4
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-09 17:42 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2015-04-09 17:42 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 04/08/2015 07:27 AM, Michael Paquier wrote:
> On Wed, Apr 8, 2015 at 3:54 AM, Heikki Linnakangas wrote:
>> On 04/07/2015 09:18 AM, Michael Paquier wrote:
>>> I have noticed as well that getCopyStart() in fe-protocol3.c needs to
>>> be made a little bit smarter to make the difference between an OOM and
>>> the not-enough-data type of problem.
>>
>> Yeah. getParamDescription still has the issue, with your patch.
>
> Check.
There are still a few parseInput subroutines that have similar issues.
In fe-protocol2.c:
* pqGetErrorNotice2 returns EOF if there is not enough data, but also on
OOM. The caller assumes it's because not enough data.
* getRowDescriptions() is the same, although it sets conn->errorMessage
on OOM.
* getAnotherTuple() is the same, but it also skips over the received
data, so you won't get stuck. So maybe that's OK.
* getNotify() just drops any NOTIFY messages on OOM. Perhaps that's OK..
The corresponding functions in fe-protocol3.c are pretty much identical,
with the same issues. In addition:
* getParameterStatus will act as if the parameter value was "out of
memory". That'll be fun for something like client_encoding or
standard_conforming_strings. Would be good to use a small char[100]
variable, in stack, if it fits, and only use malloc for larger values.
That would cover all the common variables that need to be machine-parsed.
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-04-10 11:53 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-04-10 11:53 UTC (permalink / raw)
To: hlinnaka@iki.fi; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Apr 10, 2015 at 2:42 AM, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> On 04/08/2015 07:27 AM, Michael Paquier wrote:
>>
>> On Wed, Apr 8, 2015 at 3:54 AM, Heikki Linnakangas wrote:
>>>
>>> On 04/07/2015 09:18 AM, Michael Paquier wrote:
>>>>
>>>> I have noticed as well that getCopyStart() in fe-protocol3.c needs to
>>>> be made a little bit smarter to make the difference between an OOM and
>>>> the not-enough-data type of problem.
>>>
>>>
>>> Yeah. getParamDescription still has the issue, with your patch.
>>
>>
>> Check.
>
>
> There are still a few parseInput subroutines that have similar issues. In
> fe-protocol2.c:
>
> * pqGetErrorNotice2 returns EOF if there is not enough data, but also on
> OOM. The caller assumes it's because not enough data.
> * getRowDescriptions() is the same, although it sets conn->errorMessage on
> OOM.
OK, I extended those two with the same logic as previously.
> * getAnotherTuple() is the same, but it also skips over the received data,
> so you won't get stuck. So maybe that's OK.
I think that it should be changed for consistency with the others, so
done this way for this function, and this way we only need to bail-out
if status == -2, a status of -1 meaning that there is not enough data.
> * getNotify() just drops any NOTIFY messages on OOM. Perhaps that's OK..
This one is different though, it directly skips the messages.
> The corresponding functions in fe-protocol3.c are pretty much identical,
> with the same issues. In addition:
>
> * getParameterStatus will act as if the parameter value was "out of memory".
> That'll be fun for something like client_encoding or
> standard_conforming_strings. Would be good to use a small char[100]
> variable, in stack, if it fits, and only use malloc for larger values. That
> would cover all the common variables that need to be machine-parsed.
Are you suggesting to replace PQExpBuffer?
So, attached is take three for all the other things above.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
0001-Improve-OOM-detection-of-parseInput-in-libpq.patch (text/x-patch, 41.0K) download
From f9d68b78c0409a1b733f3389ec7e4c80a5e7b341 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Fri, 10 Apr 2015 17:01:41 +0000
Subject: [PATCH] Improve OOM detection of parseInput in libpq
An OOM occurring at the beginning of parseInput() when called at the
beginning of pqGetResult could result in libpq hanging indefinitely.
The probability to face this case is rather low, but let's make the
OOM error handling of parseInput more robust in this area. Additionally,
a couple of underlying functions like getCopyStart() are made a bit
smarter to make the difference between an OOM, meaning that input
parsing should be immediately stopped, and cases where there is not
enough data, meaning that parsing should continue later on, making
the whole more robust.
---
src/interfaces/libpq/fe-exec.c | 27 +--
src/interfaces/libpq/fe-protocol2.c | 204 +++++++++++++++--------
src/interfaces/libpq/fe-protocol3.c | 320 +++++++++++++++++++++++++-----------
src/interfaces/libpq/libpq-int.h | 4 +-
4 files changed, 374 insertions(+), 181 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..754d7f3 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -62,7 +62,7 @@ static int PQsendQueryGuts(PGconn *conn,
const int *paramLengths,
const int *paramFormats,
int resultFormat);
-static void parseInput(PGconn *conn);
+static int parseInput(PGconn *conn);
static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
static bool PQexecStart(PGconn *conn);
static PGresult *PQexecFinish(PGconn *conn);
@@ -1573,7 +1573,7 @@ pqHandleSendFailure(PGconn *conn)
* Parse any available input messages. Since we are in PGASYNC_IDLE
* state, only NOTICE and NOTIFY messages will be eaten.
*/
- parseInput(conn);
+ (void) parseInput(conn);
}
/*
@@ -1641,14 +1641,16 @@ PQconsumeInput(PGconn *conn)
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF if an error occurs.
*/
-static void
+static int
parseInput(PGconn *conn)
{
if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
- pqParseInput3(conn);
+ return pqParseInput3(conn);
else
- pqParseInput2(conn);
+ return pqParseInput2(conn);
}
/*
@@ -1663,7 +1665,8 @@ PQisBusy(PGconn *conn)
return FALSE;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return FALSE;
/* PQgetResult will return immediately in all states except BUSY. */
return conn->asyncStatus == PGASYNC_BUSY;
@@ -1686,7 +1689,8 @@ PQgetResult(PGconn *conn)
return NULL;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
/* If not ready to return something, block until we are. */
while (conn->asyncStatus == PGASYNC_BUSY)
@@ -1721,7 +1725,8 @@ PQgetResult(PGconn *conn)
}
/* Parse it. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
}
/* Return the appropriate thing. */
@@ -2177,7 +2182,8 @@ PQnotifies(PGconn *conn)
return NULL;
/* Parse any available data to see if we can extract NOTIFY messages. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
event = conn->notifyHead;
if (event)
@@ -2217,7 +2223,8 @@ PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
* input data into the input buffer happens down inside pqSendSome, but
* it's not authorized to get rid of the data again.)
*/
- parseInput(conn);
+ if (parseInput(conn))
+ return -1;
if (nbytes > 0)
{
diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
index eeba7f3..5ac3d9a 100644
--- a/src/interfaces/libpq/fe-protocol2.c
+++ b/src/interfaces/libpq/fe-protocol2.c
@@ -406,8 +406,10 @@ error_return:
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if successfully parsed input.
+ * returns EOF if an error occurs.
*/
-void
+int
pqParseInput2(PGconn *conn)
{
char id;
@@ -424,14 +426,14 @@ pqParseInput2(PGconn *conn)
* protocol and have identifying leading characters.)
*/
if (conn->asyncStatus == PGASYNC_COPY_OUT)
- return;
+ return 0;
/*
* OK to try to read a message type code.
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
/*
* NOTIFY and NOTICE messages can happen in any state besides COPY
@@ -447,18 +449,21 @@ pqParseInput2(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
- if (pqGetErrorNotice2(conn, false))
- return;
+ int res = pqGetErrorNotice2(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -470,8 +475,12 @@ pqParseInput2(PGconn *conn)
*/
if (id == 'E')
{
- if (pqGetErrorNotice2(conn, false /* treat as notice */ ))
- return;
+ /* treat as notice */
+ int res = pqGetErrorNotice2(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else
{
@@ -492,13 +501,13 @@ pqParseInput2(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
@@ -506,9 +515,14 @@ pqParseInput2(PGconn *conn)
conn->asyncStatus = PGASYNC_READY;
break;
case 'E': /* error return */
- if (pqGetErrorNotice2(conn, true))
- return;
- conn->asyncStatus = PGASYNC_READY;
+ {
+ int res = pqGetErrorNotice2(conn, true);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_READY;
+ }
break;
case 'Z': /* backend is ready for new query */
conn->asyncStatus = PGASYNC_IDLE;
@@ -516,7 +530,7 @@ pqParseInput2(PGconn *conn)
case 'I': /* empty query */
/* read and throw away the closing '\0' */
if (pqGetc(&id, conn))
- return;
+ return 0;
if (id != '\0')
pqInternalNotice(&conn->noticeHooks,
"unexpected character %c following empty query response (\"I\" message)",
@@ -524,6 +538,8 @@ pqParseInput2(PGconn *conn)
if (conn->result == NULL)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
+ if (conn->result == NULL)
+ goto failure;
conn->asyncStatus = PGASYNC_READY;
break;
case 'K': /* secret key data from the backend */
@@ -534,21 +550,24 @@ pqParseInput2(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'P': /* synchronous (normal) portal */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
/* We pretty much ignore this message type... */
break;
case 'T': /* row descriptions (start of query results) */
if (conn->result == NULL)
{
+ int res = getRowDescriptions(conn);
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn))
- return;
+ if (res == -1)
+ return 0;
+ if (res == -2)
+ goto failure;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -562,15 +581,17 @@ pqParseInput2(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'D': /* ASCII data tuple */
if (conn->result != NULL)
{
- /* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, FALSE))
- return;
+ int res = getAnotherTuple(conn, FALSE);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -580,15 +601,17 @@ pqParseInput2(PGconn *conn)
"server sent data (\"D\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'B': /* Binary data tuple */
if (conn->result != NULL)
{
- /* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, TRUE))
- return;
+ int res = getAnotherTuple(conn, TRUE);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -598,7 +621,7 @@ pqParseInput2(PGconn *conn)
"server sent binary data (\"B\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'G': /* Start Copy In */
@@ -622,19 +645,28 @@ pqParseInput2(PGconn *conn)
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
} /* switch on protocol character */
}
/* Successfully consumed this message */
conn->inStart = conn->inCursor;
}
+
+ /* we are done */
+ return 0;
+
+failure:
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ return EOF;
}
/*
* parseInput subroutine to read a 'T' (row descriptions) message.
* We build a PGresult structure containing the attribute data.
- * Returns: 0 if completed message, EOF if error or not enough data
- * received yet.
+ * Returns: 0 if completed message.
+ * -1 if error or not enough data received yet.
+ * -2 in case of OOM.
*
* Note that if we run out of data, we have to suspend and reprocess
* the message after more data is received. Otherwise, conn->inStart
@@ -643,22 +675,26 @@ pqParseInput2(PGconn *conn)
static int
getRowDescriptions(PGconn *conn)
{
- PGresult *result;
+ PGresult *result = NULL;
int nfields;
- const char *errmsg;
+ const char *errmsg = NULL;
int i;
+ int status = 0;
result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
if (!result)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
/* parseInput already read the 'T' label. */
/* the next two bytes are the number of fields */
if (pqGetInt(&(result->numAttributes), 2, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -668,7 +704,7 @@ getRowDescriptions(PGconn *conn)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
@@ -685,7 +721,10 @@ getRowDescriptions(PGconn *conn)
pqGetInt(&typid, 4, conn) ||
pqGetInt(&typlen, 2, conn) ||
pqGetInt(&atttypmod, 4, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -697,7 +736,7 @@ getRowDescriptions(PGconn *conn)
conn->workBuffer.data);
if (!result->attDescs[i].name)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
result->attDescs[i].tableid = 0;
@@ -720,7 +759,7 @@ getRowDescriptions(PGconn *conn)
*/
/* And we're done. */
- return 0;
+ return status;
advance_and_error:
@@ -738,15 +777,10 @@ advance_and_error:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ if (errmsg != NULL)
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
/*
* XXX: if PQmakeEmptyPGresult() fails, there's probably not much we can
@@ -758,14 +792,15 @@ advance_and_error:
EOFexit:
if (result && result != conn->result)
PQclear(result);
- return EOF;
+ return status;
}
/*
* parseInput subroutine to read a 'B' or 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if completed message, EOF if error or not enough data
- * received yet.
+ * Returns: 0 if processed message successfully.
+ * -1 if not enough data.
+ * -2 if an OOM error happened.
*
* Note that if we run out of data, we have to suspend and reprocess
* the message after more data is received. Otherwise, conn->inStart
@@ -776,8 +811,9 @@ getAnotherTuple(PGconn *conn, bool binary)
{
PGresult *result = conn->result;
int nfields = result->numAttributes;
- const char *errmsg;
+ const char *errmsg = NULL;
PGdataValue *rowbuf;
+ int status = 0;
/* the backend sends us a bitmap of which attributes are null */
char std_bitmap[64]; /* used unless it doesn't fit */
@@ -797,7 +833,7 @@ getAnotherTuple(PGconn *conn, bool binary)
nfields * sizeof(PGdataValue));
if (!rowbuf)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
conn->rowBuf = rowbuf;
@@ -825,13 +861,16 @@ getAnotherTuple(PGconn *conn, bool binary)
bitmap = (char *) malloc(nbytes);
if (!bitmap)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
}
if (pqGetnchar(bitmap, nbytes, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
/* Scan the fields */
bitmap_index = 0;
@@ -844,7 +883,10 @@ getAnotherTuple(PGconn *conn, bool binary)
if (!(bmap & 0200))
vlen = NULL_LEN;
else if (pqGetInt(&vlen, 4, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
else
{
if (!binary)
@@ -865,7 +907,10 @@ getAnotherTuple(PGconn *conn, bool binary)
if (vlen > 0)
{
if (pqSkipnchar(vlen, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
}
/* advance the bitmap stuff */
@@ -913,15 +958,13 @@ set_error_result:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ if (errmsg != NULL)
+ {
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+ }
/*
* XXX: if PQmakeEmptyPGresult() fails, there's probably not much we can
@@ -933,7 +976,7 @@ set_error_result:
EOFexit:
if (bitmap != NULL && bitmap != std_bitmap)
free(bitmap);
- return EOF;
+ return status;
}
@@ -942,7 +985,8 @@ EOFexit:
* This is possible in several places, so we break it out as a subroutine.
* Entry: 'E' or 'N' message type has already been consumed.
* Exit: returns 0 if successfully consumed message.
- * returns EOF if not enough data.
+ * returns -1 if not enough data.
+ * returns -2 in case of out-of-memory.
*/
static int
pqGetErrorNotice2(PGconn *conn, bool isError)
@@ -951,6 +995,7 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
PQExpBufferData workBuf;
char *startp;
char *splitp;
+ int status = 0;
/*
* Since the message might be pretty long, we create a temporary
@@ -959,7 +1004,10 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
*/
initPQExpBuffer(&workBuf);
if (pqGets(&workBuf, conn))
+ {
+ status = -1;
goto failure;
+ }
/*
* Make a PGresult to hold the message. We temporarily lie about the
@@ -968,11 +1016,17 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
if (!res)
+ {
+ status = -2;
goto failure;
+ }
res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
res->errMsg = pqResultStrdup(res, workBuf.data);
if (!res->errMsg)
+ {
+ status = -2;
goto failure;
+ }
/*
* Break the message into fields. We can't do very much here, but we can
@@ -1036,13 +1090,13 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
}
termPQExpBuffer(&workBuf);
- return 0;
+ return status;
failure:
if (res)
PQclear(res);
termPQExpBuffer(&workBuf);
- return EOF;
+ return status;
}
/*
@@ -1521,9 +1575,14 @@ pqFunctionCall2(PGconn *conn, Oid fnid,
}
break;
case 'E': /* error return */
- if (pqGetErrorNotice2(conn, true))
- continue;
- status = PGRES_FATAL_ERROR;
+ {
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'A': /* notify message */
/* handle notify and go back to processing return values */
@@ -1531,9 +1590,14 @@ pqFunctionCall2(PGconn *conn, Oid fnid,
continue;
break;
case 'N': /* notice */
- /* handle notice and go back to processing return values */
- if (pqGetErrorNotice2(conn, false))
- continue;
+ {
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'Z': /* backend is ready for new query */
/* consume the message and exit */
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index a847f08..58382e0 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -61,8 +61,10 @@ static int build_startup_packet(const PGconn *conn, char *packet,
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF if an error occurs.
*/
-void
+int
pqParseInput3(PGconn *conn)
{
char id;
@@ -80,9 +82,9 @@ pqParseInput3(PGconn *conn)
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
if (pqGetInt(&msgLength, 4, conn))
- return;
+ return 0;
/*
* Try to validate message type/length here. A length less than 4 is
@@ -92,12 +94,12 @@ pqParseInput3(PGconn *conn)
if (msgLength < 4)
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
/*
@@ -126,7 +128,7 @@ pqParseInput3(PGconn *conn)
*/
handleSyncLoss(conn, id, msgLength);
}
- return;
+ return 0;
}
/*
@@ -148,18 +150,21 @@ pqParseInput3(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
- if (pqGetErrorNotice3(conn, false))
- return;
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -172,13 +177,17 @@ pqParseInput3(PGconn *conn)
*/
if (id == 'E')
{
- if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
- return;
+ /* treat as notice */
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else if (id == 'S')
{
if (getParameterStatus(conn))
- return;
+ return 0;
}
else
{
@@ -198,26 +207,31 @@ pqParseInput3(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
conn->asyncStatus = PGASYNC_READY;
break;
case 'E': /* error return */
- if (pqGetErrorNotice3(conn, true))
- return;
- conn->asyncStatus = PGASYNC_READY;
+ {
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_READY;
+ }
break;
case 'Z': /* backend is ready for new query */
if (getReadyForQuery(conn))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_IDLE;
break;
case 'I': /* empty query */
@@ -226,7 +240,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
break;
@@ -239,7 +253,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -250,7 +264,7 @@ pqParseInput3(PGconn *conn)
break;
case 'S': /* parameter status */
if (getParameterStatus(conn))
- return;
+ return 0;
break;
case 'K': /* secret key data from the backend */
@@ -260,17 +274,20 @@ pqParseInput3(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'T': /* Row Description */
if (conn->result == NULL ||
conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn, msgLength))
- return;
+ int res = getRowDescriptions(conn, msgLength);
+ if (res == -1)
+ return 0;
+ if (res == -2)
+ goto failure;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -284,7 +301,7 @@ pqParseInput3(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'n': /* No Data */
@@ -306,22 +323,29 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
- return;
+ {
+ int res = getParamDescriptions(conn);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
conn->result->resultStatus == PGRES_TUPLES_OK)
{
- /* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, msgLength))
- return;
+ int res = getAnotherTuple(conn, msgLength);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -345,21 +369,36 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
- return;
- conn->asyncStatus = PGASYNC_COPY_IN;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_IN);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_IN;
+ }
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
- return;
- conn->asyncStatus = PGASYNC_COPY_OUT;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_OUT);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_OUT;
+ conn->copy_already_done = 0;
+ }
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
- return;
- conn->asyncStatus = PGASYNC_COPY_BOTH;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_BOTH);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_BOTH;
+ conn->copy_already_done = 0;
+ }
break;
case 'd': /* Copy Data */
@@ -412,6 +451,14 @@ pqParseInput3(PGconn *conn)
conn->inStart += 5 + msgLength;
}
}
+
+ /* we are done */
+ return 0;
+
+failure:
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ return EOF;
}
/*
@@ -438,8 +485,9 @@ handleSyncLoss(PGconn *conn, char id, int msgLength)
* parseInput subroutine to read a 'T' (row descriptions) message.
* We'll build a new PGresult structure (unless called for a Describe
* command for a prepared statement) containing the attribute data.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
+ * Returns: 0 if processed message successfully.
+ * -1 if not enough data.
+ * -2 in case of OOM error.
* In either case, conn->inStart has been advanced past the message.
*/
static int
@@ -447,8 +495,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nfields;
- const char *errmsg;
+ const char *errmsg = NULL;
int i;
+ int status = 0;
/*
* When doing Describe for a prepared statement, there'll already be a
@@ -466,7 +515,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
if (!result)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
@@ -476,6 +525,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"T\" message");
+ status = -1;
goto advance_and_error;
}
nfields = result->numAttributes;
@@ -487,7 +537,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
@@ -516,6 +566,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"T\" message");
+ status = -1;
goto advance_and_error;
}
@@ -531,7 +582,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
conn->workBuffer.data);
if (!result->attDescs[i].name)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
result->attDescs[i].tableid = tableid;
@@ -549,6 +600,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
if (conn->inCursor != conn->inStart + 5 + msgLength)
{
errmsg = libpq_gettext("extraneous data in \"T\" message");
+ status = -1;
goto advance_and_error;
}
@@ -574,7 +626,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
*/
/* And we're done. */
- return 0;
+ return status;
advance_and_error:
/* Discard unsaved result, if any */
@@ -591,29 +643,30 @@ advance_and_error:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
- pqSaveErrorResult(conn);
+ if (errmsg != NULL)
+ {
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+ }
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return -1 to allow input parsing to continue in case of error.
+ * Subsequent "D" messages will be ignored until we get to end of
+ * data in this case, since an error result is already set up. If
+ * an out-of-memory happens, bail out immediately though and let
+ * the caller know that.
*/
- return 0;
+ return status;
}
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message
+ * -1 if not enough data yet.
+ * -2 in case of an OOM error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
@@ -625,15 +678,22 @@ getParamDescriptions(PGconn *conn)
PGresult *result;
int nparams;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -642,7 +702,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -652,24 +715,29 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
+ {
+ res = -1;
goto failure;
+ }
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
* parseInput subroutine to read a 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
+ * Returns: 0 if processed message successfully.
+ * -1 if not enough data.
+ * -2 if an OOM error happened.
* In either case, conn->inStart has been advanced past the message.
*/
static int
@@ -677,23 +745,26 @@ getAnotherTuple(PGconn *conn, int msgLength)
{
PGresult *result = conn->result;
int nfields = result->numAttributes;
- const char *errmsg;
+ const char *errmsg = NULL;
PGdataValue *rowbuf;
int tupnfields; /* # fields from tuple */
int vlen; /* length of the current field value */
int i;
+ int status = 0;
/* Get the field count and make sure it's what we expect */
if (pqGetInt(&tupnfields, 2, conn))
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
if (tupnfields != nfields)
{
errmsg = libpq_gettext("unexpected field count in \"D\" message");
+ status = -1;
goto advance_and_error;
}
@@ -705,7 +776,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
nfields * sizeof(PGdataValue));
if (!rowbuf)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
conn->rowBuf = rowbuf;
@@ -720,6 +791,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
rowbuf[i].len = vlen;
@@ -738,6 +810,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
}
@@ -747,6 +820,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
if (conn->inCursor != conn->inStart + 5 + msgLength)
{
errmsg = libpq_gettext("extraneous data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
@@ -756,7 +830,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
/* Process the collected row */
errmsg = NULL;
if (pqRowProcessor(conn, &errmsg))
- return 0; /* normal, successful exit */
+ return status; /* normal, successful exit */
goto set_error_result; /* pqRowProcessor failed, report it */
@@ -773,23 +847,19 @@ set_error_result:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
- pqSaveErrorResult(conn);
+ if (errmsg != NULL)
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return -1 to allow input parsing to continue in case of error.
+ * Subsequent "D" messages will be ignored until we get to end of
+ * data in this case, since an error result is already set up. If
+ * an out-of-memory happens, bail out immediately though and let
+ * the caller know that.
*/
- return 0;
+ return status;
}
@@ -798,7 +868,8 @@ set_error_result:
* This is possible in several places, so we break it out as a subroutine.
* Entry: 'E' or 'N' message type and length have already been consumed.
* Exit: returns 0 if successfully consumed message.
- * returns EOF if not enough data.
+ * returns -1 if not enough data.
+ * returns -2 in case of out-of-memory.
*/
int
pqGetErrorNotice3(PGconn *conn, bool isError)
@@ -809,6 +880,7 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
const char *val;
const char *querytext = NULL;
int querypos = 0;
+ int status = 0;
/*
* Since the fields might be pretty long, we create a temporary
@@ -825,7 +897,10 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
if (!res)
+ {
+ status = -2;
goto fail;
+ }
res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
/*
@@ -834,11 +909,17 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
for (;;)
{
if (pqGetc(&id, conn))
+ {
+ status = -1;
goto fail;
+ }
if (id == '\0')
break; /* terminator found */
if (pqGets(&workBuf, conn))
+ {
+ status = -1;
goto fail;
+ }
pqSaveMessageField(res, id, workBuf.data);
}
@@ -968,7 +1049,10 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
{
res->errMsg = pqResultStrdup(res, workBuf.data);
if (!res->errMsg)
+ {
+ status = -1;
goto fail;
+ }
pqClearAsyncResult(conn);
conn->result = res;
appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
@@ -983,12 +1067,12 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
}
termPQExpBuffer(&workBuf);
- return 0;
+ return status;
fail:
PQclear(res);
termPQExpBuffer(&workBuf);
- return EOF;
+ return status;
}
/*
@@ -1309,6 +1393,11 @@ getNotify(PGconn *conn)
* CopyBothResponse message
*
* parseInput already read the message type and length.
+ * Returns: 0 in case of success.
+ * -1 if there is not enough data. In this case parsing should
+ * continue later on.
+ * -2 in case of an OOM error. In this case parsing should be
+ * suspended immediately.
*/
static int
getCopyStart(PGconn *conn, ExecStatusType copytype)
@@ -1316,17 +1405,27 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
PGresult *result;
int nfields;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
+ {
+ res = -1;
goto failure;
+ }
result->binary = conn->copy_is_binary;
/* the next two bytes are the number of fields */
if (pqGetInt(&(result->numAttributes), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1335,7 +1434,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1344,7 +1446,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
+ {
+ res = -1;
goto failure;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1356,11 +1461,12 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
@@ -1457,8 +1563,13 @@ getCopyDataMessage(PGconn *conn)
return 0;
break;
case 'N': /* NOTICE */
- if (pqGetErrorNotice3(conn, false))
- return 0;
+ {
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ return -2;
+ }
break;
case 'S': /* ParameterStatus */
if (getParameterStatus(conn))
@@ -1922,9 +2033,14 @@ pqFunctionCall3(PGconn *conn, Oid fnid,
status = PGRES_COMMAND_OK;
break;
case 'E': /* error return */
- if (pqGetErrorNotice3(conn, true))
- continue;
- status = PGRES_FATAL_ERROR;
+ {
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'A': /* notify message */
/* handle notify and go back to processing return values */
@@ -1933,8 +2049,14 @@ pqFunctionCall3(PGconn *conn, Oid fnid,
break;
case 'N': /* notice */
/* handle notice and go back to processing return values */
- if (pqGetErrorNotice3(conn, false))
- continue;
+ {
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'Z': /* backend is ready for new query */
if (getReadyForQuery(conn))
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 2175957..235af89 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -559,7 +559,7 @@ extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput2(PGconn *conn);
+extern int pqParseInput2(PGconn *conn);
extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
extern int pqGetline2(PGconn *conn, char *s, int maxlen);
extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
@@ -573,7 +573,7 @@ extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput3(PGconn *conn);
+extern int pqParseInput3(PGconn *conn);
extern int pqGetErrorNotice3(PGconn *conn, bool isError);
extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
extern int pqGetline3(PGconn *conn, char *s, int maxlen);
--
2.3.5
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-05-20 16:31 Oleksandr Shulgin <oleksandr.shulgin@zalando.de>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Oleksandr Shulgin @ 2015-05-20 16:31 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: hlinnaka@iki.fi, Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
Michael Paquier <michael.paquier@gmail.com> writes:
>
>> There are still a few parseInput subroutines that have similar issues. In
>> fe-protocol2.c:
>>
>> * pqGetErrorNotice2 returns EOF if there is not enough data, but also on
>> OOM. The caller assumes it's because not enough data.
>> * getRowDescriptions() is the same, although it sets conn->errorMessage on
>> OOM.
>
> OK, I extended those two with the same logic as previously.
>
>> * getAnotherTuple() is the same, but it also skips over the received data,
>> so you won't get stuck. So maybe that's OK.
>
> I think that it should be changed for consistency with the others, so
> done this way for this function, and this way we only need to bail-out
> if status == -2, a status of -1 meaning that there is not enough data.
>
>> * getNotify() just drops any NOTIFY messages on OOM. Perhaps that's OK..
>
> This one is different though, it directly skips the messages.
>
>> The corresponding functions in fe-protocol3.c are pretty much identical,
>> with the same issues. In addition:
>>
>> * getParameterStatus will act as if the parameter value was "out of memory".
>> That'll be fun for something like client_encoding or
>> standard_conforming_strings. Would be good to use a small char[100]
>> variable, in stack, if it fits, and only use malloc for larger values. That
>> would cover all the common variables that need to be machine-parsed.
>
> Are you suggesting to replace PQExpBuffer?
>
> So, attached is take three for all the other things above.
There's still one call to pqGetErrorNotice3 that doesn't check returned
value for -2, in fe-connect.c. Shouldn't we also check it like this:
inline patch 1: src/interfaces/libpq/fe-connect.c (+9/-1 lines) download inline-1.patch
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index e7c7a25..330b8da 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -2242,6 +2242,7 @@ keep_going: /* We will come back to here until there is
int msgLength;
int avail;
AuthRequest areq;
+ int res;
/*
* Scan the message from current point (note that if we find
@@ -2366,11 +2367,18 @@ keep_going: /* We will come back to here until there is
{
if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
{
- if (pqGetErrorNotice3(conn, true))
+ res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
{
/* We'll come back when there is more data */
return PGRES_POLLING_READING;
}
+ else if (res == -2)
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ goto error_return;
+ }
}
else
{
--
Alex
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-05-26 07:01 Michael Paquier <michael.paquier@gmail.com>
parent: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-05-26 07:01 UTC (permalink / raw)
To: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; +Cc: hlinnaka@iki.fi, Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Thu, May 21, 2015 at 1:31 AM, Oleksandr Shulgin wrote:
> Michael Paquier <michael.paquier@gmail.com> writes:
>> So, attached is take three for all the other things above.
>
> There's still one call to pqGetErrorNotice3 that doesn't check returned
> value for -2, in fe-connect.c. Shouldn't we also check it like this:
>
> [...]
Yes, you are right. Take 4 attached is updated with something similar
to what you sent to cover this code path.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
0001-Improve-OOM-detection-of-parseInput-in-libpq.patch (text/x-diff, 41.8K) download
From d9125a0e48febc560c15a57dea84964b90d53ef3 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Tue, 26 May 2015 15:58:37 +0000
Subject: [PATCH] Improve OOM detection of parseInput in libpq
An OOM occurring at the beginning of parseInput() when called at the
beginning of pqGetResult could result in libpq hanging indefinitely.
The probability to face this case is rather low, but let's make the
OOM error handling of parseInput more robust in this area. Additionally,
a couple of underlying functions like getCopyStart() are made a bit
smarter to make the difference between an OOM, meaning that input
parsing should be immediately stopped, and cases where there is not
enough data, meaning that parsing should continue later on, making
the whole more robust.
---
src/interfaces/libpq/fe-connect.c | 9 +-
src/interfaces/libpq/fe-exec.c | 27 +--
src/interfaces/libpq/fe-protocol2.c | 204 +++++++++++++++--------
src/interfaces/libpq/fe-protocol3.c | 320 +++++++++++++++++++++++++-----------
src/interfaces/libpq/libpq-int.h | 4 +-
5 files changed, 382 insertions(+), 182 deletions(-)
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index a45f4cb..9772f7c 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -2366,11 +2366,18 @@ keep_going: /* We will come back to here until there is
{
if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
{
- if (pqGetErrorNotice3(conn, true))
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
{
/* We'll come back when there is more data */
return PGRES_POLLING_READING;
}
+ else if (res == -2)
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ goto error_return;
+ }
}
else
{
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..754d7f3 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -62,7 +62,7 @@ static int PQsendQueryGuts(PGconn *conn,
const int *paramLengths,
const int *paramFormats,
int resultFormat);
-static void parseInput(PGconn *conn);
+static int parseInput(PGconn *conn);
static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
static bool PQexecStart(PGconn *conn);
static PGresult *PQexecFinish(PGconn *conn);
@@ -1573,7 +1573,7 @@ pqHandleSendFailure(PGconn *conn)
* Parse any available input messages. Since we are in PGASYNC_IDLE
* state, only NOTICE and NOTIFY messages will be eaten.
*/
- parseInput(conn);
+ (void) parseInput(conn);
}
/*
@@ -1641,14 +1641,16 @@ PQconsumeInput(PGconn *conn)
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF if an error occurs.
*/
-static void
+static int
parseInput(PGconn *conn)
{
if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
- pqParseInput3(conn);
+ return pqParseInput3(conn);
else
- pqParseInput2(conn);
+ return pqParseInput2(conn);
}
/*
@@ -1663,7 +1665,8 @@ PQisBusy(PGconn *conn)
return FALSE;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return FALSE;
/* PQgetResult will return immediately in all states except BUSY. */
return conn->asyncStatus == PGASYNC_BUSY;
@@ -1686,7 +1689,8 @@ PQgetResult(PGconn *conn)
return NULL;
/* Parse any available data, if our state permits. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
/* If not ready to return something, block until we are. */
while (conn->asyncStatus == PGASYNC_BUSY)
@@ -1721,7 +1725,8 @@ PQgetResult(PGconn *conn)
}
/* Parse it. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
}
/* Return the appropriate thing. */
@@ -2177,7 +2182,8 @@ PQnotifies(PGconn *conn)
return NULL;
/* Parse any available data to see if we can extract NOTIFY messages. */
- parseInput(conn);
+ if (parseInput(conn))
+ return NULL;
event = conn->notifyHead;
if (event)
@@ -2217,7 +2223,8 @@ PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
* input data into the input buffer happens down inside pqSendSome, but
* it's not authorized to get rid of the data again.)
*/
- parseInput(conn);
+ if (parseInput(conn))
+ return -1;
if (nbytes > 0)
{
diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
index eeba7f3..5ac3d9a 100644
--- a/src/interfaces/libpq/fe-protocol2.c
+++ b/src/interfaces/libpq/fe-protocol2.c
@@ -406,8 +406,10 @@ error_return:
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if successfully parsed input.
+ * returns EOF if an error occurs.
*/
-void
+int
pqParseInput2(PGconn *conn)
{
char id;
@@ -424,14 +426,14 @@ pqParseInput2(PGconn *conn)
* protocol and have identifying leading characters.)
*/
if (conn->asyncStatus == PGASYNC_COPY_OUT)
- return;
+ return 0;
/*
* OK to try to read a message type code.
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
/*
* NOTIFY and NOTICE messages can happen in any state besides COPY
@@ -447,18 +449,21 @@ pqParseInput2(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
- if (pqGetErrorNotice2(conn, false))
- return;
+ int res = pqGetErrorNotice2(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -470,8 +475,12 @@ pqParseInput2(PGconn *conn)
*/
if (id == 'E')
{
- if (pqGetErrorNotice2(conn, false /* treat as notice */ ))
- return;
+ /* treat as notice */
+ int res = pqGetErrorNotice2(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else
{
@@ -492,13 +501,13 @@ pqParseInput2(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
@@ -506,9 +515,14 @@ pqParseInput2(PGconn *conn)
conn->asyncStatus = PGASYNC_READY;
break;
case 'E': /* error return */
- if (pqGetErrorNotice2(conn, true))
- return;
- conn->asyncStatus = PGASYNC_READY;
+ {
+ int res = pqGetErrorNotice2(conn, true);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_READY;
+ }
break;
case 'Z': /* backend is ready for new query */
conn->asyncStatus = PGASYNC_IDLE;
@@ -516,7 +530,7 @@ pqParseInput2(PGconn *conn)
case 'I': /* empty query */
/* read and throw away the closing '\0' */
if (pqGetc(&id, conn))
- return;
+ return 0;
if (id != '\0')
pqInternalNotice(&conn->noticeHooks,
"unexpected character %c following empty query response (\"I\" message)",
@@ -524,6 +538,8 @@ pqParseInput2(PGconn *conn)
if (conn->result == NULL)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
+ if (conn->result == NULL)
+ goto failure;
conn->asyncStatus = PGASYNC_READY;
break;
case 'K': /* secret key data from the backend */
@@ -534,21 +550,24 @@ pqParseInput2(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'P': /* synchronous (normal) portal */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
/* We pretty much ignore this message type... */
break;
case 'T': /* row descriptions (start of query results) */
if (conn->result == NULL)
{
+ int res = getRowDescriptions(conn);
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn))
- return;
+ if (res == -1)
+ return 0;
+ if (res == -2)
+ goto failure;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -562,15 +581,17 @@ pqParseInput2(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'D': /* ASCII data tuple */
if (conn->result != NULL)
{
- /* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, FALSE))
- return;
+ int res = getAnotherTuple(conn, FALSE);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -580,15 +601,17 @@ pqParseInput2(PGconn *conn)
"server sent data (\"D\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'B': /* Binary data tuple */
if (conn->result != NULL)
{
- /* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, TRUE))
- return;
+ int res = getAnotherTuple(conn, TRUE);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -598,7 +621,7 @@ pqParseInput2(PGconn *conn)
"server sent binary data (\"B\" message) without prior row description (\"T\" message)");
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
- return;
+ return 0;
}
break;
case 'G': /* Start Copy In */
@@ -622,19 +645,28 @@ pqParseInput2(PGconn *conn)
/* Discard the unexpected message; good idea?? */
conn->inStart = conn->inEnd;
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
} /* switch on protocol character */
}
/* Successfully consumed this message */
conn->inStart = conn->inCursor;
}
+
+ /* we are done */
+ return 0;
+
+failure:
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ return EOF;
}
/*
* parseInput subroutine to read a 'T' (row descriptions) message.
* We build a PGresult structure containing the attribute data.
- * Returns: 0 if completed message, EOF if error or not enough data
- * received yet.
+ * Returns: 0 if completed message.
+ * -1 if error or not enough data received yet.
+ * -2 in case of OOM.
*
* Note that if we run out of data, we have to suspend and reprocess
* the message after more data is received. Otherwise, conn->inStart
@@ -643,22 +675,26 @@ pqParseInput2(PGconn *conn)
static int
getRowDescriptions(PGconn *conn)
{
- PGresult *result;
+ PGresult *result = NULL;
int nfields;
- const char *errmsg;
+ const char *errmsg = NULL;
int i;
+ int status = 0;
result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
if (!result)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
/* parseInput already read the 'T' label. */
/* the next two bytes are the number of fields */
if (pqGetInt(&(result->numAttributes), 2, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -668,7 +704,7 @@ getRowDescriptions(PGconn *conn)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
@@ -685,7 +721,10 @@ getRowDescriptions(PGconn *conn)
pqGetInt(&typid, 4, conn) ||
pqGetInt(&typlen, 2, conn) ||
pqGetInt(&atttypmod, 4, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -697,7 +736,7 @@ getRowDescriptions(PGconn *conn)
conn->workBuffer.data);
if (!result->attDescs[i].name)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
result->attDescs[i].tableid = 0;
@@ -720,7 +759,7 @@ getRowDescriptions(PGconn *conn)
*/
/* And we're done. */
- return 0;
+ return status;
advance_and_error:
@@ -738,15 +777,10 @@ advance_and_error:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ if (errmsg != NULL)
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
/*
* XXX: if PQmakeEmptyPGresult() fails, there's probably not much we can
@@ -758,14 +792,15 @@ advance_and_error:
EOFexit:
if (result && result != conn->result)
PQclear(result);
- return EOF;
+ return status;
}
/*
* parseInput subroutine to read a 'B' or 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if completed message, EOF if error or not enough data
- * received yet.
+ * Returns: 0 if processed message successfully.
+ * -1 if not enough data.
+ * -2 if an OOM error happened.
*
* Note that if we run out of data, we have to suspend and reprocess
* the message after more data is received. Otherwise, conn->inStart
@@ -776,8 +811,9 @@ getAnotherTuple(PGconn *conn, bool binary)
{
PGresult *result = conn->result;
int nfields = result->numAttributes;
- const char *errmsg;
+ const char *errmsg = NULL;
PGdataValue *rowbuf;
+ int status = 0;
/* the backend sends us a bitmap of which attributes are null */
char std_bitmap[64]; /* used unless it doesn't fit */
@@ -797,7 +833,7 @@ getAnotherTuple(PGconn *conn, bool binary)
nfields * sizeof(PGdataValue));
if (!rowbuf)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
conn->rowBuf = rowbuf;
@@ -825,13 +861,16 @@ getAnotherTuple(PGconn *conn, bool binary)
bitmap = (char *) malloc(nbytes);
if (!bitmap)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
}
if (pqGetnchar(bitmap, nbytes, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
/* Scan the fields */
bitmap_index = 0;
@@ -844,7 +883,10 @@ getAnotherTuple(PGconn *conn, bool binary)
if (!(bmap & 0200))
vlen = NULL_LEN;
else if (pqGetInt(&vlen, 4, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
else
{
if (!binary)
@@ -865,7 +907,10 @@ getAnotherTuple(PGconn *conn, bool binary)
if (vlen > 0)
{
if (pqSkipnchar(vlen, conn))
+ {
+ status = -1;
goto EOFexit;
+ }
}
/* advance the bitmap stuff */
@@ -913,15 +958,13 @@ set_error_result:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ if (errmsg != NULL)
+ {
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+ }
/*
* XXX: if PQmakeEmptyPGresult() fails, there's probably not much we can
@@ -933,7 +976,7 @@ set_error_result:
EOFexit:
if (bitmap != NULL && bitmap != std_bitmap)
free(bitmap);
- return EOF;
+ return status;
}
@@ -942,7 +985,8 @@ EOFexit:
* This is possible in several places, so we break it out as a subroutine.
* Entry: 'E' or 'N' message type has already been consumed.
* Exit: returns 0 if successfully consumed message.
- * returns EOF if not enough data.
+ * returns -1 if not enough data.
+ * returns -2 in case of out-of-memory.
*/
static int
pqGetErrorNotice2(PGconn *conn, bool isError)
@@ -951,6 +995,7 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
PQExpBufferData workBuf;
char *startp;
char *splitp;
+ int status = 0;
/*
* Since the message might be pretty long, we create a temporary
@@ -959,7 +1004,10 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
*/
initPQExpBuffer(&workBuf);
if (pqGets(&workBuf, conn))
+ {
+ status = -1;
goto failure;
+ }
/*
* Make a PGresult to hold the message. We temporarily lie about the
@@ -968,11 +1016,17 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
if (!res)
+ {
+ status = -2;
goto failure;
+ }
res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
res->errMsg = pqResultStrdup(res, workBuf.data);
if (!res->errMsg)
+ {
+ status = -2;
goto failure;
+ }
/*
* Break the message into fields. We can't do very much here, but we can
@@ -1036,13 +1090,13 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
}
termPQExpBuffer(&workBuf);
- return 0;
+ return status;
failure:
if (res)
PQclear(res);
termPQExpBuffer(&workBuf);
- return EOF;
+ return status;
}
/*
@@ -1521,9 +1575,14 @@ pqFunctionCall2(PGconn *conn, Oid fnid,
}
break;
case 'E': /* error return */
- if (pqGetErrorNotice2(conn, true))
- continue;
- status = PGRES_FATAL_ERROR;
+ {
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'A': /* notify message */
/* handle notify and go back to processing return values */
@@ -1531,9 +1590,14 @@ pqFunctionCall2(PGconn *conn, Oid fnid,
continue;
break;
case 'N': /* notice */
- /* handle notice and go back to processing return values */
- if (pqGetErrorNotice2(conn, false))
- continue;
+ {
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'Z': /* backend is ready for new query */
/* consume the message and exit */
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index a847f08..58382e0 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -61,8 +61,10 @@ static int build_startup_packet(const PGconn *conn, char *packet,
* parseInput: if appropriate, parse input data from backend
* until input is exhausted or a stopping state is reached.
* Note that this function will NOT attempt to read more data from the backend.
+ * Exit: returns 0 if message is successfully parsed.
+ * returns EOF if an error occurs.
*/
-void
+int
pqParseInput3(PGconn *conn)
{
char id;
@@ -80,9 +82,9 @@ pqParseInput3(PGconn *conn)
*/
conn->inCursor = conn->inStart;
if (pqGetc(&id, conn))
- return;
+ return 0;
if (pqGetInt(&msgLength, 4, conn))
- return;
+ return 0;
/*
* Try to validate message type/length here. A length less than 4 is
@@ -92,12 +94,12 @@ pqParseInput3(PGconn *conn)
if (msgLength < 4)
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
{
handleSyncLoss(conn, id, msgLength);
- return;
+ return 0;
}
/*
@@ -126,7 +128,7 @@ pqParseInput3(PGconn *conn)
*/
handleSyncLoss(conn, id, msgLength);
}
- return;
+ return 0;
}
/*
@@ -148,18 +150,21 @@ pqParseInput3(PGconn *conn)
if (id == 'A')
{
if (getNotify(conn))
- return;
+ return 0;
}
else if (id == 'N')
{
- if (pqGetErrorNotice3(conn, false))
- return;
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else if (conn->asyncStatus != PGASYNC_BUSY)
{
/* If not IDLE state, just wait ... */
if (conn->asyncStatus != PGASYNC_IDLE)
- return;
+ return 0;
/*
* Unexpected message in IDLE state; need to recover somehow.
@@ -172,13 +177,17 @@ pqParseInput3(PGconn *conn)
*/
if (id == 'E')
{
- if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
- return;
+ /* treat as notice */
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
}
else if (id == 'S')
{
if (getParameterStatus(conn))
- return;
+ return 0;
}
else
{
@@ -198,26 +207,31 @@ pqParseInput3(PGconn *conn)
{
case 'C': /* command complete */
if (pqGets(&conn->workBuffer, conn))
- return;
+ return 0;
if (conn->result == NULL)
{
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
CMDSTATUS_LEN);
conn->asyncStatus = PGASYNC_READY;
break;
case 'E': /* error return */
- if (pqGetErrorNotice3(conn, true))
- return;
- conn->asyncStatus = PGASYNC_READY;
+ {
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_READY;
+ }
break;
case 'Z': /* backend is ready for new query */
if (getReadyForQuery(conn))
- return;
+ return 0;
conn->asyncStatus = PGASYNC_IDLE;
break;
case 'I': /* empty query */
@@ -226,7 +240,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
break;
@@ -239,7 +253,7 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -250,7 +264,7 @@ pqParseInput3(PGconn *conn)
break;
case 'S': /* parameter status */
if (getParameterStatus(conn))
- return;
+ return 0;
break;
case 'K': /* secret key data from the backend */
@@ -260,17 +274,20 @@ pqParseInput3(PGconn *conn)
* Save the data and continue processing.
*/
if (pqGetInt(&(conn->be_pid), 4, conn))
- return;
+ return 0;
if (pqGetInt(&(conn->be_key), 4, conn))
- return;
+ return 0;
break;
case 'T': /* Row Description */
if (conn->result == NULL ||
conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn, msgLength))
- return;
+ int res = getRowDescriptions(conn, msgLength);
+ if (res == -1)
+ return 0;
+ if (res == -2)
+ goto failure;
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -284,7 +301,7 @@ pqParseInput3(PGconn *conn)
* result.
*/
conn->asyncStatus = PGASYNC_READY;
- return;
+ return 0;
}
break;
case 'n': /* No Data */
@@ -306,22 +323,29 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ goto failure;
}
conn->asyncStatus = PGASYNC_READY;
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
- return;
+ {
+ int res = getParamDescriptions(conn);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
conn->result->resultStatus == PGRES_TUPLES_OK)
{
- /* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, msgLength))
- return;
+ int res = getAnotherTuple(conn, msgLength);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -345,21 +369,36 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
- return;
- conn->asyncStatus = PGASYNC_COPY_IN;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_IN);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_IN;
+ }
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
- return;
- conn->asyncStatus = PGASYNC_COPY_OUT;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_OUT);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_OUT;
+ conn->copy_already_done = 0;
+ }
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
- return;
- conn->asyncStatus = PGASYNC_COPY_BOTH;
- conn->copy_already_done = 0;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_BOTH);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ goto failure;
+ conn->asyncStatus = PGASYNC_COPY_BOTH;
+ conn->copy_already_done = 0;
+ }
break;
case 'd': /* Copy Data */
@@ -412,6 +451,14 @@ pqParseInput3(PGconn *conn)
conn->inStart += 5 + msgLength;
}
}
+
+ /* we are done */
+ return 0;
+
+failure:
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ return EOF;
}
/*
@@ -438,8 +485,9 @@ handleSyncLoss(PGconn *conn, char id, int msgLength)
* parseInput subroutine to read a 'T' (row descriptions) message.
* We'll build a new PGresult structure (unless called for a Describe
* command for a prepared statement) containing the attribute data.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
+ * Returns: 0 if processed message successfully.
+ * -1 if not enough data.
+ * -2 in case of OOM error.
* In either case, conn->inStart has been advanced past the message.
*/
static int
@@ -447,8 +495,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nfields;
- const char *errmsg;
+ const char *errmsg = NULL;
int i;
+ int status = 0;
/*
* When doing Describe for a prepared statement, there'll already be a
@@ -466,7 +515,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
if (!result)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
@@ -476,6 +525,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"T\" message");
+ status = -1;
goto advance_and_error;
}
nfields = result->numAttributes;
@@ -487,7 +537,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
@@ -516,6 +566,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"T\" message");
+ status = -1;
goto advance_and_error;
}
@@ -531,7 +582,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
conn->workBuffer.data);
if (!result->attDescs[i].name)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
result->attDescs[i].tableid = tableid;
@@ -549,6 +600,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
if (conn->inCursor != conn->inStart + 5 + msgLength)
{
errmsg = libpq_gettext("extraneous data in \"T\" message");
+ status = -1;
goto advance_and_error;
}
@@ -574,7 +626,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
*/
/* And we're done. */
- return 0;
+ return status;
advance_and_error:
/* Discard unsaved result, if any */
@@ -591,29 +643,30 @@ advance_and_error:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
- pqSaveErrorResult(conn);
+ if (errmsg != NULL)
+ {
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+ }
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return -1 to allow input parsing to continue in case of error.
+ * Subsequent "D" messages will be ignored until we get to end of
+ * data in this case, since an error result is already set up. If
+ * an out-of-memory happens, bail out immediately though and let
+ * the caller know that.
*/
- return 0;
+ return status;
}
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message
+ * -1 if not enough data yet.
+ * -2 in case of an OOM error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
@@ -625,15 +678,22 @@ getParamDescriptions(PGconn *conn)
PGresult *result;
int nparams;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -642,7 +702,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -652,24 +715,29 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
+ {
+ res = -1;
goto failure;
+ }
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
* parseInput subroutine to read a 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
+ * Returns: 0 if processed message successfully.
+ * -1 if not enough data.
+ * -2 if an OOM error happened.
* In either case, conn->inStart has been advanced past the message.
*/
static int
@@ -677,23 +745,26 @@ getAnotherTuple(PGconn *conn, int msgLength)
{
PGresult *result = conn->result;
int nfields = result->numAttributes;
- const char *errmsg;
+ const char *errmsg = NULL;
PGdataValue *rowbuf;
int tupnfields; /* # fields from tuple */
int vlen; /* length of the current field value */
int i;
+ int status = 0;
/* Get the field count and make sure it's what we expect */
if (pqGetInt(&tupnfields, 2, conn))
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
if (tupnfields != nfields)
{
errmsg = libpq_gettext("unexpected field count in \"D\" message");
+ status = -1;
goto advance_and_error;
}
@@ -705,7 +776,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
nfields * sizeof(PGdataValue));
if (!rowbuf)
{
- errmsg = NULL; /* means "out of memory", see below */
+ status = -2;
goto advance_and_error;
}
conn->rowBuf = rowbuf;
@@ -720,6 +791,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
rowbuf[i].len = vlen;
@@ -738,6 +810,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
}
@@ -747,6 +820,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
if (conn->inCursor != conn->inStart + 5 + msgLength)
{
errmsg = libpq_gettext("extraneous data in \"D\" message");
+ status = -1;
goto advance_and_error;
}
@@ -756,7 +830,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
/* Process the collected row */
errmsg = NULL;
if (pqRowProcessor(conn, &errmsg))
- return 0; /* normal, successful exit */
+ return status; /* normal, successful exit */
goto set_error_result; /* pqRowProcessor failed, report it */
@@ -773,23 +847,19 @@ set_error_result:
pqClearAsyncResult(conn);
/*
- * If preceding code didn't provide an error message, assume "out of
- * memory" was meant. The advantage of having this special case is that
- * freeing the old result first greatly improves the odds that gettext()
- * will succeed in providing a translation.
+ * If preceding code has set an error message, save it.
*/
- if (!errmsg)
- errmsg = libpq_gettext("out of memory for query result");
-
- printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
- pqSaveErrorResult(conn);
+ if (errmsg != NULL)
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return -1 to allow input parsing to continue in case of error.
+ * Subsequent "D" messages will be ignored until we get to end of
+ * data in this case, since an error result is already set up. If
+ * an out-of-memory happens, bail out immediately though and let
+ * the caller know that.
*/
- return 0;
+ return status;
}
@@ -798,7 +868,8 @@ set_error_result:
* This is possible in several places, so we break it out as a subroutine.
* Entry: 'E' or 'N' message type and length have already been consumed.
* Exit: returns 0 if successfully consumed message.
- * returns EOF if not enough data.
+ * returns -1 if not enough data.
+ * returns -2 in case of out-of-memory.
*/
int
pqGetErrorNotice3(PGconn *conn, bool isError)
@@ -809,6 +880,7 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
const char *val;
const char *querytext = NULL;
int querypos = 0;
+ int status = 0;
/*
* Since the fields might be pretty long, we create a temporary
@@ -825,7 +897,10 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
if (!res)
+ {
+ status = -2;
goto fail;
+ }
res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
/*
@@ -834,11 +909,17 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
for (;;)
{
if (pqGetc(&id, conn))
+ {
+ status = -1;
goto fail;
+ }
if (id == '\0')
break; /* terminator found */
if (pqGets(&workBuf, conn))
+ {
+ status = -1;
goto fail;
+ }
pqSaveMessageField(res, id, workBuf.data);
}
@@ -968,7 +1049,10 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
{
res->errMsg = pqResultStrdup(res, workBuf.data);
if (!res->errMsg)
+ {
+ status = -1;
goto fail;
+ }
pqClearAsyncResult(conn);
conn->result = res;
appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
@@ -983,12 +1067,12 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
}
termPQExpBuffer(&workBuf);
- return 0;
+ return status;
fail:
PQclear(res);
termPQExpBuffer(&workBuf);
- return EOF;
+ return status;
}
/*
@@ -1309,6 +1393,11 @@ getNotify(PGconn *conn)
* CopyBothResponse message
*
* parseInput already read the message type and length.
+ * Returns: 0 in case of success.
+ * -1 if there is not enough data. In this case parsing should
+ * continue later on.
+ * -2 in case of an OOM error. In this case parsing should be
+ * suspended immediately.
*/
static int
getCopyStart(PGconn *conn, ExecStatusType copytype)
@@ -1316,17 +1405,27 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
PGresult *result;
int nfields;
int i;
+ int res = 0;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
+ {
+ res = -2;
goto failure;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
+ {
+ res = -1;
goto failure;
+ }
result->binary = conn->copy_is_binary;
/* the next two bytes are the number of fields */
if (pqGetInt(&(result->numAttributes), 2, conn))
+ {
+ res = -1;
goto failure;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1335,7 +1434,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
+ {
+ res = -2;
goto failure;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1344,7 +1446,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
+ {
+ res = -1;
goto failure;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1356,11 +1461,12 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
- return 0;
+ return res;
failure:
- PQclear(result);
- return EOF;
+ if (result)
+ PQclear(result);
+ return res;
}
/*
@@ -1457,8 +1563,13 @@ getCopyDataMessage(PGconn *conn)
return 0;
break;
case 'N': /* NOTICE */
- if (pqGetErrorNotice3(conn, false))
- return 0;
+ {
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ return 0;
+ else if (res == -2)
+ return -2;
+ }
break;
case 'S': /* ParameterStatus */
if (getParameterStatus(conn))
@@ -1922,9 +2033,14 @@ pqFunctionCall3(PGconn *conn, Oid fnid,
status = PGRES_COMMAND_OK;
break;
case 'E': /* error return */
- if (pqGetErrorNotice3(conn, true))
- continue;
- status = PGRES_FATAL_ERROR;
+ {
+ int res = pqGetErrorNotice3(conn, true);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'A': /* notify message */
/* handle notify and go back to processing return values */
@@ -1933,8 +2049,14 @@ pqFunctionCall3(PGconn *conn, Oid fnid,
break;
case 'N': /* notice */
/* handle notice and go back to processing return values */
- if (pqGetErrorNotice3(conn, false))
- continue;
+ {
+ int res = pqGetErrorNotice3(conn, false);
+ if (res == -1)
+ continue;
+ else if (res == -2)
+ return NULL;
+ status = PGRES_FATAL_ERROR;
+ }
break;
case 'Z': /* backend is ready for new query */
if (getReadyForQuery(conn))
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 2175957..235af89 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -559,7 +559,7 @@ extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput2(PGconn *conn);
+extern int pqParseInput2(PGconn *conn);
extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
extern int pqGetline2(PGconn *conn, char *s, int maxlen);
extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
@@ -573,7 +573,7 @@ extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
const PQEnvironmentOption *options);
-extern void pqParseInput3(PGconn *conn);
+extern int pqParseInput3(PGconn *conn);
extern int pqGetErrorNotice3(PGconn *conn, bool isError);
extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
extern int pqGetline3(PGconn *conn, char *s, int maxlen);
--
2.4.1
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-03 16:32 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2015-07-03 16:32 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; +Cc: hlinnaka@iki.fi, Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 05/26/2015 10:01 AM, Michael Paquier wrote:
> On Thu, May 21, 2015 at 1:31 AM, Oleksandr Shulgin wrote:
>> Michael Paquier <michael.paquier@gmail.com> writes:
>>> So, attached is take three for all the other things above.
>>
>> There's still one call to pqGetErrorNotice3 that doesn't check returned
>> value for -2, in fe-connect.c. Shouldn't we also check it like this:
>>
>> [...]
>
> Yes, you are right. Take 4 attached is updated with something similar
> to what you sent to cover this code path.
This is still a few bricks shy of a load. Before this patch, if you run
out of memory when allocating a large result set - which is probably the
most common reason for OOM in libpq - you got this error:
postgres=# select generate_series(1, 10000000);
out of memory for query result
With this patch, I got:
postgres=# select generate_series(1, 10000000);
server sent data ("D" message) without prior row description ("T" message)
Looking at the patch again, I think we should actually leave
getAnotherTuple() alone. It's a lot nicer if getAnotherTuple() can
handle the OOM error itself than propagating it to the caller.
There's only one caller for getAnotherTuple(), but for
pqGetErrorNotice3() the same is even more true: it would be much nicer
if it could handle OOM itself, without propagating it to the caller. And
it well could do so. When it's processing an ERROR, it could just set
conn->errorMessage to "out of memory", and discard the error it received
from the server. When processing a NOTICE, it could likewise just send
"out of memory" to the NOTICE processsor, and discard the message from
the server. The real problem with pqGetErrorNotice3() today is that it
treats OOM the same as "no data available yet", and we can fix that by
reading but discarding the backend message. Like getAnotherTuple() does.
In short, the idea of returning a status code from parseInput(), instead
of just dealing with the error, was a bad one. Sorry I didn't have this
epiphany earlier...
I came up with the attached. It fixes the few cases where we were
currently returning "need more data" when OOM happened, to deal with the
OOM error instead, by setting conn->errorMessage. How does this look to you?
- Heikki
--
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
improve-OOM-handling-in-libpq-2.patch (text/x-diff, 10.2K) download
diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
index eeba7f3..7299bea 100644
--- a/src/interfaces/libpq/fe-protocol2.c
+++ b/src/interfaces/libpq/fe-protocol2.c
@@ -498,10 +498,17 @@ pqParseInput2(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
+ }
+ if (conn->result)
+ {
+ strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
+ CMDSTATUS_LEN);
}
- strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
- CMDSTATUS_LEN);
checkXactStatus(conn, conn->workBuffer.data);
conn->asyncStatus = PGASYNC_READY;
break;
@@ -522,8 +529,16 @@ pqParseInput2(PGconn *conn)
"unexpected character %c following empty query response (\"I\" message)",
id);
if (conn->result == NULL)
+ {
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
+ if (!conn->result)
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
+ }
conn->asyncStatus = PGASYNC_READY;
break;
case 'K': /* secret key data from the backend */
@@ -633,8 +648,7 @@ pqParseInput2(PGconn *conn)
/*
* parseInput subroutine to read a 'T' (row descriptions) message.
* We build a PGresult structure containing the attribute data.
- * Returns: 0 if completed message, EOF if error or not enough data
- * received yet.
+ * Returns: 0 if completed message, EOF if not enough data received yet.
*
* Note that if we run out of data, we have to suspend and reprocess
* the message after more data is received. Otherwise, conn->inStart
@@ -755,6 +769,10 @@ advance_and_error:
conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
conn->asyncStatus = PGASYNC_READY;
+ if (result && result != conn->result)
+ PQclear(result);
+ return 0;
+
EOFexit:
if (result && result != conn->result)
PQclear(result);
@@ -764,8 +782,7 @@ EOFexit:
/*
* parseInput subroutine to read a 'B' or 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if completed message, EOF if error or not enough data
- * received yet.
+ * Returns: 0 if completed message, EOF if not enough data received yet.
*
* Note that if we run out of data, we have to suspend and reprocess
* the message after more data is received. Otherwise, conn->inStart
@@ -965,14 +982,17 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
* Make a PGresult to hold the message. We temporarily lie about the
* result status, so that PQmakeEmptyPGresult doesn't uselessly copy
* conn->errorMessage.
+ *
+ * NB: This allocation might fail, if you run out of memory. The rest of
+ * the function handles that gracefully, and we still try to set the error
+ * message as the connection's error message.
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
- if (!res)
- goto failure;
- res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
- res->errMsg = pqResultStrdup(res, workBuf.data);
- if (!res->errMsg)
- goto failure;
+ if (res)
+ {
+ res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
+ res->errMsg = pqResultStrdup(res, workBuf.data);
+ }
/*
* Break the message into fields. We can't do very much here, but we can
@@ -1024,15 +1044,22 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
pqClearAsyncResult(conn);
conn->result = res;
resetPQExpBuffer(&conn->errorMessage);
- appendPQExpBufferStr(&conn->errorMessage, res->errMsg);
+ if (res && !PQExpBufferDataBroken(workBuf))
+ appendPQExpBufferStr(&conn->errorMessage, res->errMsg);
+ else
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
if (conn->xactStatus == PQTRANS_INTRANS)
conn->xactStatus = PQTRANS_INERROR;
}
else
{
- if (res->noticeHooks.noticeRec != NULL)
- (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
- PQclear(res);
+ if (res)
+ {
+ if (res->noticeHooks.noticeRec != NULL)
+ (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
+ PQclear(res);
+ }
}
termPQExpBuffer(&workBuf);
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index a847f08..1a6a2c7 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -204,10 +204,15 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
- strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
- CMDSTATUS_LEN);
+ if (conn->result)
+ strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
+ CMDSTATUS_LEN);
conn->asyncStatus = PGASYNC_READY;
break;
case 'E': /* error return */
@@ -226,7 +231,11 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
conn->asyncStatus = PGASYNC_READY;
break;
@@ -239,7 +248,11 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -306,7 +319,11 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -628,7 +645,7 @@ getParamDescriptions(PGconn *conn)
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ goto oom_error;
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
@@ -642,7 +659,7 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ goto oom_error;
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -661,8 +678,18 @@ getParamDescriptions(PGconn *conn)
return 0;
failure:
- PQclear(result);
+ /* could not read the whole message */
+ if (result)
+ PQclear(result);
return EOF;
+
+oom_error:
+ if (result)
+ PQclear(result);
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ pqSaveErrorResult(conn);
+ return 0;
}
/*
@@ -822,11 +849,14 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
* Make a PGresult to hold the accumulated fields. We temporarily lie
* about the result status, so that PQmakeEmptyPGresult doesn't uselessly
* copy conn->errorMessage.
+ *
+ * NB: This allocation might fail, if you run out of memory. The rest of
+ * the function handles that gracefully, and we still try to set the error
+ * message as the connection's error message.
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
- if (!res)
- goto fail;
- res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
+ if (res)
+ res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
/*
* Read the fields and save into res.
@@ -966,20 +996,27 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
*/
if (isError)
{
- res->errMsg = pqResultStrdup(res, workBuf.data);
- if (!res->errMsg)
- goto fail;
+ if (res)
+ res->errMsg = pqResultStrdup(res, workBuf.data);
pqClearAsyncResult(conn);
conn->result = res;
- appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
+ if (PQExpBufferDataBroken(workBuf))
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ else
+ appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
}
else
{
- /* We can cheat a little here and not copy the message. */
- res->errMsg = workBuf.data;
- if (res->noticeHooks.noticeRec != NULL)
- (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
- PQclear(res);
+ /* if we couldn't allocate the result set, just discard the NOTICE */
+ if (res)
+ {
+ /* We can cheat a little here and not copy the message. */
+ res->errMsg = workBuf.data;
+ if (res->noticeHooks.noticeRec != NULL)
+ (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
+ PQclear(res);
+ }
}
termPQExpBuffer(&workBuf);
@@ -1309,6 +1346,7 @@ getNotify(PGconn *conn)
* CopyBothResponse message
*
* parseInput already read the message type and length.
+ * Returns 0 if successfully consumed the message, EOF if not enough data.
*/
static int
getCopyStart(PGconn *conn, ExecStatusType copytype)
@@ -1319,7 +1357,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ goto oom_error;
if (pqGetc(&conn->copy_is_binary, conn))
goto failure;
@@ -1335,7 +1373,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ goto oom_error;
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1359,8 +1397,17 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
return 0;
failure:
- PQclear(result);
+ if (result)
+ PQclear(result);
return EOF;
+
+oom_error:
+ if (result)
+ PQclear(result);
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory\n"));
+ pqSaveErrorResult(conn);
+ return 0;
}
/*
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-04 12:40 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-07-04 12:40 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Jul 4, 2015 at 1:32 AM, Heikki Linnakangas wrote:
> In short, the idea of returning a status code from parseInput(), instead of
> just dealing with the error, was a bad one. Sorry I didn't have this
> epiphany earlier...
>
> I came up with the attached. It fixes the few cases where we were currently
> returning "need more data" when OOM happened, to deal with the OOM error
> instead, by setting conn->errorMessage. How does this look to you?
So this relies on the fact that when errorMessage is set subsequent
messages are ignored, right? This looks neat.
At the bottom of getAnotherTuple() in fe-protocol2.c if
PQmakeEmptyPGresult returns NULL, shouldn't the error message be
enforced to "out of memory"? It is an error code path, so an error
will be set, but perhaps the message is incorrect.
- if (!res->errMsg)
- goto failure;
+ if (res)
+ {
+ res->resultStatus = isError ? PGRES_FATAL_ERROR :
PGRES_NONFATAL_ERROR;
+ res->errMsg = pqResultStrdup(res, workBuf.data);
+ }
If res->errMsg is NULL, we may have a crash later on when calling
appendPQExpBufferStr on this field. I think that we should add an
additional check on it.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-06 17:13 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2015-07-06 17:13 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 07/04/2015 03:40 PM, Michael Paquier wrote:
> On Sat, Jul 4, 2015 at 1:32 AM, Heikki Linnakangas wrote:
>> In short, the idea of returning a status code from parseInput(), instead of
>> just dealing with the error, was a bad one. Sorry I didn't have this
>> epiphany earlier...
>>
>> I came up with the attached. It fixes the few cases where we were currently
>> returning "need more data" when OOM happened, to deal with the OOM error
>> instead, by setting conn->errorMessage. How does this look to you?
>
> So this relies on the fact that when errorMessage is set subsequent
> messages are ignored, right? This looks neat.
>
> At the bottom of getAnotherTuple() in fe-protocol2.c if
> PQmakeEmptyPGresult returns NULL, shouldn't the error message be
> enforced to "out of memory"? It is an error code path, so an error
> will be set, but perhaps the message is incorrect.
>
> - if (!res->errMsg)
> - goto failure;
> + if (res)
> + {
> + res->resultStatus = isError ? PGRES_FATAL_ERROR :
> PGRES_NONFATAL_ERROR;
> + res->errMsg = pqResultStrdup(res, workBuf.data);
> + }
> If res->errMsg is NULL, we may have a crash later on when calling
> appendPQExpBufferStr on this field. I think that we should add an
> additional check on it.
Yeah, added.
I tested the various error paths this patch modifies with a debugger,
and found out that the getCopyStart changes were not doing much good.
The caller still waits for the COPY-IN result, so it still gets stuck.
So I left out that change.
The getParamDescriptions() changes were slightly broken. It didn't read
the whole input message with pqGetInt() etc., so pqParseInput3() threw
the "message contents do not agree with length in message type" error. I
started fixing that, by changing the error handling in that function to
be more like that in getRowDescriptions(), but then I realized that all
the EOF return cases in the pqParseInput3() subroutines are actually
dead code. pqParseInput3() always reads the whole message, before
passing it on to the right subroutine. That was documented for
getRowDescriptions() and getAnotherTuple(), but the rest of the
functions were more like the protocol version 2 code, prepared to deal
with incomplete messages. I think it would be good to refactor that,
removing the EOF return cases altogether. So I left out that change for
now as well.
That left me with the attached patch. It doesn't handle the
getParamDescription() case, nor the getCopyStart() case, but it's a
start. We don't necessarily need to fix everything in one go. Does this
look correct to you, as far as it goes?
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
improve-OOM-handling-in-libpq-3.patch (text/x-diff, 6.9K) download
diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
index eeba7f3..9ff73db 100644
--- a/src/interfaces/libpq/fe-protocol2.c
+++ b/src/interfaces/libpq/fe-protocol2.c
@@ -498,10 +498,17 @@ pqParseInput2(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
+ }
+ if (conn->result)
+ {
+ strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
+ CMDSTATUS_LEN);
}
- strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
- CMDSTATUS_LEN);
checkXactStatus(conn, conn->workBuffer.data);
conn->asyncStatus = PGASYNC_READY;
break;
@@ -522,8 +529,16 @@ pqParseInput2(PGconn *conn)
"unexpected character %c following empty query response (\"I\" message)",
id);
if (conn->result == NULL)
+ {
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
+ if (!conn->result)
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
+ }
conn->asyncStatus = PGASYNC_READY;
break;
case 'K': /* secret key data from the backend */
@@ -965,14 +980,17 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
* Make a PGresult to hold the message. We temporarily lie about the
* result status, so that PQmakeEmptyPGresult doesn't uselessly copy
* conn->errorMessage.
+ *
+ * NB: This allocation can fail, if you run out of memory. The rest of the
+ * function handles that gracefully, and we still try to set the error
+ * message as the connection's error message.
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
- if (!res)
- goto failure;
- res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
- res->errMsg = pqResultStrdup(res, workBuf.data);
- if (!res->errMsg)
- goto failure;
+ if (res)
+ {
+ res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
+ res->errMsg = pqResultStrdup(res, workBuf.data);
+ }
/*
* Break the message into fields. We can't do very much here, but we can
@@ -1024,15 +1042,22 @@ pqGetErrorNotice2(PGconn *conn, bool isError)
pqClearAsyncResult(conn);
conn->result = res;
resetPQExpBuffer(&conn->errorMessage);
- appendPQExpBufferStr(&conn->errorMessage, res->errMsg);
+ if (res && !PQExpBufferDataBroken(workBuf) && res->errMsg)
+ appendPQExpBufferStr(&conn->errorMessage, res->errMsg);
+ else
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
if (conn->xactStatus == PQTRANS_INTRANS)
conn->xactStatus = PQTRANS_INERROR;
}
else
{
- if (res->noticeHooks.noticeRec != NULL)
- (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
- PQclear(res);
+ if (res)
+ {
+ if (res->noticeHooks.noticeRec != NULL)
+ (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
+ PQclear(res);
+ }
}
termPQExpBuffer(&workBuf);
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index a847f08..dbc0d89 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -204,10 +204,15 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
- strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
- CMDSTATUS_LEN);
+ if (conn->result)
+ strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
+ CMDSTATUS_LEN);
conn->asyncStatus = PGASYNC_READY;
break;
case 'E': /* error return */
@@ -226,7 +231,11 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_EMPTY_QUERY);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
conn->asyncStatus = PGASYNC_READY;
break;
@@ -239,7 +248,11 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -306,7 +319,11 @@ pqParseInput3(PGconn *conn)
conn->result = PQmakeEmptyPGresult(conn,
PGRES_COMMAND_OK);
if (!conn->result)
- return;
+ {
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ pqSaveErrorResult(conn);
+ }
}
conn->asyncStatus = PGASYNC_READY;
}
@@ -822,11 +839,14 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
* Make a PGresult to hold the accumulated fields. We temporarily lie
* about the result status, so that PQmakeEmptyPGresult doesn't uselessly
* copy conn->errorMessage.
+ *
+ * NB: This allocation can fail, if you run out of memory. The rest of the
+ * function handles that gracefully, and we still try to set the error
+ * message as the connection's error message.
*/
res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
- if (!res)
- goto fail;
- res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
+ if (res)
+ res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
/*
* Read the fields and save into res.
@@ -966,20 +986,27 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
*/
if (isError)
{
- res->errMsg = pqResultStrdup(res, workBuf.data);
- if (!res->errMsg)
- goto fail;
+ if (res)
+ res->errMsg = pqResultStrdup(res, workBuf.data);
pqClearAsyncResult(conn);
conn->result = res;
- appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
+ if (PQExpBufferDataBroken(workBuf))
+ printfPQExpBuffer(&conn->errorMessage,
+ libpq_gettext("out of memory"));
+ else
+ appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
}
else
{
- /* We can cheat a little here and not copy the message. */
- res->errMsg = workBuf.data;
- if (res->noticeHooks.noticeRec != NULL)
- (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
- PQclear(res);
+ /* if we couldn't allocate the result set, just discard the NOTICE */
+ if (res)
+ {
+ /* We can cheat a little here and not copy the message. */
+ res->errMsg = workBuf.data;
+ if (res->noticeHooks.noticeRec != NULL)
+ (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
+ PQclear(res);
+ }
}
termPQExpBuffer(&workBuf);
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-07 06:31 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-07-07 06:31 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Tue, Jul 7, 2015 at 2:13 AM, Heikki Linnakangas wrote:
> The getParamDescriptions() changes were slightly broken. It didn't read the
> whole input message with pqGetInt() etc., so pqParseInput3() threw the
> "message contents do not agree with length in message type" error. I started
> fixing that, by changing the error handling in that function to be more like
> that in getRowDescriptions(), but then I realized that all the EOF return
> cases in the pqParseInput3() subroutines are actually dead code.
> pqParseInput3() always reads the whole message, before passing it on to the
> right subroutine. That was documented for getRowDescriptions() and
> getAnotherTuple(), but the rest of the functions were more like the protocol
> version 2 code, prepared to deal with incomplete messages. I think it would
> be good to refactor that, removing the EOF return cases altogether. So I
> left out that change for now as well.
Yes, (the latter case is not actually used currently). Well, I don't
mind writing the additional patch to update . On top of that The
refactoring should be a master-only change, perhaps?
> That left me with the attached patch. It doesn't handle the
> getParamDescription() case, nor the getCopyStart() case, but it's a start.
> We don't necessarily need to fix everything in one go. Does this look
> correct to you, as far as it goes?
I have been carefully through the routines modified, doing some tests
at the same time and I haven't spotted an issue.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-07 06:32 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-07-07 06:32 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Tue, Jul 7, 2015 at 3:31 PM, Michael Paquier
<michael.paquier@gmail.com> wrote:
> On Tue, Jul 7, 2015 at 2:13 AM, Heikki Linnakangas wrote:
>> The getParamDescriptions() changes were slightly broken. It didn't read the
>> whole input message with pqGetInt() etc., so pqParseInput3() threw the
>> "message contents do not agree with length in message type" error. I started
>> fixing that, by changing the error handling in that function to be more like
>> that in getRowDescriptions(), but then I realized that all the EOF return
>> cases in the pqParseInput3() subroutines are actually dead code.
>> pqParseInput3() always reads the whole message, before passing it on to the
>> right subroutine. That was documented for getRowDescriptions() and
>> getAnotherTuple(), but the rest of the functions were more like the protocol
>> version 2 code, prepared to deal with incomplete messages. I think it would
>> be good to refactor that, removing the EOF return cases altogether. So I
>> left out that change for now as well.
>
> Yes, (the latter case is not actually used currently). Well, I don't
> mind writing the additional patch to update . On top of that The
> refactoring should be a master-only change, perhaps?
I pushed the send button too early.
I don't mind writing the additional patch for the other routines,
patch that should be backpatched, and the refactoring patch
(master-only?).
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-07 16:01 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2015-07-07 16:01 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 07/07/2015 09:32 AM, Michael Paquier wrote:
> On Tue, Jul 7, 2015 at 3:31 PM, Michael Paquier
> <michael.paquier@gmail.com> wrote:
>> On Tue, Jul 7, 2015 at 2:13 AM, Heikki Linnakangas wrote:
>>> The getParamDescriptions() changes were slightly broken. It didn't read the
>>> whole input message with pqGetInt() etc., so pqParseInput3() threw the
>>> "message contents do not agree with length in message type" error. I started
>>> fixing that, by changing the error handling in that function to be more like
>>> that in getRowDescriptions(), but then I realized that all the EOF return
>>> cases in the pqParseInput3() subroutines are actually dead code.
>>> pqParseInput3() always reads the whole message, before passing it on to the
>>> right subroutine. That was documented for getRowDescriptions() and
>>> getAnotherTuple(), but the rest of the functions were more like the protocol
>>> version 2 code, prepared to deal with incomplete messages. I think it would
>>> be good to refactor that, removing the EOF return cases altogether. So I
>>> left out that change for now as well.
>>
>> Yes, (the latter case is not actually used currently). Well, I don't
>> mind writing the additional patch to update . On top of that The
>> refactoring should be a master-only change, perhaps?
>
> I pushed the send button too early.
> I don't mind writing the additional patch for the other routines,
> patch that should be backpatched, and the refactoring patch
> (master-only?).
Ok, committed and backpatched the latest patch I posted. Yeah, we'll
need additional patches for the refactoring and the remaining issues.
I'm not sure if it's worth trying to backpatch them; let's see how big
the patch is.
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-09 13:04 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 2 replies; 48+ messages in thread
From: Michael Paquier @ 2015-07-09 13:04 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Wed, Jul 8, 2015 at 1:01 AM, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> On 07/07/2015 09:32 AM, Michael Paquier wrote:
>>
>> On Tue, Jul 7, 2015 at 3:31 PM, Michael Paquier
>> <michael.paquier@gmail.com> wrote:
>>>
>>> On Tue, Jul 7, 2015 at 2:13 AM, Heikki Linnakangas wrote:
>>>>
>>>> The getParamDescriptions() changes were slightly broken. It didn't read
>>>> the
>>>> whole input message with pqGetInt() etc., so pqParseInput3() threw the
>>>> "message contents do not agree with length in message type" error. I
>>>> started
>>>> fixing that, by changing the error handling in that function to be more
>>>> like
>>>> that in getRowDescriptions(), but then I realized that all the EOF
>>>> return
>>>> cases in the pqParseInput3() subroutines are actually dead code.
>>>> pqParseInput3() always reads the whole message, before passing it on to
>>>> the
>>>> right subroutine. That was documented for getRowDescriptions() and
>>>> getAnotherTuple(), but the rest of the functions were more like the
>>>> protocol
>>>> version 2 code, prepared to deal with incomplete messages. I think it
>>>> would
>>>> be good to refactor that, removing the EOF return cases altogether. So I
>>>> left out that change for now as well.
>>>
>>>
>>> Yes, (the latter case is not actually used currently). Well, I don't
>>> mind writing the additional patch to update . On top of that The
>>> refactoring should be a master-only change, perhaps?
>>
>>
>> I pushed the send button too early.
>> I don't mind writing the additional patch for the other routines,
>> patch that should be backpatched, and the refactoring patch
>> (master-only?).
>
>
> Ok, committed and backpatched the latest patch I posted. Yeah, we'll need
> additional patches for the refactoring and the remaining issues. I'm not
> sure if it's worth trying to backpatch them; let's see how big the patch is.
So, here are two patches aimed at fixing the hangling issues with
getStartCopy and getParamDescriptions. After trying a couple of
approaches, I found out that the most elegant way to prevent the
infinite loop in parseInput is to introduce a new PGASYNC flag to
control the error and let the caller know what happened.
More refactoring could be done, and I think that the use of this new
ASYNC flag could be spread to other places as well if you think that's
a useful. For now I have focused only on fixing the existing problems
with fixes that are rather back-patchable.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (2 files, .tar.gz)
0001-Prevent-COPY-start-from-hangling-in-libpq-on-OOM.patch (text/x-diff, 6.4K) download
From 7943d11f983a8654978a1db868b4a5e3ca22ec28 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Thu, 9 Jul 2015 12:49:31 +0000
Subject: [PATCH 1/2] Prevent COPY start from hangling in libpq on OOM
This commit improves the OOM error handling in getCopyStart of the
protocol 3 of libpq that could make process wait for caller if the
message is not consumed completely on client. When an OOM is found
out, register an error message indicating what has actually happened.
In order to allow the input parser to detect if a failure is happening
a new async flag called PGASYNC_FATAL is used to have a correct error
flow control.
---
src/interfaces/libpq/fe-exec.c | 3 ++
src/interfaces/libpq/fe-protocol3.c | 82 ++++++++++++++++++++++++++++++-------
src/interfaces/libpq/libpq-int.h | 3 +-
3 files changed, 72 insertions(+), 16 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..6c6eeaf 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1744,6 +1744,9 @@ PQgetResult(PGconn *conn)
case PGASYNC_COPY_BOTH:
res = getCopyResult(conn, PGRES_COPY_BOTH);
break;
+ case PGASYNC_FATAL:
+ res = NULL; /* some trouble happened */
+ break;
default:
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("unexpected asyncStatus: %d\n"),
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index dbc0d89..d0b22b7 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -49,7 +49,9 @@ static int getParamDescriptions(PGconn *conn);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -362,19 +364,28 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
conn->asyncStatus = PGASYNC_COPY_IN;
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
break;
@@ -1338,31 +1349,45 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
- if (nfields > 0)
+ if (result && nfields > 0)
{
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1371,22 +1396,49 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
* coerce these results to signed form.
*/
format = (int) ((int16) format);
- result->attDescs[i].format = format;
+ if (result && result->attDescs)
+ result->attDescs[i].format = format;
}
/* Success! */
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inCursor = conn->inStart + 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
return EOF;
}
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 2175957..5fe72eb 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -219,7 +219,8 @@ typedef enum
PGASYNC_READY, /* result ready for PQgetResult */
PGASYNC_COPY_IN, /* Copy In data transfer in progress */
PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
- PGASYNC_COPY_BOTH /* Copy In/Out data transfer in progress */
+ PGASYNC_COPY_BOTH, /* Copy In/Out data transfer in progress */
+ PGASYNC_FATAL /* Something awry happended during execution */
} PGAsyncStatusType;
/* PGQueryClass tracks which query protocol we are now executing */
--
2.4.5
0002-Prevent-hangling-of-libpq-for-BIND-message-results-o.patch (text/x-diff, 4.3K) download
From ba65eb6cd8dbd74d2d33a89d372982e4a940ca6c Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Thu, 9 Jul 2015 13:28:31 +0000
Subject: [PATCH 2/2] Prevent hangling of libpq for BIND message results on OOM
When failing on OOM, pqParseInput3, could finish in an infinite loop
state for this message. This commit improves the OOM error handling
of getParamDescriptions() to prevent that by using the new aaync flag
PGAYNC_FATAL.
---
src/interfaces/libpq/fe-protocol3.c | 61 ++++++++++++++++++++++++++++++-------
1 file changed, 50 insertions(+), 11 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index d0b22b7..f71cbe5 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,7 +45,7 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
@@ -331,8 +331,11 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -641,27 +644,34 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message, EOF in case of error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
- if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numParameters, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -670,7 +680,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -680,7 +693,10 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
result->paramDescs[i].typid = typid;
}
@@ -688,8 +704,31 @@ getParamDescriptions(PGconn *conn)
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inCursor = conn->inStart + 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
return EOF;
}
--
2.4.5
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-07-10 13:42 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 0 replies; 48+ messages in thread
From: Michael Paquier @ 2015-07-10 13:42 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Thu, Jul 9, 2015 at 10:04 PM, Michael Paquier
<michael.paquier@gmail.com>wrote:
> So, here are two patches aimed at fixing the hangling issues with
> getStartCopy and getParamDescriptions. After trying a couple of
> approaches, I found out that the most elegant way to prevent the
> infinite loop in parseInput is to introduce a new PGASYNC flag to
> control the error and let the caller know what happened.
>
> More refactoring could be done, and I think that the use of this new
> ASYNC flag could be spread to other places as well if you think that's
> a useful. For now I have focused only on fixing the existing problems
> with fixes that are rather back-patchable.
>
As those are actually new bug fixes, I am adding an entry in CF 2015-09.
--
Michael
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-08-29 13:35 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-08-29 13:35 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Thu, Jul 9, 2015 at 6:34 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
>
> On Wed, Jul 8, 2015 at 1:01 AM, Heikki Linnakangas <hlinnaka@iki.fi>
wrote:
> > On 07/07/2015 09:32 AM, Michael Paquier wrote:
> >
> >
> > Ok, committed and backpatched the latest patch I posted. Yeah, we'll
need
> > additional patches for the refactoring and the remaining issues. I'm not
> > sure if it's worth trying to backpatch them; let's see how big the
patch is.
>
> So, here are two patches aimed at fixing the hangling issues with
> getStartCopy and getParamDescriptions. After trying a couple of
> approaches, I found out that the most elegant way to prevent the
> infinite loop in parseInput is to introduce a new PGASYNC flag to
> control the error and let the caller know what happened.
One thing that looks slightly non-elegant about this approach is that
new async status (PGASYNC_FATAL) is used to deal with errors only
in few paths in function pqParseInput3() and not-other paths which should
be okay if there is no other better way. I have not spent enough time on
it to suggest any better alternative, but would like to hear what other
approaches you have considered?
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-08-31 07:25 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-08-31 07:25 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Aug 29, 2015 at 10:35 PM, Amit Kapila <amit.kapila16@gmail.com>
wrote:
> On Thu, Jul 9, 2015 at 6:34 PM, Michael Paquier <michael.paquier@gmail.com>
> wrote:
> >
> > On Wed, Jul 8, 2015 at 1:01 AM, Heikki Linnakangas <hlinnaka@iki.fi>
> wrote:
> > > On 07/07/2015 09:32 AM, Michael Paquier wrote:
> > >
> > >
> > > Ok, committed and backpatched the latest patch I posted. Yeah, we'll
> need
> > > additional patches for the refactoring and the remaining issues. I'm
> not
> > > sure if it's worth trying to backpatch them; let's see how big the
> patch is.
> >
> > So, here are two patches aimed at fixing the hangling issues with
> > getStartCopy and getParamDescriptions. After trying a couple of
> > approaches, I found out that the most elegant way to prevent the
> > infinite loop in parseInput is to introduce a new PGASYNC flag to
> > control the error and let the caller know what happened.
>
> One thing that looks slightly non-elegant about this approach is that
> new async status (PGASYNC_FATAL) is used to deal with errors only
> in few paths in function pqParseInput3() and not-other paths which should
> be okay if there is no other better way.
>
I considered using this logic in more code paths, but I kept focused on
having a not-too-invasive back-patchable patch as the refactoring that
would occur may be too heavy for what is usually pushed to the stable
branches. Do you think it would be better to get a cleaner refactoring
patch first and globalize the approach with PGASYNC_FATAL? As this is a
flag internal to libpq not exposed to the user this is fine on a code base,
but I am worrying about putting in stable branches more complexity than
really needed (upthread I said the same thing and Heikki mentioned that it
is fine as long as it is easy to backpatch). Note that I don't mind
spending more time on it, or to put in other works reworking the whole
patch to have something fully refactored, my goal being to have a clean fix
for all supported versions for those OOM problems.
I have not spent enough time on
> it to suggest any better alternative, but would like to hear what other
> approaches you have considered?
>
The other approach I have considered was to use the error string status to
decide if a failure happened, and this did not finish well in PQgetResult
:) It was actually a far cleaner approach to have a failure flag to decide
if based on the async state process should move on to a failure code path
or not.
--
Michael
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-04 05:07 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-09-04 05:07 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Aug 31, 2015 at 12:55 PM, Michael Paquier <michael.paquier@gmail.com
> wrote:
>
> On Sat, Aug 29, 2015 at 10:35 PM, Amit Kapila <amit.kapila16@gmail.com>
> wrote:
>>
>>
>> One thing that looks slightly non-elegant about this approach is that
>> new async status (PGASYNC_FATAL) is used to deal with errors only
>> in few paths in function pqParseInput3() and not-other paths which should
>> be okay if there is no other better way.
>>
>
> I considered using this logic in more code paths, but I kept focused on
> having a not-too-invasive back-patchable patch as the refactoring that
> would occur may be too heavy for what is usually pushed to the stable
> branches. Do you think it would be better to get a cleaner refactoring
> patch first and globalize the approach with PGASYNC_FATAL?
>
No wait, lets first try to see if this the best fix for Copy path.
The problem with the current approach is that even if we are able to
receive error, it doesn't completely clear the previous command
execution. As an example, if using debugger, I make getCopyStart()
return OOM error, then the next command execution fails.
postgres=# copy t1 from stdin;
out of memory
postgres=# copy t1 from stdin;
another command is already in progress
> As this is a flag internal to libpq not exposed to the user this is fine
> on a code base, but I am worrying about putting in stable branches more
> complexity than really needed (upthread I said the same thing and Heikki
> mentioned that it is fine as long as it is easy to backpatch). Note that I
> don't mind spending more time on it, or to put in other works reworking the
> whole patch to have something fully refactored, my goal being to have a
> clean fix for all supported versions for those OOM problems.
>
> I have not spent enough time on
>> it to suggest any better alternative, but would like to hear what other
>> approaches you have considered?
>>
>
> The other approach I have considered was to use the error string status to
> decide if a failure happened, and this did not finish well in PQgetResult :)
>
Yeah, that could be another way and we already use that in
pqParseInput3() to distinguish the error path.
> It was actually a far cleaner approach to have a failure flag to decide if
> based on the async state process should move on to a failure code path or
> not.
>
I think you have already tried, but it seems to me that if we can handle
it based on result status, that would be better, rather than introducing
new state, but anyway lets first try to sort out above reported problem.
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-04 07:25 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-09-04 07:25 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Sep 4, 2015 at 2:07 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Mon, Aug 31, 2015 at 12:55 PM, Michael Paquier <
> michael.paquier@gmail.com> wrote:
>>
>> On Sat, Aug 29, 2015 at 10:35 PM, Amit Kapila <amit.kapila16@gmail.com>
>> wrote:
>>>
>>>
>>> One thing that looks slightly non-elegant about this approach is that
>>> new async status (PGASYNC_FATAL) is used to deal with errors only
>>> in few paths in function pqParseInput3() and not-other paths which should
>>> be okay if there is no other better way.
>>>
>>
>> I considered using this logic in more code paths, but I kept focused on
>> having a not-too-invasive back-patchable patch as the refactoring that
>> would occur may be too heavy for what is usually pushed to the stable
>> branches. Do you think it would be better to get a cleaner refactoring
>> patch first and globalize the approach with PGASYNC_FATAL?
>>
>
> No wait, lets first try to see if this the best fix for Copy path.
>
Sure. Thanks. (We could remove some dead code of libpq though).
> The problem with the current approach is that even if we are able to
> receive error, it doesn't completely clear the previous command
> execution. As an example, if using debugger, I make getCopyStart()
> return OOM error, then the next command execution fails.
>
> postgres=# copy t1 from stdin;
> out of memory
> postgres=# copy t1 from stdin;
> another command is already in progress
>
Oops. Indeed. Using this new flag is obviously not a good idea because the
connection remains in a state that it considers as PGASYNC_FATAL and
actually it may not even finish to consume the remaining messages. Perhaps
I was too sleepy last time I tested that, well...
> It was actually a far cleaner approach to have a failure flag to decide if
>> based on the async state process should move on to a failure code path or
>> not.
>>
>
> I think you have already tried, but it seems to me that if we can handle
> it based on result status, that would be better, rather than introducing
> new state, but anyway lets first try to sort out above reported problem.
>
So, looking at that again with a fresh eye, I noticed that
getCopyDataMessage has a similar error handling when it fails on
pqCheckInBufferSpace. So looking at what I added, it seems that I am trying
to duplicate the protocol error handling even if everything is already
present, so that's really overdoing it. Hence, let's simply drop this idea
of new flag PGASYNC_FATAL and instead treat the OOM as a sync handling
error with the server, like in the patch attached.
When emulating an OOM with this patch, I am getting this error instead of
the infinite loop, which looks acceptable to me:
=# copy aa to stdout;
out of memory
lost synchronization with server: got message type "H", length 5
The connection to the server was lost. Attempting reset: Succeeded.
The extra message handling I have added at the end of getCopyStart and
getParamDescriptions still looks more adapted to me when a failure happens,
so I kept it.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
20150904_libpq_oom_v2.patch (application/x-patch, 7.7K) download
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index dbc0d89..174907d 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,11 +45,13 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -329,8 +331,11 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
+ {
+ handleSyncLoss(conn, id, msgLength);
return;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -362,19 +367,28 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
+ {
+ handleSyncLoss(conn, id, msgLength);
return;
+ }
conn->asyncStatus = PGASYNC_COPY_IN;
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
+ {
+ handleSyncLoss(conn, id, msgLength);
return;
+ }
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
+ {
+ handleSyncLoss(conn, id, msgLength);
return;
+ }
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
break;
@@ -630,27 +644,34 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message, EOF in case of error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
- if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numParameters, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -659,7 +680,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -669,7 +693,10 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
result->paramDescs[i].typid = typid;
}
@@ -677,8 +704,31 @@ getParamDescriptions(PGconn *conn)
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
return EOF;
}
@@ -1338,31 +1388,45 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
- if (nfields > 0)
+ if (result && nfields > 0)
{
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1371,22 +1435,49 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
* coerce these results to signed form.
*/
format = (int) ((int16) format);
- result->attDescs[i].format = format;
+ if (result && result->attDescs)
+ result->attDescs[i].format = format;
}
/* Success! */
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
return EOF;
}
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-05 12:45 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-09-05 12:45 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Sep 4, 2015 at 12:55 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
>
> On Fri, Sep 4, 2015 at 2:07 PM, Amit Kapila <amit.kapila16@gmail.com>
> wrote:
>>
>> It was actually a far cleaner approach to have a failure flag to decide
>>> if based on the async state process should move on to a failure code path
>>> or not.
>>>
>>
>> I think you have already tried, but it seems to me that if we can handle
>> it based on result status, that would be better, rather than introducing
>> new state, but anyway lets first try to sort out above reported problem.
>>
>
> So, looking at that again with a fresh eye, I noticed that
> getCopyDataMessage has a similar error handling when it fails on
> pqCheckInBufferSpace. So looking at what I added, it seems that I am trying
> to duplicate the protocol error handling even if everything is already
> present, so that's really overdoing it. Hence, let's simply drop this idea
> of new flag PGASYNC_FATAL and instead treat the OOM as a sync handling
> error with the server, like in the patch attached.
>
>
I think sync handling error, drops the connection which I feel should
be only done as a last resort for any error and if we are able to handle
OOM error for other kind of messages, then we should try to handle
it for Copy related messages as well. I have tried to do it for Copy
In and Copy Out protocol messages in the attached patch with logic
similar to what is currently used in code. The idea is that in Copy
mode if there is error we just return the error and the pending data
will be automatically discarded in next execution during PQexecStart().
> When emulating an OOM with this patch, I am getting this error instead of
> the infinite loop, which looks acceptable to me:
> =# copy aa to stdout;
> out of memory
> lost synchronization with server: got message type "H", length 5
> The connection to the server was lost. Attempting reset: Succeeded.
>
> The extra message handling I have added at the end of getCopyStart and
> getParamDescriptions still looks more adapted to me when a failure happens,
> so I kept it.
>
Sure, but then make the handling similar to getRowDescriptions() both for
failure and success case, that way code will be consistent.
Still I have not checked about COPY_BOTH and getParamDescriptions(),
see if you like what I have done in attached patch, then we can do the
similar for them as well.
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
20150905_libpq_oom_v3.patch (application/octet-stream, 9.3K) download
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..b84e5ed 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1801,6 +1801,10 @@ getCopyResult(PGconn *conn, ExecStatusType copytype)
return pqPrepareAsyncResult(conn);
}
+ /* If error has occured, return a PGRES_FATAL_ERROR result */
+ if (conn->result && conn->result->resultStatus == PGRES_FATAL_ERROR)
+ return pqPrepareAsyncResult(conn);
+
/* If we have an async result for the COPY, return that */
if (conn->result && conn->result->resultStatus == copytype)
return pqPrepareAsyncResult(conn);
@@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if we are in copy mode and error has occurred, the pending results
+ * will be discarded during next execution in PQexecStart.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
result->resultStatus == PGRES_COPY_BOTH ||
conn->status == CONNECTION_BAD)
break;
+ else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
+ conn->asyncStatus == PGASYNC_COPY_OUT ||
+ conn->asyncStatus == PGASYNC_COPY_BOTH) &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
}
return lastResult;
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index dbc0d89..05870a0 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,11 +45,13 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -329,8 +331,11 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
+ {
+ handleSyncLoss(conn, id, msgLength);
return;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -362,19 +367,27 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
return;
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
return;
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
- break;
+ continue;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
- return;
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
+ {
+ //handleSyncLoss(conn, id, msgLength);
+ //return;
+ continue;
+ }
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
break;
@@ -630,27 +643,34 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message, EOF in case of error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
- if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numParameters, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -659,7 +679,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -669,7 +692,10 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
result->paramDescs[i].typid = typid;
}
@@ -677,8 +703,31 @@ getParamDescriptions(PGconn *conn)
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
return EOF;
}
@@ -1338,31 +1387,45 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
- if (nfields > 0)
+ if (result && nfields > 0)
{
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1371,23 +1434,57 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
* coerce these results to signed form.
*/
format = (int) ((int16) format);
- result->attDescs[i].format = format;
+ if (result && result->attDescs)
+ result->attDescs[i].format = format;
}
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
- PQclear(result);
- return EOF;
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-07 08:10 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 2 replies; 48+ messages in thread
From: Michael Paquier @ 2015-09-07 08:10 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Sep 5, 2015 at 9:45 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>
>
> On Fri, Sep 4, 2015 at 12:55 PM, Michael Paquier <michael.paquier@gmail.com> wrote:
>>
>>
>> On Fri, Sep 4, 2015 at 2:07 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>>>>
>>>> It was actually a far cleaner approach to have a failure flag to decide if based on the async state process should move on to a failure code path or not.
>>>
>>>
>>> I think you have already tried, but it seems to me that if we can handle
>>> it based on result status, that would be better, rather than introducing
>>> new state, but anyway lets first try to sort out above reported problem.
>>
>>
>> So, looking at that again with a fresh eye, I noticed that getCopyDataMessage has a similar error handling when it fails on pqCheckInBufferSpace. So looking at what I added, it seems that I am trying to duplicate the protocol error handling even if everything is already present, so that's really overdoing it. Hence, let's simply drop this idea of new flag PGASYNC_FATAL and instead treat the OOM as a sync handling error with the server, like in the patch attached.
>>
>
> I think sync handling error, drops the connection which I feel should
> be only done as a last resort for any error and if we are able to handle
> OOM error for other kind of messages, then we should try to handle
> it for Copy related messages as well. I have tried to do it for Copy
> In and Copy Out protocol messages in the attached patch with logic
> similar to what is currently used in code. The idea is that in Copy
> mode if there is error we just return the error and the pending data
> will be automatically discarded in next execution during PQexecStart().
OK. So you rely on the error state set by pqSaveErrorResult, then wrap
an error check in getCopyResult and PQexecFinish... I guess that this
is acceptable for COPY as this code path would just kept looping
infinitely on the current HEAD.
>
>
>> When emulating an OOM with this patch, I am getting this error instead of the infinite loop, which looks acceptable to me:
>> =# copy aa to stdout;
>> out of memory
>> lost synchronization with server: got message type "H", length 5
>> The connection to the server was lost. Attempting reset: Succeeded.
>>
>> The extra message handling I have added at the end of getCopyStart and getParamDescriptions still looks more adapted to me when a failure happens, so I kept it.
>
>
> Sure, but then make the handling similar to getRowDescriptions() both for
> failure and success case, that way code will be consistent.
No problem for me, and this makes actually refactoring easier as those
code paths are more similar.
> Still I have not checked about COPY_BOTH and getParamDescriptions(),
> see if you like what I have done in attached patch, then we can do the
> similar for them as well.
Now, to move into the serious things...
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
This change...
+ /* getCopyStart() moves
inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
... And this change are risky for a backpatch. And they actually
break the existing replication protocol and backward compatibility so
I have no doubt that they could break any client applications that
work directly with the replication level protocol with commands like
BASE_BACKUP, START_REPLICATION and IDENTITY_SYSTEM. I think that we
should really try to keep the non-error code path as close as possible
to the original code.
So, I think that the right approach would be to leave immediately
pqParseInput3 should an error happen, switching asyncStatus to leave
the loop in PQgetResult. This seems as well to work correctly with
PGRES_COPY_BOTH (I emulated failures with pg_basebackup and errors
were caught up correctly. This brings back of course the introduction
of a new flag PGASYNC_FATAL and we could replace the extra stuff you
added in getCopyResult as well. I have a WIP patch that I don't have
the time to finish now, but I'll send it once I am done. For now I am
just sharing my thoughts on the matter.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-07 09:45 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-09-07 09:45 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Sep 7, 2015 at 1:40 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
>
> On Sat, Sep 5, 2015 at 9:45 PM, Amit Kapila <amit.kapila16@gmail.com>
wrote:
> >
>
> So, I think that the right approach would be to leave immediately
> pqParseInput3 should an error happen, switching asyncStatus to leave
> the loop in PQgetResult.
Sure, if you think that works, then do it that way.
> This seems as well to work correctly with
> PGRES_COPY_BOTH (I emulated failures with pg_basebackup and errors
> were caught up correctly. This brings back of course the introduction
> of a new flag PGASYNC_FATAL
I think we should try not to introduce this new flag, as that is not merely
a
flag, but rather a state in query-execution state machine. Now if we
introduce
a new error state into that state-machine, then it doesn't seem like a good
idea to do that only for some of the paths and doing it for all other paths
is a call for somewhat larger verification cycle (to see if it works in all
paths
as previously).
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-07 13:41 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-09-07 13:41 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Sep 7, 2015 at 6:45 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Mon, Sep 7, 2015 at 1:40 PM, Michael Paquier <michael.paquier@gmail.com>
> wrote:
>>
>> On Sat, Sep 5, 2015 at 9:45 PM, Amit Kapila <amit.kapila16@gmail.com>
>> wrote:
>> >
>>
>> So, I think that the right approach would be to leave immediately
>> pqParseInput3 should an error happen, switching asyncStatus to leave
>> the loop in PQgetResult.
>
> Sure, if you think that works, then do it that way.
>
>> This seems as well to work correctly with
>> PGRES_COPY_BOTH (I emulated failures with pg_basebackup and errors
>> were caught up correctly. This brings back of course the introduction
>> of a new flag PGASYNC_FATAL
>
> I think we should try not to introduce this new flag, as that is not merely
> a flag, but rather a state in query-execution state machine. Now if we
> introduce a new error state into that state-machine, then it doesn't seem
> like a good idea to do that only for some of the paths and doing it for all
> other paths is a call for somewhat larger verification cycle (to see if it
> works in all paths as previously).
Well, the previous patch you sent added code paths to manage the
failures with COPY protocol directly in the COPY routines in a way
similar to what the introduction of PGASYNC_FATAL is doing, except
that PGASYNC_FATAL has the advantage to let the end of PQgetResult
know that a failure has happened, centralizing the error check. Also,
it seems to me that switching getParamDescriptions to an error state
is going to need this flag, or at least a new flag to exit the loop
when parsing the input.
Regarding the other messages that could use this flag, I just
double-checked and it seems that all the other calls return an EOF
when they do not have enough data received from the backend or they
directly switch to another PGASYNC state, so they do not need a
specific fatal error handling. Please let me know if I missed
something.
In any case, attached are two patches:
- 0001 adds the OOM/failure handling for the BIND and COPY start
messages. This time the connection is not dropped. After a failure,
successive commands work as well, this addresses the previous issue
you reported.
- 0002 is a cleanup bonus, getRowDescriptions and getAnotherTuple have
some dead code that I think would be better removed, those are
remnants from a copy/paste from the similar code of protocol 2.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (2 files, .tar.gz)
0001-Prevent-COPY-start-and-BIND-to-freeze-in-libpq-on-OO.patch (binary/octet-stream, 10.2K) download
From b205c48c0137333074b770a1e5568a984e3e29e1 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Fri, 4 Sep 2015 16:22:03 +0900
Subject: [PATCH 1/2] Prevent COPY start and BIND to freeze in libpq on OOM
A new internal flag PGAYNC_FATAL is used to control the error flow.
---
src/interfaces/libpq/fe-exec.c | 13 ++++
src/interfaces/libpq/fe-protocol3.c | 145 ++++++++++++++++++++++++++++++------
src/interfaces/libpq/libpq-int.h | 3 +-
3 files changed, 136 insertions(+), 25 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..d40a39f 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1744,6 +1744,14 @@ PQgetResult(PGconn *conn)
case PGASYNC_COPY_BOTH:
res = getCopyResult(conn, PGRES_COPY_BOTH);
break;
+ case PGASYNC_FATAL:
+ res = NULL;
+ /*
+ * Set the state back to BUSY, allowing parsing to proceed to
+ * consume messages coming from the server.
+ */
+ conn->asyncStatus = PGASYNC_BUSY;
+ break;
default:
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("unexpected asyncStatus: %d\n"),
@@ -1991,6 +1999,8 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if a fatal error happened.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2015,6 +2025,9 @@ PQexecFinish(PGconn *conn)
PQclear(lastResult);
}
lastResult = result;
+ if (conn->asyncStatus == PGASYNC_FATAL &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
if (result->resultStatus == PGRES_COPY_IN ||
result->resultStatus == PGRES_COPY_OUT ||
result->resultStatus == PGRES_COPY_BOTH ||
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..0a360e4 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,11 +45,13 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -329,8 +331,11 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -362,19 +367,34 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
break;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
break;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
return;
+ }
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
break;
@@ -630,27 +650,34 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message, EOF in case of error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
- if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numParameters, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -659,7 +686,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -669,7 +699,10 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in \"t\" message");
+ goto advance_and_error;
+ }
result->paramDescs[i].typid = typid;
}
@@ -677,8 +710,31 @@ getParamDescriptions(PGconn *conn)
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
return EOF;
}
@@ -1343,22 +1399,33 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1367,7 +1434,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,7 +1446,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1390,8 +1463,32 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
conn->result = result;
return 0;
-failure:
- PQclear(result);
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+
+ /* Build a error result that will be fetched by PQgetResult */
+ pqSaveErrorResult(conn);
return EOF;
}
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 04d056e..6eebcad 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -219,7 +219,8 @@ typedef enum
PGASYNC_READY, /* result ready for PQgetResult */
PGASYNC_COPY_IN, /* Copy In data transfer in progress */
PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
- PGASYNC_COPY_BOTH /* Copy In/Out data transfer in progress */
+ PGASYNC_COPY_BOTH, /* Copy In/Out data transfer in progress */
+ PGASYNC_FATAL /* Something awry happened */
} PGAsyncStatusType;
/* PGQueryClass tracks which query protocol we are now executing */
--
2.5.1
0002-Remove-dead-code-of-libpq-protocol-3.patch (binary/octet-stream, 4.8K) download
From 752b2f95ca8bba822cda805f6892d2890d53204b Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Mon, 7 Sep 2015 22:24:29 +0900
Subject: [PATCH 2/2] Remove dead code of libpq protocol 3
getRowDescriptions and getAnotherTuple contained a code path that could
be used to stop message parsing which is visibly a copy/paste of the
equivalent code if protocol 2, however it has never been used.
---
src/interfaces/libpq/fe-protocol3.c | 46 +++++++++++++++++--------------------
1 file changed, 21 insertions(+), 25 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 0a360e4..a41f4a1 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -44,9 +44,9 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
-static int getRowDescriptions(PGconn *conn, int msgLength);
+static void getRowDescriptions(PGconn *conn, int msgLength);
static int getParamDescriptions(PGconn *conn, int msgLength);
-static int getAnotherTuple(PGconn *conn, int msgLength);
+static void getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
static int getCopyStart(PGconn *conn,
@@ -284,8 +284,7 @@ pqParseInput3(PGconn *conn)
conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn, msgLength))
- return;
+ getRowDescriptions(conn, msgLength);
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -342,8 +341,7 @@ pqParseInput3(PGconn *conn)
conn->result->resultStatus == PGRES_TUPLES_OK)
{
/* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, msgLength))
- return;
+ getAnotherTuple(conn, msgLength);
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -475,11 +473,10 @@ handleSyncLoss(PGconn *conn, char id, int msgLength)
* parseInput subroutine to read a 'T' (row descriptions) message.
* We'll build a new PGresult structure (unless called for a Describe
* command for a prepared statement) containing the attribute data.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine assumes that message is always processed successfully
+ * and conn->inStart is advanced past the message.
*/
-static int
+static void
getRowDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
@@ -602,7 +599,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
if (conn->queryclass == PGQUERY_DESCRIBE)
{
conn->asyncStatus = PGASYNC_READY;
- return 0;
+ return;
}
/*
@@ -611,7 +608,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
*/
/* And we're done. */
- return 0;
+ return;
advance_and_error:
/* Discard unsaved result, if any */
@@ -640,11 +637,11 @@ advance_and_error:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
/*
@@ -741,11 +738,10 @@ advance_and_error:
/*
* parseInput subroutine to read a 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine always considers that the message has been processed
+ * successfully, and conn->inStart is advanced past the message.
*/
-static int
+static void
getAnotherTuple(PGconn *conn, int msgLength)
{
PGresult *result = conn->result;
@@ -829,7 +825,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
/* Process the collected row */
errmsg = NULL;
if (pqRowProcessor(conn, &errmsg))
- return 0; /* normal, successful exit */
+ return; /* normal, successful exit */
goto set_error_result; /* pqRowProcessor failed, report it */
@@ -858,11 +854,11 @@ set_error_result:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
--
2.5.1
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-07 15:13 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 2 replies; 48+ messages in thread
From: Michael Paquier @ 2015-09-07 15:13 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Sep 7, 2015 at 10:41 PM, Michael Paquier wrote:
> In any case, attached are two patches:
> - 0001 adds the OOM/failure handling for the BIND and COPY start
> messages. This time the connection is not dropped. After a failure,
> successive commands work as well, this addresses the previous issue
> you reported.
> - 0002 is a cleanup bonus, getRowDescriptions and getAnotherTuple have
> some dead code that I think would be better removed, those are
> remnants from a copy/paste from the similar code of protocol 2.
And I forgot... Attached is a simple program to test BIND messages.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
extended.c (text/x-csrc, 1.1K) download
/*
* Test case for PQsendDescribePrepared
* Need first to run this query on the database connection is made
* to:
* CREATE TABLE aa (a int);
*/
#include <libpq-fe.h>
#define DB_CONN_STR "host=localhost dbname=postgres"
#define SQL_FETCH_AA "select a from aa where a = $1"
int
main(int argc, char *argv[])
{
PGconn* conn;
PGresult* res;
if ((conn = PQconnectdb(DB_CONN_STR)) == NULL)
fprintf(stderr, "Connect to '%s' failed", DB_CONN_STR);
if (PQstatus(conn) != CONNECTION_OK)
fprintf(stderr, "Connect to '%s' failed: %s",
DB_CONN_STR, PQerrorMessage(conn));
if ((res = PQprepare(conn, "sql_fetch_aa",
SQL_FETCH_AA, 2, NULL)) == NULL)
fprintf(stderr, "Preparing statement '%s' failed",
SQL_FETCH_AA);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
fprintf(stderr, "Preparing statement '%s' failed: %s",
SQL_FETCH_AA, PQerrorMessage(conn));
PQclear(res);
/* Call getParameterDescription */
PQsendDescribePrepared(conn, "sql_fetch_aa");
if ((res = PQgetResult(conn)) == NULL)
fprintf(stderr, "Describe statement '%s' failed: %s",
SQL_FETCH_AA, PQerrorMessage(conn));
PQclear(res);
return 0;
}
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-08 11:48 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 0 replies; 48+ messages in thread
From: Michael Paquier @ 2015-09-08 11:48 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Tue, Sep 8, 2015 at 12:13 AM, Michael Paquier
<michael.paquier@gmail.com> wrote:
> On Mon, Sep 7, 2015 at 10:41 PM, Michael Paquier wrote:
>> In any case, attached are two patches:
>> - 0001 adds the OOM/failure handling for the BIND and COPY start
>> messages. This time the connection is not dropped. After a failure,
>> successive commands work as well, this addresses the previous issue
>> you reported.
>> - 0002 is a cleanup bonus, getRowDescriptions and getAnotherTuple have
>> some dead code that I think would be better removed, those are
>> remnants from a copy/paste from the similar code of protocol 2.
>
> And I forgot... Attached is a simple program to test BIND messages.
And it occurred to me after sleeping on it that what I sent earlier is
not enough: in the case where the server has sent only a partial
message, we should not move into an error code path, but simply get
back into the loop of pqGetResult and wait for additional input from
the server. Attached are patches to fix that.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (2 files, .tar.gz)
0001-Prevent-COPY-start-and-BIND-to-freeze-in-libpq-on-OO.patch (binary/octet-stream, 11.3K) download
From b9701212d95e746bddc29d88584bb8eaff213cc0 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Fri, 4 Sep 2015 16:22:03 +0900
Subject: [PATCH 1/2] Prevent COPY start and BIND to freeze in libpq on OOM
A new internal flag PGAYNC_FATAL is used to control the error flow.
---
src/interfaces/libpq/fe-exec.c | 13 +++
src/interfaces/libpq/fe-protocol3.c | 200 +++++++++++++++++++++++++++++-------
src/interfaces/libpq/libpq-int.h | 3 +-
3 files changed, 179 insertions(+), 37 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..d40a39f 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1744,6 +1744,14 @@ PQgetResult(PGconn *conn)
case PGASYNC_COPY_BOTH:
res = getCopyResult(conn, PGRES_COPY_BOTH);
break;
+ case PGASYNC_FATAL:
+ res = NULL;
+ /*
+ * Set the state back to BUSY, allowing parsing to proceed to
+ * consume messages coming from the server.
+ */
+ conn->asyncStatus = PGASYNC_BUSY;
+ break;
default:
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("unexpected asyncStatus: %d\n"),
@@ -1991,6 +1999,8 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if a fatal error happened.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2015,6 +2025,9 @@ PQexecFinish(PGconn *conn)
PQclear(lastResult);
}
lastResult = result;
+ if (conn->asyncStatus == PGASYNC_FATAL &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
if (result->resultStatus == PGRES_COPY_IN ||
result->resultStatus == PGRES_COPY_OUT ||
result->resultStatus == PGRES_COPY_BOTH ||
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..20b6b13 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,11 +45,13 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -329,8 +331,16 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
- return;
+ {
+ int res = getParamDescriptions(conn, msgLength);
+ if (res == -2)
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
+ return;
+ }
+ else if (res == -1)
+ return;
+ }
break;
case 'D': /* Data Row */
if (conn->result != NULL &&
@@ -362,22 +372,52 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
- return;
- conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_IN, msgLength);
+ if (res == -2)
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
+ return;
+ }
+ else if (res == -1)
+ return;
+
+ /* getCopyStart() moves inStart itself */
+ conn->asyncStatus = PGASYNC_COPY_IN;
+ break;
+ }
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
- return;
- conn->asyncStatus = PGASYNC_COPY_OUT;
- conn->copy_already_done = 0;
- break;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_OUT, msgLength);
+ if (res == -2)
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
+ return;
+ }
+ else if (res == -1)
+ return;
+
+ /* getCopyStart() moves inStart itself */
+ conn->asyncStatus = PGASYNC_COPY_OUT;
+ conn->copy_already_done = 0;
+ break;
+ }
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
- return;
- conn->asyncStatus = PGASYNC_COPY_BOTH;
- conn->copy_already_done = 0;
- break;
+ {
+ int res = getCopyStart(conn, PGRES_COPY_BOTH, msgLength);
+ if (res == -2)
+ {
+ conn->asyncStatus = PGASYNC_FATAL;
+ return;
+ }
+ else if (res == -1)
+ return;
+
+ /* getCopyStart() moves inStart itself */
+ conn->asyncStatus = PGASYNC_COPY_BOTH;
+ conn->copy_already_done = 0;
+ break;
+ }
case 'd': /* Copy Data */
/*
@@ -630,27 +670,35 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message, -1 if not enough data and -2 in
+ * case of error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
- if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numParameters, 2, conn))
+ {
+ errmsg = libpq_gettext("insufficient data in \"t\" message");
+ goto insufficient_data;
+ }
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -659,7 +707,10 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -669,7 +720,10 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("insufficient data in \"t\" message");
+ goto insufficient_data;
+ }
result->paramDescs[i].typid = typid;
}
@@ -677,9 +731,36 @@ getParamDescriptions(PGconn *conn)
conn->result = result;
return 0;
-failure:
+insufficient_data:
PQclear(result);
- return EOF;
+ return -1;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+ return -2;
}
/*
@@ -1339,26 +1420,39 @@ getNotify(PGconn *conn)
/*
* getCopyStart - process CopyInResponse, CopyOutResponse or
* CopyBothResponse message
+ * Returns: 0 if completed message, -1 if not enough data and -2 in
+ * case of error.
*
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("insufficient data in COPY start message");
+ goto insufficient_data;
+ }
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("insufficient data in COPY start message");
+ goto insufficient_data;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1367,7 +1461,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,7 +1473,10 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("insufficient data in COPY start message");
+ goto insufficient_data;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1390,9 +1490,37 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
conn->result = result;
return 0;
-failure:
+insufficient_data:
PQclear(result);
- return EOF;
+ return -1;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+
+ /* Build a error result that will be fetched by PQgetResult */
+ pqSaveErrorResult(conn);
+ return -2;
}
/*
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 04d056e..6eebcad 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -219,7 +219,8 @@ typedef enum
PGASYNC_READY, /* result ready for PQgetResult */
PGASYNC_COPY_IN, /* Copy In data transfer in progress */
PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
- PGASYNC_COPY_BOTH /* Copy In/Out data transfer in progress */
+ PGASYNC_COPY_BOTH, /* Copy In/Out data transfer in progress */
+ PGASYNC_FATAL /* Something awry happened */
} PGAsyncStatusType;
/* PGQueryClass tracks which query protocol we are now executing */
--
2.5.1
0002-Remove-dead-code-of-libpq-protocol-3.patch (binary/octet-stream, 4.8K) download
From d0dabb152633447bdef788bb1c579031801160ad Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Mon, 7 Sep 2015 22:24:29 +0900
Subject: [PATCH 2/2] Remove dead code of libpq protocol 3
getRowDescriptions and getAnotherTuple contained a code path that could
be used to stop message parsing which is visibly a copy/paste of the
equivalent code if protocol 2, however it has never been used.
---
src/interfaces/libpq/fe-protocol3.c | 46 +++++++++++++++++--------------------
1 file changed, 21 insertions(+), 25 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 20b6b13..5da47cc 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -44,9 +44,9 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
-static int getRowDescriptions(PGconn *conn, int msgLength);
+static void getRowDescriptions(PGconn *conn, int msgLength);
static int getParamDescriptions(PGconn *conn, int msgLength);
-static int getAnotherTuple(PGconn *conn, int msgLength);
+static void getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
static int getCopyStart(PGconn *conn,
@@ -284,8 +284,7 @@ pqParseInput3(PGconn *conn)
conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn, msgLength))
- return;
+ getRowDescriptions(conn, msgLength);
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -347,8 +346,7 @@ pqParseInput3(PGconn *conn)
conn->result->resultStatus == PGRES_TUPLES_OK)
{
/* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, msgLength))
- return;
+ getAnotherTuple(conn, msgLength);
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -495,11 +493,10 @@ handleSyncLoss(PGconn *conn, char id, int msgLength)
* parseInput subroutine to read a 'T' (row descriptions) message.
* We'll build a new PGresult structure (unless called for a Describe
* command for a prepared statement) containing the attribute data.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine assumes that message is always processed successfully
+ * and conn->inStart is advanced past the message.
*/
-static int
+static void
getRowDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
@@ -622,7 +619,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
if (conn->queryclass == PGQUERY_DESCRIBE)
{
conn->asyncStatus = PGASYNC_READY;
- return 0;
+ return;
}
/*
@@ -631,7 +628,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
*/
/* And we're done. */
- return 0;
+ return;
advance_and_error:
/* Discard unsaved result, if any */
@@ -660,11 +657,11 @@ advance_and_error:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
/*
@@ -766,11 +763,10 @@ advance_and_error:
/*
* parseInput subroutine to read a 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine always considers that the message has been processed
+ * successfully, and conn->inStart is advanced past the message.
*/
-static int
+static void
getAnotherTuple(PGconn *conn, int msgLength)
{
PGresult *result = conn->result;
@@ -854,7 +850,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
/* Process the collected row */
errmsg = NULL;
if (pqRowProcessor(conn, &errmsg))
- return 0; /* normal, successful exit */
+ return; /* normal, successful exit */
goto set_error_result; /* pqRowProcessor failed, report it */
@@ -883,11 +879,11 @@ set_error_result:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
--
2.5.1
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-12 08:56 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-09-12 08:56 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Sep 7, 2015 at 8:43 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
> On Mon, Sep 7, 2015 at 10:41 PM, Michael Paquier wrote:
> > In any case, attached are two patches:
> > - 0001 adds the OOM/failure handling for the BIND and COPY start
> > messages. This time the connection is not dropped. After a failure,
> > successive commands work as well, this addresses the previous issue
> > you reported.
> > - 0002 is a cleanup bonus, getRowDescriptions and getAnotherTuple have
> > some dead code that I think would be better removed, those are
> > remnants from a copy/paste from the similar code of protocol 2.
>
> And I forgot... Attached is a simple program to test BIND messages.
>
Still the same test fails for me.
postgres=# copy t1 from stdin;
out of memory
postgres=# copy t1 from stdin; --hangs here
It hangs in second statement, basically I think you can't change the
state to PGASYNC_BUSY on failure in case of copy in below code.
+ case PGASYNC_FATAL:
+ res = NULL;
+ /*
+ * Set the state back to BUSY, allowing parsing to proceed to
+ * consume messages coming from the server.
+ */
+ conn->asyncStatus = PGASYNC_BUSY;
+ break;
I think you need to keep the state as PGASYNC_COPY_*, so that
the pending data can be discarded.
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-12 09:11 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-09-12 09:11 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Sep 7, 2015 at 1:40 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
> On Sat, Sep 5, 2015 at 9:45 PM, Amit Kapila <amit.kapila16@gmail.com>
> wrote:
>
> Now, to move into the serious things...
>
> + /*
> + * Advance inStart to show that the copy related message has been
> + * processed.
> + */
> + conn->inStart = conn->inCursor;
> This change...
>
> + /* getCopyStart() moves
> inStart itself */
> conn->asyncStatus =
> PGASYNC_COPY_IN;
> - break;
> + continue;
> ... And this change are risky for a backpatch. And they actually
> break the existing replication protocol
Can you please explain how will it break replication protocol?
I have done the required handling for Copy Both mode as well in attached
patch similar to what was done for other Copy modes in previous patch.
Check if you still find it as broken for replication?
I have only kept the changes for COPY modes, so that once we settle on
those, I think similar changes could be done for getParamDescriptions()
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
20150912_libpq_oom_v4.patch (application/octet-stream, 7.0K) download
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index b7bbcf6..8fae3a9 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
PQresultStatus(lastResult) == PGRES_COPY_OUT ||
PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
+ PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
PQstatus(streamConn) == CONNECTION_BAD)
break;
}
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..b84e5ed 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1801,6 +1801,10 @@ getCopyResult(PGconn *conn, ExecStatusType copytype)
return pqPrepareAsyncResult(conn);
}
+ /* If error has occured, return a PGRES_FATAL_ERROR result */
+ if (conn->result && conn->result->resultStatus == PGRES_FATAL_ERROR)
+ return pqPrepareAsyncResult(conn);
+
/* If we have an async result for the COPY, return that */
if (conn->result && conn->result->resultStatus == copytype)
return pqPrepareAsyncResult(conn);
@@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if we are in copy mode and error has occurred, the pending results
+ * will be discarded during next execution in PQexecStart.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
result->resultStatus == PGRES_COPY_BOTH ||
conn->status == CONNECTION_BAD)
break;
+ else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
+ conn->asyncStatus == PGASYNC_COPY_OUT ||
+ conn->asyncStatus == PGASYNC_COPY_BOTH) &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
}
return lastResult;
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..4ee1610 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -49,7 +49,9 @@ static int getParamDescriptions(PGconn *conn);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -362,22 +364,26 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
return;
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
return;
+
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
- break;
+ continue;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
return;
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
- break;
+ continue;
case 'd': /* Copy Data */
/*
@@ -630,7 +636,7 @@ advance_and_error:
/*
* parseInput subroutine to read a 't' (ParameterDescription) message.
* We'll build a new PGresult structure containing the parameter data.
- * Returns: 0 if completed message, EOF if not enough data yet.
+ * Returns: 0 if completed message, EOF in case of error.
*
* Note that if we run out of data, we have to release the partially
* constructed PGresult, and rebuild it again next time. Fortunately,
@@ -1343,31 +1349,45 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
- if (nfields > 0)
+ if (result && nfields > 0)
{
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ {
+ errmsg = NULL;
+ goto advance_and_error;
+ }
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,23 +1396,57 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
* coerce these results to signed form.
*/
format = (int) ((int16) format);
- result->attDescs[i].format = format;
+ if (result && result->attDescs)
+ result->attDescs[i].format = format;
}
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
- PQclear(result);
- return EOF;
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-13 22:57 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 0 replies; 48+ messages in thread
From: Michael Paquier @ 2015-09-13 22:57 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Sep 12, 2015 at 5:56 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Mon, Sep 7, 2015 at 8:43 PM, Michael Paquier <michael.paquier@gmail.com>
> wrote:
>>
>> On Mon, Sep 7, 2015 at 10:41 PM, Michael Paquier wrote:
>> > In any case, attached are two patches:
>> > - 0001 adds the OOM/failure handling for the BIND and COPY start
>> > messages. This time the connection is not dropped. After a failure,
>> > successive commands work as well, this addresses the previous issue
>> > you reported.
>> > - 0002 is a cleanup bonus, getRowDescriptions and getAnotherTuple have
>> > some dead code that I think would be better removed, those are
>> > remnants from a copy/paste from the similar code of protocol 2.
>>
>> And I forgot... Attached is a simple program to test BIND messages.
>
>
> Still the same test fails for me.
>
> postgres=# copy t1 from stdin;
> out of memory
> postgres=# copy t1 from stdin; --hangs here
>
> It hangs in second statement, basically I think you can't change the
> state to PGASYNC_BUSY on failure in case of copy in below code.
>
> + case PGASYNC_FATAL:
> + res = NULL;
> + /*
> + * Set the state back to BUSY, allowing parsing to proceed to
> + * consume messages coming from the server.
> + */
> + conn->asyncStatus = PGASYNC_BUSY;
> + break;
>
> I think you need to keep the state as PGASYNC_COPY_*, so that
> the pending data can be discarded.
Yes right. And my patch was as well broken with PGRES_COPY_BOTH. If
the replication protocol expected to wait for some data, this would
have frozen as well as it's a two-way data exchange in this case.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-14 01:36 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-09-14 01:36 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Sep 12, 2015 at 6:11 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Mon, Sep 7, 2015 at 1:40 PM, Michael Paquier <michael.paquier@gmail.com>
> wrote:
>>
>> On Sat, Sep 5, 2015 at 9:45 PM, Amit Kapila <amit.kapila16@gmail.com>
>> wrote:
>>
>> Now, to move into the serious things...
>>
>> + /*
>> + * Advance inStart to show that the copy related message has been
>> + * processed.
>> + */
>> + conn->inStart = conn->inCursor;
>> This change...
>>
>> + /* getCopyStart() moves
>> inStart itself */
>> conn->asyncStatus =
>> PGASYNC_COPY_IN;
>> - break;
>> + continue;
>> ... And this change are risky for a backpatch. And they actually
>> break the existing replication protocol
First, many thanks for providing your input! I am really looking
forward into fixing those problems appropriately.
> Can you please explain how will it break replication protocol?
> I have done the required handling for Copy Both mode as well in attached
> patch similar to what was done for other Copy modes in previous patch.
> Check if you still find it as broken for replication?
When not enough data has been received from the server, it seems that
we should PQclear the existing result, and leave immediately
pqParseInput3 with the status PGASYNC_BUSY to be able to wait for more
data. Your patch, as-is, is breaking that promise (and this comes from
the first versions of my patches). It seems also that we should not
write an error message on connection in this case to be consistent in
the behavior of back-branches. For the OOM case, we definitely need to
take the error code path though, as your patch is correctly doing, and
what mine legendary failed to do.
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ {
+ errmsg = libpq_gettext("extraneous data in COPY start message");
+ goto advance_and_error;
+ }
Here an error message is not needed, and this message should have been
formulated as "insufficient data in blah" either way.
> I have only kept the changes for COPY modes, so that once we settle on
> those, I think similar changes could be done for getParamDescriptions()
Yeah, I looked into this one as well, resulting in patch 0002
attached. In this case we have the advantage to only receive data from
the server, so pqPrepareAsyncResult is handling the failure just fine.
Attached as well is the test case I used (similar to previous one,
just extended a bit to report the error message), after getting the
result from PQsendDescribePrepared, PQresultStatus is set correctly on
error and reports "out of memory" to the user. What do you think about
it?
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (4 files, .tar.gz)
0001-Fix-OOM-error-handling-in-COPY-protocol-of-libpq.patch (text/x-patch, 7.1K) download
From cb9ef38f4e9d89d52bc11e6e736dd211fb8d713f Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Mon, 14 Sep 2015 09:54:21 +0900
Subject: [PATCH 1/3] Fix OOM error handling in COPY protocol of libpq
An OOM occurring while all the data needed by process from server has been
received can result in an infinite loop when parsing the output message.
getCopyStart is switched to discard a a message read from server in case of
server and any subsequent ones when receiving data from server for
PGASYNC_COPY_OUT, and not wait for any additional data when input is expected
via PGASYNC_COPY_IN. In the case of PGASYNC_COPY_BOTH, both concepts apply.
---
.../libpqwalreceiver/libpqwalreceiver.c | 1 +
src/interfaces/libpq/fe-exec.c | 12 ++++
src/interfaces/libpq/fe-protocol3.c | 73 +++++++++++++++++-----
3 files changed, 70 insertions(+), 16 deletions(-)
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index b7bbcf6..8fae3a9 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
PQresultStatus(lastResult) == PGRES_COPY_OUT ||
PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
+ PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
PQstatus(streamConn) == CONNECTION_BAD)
break;
}
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..b84e5ed 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1801,6 +1801,10 @@ getCopyResult(PGconn *conn, ExecStatusType copytype)
return pqPrepareAsyncResult(conn);
}
+ /* If error has occured, return a PGRES_FATAL_ERROR result */
+ if (conn->result && conn->result->resultStatus == PGRES_FATAL_ERROR)
+ return pqPrepareAsyncResult(conn);
+
/* If we have an async result for the COPY, return that */
if (conn->result && conn->result->resultStatus == copytype)
return pqPrepareAsyncResult(conn);
@@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if we are in copy mode and error has occurred, the pending results
+ * will be discarded during next execution in PQexecStart.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
result->resultStatus == PGRES_COPY_BOTH ||
conn->status == CONNECTION_BAD)
break;
+ else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
+ conn->asyncStatus == PGASYNC_COPY_OUT ||
+ conn->asyncStatus == PGASYNC_COPY_BOTH) &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
}
return lastResult;
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..7d99d66 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -49,7 +49,9 @@ static int getParamDescriptions(PGconn *conn);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -362,22 +364,25 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
- break;
+ continue;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
- break;
+ continue;
case 'd': /* Copy Data */
/*
@@ -1343,31 +1348,33 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ goto advance_and_error;
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ goto not_enough_data;
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ goto not_enough_data;
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
- if (nfields > 0)
+ if (result && nfields > 0)
{
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,7 +1383,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ goto not_enough_data;
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1388,11 +1395,45 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.5.1
0002-Fix-OOM-error-handling-in-BIND-protocol-of-libpq.patch (text/x-patch, 3.6K) download
From f71c9fee2eba33bbf2e5adad13323d63d85fe19f Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Mon, 14 Sep 2015 10:26:13 +0900
Subject: [PATCH 2/3] Fix OOM error handling in BIND protocol of libpq
---
src/interfaces/libpq/fe-protocol3.c | 54 ++++++++++++++++++++++++++++++-------
1 file changed, 45 insertions(+), 9 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 7d99d66..98afc22 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,7 +45,7 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
@@ -331,9 +331,10 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
return;
- break;
+ /* getParamDescriptions() moves inStart itself */
+ continue;
case 'D': /* Data Row */
if (conn->result != NULL &&
conn->result->resultStatus == PGRES_TUPLES_OK)
@@ -642,20 +643,21 @@ advance_and_error:
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ goto advance_and_error;
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ goto not_enough_data;
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -664,7 +666,7 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -674,17 +676,51 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ goto not_enough_data;
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.5.1
0003-Remove-dead-code-of-libpq-protocol-3.patch (text/x-patch, 4.8K) download
From 68622fd7d1036142deb1b622e494ab7216fef3ba Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Mon, 7 Sep 2015 22:24:29 +0900
Subject: [PATCH 3/3] Remove dead code of libpq protocol 3
getRowDescriptions and getAnotherTuple contained a code path that could
be used to stop message parsing which is visibly a copy/paste of the
equivalent code if protocol 2, however it has never been used.
---
src/interfaces/libpq/fe-protocol3.c | 46 +++++++++++++++++--------------------
1 file changed, 21 insertions(+), 25 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 98afc22..7fb32ae 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -44,9 +44,9 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
-static int getRowDescriptions(PGconn *conn, int msgLength);
+static void getRowDescriptions(PGconn *conn, int msgLength);
static int getParamDescriptions(PGconn *conn, int msgLength);
-static int getAnotherTuple(PGconn *conn, int msgLength);
+static void getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
static int getCopyStart(PGconn *conn,
@@ -284,8 +284,7 @@ pqParseInput3(PGconn *conn)
conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn, msgLength))
- return;
+ getRowDescriptions(conn, msgLength);
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -340,8 +339,7 @@ pqParseInput3(PGconn *conn)
conn->result->resultStatus == PGRES_TUPLES_OK)
{
/* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, msgLength))
- return;
+ getAnotherTuple(conn, msgLength);
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -461,11 +459,10 @@ handleSyncLoss(PGconn *conn, char id, int msgLength)
* parseInput subroutine to read a 'T' (row descriptions) message.
* We'll build a new PGresult structure (unless called for a Describe
* command for a prepared statement) containing the attribute data.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine assumes that message is always processed successfully
+ * and conn->inStart is advanced past the message.
*/
-static int
+static void
getRowDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
@@ -588,7 +585,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
if (conn->queryclass == PGQUERY_DESCRIBE)
{
conn->asyncStatus = PGASYNC_READY;
- return 0;
+ return;
}
/*
@@ -597,7 +594,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
*/
/* And we're done. */
- return 0;
+ return;
advance_and_error:
/* Discard unsaved result, if any */
@@ -626,11 +623,11 @@ advance_and_error:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
/*
@@ -726,11 +723,10 @@ advance_and_error:
/*
* parseInput subroutine to read a 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine always considers that the message has been processed
+ * successfully, and conn->inStart is advanced past the message.
*/
-static int
+static void
getAnotherTuple(PGconn *conn, int msgLength)
{
PGresult *result = conn->result;
@@ -814,7 +810,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
/* Process the collected row */
errmsg = NULL;
if (pqRowProcessor(conn, &errmsg))
- return 0; /* normal, successful exit */
+ return; /* normal, successful exit */
goto set_error_result; /* pqRowProcessor failed, report it */
@@ -843,11 +839,11 @@ set_error_result:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
--
2.5.1
extended.c (text/x-csrc, 1.4K) download
/*
* Test case for PQsendDescribePrepared
* Need first to run this query on the database connection is made
* to:
* CREATE TABLE aa (a int);
*/
#include <libpq-fe.h>
#define DB_CONN_STR "host=localhost dbname=ioltas"
#define SQL_FETCH_AA "select a from aa where a = $1"
int
main(int argc, char *argv[])
{
PGconn* conn;
PGresult* res;
int status;
if ((conn = PQconnectdb(DB_CONN_STR)) == NULL)
fprintf(stderr, "Connect to '%s' failed", DB_CONN_STR);
if (PQstatus(conn) != CONNECTION_OK)
fprintf(stderr, "Connect to '%s' failed: %s",
DB_CONN_STR, PQerrorMessage(conn));
if ((res = PQprepare(conn, "sql_fetch_aa",
SQL_FETCH_AA, 2, NULL)) == NULL)
fprintf(stderr, "Preparing statement '%s' failed",
SQL_FETCH_AA);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
fprintf(stderr, "Preparing statement '%s' failed: %s",
SQL_FETCH_AA, PQerrorMessage(conn));
PQclear(res);
/* Call getParameterDescription */
if (PQsendDescribePrepared(conn, "sql_fetch_aa") == 0)
fprintf(stderr, "Call to PQsendDescribePrepared failed: %s",
PQerrorMessage(conn));
if ((res = PQgetResult(conn)) == NULL)
fprintf(stderr, "Describe statement '%s' failed: %s",
SQL_FETCH_AA, PQerrorMessage(conn));
if (PQresultStatus(res) != PGRES_COMMAND_OK)
fprintf(stderr, "Preparing statement '%s' failed: %s",
SQL_FETCH_AA, PQerrorMessage(conn));
PQclear(res);
return 0;
}
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-18 17:55 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 2 replies; 48+ messages in thread
From: Heikki Linnakangas @ 2015-09-18 17:55 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 09/14/2015 04:36 AM, Michael Paquier wrote:
> On Sat, Sep 12, 2015 at 6:11 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> On Mon, Sep 7, 2015 at 1:40 PM, Michael Paquier <michael.paquier@gmail.com>
>> wrote:
>>>
>>> On Sat, Sep 5, 2015 at 9:45 PM, Amit Kapila <amit.kapila16@gmail.com>
>>> wrote:
>>>
>>> Now, to move into the serious things...
>>>
>>> + /*
>>> + * Advance inStart to show that the copy related message has been
>>> + * processed.
>>> + */
>>> + conn->inStart = conn->inCursor;
>>> This change...
>>>
>>> + /* getCopyStart() moves
>>> inStart itself */
>>> conn->asyncStatus =
>>> PGASYNC_COPY_IN;
>>> - break;
>>> + continue;
>>> ... And this change are risky for a backpatch. And they actually
>>> break the existing replication protocol
>
> First, many thanks for providing your input! I am really looking
> forward into fixing those problems appropriately.
>
>> Can you please explain how will it break replication protocol?
>> I have done the required handling for Copy Both mode as well in attached
>> patch similar to what was done for other Copy modes in previous patch.
>> Check if you still find it as broken for replication?
>
> When not enough data has been received from the server, it seems that
> we should PQclear the existing result, and leave immediately
> pqParseInput3 with the status PGASYNC_BUSY to be able to wait for more
> data. Your patch, as-is, is breaking that promise (and this comes from
> the first versions of my patches). It seems also that we should not
> write an error message on connection in this case to be consistent in
> the behavior of back-branches. For the OOM case, we definitely need to
> take the error code path though, as your patch is correctly doing, and
> what mine legendary failed to do.
>
> + if (pqGetInt(&result->numAttributes, 2, conn))
> + {
> + errmsg = libpq_gettext("extraneous data in COPY start message");
> + goto advance_and_error;
> + }
> Here an error message is not needed, and this message should have been
> formulated as "insufficient data in blah" either way.
>
>> I have only kept the changes for COPY modes, so that once we settle on
>> those, I think similar changes could be done for getParamDescriptions()
>
> Yeah, I looked into this one as well, resulting in patch 0002
> attached. In this case we have the advantage to only receive data from
> the server, so pqPrepareAsyncResult is handling the failure just fine.
> Attached as well is the test case I used (similar to previous one,
> just extended a bit to report the error message), after getting the
> result from PQsendDescribePrepared, PQresultStatus is set correctly on
> error and reports "out of memory" to the user. What do you think about
> it?
Patches 0001 and 0002 look good to me. Two tiny nitpicks:
> --- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
> +++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
> @@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
> if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
> PQresultStatus(lastResult) == PGRES_COPY_OUT ||
> PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
> + PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
> PQstatus(streamConn) == CONNECTION_BAD)
> break;
> }
Is this really needed? AFAICS, the loop will terminate on
PGRES_FATAL_ERROR too. Without this patch, it will always return the
last result from the query, whether or not it was an error result. With
this patch, it will return the first error encountered, or last
non-error result if there is no error. In practice, there is no
difference because we don't expect multiple results from the server.
> @@ -1343,31 +1348,33 @@ getNotify(PGconn *conn)
> * parseInput already read the message type and length.
> */
> static int
> -getCopyStart(PGconn *conn, ExecStatusType copytype)
> +getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
> {
> PGresult *result;
> int nfields;
> int i;
> + const char *errmsg = NULL;
>
> result = PQmakeEmptyPGresult(conn, copytype);
> if (!result)
> - goto failure;
> + goto advance_and_error;
>
> if (pqGetc(&conn->copy_is_binary, conn))
> - goto failure;
> + goto not_enough_data;
> result->binary = conn->copy_is_binary;
> +
> /* the next two bytes are the number of fields */
> - if (pqGetInt(&(result->numAttributes), 2, conn))
> - goto failure;
> + if (pqGetInt(&result->numAttributes, 2, conn))
> + goto not_enough_data;
> nfields = result->numAttributes;
>
> /* allocate space for the attribute descriptors */
> - if (nfields > 0)
> + if (result && nfields > 0)
'result' is never NULL here, so the NULL test is still not needed.
The 0003 patch also looks OK to me as far as it goes. I feel that some
more refactoring would be in order, though. There are still many
different styles for handling a command: sometimes it's done inline in
the case-statement, sometimes it calls out to a separate function.
Sometimes the function moves inStart, sometimes it does not. On error
(e.g. short message), sometimes the function returns 'false', sometimes
it sets an error message itself.
Patches 0001 and 0002 look small enough that we probably could backpatch
them, so that would leave 0003 as a optional master-only cleanup.
I spent some time writing a regression test for this. This is pretty
difficult to test otherwise, and it's a good candidate for automated,
exchaustive testing. The only difficulty is injecting the malloc()
failures in a cross-platform way. I ended up with a glibc-only solution
that uses glibc's malloc() hooks. Other alternatives I considered were
Linux-specific LD_PRELOAD, GNU ld specific -wrap option. One
cross-platform solution would be to #define malloc() and friends to
wrapper functions, and compile a special version of libpq. Anyway, I
came up with the attached test program. It hangs without your fixes, and
works with the patches applied. Thoughts?
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments:
0001-Initial-version-of-libpq-mallocfail-tester.patch (text/x-diff, 13.8K) download
From f83b781b86e65263890cbe58347063cc1ceabcde Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Fri, 18 Sep 2015 14:17:13 +0300
Subject: [PATCH 1/1] Initial version of libpq mallocfail tester
---
src/interfaces/libpq/test/Makefile | 11 +-
src/interfaces/libpq/test/mallocfail.c | 83 ++++++++
src/interfaces/libpq/test/mallocfail.h | 23 ++
src/interfaces/libpq/test/oom-test.c | 377 +++++++++++++++++++++++++++++++++
4 files changed, 493 insertions(+), 1 deletion(-)
create mode 100644 src/interfaces/libpq/test/mallocfail.c
create mode 100644 src/interfaces/libpq/test/mallocfail.h
create mode 100644 src/interfaces/libpq/test/oom-test.c
diff --git a/src/interfaces/libpq/test/Makefile b/src/interfaces/libpq/test/Makefile
index ab41dc3..92fbf7f 100644
--- a/src/interfaces/libpq/test/Makefile
+++ b/src/interfaces/libpq/test/Makefile
@@ -9,14 +9,23 @@ endif
override CPPFLAGS := -I$(libpq_srcdir) $(CPPFLAGS)
override LDLIBS := $(libpq_pgport) $(LDLIBS)
-PROGS = uri-regress
+PROGS = uri-regress oom-test
all: $(PROGS)
+# The malloc hooks in glibc are marked as deprecated. We want to use them
+# anyway, the alternatives are much more complicated, so just silence the
+# warnings.
+mallocfail.o: CPPFLAGS := -Wno-deprecated-declarations
+
+oom-test$(X): mallocfail.o
+
installcheck: all
SRCDIR='$(top_srcdir)' SUBDIR='$(subdir)' \
$(PERL) $(top_srcdir)/$(subdir)/regress.pl
clean distclean maintainer-clean:
rm -f $(PROGS)
+ rm -f mallocfail.o oom-test.o
+ rm uri-regress.o
rm -f regress.out regress.diff
diff --git a/src/interfaces/libpq/test/mallocfail.c b/src/interfaces/libpq/test/mallocfail.c
new file mode 100644
index 0000000..e327e9c
--- /dev/null
+++ b/src/interfaces/libpq/test/mallocfail.c
@@ -0,0 +1,83 @@
+/*
+ * mallocfail.c
+ * Helper functions for simulating malloc() failures.
+ *
+ * This uses glibc-specific malloc hooks to hijack calls to malloc().
+ * Call mallocfail_init() to initialize. After that, this module will call
+ * a function called "mallocfail_callback" on every malloc() call, which must
+ * be defined elsewhere. If the callback returns 1, we return NULL to the
+ * caller of malloc(), otherwise we let the allocation to succeed (the libc
+ * libc malloc() call might still fail if you get a genuine out-of-memory
+ * error).
+ *
+ * Portions Copyright (c) 2015, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/interfaces/libpq/test/mallocfail.c
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <malloc.h>
+
+#include "mallocfail.h"
+
+static void *(*orig_malloc) (size_t size, const void *caller);
+static void *(*orig_realloc) (void *ptr, size_t size, const void *caller);
+
+static void *mallocfail_malloc(size_t size, const void *caller);
+static void *mallocfail_realloc(void *ptr, size_t size, const void *caller);
+
+static void *
+mallocfail_malloc(size_t size, const void *caller)
+{
+ void *result;
+
+ if (mallocfail_callback("malloc"))
+ return NULL;
+
+ /* restore original hooks */
+ __malloc_hook = orig_malloc;
+ __realloc_hook = orig_realloc;
+
+ result = malloc(size);
+
+ /* restore myself */
+ __malloc_hook = mallocfail_malloc;
+ __realloc_hook = mallocfail_realloc;
+
+ return result;
+}
+
+static void *
+mallocfail_realloc(void *ptr, size_t size, const void *caller)
+{
+ void *result;
+
+ if (mallocfail_callback("realloc"))
+ return NULL;
+
+ /* restore original hooks */
+ __malloc_hook = orig_malloc;
+ __realloc_hook = orig_realloc;
+
+ result = realloc(ptr, size);
+
+ /* restore myself */
+ __malloc_hook = mallocfail_malloc;
+ __realloc_hook = mallocfail_realloc;
+
+ return result;
+}
+
+void
+mallocfail_init(void)
+{
+ orig_malloc = __malloc_hook;
+ orig_realloc = __realloc_hook;
+ __malloc_hook = mallocfail_malloc;
+ __realloc_hook = mallocfail_realloc;
+}
diff --git a/src/interfaces/libpq/test/mallocfail.h b/src/interfaces/libpq/test/mallocfail.h
new file mode 100644
index 0000000..727bf7e
--- /dev/null
+++ b/src/interfaces/libpq/test/mallocfail.h
@@ -0,0 +1,23 @@
+/*-------------------------------------------------------------------------
+ *
+ * mallocfail.h
+ *
+ * Definitions for malloc() out-of-memory simulation
+ *
+ * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/interfaces/libpq/test/mallocfail.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MALLOCFAIL_H
+#define MALLOCFAIL_H
+
+/* defined in mallocfail.c */
+extern void mallocfail_init(void);
+
+/* defined in oomtest.c */
+extern int mallocfail_callback(const char *funcname);
+
+#endif /* MALLOCFAIL_H */
diff --git a/src/interfaces/libpq/test/oom-test.c b/src/interfaces/libpq/test/oom-test.c
new file mode 100644
index 0000000..fd40ee9
--- /dev/null
+++ b/src/interfaces/libpq/test/oom-test.c
@@ -0,0 +1,377 @@
+/*
+ * oom-test.c
+ * A test program for libpq behaviour on out-of-memory
+ *
+ * This relies on a mechanism to intercept malloc() calls, see mallocfail.c.
+ * The intercepter must call our mallocfail_callback() function for every
+ * intercepted malloc() call, which will decide whether to let the call
+ * to succeed.
+ *
+ * Portions Copyright (c) 2012-2015, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/interfaces/libpq/test/oom-test.c
+ */
+#include <libpq-fe.h>
+
+#include "c.h"
+
+#include "mallocfail.h"
+
+/* A global variable that counts malloc() calls issued so far */
+static int malloc_counter = 0;
+static bool mallocfail_enabled = false;
+
+/* If non-zero, cause this allocation to fail. */
+static int malloc_fail_at = 0;
+
+/*
+ * Checks that a result set looks correct. We know exactly what the result sets
+ * used in these tests should look like; two rows and two columns:
+ *
+ * foo1 foo2
+ * bar1 bar2
+ */
+static bool
+check_result_set(PGresult *res)
+{
+ /*
+ * If the result is not correct, print it out to stderr for debugging.
+ */
+ if (PQntuples(res) != 2 || PQnfields(res) != 2 ||
+ strcmp(PQgetvalue(res, 0, 0), "foo1") != 0 ||
+ strcmp(PQgetvalue(res, 0, 1), "foo2") != 0 ||
+ strcmp(PQgetvalue(res, 1, 0), "bar1") != 0 ||
+ strcmp(PQgetvalue(res, 1, 1), "bar2") != 0)
+ {
+ int row,
+ col;
+
+ fprintf(stderr, "unexpected result set with %d rows and %d cols:\n",
+ PQntuples(res), PQnfields(res));
+ for (row = 0; row < PQntuples(res); row++)
+ {
+ for (col = 0; col < PQnfields(res); col++)
+ {
+ if (col > 0)
+ fprintf(stderr, "\t");
+ fprintf(stderr, "%s", PQgetvalue(res, row, col));
+ }
+ fprintf(stderr, "\n");
+ }
+ return FALSE;
+ }
+ else
+ {
+ printf("Got correct result set\n");
+ return TRUE;
+ }
+}
+
+/*
+ * Check that a result indicates an out-of-memory error (and not some
+ * other kind of error).
+ */
+static bool
+check_error_is_oom(const char *funcname, PGresult *res)
+{
+ char *errmsg = PQresultErrorMessage(res);
+
+ /* XXX: This won't work with non-English locale. */
+ if (strncmp(errmsg, "out of memory", strlen("out of memory")) == 0)
+ {
+ /* got "out of memory", that's OK. */
+ printf("%s failed with OOM: %s\n", funcname, errmsg);
+ return TRUE;
+ }
+ else
+ {
+ /* any other error is not expected */
+ fprintf(stderr, "%s returned error: %s\n", funcname, errmsg);
+ return FALSE;
+ }
+}
+
+/*
+ * Test functions.
+ *
+ * The test driver, main/run_tests will call these repeatedly, with the
+ * malloc hook set up to fail at some calls.
+ */
+
+/* Test PQexec() */
+static bool
+test_PQexec(PGconn *conn)
+{
+ PGresult *res;
+ bool success;
+
+ mallocfail_enabled = true;
+ res = PQexec(conn, "values ('foo1', 'foo2'), ('bar1', 'bar2')");
+ mallocfail_enabled = false;
+
+ /*
+ * There are two valid outcomes: 1. success 2. Ran out of memory
+ */
+ if (PQresultStatus(res) == PGRES_TUPLES_OK)
+ success = check_result_set(res);
+ else if (PQresultStatus(res) == PGRES_FATAL_ERROR)
+ success = check_error_is_oom("PQexec", res);
+ else
+ {
+ fprintf(stderr, "PQexec returned unexpected result status: %s\n",
+ PQresStatus(PQresultStatus(res)));
+ success = FALSE;
+ }
+
+ PQclear(res);
+
+ return success;
+}
+
+
+/* Test PQprepare() + PQdescribePrepared() + PQexec */
+static bool
+test_PQprepare(PGconn *conn)
+{
+ PGresult *res;
+ bool success = TRUE;
+ char *param = "foo1";
+
+ /* 1. Call PQPrepare() to prepare an unnamed statement */
+ mallocfail_enabled = true;
+ res = PQprepare(conn, "",
+ "values ($1, 'foo2'), ('bar1', 'bar2')", 1, NULL);
+ mallocfail_enabled = false;
+
+ if (PQresultStatus(res) == PGRES_FATAL_ERROR)
+ success = check_error_is_oom("PQprepare", res);
+ else if (PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ fprintf(stderr, "PQprepare returned unexpected result status: %s\n",
+ PQresStatus(PQresultStatus(res)));
+ success = FALSE;
+ }
+ PQclear(res);
+
+ if (!success)
+ return FALSE;
+
+ /* 2. Call PQdescribePrepared */
+ mallocfail_enabled = true;
+ res = PQdescribePrepared(conn, "");
+ mallocfail_enabled = false;
+
+ if (PQresultStatus(res) == PGRES_FATAL_ERROR)
+ success = check_error_is_oom("PQdescribePrepared", res);
+ else if (PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ fprintf(stderr, "PQdescribePrepared returned unexpected result status: %s\n",
+ PQresStatus(PQresultStatus(res)));
+ success = FALSE;
+ }
+ PQclear(res);
+
+ if (!success)
+ return FALSE;
+
+
+ /* 2. Call PQexecPrepared */
+ mallocfail_enabled = true;
+ res = PQexecPrepared(conn, "", 1, (const char *const *) ¶m, NULL, NULL, 0);
+ mallocfail_enabled = false;
+
+ if (PQresultStatus(res) == PGRES_TUPLES_OK)
+ success = check_result_set(res);
+ else if (PQresultStatus(res) == PGRES_FATAL_ERROR)
+ success = check_error_is_oom("PQexecPrepared", res);
+ else
+ {
+ fprintf(stderr, "PQexecPrepared returned unexpected result status: %s\n",
+ PQresStatus(PQresultStatus(res)));
+ success = FALSE;
+ }
+ PQclear(res);
+
+ if (!success)
+ return FALSE;
+
+
+ return success;
+}
+
+
+/* Test COPY FROM STDIN */
+static bool
+test_COPY_FROM(PGconn *conn)
+{
+ PGresult *res;
+ bool success;
+ static bool table_created = false;
+ char *rowdata[2] = { "foo1\t\foo2\n", "bar1\tbar2\n" };
+ int rc;
+ int i;
+
+ if (!table_created)
+ {
+ res = PQexec(conn, "CREATE TEMPORARY TABLE copytest (col1 text, col2 text) ON COMMIT DELETE ROWS");
+ if (PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ fprintf(stderr, "failed to create temporary table: %s",
+ PQerrorMessage(conn));
+ return false;
+ }
+ table_created = true;
+ }
+
+ mallocfail_enabled = true;
+ res = PQexec(conn, "COPY copytest FROM STDIN");
+ mallocfail_enabled = false;
+ if (PQresultStatus(res) != PGRES_COPY_IN)
+ {
+ fprintf(stderr, "unexpected result for COPY FROM STDIN: %s",
+ PQerrorMessage(conn));
+ return false;
+ }
+
+ mallocfail_enabled = true;
+ for (i = 0; i < 2; i++)
+ {
+ rc = PQputCopyData(conn, rowdata[i], strlen(rowdata[i]));
+ if (rc == -1)
+ {
+ mallocfail_enabled = false;
+ fprintf(stderr, "PQputCopyData failed: %s\n", PQerrorMessage(conn));
+ return false;
+ }
+ }
+
+ rc = PQputCopyEnd(conn, NULL);
+ mallocfail_enabled = false;
+ if (rc == -1)
+ {
+ fprintf(stderr, "PQputCopyEnd failed: %s\n", PQerrorMessage(conn));
+ return false;
+ }
+
+ mallocfail_enabled = true;
+ res = PQgetResult(conn);
+ mallocfail_enabled = false;
+
+ /*
+ * There are two valid outcomes: 1. success 2. Ran out of memory
+ */
+ if (PQresultStatus(res) == PGRES_COMMAND_OK)
+ success = true;
+ else if (PQresultStatus(res) == PGRES_FATAL_ERROR)
+ success = check_error_is_oom("PQexec", res);
+ else
+ {
+ fprintf(stderr, "PQexec returned unexpected result status: %s\n",
+ PQresStatus(PQresultStatus(res)));
+ success = false;
+ }
+
+ PQclear(res);
+
+ return success;
+}
+
+/*
+ * This function needs to be called for every malloc() call. It decides
+ * whether the call should be let to succeed, or we should simulate OOM and
+ * return NULL to the caller.
+ */
+int
+mallocfail_callback(const char *func)
+{
+ if (!mallocfail_enabled)
+ return 0;
+
+ malloc_counter++;
+ if (malloc_counter == malloc_fail_at)
+ {
+ printf("%s failing: %d!\n", func, malloc_counter);
+ return 1;
+ }
+ else
+ {
+ printf("%s called: %d\n", func, malloc_counter);
+ return 0;
+ }
+}
+
+/*
+ * Run a test function multiple times. In each iteration, cause one malloc()
+ * call to fail.
+ */
+static void
+run_testfunc(PGconn *conn, const char *testname, bool (*testfunc) (PGconn *conn))
+{
+ int i;
+ int nmallocs;
+
+ /*
+ * Run the test once without any malloc() failures, to count the number of
+ * malloc() calls it makes when run normally.
+ */
+ malloc_counter = 0;
+ malloc_fail_at = 0;
+ if (!testfunc(conn))
+ {
+ fprintf(stderr, "%s pre-test failed!\n", testname);
+ return;
+ }
+ nmallocs = malloc_counter;
+
+ /*
+ * If our callback isn't get called at all, the most likely reason is that
+ * the failure injecting code was not loaded correctly.
+ */
+ if (nmallocs == 0)
+ {
+ fprintf(stderr, "malloc() callback was not called in %s test.\n", testname);
+ return;
+ }
+ printf("%s called malloc() %d times\n", testname, nmallocs);
+
+ /*
+ * Ok, now run the test again several times, causing a different malloc()
+ * call to fail each time.
+ */
+ for (i = 1; i <= nmallocs; i++)
+ {
+ printf("Running %s test, with failure at malloc call %d...\n", testname, i);
+ malloc_counter = 0;
+ malloc_fail_at = i;
+ testfunc(conn);
+ malloc_fail_at = 0;
+ }
+}
+
+int
+main(int argc, char *argv[])
+{
+ PGconn *conn;
+
+ if ((conn = PQconnectdb("")) == NULL)
+ {
+ fprintf(stderr, "PQconnectdb failed");
+ exit(1);
+ }
+
+ if (PQstatus(conn) != CONNECTION_OK)
+ {
+ fprintf(stderr, "PQconnectdb failed: %s",
+ PQerrorMessage(conn));
+ exit(1);
+ }
+
+ mallocfail_init();
+
+ run_testfunc(conn, "PQexec", &test_PQexec);
+ run_testfunc(conn, "PQprepare", &test_PQprepare);
+ run_testfunc(conn, "COPY FROM STDIN", &test_COPY_FROM);
+
+ return 0;
+}
--
2.1.4
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-18 22:17 Michael Paquier <michael.paquier@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
1 sibling, 0 replies; 48+ messages in thread
From: Michael Paquier @ 2015-09-18 22:17 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Sep 18, 2015 at 12:55 PM, Heikki Linnakangas wrote:
> On 09/14/2015 04:36 AM, Michael Paquier wrote:
> Patches 0001 and 0002 look good to me. Two tiny nitpicks:
>
>> --- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
>> +++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
>> @@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
>> if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
>> PQresultStatus(lastResult) == PGRES_COPY_OUT ||
>> PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
>> + PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
>> PQstatus(streamConn) == CONNECTION_BAD)
>> break;
>> }
>
>
> Is this really needed? AFAICS, the loop will terminate on PGRES_FATAL_ERROR
> too. Without this patch, it will always return the last result from the
> query, whether or not it was an error result. With this patch, it will
> return the first error encountered, or last non-error result if there is no
> error. In practice, there is no difference because we don't expect multiple
> results from the server.
Yes, you are right. PQgetResult is doing the necessary processing
here. This seems to be some remnant of previous testing around the
replication protocol, and while it has no real incidence for the
server, it may for applications that rely on libpqwalreceiver.so...
Hence let's remove it. Thanks for pointing out that.
>> @@ -1343,31 +1348,33 @@ getNotify(PGconn *conn)
>> [...]
>> + if (result && nfields > 0)
>
> 'result' is never NULL here, so the NULL test is still not needed.
I thought I removed all of them.
> The 0003 patch also looks OK to me as far as it goes. I feel that some more
> refactoring would be in order, though. There are still many different styles
> for handling a command: sometimes it's done inline in the case-statement,
> sometimes it calls out to a separate function. Sometimes the function moves
> inStart, sometimes it does not. On error (e.g. short message), sometimes the
> function returns 'false', sometimes it sets an error message itself.
Sure. I had in mind a backpatch as the main goal of this set of
patches, and there is surely more room than simply removing all the
dead code paths that 0003 is currently doing. Why not simply fixing
the holes in the current logic to begin, and have the refactoring
patch as something to work on for the next CF? I don't mind working on
it FWIW. That's just a larger topic than what is discussed on this
thread.
> Patches 0001 and 0002 look small enough that we probably could backpatch
> them, so that would leave 0003 as a optional master-only cleanup.
That makes sense, and what I had in mind as well. Attached are updated
patches, feel free to ignore 0003, that's the same as before only
removing the dead code.
> I spent some time writing a regression test for this. This is pretty
> difficult to test otherwise, and it's a good candidate for automated,
> exchaustive testing. The only difficulty is injecting the malloc() failures
> in a cross-platform way. I ended up with a glibc-only solution that uses
> glibc's malloc() hooks. Other alternatives I considered were Linux-specific
> LD_PRELOAD, GNU ld specific -wrap option. One cross-platform solution would
> be to #define malloc() and friends to wrapper functions, and compile a
> special version of libpq. Anyway, I came up with the attached test program.
> It hangs without your fixes, and works with the patches applied. Thoughts?
That's not going to work on OSX/BSD (as those callbacks are not
present) and Windows, but testing that on Linux only looks fine to me,
and locating it where it is, aka in a non-default compile path is
definitely better. You should add .gitignore in
src/interfaces/libpq/test/ (uri-regress is missing as well btw).
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (3 files, .tar.gz)
0001-Fix-OOM-error-handling-in-COPY-protocol-of-libpq.patch (text/x-diff, 6.5K) download
From 6bbfc1d3e3172870e587c5e7d5a5848ea172c4a4 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Fri, 18 Sep 2015 17:02:39 -0500
Subject: [PATCH 1/3] Fix OOM error handling in COPY protocol of libpq
An OOM occurring while all the data needed by process from server has been
received can result in an infinite loop when parsing the output message.
getCopyStart is switched to discard a a message read from server in case of
server and any subsequent ones when receiving data from server for
PGASYNC_COPY_OUT, and not wait for any additional data when input is expected
via PGASYNC_COPY_IN. In the case of PGASYNC_COPY_BOTH, both concepts apply.
---
src/interfaces/libpq/fe-exec.c | 12 +++++++
src/interfaces/libpq/fe-protocol3.c | 71 +++++++++++++++++++++++++++++--------
2 files changed, 68 insertions(+), 15 deletions(-)
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..b84e5ed 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1801,6 +1801,10 @@ getCopyResult(PGconn *conn, ExecStatusType copytype)
return pqPrepareAsyncResult(conn);
}
+ /* If error has occured, return a PGRES_FATAL_ERROR result */
+ if (conn->result && conn->result->resultStatus == PGRES_FATAL_ERROR)
+ return pqPrepareAsyncResult(conn);
+
/* If we have an async result for the COPY, return that */
if (conn->result && conn->result->resultStatus == copytype)
return pqPrepareAsyncResult(conn);
@@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if we are in copy mode and error has occurred, the pending results
+ * will be discarded during next execution in PQexecStart.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
result->resultStatus == PGRES_COPY_BOTH ||
conn->status == CONNECTION_BAD)
break;
+ else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
+ conn->asyncStatus == PGASYNC_COPY_OUT ||
+ conn->asyncStatus == PGASYNC_COPY_BOTH) &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
}
return lastResult;
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..1079911 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -49,7 +49,9 @@ static int getParamDescriptions(PGconn *conn);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -362,22 +364,25 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
- break;
+ continue;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
- break;
+ continue;
case 'd': /* Copy Data */
/*
@@ -1343,22 +1348,24 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ goto advance_and_error;
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ goto not_enough_data;
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ goto not_enough_data;
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1367,7 +1374,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,7 +1383,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ goto not_enough_data;
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1388,11 +1395,45 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.5.1
0002-Fix-OOM-error-handling-in-BIND-protocol-of-libpq.patch (text/x-diff, 3.6K) download
From 2a68e9c7fcac2046eb5ec60b396faec1250ab5cd Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Fri, 18 Sep 2015 17:02:59 -0500
Subject: [PATCH 2/3] Fix OOM error handling in BIND protocol of libpq
---
src/interfaces/libpq/fe-protocol3.c | 54 ++++++++++++++++++++++++++++++-------
1 file changed, 45 insertions(+), 9 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 1079911..e98f99b 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,7 +45,7 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
@@ -331,9 +331,10 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
return;
- break;
+ /* getParamDescriptions() moves inStart itself */
+ continue;
case 'D': /* Data Row */
if (conn->result != NULL &&
conn->result->resultStatus == PGRES_TUPLES_OK)
@@ -642,20 +643,21 @@ advance_and_error:
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ goto advance_and_error;
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ goto not_enough_data;
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -664,7 +666,7 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -674,17 +676,51 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ goto not_enough_data;
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.5.1
0003-Remove-dead-code-of-libpq-protocol-3.patch (text/x-diff, 4.8K) download
From 7968bd3cc545bb5e0793e3b833d03fdd0cf2a860 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Mon, 7 Sep 2015 22:24:29 +0900
Subject: [PATCH 3/3] Remove dead code of libpq protocol 3
getRowDescriptions and getAnotherTuple contained a code path that could
be used to stop message parsing which is visibly a copy/paste of the
equivalent code if protocol 2, however it has never been used.
---
src/interfaces/libpq/fe-protocol3.c | 46 +++++++++++++++++--------------------
1 file changed, 21 insertions(+), 25 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index e98f99b..9ce791f 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -44,9 +44,9 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
-static int getRowDescriptions(PGconn *conn, int msgLength);
+static void getRowDescriptions(PGconn *conn, int msgLength);
static int getParamDescriptions(PGconn *conn, int msgLength);
-static int getAnotherTuple(PGconn *conn, int msgLength);
+static void getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
static int getCopyStart(PGconn *conn,
@@ -284,8 +284,7 @@ pqParseInput3(PGconn *conn)
conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
- if (getRowDescriptions(conn, msgLength))
- return;
+ getRowDescriptions(conn, msgLength);
/* getRowDescriptions() moves inStart itself */
continue;
}
@@ -340,8 +339,7 @@ pqParseInput3(PGconn *conn)
conn->result->resultStatus == PGRES_TUPLES_OK)
{
/* Read another tuple of a normal query response */
- if (getAnotherTuple(conn, msgLength))
- return;
+ getAnotherTuple(conn, msgLength);
/* getAnotherTuple() moves inStart itself */
continue;
}
@@ -461,11 +459,10 @@ handleSyncLoss(PGconn *conn, char id, int msgLength)
* parseInput subroutine to read a 'T' (row descriptions) message.
* We'll build a new PGresult structure (unless called for a Describe
* command for a prepared statement) containing the attribute data.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine assumes that message is always processed successfully
+ * and conn->inStart is advanced past the message.
*/
-static int
+static void
getRowDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
@@ -588,7 +585,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
if (conn->queryclass == PGQUERY_DESCRIBE)
{
conn->asyncStatus = PGASYNC_READY;
- return 0;
+ return;
}
/*
@@ -597,7 +594,7 @@ getRowDescriptions(PGconn *conn, int msgLength)
*/
/* And we're done. */
- return 0;
+ return;
advance_and_error:
/* Discard unsaved result, if any */
@@ -626,11 +623,11 @@ advance_and_error:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
/*
@@ -726,11 +723,10 @@ advance_and_error:
/*
* parseInput subroutine to read a 'D' (row data) message.
* We fill rowbuf with column pointers and then call the row processor.
- * Returns: 0 if processed message successfully, EOF to suspend parsing
- * (the latter case is not actually used currently).
- * In either case, conn->inStart has been advanced past the message.
+ * This routine always considers that the message has been processed
+ * successfully, and conn->inStart is advanced past the message.
*/
-static int
+static void
getAnotherTuple(PGconn *conn, int msgLength)
{
PGresult *result = conn->result;
@@ -814,7 +810,7 @@ getAnotherTuple(PGconn *conn, int msgLength)
/* Process the collected row */
errmsg = NULL;
if (pqRowProcessor(conn, &errmsg))
- return 0; /* normal, successful exit */
+ return; /* normal, successful exit */
goto set_error_result; /* pqRowProcessor failed, report it */
@@ -843,11 +839,11 @@ set_error_result:
pqSaveErrorResult(conn);
/*
- * Return zero to allow input parsing to continue. Subsequent "D"
- * messages will be ignored until we get to end of data, since an error
- * result is already set up.
+ * Return to allow input parsing to continue. Subsequent "D" messages
+ * will be ignored until we get to end of data, since an error result
+ * is already set up.
*/
- return 0;
+ return;
}
--
2.5.1
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-19 04:32 Amit Kapila <amit.kapila16@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
1 sibling, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-09-19 04:32 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Michael Paquier <michael.paquier@gmail.com>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Sep 18, 2015 at 11:25 PM, Heikki Linnakangas <hlinnaka@iki.fi>
wrote:
> On 09/14/2015 04:36 AM, Michael Paquier wrote:
>
> Patches 0001 and 0002 look good to me. Two tiny nitpicks:
>
> --- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
>> +++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
>> @@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
>> if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
>> PQresultStatus(lastResult) == PGRES_COPY_OUT ||
>> PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
>> + PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
>> PQstatus(streamConn) == CONNECTION_BAD)
>> break;
>> }
>>
>
> Is this really needed? AFAICS, the loop will terminate on
> PGRES_FATAL_ERROR too.
IIRC, this is required to sanely report "out of memory" error in case
of replication protocol (master-standby setup). This loop and in-particular
this check is quite similar to PQexecFinish() functions check and loop
where we return last result. I think it is better to keep both the places
in-sync
and also I think this is required to report the error appropriately. I have
tried manual debugging for the out of memory error for this case and
it works well with this check and without the check it doesn't report
the error in an appropriate way(don't remember exactly what was
the difference). If required, I can again try to reproduce the scenario
and share the exact report.
> Patches 0001 and 0002 look small enough that we probably could backpatch
> them, so that would leave 0003 as a optional master-only cleanup.
>
>
+
+advance_and_error:
+ /* Discard unsaved result, if any */
This part seems to be common in both patches and is also being
used in getRowDescriptions(), we can have a common routine for
that part, if you see any benefit in same.
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-09-19 05:14 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-09-19 05:14 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Sep 18, 2015 at 11:32 PM, Amit Kapila wrote:
> IIRC, this is required to sanely report "out of memory" error in case
> of replication protocol (master-standby setup). This loop and
in-particular
> this check is quite similar to PQexecFinish() functions check and loop
> where we return last result. I think it is better to keep both the places
> in-sync
> and also I think this is required to report the error appropriately. I
have
> tried manual debugging for the out of memory error for this case and
> it works well with this check and without the check it doesn't report
> the error in an appropriate way(don't remember exactly what was
> the difference). If required, I can again try to reproduce the scenario
> and share the exact report.
I just had a look at that again... Put for example a call to pg_usleep in
libpqrcv_identify_system after executing IDENTIFY_SYSTEM and before calling
PQresultStatus, then take a breakpoint on the WAL receiver process when
starting up a standby. This gives plenty of room to emulate the OOM failure
in getCopyStart. When the check on PGRES_FATAL_ERROR is not added and when
emulating the OOM immediately, libpqrcv_PQexec loops twice and thinks it
can start up strrep but fails afterwards. Here is the failure seen from the
standby:
LOG: started streaming WAL from primary at 0/3000000 on timeline 1
FATAL: could not send data to WAL stream: server closed the connection
unexpectedly
And from the master:
LOG: unexpected EOF on standby connection
The WAL receiver process ultimately restarts after.
When the check on PGRES_FATAL_ERROR is added, strrep fails to start
appropriately and the error is fetched correctly by the WAL receiver:
FATAL: could not start WAL streaming: out of memory
In short: Amit seems right to have added this check.
Note for later: looking at patches during conferences is really a bad habit.
--
Michael
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-10-10 12:06 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-10-10 12:06 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Sep 19, 2015 at 10:44 AM, Michael Paquier <michael.paquier@gmail.com
> wrote:
>
>
> On Fri, Sep 18, 2015 at 11:32 PM, Amit Kapila wrote:
> > IIRC, this is required to sanely report "out of memory" error in case
> > of replication protocol (master-standby setup). This loop and
in-particular
> > this check is quite similar to PQexecFinish() functions check and loop
> > where we return last result. I think it is better to keep both the
places
> > in-sync
> > and also I think this is required to report the error appropriately. I
have
> > tried manual debugging for the out of memory error for this case and
> > it works well with this check and without the check it doesn't report
> > the error in an appropriate way(don't remember exactly what was
> > the difference). If required, I can again try to reproduce the scenario
> > and share the exact report.
>
> I just had a look at that again... Put for example a call to pg_usleep in
libpqrcv_identify_system after executing IDENTIFY_SYSTEM and before calling
PQresultStatus, then take a breakpoint on the WAL receiver process when
starting up a standby. This gives plenty of room to emulate the OOM failure
in getCopyStart. When the check on PGRES_FATAL_ERROR is not added and when
emulating the OOM immediately, libpqrcv_PQexec loops twice and thinks it
can start up strrep but fails afterwards. Here is the failure seen from the
standby:
> LOG: started streaming WAL from primary at 0/3000000 on timeline 1
> FATAL: could not send data to WAL stream: server closed the connection
unexpectedly
> And from the master:
> LOG: unexpected EOF on standby connection
> The WAL receiver process ultimately restarts after.
>
> When the check on PGRES_FATAL_ERROR is added, strrep fails to start
appropriately and the error is fetched correctly by the WAL receiver:
> FATAL: could not start WAL streaming: out of memory
>
> In short: Amit seems right to have added this check.
>
Okay, in that case, you can revert that change in your first patch and
then that patch will be Ready for committer.
In second patch [1], the handling is to continue on error as below:
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
return;
- break;
+ /* getParamDescriptions() moves inStart itself */
+ continue;
Now, assume there is "out of memory" error in getParamDescription(),
the next message is 'T' which leads to a call to getRowDescriptions()
and in that function if there is an error in below part of code, then I
think it will just overwrite the previous "out of memory" error (I have
tried by manual debugging and forcefully generating the below error):
getRowDescriptions()
{
..
if (pqGetInt(&(result->numAttributes), 2, conn))
{
/* We should not run out of data here, so complain */
errmsg = libpq_gettext("insufficient data in \"T\" message");
goto advance_and_error;
}
..
}
Here, the point to note is that for similar handling of error from
getRowDescriptions(), we just skip the consecutive 'D' messages
by checking resultStatus.
I think overwriting of error for this case is not the right behaviour.
[1] - 0002-Fix-OOM-error-handling-in-BIND-protocol-of-libpq-2.patch
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-10-11 13:01 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-10-11 13:01 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sat, Oct 10, 2015 at 9:06 PM, Amit Kapila wrote:
> Okay, in that case, you can revert that change in your first patch and
> then that patch will be Ready for committer.
Yep. Done.
> In second patch [1], the handling is to continue on error as below:
>
> - if (getParamDescriptions(conn))
> + if (getParamDescriptions(conn, msgLength))
> return;
> - break;
> + /* getParamDescriptions() moves inStart itself */
> + continue;
>
> Now, assume there is "out of memory" error in getParamDescription(),
> the next message is 'T' which leads to a call to getRowDescriptions()
> and in that function if there is an error in below part of code, then I
> think it will just overwrite the previous "out of memory" error (I have
> tried by manual debugging and forcefully generating the below error):
> Here, the point to note is that for similar handling of error from
> getRowDescriptions(), we just skip the consecutive 'D' messages
> by checking resultStatus.
> I think overwriting of error for this case is not the right behaviour.
> [1] - 0002-Fix-OOM-error-handling-in-BIND-protocol-of-libpq-2.patch
Yeah, this behavior is caused by this piece of code:
@@ -600,7 +601,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
advance_and_error:
/* Discard unsaved result, if any */
if (result && result != conn->result)
PQclear(result);
An idea may be to check for conn->result->resultStatus !=
PGRES_FATAL_ERROR to concatenate correctly the error messages using
pqCatenateResultError. But just returning the first error encountered
as you mention would be more natural. So I updated the patch this way.
Regards,
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (2 files, .tar.gz)
0001-Fix-OOM-error-handling-in-COPY-protocol-of-libpq.patch (application/x-patch, 7.1K) download
From a556405d747b87c4c6b82718d962a8aaab30ad37 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Sun, 11 Oct 2015 20:46:40 +0900
Subject: [PATCH 1/2] Fix OOM error handling in COPY protocol of libpq
An OOM occurring while all the data needed by process from server has been
received can result in an infinite loop when parsing the output message.
getCopyStart is switched to discard a a message read from server in case of
server and any subsequent ones when receiving data from server for
PGASYNC_COPY_OUT, and not wait for any additional data when input is expected
via PGASYNC_COPY_IN. In the case of PGASYNC_COPY_BOTH, both concepts apply.
---
.../libpqwalreceiver/libpqwalreceiver.c | 1 +
src/interfaces/libpq/fe-exec.c | 12 ++++
src/interfaces/libpq/fe-protocol3.c | 71 +++++++++++++++++-----
3 files changed, 69 insertions(+), 15 deletions(-)
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index b7bbcf6..8fae3a9 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
PQresultStatus(lastResult) == PGRES_COPY_OUT ||
PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
+ PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
PQstatus(streamConn) == CONNECTION_BAD)
break;
}
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..b84e5ed 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1801,6 +1801,10 @@ getCopyResult(PGconn *conn, ExecStatusType copytype)
return pqPrepareAsyncResult(conn);
}
+ /* If error has occured, return a PGRES_FATAL_ERROR result */
+ if (conn->result && conn->result->resultStatus == PGRES_FATAL_ERROR)
+ return pqPrepareAsyncResult(conn);
+
/* If we have an async result for the COPY, return that */
if (conn->result && conn->result->resultStatus == copytype)
return pqPrepareAsyncResult(conn);
@@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if we are in copy mode and error has occurred, the pending results
+ * will be discarded during next execution in PQexecStart.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
result->resultStatus == PGRES_COPY_BOTH ||
conn->status == CONNECTION_BAD)
break;
+ else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
+ conn->asyncStatus == PGASYNC_COPY_OUT ||
+ conn->asyncStatus == PGASYNC_COPY_BOTH) &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
}
return lastResult;
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..1079911 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -49,7 +49,9 @@ static int getParamDescriptions(PGconn *conn);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -362,22 +364,25 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
- break;
+ continue;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
- break;
+ continue;
case 'd': /* Copy Data */
/*
@@ -1343,22 +1348,24 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ goto advance_and_error;
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ goto not_enough_data;
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ goto not_enough_data;
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1367,7 +1374,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,7 +1383,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ goto not_enough_data;
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1388,11 +1395,45 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.6.0
0002-Fix-OOM-error-handling-in-BIND-protocol-of-libpq.patch (application/x-patch, 4.3K) download
From 64d7ae9b2966f3aa57dc3359d9047436c49fb10f Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Sun, 11 Oct 2015 21:57:27 +0900
Subject: [PATCH 2/2] Fix OOM error handling in BIND protocol of libpq
---
src/interfaces/libpq/fe-protocol3.c | 67 +++++++++++++++++++++++++++++++------
1 file changed, 56 insertions(+), 11 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 1079911..a8c672a 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,7 +45,7 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
@@ -280,8 +280,17 @@ pqParseInput3(PGconn *conn)
return;
break;
case 'T': /* Row Description */
- if (conn->result == NULL ||
- conn->queryclass == PGQUERY_DESCRIBE)
+ if (conn->result != NULL &&
+ conn->result->resultStatus == PGRES_FATAL_ERROR)
+ {
+ /*
+ * We've already choked for some reason. Just discard
+ * the data till we get to the end of the query.
+ */
+ conn->inCursor += msgLength;
+ }
+ else if (conn->result == NULL ||
+ conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
if (getRowDescriptions(conn, msgLength))
@@ -331,9 +340,10 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
return;
- break;
+ /* getParamDescriptions() moves inStart itself */
+ continue;
case 'D': /* Data Row */
if (conn->result != NULL &&
conn->result->resultStatus == PGRES_TUPLES_OK)
@@ -642,20 +652,21 @@ advance_and_error:
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ goto advance_and_error;
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ goto not_enough_data;
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -664,7 +675,7 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -674,17 +685,51 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ goto not_enough_data;
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.6.0
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-10-15 14:28 Amit Kapila <amit.kapila16@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-10-15 14:28 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Sun, Oct 11, 2015 at 6:31 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:
>
>
> Yeah, this behavior is caused by this piece of code:
> @@ -600,7 +601,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
> advance_and_error:
> /* Discard unsaved result, if any */
> if (result && result != conn->result)
> PQclear(result);
> An idea may be to check for conn->result->resultStatus !=
> PGRES_FATAL_ERROR to concatenate correctly the error messages using
> pqCatenateResultError. But just returning the first error encountered
> as you mention would be more natural. So I updated the patch this way.
>
Minor comment:
+getParamDescriptions(PGconn *conn, int msgLength)
{
..
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
..
}
Reference to 'copy' in above comment seems to be wrong.
Other than that both the patches looks good to me, I will mark this as
Ready for committer. Please see if you can update the patch soonish,
if you find above comment valid.
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-10-16 02:00 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 2 replies; 48+ messages in thread
From: Michael Paquier @ 2015-10-16 02:00 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Thu, Oct 15, 2015 at 11:28 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Sun, Oct 11, 2015 at 6:31 PM, Michael Paquier <michael.paquier@gmail.com>
> wrote:
>>
>>
>> Yeah, this behavior is caused by this piece of code:
>> @@ -600,7 +601,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
>> advance_and_error:
>> /* Discard unsaved result, if any */
>> if (result && result != conn->result)
>> PQclear(result);
>> An idea may be to check for conn->result->resultStatus !=
>> PGRES_FATAL_ERROR to concatenate correctly the error messages using
>> pqCatenateResultError. But just returning the first error encountered
>> as you mention would be more natural. So I updated the patch this way.
>>
>
> Minor comment:
> +getParamDescriptions(PGconn *conn, int msgLength)
> {
> ..
> +
> + /*
> + * Advance inStart to show that the copy related message has been
> + * processed.
> + */
> + conn->inStart = conn->inCursor;
> +
> ..
> }
>
> Reference to 'copy' in above comment seems to be wrong.
Oh, yes it wrong. This should refer to the "t" message.
> Other than that both the patches looks good to me, I will mark this as
> Ready for committer. Please see if you can update the patch soonish,
> if you find above comment valid.
Done. Thanks for the review!
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Attachments: download all (2 files, .tar.gz)
0001-Fix-OOM-error-handling-in-COPY-protocol-of-libpq.patch (text/x-diff, 7.1K) download
From 592f501be9864dd17ca023103278ee0926bb193d Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Sun, 11 Oct 2015 20:46:40 +0900
Subject: [PATCH 1/2] Fix OOM error handling in COPY protocol of libpq
An OOM occurring while all the data needed by process from server has been
received can result in an infinite loop when parsing the output message.
getCopyStart is switched to discard a a message read from server in case of
server and any subsequent ones when receiving data from server for
PGASYNC_COPY_OUT, and not wait for any additional data when input is expected
via PGASYNC_COPY_IN. In the case of PGASYNC_COPY_BOTH, both concepts apply.
---
.../libpqwalreceiver/libpqwalreceiver.c | 1 +
src/interfaces/libpq/fe-exec.c | 12 ++++
src/interfaces/libpq/fe-protocol3.c | 71 +++++++++++++++++-----
3 files changed, 69 insertions(+), 15 deletions(-)
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index b7bbcf6..8fae3a9 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -445,6 +445,7 @@ libpqrcv_PQexec(const char *query)
if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
PQresultStatus(lastResult) == PGRES_COPY_OUT ||
PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
+ PQresultStatus(lastResult) == PGRES_FATAL_ERROR ||
PQstatus(streamConn) == CONNECTION_BAD)
break;
}
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 828f18e..b84e5ed 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1801,6 +1801,10 @@ getCopyResult(PGconn *conn, ExecStatusType copytype)
return pqPrepareAsyncResult(conn);
}
+ /* If error has occured, return a PGRES_FATAL_ERROR result */
+ if (conn->result && conn->result->resultStatus == PGRES_FATAL_ERROR)
+ return pqPrepareAsyncResult(conn);
+
/* If we have an async result for the COPY, return that */
if (conn->result && conn->result->resultStatus == copytype)
return pqPrepareAsyncResult(conn);
@@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
* We have to stop if we see copy in/out/both, however. We will resume
* parsing after application performs the data transfer.
*
+ * Stop if we are in copy mode and error has occurred, the pending results
+ * will be discarded during next execution in PQexecStart.
+ *
* Also stop if the connection is lost (else we'll loop infinitely).
*/
lastResult = NULL;
@@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
result->resultStatus == PGRES_COPY_BOTH ||
conn->status == CONNECTION_BAD)
break;
+ else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
+ conn->asyncStatus == PGASYNC_COPY_OUT ||
+ conn->asyncStatus == PGASYNC_COPY_BOTH) &&
+ result->resultStatus == PGRES_FATAL_ERROR)
+ break;
}
return lastResult;
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 641804c..1079911 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -49,7 +49,9 @@ static int getParamDescriptions(PGconn *conn);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
-static int getCopyStart(PGconn *conn, ExecStatusType copytype);
+static int getCopyStart(PGconn *conn,
+ ExecStatusType copytype,
+ int msgLength);
static int getReadyForQuery(PGconn *conn);
static void reportErrorPosition(PQExpBuffer msg, const char *query,
int loc, int encoding);
@@ -362,22 +364,25 @@ pqParseInput3(PGconn *conn)
}
break;
case 'G': /* Start Copy In */
- if (getCopyStart(conn, PGRES_COPY_IN))
+ if (getCopyStart(conn, PGRES_COPY_IN, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_IN;
- break;
+ continue;
case 'H': /* Start Copy Out */
- if (getCopyStart(conn, PGRES_COPY_OUT))
+ if (getCopyStart(conn, PGRES_COPY_OUT, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_OUT;
conn->copy_already_done = 0;
- break;
+ continue;
case 'W': /* Start Copy Both */
- if (getCopyStart(conn, PGRES_COPY_BOTH))
+ if (getCopyStart(conn, PGRES_COPY_BOTH, msgLength))
return;
+ /* getCopyStart() moves inStart itself */
conn->asyncStatus = PGASYNC_COPY_BOTH;
conn->copy_already_done = 0;
- break;
+ continue;
case 'd': /* Copy Data */
/*
@@ -1343,22 +1348,24 @@ getNotify(PGconn *conn)
* parseInput already read the message type and length.
*/
static int
-getCopyStart(PGconn *conn, ExecStatusType copytype)
+getCopyStart(PGconn *conn, ExecStatusType copytype, int msgLength)
{
PGresult *result;
int nfields;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, copytype);
if (!result)
- goto failure;
+ goto advance_and_error;
if (pqGetc(&conn->copy_is_binary, conn))
- goto failure;
+ goto not_enough_data;
result->binary = conn->copy_is_binary;
+
/* the next two bytes are the number of fields */
- if (pqGetInt(&(result->numAttributes), 2, conn))
- goto failure;
+ if (pqGetInt(&result->numAttributes, 2, conn))
+ goto not_enough_data;
nfields = result->numAttributes;
/* allocate space for the attribute descriptors */
@@ -1367,7 +1374,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
result->attDescs = (PGresAttDesc *)
pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
if (!result->attDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
}
@@ -1376,7 +1383,7 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
int format;
if (pqGetInt(&format, 2, conn))
- goto failure;
+ goto not_enough_data;
/*
* Since pqGetInt treats 2-byte integers as unsigned, we need to
@@ -1388,11 +1395,45 @@ getCopyStart(PGconn *conn, ExecStatusType copytype)
/* Success! */
conn->result = result;
+
+ /*
+ * Advance inStart to show that the copy related message has been
+ * processed.
+ */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.6.1
0002-Fix-OOM-error-handling-in-BIND-protocol-of-libpq.patch (text/x-diff, 4.3K) download
From 93e631ce21c4fcbfea6403afb1de1965183fc8bd Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Fri, 16 Oct 2015 10:59:03 +0900
Subject: [PATCH 2/2] Fix OOM error handling in BIND protocol of libpq
---
src/interfaces/libpq/fe-protocol3.c | 64 ++++++++++++++++++++++++++++++-------
1 file changed, 53 insertions(+), 11 deletions(-)
diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 1079911..0ed4f5c 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -45,7 +45,7 @@
static void handleSyncLoss(PGconn *conn, char id, int msgLength);
static int getRowDescriptions(PGconn *conn, int msgLength);
-static int getParamDescriptions(PGconn *conn);
+static int getParamDescriptions(PGconn *conn, int msgLength);
static int getAnotherTuple(PGconn *conn, int msgLength);
static int getParameterStatus(PGconn *conn);
static int getNotify(PGconn *conn);
@@ -280,8 +280,17 @@ pqParseInput3(PGconn *conn)
return;
break;
case 'T': /* Row Description */
- if (conn->result == NULL ||
- conn->queryclass == PGQUERY_DESCRIBE)
+ if (conn->result != NULL &&
+ conn->result->resultStatus == PGRES_FATAL_ERROR)
+ {
+ /*
+ * We've already choked for some reason. Just discard
+ * the data till we get to the end of the query.
+ */
+ conn->inCursor += msgLength;
+ }
+ else if (conn->result == NULL ||
+ conn->queryclass == PGQUERY_DESCRIBE)
{
/* First 'T' in a query sequence */
if (getRowDescriptions(conn, msgLength))
@@ -331,9 +340,10 @@ pqParseInput3(PGconn *conn)
}
break;
case 't': /* Parameter Description */
- if (getParamDescriptions(conn))
+ if (getParamDescriptions(conn, msgLength))
return;
- break;
+ /* getParamDescriptions() moves inStart itself */
+ continue;
case 'D': /* Data Row */
if (conn->result != NULL &&
conn->result->resultStatus == PGRES_TUPLES_OK)
@@ -642,20 +652,21 @@ advance_and_error:
* that shouldn't happen often, since 't' messages usually fit in a packet.
*/
static int
-getParamDescriptions(PGconn *conn)
+getParamDescriptions(PGconn *conn, int msgLength)
{
PGresult *result;
int nparams;
int i;
+ const char *errmsg = NULL;
result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
if (!result)
- goto failure;
+ goto advance_and_error;
/* parseInput already read the 't' label and message length. */
/* the next two bytes are the number of parameters */
if (pqGetInt(&(result->numParameters), 2, conn))
- goto failure;
+ goto not_enough_data;
nparams = result->numParameters;
/* allocate space for the parameter descriptors */
@@ -664,7 +675,7 @@ getParamDescriptions(PGconn *conn)
result->paramDescs = (PGresParamDesc *)
pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
if (!result->paramDescs)
- goto failure;
+ goto advance_and_error;
MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
}
@@ -674,17 +685,48 @@ getParamDescriptions(PGconn *conn)
int typid;
if (pqGetInt(&typid, 4, conn))
- goto failure;
+ goto not_enough_data;
result->paramDescs[i].typid = typid;
}
/* Success! */
conn->result = result;
+
+ /* Advance inStart to show that the "t" message has been processed. */
+ conn->inStart = conn->inCursor;
+
return 0;
-failure:
+not_enough_data:
PQclear(result);
return EOF;
+
+advance_and_error:
+ /* Discard unsaved result, if any */
+ if (result && result != conn->result)
+ PQclear(result);
+
+ /* Discard the failed message by pretending we read it */
+ conn->inStart += 5 + msgLength;
+
+ /*
+ * Replace partially constructed result with an error result. First
+ * discard the old result to try to win back some memory.
+ */
+ pqClearAsyncResult(conn);
+
+ /*
+ * If preceding code didn't provide an error message, assume "out of
+ * memory" was meant. The advantage of having this special case is that
+ * freeing the old result first greatly improves the odds that gettext()
+ * will succeed in providing a translation.
+ */
+ if (!errmsg)
+ errmsg = libpq_gettext("out of memory");
+ printfPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
+ pqSaveErrorResult(conn);
+
+ return 0;
}
/*
--
2.6.1
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-12-01 13:03 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-12-01 13:03 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Fri, Oct 16, 2015 at 11:00 AM, Michael Paquier
<michael.paquier@gmail.com> wrote:
> On Thu, Oct 15, 2015 at 11:28 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> Other than that both the patches looks good to me, I will mark this as
>> Ready for committer. Please see if you can update the patch soonish,
>> if you find above comment valid.
>
> Done. Thanks for the review!
Could it be possible to get some committer attention for this patch
and get that committed for this CF? This is a clearly bug fix and it
is present for months. At least Amit and I have reached a consensus
about a way to do things.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-12-01 14:55 Tom Lane <tgl@sss.pgh.pa.us>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Tom Lane @ 2015-12-01 14:55 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; pgsql-bugs
Michael Paquier <michael.paquier@gmail.com> writes:
> Could it be possible to get some committer attention for this patch
> and get that committed for this CF?
FWIW, I've been assuming that Heikki would handle it, since he was
involved earlier. If he's not got time/interest for some reason,
I could pick it up.
regards, tom lane
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-12-02 02:28 Michael Paquier <michael.paquier@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 0 replies; 48+ messages in thread
From: Michael Paquier @ 2015-12-02 02:28 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; pgsql-bugs
On Tue, Dec 1, 2015 at 11:55 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Michael Paquier <michael.paquier@gmail.com> writes:
>> Could it be possible to get some committer attention for this patch
>> and get that committed for this CF?
>
> FWIW, I've been assuming that Heikki would handle it, since he was
> involved earlier. If he's not got time/interest for some reason,
> I could pick it up.
Thanks.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-12-14 17:11 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael.paquier@gmail.com>
1 sibling, 1 reply; 48+ messages in thread
From: Heikki Linnakangas @ 2015-12-14 17:11 UTC (permalink / raw)
To: Michael Paquier <michael.paquier@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; +Cc: Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On 16/10/15 05:00, Michael Paquier wrote:
> On Thu, Oct 15, 2015 at 11:28 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> On Sun, Oct 11, 2015 at 6:31 PM, Michael Paquier <michael.paquier@gmail.com>
>> wrote:
>>>
>>> Yeah, this behavior is caused by this piece of code:
>>> @@ -600,7 +601,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
>>> advance_and_error:
>>> /* Discard unsaved result, if any */
>>> if (result && result != conn->result)
>>> PQclear(result);
>>> An idea may be to check for conn->result->resultStatus !=
>>> PGRES_FATAL_ERROR to concatenate correctly the error messages using
>>> pqCatenateResultError. But just returning the first error encountered
>>> as you mention would be more natural. So I updated the patch this way.
I pushed the ParamDescription fix. I'm not quite sure on the details of
the COPY patch. Do you remember what this change in PQexecFinish is for:
> @@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
> * We have to stop if we see copy in/out/both, however. We will resume
> * parsing after application performs the data transfer.
> *
> + * Stop if we are in copy mode and error has occurred, the pending results
> + * will be discarded during next execution in PQexecStart.
> + *
> * Also stop if the connection is lost (else we'll loop infinitely).
> */
> lastResult = NULL;
> @@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
> result->resultStatus == PGRES_COPY_BOTH ||
> conn->status == CONNECTION_BAD)
> break;
> + else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
> + conn->asyncStatus == PGASYNC_COPY_OUT ||
> + conn->asyncStatus == PGASYNC_COPY_BOTH) &&
> + result->resultStatus == PGRES_FATAL_ERROR)
> + break;
> }
>
> return lastResult;
I don't immediately see why that's needed. I ran the little tester
program I wrote earlier
(http://www.postgresql.org/message-id/55FC501A.5000409@iki.fi), with and
without that change, and it behaved the same.
Also, when I modify my tester program so that when malloc fails, all
subsequent mallocs fail too, I'm still getting the "another command is
already in progress" error. The problem scenario is:
1. Application calls PQexec("COPY foo FROM STDIN")
2. getCopyStart sets conn->asyncStatus = PGASYNC_COPY_IN.
3. PQgetResult calls getCopyResult() but it fails with OOM.
Now, libpq is already in PGASYNC_COPY_IN mode, but PQexec() returned
NULL because of the OOM, so the application doesn't know that it's in
copy mode. When the application calls PQexec() again, it fails with the
"another command is already in progress" error.
Let's see if we can fix that too, or if we should put that off to yet
another patch.
- Heikki
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-12-15 05:22 Amit Kapila <amit.kapila16@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 48+ messages in thread
From: Amit Kapila @ 2015-12-15 05:22 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Michael Paquier <michael.paquier@gmail.com>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Mon, Dec 14, 2015 at 10:41 PM, Heikki Linnakangas <hlinnaka@iki.fi>
wrote:
> On 16/10/15 05:00, Michael Paquier wrote:
>
>> On Thu, Oct 15, 2015 at 11:28 PM, Amit Kapila <amit.kapila16@gmail.com>
>> wrote:
>>
>>> On Sun, Oct 11, 2015 at 6:31 PM, Michael Paquier <
>>> michael.paquier@gmail.com>
>>> wrote:
>>>
>>>>
>>>> Yeah, this behavior is caused by this piece of code:
>>>> @@ -600,7 +601,9 @@ getRowDescriptions(PGconn *conn, int msgLength)
>>>> advance_and_error:
>>>> /* Discard unsaved result, if any */
>>>> if (result && result != conn->result)
>>>> PQclear(result);
>>>> An idea may be to check for conn->result->resultStatus !=
>>>> PGRES_FATAL_ERROR to concatenate correctly the error messages using
>>>> pqCatenateResultError. But just returning the first error encountered
>>>> as you mention would be more natural. So I updated the patch this way.
>>>>
>>>
> I pushed the ParamDescription fix. I'm not quite sure on the details of
> the COPY patch. Do you remember what this change in PQexecFinish is for:
>
> @@ -1991,6 +1995,9 @@ PQexecFinish(PGconn *conn)
>> * We have to stop if we see copy in/out/both, however. We will
>> resume
>> * parsing after application performs the data transfer.
>> *
>> + * Stop if we are in copy mode and error has occurred, the
>> pending results
>> + * will be discarded during next execution in PQexecStart.
>> + *
>> * Also stop if the connection is lost (else we'll loop
>> infinitely).
>> */
>> lastResult = NULL;
>> @@ -2020,6 +2027,11 @@ PQexecFinish(PGconn *conn)
>> result->resultStatus == PGRES_COPY_BOTH ||
>> conn->status == CONNECTION_BAD)
>> break;
>> + else if ((conn->asyncStatus == PGASYNC_COPY_IN ||
>> + conn->asyncStatus == PGASYNC_COPY_OUT
>> ||
>> + conn->asyncStatus == PGASYNC_COPY_BOTH)
>> &&
>> + result->resultStatus ==
>> PGRES_FATAL_ERROR)
>> + break;
>> }
>>
>> return lastResult;
>>
>
> I don't immediately see why that's needed. I ran the little tester program
> I wrote earlier (
> http://www.postgresql.org/message-id/55FC501A.5000409@iki.fi), with and
> without that change, and it behaved the same.
>
>
Without this change, it can ignore the OOM error for copy command.
As an example, for command like "copy t1 from stdin;", when the
flow reaches getCopyStart() in debugger, I have manually ensured
that PQmakeEmptyPGresult() return NULL by overwriting the return
value of malloc to zero and then it enters the error path
(advance_and_error) and then I just press continue and what I observed
is without above change it just doesn't show OOM error and with the
above change it properly reports OOM error.
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2015-12-15 06:54 Michael Paquier <michael.paquier@gmail.com>
parent: Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 48+ messages in thread
From: Michael Paquier @ 2015-12-15 06:54 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Tue, Dec 15, 2015 at 2:22 PM, Amit Kapila <amit.kapila16@gmail.com>
wrote:
> On Mon, Dec 14, 2015 at 10:41 PM, Heikki Linnakangas <hlinnaka@iki.fi>
wrote:
>> On 16/10/15 05:00, Michael Paquier wrote:
>> I don't immediately see why that's needed. I ran the little tester
program I wrote earlier (
http://www.postgresql.org/message-id/55FC501A.5000409@iki.fi), with and
without that change, and it behaved the same.
>>
>
> Without this change, it can ignore the OOM error for copy command.
> As an example, for command like "copy t1 from stdin;", when the
> flow reaches getCopyStart() in debugger, I have manually ensured
> that PQmakeEmptyPGresult() return NULL by overwriting the return
> value of malloc to zero and then it enters the error path
> (advance_and_error) and then I just press continue and what I observed
> is without above change it just doesn't show OOM error and with the
> above change it properly reports OOM error.
Yeah, that's basically this kind of trace:
* frame #0: 0x0000000100e8edad
libpq.5.dylib`getCopyStart(conn=0x00007fb238404090,
copytype=PGRES_COPY_OUT, msgLength=5) + 29 at fe-protocol3.c:1400
frame #1: 0x0000000100e8d3d6
libpq.5.dylib`pqParseInput3(conn=0x00007fb238404090) + 2374 at
fe-protocol3.c:383
frame #2: 0x0000000100e7f5ad
libpq.5.dylib`parseInput(conn=0x00007fb238404090) + 45 at fe-exec.c:1652
frame #3: 0x0000000100e7f86b
libpq.5.dylib`PQgetResult(conn=0x00007fb238404090) + 251 at fe-exec.c:1727
frame #4: 0x0000000100e7fdad
libpq.5.dylib`PQexecFinish(conn=0x00007fb238404090) + 29 at fe-exec.c:2007
frame #5: 0x0000000100e7fbdc
libpq.5.dylib`PQexec(conn=0x00007fb238404090, query=0x00007fb23841b760) +
92 at fe-exec.c:1838
frame #6: 0x0000000100dd2f35 psql`SendQuery(query=0x00007fb23841b760) +
965 at common.c:1064
frame #7: 0x0000000100dd99f4 psql`MainLoop(source=0x00007fff74944a90) +
2388 at mainloop.c:292
frame #8: 0x0000000100de1988 psql`main(argc=1, argv=0x00007fff5ee36510)
+ 3304 at startup.c:390
If an error occurs in the COPY start message, this allows to fetch
correctly the error that is generated by getCopyResult(), and that what has
been written to conn->errorMessage does not get overwritten by subsequent
messages, allowing to output the correct report to the user.
--
Michael
^ permalink raw reply [nested|flat] 48+ messages in thread
* Re: PQexec() hangs on OOM
@ 2016-02-06 12:11 Michael Paquier <michael.paquier@gmail.com>
parent: Michael Paquier <michael.paquier@gmail.com>
0 siblings, 0 replies; 48+ messages in thread
From: Michael Paquier @ 2016-02-06 12:11 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Oleksandr Shulgin <oleksandr.shulgin@zalando.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-bugs
On Tue, Dec 15, 2015 at 3:54 PM, Michael Paquier
<michael.paquier@gmail.com> wrote:
>
>
> On Tue, Dec 15, 2015 at 2:22 PM, Amit Kapila <amit.kapila16@gmail.com>
> wrote:
>> On Mon, Dec 14, 2015 at 10:41 PM, Heikki Linnakangas <hlinnaka@iki.fi>
>> wrote:
>>> On 16/10/15 05:00, Michael Paquier wrote:
>>> I don't immediately see why that's needed. I ran the little tester
>>> program I wrote earlier
>>> (http://www.postgresql.org/message-id/55FC501A.5000409@iki.fi), with and
>>> without that change, and it behaved the same.
>>>
>>
>> Without this change, it can ignore the OOM error for copy command.
>> As an example, for command like "copy t1 from stdin;", when the
>> flow reaches getCopyStart() in debugger, I have manually ensured
>> that PQmakeEmptyPGresult() return NULL by overwriting the return
>> value of malloc to zero and then it enters the error path
>> (advance_and_error) and then I just press continue and what I observed
>> is without above change it just doesn't show OOM error and with the
>> above change it properly reports OOM error.
>
> Yeah, that's basically this kind of trace:
> * frame #0: 0x0000000100e8edad
> libpq.5.dylib`getCopyStart(conn=0x00007fb238404090, copytype=PGRES_COPY_OUT,
> msgLength=5) + 29 at fe-protocol3.c:1400
> frame #1: 0x0000000100e8d3d6
> libpq.5.dylib`pqParseInput3(conn=0x00007fb238404090) + 2374 at
> fe-protocol3.c:383
> frame #2: 0x0000000100e7f5ad
> libpq.5.dylib`parseInput(conn=0x00007fb238404090) + 45 at fe-exec.c:1652
> frame #3: 0x0000000100e7f86b
> libpq.5.dylib`PQgetResult(conn=0x00007fb238404090) + 251 at fe-exec.c:1727
> frame #4: 0x0000000100e7fdad
> libpq.5.dylib`PQexecFinish(conn=0x00007fb238404090) + 29 at fe-exec.c:2007
> frame #5: 0x0000000100e7fbdc
> libpq.5.dylib`PQexec(conn=0x00007fb238404090, query=0x00007fb23841b760) + 92
> at fe-exec.c:1838
> frame #6: 0x0000000100dd2f35 psql`SendQuery(query=0x00007fb23841b760) +
> 965 at common.c:1064
> frame #7: 0x0000000100dd99f4 psql`MainLoop(source=0x00007fff74944a90) +
> 2388 at mainloop.c:292
> frame #8: 0x0000000100de1988 psql`main(argc=1, argv=0x00007fff5ee36510)
> + 3304 at startup.c:390
>
> If an error occurs in the COPY start message, this allows to fetch correctly
> the error that is generated by getCopyResult(), and that what has been
> written to conn->errorMessage does not get overwritten by subsequent
> messages, allowing to output the correct report to the user.
Heikki and I had a short talk about this issue in Moscow, and Heikki
has mentioned me that he cannot convince himself that this would be a
sane change for the COPY protocol. Based on his experience with those
things, I'd rather put every back on the table and look again at this
issue with fresh eyes with more testing involving in-core and external
tools that use the COPY protocol with libpq routines. I recall having
doing some testing with pg_receivexlog and pg_recvlogical but I'll
look at that again. Also, I know one tool which would be interesting
to test: pg_bulkload. Do you know of any other things worth looking
at? We want things that link with libpq directly.
So, in short, I am planning to do more testing, even if it has proved
to be rather clear that this change has the advantage to make the
error stack to be clearer. But we may be missing something, so let's
see.
--
Michael
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
^ permalink raw reply [nested|flat] 48+ messages in thread
end of thread, other threads:[~2016-02-06 12:11 UTC | newest]
Thread overview: 48+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2014-11-25 13:15 PQexec() hangs on OOM Heikki Linnakangas <hlinnakangas@vmware.com>
2015-04-06 06:54 ` Michael Paquier <michael.paquier@gmail.com>
2015-04-06 06:59 ` Michael Paquier <michael.paquier@gmail.com>
2015-04-06 13:46 ` Tom Lane <tgl@sss.pgh.pa.us>
2015-04-07 06:18 ` Michael Paquier <michael.paquier@gmail.com>
2015-04-07 18:54 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-04-08 04:27 ` Michael Paquier <michael.paquier@gmail.com>
2015-04-09 17:42 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-04-10 11:53 ` Michael Paquier <michael.paquier@gmail.com>
2015-05-20 16:31 ` Oleksandr Shulgin <oleksandr.shulgin@zalando.de>
2015-05-26 07:01 ` Michael Paquier <michael.paquier@gmail.com>
2015-07-03 16:32 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-07-04 12:40 ` Michael Paquier <michael.paquier@gmail.com>
2015-07-06 17:13 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-07-07 06:31 ` Michael Paquier <michael.paquier@gmail.com>
2015-07-07 06:32 ` Michael Paquier <michael.paquier@gmail.com>
2015-07-07 16:01 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-07-09 13:04 ` Michael Paquier <michael.paquier@gmail.com>
2015-07-10 13:42 ` Michael Paquier <michael.paquier@gmail.com>
2015-08-29 13:35 ` Amit Kapila <amit.kapila16@gmail.com>
2015-08-31 07:25 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-04 05:07 ` Amit Kapila <amit.kapila16@gmail.com>
2015-09-04 07:25 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-05 12:45 ` Amit Kapila <amit.kapila16@gmail.com>
2015-09-07 08:10 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-07 09:45 ` Amit Kapila <amit.kapila16@gmail.com>
2015-09-07 13:41 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-07 15:13 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-08 11:48 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-12 08:56 ` Amit Kapila <amit.kapila16@gmail.com>
2015-09-13 22:57 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-12 09:11 ` Amit Kapila <amit.kapila16@gmail.com>
2015-09-14 01:36 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-18 17:55 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-09-18 22:17 ` Michael Paquier <michael.paquier@gmail.com>
2015-09-19 04:32 ` Amit Kapila <amit.kapila16@gmail.com>
2015-09-19 05:14 ` Michael Paquier <michael.paquier@gmail.com>
2015-10-10 12:06 ` Amit Kapila <amit.kapila16@gmail.com>
2015-10-11 13:01 ` Michael Paquier <michael.paquier@gmail.com>
2015-10-15 14:28 ` Amit Kapila <amit.kapila16@gmail.com>
2015-10-16 02:00 ` Michael Paquier <michael.paquier@gmail.com>
2015-12-01 13:03 ` Michael Paquier <michael.paquier@gmail.com>
2015-12-01 14:55 ` Tom Lane <tgl@sss.pgh.pa.us>
2015-12-02 02:28 ` Michael Paquier <michael.paquier@gmail.com>
2015-12-14 17:11 ` Heikki Linnakangas <hlinnaka@iki.fi>
2015-12-15 05:22 ` Amit Kapila <amit.kapila16@gmail.com>
2015-12-15 06:54 ` Michael Paquier <michael.paquier@gmail.com>
2016-02-06 12:11 ` Michael Paquier <michael.paquier@gmail.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox