Hi, An old patch [1] got pushed today. While reading the pushed commit, I noticed two pre-existing issues in copy_read_data().
1. The leftover-data branch doesn’t advance outbuf
```
/* If there are some leftover data from previous read, use it. */
avail = copybuf.len - copybuf.cursor;
if (avail)
{
if (avail > maxread)
avail = maxread;
memcpy(outbuf, ©buf.data[copybuf.cursor], avail);
copybuf.cursor += avail;
maxread -= avail;
bytesread += avail;
}
while (maxread > 0 && bytesread < minread)
{
```
After copying the leftover bytes, copy_read_data() doesn’t advance outbuf. If
the number of bytes copied is less than minread, the next memcpy() would
overwrite them. The current caller only passes 1 for minread, so copying even
one leftover byte is enough to skip the while loop. That’s why this bug cannot
be triggered today.
2. The maxread checks are redundant
In the same code snippet as in issue 1, avail is always clamped to maxread
before memcpy(). Since memcpy() takes a size_t as its third parameter, passing
a negative avail would result in an out-of-bounds write. If maxread is 0, the
function becomes a no-op. So, maxread should must be >0.
Each copy subtracts avail from maxread and adds it to bytesread. Since maxread
is at least minread on entry, maxread must still be greater than zero as long
as bytesread is less than minread. Thus, the condition maxread > 0 in the while
loop is redundant. For the same reason, maxread <= 0 in the return condition
inside the loop is redundant as well.
We can add an assertion at the beginning of the function and delete these
redundant checks. WRT the assertion, based on the current code logic, I think
minread should also be >0. If minread is <=0, the function will never enter the
while loop, then walrcv_receive() is never called. And there is no current
caller passes 0 as minread. So I think we can assert minread > 0 && maxread >=
minread.
The first issue seems like a concrete bug, and the second feels more like a
small cleanup, so I’ve split the changes into two commits.
[1] https://postgr.es/m/[email protected]
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
v1-0001-Advance-outbuf-after-copying-leftover-data-in-cop.patch
Description: Binary data
v1-0002-Simplify-the-read-conditions-in-copy_read_data.patch
Description: Binary data
