Skip to content

Commit 539e4a7

Browse files
committed
ubsan: Emit bounds checks for array indexing, vector indexing, and (in really simple cases) pointer arithmetic. This augments the existing bounds checking with language-level array bounds information.
llvm-svn: 175949
1 parent 0404ec8 commit 539e4a7

File tree

7 files changed

+207
-17
lines changed

7 files changed

+207
-17
lines changed

clang/lib/CodeGen/CGExpr.cpp

+94-3
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,83 @@ void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
630630
}
631631
}
632632

633+
/// Determine whether this expression refers to a flexible array member in a
634+
/// struct. We disable array bounds checks for such members.
635+
static bool isFlexibleArrayMemberExpr(const Expr *E) {
636+
// For compatibility with existing code, we treat arrays of length 0 or
637+
// 1 as flexible array members.
638+
const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
639+
if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
640+
if (CAT->getSize().ugt(1))
641+
return false;
642+
} else if (!isa<IncompleteArrayType>(AT))
643+
return false;
644+
645+
E = E->IgnoreParens();
646+
647+
// A flexible array member must be the last member in the class.
648+
if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
649+
// FIXME: If the base type of the member expr is not FD->getParent(),
650+
// this should not be treated as a flexible array member access.
651+
if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
652+
RecordDecl::field_iterator FI(
653+
DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
654+
return ++FI == FD->getParent()->field_end();
655+
}
656+
}
657+
658+
return false;
659+
}
660+
661+
/// If Base is known to point to the start of an array, return the length of
662+
/// that array. Return 0 if the length cannot be determined.
663+
llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base,
664+
QualType &IndexedType) {
665+
// For the vector indexing extension, the bound is the number of elements.
666+
if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
667+
IndexedType = Base->getType();
668+
return CGF.Builder.getInt32(VT->getNumElements());
669+
}
670+
671+
Base = Base->IgnoreParens();
672+
673+
if (const CastExpr *CE = dyn_cast<CastExpr>(Base)) {
674+
if (CE->getCastKind() == CK_ArrayToPointerDecay &&
675+
!isFlexibleArrayMemberExpr(CE->getSubExpr())) {
676+
IndexedType = CE->getSubExpr()->getType();
677+
const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
678+
if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
679+
return CGF.Builder.getInt(CAT->getSize());
680+
else if (const VariableArrayType *VAT = cast<VariableArrayType>(AT))
681+
return CGF.getVLASize(VAT).first;
682+
}
683+
}
684+
685+
return 0;
686+
}
687+
688+
void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
689+
llvm::Value *Index, QualType IndexType,
690+
bool Accessed) {
691+
QualType IndexedType;
692+
llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
693+
if (!Bound)
694+
return;
695+
696+
bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
697+
llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
698+
llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
699+
700+
llvm::Constant *StaticData[] = {
701+
EmitCheckSourceLocation(E->getExprLoc()),
702+
EmitCheckTypeDescriptor(IndexedType),
703+
EmitCheckTypeDescriptor(IndexType)
704+
};
705+
llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
706+
: Builder.CreateICmpULE(IndexVal, BoundVal);
707+
EmitCheck(Check, "out_of_bounds", StaticData, Index, CRK_Recoverable);
708+
}
709+
633710

634711
CodeGenFunction::ComplexPairTy CodeGenFunction::
635712
EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
@@ -705,7 +782,11 @@ LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
705782
}
706783

707784
LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
708-
LValue LV = EmitLValue(E);
785+
LValue LV;
786+
if (SanOpts->Bounds && isa<ArraySubscriptExpr>(E))
787+
LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
788+
else
789+
LV = EmitLValue(E);
709790
if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
710791
EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
711792
E->getType(), LV.getAlignment());
@@ -2121,12 +2202,16 @@ static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
21212202
return SubExpr;
21222203
}
21232204

2124-
LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2205+
LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2206+
bool Accessed) {
21252207
// The index must always be an integer, which is not an aggregate. Emit it.
21262208
llvm::Value *Idx = EmitScalarExpr(E->getIdx());
21272209
QualType IdxTy = E->getIdx()->getType();
21282210
bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
21292211

2212+
if (SanOpts->Bounds)
2213+
EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2214+
21302215
// If the base is a vector type, then we are forming a vector element lvalue
21312216
// with this subscript.
21322217
if (E->getBase()->getType()->isVectorType()) {
@@ -2187,7 +2272,13 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
21872272
// "gep x, i" here. Emit one "gep A, 0, i".
21882273
assert(Array->getType()->isArrayType() &&
21892274
"Array to pointer decay must have array source type!");
2190-
LValue ArrayLV = EmitLValue(Array);
2275+
LValue ArrayLV;
2276+
// For simple multidimensional array indexing, set the 'accessed' flag for
2277+
// better bounds-checking of the base expression.
2278+
if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Array))
2279+
ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2280+
else
2281+
ArrayLV = EmitLValue(Array);
21912282
llvm::Value *ArrayPtr = ArrayLV.getAddress();
21922283
llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
21932284
llvm::Value *Args[] = { Zero, Idx };

