1 //===-- ubsan_handlers.cc -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Error logging entry points for the UBSan runtime.
12 //===----------------------------------------------------------------------===//
14 #include "ubsan_platform.h"
16 #include "ubsan_handlers.h"
17 #include "ubsan_diag.h"
19 #include "sanitizer_common/sanitizer_common.h"
21 using namespace __sanitizer;
22 using namespace __ubsan;
25 bool ignoreReport(SourceLocation SLoc, ReportOptions Opts, ErrorType ET) {
26 // We are not allowed to skip error report: if we are in unrecoverable
27 // handler, we have to terminate the program right now, and therefore
28 // have to print some diagnostic.
30 // Even if source location is disabled, it doesn't mean that we have
31 // already report an error to the user: some concurrently running
32 // thread could have acquired it, but not yet printed the report.
33 if (Opts.FromUnrecoverableHandler)
35 return SLoc.isDisabled() || IsPCSuppressed(ET, Opts.pc, SLoc.getFilename());
38 const char *TypeCheckKinds[] = {
39 "load of", "store to", "reference binding to", "member access within",
40 "member call on", "constructor call on", "downcast of", "downcast of",
41 "upcast of", "cast to virtual base of", "_Nonnull binding to"};
44 static void handleTypeMismatchImpl(TypeMismatchData *Data, ValueHandle Pointer,
46 Location Loc = Data->Loc.acquire();
48 uptr Alignment = (uptr)1 << Data->LogAlignment;
51 ET = ErrorType::NullPointerUse;
52 else if (Pointer & (Alignment - 1))
53 ET = ErrorType::MisalignedPointerUse;
55 ET = ErrorType::InsufficientObjectSize;
57 // Use the SourceLocation from Data to track deduplication, even if it's
59 if (ignoreReport(Loc.getSourceLocation(), Opts, ET))
62 SymbolizedStackHolder FallbackLoc;
63 if (Data->Loc.isInvalid()) {
64 FallbackLoc.reset(getCallerLocation(Opts.pc));
68 ScopedReport R(Opts, Loc, ET);
71 case ErrorType::NullPointerUse:
72 Diag(Loc, DL_Error, "%0 null pointer of type %1")
73 << TypeCheckKinds[Data->TypeCheckKind] << Data->Type;
75 case ErrorType::MisalignedPointerUse:
76 Diag(Loc, DL_Error, "%0 misaligned address %1 for type %3, "
77 "which requires %2 byte alignment")
78 << TypeCheckKinds[Data->TypeCheckKind] << (void *)Pointer << Alignment
81 case ErrorType::InsufficientObjectSize:
82 Diag(Loc, DL_Error, "%0 address %1 with insufficient space "
83 "for an object of type %2")
84 << TypeCheckKinds[Data->TypeCheckKind] << (void *)Pointer << Data->Type;
87 UNREACHABLE("unexpected error type!");
91 Diag(Pointer, DL_Note, "pointer points here");
94 void __ubsan::__ubsan_handle_type_mismatch_v1(TypeMismatchData *Data,
95 ValueHandle Pointer) {
96 GET_REPORT_OPTIONS(false);
97 handleTypeMismatchImpl(Data, Pointer, Opts);
99 void __ubsan::__ubsan_handle_type_mismatch_v1_abort(TypeMismatchData *Data,
100 ValueHandle Pointer) {
101 GET_REPORT_OPTIONS(true);
102 handleTypeMismatchImpl(Data, Pointer, Opts);
106 /// \brief Common diagnostic emission for various forms of integer overflow.
107 template <typename T>
108 static void handleIntegerOverflowImpl(OverflowData *Data, ValueHandle LHS,
109 const char *Operator, T RHS,
110 ReportOptions Opts) {
111 SourceLocation Loc = Data->Loc.acquire();
112 bool IsSigned = Data->Type.isSignedIntegerTy();
113 ErrorType ET = IsSigned ? ErrorType::SignedIntegerOverflow
114 : ErrorType::UnsignedIntegerOverflow;
116 if (ignoreReport(Loc, Opts, ET))
119 ScopedReport R(Opts, Loc, ET);
121 Diag(Loc, DL_Error, "%0 integer overflow: "
122 "%1 %2 %3 cannot be represented in type %4")
123 << (IsSigned ? "signed" : "unsigned")
124 << Value(Data->Type, LHS) << Operator << RHS << Data->Type;
127 #define UBSAN_OVERFLOW_HANDLER(handler_name, op, unrecoverable) \
128 void __ubsan::handler_name(OverflowData *Data, ValueHandle LHS, \
130 GET_REPORT_OPTIONS(unrecoverable); \
131 handleIntegerOverflowImpl(Data, LHS, op, Value(Data->Type, RHS), Opts); \
136 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_add_overflow, "+", false)
137 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_add_overflow_abort, "+", true)
138 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_sub_overflow, "-", false)
139 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_sub_overflow_abort, "-", true)
140 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_mul_overflow, "*", false)
141 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_mul_overflow_abort, "*", true)
143 static void handleNegateOverflowImpl(OverflowData *Data, ValueHandle OldVal,
144 ReportOptions Opts) {
145 SourceLocation Loc = Data->Loc.acquire();
146 bool IsSigned = Data->Type.isSignedIntegerTy();
147 ErrorType ET = IsSigned ? ErrorType::SignedIntegerOverflow
148 : ErrorType::UnsignedIntegerOverflow;
150 if (ignoreReport(Loc, Opts, ET))
153 ScopedReport R(Opts, Loc, ET);
157 "negation of %0 cannot be represented in type %1; "
158 "cast to an unsigned type to negate this value to itself")
159 << Value(Data->Type, OldVal) << Data->Type;
161 Diag(Loc, DL_Error, "negation of %0 cannot be represented in type %1")
162 << Value(Data->Type, OldVal) << Data->Type;
165 void __ubsan::__ubsan_handle_negate_overflow(OverflowData *Data,
166 ValueHandle OldVal) {
167 GET_REPORT_OPTIONS(false);
168 handleNegateOverflowImpl(Data, OldVal, Opts);
170 void __ubsan::__ubsan_handle_negate_overflow_abort(OverflowData *Data,
171 ValueHandle OldVal) {
172 GET_REPORT_OPTIONS(true);
173 handleNegateOverflowImpl(Data, OldVal, Opts);
177 static void handleDivremOverflowImpl(OverflowData *Data, ValueHandle LHS,
178 ValueHandle RHS, ReportOptions Opts) {
179 SourceLocation Loc = Data->Loc.acquire();
180 Value LHSVal(Data->Type, LHS);
181 Value RHSVal(Data->Type, RHS);
184 if (RHSVal.isMinusOne())
185 ET = ErrorType::SignedIntegerOverflow;
186 else if (Data->Type.isIntegerTy())
187 ET = ErrorType::IntegerDivideByZero;
189 ET = ErrorType::FloatDivideByZero;
191 if (ignoreReport(Loc, Opts, ET))
194 ScopedReport R(Opts, Loc, ET);
197 case ErrorType::SignedIntegerOverflow:
198 Diag(Loc, DL_Error, "division of %0 by -1 cannot be represented in type %1")
199 << LHSVal << Data->Type;
202 Diag(Loc, DL_Error, "division by zero");
207 void __ubsan::__ubsan_handle_divrem_overflow(OverflowData *Data,
208 ValueHandle LHS, ValueHandle RHS) {
209 GET_REPORT_OPTIONS(false);
210 handleDivremOverflowImpl(Data, LHS, RHS, Opts);
212 void __ubsan::__ubsan_handle_divrem_overflow_abort(OverflowData *Data,
215 GET_REPORT_OPTIONS(true);
216 handleDivremOverflowImpl(Data, LHS, RHS, Opts);
220 static void handleShiftOutOfBoundsImpl(ShiftOutOfBoundsData *Data,
221 ValueHandle LHS, ValueHandle RHS,
222 ReportOptions Opts) {
223 SourceLocation Loc = Data->Loc.acquire();
224 Value LHSVal(Data->LHSType, LHS);
225 Value RHSVal(Data->RHSType, RHS);
228 if (RHSVal.isNegative() ||
229 RHSVal.getPositiveIntValue() >= Data->LHSType.getIntegerBitWidth())
230 ET = ErrorType::InvalidShiftExponent;
232 ET = ErrorType::InvalidShiftBase;
234 if (ignoreReport(Loc, Opts, ET))
237 ScopedReport R(Opts, Loc, ET);
239 if (ET == ErrorType::InvalidShiftExponent) {
240 if (RHSVal.isNegative())
241 Diag(Loc, DL_Error, "shift exponent %0 is negative") << RHSVal;
243 Diag(Loc, DL_Error, "shift exponent %0 is too large for %1-bit type %2")
244 << RHSVal << Data->LHSType.getIntegerBitWidth() << Data->LHSType;
246 if (LHSVal.isNegative())
247 Diag(Loc, DL_Error, "left shift of negative value %0") << LHSVal;
250 "left shift of %0 by %1 places cannot be represented in type %2")
251 << LHSVal << RHSVal << Data->LHSType;
255 void __ubsan::__ubsan_handle_shift_out_of_bounds(ShiftOutOfBoundsData *Data,
258 GET_REPORT_OPTIONS(false);
259 handleShiftOutOfBoundsImpl(Data, LHS, RHS, Opts);
261 void __ubsan::__ubsan_handle_shift_out_of_bounds_abort(
262 ShiftOutOfBoundsData *Data,
265 GET_REPORT_OPTIONS(true);
266 handleShiftOutOfBoundsImpl(Data, LHS, RHS, Opts);
270 static void handleOutOfBoundsImpl(OutOfBoundsData *Data, ValueHandle Index,
271 ReportOptions Opts) {
272 SourceLocation Loc = Data->Loc.acquire();
273 ErrorType ET = ErrorType::OutOfBoundsIndex;
275 if (ignoreReport(Loc, Opts, ET))
278 ScopedReport R(Opts, Loc, ET);
280 Value IndexVal(Data->IndexType, Index);
281 Diag(Loc, DL_Error, "index %0 out of bounds for type %1")
282 << IndexVal << Data->ArrayType;
285 void __ubsan::__ubsan_handle_out_of_bounds(OutOfBoundsData *Data,
287 GET_REPORT_OPTIONS(false);
288 handleOutOfBoundsImpl(Data, Index, Opts);
290 void __ubsan::__ubsan_handle_out_of_bounds_abort(OutOfBoundsData *Data,
292 GET_REPORT_OPTIONS(true);
293 handleOutOfBoundsImpl(Data, Index, Opts);
297 static void handleBuiltinUnreachableImpl(UnreachableData *Data,
298 ReportOptions Opts) {
299 ScopedReport R(Opts, Data->Loc, ErrorType::UnreachableCall);
300 Diag(Data->Loc, DL_Error, "execution reached a __builtin_unreachable() call");
303 void __ubsan::__ubsan_handle_builtin_unreachable(UnreachableData *Data) {
304 GET_REPORT_OPTIONS(true);
305 handleBuiltinUnreachableImpl(Data, Opts);
309 static void handleMissingReturnImpl(UnreachableData *Data, ReportOptions Opts) {
310 ScopedReport R(Opts, Data->Loc, ErrorType::MissingReturn);
311 Diag(Data->Loc, DL_Error,
312 "execution reached the end of a value-returning function "
313 "without returning a value");
316 void __ubsan::__ubsan_handle_missing_return(UnreachableData *Data) {
317 GET_REPORT_OPTIONS(true);
318 handleMissingReturnImpl(Data, Opts);
322 static void handleVLABoundNotPositive(VLABoundData *Data, ValueHandle Bound,
323 ReportOptions Opts) {
324 SourceLocation Loc = Data->Loc.acquire();
325 ErrorType ET = ErrorType::NonPositiveVLAIndex;
327 if (ignoreReport(Loc, Opts, ET))
330 ScopedReport R(Opts, Loc, ET);
332 Diag(Loc, DL_Error, "variable length array bound evaluates to "
333 "non-positive value %0")
334 << Value(Data->Type, Bound);
337 void __ubsan::__ubsan_handle_vla_bound_not_positive(VLABoundData *Data,
339 GET_REPORT_OPTIONS(false);
340 handleVLABoundNotPositive(Data, Bound, Opts);
342 void __ubsan::__ubsan_handle_vla_bound_not_positive_abort(VLABoundData *Data,
344 GET_REPORT_OPTIONS(true);
345 handleVLABoundNotPositive(Data, Bound, Opts);
349 static bool looksLikeFloatCastOverflowDataV1(void *Data) {
350 // First field is either a pointer to filename or a pointer to a
352 u8 *FilenameOrTypeDescriptor;
353 internal_memcpy(&FilenameOrTypeDescriptor, Data,
354 sizeof(FilenameOrTypeDescriptor));
356 // Heuristic: For float_cast_overflow, the TypeKind will be either TK_Integer
357 // (0x0), TK_Float (0x1) or TK_Unknown (0xff). If both types are known,
358 // adding both bytes will be 0 or 1 (for BE or LE). If it were a filename,
359 // adding two printable characters will not yield such a value. Otherwise,
360 // if one of them is 0xff, this is most likely TK_Unknown type descriptor.
361 u16 MaybeFromTypeKind =
362 FilenameOrTypeDescriptor[0] + FilenameOrTypeDescriptor[1];
363 return MaybeFromTypeKind < 2 || FilenameOrTypeDescriptor[0] == 0xff ||
364 FilenameOrTypeDescriptor[1] == 0xff;
367 static void handleFloatCastOverflow(void *DataPtr, ValueHandle From,
368 ReportOptions Opts) {
369 SymbolizedStackHolder CallerLoc;
371 const TypeDescriptor *FromType, *ToType;
372 ErrorType ET = ErrorType::FloatCastOverflow;
374 if (looksLikeFloatCastOverflowDataV1(DataPtr)) {
375 auto Data = reinterpret_cast<FloatCastOverflowData *>(DataPtr);
376 CallerLoc.reset(getCallerLocation(Opts.pc));
378 FromType = &Data->FromType;
379 ToType = &Data->ToType;
381 auto Data = reinterpret_cast<FloatCastOverflowDataV2 *>(DataPtr);
382 SourceLocation SLoc = Data->Loc.acquire();
383 if (ignoreReport(SLoc, Opts, ET))
386 FromType = &Data->FromType;
387 ToType = &Data->ToType;
390 ScopedReport R(Opts, Loc, ET);
393 "%0 is outside the range of representable values of type %2")
394 << Value(*FromType, From) << *FromType << *ToType;
397 void __ubsan::__ubsan_handle_float_cast_overflow(void *Data, ValueHandle From) {
398 GET_REPORT_OPTIONS(false);
399 handleFloatCastOverflow(Data, From, Opts);
401 void __ubsan::__ubsan_handle_float_cast_overflow_abort(void *Data,
403 GET_REPORT_OPTIONS(true);
404 handleFloatCastOverflow(Data, From, Opts);
408 static void handleLoadInvalidValue(InvalidValueData *Data, ValueHandle Val,
409 ReportOptions Opts) {
410 SourceLocation Loc = Data->Loc.acquire();
411 // This check could be more precise if we used different handlers for
412 // -fsanitize=bool and -fsanitize=enum.
413 bool IsBool = (0 == internal_strcmp(Data->Type.getTypeName(), "'bool'")) ||
414 (0 == internal_strncmp(Data->Type.getTypeName(), "'BOOL'", 6));
416 IsBool ? ErrorType::InvalidBoolLoad : ErrorType::InvalidEnumLoad;
418 if (ignoreReport(Loc, Opts, ET))
421 ScopedReport R(Opts, Loc, ET);
424 "load of value %0, which is not a valid value for type %1")
425 << Value(Data->Type, Val) << Data->Type;
428 void __ubsan::__ubsan_handle_load_invalid_value(InvalidValueData *Data,
430 GET_REPORT_OPTIONS(false);
431 handleLoadInvalidValue(Data, Val, Opts);
433 void __ubsan::__ubsan_handle_load_invalid_value_abort(InvalidValueData *Data,
435 GET_REPORT_OPTIONS(true);
436 handleLoadInvalidValue(Data, Val, Opts);
440 static void handleFunctionTypeMismatch(FunctionTypeMismatchData *Data,
441 ValueHandle Function,
442 ReportOptions Opts) {
443 SourceLocation CallLoc = Data->Loc.acquire();
444 ErrorType ET = ErrorType::FunctionTypeMismatch;
446 if (ignoreReport(CallLoc, Opts, ET))
449 ScopedReport R(Opts, CallLoc, ET);
451 SymbolizedStackHolder FLoc(getSymbolizedLocation(Function));
452 const char *FName = FLoc.get()->info.function;
456 Diag(CallLoc, DL_Error,
457 "call to function %0 through pointer to incorrect function type %1")
458 << FName << Data->Type;
459 Diag(FLoc, DL_Note, "%0 defined here") << FName;
463 __ubsan::__ubsan_handle_function_type_mismatch(FunctionTypeMismatchData *Data,
464 ValueHandle Function) {
465 GET_REPORT_OPTIONS(false);
466 handleFunctionTypeMismatch(Data, Function, Opts);
469 void __ubsan::__ubsan_handle_function_type_mismatch_abort(
470 FunctionTypeMismatchData *Data, ValueHandle Function) {
471 GET_REPORT_OPTIONS(true);
472 handleFunctionTypeMismatch(Data, Function, Opts);
476 static void handleNonNullReturn(NonNullReturnData *Data, ReportOptions Opts,
478 SourceLocation Loc = Data->Loc.acquire();
479 ErrorType ET = ErrorType::InvalidNullReturn;
481 if (ignoreReport(Loc, Opts, ET))
484 ScopedReport R(Opts, Loc, ET);
486 Diag(Loc, DL_Error, "null pointer returned from function declared to never "
488 if (!Data->AttrLoc.isInvalid())
489 Diag(Data->AttrLoc, DL_Note, "%0 specified here")
490 << (IsAttr ? "returns_nonnull attribute"
491 : "_Nonnull return type annotation");
494 void __ubsan::__ubsan_handle_nonnull_return(NonNullReturnData *Data) {
495 GET_REPORT_OPTIONS(false);
496 handleNonNullReturn(Data, Opts, true);
499 void __ubsan::__ubsan_handle_nonnull_return_abort(NonNullReturnData *Data) {
500 GET_REPORT_OPTIONS(true);
501 handleNonNullReturn(Data, Opts, true);
505 void __ubsan::__ubsan_handle_nullability_return(NonNullReturnData *Data) {
506 GET_REPORT_OPTIONS(false);
507 handleNonNullReturn(Data, Opts, false);
510 void __ubsan::__ubsan_handle_nullability_return_abort(NonNullReturnData *Data) {
511 GET_REPORT_OPTIONS(true);
512 handleNonNullReturn(Data, Opts, false);
516 static void handleNonNullArg(NonNullArgData *Data, ReportOptions Opts,
518 SourceLocation Loc = Data->Loc.acquire();
519 ErrorType ET = ErrorType::InvalidNullArgument;
521 if (ignoreReport(Loc, Opts, ET))
524 ScopedReport R(Opts, Loc, ET);
527 "null pointer passed as argument %0, which is declared to "
530 if (!Data->AttrLoc.isInvalid())
531 Diag(Data->AttrLoc, DL_Note, "%0 specified here")
532 << (IsAttr ? "nonnull attribute" : "_Nonnull type annotation");
535 void __ubsan::__ubsan_handle_nonnull_arg(NonNullArgData *Data) {
536 GET_REPORT_OPTIONS(false);
537 handleNonNullArg(Data, Opts, true);
540 void __ubsan::__ubsan_handle_nonnull_arg_abort(NonNullArgData *Data) {
541 GET_REPORT_OPTIONS(true);
542 handleNonNullArg(Data, Opts, true);
546 void __ubsan::__ubsan_handle_nullability_arg(NonNullArgData *Data) {
547 GET_REPORT_OPTIONS(false);
548 handleNonNullArg(Data, Opts, false);
551 void __ubsan::__ubsan_handle_nullability_arg_abort(NonNullArgData *Data) {
552 GET_REPORT_OPTIONS(true);
553 handleNonNullArg(Data, Opts, false);
557 static void handleCFIBadIcall(CFICheckFailData *Data, ValueHandle Function,
558 ReportOptions Opts) {
559 if (Data->CheckKind != CFITCK_ICall)
562 SourceLocation Loc = Data->Loc.acquire();
563 ErrorType ET = ErrorType::CFIBadType;
565 if (ignoreReport(Loc, Opts, ET))
568 ScopedReport R(Opts, Loc, ET);
570 Diag(Loc, DL_Error, "control flow integrity check for type %0 failed during "
571 "indirect function call")
574 SymbolizedStackHolder FLoc(getSymbolizedLocation(Function));
575 const char *FName = FLoc.get()->info.function;
578 Diag(FLoc, DL_Note, "%0 defined here") << FName;
582 #ifdef UBSAN_CAN_USE_CXXABI
583 SANITIZER_WEAK_ATTRIBUTE
584 void HandleCFIBadType(CFICheckFailData *Data, ValueHandle Vtable,
585 bool ValidVtable, ReportOptions Opts);
587 static void HandleCFIBadType(CFICheckFailData *Data, ValueHandle Vtable,
588 bool ValidVtable, ReportOptions Opts) {
592 } // namespace __ubsan
594 void __ubsan::__ubsan_handle_cfi_check_fail(CFICheckFailData *Data,
597 GET_REPORT_OPTIONS(false);
598 if (Data->CheckKind == CFITCK_ICall)
599 handleCFIBadIcall(Data, Value, Opts);
601 HandleCFIBadType(Data, Value, ValidVtable, Opts);
604 void __ubsan::__ubsan_handle_cfi_check_fail_abort(CFICheckFailData *Data,
607 GET_REPORT_OPTIONS(true);
608 if (Data->CheckKind == CFITCK_ICall)
609 handleCFIBadIcall(Data, Value, Opts);
611 HandleCFIBadType(Data, Value, ValidVtable, Opts);
615 #endif // CAN_SANITIZE_UB