NSLogger icon indicating copy to clipboard operation
NSLogger copied to clipboard

encoding code falls into traps with -fcatch-undefined-behavior

Open darwin opened this issue 12 years ago • 2 comments
trafficstars

Compiling under XCode 5.0.1 (GM) with additional flags: OTHER_CFLAGS = -ftrapv -fcatch-undefined-behavior

http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html

The problem is that the code probably depends on undefined behaviour. Unfortunately I wasn't able to fix it - it may be a false positive in new clang. So I disabled strict checking for now.

darwin avatar Oct 09 '13 12:10 darwin

just a screenshot of the assertion: https://www.dropbox.com/s/etmylpx6v2a149h/Screenshot%202013-10-09%2014.06.22.png

darwin avatar Oct 09 '13 12:10 darwin

the new version of the encoder uses unaligned writes, which are perfectly supported by the processor on x86 and ARM. -fcatch-undefined-behavior adds a new specific alignment check at the binary level before reading or writing. In particular, this code:

*(uint64_t *)p = CFSwapInt64HostToBig((uint64_t)anInt);

translates (when compiled for x86_64) to:

0x10ebfdd7f:  testb  $7, %al      ; this tests for alignment on multiple of 8 bytes
0x10ebfdd81:  jne    0x10ebfdd8e  ; and if unaligned, jump to the trap instruction
0x10ebfdd83:  bswapq %rbx
...
0x10ebfdd8d:  ret    
0x10ebfdd8e:  ud2                 ; trigger an Invalid Opcode exception

the ud2 instruction generates an exception. The check above is there to guarantee that the write to a uint64_t is aligned on a multiple of 8 bytes.

I'm still trying to find how to test for this compile-time option, and if enabled use "safe" code.

fpillet avatar Nov 22 '13 09:11 fpillet