clang/lib/CodeGen/CGExprScalar.cpp

+10-1
Original file line numberDiff line numberDiff line change
@@ -986,7 +986,12 @@ Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
986986
// integer value.
987987
Value *Base = Visit(E->getBase());
988988
Value *Idx = Visit(E->getIdx());
989-
bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
989+
QualType IdxTy = E->getIdx()->getType();
990+
991+
if (CGF.SanOpts->Bounds)
992+
CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
993+
994+
bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
990995
Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
991996
return Builder.CreateExtractElement(Base, Idx, "vecext");
992997
}
@@ -2134,6 +2139,10 @@ static Value *emitPointerArithmetic(CodeGenFunction &CGF,
21342139
if (isSubtraction)
21352140
index = CGF.Builder.CreateNeg(index, "idx.neg");
21362141

2142+
if (CGF.SanOpts->Bounds)
2143+
CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2144+
/*Accessed*/ false);
2145+
21372146
const PointerType *pointerType
21382147
= pointerOperand->getType()->getAs<PointerType>();
21392148
if (!pointerType) {

clang/lib/CodeGen/CodeGenFunction.h

+8-1
Original file line numberDiff line numberDiff line change
@@ -1910,6 +1910,12 @@ class CodeGenFunction : public CodeGenTypeCache {
19101910
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
19111911
QualType Type, CharUnits Alignment = CharUnits::Zero());
19121912

1913+
/// \brief Emit a check that \p Base points into an array object, which
1914+
/// we can access at index \p Index. \p Accessed should be \c false if we
1915+
/// this expression is used as an lvalue, for instance in "&Arr[Idx]".
1916+
void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
1917+
QualType IndexType, bool Accessed);
1918+
19131919
llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
19141920
bool isInc, bool isPre);
19151921
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
@@ -2187,7 +2193,8 @@ class CodeGenFunction : public CodeGenTypeCache {
21872193
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
21882194
LValue EmitPredefinedLValue(const PredefinedExpr *E);
21892195
LValue EmitUnaryOpLValue(const UnaryOperator *E);
2190-
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
2196+
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2197+
bool Accessed = false);
21912198
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
21922199
LValue EmitMemberExpr(const MemberExpr *E);
21932200
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);

clang/lib/Driver/SanitizerArgs.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ class SanitizerArgs {
3737
NeedsAsanRt = Address,
3838
NeedsTsanRt = Thread,
3939
NeedsMsanRt = Memory,
40-
NeedsUbsanRt = (Undefined & ~Bounds) | Integer,
40+
NeedsUbsanRt = Undefined | Integer,
4141
NotAllowedWithTrap = Vptr
4242
};
4343
unsigned Kind;

clang/test/CodeGenCXX/catch-undef-behavior.cpp

+90-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// RUN: %clang_cc1 -fsanitize=signed-integer-overflow,integer-divide-by-zero,float-divide-by-zero,shift,unreachable,return,vla-bound,alignment,null,vptr,object-size,float-cast-overflow,bool,enum -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
1+
// RUN: %clang_cc1 -fsanitize=signed-integer-overflow,integer-divide-by-zero,float-divide-by-zero,shift,unreachable,return,vla-bound,alignment,null,vptr,object-size,float-cast-overflow,bool,enum,bounds -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
22

