地址消毒器在静态投射无效指针时报告错误

address sanitizer reports error when statically casting an invalid pointer

将未分配内存中的 Derived* 静态转换为 Base* 时,gcc 的 ASAN 报告:

ASAN:DEADLYSIGNAL
=================================================================
==12829==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x563da3783776 bp 0x7ffde1670e50 sp 0x7ffde166d800 T0)
==12829==The signal is caused by a READ memory access.
==12829==Hint: address points to the zero page.

为了测试,我使用了这个设置:

struct Base2 { int dummy; };
struct Base { int dummy2; };
struct Derived : public Base2, public virtual Base { };

Derived* derived = (Derived*)0x1122334455667788; /* some pointer into non-allocated memory */
Base* base = static_cast<Base*>(derived); /* ASAN fails here */

为什么 ASAN 在这里报告无效的读取访问?指针偏移量和正确的结果指针值不应该在编译时已知吗?

那么为什么需要这种读取权限?

Shouldn't the pointer offset and therefore the correct resulting pointer value be known at compile time?

不,虚拟继承的偏移量 class 在编译时是未知的,因此编译器会在运行时通过访问 vtable 来计算它。

这是一个简单的例子:

Base *foo(Derived *p) {
  return static_cast<Base*>(p);
}

编译为

movq    (%rdi), %rax     # Get vptr
addq    -24(%rax), %rdi  # Load offset of Base from vtable
movq    %rdi, %rax       # Return result
ret

ASan 抱怨是因为您尝试访问一些导致段错误的随机内存地址。