Skip to content

Commit 3ad2fe9

Browse files
committed
[Clang][CodeGen] Avoid __builtin_assume_aligned crash when the 1st arg is array type
Avoid __builtin_assume_aligned crash when the 1st arg is array type(or string literal). Open issue: llvm/llvm-project#57169 Reviewed By: rjmccall Differential Revision: https://reviews.llvm.org/D133202
1 parent 5aee272 commit 3ad2fe9

File tree

7 files changed

+103
-17
lines changed

7 files changed

+103
-17
lines changed

clang/include/clang/Basic/Builtins.def

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,7 @@ BUILTIN(__builtin_va_start, "vA.", "nt")
546546
BUILTIN(__builtin_va_end, "vA", "n")
547547
BUILTIN(__builtin_va_copy, "vAA", "n")
548548
BUILTIN(__builtin_stdarg_start, "vA.", "nt")
549-
BUILTIN(__builtin_assume_aligned, "v*vC*z.", "nc")
549+
BUILTIN(__builtin_assume_aligned, "v*vC*z.", "nct")
550550
BUILTIN(__builtin_bcmp, "ivC*vC*z", "Fn")
551551
BUILTIN(__builtin_bcopy, "vv*v*z", "n")
552552
BUILTIN(__builtin_bzero, "vv*z", "nF")

clang/lib/CodeGen/CGBuiltin.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2781,6 +2781,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
27812781
case Builtin::BI__builtin_assume_aligned: {
27822782
const Expr *Ptr = E->getArg(0);
27832783
Value *PtrValue = EmitScalarExpr(Ptr);
2784+
if (PtrValue->getType() != VoidPtrTy)
2785+
PtrValue = EmitCastToVoidPtr(PtrValue);
27842786
Value *OffsetValue =
27852787
(E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
27862788

clang/lib/CodeGen/CodeGenFunction.cpp

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2443,8 +2443,6 @@ void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
24432443
SourceLocation AssumptionLoc,
24442444
llvm::Value *Alignment,
24452445
llvm::Value *OffsetValue) {
2446-
if (auto *CE = dyn_cast<CastExpr>(E))
2447-
E = CE->getSubExprAsWritten();
24482446
QualType Ty = E->getType();
24492447
SourceLocation Loc = E->getExprLoc();
24502448

clang/lib/Sema/SemaChecking.cpp

Lines changed: 57 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,28 @@ static bool checkArgCountAtLeast(Sema &S, CallExpr *Call,
128128
<< Call->getSourceRange();
129129
}
130130

131+
/// Checks that a call expression's argument count is at most the desired
132+
/// number. This is useful when doing custom type-checking on a variadic
133+
/// function. Returns true on error.
134+
static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount) {
135+
unsigned ArgCount = Call->getNumArgs();
136+
if (ArgCount <= MaxArgCount)
137+
return false;
138+
return S.Diag(Call->getEndLoc(),
139+
diag::err_typecheck_call_too_many_args_at_most)
140+
<< 0 /*function call*/ << MaxArgCount << ArgCount
141+
<< Call->getSourceRange();
142+
}
143+
144+
/// Checks that a call expression's argument count is in the desired range. This
145+
/// is useful when doing custom type-checking on a variadic function. Returns
146+
/// true on error.
147+
static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount,
148+
unsigned MaxArgCount) {
149+
return checkArgCountAtLeast(S, Call, MinArgCount) ||
150+
checkArgCountAtMost(S, Call, MaxArgCount);
151+
}
152+
131153
/// Checks that a call expression's argument count is the desired number.
132154
/// This is useful when doing custom type-checking. Returns true on error.
133155
static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
@@ -148,6 +170,20 @@ static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
148170
<< Call->getArg(1)->getSourceRange();
149171
}
150172

