我怎样才能打破 gdb 中的 UBSan 报告并继续?

How can I break on UBSan reports in gdb and continue?

最新版本的 GCC 和 Clang 具有未定义行为消毒器 (UBSan),它是一个编译标志 (-fsanitize=undefined),可添加运行时检测代码。出现错误时,会显示如下警告:

packet-ber.c:1917:23: runtime error: left shift of 54645397829836991 by 8 places cannot be represented in type 'long int'

现在我想调试它并在所述行上获得调试中断。对于 Address Sanitizer (ASAN),有 ASAN_OPTIONS=abort_on_error=1 会导致可捕获的致命错误。唯一可用的 UBSan 选项是 UBSAN_OPTIONS=print_stacktrace=1,它会生成报告的调用跟踪转储。然而,这不允许我检查局部变量然后继续程序。因此无法使用 -fsanitize-undefined-trap-on-error

我应该如何在 UBSan 报告中中断 gdb?虽然 break __sanitizer::SharedPrintfCode 似乎有效,但名称看​​起来很内部。

正如@Mark Plotnick points out,这样做的方法是在 UBSan 的 handlers.

处设置断点

UBSan 有许多处理程序或魔术函数入口点,它们会为未定义的行为调用。编译器通过适当地注入检查来检测代码;如果检查代码检测到 UB,它会调用这些处理程序。它们都以__ubsan_handle_开头,定义在libsanitizer/ubsan/ubsan_handlers.h中。这是 link to GCC's copy of ubsan_handlers.h.

这是 UBSan header 的相关位(其中任何一个的断点):

#define UNRECOVERABLE(checkname, ...) \
  extern "C" SANITIZER_INTERFACE_ATTRIBUTE NORETURN \
    void __ubsan_handle_ ## checkname( __VA_ARGS__ );

#define RECOVERABLE(checkname, ...) \
  extern "C" SANITIZER_INTERFACE_ATTRIBUTE \
    void __ubsan_handle_ ## checkname( __VA_ARGS__ ); \
  extern "C" SANITIZER_INTERFACE_ATTRIBUTE NORETURN \
    void __ubsan_handle_ ## checkname ## _abort( __VA_ARGS__ );

/// \brief Handle a runtime type check failure, caused by either a misaligned
/// pointer, a null pointer, or a pointer to insufficient storage for the
/// type.
RECOVERABLE(type_mismatch, TypeMismatchData *Data, ValueHandle Pointer)

/// \brief Handle an integer addition overflow.
RECOVERABLE(add_overflow, OverflowData *Data, ValueHandle LHS, ValueHandle RHS)

/// \brief Handle an integer subtraction overflow.
RECOVERABLE(sub_overflow, OverflowData *Data, ValueHandle LHS, ValueHandle RHS)

/// \brief Handle an integer multiplication overflow.
RECOVERABLE(mul_overflow, OverflowData *Data, ValueHandle LHS, ValueHandle RHS)

/// \brief Handle a signed integer overflow for a unary negate operator.
RECOVERABLE(negate_overflow, OverflowData *Data, ValueHandle OldVal)

/// \brief Handle an INT_MIN/-1 overflow or division by zero.
RECOVERABLE(divrem_overflow, OverflowData *Data,
            ValueHandle LHS, ValueHandle RHS)

/// \brief Handle a shift where the RHS is out of bounds or a left shift where
/// the LHS is negative or overflows.
RECOVERABLE(shift_out_of_bounds, ShiftOutOfBoundsData *Data,
            ValueHandle LHS, ValueHandle RHS)

/// \brief Handle an array index out of bounds error.
RECOVERABLE(out_of_bounds, OutOfBoundsData *Data, ValueHandle Index)

/// \brief Handle a __builtin_unreachable which is reached.
UNRECOVERABLE(builtin_unreachable, UnreachableData *Data)
/// \brief Handle reaching the end of a value-returning function.
UNRECOVERABLE(missing_return, UnreachableData *Data)

/// \brief Handle a VLA with a non-positive bound.
RECOVERABLE(vla_bound_not_positive, VLABoundData *Data, ValueHandle Bound)

/// \brief Handle overflow in a conversion to or from a floating-point type.
RECOVERABLE(float_cast_overflow, FloatCastOverflowData *Data, ValueHandle From)

/// \brief Handle a load of an invalid value for the type.
RECOVERABLE(load_invalid_value, InvalidValueData *Data, ValueHandle Val)

RECOVERABLE(function_type_mismatch,
            FunctionTypeMismatchData *Data,
            ValueHandle Val)

/// \brief Handle returning null from function with returns_nonnull attribute.
RECOVERABLE(nonnull_return, NonNullReturnData *Data)

/// \brief Handle passing null pointer to function with nonnull attribute.
RECOVERABLE(nonnull_arg, NonNullArgData *Data)

ASan更简单。如果您查看 libsanitizer/include/sanitizer/asan_interface.h,您应该浏览 here,您可以阅读评论的死赠品:

  // This is an internal function that is called to report an error.
  // However it is still a part of the interface because users may want to
  // set a breakpoint on this function in a debugger.
  void __asan_report_error(void *pc, void *bp, void *sp,
                           void *addr, int is_write, size_t access_size);

此 header 中的许多其他函数被明确注释为已创建 public 以便可从调试器调用。

我绝对建议您探索 libsanitizer/include/sanitizer here 的其他 header。那里有很多好东西。


