39

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

packet-ber.c:1917:23: 运行时错误: 54645397829836991 的左移 8 位不能用“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似乎有效,但这个名字看起来很内部。

4

3 回答 3

24

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

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

对于来自ppa:ubuntu-toolchain-r/test 的GCC 4.9.2 ,您需要libubsan0-dbg使上述断点可用。带有 Clang 3.3 和 3.4 的 Ubuntu 14.04 不支持__ubsan::ScopedReport::~ScopedReport断点,因此您只能在使用__ubsan::Diag::~Diag.

错误源代码示例和 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部分记录为公共接口。每当检测到违规时,都会调用此函数,其流程在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 没有公共接口,但它当前的实现也更加简单和有限(更少的选项)。出错时,可以在UBSAN_OPTIONS=print_stacktrace=1设置环境变量时打印堆栈跟踪。因此,通过搜索源代码print_stacktrace,可以找到通过ScopedReport 析构函数调用的函数MaybePrintStackTrace

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. 如果这些函数似乎都不可用(即使安装了调试符号),您可以尝试info functions ubsaninfo functions sanitizer获取所有与 (UndefinedBehavior)Sanitizer 相关的函数。

于 2015-07-23T00:43:08.223 回答
17

正如@Mark Plotnick指出的那样,这样做的方法是在 UBSan 的处理程序处设置断点。

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

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

#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浏览的内容,您可以阅读到评论的死赠品:

  // 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);

此标头中的许多其他函数被明确注释为已公开,以便可以从调试器调用。

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


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

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

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

于 2015-07-16T16:00:05.763 回答
3

设置的断点__asan_report_error对我来说没有命中,并且在没有调试器触发的情况下打印诊断信息后程序就存在了。__asan::ReportGenericError在打印诊断程序之前和__sanitizer::Die打印诊断程序之后,确实会如asan wiki中所述受到打击。

于 2019-04-12T12:56:57.820 回答