Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect usage of macro? (errno)

This is very specific, and a bit difficult to explain, and quite likely impossible, but here goes.

I want to implement <errno.h>. (My hobby project is implementing a Standard C library.)

The naïve way to go about it is:

// in <errno.h>
extern int errno;

// in some .c file
int errno = 0;

This works. But it has one disadvantage: If a math library function is called, it always has to query the FPU status after execution to set errno as appropriate. This stalls the FPU in math-heavy applications.

The C standard endorses lazy evaluation of errno by making it a macro instead:

int * __errno();
#define errno *__errno()

This way, errno is only "set" when its value is actually requested:

// "__errno()" returns the location of the current errno value,
// the "errno" macro turns it into a value.
x = errno;

Given some logic in the rest of the library, the FPU status needs only be queried if the last library function called was actually one using the FPU, and the value of errno is actually requested.

So far, everything is fine. But it's the other way around that is giving me headaches:

errno = 0;

The value of errno is not requested at all. But __errno() does not know that, and will query the FPU status if the last library function called was using the FPU.

Right now I don't see a way to avoid that (i.e., have the errno macro or the __errno() function somehow work differently depending on whether they are used to the left or the right of the assignment operator), and am almost content to accept this.

But perhaps any of you SO'ers has a brilliant idea?

like image 445
DevSolar Avatar asked Aug 28 '09 14:08

DevSolar


1 Answers

No brilliant ideas here, but afaik errno is allowed to be implemented via function calls to make thread-safe implementations of the standard library possible. I don't think querying the FPU lazily is a good idea: How will you avoid inconsistency in situations like this:

  • set errno
  • floating-point ops which set error flags
  • get errno
  • get flags

Should a call to __errno() clear the flags or not?

According to the standard, whether or not errno has to be set by math functions is determined by the value of math_errhandling (specifically, math_errhandling & MATH_ERRNO).

What I would do is make the error reporting optional via preprocessor directives and allow the programmer to set the value of math_errhandling at compile time. This would mean that the math functions can't be compiled statically beforehand but have to reside in a header, which might be a good idea anyway to allow compilers without link-time optimizations to inline these functions.

like image 118
Christoph Avatar answered Oct 12 '22 23:10

Christoph