UBSan 和 ASan 的断点可以添加如下:

(gdb) rbreak ^__ubsan_handle_ __asan_report_error
(gdb) commands
(gdb) finish
(gdb) end

这将在处理程序上设置断点,finish 紧随其后。这允许打印报告,但调试器在打印后立即获得控制权。

虽然中断检测功能(如 and 所述)是一种选择,但更好的方法是中断检测后报告这些问题的功能。这种方法也用于 ASAN,其中一个人会在 __asan_report_error.

上中断

总结:您可以通过 __ubsan::ScopedReport::~ScopedReport__ubsan::Diag::~Diag 上的断点停止 ubsan 报告。这些是私有实现细节,但将来可能会发生变化。使用 GCC 4.9、5.1.0、5.2.0 和 Clang 3.3、3.4、3.6.2 进行测试。

对于来自 ppa:ubuntu-toolchain-r/test, you need libubsan0-dbg to make the above breakpoints available. Ubuntu 14.04 with Clang 3.3 and 3.4 do not support the __ubsan::ScopedReport::~ScopedReport breakpoints, so you can only break before printing the message using __ubsan::Diag::~Diag 的 GCC 4.9.2。

错误源代码示例和 gdb 会话:

$ cat undef.c
int main(void) { return 1 << 1000; }
$ clang --version
clang version 3.6.2 (tags/RELEASE_362/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
$ clang -w -fsanitize=undefined undef.c -g
$ gdb -q -ex break\ __ubsan::ScopedReport::~ScopedReport -ex r ./a.out 
Reading symbols from ./a.out...done.
Breakpoint 1 at 0x428fb0
Starting program: ./a.out 
undef.c:1:27: runtime error: shift exponent 1000 is too large for 32-bit type 'int'

Breakpoint 1, 0x0000000000428fb0 in __ubsan::ScopedReport::~ScopedReport() ()
(gdb) bt
#0  0x0000000000428fb0 in __ubsan::ScopedReport::~ScopedReport() ()
#1  0x000000000042affb in handleShiftOutOfBoundsImpl(__ubsan::ShiftOutOfBoundsData*, unsigned long, unsigned long, __ubsan::ReportOptions) ()
#2  0x000000000042a952 in __ubsan_handle_shift_out_of_bounds ()
#3  0x000000000042d057 in main () at undef.c:1

具体分析如下。请注意,ASAN 和 ubsan 都源自 LLVM 项目 compiler-rt。这被 Clang 使用并最终出现在 GCC 中。以下部分中的链接指向 compiler-rt 项目代码,版本 3.6。

ASAN 已使其内部 __asan_report_error 成为 documented public interface. This function gets called whenever a violation is detected, its flow continues in lib/asan/asan_report.c:938:

的一部分
void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
                         uptr access_size) {
  // Determine the error type.
  const char *bug_descr = "unknown-crash";
  ...

  ReportData report = { pc, sp, bp, addr, (bool)is_write, access_size,
                        bug_descr };
  ScopedInErrorReport in_report(&report);

  Decorator d;
  Printf("%s", d.Warning());
  Report("ERROR: AddressSanitizer: %s on address "
             "%p at pc %p bp %p sp %p\n",
             bug_descr, (void*)addr, pc, bp, sp);
  Printf("%s", d.EndWarning());

  u32 curr_tid = GetCurrentTidOrInvalid();
  char tname[128];
  Printf("%s%s of size %zu at %p thread T%d%s%s\n",
         d.Access(),
         access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
         access_size, (void*)addr, curr_tid,
         ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)),
         d.EndAccess());

  GET_STACK_TRACE_FATAL(pc, bp);
  stack.Print();

  DescribeAddress(addr, access_size);
  ReportErrorSummary(bug_descr, &stack);
  PrintShadowMemoryForAddress(addr);
}

ubsan 另一方面没有 public 接口,但它当前的实现也更简单和有限(选项更少)。出错时,可以在设置 UBSAN_OPTIONS=print_stacktrace=1 环境变量时打印堆栈跟踪。因此,通过搜索 print_stacktrace 的源代码,可以找到函数 MaybePrintStackTrace which is called though the ScopedReport destructor:

ScopedReport::~ScopedReport() {
  MaybePrintStackTrace(Opts.pc, Opts.bp);
  MaybeReportErrorSummary(SummaryLoc);
  CommonSanitizerReportMutex.Unlock();
  if (Opts.DieAfterReport || flags()->halt_on_error)
    Die();
}

如您所见,有一种方法可以在出现错误时终止程序,但遗憾的是没有内置机制来触发调试器陷阱。那就找个合适的断点吧。

GDB 命令info functions <function name> 可以将MaybePrintStackTrace 识别为可以设置断点的函数。 info functions ScopedReport::~ScopedReport 的执行给出了另一个函数:__ubsan::ScopedReport::~ScopedReport。如果 none 这些功能似乎可用(即使安装了调试符号),您可以尝试 info functions ubsaninfo functions sanitizer 来获取所有 (UndefinedBehavior)Sanitizer 相关的功能。

设置在 __asan_report_error 的断点对我来说没有命中,程序在打印诊断后就存在而没有调试器触发。 __asan::ReportGenericError 在打印诊断之前和 __sanitizer::Die 在打印诊断之后确实如 the asan wiki 中所述被命中。