Skip to content

Commit 0404ec8

Browse files
committed
ubsan: Runtime handlers for array indexing checks.
llvm-svn: 175948
1 parent e9ca4af commit 0404ec8

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// RUN: %clang -fsanitize=bounds %s -O3 -o %T/bounds.exe
2+
// RUN: %T/bounds.exe 0 0 0
3+
// RUN: %T/bounds.exe 1 2 3
4+
// RUN: %T/bounds.exe 2 0 0 2>&1 | FileCheck %s --check-prefix=CHECK-A-2
5+
// RUN: %T/bounds.exe 0 3 0 2>&1 | FileCheck %s --check-prefix=CHECK-B-3
6+
// RUN: %T/bounds.exe 0 0 4 2>&1 | FileCheck %s --check-prefix=CHECK-C-4
7+
8+
int main(int argc, char **argv) {
9+
int arr[2][3][4] = {};
10+
11+
return arr[argv[1][0] - '0'][argv[2][0] - '0'][argv[3][0] - '0'];
12+
// CHECK-A-2: bounds.cpp:11:10: runtime error: index 2 out of bounds for type 'int [2][3][4]'
13+
// CHECK-B-3: bounds.cpp:11:10: runtime error: index 3 out of bounds for type 'int [3][4]'
14+
// CHECK-C-4: bounds.cpp:11:10: runtime error: index 4 out of bounds for type 'int [4]'
15+
}

compiler-rt/lib/ubsan/ubsan_handlers.cc

+16
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,22 @@ void __ubsan::__ubsan_handle_shift_out_of_bounds_abort(
183183
Die();
184184
}
185185

186+
void __ubsan::__ubsan_handle_out_of_bounds(OutOfBoundsData *Data,
187+
ValueHandle Index) {
188+
SourceLocation Loc = Data->Loc.acquire();
189+
if (Loc.isDisabled())
190+
return;
191+
192+
Value IndexVal(Data->IndexType, Index);
193+
Diag(Loc, DL_Error, "index %0 out of bounds for type %1")
194+
<< IndexVal << Data->ArrayType;
195+
}
196+
void __ubsan::__ubsan_handle_out_of_bounds_abort(OutOfBoundsData *Data,
197+
ValueHandle Index) {
198+
__ubsan_handle_out_of_bounds(Data, Index);
199+
Die();
200+
}
201+
186202
void __ubsan::__ubsan_handle_builtin_unreachable(UnreachableData *Data) {
187203
Diag(Data->Loc, DL_Error, "execution reached a __builtin_unreachable() call");
188204
Die();

compiler-rt/lib/ubsan/ubsan_handlers.h

+9
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ struct ShiftOutOfBoundsData {
6767
RECOVERABLE(shift_out_of_bounds, ShiftOutOfBoundsData *Data,
6868
ValueHandle LHS, ValueHandle RHS)
6969

70+
struct OutOfBoundsData {
71+
SourceLocation Loc;
72+
const TypeDescriptor &ArrayType;
73+
const TypeDescriptor &IndexType;
74+
};
75+
76+
/// \brief Handle an array index out of bounds error.
77+
RECOVERABLE(out_of_bounds, OutOfBoundsData *Data, ValueHandle Index)
78+
7079
struct UnreachableData {
7180
SourceLocation Loc;
7281
};

0 commit comments

Comments
 (0)