voidAddressSanitizer(){char p[5];
p[5]='a';// AddressSanitizer: stack-buffer-overflow on address 0x7ffeefbff1e5 at pc 0x000100001c69 bp 0x7ffeefbff1b0 sp 0x7ffeefbff1a8*(&p[0]-1)='a';// AddressSanitizer: stack-buffer-underflow on address 0x7ffeefbff1df at pc 0x000100001c69 bp 0x7ffeefbff1b0 sp 0x7ffeefbff1a8char*ptr = new char[5];
ptr[5]='a';// AddressSanitizer: heap-buffer-overflow on address 0x602000000c35 at pc 0x000100001cd7 bp 0x7ffeefbff250 sp 0x7ffeefbff248*(ptr -1)='a';// AddressSanitizer: heap-buffer-overflow on address 0x602000000c2f at pc 0x000100001cd7 bp 0x7ffeefbff250 sp 0x7ffeefbff248
delete []ptr;
ptr[0]='a';// AddressSanitizer: heap-use-after-free on address 0x602000000c30 at pc 0x000100001cdc bp 0x7ffeefbff250 sp 0x7ffeefbff248}voidThreadSanitizer(){int Global =0;
std::thread t = std::thread([&](){
Global =42;// Data race in RunOnMainThread()::$_0::operator()() const});
Global =43;
t.join();}voidUndefinedBehaviorSanitizer(){int a[4];
a[4]=4;// runtime error: index 4 out of bounds for type 'int [4]'int k =0x7fffffff;
k +=1;// runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'char stack[5];*(stack -1)=1;// Index -1 out of bounds for type 'char [5]'
stack[5]=1;// Index 5 out of bounds for type 'char [5]'}
Runtime API Checking:检测是否有后台线程执行UI API,如果出现这样的情况就会暂停在执行的位置
Guard Malloc:如果设置了,当malloc的时候它会记录此地址,free的时候它会检查此地址有没有在登记列表中(如果不在列表中它会有这样的打印was not claimed by any registered)。当出现下溢访问的时候会奔溃在访问的位置。它还会在分配区域的前8个字节写入特定的值(每四个字节的字符是0xdeadbeef)。此选项还需要要求Logging模式为All Allocation and Free History否则不起作用。
Zombie Objects:僵尸对象检查
Malloc Stack Logging:Logging有两种模式:Live Allocations Only(简化版)和All Allocation and Free History(完整版)
voidMallocScribble(){
uint8_t* p = new uint8_t[5];printf("0x%x 0x%x 0x%x 0x%x 0x%x\n", p[0], p[1], p[2], p[3], p[4]);// 0xaa 0xaa 0xaa 0xaa 0xaa
delete [] p;printf("0x%x 0x%x 0x%x 0x%x 0x%x\n", p[0], p[1], p[2], p[3], p[4]);// 0x55 0x55 0x55 0x55 0x55}voidMallocGuardEdges(){
uint8_t* p = new uint8_t[100*1024];
uint8_t* before = p -8;
before[0]=1;// Thread 1: EXC_BAD_ACCESS (code=2, address=0x100371ff8)}voidGuardMalloc(){
uint8_t* p = new uint8_t[100*1024];printf("%p\n", p);// 0x10efc0000
uint8_t* before = p -8;printf("0x%x\n",*reinterpret_cast<uint32_t*>(before));// 0xdeadbeefprintf("0x%x\n",*(reinterpret_cast<uint32_t*>(before)+1));// 0xdeadbeef
before[0]=1;// 这里能运行通过,说明GuardMalloc检查不出内存上溢
uint8_t* after = p +100*1024;// Live Allocations Only选项时不会奔溃,All Allocation and Free History选项会奔溃
after[0]=1;// Thread 1: EXC_BAD_ACCESS (code=1, address=0x10f100000)
delete [](p +1);// GuardMalloc[MediaService-99664]: attempted free of pointer 0x10efc0001 that was not claimed by any registered malloc zone}