blob: 49c153d8c86196da84b2097cf67a86d0da675858 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Basic/Diagnostic.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000022#include "SemaUtil.h"
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
25/// CheckFunctionCall - Check a direct function call for various correctness
26/// and safety properties not strictly enforced by the C type system.
Eli Friedmand38617c2008-05-14 19:38:39 +000027Action::ExprResult
Eli Friedmane8018702008-05-16 17:51:27 +000028Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
29 llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
Chris Lattner59907c42007-08-10 20:18:51 +000030 // Get the IdentifierInfo* for the called function.
31 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000032
33 // None of the checks below are needed for functions that don't have
34 // simple names (e.g., C++ conversion functions).
35 if (!FnInfo)
36 return TheCall.take();
37
Chris Lattner30ce3442007-12-19 23:59:04 +000038 switch (FnInfo->getBuiltinID()) {
39 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000040 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000041 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000042 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand38617c2008-05-14 19:38:39 +000043 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000044 return TheCall.take();
Ted Kremenek49ff7a12008-07-09 17:58:53 +000045 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000046 case Builtin::BI__builtin_va_start:
Chris Lattnerb7cfe882008-06-30 18:32:54 +000047 if (SemaBuiltinVAStart(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000048 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000049 return TheCall.take();
Chris Lattner1b9a0792007-12-20 00:26:33 +000050 case Builtin::BI__builtin_isgreater:
51 case Builtin::BI__builtin_isgreaterequal:
52 case Builtin::BI__builtin_isless:
53 case Builtin::BI__builtin_islessequal:
54 case Builtin::BI__builtin_islessgreater:
55 case Builtin::BI__builtin_isunordered:
Eli Friedmane8018702008-05-16 17:51:27 +000056 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000057 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000058 return TheCall.take();
Eli Friedman6cfda232008-05-20 08:23:37 +000059 case Builtin::BI__builtin_return_address:
60 case Builtin::BI__builtin_frame_address:
61 if (SemaBuiltinStackAddress(TheCall.get()))
62 return true;
63 return TheCall.take();
Eli Friedmand38617c2008-05-14 19:38:39 +000064 case Builtin::BI__builtin_shufflevector:
Eli Friedmane8018702008-05-16 17:51:27 +000065 return SemaBuiltinShuffleVector(TheCall.get());
Daniel Dunbar4493f792008-07-21 22:59:13 +000066 case Builtin::BI__builtin_prefetch:
67 if (SemaBuiltinPrefetch(TheCall.get()))
68 return true;
69 return TheCall.take();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +000070 case Builtin::BI__builtin_object_size:
71 if (SemaBuiltinObjectSize(TheCall.get()))
72 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +000073 }
Daniel Dunbarde454282008-10-02 18:44:07 +000074
75 // FIXME: This mechanism should be abstracted to be less fragile and
76 // more efficient. For example, just map function ids to custom
77 // handlers.
78
Chris Lattner59907c42007-08-10 20:18:51 +000079 // Search the KnownFunctionIDs for the identifier.
80 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000081 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedmane8018702008-05-16 17:51:27 +000082 if (i == e) return TheCall.take();
Chris Lattner59907c42007-08-10 20:18:51 +000083
84 // Printf checking.
85 if (i <= id_vprintf) {
Ted Kremenek71895b92007-08-14 17:39:48 +000086 // Retrieve the index of the format string parameter and determine
87 // if the function is passed a va_arg argument.
Chris Lattner59907c42007-08-10 20:18:51 +000088 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000089 bool HasVAListArg = false;
90
Chris Lattner59907c42007-08-10 20:18:51 +000091 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000092 default: assert(false && "No format string argument index.");
Daniel Dunbarde454282008-10-02 18:44:07 +000093 case id_NSLog: format_idx = 0; break;
94 case id_asprintf: format_idx = 1; break;
95 case id_fprintf: format_idx = 1; break;
96 case id_printf: format_idx = 0; break;
97 case id_snprintf: format_idx = 2; break;
98 case id_snprintf_chk: format_idx = 4; break;
99 case id_sprintf: format_idx = 1; break;
100 case id_sprintf_chk: format_idx = 3; break;
101 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
102 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
103 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
104 case id_vsnprintf_chk: format_idx = 4; HasVAListArg = true; break;
105 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
106 case id_vsprintf_chk: format_idx = 3; HasVAListArg = true; break;
107 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000108 }
109
Eli Friedmane8018702008-05-16 17:51:27 +0000110 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +0000111 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000112
Eli Friedmane8018702008-05-16 17:51:27 +0000113 return TheCall.take();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000114}
115
116/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
117/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +0000118bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000119 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000120
121 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
122
123 if (!Literal || Literal->isWide()) {
124 Diag(Arg->getLocStart(),
125 diag::err_cfstring_literal_not_string_constant,
126 Arg->getSourceRange());
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000127 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000128 }
129
130 const char *Data = Literal->getStrData();
131 unsigned Length = Literal->getByteLength();
132
133 for (unsigned i = 0; i < Length; ++i) {
134 if (!isascii(Data[i])) {
135 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
136 diag::warn_cfstring_literal_contains_non_ascii_character,
137 Arg->getSourceRange());
138 break;
139 }
140
141 if (!Data[i]) {
142 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
143 diag::warn_cfstring_literal_contains_nul_character,
144 Arg->getSourceRange());
145 break;
146 }
147 }
148
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000149 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000150}
151
Chris Lattnerc27c6652007-12-20 00:05:45 +0000152/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
153/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000154bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
155 Expr *Fn = TheCall->getCallee();
156 if (TheCall->getNumArgs() > 2) {
157 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000158 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000159 SourceRange(TheCall->getArg(2)->getLocStart(),
160 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner30ce3442007-12-19 23:59:04 +0000161 return true;
162 }
163
Chris Lattnerc27c6652007-12-20 00:05:45 +0000164 // Determine whether the current function is variadic or not.
165 bool isVariadic;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000166 if (getCurFunctionDecl())
Chris Lattnerc27c6652007-12-20 00:05:45 +0000167 isVariadic =
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000168 cast<FunctionTypeProto>(getCurFunctionDecl()->getType())->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000169 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000170 isVariadic = getCurMethodDecl()->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000171
Chris Lattnerc27c6652007-12-20 00:05:45 +0000172 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000173 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
174 return true;
175 }
176
177 // Verify that the second argument to the builtin is the last argument of the
178 // current function or method.
179 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000180 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000181
182 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
183 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000184 // FIXME: This isn't correct for methods (results in bogus warning).
185 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000186 const ParmVarDecl *LastArg;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000187 if (getCurFunctionDecl())
188 LastArg = *(getCurFunctionDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000189 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000190 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000191 SecondArgIsLastNamedArgument = PV == LastArg;
192 }
193 }
194
195 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000196 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000197 diag::warn_second_parameter_of_va_start_not_last_named_argument);
198 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000199}
Chris Lattner30ce3442007-12-19 23:59:04 +0000200
Chris Lattner1b9a0792007-12-20 00:26:33 +0000201/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
202/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000203bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
204 if (TheCall->getNumArgs() < 2)
205 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
206 if (TheCall->getNumArgs() > 2)
207 return Diag(TheCall->getArg(2)->getLocStart(),
208 diag::err_typecheck_call_too_many_args,
209 SourceRange(TheCall->getArg(2)->getLocStart(),
210 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000211
Chris Lattner925e60d2007-12-28 05:29:59 +0000212 Expr *OrigArg0 = TheCall->getArg(0);
213 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000214
215 // Do standard promotions between the two arguments, returning their common
216 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000217 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000218
219 // If the common type isn't a real floating type, then the arguments were
220 // invalid for this operation.
221 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000222 return Diag(OrigArg0->getLocStart(),
Chris Lattner1b9a0792007-12-20 00:26:33 +0000223 diag::err_typecheck_call_invalid_ordered_compare,
224 OrigArg0->getType().getAsString(),
225 OrigArg1->getType().getAsString(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000226 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000227
228 return false;
229}
230
Eli Friedman6cfda232008-05-20 08:23:37 +0000231bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
232 // The signature for these builtins is exact; the only thing we need
233 // to check is that the argument is a constant.
234 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000235 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Eli Friedman6cfda232008-05-20 08:23:37 +0000236 return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000237
Eli Friedman6cfda232008-05-20 08:23:37 +0000238 return false;
239}
240
Eli Friedmand38617c2008-05-14 19:38:39 +0000241/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
242// This is declared to take (...), so we have to check everything.
243Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
244 if (TheCall->getNumArgs() < 3)
245 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
246 TheCall->getSourceRange());
247
248 QualType FAType = TheCall->getArg(0)->getType();
249 QualType SAType = TheCall->getArg(1)->getType();
250
251 if (!FAType->isVectorType() || !SAType->isVectorType()) {
252 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector,
253 SourceRange(TheCall->getArg(0)->getLocStart(),
254 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000255 return true;
256 }
257
Chris Lattnerb77792e2008-07-26 22:17:49 +0000258 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
259 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000260 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector,
261 SourceRange(TheCall->getArg(0)->getLocStart(),
262 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000263 return true;
264 }
265
266 unsigned numElements = FAType->getAsVectorType()->getNumElements();
267 if (TheCall->getNumArgs() != numElements+2) {
268 if (TheCall->getNumArgs() < numElements+2)
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000269 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
270 TheCall->getSourceRange());
271 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
272 TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000273 }
274
275 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
276 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000277 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
278 return Diag(TheCall->getLocStart(),
279 diag::err_shufflevector_nonconstant_argument,
280 TheCall->getArg(i)->getSourceRange());
281
282 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
283 return Diag(TheCall->getLocStart(),
284 diag::err_shufflevector_argument_too_large,
285 TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000286 }
287
288 llvm::SmallVector<Expr*, 32> exprs;
289
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000290 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000291 exprs.push_back(TheCall->getArg(i));
292 TheCall->setArg(i, 0);
293 }
294
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000295 return new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
296 TheCall->getCallee()->getLocStart(),
297 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +0000298}
Chris Lattner30ce3442007-12-19 23:59:04 +0000299
Daniel Dunbar4493f792008-07-21 22:59:13 +0000300/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
301// This is declared to take (const void*, ...) and can take two
302// optional constant int args.
303bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
304 unsigned numArgs = TheCall->getNumArgs();
305 bool res = false;
306
307 if (numArgs > 3) {
308 res |= Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
309 TheCall->getSourceRange());
310 }
311
312 // Argument 0 is checked for us and the remaining arguments must be
313 // constant integers.
314 for (unsigned i=1; i<numArgs; ++i) {
315 Expr *Arg = TheCall->getArg(i);
316 QualType RWType = Arg->getType();
317
318 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000319 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000320 if (!BT || BT->getKind() != BuiltinType::Int ||
321 !Arg->isIntegerConstantExpr(Result, Context)) {
322 if (Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument,
323 SourceRange(Arg->getLocStart(), Arg->getLocEnd()))) {
324 res = true;
325 continue;
326 }
327 }
328
329 // FIXME: gcc issues a warning and rewrites these to 0. These
330 // seems especially odd for the third argument since the default
331 // is 3.
332 if (i==1) {
333 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000334 res |= Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
Daniel Dunbar4493f792008-07-21 22:59:13 +0000335 "0", "1",
336 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
337 } else {
338 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000339 res |= Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
Daniel Dunbar4493f792008-07-21 22:59:13 +0000340 "0", "3",
341 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
342 }
343 }
344
345 return res;
346}
347
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000348/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
349/// int type). This simply type checks that type is one of the defined
350/// constants (0-3).
351bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
352 Expr *Arg = TheCall->getArg(1);
353 QualType ArgType = Arg->getType();
354 const BuiltinType *BT = ArgType->getAsBuiltinType();
355 llvm::APSInt Result(32);
356 if (!BT || BT->getKind() != BuiltinType::Int ||
357 !Arg->isIntegerConstantExpr(Result, Context)) {
358 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument,
359 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
360 }
361
362 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
363 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
364 "0", "3",
365 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
366 }
367
368 return false;
369}
370
Chris Lattner59907c42007-08-10 20:18:51 +0000371/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000372/// correct use of format strings.
373///
374/// HasVAListArg - A predicate indicating whether the printf-like
375/// function is passed an explicit va_arg argument (e.g., vprintf)
376///
377/// format_idx - The index into Args for the format string.
378///
379/// Improper format strings to functions in the printf family can be
380/// the source of bizarre bugs and very serious security holes. A
381/// good source of information is available in the following paper
382/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000383///
384/// FormatGuard: Automatic Protection From printf Format String
385/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000386///
387/// Functionality implemented:
388///
389/// We can statically check the following properties for string
390/// literal format strings for non v.*printf functions (where the
391/// arguments are passed directly):
392//
393/// (1) Are the number of format conversions equal to the number of
394/// data arguments?
395///
396/// (2) Does each format conversion correctly match the type of the
397/// corresponding data argument? (TODO)
398///
399/// Moreover, for all printf functions we can:
400///
401/// (3) Check for a missing format string (when not caught by type checking).
402///
403/// (4) Check for no-operation flags; e.g. using "#" with format
404/// conversion 'c' (TODO)
405///
406/// (5) Check the use of '%n', a major source of security holes.
407///
408/// (6) Check for malformed format conversions that don't specify anything.
409///
410/// (7) Check for empty format strings. e.g: printf("");
411///
412/// (8) Check that the format string is a wide literal.
413///
Ted Kremenek6d439592008-03-03 16:50:00 +0000414/// (9) Also check the arguments of functions with the __format__ attribute.
415/// (TODO).
416///
Ted Kremenek71895b92007-08-14 17:39:48 +0000417/// All of these checks can be done by parsing the format string.
418///
419/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000420void
Chris Lattner925e60d2007-12-28 05:29:59 +0000421Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
422 unsigned format_idx) {
423 Expr *Fn = TheCall->getCallee();
424
Ted Kremenek71895b92007-08-14 17:39:48 +0000425 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000426 if (format_idx >= TheCall->getNumArgs()) {
427 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000428 Fn->getSourceRange());
429 return;
430 }
431
Chris Lattner56f34942008-02-13 01:02:39 +0000432 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000433
Chris Lattner59907c42007-08-10 20:18:51 +0000434 // CHECK: format string is not a string literal.
435 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000436 // Dynamically generated format strings are difficult to
437 // automatically vet at compile time. Requiring that format strings
438 // are string literals: (1) permits the checking of format strings by
439 // the compiler and thereby (2) can practically remove the source of
440 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000441
442 // Format string can be either ObjC string (e.g. @"%d") or
443 // C string (e.g. "%d")
444 // ObjC string uses the same format specifiers as C string, so we can use
445 // the same format string checking logic for both ObjC and C strings.
446 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
447 StringLiteral *FExpr = NULL;
448
449 if(ObjCFExpr != NULL)
450 FExpr = ObjCFExpr->getString();
451 else
452 FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
453
Ted Kremenek71895b92007-08-14 17:39:48 +0000454 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000455 // For vprintf* functions (i.e., HasVAListArg==true), we add a
456 // special check to see if the format string is a function parameter
457 // of the function calling the printf function. If the function
458 // has an attribute indicating it is a printf-like function, then we
459 // should suppress warnings concerning non-literals being used in a call
460 // to a vprintf function. For example:
461 //
462 // void
463 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
464 // va_list ap;
465 // va_start(ap, fmt);
466 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
467 // ...
468 //
469 //
470 // FIXME: We don't have full attribute support yet, so just check to see
471 // if the argument is a DeclRefExpr that references a parameter. We'll
472 // add proper support for checking the attribute later.
473 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000474 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
475 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000476 return;
477
Chris Lattner925e60d2007-12-28 05:29:59 +0000478 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000479 diag::warn_printf_not_string_constant,
480 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000481 return;
482 }
483
484 // CHECK: is the format string a wide literal?
485 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000486 Diag(FExpr->getLocStart(),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000487 diag::warn_printf_format_string_is_wide_literal,
488 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000489 return;
490 }
491
492 // Str - The format string. NOTE: this is NOT null-terminated!
493 const char * const Str = FExpr->getStrData();
494
495 // CHECK: empty format string?
496 const unsigned StrLen = FExpr->getByteLength();
497
498 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000499 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000500 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000501 return;
502 }
503
504 // We process the format string using a binary state machine. The
505 // current state is stored in CurrentState.
506 enum {
507 state_OrdChr,
508 state_Conversion
509 } CurrentState = state_OrdChr;
510
511 // numConversions - The number of conversions seen so far. This is
512 // incremented as we traverse the format string.
513 unsigned numConversions = 0;
514
515 // numDataArgs - The number of data arguments after the format
516 // string. This can only be determined for non vprintf-like
517 // functions. For those functions, this value is 1 (the sole
518 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000519 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000520
521 // Inspect the format string.
522 unsigned StrIdx = 0;
523
524 // LastConversionIdx - Index within the format string where we last saw
525 // a '%' character that starts a new format conversion.
526 unsigned LastConversionIdx = 0;
527
Chris Lattner925e60d2007-12-28 05:29:59 +0000528 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000529
Ted Kremenek71895b92007-08-14 17:39:48 +0000530 // Is the number of detected conversion conversions greater than
531 // the number of matching data arguments? If so, stop.
532 if (!HasVAListArg && numConversions > numDataArgs) break;
533
534 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000535 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000536 // The string returned by getStrData() is not null-terminated,
537 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000538 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
539 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000540 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000541 return;
542 }
543
544 // Ordinary characters (not processing a format conversion).
545 if (CurrentState == state_OrdChr) {
546 if (Str[StrIdx] == '%') {
547 CurrentState = state_Conversion;
548 LastConversionIdx = StrIdx;
549 }
550 continue;
551 }
552
553 // Seen '%'. Now processing a format conversion.
554 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000555 // Handle dynamic precision or width specifier.
556 case '*': {
557 ++numConversions;
558
559 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000560 SourceLocation Loc = FExpr->getLocStart();
561 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000562
Ted Kremenek580b6642007-10-12 20:51:52 +0000563 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000564 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000565 OrigFormatExpr->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000566 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000567 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000568 OrigFormatExpr->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000569
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000570 // Don't do any more checking. We'll just emit spurious errors.
571 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000572 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000573
574 // Perform type checking on width/precision specifier.
575 Expr *E = TheCall->getArg(format_idx+numConversions);
576 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
577 if (BT->getKind() == BuiltinType::Int)
578 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000579
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000580 SourceLocation Loc =
581 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
582
583 if (Str[StrIdx-1] == '.')
584 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
585 E->getType().getAsString(), E->getSourceRange());
586 else
587 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
588 E->getType().getAsString(), E->getSourceRange());
589
590 break;
591 }
592
593 // Characters which can terminate a format conversion
594 // (e.g. "%d"). Characters that specify length modifiers or
595 // other flags are handled by the default case below.
596 //
597 // FIXME: additional checks will go into the following cases.
598 case 'i':
599 case 'd':
600 case 'o':
601 case 'u':
602 case 'x':
603 case 'X':
604 case 'D':
605 case 'O':
606 case 'U':
607 case 'e':
608 case 'E':
609 case 'f':
610 case 'F':
611 case 'g':
612 case 'G':
613 case 'a':
614 case 'A':
615 case 'c':
616 case 'C':
617 case 'S':
618 case 's':
619 case 'p':
620 ++numConversions;
621 CurrentState = state_OrdChr;
622 break;
623
624 // CHECK: Are we using "%n"? Issue a warning.
625 case 'n': {
626 ++numConversions;
627 CurrentState = state_OrdChr;
628 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
629 LastConversionIdx+1);
630
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000631 Diag(Loc, diag::warn_printf_write_back, OrigFormatExpr->getSourceRange());
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000632 break;
633 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000634
635 // Handle "%@"
636 case '@':
637 // %@ is allowed in ObjC format strings only.
638 if(ObjCFExpr != NULL)
639 CurrentState = state_OrdChr;
640 else {
641 // Issue a warning: invalid format conversion.
642 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
643 LastConversionIdx+1);
644
645 Diag(Loc, diag::warn_printf_invalid_conversion,
646 std::string(Str+LastConversionIdx,
647 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000648 OrigFormatExpr->getSourceRange());
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000649 }
650 ++numConversions;
651 break;
652
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000653 // Handle "%%"
654 case '%':
655 // Sanity check: Was the first "%" character the previous one?
656 // If not, we will assume that we have a malformed format
657 // conversion, and that the current "%" character is the start
658 // of a new conversion.
659 if (StrIdx - LastConversionIdx == 1)
660 CurrentState = state_OrdChr;
661 else {
662 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000663 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
664 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000665
666 Diag(Loc, diag::warn_printf_invalid_conversion,
667 std::string(Str+LastConversionIdx, Str+StrIdx),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000668 OrigFormatExpr->getSourceRange());
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000669
670 // This conversion is broken. Advance to the next format
671 // conversion.
672 LastConversionIdx = StrIdx;
673 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000674 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000675 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000676
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000677 default:
678 // This case catches all other characters: flags, widths, etc.
679 // We should eventually process those as well.
680 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000681 }
682 }
683
684 if (CurrentState == state_Conversion) {
685 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000686 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
687 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000688
689 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000690 std::string(Str+LastConversionIdx,
691 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000692 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000693 return;
694 }
695
696 if (!HasVAListArg) {
697 // CHECK: Does the number of format conversions exceed the number
698 // of data arguments?
699 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000700 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
701 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000702
703 Diag(Loc, diag::warn_printf_insufficient_data_args,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000704 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000705 }
706 // CHECK: Does the number of data arguments exceed the number of
707 // format conversions in the format string?
708 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000709 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000710 diag::warn_printf_too_many_data_args,
711 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000712 }
713}
Ted Kremenek06de2762007-08-17 16:46:58 +0000714
715//===--- CHECK: Return Address of Stack Variable --------------------------===//
716
717static DeclRefExpr* EvalVal(Expr *E);
718static DeclRefExpr* EvalAddr(Expr* E);
719
720/// CheckReturnStackAddr - Check if a return statement returns the address
721/// of a stack variable.
722void
723Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
724 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000725
Ted Kremenek06de2762007-08-17 16:46:58 +0000726 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000727 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000728 if (DeclRefExpr *DR = EvalAddr(RetValExp))
729 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
730 DR->getDecl()->getIdentifier()->getName(),
731 RetValExp->getSourceRange());
Steve Naroffc50a4a52008-09-16 22:25:10 +0000732
733 // Skip over implicit cast expressions when checking for block expressions.
734 if (ImplicitCastExpr *IcExpr =
735 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
736 RetValExp = IcExpr->getSubExpr();
737
Steve Naroff61f40a22008-09-10 19:17:48 +0000738 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Steve Naroffdd972f22008-09-05 22:11:13 +0000739 Diag(C->getLocStart(), diag::err_ret_local_block,
740 C->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000741 }
742 // Perform checking for stack values returned by reference.
743 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000744 // Check for a reference to the stack
745 if (DeclRefExpr *DR = EvalVal(RetValExp))
746 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
747 DR->getDecl()->getIdentifier()->getName(),
748 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000749 }
750}
751
752/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
753/// check if the expression in a return statement evaluates to an address
754/// to a location on the stack. The recursion is used to traverse the
755/// AST of the return expression, with recursion backtracking when we
756/// encounter a subexpression that (1) clearly does not lead to the address
757/// of a stack variable or (2) is something we cannot determine leads to
758/// the address of a stack variable based on such local checking.
759///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000760/// EvalAddr processes expressions that are pointers that are used as
761/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000762/// At the base case of the recursion is a check for a DeclRefExpr* in
763/// the refers to a stack variable.
764///
765/// This implementation handles:
766///
767/// * pointer-to-pointer casts
768/// * implicit conversions from array references to pointers
769/// * taking the address of fields
770/// * arbitrary interplay between "&" and "*" operators
771/// * pointer arithmetic from an address of a stack variable
772/// * taking the address of an array element where the array is on the stack
773static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000774 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000775 assert((E->getType()->isPointerType() ||
776 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000777 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000778 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000779
780 // Our "symbolic interpreter" is just a dispatch off the currently
781 // viewed AST node. We then recursively traverse the AST by calling
782 // EvalAddr and EvalVal appropriately.
783 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000784 case Stmt::ParenExprClass:
785 // Ignore parentheses.
786 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000787
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000788 case Stmt::UnaryOperatorClass: {
789 // The only unary operator that make sense to handle here
790 // is AddrOf. All others don't make sense as pointers.
791 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000792
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000793 if (U->getOpcode() == UnaryOperator::AddrOf)
794 return EvalVal(U->getSubExpr());
795 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000796 return NULL;
797 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000798
799 case Stmt::BinaryOperatorClass: {
800 // Handle pointer arithmetic. All other binary operators are not valid
801 // in this context.
802 BinaryOperator *B = cast<BinaryOperator>(E);
803 BinaryOperator::Opcode op = B->getOpcode();
804
805 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
806 return NULL;
807
808 Expr *Base = B->getLHS();
809
810 // Determine which argument is the real pointer base. It could be
811 // the RHS argument instead of the LHS.
812 if (!Base->getType()->isPointerType()) Base = B->getRHS();
813
814 assert (Base->getType()->isPointerType());
815 return EvalAddr(Base);
816 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000817
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000818 // For conditional operators we need to see if either the LHS or RHS are
819 // valid DeclRefExpr*s. If one of them is valid, we return it.
820 case Stmt::ConditionalOperatorClass: {
821 ConditionalOperator *C = cast<ConditionalOperator>(E);
822
823 // Handle the GNU extension for missing LHS.
824 if (Expr *lhsExpr = C->getLHS())
825 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
826 return LHS;
827
828 return EvalAddr(C->getRHS());
829 }
830
Ted Kremenek54b52742008-08-07 00:49:01 +0000831 // For casts, we need to handle conversions from arrays to
832 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000833 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000834 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000835 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000836 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000837 QualType T = SubExpr->getType();
838
Steve Naroffdd972f22008-09-05 22:11:13 +0000839 if (SubExpr->getType()->isPointerType() ||
840 SubExpr->getType()->isBlockPointerType() ||
841 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000842 return EvalAddr(SubExpr);
843 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000844 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000845 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000846 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000847 }
848
849 // C++ casts. For dynamic casts, static casts, and const casts, we
850 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000851 // through the cast. In the case the dynamic cast doesn't fail (and
852 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000853 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000854 // FIXME: The comment about is wrong; we're not always converting
855 // from pointer to pointer. I'm guessing that this code should also
856 // handle references to objects.
857 case Stmt::CXXStaticCastExprClass:
858 case Stmt::CXXDynamicCastExprClass:
859 case Stmt::CXXConstCastExprClass:
860 case Stmt::CXXReinterpretCastExprClass: {
861 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000862 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000863 return EvalAddr(S);
864 else
865 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000866 }
867
868 // Everything else: we simply don't reason about them.
869 default:
870 return NULL;
871 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000872}
873
874
875/// EvalVal - This function is complements EvalAddr in the mutual recursion.
876/// See the comments for EvalAddr for more details.
877static DeclRefExpr* EvalVal(Expr *E) {
878
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000879 // We should only be called for evaluating non-pointer expressions, or
880 // expressions with a pointer type that are not used as references but instead
881 // are l-values (e.g., DeclRefExpr with a pointer type).
882
Ted Kremenek06de2762007-08-17 16:46:58 +0000883 // Our "symbolic interpreter" is just a dispatch off the currently
884 // viewed AST node. We then recursively traverse the AST by calling
885 // EvalAddr and EvalVal appropriately.
886 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000887 case Stmt::DeclRefExprClass: {
888 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
889 // at code that refers to a variable's name. We check if it has local
890 // storage within the function, and if so, return the expression.
891 DeclRefExpr *DR = cast<DeclRefExpr>(E);
892
893 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000894 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000895
896 return NULL;
897 }
898
899 case Stmt::ParenExprClass:
900 // Ignore parentheses.
901 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
902
903 case Stmt::UnaryOperatorClass: {
904 // The only unary operator that make sense to handle here
905 // is Deref. All others don't resolve to a "name." This includes
906 // handling all sorts of rvalues passed to a unary operator.
907 UnaryOperator *U = cast<UnaryOperator>(E);
908
909 if (U->getOpcode() == UnaryOperator::Deref)
910 return EvalAddr(U->getSubExpr());
911
912 return NULL;
913 }
914
915 case Stmt::ArraySubscriptExprClass: {
916 // Array subscripts are potential references to data on the stack. We
917 // retrieve the DeclRefExpr* for the array variable if it indeed
918 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000919 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000920 }
921
922 case Stmt::ConditionalOperatorClass: {
923 // For conditional operators we need to see if either the LHS or RHS are
924 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
925 ConditionalOperator *C = cast<ConditionalOperator>(E);
926
Anders Carlsson39073232007-11-30 19:04:31 +0000927 // Handle the GNU extension for missing LHS.
928 if (Expr *lhsExpr = C->getLHS())
929 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
930 return LHS;
931
932 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000933 }
934
935 // Accesses to members are potential references to data on the stack.
936 case Stmt::MemberExprClass: {
937 MemberExpr *M = cast<MemberExpr>(E);
938
939 // Check for indirect access. We only want direct field accesses.
940 if (!M->isArrow())
941 return EvalVal(M->getBase());
942 else
943 return NULL;
944 }
945
946 // Everything else: we simply don't reason about them.
947 default:
948 return NULL;
949 }
950}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000951
952//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
953
954/// Check for comparisons of floating point operands using != and ==.
955/// Issue a warning if these are no self-comparisons, as they are not likely
956/// to do what the programmer intended.
957void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
958 bool EmitWarning = true;
959
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000960 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000961 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000962
963 // Special case: check for x == x (which is OK).
964 // Do not emit warnings for such cases.
965 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
966 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
967 if (DRL->getDecl() == DRR->getDecl())
968 EmitWarning = false;
969
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000970
971 // Special case: check for comparisons against literals that can be exactly
972 // represented by APFloat. In such cases, do not emit a warning. This
973 // is a heuristic: often comparison against such literals are used to
974 // detect if a value in a variable has not changed. This clearly can
975 // lead to false negatives.
976 if (EmitWarning) {
977 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
978 if (FLL->isExact())
979 EmitWarning = false;
980 }
981 else
982 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
983 if (FLR->isExact())
984 EmitWarning = false;
985 }
986 }
987
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000988 // Check for comparisons with builtin types.
989 if (EmitWarning)
990 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
991 if (isCallBuiltin(CL))
992 EmitWarning = false;
993
994 if (EmitWarning)
995 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
996 if (isCallBuiltin(CR))
997 EmitWarning = false;
998
999 // Emit the diagnostic.
1000 if (EmitWarning)
1001 Diag(loc, diag::warn_floatingpoint_eq,
1002 lex->getSourceRange(),rex->getSourceRange());
1003}