Use the Source, Luke!

October 20th, 2009 by Ramsey Dow

If there's one thing that I've learned throughout the years as a programmer, it is not always safe to trust the documentation. In fact, there is an old saying, “Use the source, Luke!” When possible, you should do just that.

While looking over the CERT Secure C Coding Standard I noticed the following recommendation: ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure. CERT goes on to write, “[s]ome functions lack documentation regarding errno in the C99 standard.” They follow this up with an example for Windows: “[i]n this compliant solution, errno is not checked because fopen() makes no promise of setting it.” This would be fine, were it true. However, it is false. Let us take a closer look.

It is true that the symbol, errno, appears nowhere in the MSDN documentation for fopen. However, one need only look to fopen.c (included with all commercial Visual C implementations) to see that errno.h is #include'd and errno is indeed set for locked streams, bad names (e.g., empty string), et al.

The use of errno is not as robust in the case of Microsoft's fopen implementation as it is in the implementation on my NetBSD box, but that's not the point. The point is that CERT stated something was true based on documentation when in fact, it was not true. The lesson here is that one cannot simply rely on assumptions based on documentation, one must also look to the source to see what is happening.

In the case of Microsoft's C and secure C runtimes, the source code is available for you to look at, provided you have Visual Studio installed. (Caveat: you don't get the CRT source code if you install Visual C++ Express.) I found the code living on my box under Program Files at Microsoft Visual Studio 9.0\VC\crt\src.

Of course, if you're programming on Windows you should prefer fopen_s to fopen anyway. For the record, the MSDN documentation for fopen_s clearly states that it returns an errno_t, which is the Secure CRT's answer to errno.

Update: I just found out from a source inside the Visual Studio team at Microsoft that Visual Studio 2010 Beta 2's Express Edition SKU contains the CRT source code. That's good news. You can get more information on Visual Studio 2010 Beta 2 here, and you can download it here.

Tags: ,



Leave a Comment