Googles appar
Huvudmeny

Post a Comment On: cbloom rants

"Robust Win32 IO"

3 Comments -

1 – 3 of 3
Blogger Thom said...

I think this code has a bug in the sync read code (I don't use the writing functions so I don't know if it's there too, didn't look).

Essentially, the problem is `win32_sync_read_sub` returns an error if asked to do a read that starts at EOF, but `win32_sync_read` can request a read like that in later iterations of the loop if `pos + N * MAX_SINGLE_IO_SIZE` happens to be exactly the file size, and `pos + size` happens to go past the end of the file (which seems to be supported otherwise).

This is rare, but can happen if you have files with sizes which are an exact multiple of 2MB (e.g. 1<<21, MAX_SINGLE_IO_SIZE) and do a read starting at 0 with an overly large buffer.

In my case it was trivial to fix, and had the code not explicitly advertised as "robust" I'd probably not bother mentioning it and just assume that it's buggy if `pos + size` goes past the end of the file in rare cases, but as it is it's probably worth fixing for the sake of robustness.

December 5, 2020 at 7:31 PM

Blogger cbloom said...

Yes. In that case it should still read the bytes and fill *pGotSize correctly, but it returns FALSE which is misleading and not well documented.

I think probably the cleanest thing is to explicitly return that EOF was reached, so instead of returning BOOL return a trinary. The EOF handling in general in this code is not great.

To be clear the claims of "robust" are optimistic at best, since I don't actually use this code as-is, and untested/unused code is always crap. (good coder principle is to always ship the exact same code that you use every day, not have a ship version vs. daily version). At the moment it's more of a demonstration of some issues that I see people fail to handle regularly. That said I'll try to maintain it so actual usability improves.

December 6, 2020 at 9:36 AM

Blogger cbloom said...

.. updated to make EOF a first class state, which cleans up things a bit. Hitting EOF during a read now counts as success, but the number of bytes read might be less than he number requested.

Caveat above still applies : this is a basically untested extraction of code to make it dependency-free that isn't what I actually use, so apologies if it's not great.

December 14, 2020 at 9:50 AM

You can use some HTML tags, such as <b>, <i>, <a>

This blog does not allow anonymous comments.

Comment moderation has been enabled. All comments must be approved by the blog author.

You will be asked to sign in after submitting your comment.