blob: 00b469b7c05cff7d866e14029ba0c1f127659f73 [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();
32
Chris Lattner30ce3442007-12-19 23:59:04 +000033 switch (FnInfo->getBuiltinID()) {
34 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000035 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000036 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000037 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand38617c2008-05-14 19:38:39 +000038 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000039 return TheCall.take();
Ted Kremenek49ff7a12008-07-09 17:58:53 +000040 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000041 case Builtin::BI__builtin_va_start:
Chris Lattnerb7cfe882008-06-30 18:32:54 +000042 if (SemaBuiltinVAStart(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000043 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000044 return TheCall.take();
Chris Lattner1b9a0792007-12-20 00:26:33 +000045 case Builtin::BI__builtin_isgreater:
46 case Builtin::BI__builtin_isgreaterequal:
47 case Builtin::BI__builtin_isless:
48 case Builtin::BI__builtin_islessequal:
49 case Builtin::BI__builtin_islessgreater:
50 case Builtin::BI__builtin_isunordered:
Eli Friedmane8018702008-05-16 17:51:27 +000051 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000052 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000053 return TheCall.take();
Eli Friedman6cfda232008-05-20 08:23:37 +000054 case Builtin::BI__builtin_return_address:
55 case Builtin::BI__builtin_frame_address:
56 if (SemaBuiltinStackAddress(TheCall.get()))
57 return true;
58 return TheCall.take();
Eli Friedmand38617c2008-05-14 19:38:39 +000059 case Builtin::BI__builtin_shufflevector:
Eli Friedmane8018702008-05-16 17:51:27 +000060 return SemaBuiltinShuffleVector(TheCall.get());
Daniel Dunbar4493f792008-07-21 22:59:13 +000061 case Builtin::BI__builtin_prefetch:
62 if (SemaBuiltinPrefetch(TheCall.get()))
63 return true;
64 return TheCall.take();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +000065 case Builtin::BI__builtin_object_size:
66 if (SemaBuiltinObjectSize(TheCall.get()))
67 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +000068 }
69
Chris Lattner59907c42007-08-10 20:18:51 +000070 // Search the KnownFunctionIDs for the identifier.
71 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000072 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedmane8018702008-05-16 17:51:27 +000073 if (i == e) return TheCall.take();
Chris Lattner59907c42007-08-10 20:18:51 +000074
75 // Printf checking.
76 if (i <= id_vprintf) {
Ted Kremenek71895b92007-08-14 17:39:48 +000077 // Retrieve the index of the format string parameter and determine
78 // if the function is passed a va_arg argument.
Chris Lattner59907c42007-08-10 20:18:51 +000079 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000080 bool HasVAListArg = false;
81
Chris Lattner59907c42007-08-10 20:18:51 +000082 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000083 default: assert(false && "No format string argument index.");
84 case id_printf: format_idx = 0; break;
85 case id_fprintf: format_idx = 1; break;
86 case id_sprintf: format_idx = 1; break;
87 case id_snprintf: format_idx = 2; break;
88 case id_asprintf: format_idx = 1; break;
Ted Kremenek7ff22b22008-06-16 18:00:42 +000089 case id_NSLog: format_idx = 0; break;
Chris Lattner30ce3442007-12-19 23:59:04 +000090 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
91 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
92 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
93 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
94 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek71895b92007-08-14 17:39:48 +000095 }
96
Eli Friedmane8018702008-05-16 17:51:27 +000097 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +000098 }
Anders Carlsson71993dd2007-08-17 05:31:46 +000099
Eli Friedmane8018702008-05-16 17:51:27 +0000100 return TheCall.take();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000101}
102
103/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
104/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +0000105bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000106 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000107
108 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
109
110 if (!Literal || Literal->isWide()) {
111 Diag(Arg->getLocStart(),
112 diag::err_cfstring_literal_not_string_constant,
113 Arg->getSourceRange());
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000114 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000115 }
116
117 const char *Data = Literal->getStrData();
118 unsigned Length = Literal->getByteLength();
119
120 for (unsigned i = 0; i < Length; ++i) {
121 if (!isascii(Data[i])) {
122 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
123 diag::warn_cfstring_literal_contains_non_ascii_character,
124 Arg->getSourceRange());
125 break;
126 }
127
128 if (!Data[i]) {
129 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
130 diag::warn_cfstring_literal_contains_nul_character,
131 Arg->getSourceRange());
132 break;
133 }
134 }
135
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000136 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000137}
138
Chris Lattnerc27c6652007-12-20 00:05:45 +0000139/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
140/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000141bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
142 Expr *Fn = TheCall->getCallee();
143 if (TheCall->getNumArgs() > 2) {
144 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000145 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000146 SourceRange(TheCall->getArg(2)->getLocStart(),
147 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner30ce3442007-12-19 23:59:04 +0000148 return true;
149 }
150
Chris Lattnerc27c6652007-12-20 00:05:45 +0000151 // Determine whether the current function is variadic or not.
152 bool isVariadic;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000153 if (getCurFunctionDecl())
Chris Lattnerc27c6652007-12-20 00:05:45 +0000154 isVariadic =
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000155 cast<FunctionTypeProto>(getCurFunctionDecl()->getType())->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000156 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000157 isVariadic = getCurMethodDecl()->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000158
Chris Lattnerc27c6652007-12-20 00:05:45 +0000159 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000160 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
161 return true;
162 }
163
164 // Verify that the second argument to the builtin is the last argument of the
165 // current function or method.
166 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000167 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000168
169 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
170 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000171 // FIXME: This isn't correct for methods (results in bogus warning).
172 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000173 const ParmVarDecl *LastArg;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000174 if (getCurFunctionDecl())
175 LastArg = *(getCurFunctionDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000176 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000177 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000178 SecondArgIsLastNamedArgument = PV == LastArg;
179 }
180 }
181
182 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000183 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000184 diag::warn_second_parameter_of_va_start_not_last_named_argument);
185 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000186}
Chris Lattner30ce3442007-12-19 23:59:04 +0000187
Chris Lattner1b9a0792007-12-20 00:26:33 +0000188/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
189/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000190bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
191 if (TheCall->getNumArgs() < 2)
192 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
193 if (TheCall->getNumArgs() > 2)
194 return Diag(TheCall->getArg(2)->getLocStart(),
195 diag::err_typecheck_call_too_many_args,
196 SourceRange(TheCall->getArg(2)->getLocStart(),
197 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000198
Chris Lattner925e60d2007-12-28 05:29:59 +0000199 Expr *OrigArg0 = TheCall->getArg(0);
200 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000201
202 // Do standard promotions between the two arguments, returning their common
203 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000204 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000205
206 // If the common type isn't a real floating type, then the arguments were
207 // invalid for this operation.
208 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000209 return Diag(OrigArg0->getLocStart(),
Chris Lattner1b9a0792007-12-20 00:26:33 +0000210 diag::err_typecheck_call_invalid_ordered_compare,
211 OrigArg0->getType().getAsString(),
212 OrigArg1->getType().getAsString(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000213 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000214
215 return false;
216}
217
Eli Friedman6cfda232008-05-20 08:23:37 +0000218bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
219 // The signature for these builtins is exact; the only thing we need
220 // to check is that the argument is a constant.
221 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000222 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Eli Friedman6cfda232008-05-20 08:23:37 +0000223 return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000224
Eli Friedman6cfda232008-05-20 08:23:37 +0000225 return false;
226}
227
Eli Friedmand38617c2008-05-14 19:38:39 +0000228/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
229// This is declared to take (...), so we have to check everything.
230Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
231 if (TheCall->getNumArgs() < 3)
232 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
233 TheCall->getSourceRange());
234
235 QualType FAType = TheCall->getArg(0)->getType();
236 QualType SAType = TheCall->getArg(1)->getType();
237
238 if (!FAType->isVectorType() || !SAType->isVectorType()) {
239 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector,
240 SourceRange(TheCall->getArg(0)->getLocStart(),
241 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000242 return true;
243 }
244
Chris Lattnerb77792e2008-07-26 22:17:49 +0000245 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
246 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000247 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector,
248 SourceRange(TheCall->getArg(0)->getLocStart(),
249 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000250 return true;
251 }
252
253 unsigned numElements = FAType->getAsVectorType()->getNumElements();
254 if (TheCall->getNumArgs() != numElements+2) {
255 if (TheCall->getNumArgs() < numElements+2)
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000256 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
257 TheCall->getSourceRange());
258 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
259 TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000260 }
261
262 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
263 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000264 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
265 return Diag(TheCall->getLocStart(),
266 diag::err_shufflevector_nonconstant_argument,
267 TheCall->getArg(i)->getSourceRange());
268
269 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
270 return Diag(TheCall->getLocStart(),
271 diag::err_shufflevector_argument_too_large,
272 TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000273 }
274
275 llvm::SmallVector<Expr*, 32> exprs;
276
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000277 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000278 exprs.push_back(TheCall->getArg(i));
279 TheCall->setArg(i, 0);
280 }
281
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000282 return new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
283 TheCall->getCallee()->getLocStart(),
284 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +0000285}
Chris Lattner30ce3442007-12-19 23:59:04 +0000286
Daniel Dunbar4493f792008-07-21 22:59:13 +0000287/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
288// This is declared to take (const void*, ...) and can take two
289// optional constant int args.
290bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
291 unsigned numArgs = TheCall->getNumArgs();
292 bool res = false;
293
294 if (numArgs > 3) {
295 res |= Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
296 TheCall->getSourceRange());
297 }
298
299 // Argument 0 is checked for us and the remaining arguments must be
300 // constant integers.
301 for (unsigned i=1; i<numArgs; ++i) {
302 Expr *Arg = TheCall->getArg(i);
303 QualType RWType = Arg->getType();
304
305 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000306 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000307 if (!BT || BT->getKind() != BuiltinType::Int ||
308 !Arg->isIntegerConstantExpr(Result, Context)) {
309 if (Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument,
310 SourceRange(Arg->getLocStart(), Arg->getLocEnd()))) {
311 res = true;
312 continue;
313 }
314 }
315
316 // FIXME: gcc issues a warning and rewrites these to 0. These
317 // seems especially odd for the third argument since the default
318 // is 3.
319 if (i==1) {
320 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000321 res |= Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
Daniel Dunbar4493f792008-07-21 22:59:13 +0000322 "0", "1",
323 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
324 } else {
325 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000326 res |= Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
Daniel Dunbar4493f792008-07-21 22:59:13 +0000327 "0", "3",
328 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
329 }
330 }
331
332 return res;
333}
334
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000335/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
336/// int type). This simply type checks that type is one of the defined
337/// constants (0-3).
338bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
339 Expr *Arg = TheCall->getArg(1);
340 QualType ArgType = Arg->getType();
341 const BuiltinType *BT = ArgType->getAsBuiltinType();
342 llvm::APSInt Result(32);
343 if (!BT || BT->getKind() != BuiltinType::Int ||
344 !Arg->isIntegerConstantExpr(Result, Context)) {
345 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument,
346 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
347 }
348
349 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
350 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
351 "0", "3",
352 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
353 }
354
355 return false;
356}
357
Chris Lattner59907c42007-08-10 20:18:51 +0000358/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000359/// correct use of format strings.
360///
361/// HasVAListArg - A predicate indicating whether the printf-like
362/// function is passed an explicit va_arg argument (e.g., vprintf)
363///
364/// format_idx - The index into Args for the format string.
365///
366/// Improper format strings to functions in the printf family can be
367/// the source of bizarre bugs and very serious security holes. A
368/// good source of information is available in the following paper
369/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000370///
371/// FormatGuard: Automatic Protection From printf Format String
372/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000373///
374/// Functionality implemented:
375///
376/// We can statically check the following properties for string
377/// literal format strings for non v.*printf functions (where the
378/// arguments are passed directly):
379//
380/// (1) Are the number of format conversions equal to the number of
381/// data arguments?
382///
383/// (2) Does each format conversion correctly match the type of the
384/// corresponding data argument? (TODO)
385///
386/// Moreover, for all printf functions we can:
387///
388/// (3) Check for a missing format string (when not caught by type checking).
389///
390/// (4) Check for no-operation flags; e.g. using "#" with format
391/// conversion 'c' (TODO)
392///
393/// (5) Check the use of '%n', a major source of security holes.
394///
395/// (6) Check for malformed format conversions that don't specify anything.
396///
397/// (7) Check for empty format strings. e.g: printf("");
398///
399/// (8) Check that the format string is a wide literal.
400///
Ted Kremenek6d439592008-03-03 16:50:00 +0000401/// (9) Also check the arguments of functions with the __format__ attribute.
402/// (TODO).
403///
Ted Kremenek71895b92007-08-14 17:39:48 +0000404/// All of these checks can be done by parsing the format string.
405///
406/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000407void
Chris Lattner925e60d2007-12-28 05:29:59 +0000408Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
409 unsigned format_idx) {
410 Expr *Fn = TheCall->getCallee();
411
Ted Kremenek71895b92007-08-14 17:39:48 +0000412 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000413 if (format_idx >= TheCall->getNumArgs()) {
414 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000415 Fn->getSourceRange());
416 return;
417 }
418
Chris Lattner56f34942008-02-13 01:02:39 +0000419 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000420
Chris Lattner59907c42007-08-10 20:18:51 +0000421 // CHECK: format string is not a string literal.
422 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000423 // Dynamically generated format strings are difficult to
424 // automatically vet at compile time. Requiring that format strings
425 // are string literals: (1) permits the checking of format strings by
426 // the compiler and thereby (2) can practically remove the source of
427 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000428
429 // Format string can be either ObjC string (e.g. @"%d") or
430 // C string (e.g. "%d")
431 // ObjC string uses the same format specifiers as C string, so we can use
432 // the same format string checking logic for both ObjC and C strings.
433 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
434 StringLiteral *FExpr = NULL;
435
436 if(ObjCFExpr != NULL)
437 FExpr = ObjCFExpr->getString();
438 else
439 FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
440
Ted Kremenek71895b92007-08-14 17:39:48 +0000441 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000442 // For vprintf* functions (i.e., HasVAListArg==true), we add a
443 // special check to see if the format string is a function parameter
444 // of the function calling the printf function. If the function
445 // has an attribute indicating it is a printf-like function, then we
446 // should suppress warnings concerning non-literals being used in a call
447 // to a vprintf function. For example:
448 //
449 // void
450 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
451 // va_list ap;
452 // va_start(ap, fmt);
453 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
454 // ...
455 //
456 //
457 // FIXME: We don't have full attribute support yet, so just check to see
458 // if the argument is a DeclRefExpr that references a parameter. We'll
459 // add proper support for checking the attribute later.
460 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000461 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
462 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000463 return;
464
Chris Lattner925e60d2007-12-28 05:29:59 +0000465 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000466 diag::warn_printf_not_string_constant,
467 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000468 return;
469 }
470
471 // CHECK: is the format string a wide literal?
472 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000473 Diag(FExpr->getLocStart(),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000474 diag::warn_printf_format_string_is_wide_literal,
475 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000476 return;
477 }
478
479 // Str - The format string. NOTE: this is NOT null-terminated!
480 const char * const Str = FExpr->getStrData();
481
482 // CHECK: empty format string?
483 const unsigned StrLen = FExpr->getByteLength();
484
485 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000486 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000487 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000488 return;
489 }
490
491 // We process the format string using a binary state machine. The
492 // current state is stored in CurrentState.
493 enum {
494 state_OrdChr,
495 state_Conversion
496 } CurrentState = state_OrdChr;
497
498 // numConversions - The number of conversions seen so far. This is
499 // incremented as we traverse the format string.
500 unsigned numConversions = 0;
501
502 // numDataArgs - The number of data arguments after the format
503 // string. This can only be determined for non vprintf-like
504 // functions. For those functions, this value is 1 (the sole
505 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000506 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000507
508 // Inspect the format string.
509 unsigned StrIdx = 0;
510
511 // LastConversionIdx - Index within the format string where we last saw
512 // a '%' character that starts a new format conversion.
513 unsigned LastConversionIdx = 0;
514
Chris Lattner925e60d2007-12-28 05:29:59 +0000515 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000516
Ted Kremenek71895b92007-08-14 17:39:48 +0000517 // Is the number of detected conversion conversions greater than
518 // the number of matching data arguments? If so, stop.
519 if (!HasVAListArg && numConversions > numDataArgs) break;
520
521 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000522 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000523 // The string returned by getStrData() is not null-terminated,
524 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000525 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
526 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000527 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000528 return;
529 }
530
531 // Ordinary characters (not processing a format conversion).
532 if (CurrentState == state_OrdChr) {
533 if (Str[StrIdx] == '%') {
534 CurrentState = state_Conversion;
535 LastConversionIdx = StrIdx;
536 }
537 continue;
538 }
539
540 // Seen '%'. Now processing a format conversion.
541 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000542 // Handle dynamic precision or width specifier.
543 case '*': {
544 ++numConversions;
545
546 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000547 SourceLocation Loc = FExpr->getLocStart();
548 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000549
Ted Kremenek580b6642007-10-12 20:51:52 +0000550 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000551 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000552 OrigFormatExpr->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000553 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000554 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000555 OrigFormatExpr->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000556
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000557 // Don't do any more checking. We'll just emit spurious errors.
558 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000559 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000560
561 // Perform type checking on width/precision specifier.
562 Expr *E = TheCall->getArg(format_idx+numConversions);
563 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
564 if (BT->getKind() == BuiltinType::Int)
565 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000566
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000567 SourceLocation Loc =
568 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
569
570 if (Str[StrIdx-1] == '.')
571 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
572 E->getType().getAsString(), E->getSourceRange());
573 else
574 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
575 E->getType().getAsString(), E->getSourceRange());
576
577 break;
578 }
579
580 // Characters which can terminate a format conversion
581 // (e.g. "%d"). Characters that specify length modifiers or
582 // other flags are handled by the default case below.
583 //
584 // FIXME: additional checks will go into the following cases.
585 case 'i':
586 case 'd':
587 case 'o':
588 case 'u':
589 case 'x':
590 case 'X':
591 case 'D':
592 case 'O':
593 case 'U':
594 case 'e':
595 case 'E':
596 case 'f':
597 case 'F':
598 case 'g':
599 case 'G':
600 case 'a':
601 case 'A':
602 case 'c':
603 case 'C':
604 case 'S':
605 case 's':
606 case 'p':
607 ++numConversions;
608 CurrentState = state_OrdChr;
609 break;
610
611 // CHECK: Are we using "%n"? Issue a warning.
612 case 'n': {
613 ++numConversions;
614 CurrentState = state_OrdChr;
615 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
616 LastConversionIdx+1);
617
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000618 Diag(Loc, diag::warn_printf_write_back, OrigFormatExpr->getSourceRange());
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000619 break;
620 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000621
622 // Handle "%@"
623 case '@':
624 // %@ is allowed in ObjC format strings only.
625 if(ObjCFExpr != NULL)
626 CurrentState = state_OrdChr;
627 else {
628 // Issue a warning: invalid format conversion.
629 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
630 LastConversionIdx+1);
631
632 Diag(Loc, diag::warn_printf_invalid_conversion,
633 std::string(Str+LastConversionIdx,
634 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000635 OrigFormatExpr->getSourceRange());
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000636 }
637 ++numConversions;
638 break;
639
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000640 // Handle "%%"
641 case '%':
642 // Sanity check: Was the first "%" character the previous one?
643 // If not, we will assume that we have a malformed format
644 // conversion, and that the current "%" character is the start
645 // of a new conversion.
646 if (StrIdx - LastConversionIdx == 1)
647 CurrentState = state_OrdChr;
648 else {
649 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000650 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
651 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000652
653 Diag(Loc, diag::warn_printf_invalid_conversion,
654 std::string(Str+LastConversionIdx, Str+StrIdx),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000655 OrigFormatExpr->getSourceRange());
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000656
657 // This conversion is broken. Advance to the next format
658 // conversion.
659 LastConversionIdx = StrIdx;
660 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000661 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000662 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000663
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000664 default:
665 // This case catches all other characters: flags, widths, etc.
666 // We should eventually process those as well.
667 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000668 }
669 }
670
671 if (CurrentState == state_Conversion) {
672 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000673 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
674 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000675
676 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000677 std::string(Str+LastConversionIdx,
678 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000679 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000680 return;
681 }
682
683 if (!HasVAListArg) {
684 // CHECK: Does the number of format conversions exceed the number
685 // of data arguments?
686 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000687 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
688 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000689
690 Diag(Loc, diag::warn_printf_insufficient_data_args,
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000691 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000692 }
693 // CHECK: Does the number of data arguments exceed the number of
694 // format conversions in the format string?
695 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000696 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek9801c8b2008-07-25 22:03:03 +0000697 diag::warn_printf_too_many_data_args,
698 OrigFormatExpr->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000699 }
700}
Ted Kremenek06de2762007-08-17 16:46:58 +0000701
702//===--- CHECK: Return Address of Stack Variable --------------------------===//
703
704static DeclRefExpr* EvalVal(Expr *E);
705static DeclRefExpr* EvalAddr(Expr* E);
706
707/// CheckReturnStackAddr - Check if a return statement returns the address
708/// of a stack variable.
709void
710Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
711 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000712
Ted Kremenek06de2762007-08-17 16:46:58 +0000713 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000714 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000715 if (DeclRefExpr *DR = EvalAddr(RetValExp))
716 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
717 DR->getDecl()->getIdentifier()->getName(),
718 RetValExp->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +0000719
Steve Naroff61f40a22008-09-10 19:17:48 +0000720 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Steve Naroffdd972f22008-09-05 22:11:13 +0000721 Diag(C->getLocStart(), diag::err_ret_local_block,
722 C->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000723 }
724 // Perform checking for stack values returned by reference.
725 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000726 // Check for an implicit cast to a reference.
727 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
728 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
729 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
730 DR->getDecl()->getIdentifier()->getName(),
731 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000732 }
733}
734
735/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
736/// check if the expression in a return statement evaluates to an address
737/// to a location on the stack. The recursion is used to traverse the
738/// AST of the return expression, with recursion backtracking when we
739/// encounter a subexpression that (1) clearly does not lead to the address
740/// of a stack variable or (2) is something we cannot determine leads to
741/// the address of a stack variable based on such local checking.
742///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000743/// EvalAddr processes expressions that are pointers that are used as
744/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000745/// At the base case of the recursion is a check for a DeclRefExpr* in
746/// the refers to a stack variable.
747///
748/// This implementation handles:
749///
750/// * pointer-to-pointer casts
751/// * implicit conversions from array references to pointers
752/// * taking the address of fields
753/// * arbitrary interplay between "&" and "*" operators
754/// * pointer arithmetic from an address of a stack variable
755/// * taking the address of an array element where the array is on the stack
756static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000757 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000758 assert((E->getType()->isPointerType() ||
759 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000760 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000761 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000762
763 // Our "symbolic interpreter" is just a dispatch off the currently
764 // viewed AST node. We then recursively traverse the AST by calling
765 // EvalAddr and EvalVal appropriately.
766 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000767 case Stmt::ParenExprClass:
768 // Ignore parentheses.
769 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000770
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000771 case Stmt::UnaryOperatorClass: {
772 // The only unary operator that make sense to handle here
773 // is AddrOf. All others don't make sense as pointers.
774 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000775
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000776 if (U->getOpcode() == UnaryOperator::AddrOf)
777 return EvalVal(U->getSubExpr());
778 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000779 return NULL;
780 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000781
782 case Stmt::BinaryOperatorClass: {
783 // Handle pointer arithmetic. All other binary operators are not valid
784 // in this context.
785 BinaryOperator *B = cast<BinaryOperator>(E);
786 BinaryOperator::Opcode op = B->getOpcode();
787
788 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
789 return NULL;
790
791 Expr *Base = B->getLHS();
792
793 // Determine which argument is the real pointer base. It could be
794 // the RHS argument instead of the LHS.
795 if (!Base->getType()->isPointerType()) Base = B->getRHS();
796
797 assert (Base->getType()->isPointerType());
798 return EvalAddr(Base);
799 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000800
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000801 // For conditional operators we need to see if either the LHS or RHS are
802 // valid DeclRefExpr*s. If one of them is valid, we return it.
803 case Stmt::ConditionalOperatorClass: {
804 ConditionalOperator *C = cast<ConditionalOperator>(E);
805
806 // Handle the GNU extension for missing LHS.
807 if (Expr *lhsExpr = C->getLHS())
808 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
809 return LHS;
810
811 return EvalAddr(C->getRHS());
812 }
813
Ted Kremenek54b52742008-08-07 00:49:01 +0000814 // For casts, we need to handle conversions from arrays to
815 // pointer values, and pointer-to-pointer conversions.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000816 case Stmt::ExplicitCastExprClass:
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000817 case Stmt::ImplicitCastExprClass: {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000818
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000819 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000820 QualType T = SubExpr->getType();
821
Steve Naroffdd972f22008-09-05 22:11:13 +0000822 if (SubExpr->getType()->isPointerType() ||
823 SubExpr->getType()->isBlockPointerType() ||
824 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000825 return EvalAddr(SubExpr);
826 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000827 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000828 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000829 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000830 }
831
832 // C++ casts. For dynamic casts, static casts, and const casts, we
833 // are always converting from a pointer-to-pointer, so we just blow
834 // through the cast. In the case the dynamic cast doesn't fail
835 // (and return NULL), we take the conservative route and report cases
836 // where we return the address of a stack variable. For Reinterpre
837 case Stmt::CXXCastExprClass: {
838 CXXCastExpr *C = cast<CXXCastExpr>(E);
839
840 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
841 Expr *S = C->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000842 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000843 return EvalAddr(S);
844 else
845 return NULL;
846 }
847 else
848 return EvalAddr(C->getSubExpr());
849 }
850
851 // Everything else: we simply don't reason about them.
852 default:
853 return NULL;
854 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000855}
856
857
858/// EvalVal - This function is complements EvalAddr in the mutual recursion.
859/// See the comments for EvalAddr for more details.
860static DeclRefExpr* EvalVal(Expr *E) {
861
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000862 // We should only be called for evaluating non-pointer expressions, or
863 // expressions with a pointer type that are not used as references but instead
864 // are l-values (e.g., DeclRefExpr with a pointer type).
865
Ted Kremenek06de2762007-08-17 16:46:58 +0000866 // Our "symbolic interpreter" is just a dispatch off the currently
867 // viewed AST node. We then recursively traverse the AST by calling
868 // EvalAddr and EvalVal appropriately.
869 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000870 case Stmt::DeclRefExprClass: {
871 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
872 // at code that refers to a variable's name. We check if it has local
873 // storage within the function, and if so, return the expression.
874 DeclRefExpr *DR = cast<DeclRefExpr>(E);
875
876 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
877 if(V->hasLocalStorage()) return DR;
878
879 return NULL;
880 }
881
882 case Stmt::ParenExprClass:
883 // Ignore parentheses.
884 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
885
886 case Stmt::UnaryOperatorClass: {
887 // The only unary operator that make sense to handle here
888 // is Deref. All others don't resolve to a "name." This includes
889 // handling all sorts of rvalues passed to a unary operator.
890 UnaryOperator *U = cast<UnaryOperator>(E);
891
892 if (U->getOpcode() == UnaryOperator::Deref)
893 return EvalAddr(U->getSubExpr());
894
895 return NULL;
896 }
897
898 case Stmt::ArraySubscriptExprClass: {
899 // Array subscripts are potential references to data on the stack. We
900 // retrieve the DeclRefExpr* for the array variable if it indeed
901 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000902 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000903 }
904
905 case Stmt::ConditionalOperatorClass: {
906 // For conditional operators we need to see if either the LHS or RHS are
907 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
908 ConditionalOperator *C = cast<ConditionalOperator>(E);
909
Anders Carlsson39073232007-11-30 19:04:31 +0000910 // Handle the GNU extension for missing LHS.
911 if (Expr *lhsExpr = C->getLHS())
912 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
913 return LHS;
914
915 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000916 }
917
918 // Accesses to members are potential references to data on the stack.
919 case Stmt::MemberExprClass: {
920 MemberExpr *M = cast<MemberExpr>(E);
921
922 // Check for indirect access. We only want direct field accesses.
923 if (!M->isArrow())
924 return EvalVal(M->getBase());
925 else
926 return NULL;
927 }
928
929 // Everything else: we simply don't reason about them.
930 default:
931 return NULL;
932 }
933}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000934
935//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
936
937/// Check for comparisons of floating point operands using != and ==.
938/// Issue a warning if these are no self-comparisons, as they are not likely
939/// to do what the programmer intended.
940void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
941 bool EmitWarning = true;
942
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000943 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000944 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000945
946 // Special case: check for x == x (which is OK).
947 // Do not emit warnings for such cases.
948 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
949 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
950 if (DRL->getDecl() == DRR->getDecl())
951 EmitWarning = false;
952
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000953
954 // Special case: check for comparisons against literals that can be exactly
955 // represented by APFloat. In such cases, do not emit a warning. This
956 // is a heuristic: often comparison against such literals are used to
957 // detect if a value in a variable has not changed. This clearly can
958 // lead to false negatives.
959 if (EmitWarning) {
960 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
961 if (FLL->isExact())
962 EmitWarning = false;
963 }
964 else
965 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
966 if (FLR->isExact())
967 EmitWarning = false;
968 }
969 }
970
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000971 // Check for comparisons with builtin types.
972 if (EmitWarning)
973 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
974 if (isCallBuiltin(CL))
975 EmitWarning = false;
976
977 if (EmitWarning)
978 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
979 if (isCallBuiltin(CR))
980 EmitWarning = false;
981
982 // Emit the diagnostic.
983 if (EmitWarning)
984 Diag(loc, diag::warn_floatingpoint_eq,
985 lex->getSourceRange(),rex->getSourceRange());
986}