Win32's feof is implemented as a function and a macro

August 14th, 2008 Jonathan

Discovered a nasty feature of win32’s feof function.  We have our own dll loader on win32 that automagically handles linking up any of the usual filesystem functions (fopen, fclose et. al.) into our virtual filesystem versions.  This allows dll’s to not have to care about where they’re getting their files from, which is neat.  Found a problem the other day where a user was reporting lockups when XBMC attempted to load zero byte sized jpg files.  This seemed rather strange to me, and I initially suspected problems in the image library we use (cximage).  Debugging dll’s is never a fun experience when you aren’t loading them using the normal win32 LoadLibrary functions – basically one is reduced to printf.  After an hour or so of running through various massive log outputs, I figured out that the problem was an infinite loop in the implementation of the BMP loading function.  It basically ran a loop reading in characters from the file via getc and checking for EOF using feof.  The weird bit was that our exported version of feof was not being called.  How could this be?  More investigation showed that the dll wasn’t actually including it as a wanted import at all – somehow it had it’s own implementation of feof built in.

The reason was this: win32 defines feof using both a macro and a function. The macro was the version it was calling, and obviously wasn’t working, as the FILE * object it was operating on was the structure that we use to store everything we need to know about the virtual filesystem layer, and was thus not returning EOF.

A quick #undef feof later, and we were back in business.

Comments are closed.