1//===-- ubsan_handlers.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Error logging entry points for the UBSan runtime.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ubsan_platform.h"
14#if CAN_SANITIZE_UB
15#include "ubsan_handlers.h"
16#include "ubsan_diag.h"
17#include "ubsan_flags.h"
18#include "ubsan_monitor.h"
19#include "ubsan_value.h"
20
21#include "sanitizer_common/sanitizer_common.h"
22#include "ubsan_handlers_internal.h"
23
24using namespace __sanitizer;
25using namespace __ubsan;
26
27namespace __ubsan {
28bool ignoreReport(SourceLocation SLoc, ReportOptions Opts, ErrorType ET) {
29 // We are not allowed to skip error report: if we are in unrecoverable
30 // handler, we have to terminate the program right now, and therefore
31 // have to print some diagnostic.
32 //
33 // Even if source location is disabled, it doesn't mean that we have
34 // already report an error to the user: some concurrently running
35 // thread could have acquired it, but not yet printed the report.
36 if (Opts.FromUnrecoverableHandler)
37 return false;
38 if (Opts.FromOffload)
39 return SLoc.isDisabled();
40 return SLoc.isDisabled() || IsPCSuppressed(ET, PC: Opts.pc, Filename: SLoc.getFilename());
41}
42
43/// Situations in which we might emit a check for the suitability of a
44/// pointer or glvalue. Needs to be kept in sync with CodeGenFunction.h in
45/// clang.
46enum TypeCheckKind {
47 /// Checking the operand of a load. Must be suitably sized and aligned.
48 TCK_Load,
49 /// Checking the destination of a store. Must be suitably sized and aligned.
50 TCK_Store,
51 /// Checking the bound value in a reference binding. Must be suitably sized
52 /// and aligned, but is not required to refer to an object (until the
53 /// reference is used), per core issue 453.
54 TCK_ReferenceBinding,
55 /// Checking the object expression in a non-static data member access. Must
56 /// be an object within its lifetime.
57 TCK_MemberAccess,
58 /// Checking the 'this' pointer for a call to a non-static member function.
59 /// Must be an object within its lifetime.
60 TCK_MemberCall,
61 /// Checking the 'this' pointer for a constructor call.
62 TCK_ConstructorCall,
63 /// Checking the operand of a static_cast to a derived pointer type. Must be
64 /// null or an object within its lifetime.
65 TCK_DowncastPointer,
66 /// Checking the operand of a static_cast to a derived reference type. Must
67 /// be an object within its lifetime.
68 TCK_DowncastReference,
69 /// Checking the operand of a cast to a base object. Must be suitably sized
70 /// and aligned.
71 TCK_Upcast,
72 /// Checking the operand of a cast to a virtual base object. Must be an
73 /// object within its lifetime.
74 TCK_UpcastToVirtualBase,
75 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
76 TCK_NonnullAssign,
77 /// Checking the operand of a dynamic_cast or a typeid expression. Must be
78 /// null or an object within its lifetime.
79 TCK_DynamicOperation
80};
81
82extern const char *const TypeCheckKinds[] = {
83 "load of", "store to", "reference binding to", "member access within",
84 "member call on", "constructor call on", "downcast of", "downcast of",
85 "upcast of", "cast to virtual base of", "_Nonnull binding to",
86 "dynamic operation on"};
87}
88
89void __ubsan::handleTypeMismatchImpl(TypeMismatchData *Data,
90 ValueHandle Pointer, ReportOptions Opts) {
91 Location Loc = Data->Loc.acquire();
92
93 uptr Alignment = (uptr)1 << Data->LogAlignment;
94 ErrorType ET;
95 if (!Pointer)
96 ET = (Data->TypeCheckKind == TCK_NonnullAssign)
97 ? ErrorType::NullPointerUseWithNullability
98 : ErrorType::NullPointerUse;
99 else if (Pointer & (Alignment - 1))
100 ET = ErrorType::MisalignedPointerUse;
101 else
102 ET = ErrorType::InsufficientObjectSize;
103
104 // Use the SourceLocation from Data to track deduplication, even if it's
105 // invalid.
106 if (ignoreReport(SLoc: Loc.getSourceLocation(), Opts, ET))
107 return;
108
109 SymbolizedStackHolder FallbackLoc;
110 if (Data->Loc.isInvalid()) {
111 FallbackLoc.reset(S: getReportLocation(PC: Opts.pc, FromOffload: Opts.FromOffload));
112 Loc = FallbackLoc;
113 }
114
115 ScopedReport R(Opts, Loc, ET);
116
117 switch (ET) {
118 case ErrorType::NullPointerUse:
119 case ErrorType::NullPointerUseWithNullability:
120 Diag(Loc, DL_Error, ET, "%0 null pointer of type %1")
121 << TypeCheckKinds[Data->TypeCheckKind] << Data->Type;
122 break;
123 case ErrorType::MisalignedPointerUse:
124 Diag(Loc, DL_Error, ET, "%0 misaligned address %1 for type %3, "
125 "which requires %2 byte alignment")
126 << TypeCheckKinds[Data->TypeCheckKind] << (void *)Pointer << Alignment
127 << Data->Type;
128 break;
129 case ErrorType::InsufficientObjectSize:
130 Diag(Loc, DL_Error, ET, "%0 address %1 with insufficient space "
131 "for an object of type %2")
132 << TypeCheckKinds[Data->TypeCheckKind] << (void *)Pointer << Data->Type;
133 break;
134 default:
135 UNREACHABLE("unexpected error type!");
136 }
137
138 // Device pointers are not always host-accessible.
139 if (Pointer && !Opts.FromOffload)
140 Diag(Pointer, DL_Note, ET, "pointer points here");
141}
142
143void __ubsan::__ubsan_handle_type_mismatch_v1(TypeMismatchData *Data,
144 ValueHandle Pointer) {
145 GET_REPORT_OPTIONS(false);
146 handleTypeMismatchImpl(Data, Pointer, Opts);
147}
148void __ubsan::__ubsan_handle_type_mismatch_v1_abort(TypeMismatchData *Data,
149 ValueHandle Pointer) {
150 GET_REPORT_OPTIONS(true);
151 handleTypeMismatchImpl(Data, Pointer, Opts);
152 Die();
153}
154
155static void
156emitAlignmentAssumptionReport(Location Loc, SourceLocation AssumptionLoc,
157 const TypeDescriptor &Type, ValueHandle Pointer,
158 ValueHandle Alignment, ValueHandle Offset,
159 ReportOptions Opts) {
160 ErrorType ET = ErrorType::AlignmentAssumption;
161
162 if (ignoreReport(SLoc: Loc.getSourceLocation(), Opts, ET))
163 return;
164
165 ScopedReport R(Opts, Loc, ET);
166
167 uptr RealPointer = Pointer - Offset;
168 uptr LSB = LeastSignificantSetBitIndex(x: RealPointer);
169 uptr ActualAlignment = uptr(1) << LSB;
170
171 uptr Mask = Alignment - 1;
172 uptr MisAlignmentOffset = RealPointer & Mask;
173
174 if (!Offset) {
175 Diag(Loc, DL_Error, ET,
176 "assumption of %0 byte alignment for pointer of type %1 failed")
177 << Alignment << Type;
178 } else {
179 Diag(Loc, DL_Error, ET,
180 "assumption of %0 byte alignment (with offset of %1 byte) for pointer "
181 "of type %2 failed")
182 << Alignment << Offset << Type;
183 }
184
185 if (!AssumptionLoc.isInvalid())
186 Diag(AssumptionLoc, DL_Note, ET, "alignment assumption was specified here");
187
188 Diag(Opts.FromOffload ? Loc : Location(RealPointer), DL_Note, ET,
189 "%0address is %1 aligned, misalignment offset is %2 bytes")
190 << (Offset ? "offset " : "") << ActualAlignment << MisAlignmentOffset;
191}
192
193void __ubsan::handleAlignmentAssumptionImpl(AlignmentAssumptionData *Data,
194 ValueHandle Pointer,
195 ValueHandle Alignment,
196 ValueHandle Offset,
197 ReportOptions Opts) {
198 Location Loc = Data->Loc.acquire();
199 SourceLocation AssumptionLoc = Data->AssumptionLoc.acquire();
200 emitAlignmentAssumptionReport(Loc, AssumptionLoc, Type: Data->Type, Pointer,
201 Alignment, Offset, Opts);
202}
203
204void __ubsan::__ubsan_handle_alignment_assumption(AlignmentAssumptionData *Data,
205 ValueHandle Pointer,
206 ValueHandle Alignment,
207 ValueHandle Offset) {
208 GET_REPORT_OPTIONS(false);
209 handleAlignmentAssumptionImpl(Data, Pointer, Alignment, Offset, Opts);
210}
211void __ubsan::__ubsan_handle_alignment_assumption_abort(
212 AlignmentAssumptionData *Data, ValueHandle Pointer, ValueHandle Alignment,
213 ValueHandle Offset) {
214 GET_REPORT_OPTIONS(true);
215 handleAlignmentAssumptionImpl(Data, Pointer, Alignment, Offset, Opts);
216 Die();
217}
218
219void __ubsan::handleReturnAlignmentAssumptionImpl(
220 ReturnAlignmentAssumptionData *Data, SourceLocation *LocPtr,
221 ValueHandle Pointer, ValueHandle Alignment, ValueHandle Offset,
222 ReportOptions Opts) {
223 if (!LocPtr)
224 UNREACHABLE("source location pointer is null!");
225
226 Location Loc = LocPtr->acquire();
227 emitAlignmentAssumptionReport(Loc, AssumptionLoc: Data->AssumptionLoc, Type: Data->Type, Pointer,
228 Alignment, Offset, Opts);
229}
230
231void __ubsan::__ubsan_handle_return_alignment_assumption(
232 ReturnAlignmentAssumptionData *Data, SourceLocation *LocPtr,
233 ValueHandle Pointer, ValueHandle Alignment, ValueHandle Offset) {
234 GET_REPORT_OPTIONS(false);
235 handleReturnAlignmentAssumptionImpl(Data, LocPtr, Pointer, Alignment, Offset,
236 Opts);
237}
238void __ubsan::__ubsan_handle_return_alignment_assumption_abort(
239 ReturnAlignmentAssumptionData *Data, SourceLocation *LocPtr,
240 ValueHandle Pointer, ValueHandle Alignment, ValueHandle Offset) {
241 GET_REPORT_OPTIONS(true);
242 handleReturnAlignmentAssumptionImpl(Data, LocPtr, Pointer, Alignment, Offset,
243 Opts);
244 Die();
245}
246
247void __ubsan::handleIntegerOverflowImpl(OverflowData *Data, ValueHandle LHS,
248 const char *Operator, ValueHandle RHS,
249 ReportOptions Opts) {
250 SourceLocation Loc = Data->Loc.acquire();
251 bool IsSigned = Data->Type.isSignedIntegerTy();
252 ErrorType ET = IsSigned ? ErrorType::SignedIntegerOverflow
253 : ErrorType::UnsignedIntegerOverflow;
254
255 if (ignoreReport(SLoc: Loc, Opts, ET))
256 return;
257
258 // If this is an unsigned overflow in non-fatal mode, potentially ignore it.
259 if (!IsSigned && !Opts.FromUnrecoverableHandler &&
260 flags()->silence_unsigned_overflow)
261 return;
262
263 ScopedReport R(Opts, Loc, ET);
264
265 Diag(Loc, DL_Error, ET,
266 "%0 integer overflow: "
267 "%1 %2 %3 cannot be represented in type %4")
268 << (IsSigned ? "signed" : "unsigned") << Value(Data->Type, LHS)
269 << Operator << Value(Data->Type, RHS) << Data->Type;
270}
271
272#define UBSAN_OVERFLOW_HANDLER(handler_name, op, unrecoverable) \
273 void __ubsan::handler_name(OverflowData *Data, ValueHandle LHS, \
274 ValueHandle RHS) { \
275 GET_REPORT_OPTIONS(unrecoverable); \
276 handleIntegerOverflowImpl(Data, LHS, op, RHS, Opts); \
277 if (unrecoverable) \
278 Die(); \
279 }
280
281UBSAN_OVERFLOW_HANDLER(__ubsan_handle_add_overflow, "+", false)
282UBSAN_OVERFLOW_HANDLER(__ubsan_handle_add_overflow_abort, "+", true)
283UBSAN_OVERFLOW_HANDLER(__ubsan_handle_sub_overflow, "-", false)
284UBSAN_OVERFLOW_HANDLER(__ubsan_handle_sub_overflow_abort, "-", true)
285UBSAN_OVERFLOW_HANDLER(__ubsan_handle_mul_overflow, "*", false)
286UBSAN_OVERFLOW_HANDLER(__ubsan_handle_mul_overflow_abort, "*", true)
287
288void __ubsan::handleNegateOverflowImpl(OverflowData *Data, ValueHandle OldVal,
289 ReportOptions Opts) {
290 SourceLocation Loc = Data->Loc.acquire();
291 bool IsSigned = Data->Type.isSignedIntegerTy();
292 ErrorType ET = IsSigned ? ErrorType::SignedIntegerOverflow
293 : ErrorType::UnsignedIntegerOverflow;
294
295 if (ignoreReport(SLoc: Loc, Opts, ET))
296 return;
297
298 if (!IsSigned && flags()->silence_unsigned_overflow)
299 return;
300
301 ScopedReport R(Opts, Loc, ET);
302
303 if (IsSigned)
304 Diag(Loc, DL_Error, ET,
305 "negation of %0 cannot be represented in type %1; "
306 "cast to an unsigned type to negate this value to itself")
307 << Value(Data->Type, OldVal) << Data->Type;
308 else
309 Diag(Loc, DL_Error, ET, "negation of %0 cannot be represented in type %1")
310 << Value(Data->Type, OldVal) << Data->Type;
311}
312
313void __ubsan::__ubsan_handle_negate_overflow(OverflowData *Data,
314 ValueHandle OldVal) {
315 GET_REPORT_OPTIONS(false);
316 handleNegateOverflowImpl(Data, OldVal, Opts);
317}
318void __ubsan::__ubsan_handle_negate_overflow_abort(OverflowData *Data,
319 ValueHandle OldVal) {
320 GET_REPORT_OPTIONS(true);
321 handleNegateOverflowImpl(Data, OldVal, Opts);
322 Die();
323}
324
325void __ubsan::handleDivremOverflowImpl(OverflowData *Data, ValueHandle LHS,
326 ValueHandle RHS, ReportOptions Opts) {
327 SourceLocation Loc = Data->Loc.acquire();
328 Value LHSVal(Data->Type, LHS);
329 Value RHSVal(Data->Type, RHS);
330
331 ErrorType ET;
332 if (RHSVal.isMinusOne())
333 ET = ErrorType::SignedIntegerOverflow;
334 else if (Data->Type.isIntegerTy())
335 ET = ErrorType::IntegerDivideByZero;
336 else
337 ET = ErrorType::FloatDivideByZero;
338
339 if (ignoreReport(SLoc: Loc, Opts, ET))
340 return;
341
342 ScopedReport R(Opts, Loc, ET);
343
344 switch (ET) {
345 case ErrorType::SignedIntegerOverflow:
346 Diag(Loc, DL_Error, ET,
347 "division of %0 by -1 cannot be represented in type %1")
348 << LHSVal << Data->Type;
349 break;
350 default:
351 Diag(Loc, DL_Error, ET, "division by zero");
352 break;
353 }
354}
355
356void __ubsan::__ubsan_handle_divrem_overflow(OverflowData *Data,
357 ValueHandle LHS, ValueHandle RHS) {
358 GET_REPORT_OPTIONS(false);
359 handleDivremOverflowImpl(Data, LHS, RHS, Opts);
360}
361void __ubsan::__ubsan_handle_divrem_overflow_abort(OverflowData *Data,
362 ValueHandle LHS,
363 ValueHandle RHS) {
364 GET_REPORT_OPTIONS(true);
365 handleDivremOverflowImpl(Data, LHS, RHS, Opts);
366 Die();
367}
368
369void __ubsan::handleShiftOutOfBoundsImpl(ShiftOutOfBoundsData *Data,
370 ValueHandle LHS, ValueHandle RHS,
371 ReportOptions Opts) {
372 SourceLocation Loc = Data->Loc.acquire();
373 Value LHSVal(Data->LHSType, LHS);
374 Value RHSVal(Data->RHSType, RHS);
375
376 ErrorType ET;
377 if (RHSVal.isNegative() ||
378 RHSVal.getPositiveIntValue() >= Data->LHSType.getIntegerBitWidth())
379 ET = ErrorType::InvalidShiftExponent;
380 else
381 ET = ErrorType::InvalidShiftBase;
382
383 if (ignoreReport(SLoc: Loc, Opts, ET))
384 return;
385
386 ScopedReport R(Opts, Loc, ET);
387
388 if (ET == ErrorType::InvalidShiftExponent) {
389 if (RHSVal.isNegative())
390 Diag(Loc, DL_Error, ET, "shift exponent %0 is negative") << RHSVal;
391 else
392 Diag(Loc, DL_Error, ET,
393 "shift exponent %0 is too large for %1-bit type %2")
394 << RHSVal << Data->LHSType.getIntegerBitWidth() << Data->LHSType;
395 } else {
396 if (LHSVal.isNegative())
397 Diag(Loc, DL_Error, ET, "left shift of negative value %0") << LHSVal;
398 else
399 Diag(Loc, DL_Error, ET,
400 "left shift of %0 by %1 places cannot be represented in type %2")
401 << LHSVal << RHSVal << Data->LHSType;
402 }
403}
404
405void __ubsan::__ubsan_handle_shift_out_of_bounds(ShiftOutOfBoundsData *Data,
406 ValueHandle LHS,
407 ValueHandle RHS) {
408 GET_REPORT_OPTIONS(false);
409 handleShiftOutOfBoundsImpl(Data, LHS, RHS, Opts);
410}
411void __ubsan::__ubsan_handle_shift_out_of_bounds_abort(
412 ShiftOutOfBoundsData *Data,
413 ValueHandle LHS,
414 ValueHandle RHS) {
415 GET_REPORT_OPTIONS(true);
416 handleShiftOutOfBoundsImpl(Data, LHS, RHS, Opts);
417 Die();
418}
419
420void __ubsan::handleOutOfBoundsImpl(OutOfBoundsData *Data, ValueHandle Index,
421 ReportOptions Opts) {
422 SourceLocation Loc = Data->Loc.acquire();
423 ErrorType ET = ErrorType::OutOfBoundsIndex;
424
425 if (ignoreReport(SLoc: Loc, Opts, ET))
426 return;
427
428 ScopedReport R(Opts, Loc, ET);
429
430 Value IndexVal(Data->IndexType, Index);
431 Diag(Loc, DL_Error, ET, "index %0 out of bounds for type %1")
432 << IndexVal << Data->ArrayType;
433}
434
435void __ubsan::__ubsan_handle_out_of_bounds(OutOfBoundsData *Data,
436 ValueHandle Index) {
437 GET_REPORT_OPTIONS(false);
438 handleOutOfBoundsImpl(Data, Index, Opts);
439}
440void __ubsan::__ubsan_handle_out_of_bounds_abort(OutOfBoundsData *Data,
441 ValueHandle Index) {
442 GET_REPORT_OPTIONS(true);
443 handleOutOfBoundsImpl(Data, Index, Opts);
444 Die();
445}
446
447void __ubsan::handleLocalOutOfBoundsImpl(ReportOptions Opts) {
448 // FIXME: Pass more diagnostic info.
449 SymbolizedStackHolder CallerLoc;
450 CallerLoc.reset(S: getReportLocation(PC: Opts.pc, FromOffload: Opts.FromOffload));
451 Location Loc;
452 Loc = CallerLoc;
453 ErrorType ET = ErrorType::LocalOutOfBounds;
454 ScopedReport R(Opts, Loc, ET);
455 Diag(Loc, DL_Error, ET, "access out of bounds");
456}
457
458void __ubsan::__ubsan_handle_local_out_of_bounds() {
459 GET_REPORT_OPTIONS(false);
460 handleLocalOutOfBoundsImpl(Opts);
461}
462
463void __ubsan::__ubsan_handle_local_out_of_bounds_abort() {
464 GET_REPORT_OPTIONS(true);
465 handleLocalOutOfBoundsImpl(Opts);
466 Die();
467}
468
469void __ubsan::handleBuiltinUnreachableImpl(UnreachableData *Data,
470 ReportOptions Opts) {
471 ErrorType ET = ErrorType::UnreachableCall;
472 ScopedReport R(Opts, Data->Loc, ET);
473 Diag(Data->Loc, DL_Error, ET,
474 "execution reached an unreachable program point");
475}
476
477void __ubsan::__ubsan_handle_builtin_unreachable(UnreachableData *Data) {
478 GET_REPORT_OPTIONS(true);
479 handleBuiltinUnreachableImpl(Data, Opts);
480 Die();
481}
482
483void __ubsan::handleMissingReturnImpl(UnreachableData *Data,
484 ReportOptions Opts) {
485 ErrorType ET = ErrorType::MissingReturn;
486 ScopedReport R(Opts, Data->Loc, ET);
487 Diag(Data->Loc, DL_Error, ET,
488 "execution reached the end of a value-returning function "
489 "without returning a value");
490}
491
492void __ubsan::__ubsan_handle_missing_return(UnreachableData *Data) {
493 GET_REPORT_OPTIONS(true);
494 handleMissingReturnImpl(Data, Opts);
495 Die();
496}
497
498void __ubsan::handleVLABoundNotPositive(VLABoundData *Data, ValueHandle Bound,
499 ReportOptions Opts) {
500 SourceLocation Loc = Data->Loc.acquire();
501 ErrorType ET = ErrorType::NonPositiveVLAIndex;
502
503 if (ignoreReport(SLoc: Loc, Opts, ET))
504 return;
505
506 ScopedReport R(Opts, Loc, ET);
507
508 Diag(Loc, DL_Error, ET, "variable length array bound evaluates to "
509 "non-positive value %0")
510 << Value(Data->Type, Bound);
511}
512
513void __ubsan::__ubsan_handle_vla_bound_not_positive(VLABoundData *Data,
514 ValueHandle Bound) {
515 GET_REPORT_OPTIONS(false);
516 handleVLABoundNotPositive(Data, Bound, Opts);
517}
518void __ubsan::__ubsan_handle_vla_bound_not_positive_abort(VLABoundData *Data,
519 ValueHandle Bound) {
520 GET_REPORT_OPTIONS(true);
521 handleVLABoundNotPositive(Data, Bound, Opts);
522 Die();
523}
524
525static bool looksLikeFloatCastOverflowDataV1(void *Data) {
526 // First field is either a pointer to filename or a pointer to a
527 // TypeDescriptor.
528 u8 *FilenameOrTypeDescriptor;
529 internal_memcpy(dest: &FilenameOrTypeDescriptor, src: Data,
530 n: sizeof(FilenameOrTypeDescriptor));
531
532 // Heuristic: For float_cast_overflow, the TypeKind will be either TK_Integer
533 // (0x0), TK_Float (0x1) or TK_Unknown (0xff). If both types are known,
534 // adding both bytes will be 0 or 1 (for BE or LE). If it were a filename,
535 // adding two printable characters will not yield such a value. Otherwise,
536 // if one of them is 0xff, this is most likely TK_Unknown type descriptor.
537 return looksLikeFloatCastOverflowDataV1Bytes(Desc: FilenameOrTypeDescriptor);
538}
539
540void __ubsan::handleFloatCastOverflow(void *DataPtr, ValueHandle From,
541 ReportOptions Opts) {
542 SymbolizedStackHolder CallerLoc;
543 Location Loc;
544 const TypeDescriptor *FromType, *ToType;
545 ErrorType ET = ErrorType::FloatCastOverflow;
546
547 if (looksLikeFloatCastOverflowDataV1(Data: DataPtr)) {
548 auto Data = reinterpret_cast<FloatCastOverflowData *>(DataPtr);
549 CallerLoc.reset(S: getReportLocation(PC: Opts.pc, FromOffload: Opts.FromOffload));
550 Loc = CallerLoc;
551 FromType = &Data->FromType;
552 ToType = &Data->ToType;
553 } else {
554 auto Data = reinterpret_cast<FloatCastOverflowDataV2 *>(DataPtr);
555 SourceLocation SLoc = Data->Loc.acquire();
556 if (ignoreReport(SLoc, Opts, ET))
557 return;
558 Loc = SLoc;
559 FromType = &Data->FromType;
560 ToType = &Data->ToType;
561 }
562
563 ScopedReport R(Opts, Loc, ET);
564
565 Diag(Loc, DL_Error, ET,
566 "%0 is outside the range of representable values of type %2")
567 << Value(*FromType, From) << *FromType << *ToType;
568}
569
570void __ubsan::__ubsan_handle_float_cast_overflow(void *Data, ValueHandle From) {
571 GET_REPORT_OPTIONS(false);
572 handleFloatCastOverflow(DataPtr: Data, From, Opts);
573}
574void __ubsan::__ubsan_handle_float_cast_overflow_abort(void *Data,
575 ValueHandle From) {
576 GET_REPORT_OPTIONS(true);
577 handleFloatCastOverflow(DataPtr: Data, From, Opts);
578 Die();
579}
580
581void __ubsan::handleLoadInvalidValue(InvalidValueData *Data, ValueHandle Val,
582 ReportOptions Opts) {
583 SourceLocation Loc = Data->Loc.acquire();
584 // This check could be more precise if we used different handlers for
585 // -fsanitize=bool and -fsanitize=enum.
586 bool IsBool = (0 == internal_strcmp(s1: Data->Type.getTypeName(), s2: "'bool'")) ||
587 (0 == internal_strncmp(s1: Data->Type.getTypeName(), s2: "'BOOL'", n: 6));
588 ErrorType ET =
589 IsBool ? ErrorType::InvalidBoolLoad : ErrorType::InvalidEnumLoad;
590
591 if (ignoreReport(SLoc: Loc, Opts, ET))
592 return;
593
594 ScopedReport R(Opts, Loc, ET);
595
596 Diag(Loc, DL_Error, ET,
597 "load of value %0, which is not a valid value for type %1")
598 << Value(Data->Type, Val) << Data->Type;
599}
600
601void __ubsan::__ubsan_handle_load_invalid_value(InvalidValueData *Data,
602 ValueHandle Val) {
603 GET_REPORT_OPTIONS(false);
604 handleLoadInvalidValue(Data, Val, Opts);
605}
606void __ubsan::__ubsan_handle_load_invalid_value_abort(InvalidValueData *Data,
607 ValueHandle Val) {
608 GET_REPORT_OPTIONS(true);
609 handleLoadInvalidValue(Data, Val, Opts);
610 Die();
611}
612
613void __ubsan::handleImplicitConversion(ImplicitConversionData *Data,
614 ReportOptions Opts, ValueHandle Src,
615 ValueHandle Dst) {
616 SourceLocation Loc = Data->Loc.acquire();
617 const TypeDescriptor &SrcTy = Data->FromType;
618 const TypeDescriptor &DstTy = Data->ToType;
619 bool SrcSigned = SrcTy.isSignedIntegerTy();
620 bool DstSigned = DstTy.isSignedIntegerTy();
621 ErrorType ET = ErrorType::GenericUB;
622
623 switch (Data->Kind) {
624 case ICCK_IntegerTruncation: { // Legacy, no longer used.
625 // Let's figure out what it should be as per the new types, and upgrade.
626 // If both types are unsigned, then it's an unsigned truncation.
627 // Else, it is a signed truncation.
628 if (!SrcSigned && !DstSigned) {
629 ET = ErrorType::ImplicitUnsignedIntegerTruncation;
630 } else {
631 ET = ErrorType::ImplicitSignedIntegerTruncation;
632 }
633 break;
634 }
635 case ICCK_UnsignedIntegerTruncation:
636 ET = ErrorType::ImplicitUnsignedIntegerTruncation;
637 break;
638 case ICCK_SignedIntegerTruncation:
639 ET = ErrorType::ImplicitSignedIntegerTruncation;
640 break;
641 case ICCK_IntegerSignChange:
642 ET = ErrorType::ImplicitIntegerSignChange;
643 break;
644 case ICCK_SignedIntegerTruncationOrSignChange:
645 ET = ErrorType::ImplicitSignedIntegerTruncationOrSignChange;
646 break;
647 }
648
649 if (ignoreReport(SLoc: Loc, Opts, ET))
650 return;
651
652 ScopedReport R(Opts, Loc, ET);
653
654 // In the case we have a bitfield, we want to explicitly say so in the
655 // error message.
656 // FIXME: is it possible to dump the values as hex with fixed width?
657 if (Data->BitfieldBits)
658 Diag(Loc, DL_Error, ET,
659 "implicit conversion from type %0 of value %1 (%2-bit, %3signed) to "
660 "type %4 changed the value to %5 (%6-bit bitfield, %7signed)")
661 << SrcTy << Value(SrcTy, Src) << SrcTy.getIntegerBitWidth()
662 << (SrcSigned ? "" : "un") << DstTy << Value(DstTy, Dst)
663 << Data->BitfieldBits << (DstSigned ? "" : "un");
664 else
665 Diag(Loc, DL_Error, ET,
666 "implicit conversion from type %0 of value %1 (%2-bit, %3signed) to "
667 "type %4 changed the value to %5 (%6-bit, %7signed)")
668 << SrcTy << Value(SrcTy, Src) << SrcTy.getIntegerBitWidth()
669 << (SrcSigned ? "" : "un") << DstTy << Value(DstTy, Dst)
670 << DstTy.getIntegerBitWidth() << (DstSigned ? "" : "un");
671}
672
673void __ubsan::__ubsan_handle_implicit_conversion(ImplicitConversionData *Data,
674 ValueHandle Src,
675 ValueHandle Dst) {
676 GET_REPORT_OPTIONS(false);
677 handleImplicitConversion(Data, Opts, Src, Dst);
678}
679void __ubsan::__ubsan_handle_implicit_conversion_abort(
680 ImplicitConversionData *Data, ValueHandle Src, ValueHandle Dst) {
681 GET_REPORT_OPTIONS(true);
682 handleImplicitConversion(Data, Opts, Src, Dst);
683 Die();
684}
685
686void __ubsan::handleInvalidBuiltin(InvalidBuiltinData *Data,
687 ReportOptions Opts) {
688 SourceLocation Loc = Data->Loc.acquire();
689 ErrorType ET = ErrorType::InvalidBuiltin;
690
691 if (ignoreReport(SLoc: Loc, Opts, ET))
692 return;
693
694 ScopedReport R(Opts, Loc, ET);
695
696 if (Data->Kind == BCK_AssumePassedFalse)
697 Diag(Loc, DL_Error, ET, "assumption is violated during execution");
698 else if (Data->Kind == BCK_NonUniformLane)
699 Diag(Loc, DL_Error, ET,
700 "lane index passed to __builtin_amdgcn_readlane() is not uniform "
701 "across active lanes");
702 else if (Data->Kind == BCK_InactiveLane)
703 Diag(Loc, DL_Error, ET,
704 "lane index passed to __builtin_amdgcn_wave_shuffle() refers to an "
705 "inactive lane");
706 else
707 Diag(Loc, DL_Error, ET,
708 "passing zero to __builtin_%0(), which is not a valid argument")
709 << ((Data->Kind == BCK_CTZPassedZero) ? "ctz" : "clz");
710}
711
712void __ubsan::__ubsan_handle_invalid_builtin(InvalidBuiltinData *Data) {
713 GET_REPORT_OPTIONS(false);
714 handleInvalidBuiltin(Data, Opts);
715}
716void __ubsan::__ubsan_handle_invalid_builtin_abort(InvalidBuiltinData *Data) {
717 GET_REPORT_OPTIONS(true);
718 handleInvalidBuiltin(Data, Opts);
719 Die();
720}
721
722void __ubsan::handleInvalidObjCCast(InvalidObjCCast *Data, ValueHandle Pointer,
723 ReportOptions Opts) {
724 SourceLocation Loc = Data->Loc.acquire();
725 ErrorType ET = ErrorType::InvalidObjCCast;
726
727 if (ignoreReport(SLoc: Loc, Opts, ET))
728 return;
729
730 ScopedReport R(Opts, Loc, ET);
731
732 const char *GivenClass = getObjCClassName(Pointer);
733 const char *GivenClassStr = GivenClass ? GivenClass : "<unknown type>";
734
735 Diag(Loc, DL_Error, ET,
736 "invalid ObjC cast, object is a '%0', but expected a %1")
737 << GivenClassStr << Data->ExpectedType;
738}
739
740void __ubsan::__ubsan_handle_invalid_objc_cast(InvalidObjCCast *Data,
741 ValueHandle Pointer) {
742 GET_REPORT_OPTIONS(false);
743 handleInvalidObjCCast(Data, Pointer, Opts);
744}
745void __ubsan::__ubsan_handle_invalid_objc_cast_abort(InvalidObjCCast *Data,
746 ValueHandle Pointer) {
747 GET_REPORT_OPTIONS(true);
748 handleInvalidObjCCast(Data, Pointer, Opts);
749 Die();
750}
751
752void __ubsan::handleNonNullReturn(NonNullReturnData *Data,
753 SourceLocation *LocPtr, ReportOptions Opts,
754 bool IsAttr) {
755 if (!LocPtr)
756 UNREACHABLE("source location pointer is null!");
757
758 SourceLocation Loc = LocPtr->acquire();
759 ErrorType ET = IsAttr ? ErrorType::InvalidNullReturn
760 : ErrorType::InvalidNullReturnWithNullability;
761
762 if (ignoreReport(SLoc: Loc, Opts, ET))
763 return;
764
765 ScopedReport R(Opts, Loc, ET);
766
767 Diag(Loc, DL_Error, ET,
768 "null pointer returned from function declared to never return null");
769 if (!Data->AttrLoc.isInvalid())
770 Diag(Data->AttrLoc, DL_Note, ET, "%0 specified here")
771 << (IsAttr ? "returns_nonnull attribute"
772 : "_Nonnull return type annotation");
773}
774
775void __ubsan::__ubsan_handle_nonnull_return_v1(NonNullReturnData *Data,
776 SourceLocation *LocPtr) {
777 GET_REPORT_OPTIONS(false);
778 handleNonNullReturn(Data, LocPtr, Opts, IsAttr: true);
779}
780
781void __ubsan::__ubsan_handle_nonnull_return_v1_abort(NonNullReturnData *Data,
782 SourceLocation *LocPtr) {
783 GET_REPORT_OPTIONS(true);
784 handleNonNullReturn(Data, LocPtr, Opts, IsAttr: true);
785 Die();
786}
787
788void __ubsan::__ubsan_handle_nullability_return_v1(NonNullReturnData *Data,
789 SourceLocation *LocPtr) {
790 GET_REPORT_OPTIONS(false);
791 handleNonNullReturn(Data, LocPtr, Opts, IsAttr: false);
792}
793
794void __ubsan::__ubsan_handle_nullability_return_v1_abort(
795 NonNullReturnData *Data, SourceLocation *LocPtr) {
796 GET_REPORT_OPTIONS(true);
797 handleNonNullReturn(Data, LocPtr, Opts, IsAttr: false);
798 Die();
799}
800
801void __ubsan::handleNonNullArg(NonNullArgData *Data, ReportOptions Opts,
802 bool IsAttr) {
803 SourceLocation Loc = Data->Loc.acquire();
804 ErrorType ET = IsAttr ? ErrorType::InvalidNullArgument
805 : ErrorType::InvalidNullArgumentWithNullability;
806
807 if (ignoreReport(SLoc: Loc, Opts, ET))
808 return;
809
810 ScopedReport R(Opts, Loc, ET);
811
812 Diag(Loc, DL_Error, ET,
813 "null pointer passed as argument %0, which is declared to "
814 "never be null")
815 << Data->ArgIndex;
816 if (!Data->AttrLoc.isInvalid())
817 Diag(Data->AttrLoc, DL_Note, ET, "%0 specified here")
818 << (IsAttr ? "nonnull attribute" : "_Nonnull type annotation");
819}
820
821void __ubsan::__ubsan_handle_nonnull_arg(NonNullArgData *Data) {
822 GET_REPORT_OPTIONS(false);
823 handleNonNullArg(Data, Opts, IsAttr: true);
824}
825
826void __ubsan::__ubsan_handle_nonnull_arg_abort(NonNullArgData *Data) {
827 GET_REPORT_OPTIONS(true);
828 handleNonNullArg(Data, Opts, IsAttr: true);
829 Die();
830}
831
832void __ubsan::__ubsan_handle_nullability_arg(NonNullArgData *Data) {
833 GET_REPORT_OPTIONS(false);
834 handleNonNullArg(Data, Opts, IsAttr: false);
835}
836
837void __ubsan::__ubsan_handle_nullability_arg_abort(NonNullArgData *Data) {
838 GET_REPORT_OPTIONS(true);
839 handleNonNullArg(Data, Opts, IsAttr: false);
840 Die();
841}
842
843void __ubsan::handlePointerOverflowImpl(PointerOverflowData *Data,
844 ValueHandle Base, ValueHandle Result,
845 ReportOptions Opts) {
846 SourceLocation Loc = Data->Loc.acquire();
847 ErrorType ET;
848
849 if (Base == 0 && Result == 0)
850 ET = ErrorType::NullptrWithOffset;
851 else if (Base == 0 && Result != 0)
852 ET = ErrorType::NullptrWithNonZeroOffset;
853 else if (Base != 0 && Result == 0)
854 ET = ErrorType::NullptrAfterNonZeroOffset;
855 else
856 ET = ErrorType::PointerOverflow;
857
858 if (ignoreReport(SLoc: Loc, Opts, ET))
859 return;
860
861 ScopedReport R(Opts, Loc, ET);
862
863 if (ET == ErrorType::NullptrWithOffset) {
864 Diag(Loc, DL_Error, ET, "applying zero offset to null pointer");
865 } else if (ET == ErrorType::NullptrWithNonZeroOffset) {
866 Diag(Loc, DL_Error, ET, "applying non-zero offset %0 to null pointer")
867 << Result;
868 } else if (ET == ErrorType::NullptrAfterNonZeroOffset) {
869 Diag(
870 Loc, DL_Error, ET,
871 "applying non-zero offset to non-null pointer %0 produced null pointer")
872 << (void *)Base;
873 } else if ((sptr(Base) >= 0) == (sptr(Result) >= 0)) {
874 if (Base > Result)
875 Diag(Loc, DL_Error, ET,
876 "addition of unsigned offset to %0 overflowed to %1")
877 << (void *)Base << (void *)Result;
878 else
879 Diag(Loc, DL_Error, ET,
880 "subtraction of unsigned offset from %0 overflowed to %1")
881 << (void *)Base << (void *)Result;
882 } else {
883 Diag(Loc, DL_Error, ET,
884 "pointer index expression with base %0 overflowed to %1")
885 << (void *)Base << (void *)Result;
886 }
887}
888
889void __ubsan::__ubsan_handle_pointer_overflow(PointerOverflowData *Data,
890 ValueHandle Base,
891 ValueHandle Result) {
892 GET_REPORT_OPTIONS(false);
893 handlePointerOverflowImpl(Data, Base, Result, Opts);
894}
895
896void __ubsan::__ubsan_handle_pointer_overflow_abort(PointerOverflowData *Data,
897 ValueHandle Base,
898 ValueHandle Result) {
899 GET_REPORT_OPTIONS(true);
900 handlePointerOverflowImpl(Data, Base, Result, Opts);
901 Die();
902}
903
904// Returns true if this is an artificial debug location created by the
905// LowerTypeTests pass (see createJumpTableDebugInfo in LLVM).
906static bool isArtificialStack(const SymbolizedStack *S) {
907 static constexpr char kSuffix[] = "ubsan_interface.h";
908 if (!S || !S->info.function || !S->info.file)
909 return false;
910 const char *File = S->info.file;
911 uptr FileLen = internal_strlen(s: File);
912 uptr SuffixLen = internal_strlen(s: kSuffix);
913 if (FileLen < SuffixLen)
914 return false;
915 return internal_strcmp(s1: File + FileLen - SuffixLen, s2: kSuffix) == 0;
916}
917
918// Stripping the file name from artificial frames forces the UBSan Diag
919// to fall back to module names. This preserves the original behavior
920// of showing the module, while still allowing the symbolizer
921// to include the helpful (.cfi_jt) function suffix.
922static SymbolizedStack *removeArtificialFiles(SymbolizedStack *FS) {
923 for (SymbolizedStack *S = FS; S; S = S->next) {
924 if (isArtificialStack(S))
925 S->info.file = nullptr;
926 }
927 return FS;
928}
929
930void __ubsan::handleCFIBadIcall(CFICheckFailData *Data, ValueHandle Function,
931 ReportOptions Opts) {
932 ErrorType ET;
933 switch (Data->CheckKind) {
934 case CFITCK_ICall:
935 ET = ErrorType::CFIICall;
936 break;
937 case CFITCK_NVMFCall:
938 ET = ErrorType::CFIMFCall;
939 break;
940 default:
941 Die();
942 }
943
944 SourceLocation Loc = Data->Loc.acquire();
945
946 if (ignoreReport(SLoc: Loc, Opts, ET))
947 return;
948
949 ScopedReport R(Opts, Loc, ET);
950
951 const char *CheckKindStr = Data->CheckKind == CFITCK_NVMFCall
952 ? "non-virtual pointer to member function call"
953 : "indirect function call";
954 Diag(Loc, DL_Error, ET,
955 "control flow integrity check for type %0 failed during %1")
956 << Data->Type << CheckKindStr;
957
958 SymbolizedStackHolder FLoc(
959 removeArtificialFiles(FS: getSymbolizedLocation(PC: Function)));
960
961 const char *FName = FLoc.get()->info.function;
962 if (!FName)
963 FName = "(unknown)";
964 Diag(FLoc, DL_Note, ET, "%0 defined here") << FName;
965
966 // If the failure involved different DSOs for the check location and icall
967 // target, report the DSO names.
968 const char *DstModule = FLoc.get()->info.module;
969 if (!DstModule)
970 DstModule = "(unknown)";
971
972 const char *SrcModule = Symbolizer::GetOrInit()->GetModuleNameForPc(pc: Opts.pc);
973 if (!SrcModule)
974 SrcModule = "(unknown)";
975
976 if (internal_strcmp(s1: SrcModule, s2: DstModule))
977 Diag(Loc, DL_Note, ET,
978 "check failed in %0, destination function located in %1")
979 << SrcModule << DstModule;
980}
981
982namespace __ubsan {
983
984#if defined(_WIN32) && (!defined(__GNUC__) || defined(__clang__))
985extern "C" void __ubsan_handle_cfi_bad_type_default(CFICheckFailData *Data,
986 ValueHandle Vtable,
987 bool ValidVtable,
988 ReportOptions Opts) {
989 Die();
990}
991
992WIN_WEAK_ALIAS(__ubsan_handle_cfi_bad_type, __ubsan_handle_cfi_bad_type_default)
993void __ubsan_handle_cfi_bad_type(CFICheckFailData *Data, ValueHandle Vtable,
994 bool ValidVtable, ReportOptions Opts);
995#elif defined(_WIN32)
996// GNU ld does not support /alternatename. The real implementation lives in
997// ubsan_handlers_cxx.cpp.
998void __ubsan_handle_cfi_bad_type(CFICheckFailData *Data, ValueHandle Vtable,
999 bool ValidVtable, ReportOptions Opts);
1000#else
1001SANITIZER_WEAK_ATTRIBUTE
1002void __ubsan_handle_cfi_bad_type(CFICheckFailData *Data, ValueHandle Vtable,
1003 bool ValidVtable, ReportOptions Opts) {
1004 Die();
1005}
1006#endif
1007
1008} // namespace __ubsan
1009
1010void __ubsan::__ubsan_handle_cfi_check_fail(CFICheckFailData *Data,
1011 ValueHandle Value,
1012 uptr ValidVtable) {
1013 GET_REPORT_OPTIONS(false);
1014 if (Data->CheckKind == CFITCK_ICall || Data->CheckKind == CFITCK_NVMFCall)
1015 handleCFIBadIcall(Data, Function: Value, Opts);
1016 else
1017 __ubsan_handle_cfi_bad_type(Data, Vtable: Value, ValidVtable, Opts);
1018}
1019
1020void __ubsan::__ubsan_handle_cfi_check_fail_abort(CFICheckFailData *Data,
1021 ValueHandle Value,
1022 uptr ValidVtable) {
1023 GET_REPORT_OPTIONS(true);
1024 if (Data->CheckKind == CFITCK_ICall || Data->CheckKind == CFITCK_NVMFCall)
1025 handleCFIBadIcall(Data, Function: Value, Opts);
1026 else
1027 __ubsan_handle_cfi_bad_type(Data, Vtable: Value, ValidVtable, Opts);
1028 Die();
1029}
1030
1031bool __ubsan::handleFunctionTypeMismatch(FunctionTypeMismatchData *Data,
1032 ValueHandle Function,
1033 ReportOptions Opts) {
1034 SourceLocation CallLoc = Data->Loc.acquire();
1035 ErrorType ET = ErrorType::FunctionTypeMismatch;
1036 if (ignoreReport(SLoc: CallLoc, Opts, ET))
1037 return true;
1038
1039 ScopedReport R(Opts, CallLoc, ET);
1040
1041 SymbolizedStackHolder FLoc(getSymbolizedLocation(PC: Function));
1042 const char *FName = FLoc.get()->info.function;
1043 if (!FName)
1044 FName = "(unknown)";
1045
1046 Diag(CallLoc, DL_Error, ET,
1047 "call to function %0 through pointer to incorrect function type %1")
1048 << FName << Data->Type;
1049 Diag(FLoc, DL_Note, ET, "%0 defined here") << FName;
1050 return true;
1051}
1052
1053void __ubsan::__ubsan_handle_function_type_mismatch(
1054 FunctionTypeMismatchData *Data, ValueHandle Function) {
1055 GET_REPORT_OPTIONS(false);
1056 handleFunctionTypeMismatch(Data, Function, Opts);
1057}
1058
1059void __ubsan::__ubsan_handle_function_type_mismatch_abort(
1060 FunctionTypeMismatchData *Data, ValueHandle Function) {
1061 GET_REPORT_OPTIONS(true);
1062 if (handleFunctionTypeMismatch(Data, Function, Opts))
1063 Die();
1064}
1065
1066#endif // CAN_SANITIZE_UB
1067