It Is Never a Compiler Bug Until It Is

2020-09-29T02:37:01Z

Last week I was trying to add some testing code to libsecp256k1 and I was pulling out my hair trying to get it to work. No amount of printf was working to illuminate what I was doing wrong. Finally, out of desperation, I thought I would do a quick check to see if there are any compiler bugs related to memcmp, and lo and behold, I found GCC bug #95189: memcmp being wrongly stripped like strcmp.

Honestly this was a pretty horrifying bug to read about. Under some circumstances GCC 9 and 10 will cause memcmp to return an incorrect value when one of the inputs is statically known array that contains NULL bytes. As I rushed to recompile my computer system using GCC 8, I contemplated what the vast consequences of such a bug could be, and pondered how it was possible that computers could function at all.

However over the week, with the help of my colleagues, we managed to get a better understanding of the scope of the bug. The bug can only convert non-zero values to zero values. The static array needs to have a NULL byte within the first 4 bytes. Most importantly, the memcmp result must not immediately be compared to 0 for equality or inequality, or any equivalent test. A different code path is taken in the compiler in that case. That explained why computers were still functioning. I expect the vast majority of the uses of memcmp does an immediate test for equality with 0.

I still wondered though, how much code was being affected. My colleague Tim suggested that it would be possible to instrument GCC to emit a message when it was about to miscompile a program. Together we came up with a patch to GCC 9 and 10 that would print a debugging message. Once again, I recompiled my entire system, to see what GCC was miscompiling. This is what I found:

On my entire system I only found 10 lines of code that were miscompiled. Three lines are tests. All of the lines could be rewritten as a comparison to 0. None of the lines looked that serious. I am not sure which one is the worse: the reduced message integrity code(?) from some ARCFOUR implementation or the something something from an ATM driver?

The mplayer miscompilation is the most mysterious. The code surrounding that function all appears to be immediately compare memcmp with 0. And given that my debug message refused to point to exactly what line is being miscompiled in that function, I fear some set of optimizations has happened to allow this code to be miscompiled in some way.

With more hardware I could do a more thorough investigation of the consequences of this GCC bug. Until then I am going to stick with GCC 8 until GCC 9 and 10 have a new point releases.

Update: Thanks goes to Marc ‘risson’ Schmitt, who had more hardware. Please check out his results.

Tags

Responses


Russell O’Connor: contact me