33
struct S {
44
double d;
@@ -220,4 +220,93 @@ void bad_downcast_reference(S &p) {
220220
(void) static_cast<T&>(p);
221221
}
222222

223+
// CHECK: @_Z11array_index
224+
int array_index(const int (&a)[4], int n) {
225+
// CHECK: %[[K1_OK:.*]] = icmp ult i64 %{{.*}}, 4
226+
// CHECK: br i1 %[[K1_OK]]
227+
// CHECK: call void @__ubsan_handle_out_of_bounds(
228+
int k1 = a[n];
229+
230+
// CHECK: %[[R1_OK:.*]] = icmp ule i64 %{{.*}}, 4
231+
// CHECK: br i1 %[[R1_OK]]
232+
// CHECK: call void @__ubsan_handle_out_of_bounds(
233+
const int *r1 = &a[n];
234+
235+
// CHECK: %[[K2_OK:.*]] = icmp ult i64 %{{.*}}, 8
236+
// CHECK: br i1 %[[K2_OK]]
237+
// CHECK: call void @__ubsan_handle_out_of_bounds(
238+
int k2 = ((const int(&)[8])a)[n];
239+
240+
// CHECK: %[[K3_OK:.*]] = icmp ult i64 %{{.*}}, 4
241+
// CHECK: br i1 %[[K3_OK]]
242+
// CHECK: call void @__ubsan_handle_out_of_bounds(
243+
int k3 = n[a];
244+
245+
return k1 + *r1 + k2;
246+
}
247+
248+
// CHECK: @_Z17multi_array_index
249+
int multi_array_index(int n, int m) {
250+
int arr[4][6];
251+
252+
// CHECK: %[[IDX2_OK:.*]] = icmp ult i64 %{{.*}}, 6
253+
// CHECK: br i1 %[[IDX2_OK]]
254+
// CHECK: call void @__ubsan_handle_out_of_bounds(
255+
256+
// CHECK: %[[IDX1_OK:.*]] = icmp ult i64 %{{.*}}, 4
257+
// CHECK: br i1 %[[IDX1_OK]]
258+
// CHECK: call void @__ubsan_handle_out_of_bounds(
259+
return arr[n][m];
260+
}
261+
262+
// CHECK: @_Z11array_arith
263+
int array_arith(const int (&a)[4], int n) {
264+
// CHECK: %[[K1_OK:.*]] = icmp ule i64 %{{.*}}, 4
265+
// CHECK: br i1 %[[K1_OK]]
266+
// CHECK: call void @__ubsan_handle_out_of_bounds(
267+
const int *k1 = a + n;
268+
269+
// CHECK: %[[K2_OK:.*]] = icmp ule i64 %{{.*}}, 8
270+
// CHECK: br i1 %[[K2_OK]]
271+
// CHECK: call void @__ubsan_handle_out_of_bounds(
272+
const int *k2 = (const int(&)[8])a + n;
273+
274+
return *k1 + *k2;
275+
}
276+
277+
struct ArrayMembers {
278+
int a1[5];
279+
int a2[1];
280+
};
281+
// CHECK: @_Z18struct_array_index
282+
int struct_array_index(ArrayMembers *p, int n) {
283+
// CHECK: %[[IDX_OK:.*]] = icmp ult i64 %{{.*}}, 5
284+
// CHECK: br i1 %[[IDX_OK]]
285+
// CHECK: call void @__ubsan_handle_out_of_bounds(
286+
return p->a1[n];
287+
}
288+
289+
// CHECK: @_Z16flex_array_index
290+
int flex_array_index(ArrayMembers *p, int n) {
291+
// CHECK-NOT: call void @__ubsan_handle_out_of_bounds(
292+
return p->a2[n];
293+
}
294+
295+
typedef __attribute__((ext_vector_type(4))) int V4I;
296+
// CHECK: @_Z12vector_index
297+
int vector_index(V4I v, int n) {
298+
// CHECK: %[[IDX_OK:.*]] = icmp ult i64 %{{.*}}, 4
299+
// CHECK: br i1 %[[IDX_OK]]
300+
// CHECK: call void @__ubsan_handle_out_of_bounds(
301+
return v[n];
302+
}
303+
304+
// CHECK: @_Z12string_index
305+
char string_index(int n) {
306+
// CHECK: %[[IDX_OK:.*]] = icmp ult i64 %{{.*}}, 6
307+
// CHECK: br i1 %[[IDX_OK]]
308+
// CHECK: call void @__ubsan_handle_out_of_bounds(
309+
return "Hello"[n];
310+
}
311+
223312
// CHECK: attributes [[NR_NUW]] = { noreturn nounwind }

clang/test/Driver/darwin-sanitizer-ld.c

+4-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828
// CHECK-UBSAN: stdc++
2929

3030
// RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \
31-
// RUN: -fsanitize=bounds %s -o %t.o 2>&1 \
31+
// RUN: -fsanitize=bounds -fsanitize-undefined-trap-on-error \
32+
// RUN: %s -o %t.o 2>&1 \
3233
// RUN: | FileCheck --check-prefix=CHECK-BOUNDS %s
3334

3435
// CHECK-BOUNDS: "{{.*}}ld{{(.exe)?}}"
@@ -43,7 +44,8 @@
4344
// CHECK-DYN-UBSAN: libclang_rt.ubsan_osx.a
4445

4546
// RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \
46-
// RUN: -fPIC -shared -fsanitize=bounds %s -o %t.so 2>&1 \
47+
// RUN: -fsanitize=bounds -fsanitize-undefined-trap-on-error \
48+
// RUN: %s -o %t.so -fPIC -shared 2>&1 \
4749
// RUN: | FileCheck --check-prefix=CHECK-DYN-BOUNDS %s
4850

4951
// CHECK-DYN-BOUNDS: "{{.*}}ld{{(.exe)?}}"

clang/test/Driver/ubsan-ld.c

-8
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,3 @@
1818
// CHECK-LINUX-SHARED-NOT: "-lc"
1919
// CHECK-LINUX-SHARED: libclang_rt.ubsan-i386.a"
2020
// CHECK-LINUX-SHARED: "-lpthread"
21-
22-
// RUN: %clang -fsanitize=bounds %s -### -o %t.o 2>&1 \
23-
// RUN: -target i386-unknown-linux \
24-
// RUN: --sysroot=%S/Inputs/basic_linux_tree \
25-
// RUN: | FileCheck --check-prefix=CHECK-LINUX1 %s
26-
// CHECK-LINUX1: "{{.*}}ld{{(.exe)?}}"
27-
// CHECK-LINUX1-NOT: libclang_rt.ubsan-i386.a"
28-
// CHECK-LINUX1-NOT: "-lpthread"

0 commit comments

Comments
 (0)