173+
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
174+
if (Value->isTypeDependent())
175+
return false;
176+
177+
InitializedEntity Entity =
178+
InitializedEntity::InitializeParameter(S.Context, Ty, false);
179+
ExprResult Result =
180+
S.PerformCopyInitialization(Entity, SourceLocation(), Value);
181+
if (Result.isInvalid())
182+
return true;
183+
Value = Result.get();
184+
return false;
185+
}
186+
151187
/// Check that the first argument to __builtin_annotation is an integer
152188
/// and the second argument is a non-wide string literal.
153189
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
@@ -7644,38 +7680,45 @@ bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
76447680
/// Handle __builtin_assume_aligned. This is declared
76457681
/// as (const void*, size_t, ...) and can take one optional constant int arg.
76467682
bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7683+
if (checkArgCountRange(*this, TheCall, 2, 3))
7684+
return true;
7685+
76477686
unsigned NumArgs = TheCall->getNumArgs();
7687+
Expr *FirstArg = TheCall->getArg(0);
76487688

7649-
if (NumArgs > 3)
7650-
return Diag(TheCall->getEndLoc(),
7651-
diag::err_typecheck_call_too_many_args_at_most)
7652-
<< 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7689+
{
7690+
ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
7691+
if (FirstArgResult.isInvalid())
7692+
return true;
7693+
TheCall->setArg(0, FirstArgResult.get());
7694+
}
76537695

76547696
// The alignment must be a constant integer.
7655-
Expr *Arg = TheCall->getArg(1);
7697+
Expr *SecondArg = TheCall->getArg(1);
7698+
if (convertArgumentToType(*this, SecondArg, Context.getSizeType()))
7699+
return true;
7700+
TheCall->setArg(1, SecondArg);
76567701

76577702
// We can't check the value of a dependent argument.
7658-
if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7703+
if (!SecondArg->isValueDependent()) {
76597704
llvm::APSInt Result;
76607705
if (SemaBuiltinConstantArg(TheCall, 1, Result))
76617706
return true;
76627707

76637708
if (!Result.isPowerOf2())
76647709
return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7665-
<< Arg->getSourceRange();
7710+
<< SecondArg->getSourceRange();
76667711

76677712
if (Result > Sema::MaximumAlignment)
76687713
Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7669-
<< Arg->getSourceRange() << Sema::MaximumAlignment;
7714+
<< SecondArg->getSourceRange() << Sema::MaximumAlignment;
76707715
}
76717716

76727717
if (NumArgs > 2) {
7673-
ExprResult Arg(TheCall->getArg(2));
7674-
InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7675-
Context.getSizeType(), false);
7676-
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7677-
if (Arg.isInvalid()) return true;
7678-
TheCall->setArg(2, Arg.get());
7718+
Expr *ThirdArg = TheCall->getArg(2);
7719+
if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
7720+
return true;
7721+
TheCall->setArg(2, ThirdArg);
76797722
}
76807723

