My library doctest is tested with 200+ builds on travis CI - x86/x64 Debug/Release linux/osx and with a wide range of compilers - from gcc 4.4 to 6 and clang 3.4 to 3.8
All my tests are ran through valgrind and the address sanitizer (also UB sanitizer).
I recently discovered that not all features of ASAN are on by default - for example:
check_initialization_order=true
detect_stack_use_after_return=true
strict_init_order=true
so I enabled them and started getting errors for code like the example below.
int& getStatic() {
static int data;
return data;
}
int reg() { return getStatic() = 0; }
static int dummy = reg();
int main() { return getStatic(); }
compiled with g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
:
g++ -fsanitize=address -g -fno-omit-frame-pointer -O2 a.cpp
and ran like this:
ASAN_OPTIONS=verbosity=0:strict_string_checks=true:detect_odr_violation=2:check_initialization_order=true:detect_stack_use_after_return=true:strict_init_order=true ./a.out
produces the following error:
==23425==AddressSanitizer CHECK failed: ../../../../src/libsanitizer/asan/asan_globals.cc:255 "((dynamic_init_globals)) != (0)" (0x0, 0x0)
#0 0x7f699bd699c1 (/usr/lib/x86_64-linux-gnu/libasan.so.2+0xa09c1)
#1 0x7f699bd6e973 in __sanitizer::CheckFailed(char const*, int, char const*, unsigned long long, unsigned long long) (/usr/lib/x86_64-linux-gnu/libasan.so.2+0xa5973)
#2 0x7f699bcf2f5c in __asan_before_dynamic_init (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x29f5c)
#3 0x40075d in __static_initialization_and_destruction_0 /home/onqtam/a.cpp:10
#4 0x40075d in _GLOBAL__sub_I__Z9getStaticv /home/onqtam/a.cpp:10
#5 0x40090c in __libc_csu_init (/home/onqtam/a.out+0x40090c)
#6 0x7f699b91fa4e in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a4e)
#7 0x4007b8 in _start (/home/onqtam/a.out+0x4007b8)
The same is with g++-6 (Ubuntu 6.1.1-3ubuntu11~12.04.1) 6.1.1 20160511
The error disappears when I do one of these 3 things:
- use clang++ (any version) instead of g++
- remove the
-O2
and use-O0
- remove the
static
in front ofdummy
Why is this happening? If it is a bug - is it reported? How to avoid it?
EDIT:
@vadikrobot said that even this: static int data = 0; static int dummy = data; int main() { }
produces the problem.
EDIT:
the answer of @ead is correct, however I found a way to circumvent the removal of the static dummy and asan doesn't assert anymore:
int& getStatic() {
static int data = 0;
return data;
}
int __attribute__((noinline)) reg(int* dummy_ptr) { *dummy_ptr = 5; return getStatic() = 0; }
static int __attribute__((unused)) dummy = reg(&dummy);
int main(int argc, char** argv) { return getStatic(); }