pread, pwrite, etc return ssize_t not int

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Cc: Thomas Munro <thomas(dot)munro(at)gmail(dot)com>
Subject: pread, pwrite, etc return ssize_t not int
Date: 2023-12-24 18:09:00
Message-ID: 1672202.1703441340@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Coverity whinged this morning about the following bit in
the new pg_combinebackup code:

644 unsigned rb;
645
646 /* Read the block from the correct source, except if dry-run. */
647 rb = pg_pread(s->fd, buffer, BLCKSZ, offsetmap[i]);
648 if (rb != BLCKSZ)
649 {
>>> CID 1559912: Control flow issues (NO_EFFECT)
>>> This less-than-zero comparison of an unsigned value is never true. "rb < 0U".
650 if (rb < 0)
651 pg_fatal("could not read file \"%s\": %m", s->filename);

It's dead right to complain of course. (I kind of think that the
majority of places where reconstruct.c is using "unsigned" variables
are poorly-thought-through; many of them look like they should be
size_t, and I suspect some other ones beside this one are flat wrong
or at least unnecessarily fragile. But I digress.)

While looking around for other places that might've made comparable
mistakes, I noted that we have places that are storing the result of
pg_pread[v]/pg_pwrite[v] into an "int" variable even though they are
passing a size_t count argument that there is no obvious reason to
believe must fit in int. This seems like trouble waiting to happen,
so I fixed some of these in the attached. The major remaining place
that I think we ought to change is the newly-minted
FileRead[V]/FileWrite[V] functions, which are declared to return int
but really should be returning ssize_t IMO. I didn't do that here
though.

We could go further by insisting that *all* uses of pg_pread/pg_pwrite
use ssize_t result variables. I think that's probably overkill --- in
the example above, which is only asking to write BLCKSZ worth of data,
surely an int is sufficient. But you could argue that allowing this
pattern at all creates risk of copy/paste errors.

Of course the real elephant in the room is that plain old read(2)
and write(2) also return ssize_t. I've not attempted to vet every
call of those, and I think it'd likely be a waste of effort, as
we're unlikely to ever try to shove more than INT_MAX worth of
data through them. But it's a bit harder to make that argument
for the iovec-based file APIs. I think we ought to try to keep
our uses of those functions clean on this point.

Thoughts?

regards, tom lane

Attachment Content-Type Size
v1-fix-wrong-datatype-for-pread-and-pwrite.patch text/x-diff 4.3 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2023-12-24 18:11:28 Re: Password leakage avoidance
Previous Message Joe Conway 2023-12-24 18:02:01 Re: Password leakage avoidance