76817724
return false;
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// RUN: %clang_cc1 -no-opaque-pointers -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
2+
// RUN: %clang_cc1 -no-opaque-pointers -fsanitize=alignment -fno-sanitize-recover=alignment -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s -implicit-check-not="call void @__ubsan_handle_alignment_assumption" --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER,CHECK-SANITIZE-UNREACHABLE
3+
// RUN: %clang_cc1 -no-opaque-pointers -fsanitize=alignment -fsanitize-recover=alignment -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s -implicit-check-not="call void @__ubsan_handle_alignment_assumption" --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER
4+
// RUN: %clang_cc1 -no-opaque-pointers -fsanitize=alignment -fsanitize-trap=alignment -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s -implicit-check-not="call void @__ubsan_handle_alignment_assumption" --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP,CHECK-SANITIZE-UNREACHABLE
5+
6+
// CHECK-SANITIZE-ANYRECOVER: @[[CHAR:.*]] = {{.*}} c"'char *'\00" }
7+
// CHECK-SANITIZE-ANYRECOVER: @[[ALIGNMENT_ASSUMPTION:.*]] = {{.*}}, i32 31, i32 35 }, {{.*}}* @[[CHAR]] }
8+
9+
void *caller(void) {
10+
char str[] = "";
11+
// CHECK: define{{.*}}
12+
// CHECK-NEXT: entry:
13+
// CHECK-NEXT: %[[STR:.*]] = alloca [1 x i8], align 1
14+
// CHECK-NEXT: %[[BITCAST:.*]] = bitcast [1 x i8]* %[[STR]] to i8*
15+
// CHECK-NEXT: call void @llvm.memset.p0i8.i64(i8* align 1 %[[BITCAST]], i8 0, i64 1, i1 false)
16+
// CHECK-NEXT: %[[ARRAYDECAY:.*]] = getelementptr inbounds [1 x i8], [1 x i8]* %[[STR]], i64 0, i64 0
17+
// CHECK-SANITIZE-NEXT: %[[PTRINT:.*]] = ptrtoint i8* %[[ARRAYDECAY]] to i64
18+
// CHECK-SANITIZE-NEXT: %[[MASKEDPTR:.*]] = and i64 %[[PTRINT]], 0
19+
// CHECK-SANITIZE-NEXT: %[[MASKCOND:.*]] = icmp eq i64 %[[MASKEDPTR]], 0
20+
// CHECK-SANITIZE-NEXT: %[[PTRINT_DUP:.*]] = ptrtoint i8* %[[ARRAYDECAY]] to i64, !nosanitize
21+
// CHECK-SANITIZE-NEXT: br i1 %[[MASKCOND]], label %[[CONT:.*]], label %[[HANDLER_ALIGNMENT_ASSUMPTION:[^,]+]],{{.*}} !nosanitize
22+
// CHECK-SANITIZE: [[HANDLER_ALIGNMENT_ASSUMPTION]]:
23+
// CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_alignment_assumption_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}, {{{.*}}}* }* @[[ALIGNMENT_ASSUMPTION]] to i8*), i64 %[[PTRINT_DUP]], i64 1, i64 0){{.*}}, !nosanitize
24+
// CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_alignment_assumption(i8* bitcast ({ {{{.*}}}, {{{.*}}}, {{{.*}}}* }* @[[ALIGNMENT_ASSUMPTION]] to i8*), i64 %[[PTRINT_DUP]], i64 1, i64 0){{.*}}, !nosanitize
25+
// CHECK-SANITIZE-TRAP-NEXT: call void @llvm.ubsantrap(i8 23){{.*}}, !nosanitize
26+
// CHECK-SANITIZE-UNREACHABLE-NEXT: unreachable, !nosanitize
27+
// CHECK-SANITIZE: [[CONT]]:
28+
// CHECK-NEXT: call void @llvm.assume(i1 true) [ "align"(i8* %[[ARRAYDECAY]], i64 1) ]
29+
// CHECK-NEXT: ret i8* %[[ARRAYDECAY]]
30+
// CHECK-NEXT: }
31+
return __builtin_assume_aligned(str, 1);
32+
}

clang/test/CodeGen/catch-alignment-assumption-ignorelist.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,9 @@ void *dont_ignore_volatile_ptrs(void * volatile x) {
2626
void *ignore_volatiles(volatile void * x) {
2727
return __builtin_assume_aligned(x, 1);
2828
}
29+
30+
// CHECK-LABEL: ignore_array_volatiles
31+
void *ignore_array_volatiles() {
32+
volatile int arr[] = {1};
33+
return __builtin_assume_aligned(arr, 4);
34+
}

clang/test/Sema/builtin-assume-aligned.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ int test12(int *a) {
6666
}
6767
#endif
6868

69+
int test13(int *a) {
70+
a = (int *)__builtin_assume_aligned(a, 2 * 2.0); // expected-error {{argument to '__builtin_assume_aligned' must be a constant integer}}
71+
return a[0];
72+
}
73+
6974
void test_void_assume_aligned(void) __attribute__((assume_aligned(32))); // expected-warning {{'assume_aligned' attribute only applies to return values that are pointers}}
7075
int test_int_assume_aligned(void) __attribute__((assume_aligned(16))); // expected-warning {{'assume_aligned' attribute only applies to return values that are pointers}}
7176
void *test_ptr_assume_aligned(void) __attribute__((assume_aligned(64))); // no-warning

0 commit comments

Comments
 (0)