Skip to content

Commit ccbb01f

Browse files
committed
pgbench: avoid FD_ISSET on an invalid file descriptor
The original code wasn't careful to test the file descriptor returned by PQsocket() for an invalid socket. If an invalid socket did turn up, that would amount to calling FD_ISSET with fd = -1, whereby undefined behavior can be invoked. To fix, test file descriptor for validity and stop further processing if that fails. Problem noticed by Coverity. There is an existing FD_ISSET callsite that does check for invalid sockets beforehand, but the error message reported by it was strerror(errno); in testing the aforementioned change, that turns out to result in "bad socket: Success" which isn't terribly helpful. Instead use PQerrorMessage() in both places which is more likely to contain an useful error message. Backpatch-through: 9.1.
1 parent e3ad502 commit ccbb01f

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

contrib/pgbench/pgbench.c

+15-5
Original file line numberDiff line numberDiff line change
@@ -3231,7 +3231,7 @@ threadRun(void *arg)
32313231
sock = PQsocket(st->con);
32323232
if (sock < 0)
32333233
{
3234-
fprintf(stderr, "bad socket: %s\n", strerror(errno));
3234+
fprintf(stderr, "bad socket: %s", PQerrorMessage(st->con));
32353235
goto done;
32363236
}
32373237

@@ -3299,11 +3299,21 @@ threadRun(void *arg)
32993299
Command **commands = sql_files[st->use_file];
33003300
int prev_ecnt = st->ecnt;
33013301

3302-
if (st->con && (FD_ISSET(PQsocket(st->con), &input_mask)
3303-
|| commands[st->state]->type == META_COMMAND))
3302+
if (st->con)
33043303
{
3305-
if (!doCustom(thread, st, &result->conn_time, logfile, &aggs))
3306-
remains--; /* I've aborted */
3304+
int sock = PQsocket(st->con);
3305+
3306+
if (sock < 0)
3307+
{
3308+
fprintf(stderr, "bad socket: %s", PQerrorMessage(st->con));
3309+
goto done;
3310+
}
3311+
if (FD_ISSET(sock, &input_mask) ||
3312+
commands[st->state]->type == META_COMMAND)
3313+
{
3314+
if (!doCustom(thread, st, &result->conn_time, logfile, &aggs))
3315+
remains--; /* I've aborted */
3316+
}
33073317
}
33083318

33093319
if (st->ecnt > prev_ecnt && commands[st->state]->type == META_COMMAND)

0 commit comments

Comments
 (0)