nothings / stb

stb single-file public domain libraries for C/C++
https://twitter.com/nothings
Other
26.81k stars 7.72k forks source link

stb_image: Improve error reporting if file operations fail within *_from_file functions. #1420

Open NBickford-NV opened 1 year ago

NBickford-NV commented 1 year ago

Within the stb_image *_from_file() APIs, several of the calls to ftell() and fseek() responsible for resetting the file position don't check for returned error codes. This merge request adds error checks to these calls.

The main goal of this pull request for me is to fix a few warnings from our static analysis tool. It's difficult but possible to get these calls to fail even if the file's been successfully opened: for instance, imagine another process deletes the file or obtains an exclusive lock to the file - or say the file's on a flash drive that's unplugged at just the right time.

In stbi_load_from_file() and stbi_load_from_file_16(), the effect is that the function's guarantee that

// for stbi_load_from_file, file pointer is left pointing immediately after image

breaks; the file could still be readable, but not returning an error when the file position is unknown could lead to trouble if an application uses the FILE pointer afterwards.

In stbi_is_hdr_from_file(), stbi_info_from_file(), and stbi_is_16_bit_from_file(), the return value from ftell() — which is negative if ftell() produced an error — is passed to fseek(..., SEEK_SET). The ensuing behavior of fseek() when called to set a negative seek position probably depends on the C library implementation; Watcom's version of the specification, for instance, prohibits this.

(This does not adjust the credits to avoid merge conflicts with PR https://github.com/nothings/stb/pull/1223).

Thanks!