3 ms·
This is a security nightmare. For one thing, it makes it impossible to use GCC's (and clang's) format function attribute, which allow the compiler to statically
by wahern 9y ago
This is a security nightmare. For one thing, it makes it impossible to use GCC's (and clang's) format function attribute, which allow the compiler to statically type check the format string and variable argument list. For another, printf bugs are a fertile ground for remote code execution and this glibc feature, by relying on runtime-assigned function pointers, is considerably worse. Combined with the lack of static type checking (because you can't use the format attribute GCC extension), I'd fire anyone who relied on this feature despite my objections.
Thankfully, I've never seen real-world code that made use of this feature, and hopefully never will. And if glibc knew what was good for them they'd kill it off.
If you're early enough in your C programming evolution that you find this stuff enticing, there are better ways to screw around. For example, read about GCC's __builtin_types_compatible_p feature (and the slightly less powerful, but more portable, C11 _Generic), and ponder how you might devise an interface that transforms variable argument list arguments to self-describing structs which don't solely depend on a separate declaration in the format string for type information. (Hint: also read about C99's variable argument preprocessor macros.)
I wouldn't recommend it for production, but exploring that space is a decent way to hone your C skills. Learning what _not_ to do, and why not, is at least as important as learning what to do. Poking at glibc's printf extension doesn't offer such dividends.
Finally, if you're interested in the mechanics of printf more generally, stay as far away from glibc's implementation as you can. It's a nightmare by every conceivable metric.[1] While there are simpler implementations, of the fully compliant implementations which see widespread use, I'd recommend musl libc's and OpenBSD's implementations.
[1] It's not even a good example of what _not_ to do because by the time you've mentally mapped out what it's doing and why, you could have completed a Ph.D or burned through a dozen rounds of VC funding.