blob: 8bb263e84ee4d56abca11ce007a530d35c5a7456 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Ted Kremenek and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringExtras.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000028#include "SemaUtil.h"
29
Chris Lattner59907c42007-08-10 20:18:51 +000030using namespace clang;
31
32/// CheckFunctionCall - Check a direct function call for various correctness
33/// and safety properties not strictly enforced by the C type system.
Anders Carlsson71993dd2007-08-17 05:31:46 +000034bool
Chris Lattner30ce3442007-12-19 23:59:04 +000035Sema::CheckFunctionCall(Expr *Fn, SourceLocation RParenLoc,
Ted Kremenek71895b92007-08-14 17:39:48 +000036 FunctionDecl *FDecl,
Chris Lattner59907c42007-08-10 20:18:51 +000037 Expr** Args, unsigned NumArgsInCall) {
38
39 // Get the IdentifierInfo* for the called function.
40 IdentifierInfo *FnInfo = FDecl->getIdentifier();
41
Chris Lattner30ce3442007-12-19 23:59:04 +000042 switch (FnInfo->getBuiltinID()) {
43 case Builtin::BI__builtin___CFStringMakeConstantString:
Anders Carlsson71993dd2007-08-17 05:31:46 +000044 assert(NumArgsInCall == 1 &&
Chris Lattner6f4b92c2007-08-30 17:08:17 +000045 "Wrong number of arguments to builtin CFStringMakeConstantString");
Anders Carlsson71993dd2007-08-17 05:31:46 +000046 return CheckBuiltinCFStringArgument(Args[0]);
Chris Lattner30ce3442007-12-19 23:59:04 +000047 case Builtin::BI__builtin_va_start:
48 return SemaBuiltinVAStart(Fn, Args, NumArgsInCall);
Anders Carlsson71993dd2007-08-17 05:31:46 +000049 }
50
Chris Lattner59907c42007-08-10 20:18:51 +000051 // Search the KnownFunctionIDs for the identifier.
52 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000053 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +000054 if (i == e) return false;
Chris Lattner59907c42007-08-10 20:18:51 +000055
56 // Printf checking.
57 if (i <= id_vprintf) {
Ted Kremenek71895b92007-08-14 17:39:48 +000058 // Retrieve the index of the format string parameter and determine
59 // if the function is passed a va_arg argument.
Chris Lattner59907c42007-08-10 20:18:51 +000060 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000061 bool HasVAListArg = false;
62
Chris Lattner59907c42007-08-10 20:18:51 +000063 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000064 default: assert(false && "No format string argument index.");
65 case id_printf: format_idx = 0; break;
66 case id_fprintf: format_idx = 1; break;
67 case id_sprintf: format_idx = 1; break;
68 case id_snprintf: format_idx = 2; break;
69 case id_asprintf: format_idx = 1; break;
70 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
71 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
72 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
73 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
74 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek71895b92007-08-14 17:39:48 +000075 }
76
Chris Lattner30ce3442007-12-19 23:59:04 +000077 CheckPrintfArguments(Fn, RParenLoc, HasVAListArg,
Ted Kremenek06de2762007-08-17 16:46:58 +000078 FDecl, format_idx, Args, NumArgsInCall);
Chris Lattner59907c42007-08-10 20:18:51 +000079 }
Anders Carlsson71993dd2007-08-17 05:31:46 +000080
Anders Carlsson9cdc4d32007-08-17 15:44:17 +000081 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +000082}
83
84/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
85/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +000086bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner459e8482007-08-25 05:36:18 +000087 // FIXME: This should go in a helper.
Chris Lattnercc6f65d2007-08-25 05:30:33 +000088 while (1) {
89 if (ParenExpr *PE = dyn_cast<ParenExpr>(Arg))
90 Arg = PE->getSubExpr();
91 else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
92 Arg = ICE->getSubExpr();
93 else
94 break;
95 }
Anders Carlsson71993dd2007-08-17 05:31:46 +000096
97 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
98
99 if (!Literal || Literal->isWide()) {
100 Diag(Arg->getLocStart(),
101 diag::err_cfstring_literal_not_string_constant,
102 Arg->getSourceRange());
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000103 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000104 }
105
106 const char *Data = Literal->getStrData();
107 unsigned Length = Literal->getByteLength();
108
109 for (unsigned i = 0; i < Length; ++i) {
110 if (!isascii(Data[i])) {
111 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
112 diag::warn_cfstring_literal_contains_non_ascii_character,
113 Arg->getSourceRange());
114 break;
115 }
116
117 if (!Data[i]) {
118 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
119 diag::warn_cfstring_literal_contains_nul_character,
120 Arg->getSourceRange());
121 break;
122 }
123 }
124
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000125 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000126}
127
Chris Lattner30ce3442007-12-19 23:59:04 +0000128bool Sema::SemaBuiltinVAStart(Expr *Fn, Expr** Args, unsigned NumArgs) {
129 if (NumArgs > 2) {
130 Diag(Args[2]->getLocStart(),
131 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
132 SourceRange(Args[2]->getLocStart(), Args[NumArgs-1]->getLocEnd()));
133 return true;
134 }
135
136 FunctionTypeProto *Proto;
137 if (CurFunctionDecl)
138 Proto = cast<FunctionTypeProto>(CurFunctionDecl->getType());
139 else
140 Proto =
141 cast<FunctionTypeProto>(ObjcGetTypeForMethodDefinition(CurMethodDecl));
142
143 if (!Proto->isVariadic()) {
144 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
145 return true;
146 }
147
148 // Verify that the second argument to the builtin is the last argument of the
149 // current function or method.
150 bool SecondArgIsLastNamedArgument = false;
151 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Args[1])) {
152 if (ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
153 // FIXME: This isn't correct for methods (results in bogus warning).
154 // Get the last formal in the current function.
155 ParmVarDecl *LastArg;
156 if (CurFunctionDecl)
157 LastArg = *(CurFunctionDecl->param_end()-1);
158 else
159 LastArg = *(CurMethodDecl->param_end()-1);
160 SecondArgIsLastNamedArgument = PV == LastArg;
161 }
162 }
163
164 if (!SecondArgIsLastNamedArgument)
165 Diag(Args[1]->getLocStart(),
166 diag::warn_second_parameter_of_va_start_not_last_named_argument);
167 return false;
168}
169
170
Chris Lattner59907c42007-08-10 20:18:51 +0000171/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000172/// correct use of format strings.
173///
174/// HasVAListArg - A predicate indicating whether the printf-like
175/// function is passed an explicit va_arg argument (e.g., vprintf)
176///
177/// format_idx - The index into Args for the format string.
178///
179/// Improper format strings to functions in the printf family can be
180/// the source of bizarre bugs and very serious security holes. A
181/// good source of information is available in the following paper
182/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000183///
184/// FormatGuard: Automatic Protection From printf Format String
185/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000186///
187/// Functionality implemented:
188///
189/// We can statically check the following properties for string
190/// literal format strings for non v.*printf functions (where the
191/// arguments are passed directly):
192//
193/// (1) Are the number of format conversions equal to the number of
194/// data arguments?
195///
196/// (2) Does each format conversion correctly match the type of the
197/// corresponding data argument? (TODO)
198///
199/// Moreover, for all printf functions we can:
200///
201/// (3) Check for a missing format string (when not caught by type checking).
202///
203/// (4) Check for no-operation flags; e.g. using "#" with format
204/// conversion 'c' (TODO)
205///
206/// (5) Check the use of '%n', a major source of security holes.
207///
208/// (6) Check for malformed format conversions that don't specify anything.
209///
210/// (7) Check for empty format strings. e.g: printf("");
211///
212/// (8) Check that the format string is a wide literal.
213///
214/// All of these checks can be done by parsing the format string.
215///
216/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000217void
Chris Lattner30ce3442007-12-19 23:59:04 +0000218Sema::CheckPrintfArguments(Expr *Fn, SourceLocation RParenLoc,
Ted Kremenek71895b92007-08-14 17:39:48 +0000219 bool HasVAListArg, FunctionDecl *FDecl,
Ted Kremenek82077102007-08-10 21:21:05 +0000220 unsigned format_idx, Expr** Args,
221 unsigned NumArgsInCall) {
Ted Kremenek71895b92007-08-14 17:39:48 +0000222 // CHECK: printf-like function is called with no format string.
223 if (format_idx >= NumArgsInCall) {
224 Diag(RParenLoc, diag::warn_printf_missing_format_string,
225 Fn->getSourceRange());
226 return;
227 }
228
Chris Lattner459e8482007-08-25 05:36:18 +0000229 Expr *OrigFormatExpr = Args[format_idx];
230 // FIXME: This should go in a helper.
231 while (1) {
232 if (ParenExpr *PE = dyn_cast<ParenExpr>(OrigFormatExpr))
233 OrigFormatExpr = PE->getSubExpr();
234 else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(OrigFormatExpr))
235 OrigFormatExpr = ICE->getSubExpr();
236 else
237 break;
238 }
239
Chris Lattner59907c42007-08-10 20:18:51 +0000240 // CHECK: format string is not a string literal.
241 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000242 // Dynamically generated format strings are difficult to
243 // automatically vet at compile time. Requiring that format strings
244 // are string literals: (1) permits the checking of format strings by
245 // the compiler and thereby (2) can practically remove the source of
246 // many format string exploits.
Chris Lattner459e8482007-08-25 05:36:18 +0000247 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Chris Lattner59907c42007-08-10 20:18:51 +0000248
Ted Kremenek71895b92007-08-14 17:39:48 +0000249 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000250 // For vprintf* functions (i.e., HasVAListArg==true), we add a
251 // special check to see if the format string is a function parameter
252 // of the function calling the printf function. If the function
253 // has an attribute indicating it is a printf-like function, then we
254 // should suppress warnings concerning non-literals being used in a call
255 // to a vprintf function. For example:
256 //
257 // void
258 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
259 // va_list ap;
260 // va_start(ap, fmt);
261 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
262 // ...
263 //
264 //
265 // FIXME: We don't have full attribute support yet, so just check to see
266 // if the argument is a DeclRefExpr that references a parameter. We'll
267 // add proper support for checking the attribute later.
268 if (HasVAListArg)
269 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(IgnoreParen(OrigFormatExpr)))
270 if (isa<ParmVarDecl>(DR->getDecl()))
271 return;
272
273 Diag(Args[format_idx]->getLocStart(), diag::warn_printf_not_string_constant,
274 Fn->getSourceRange());
275
Ted Kremenek71895b92007-08-14 17:39:48 +0000276 return;
277 }
278
279 // CHECK: is the format string a wide literal?
280 if (FExpr->isWide()) {
281 Diag(Args[format_idx]->getLocStart(),
282 diag::warn_printf_format_string_is_wide_literal,
283 Fn->getSourceRange());
284 return;
285 }
286
287 // Str - The format string. NOTE: this is NOT null-terminated!
288 const char * const Str = FExpr->getStrData();
289
290 // CHECK: empty format string?
291 const unsigned StrLen = FExpr->getByteLength();
292
293 if (StrLen == 0) {
294 Diag(Args[format_idx]->getLocStart(),
295 diag::warn_printf_empty_format_string, Fn->getSourceRange());
296 return;
297 }
298
299 // We process the format string using a binary state machine. The
300 // current state is stored in CurrentState.
301 enum {
302 state_OrdChr,
303 state_Conversion
304 } CurrentState = state_OrdChr;
305
306 // numConversions - The number of conversions seen so far. This is
307 // incremented as we traverse the format string.
308 unsigned numConversions = 0;
309
310 // numDataArgs - The number of data arguments after the format
311 // string. This can only be determined for non vprintf-like
312 // functions. For those functions, this value is 1 (the sole
313 // va_arg argument).
314 unsigned numDataArgs = NumArgsInCall-(format_idx+1);
315
316 // Inspect the format string.
317 unsigned StrIdx = 0;
318
319 // LastConversionIdx - Index within the format string where we last saw
320 // a '%' character that starts a new format conversion.
321 unsigned LastConversionIdx = 0;
322
323 for ( ; StrIdx < StrLen ; ++StrIdx ) {
324
325 // Is the number of detected conversion conversions greater than
326 // the number of matching data arguments? If so, stop.
327 if (!HasVAListArg && numConversions > numDataArgs) break;
328
329 // Handle "\0"
330 if(Str[StrIdx] == '\0' ) {
331 // The string returned by getStrData() is not null-terminated,
332 // so the presence of a null character is likely an error.
333
334 SourceLocation Loc =
335 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),StrIdx+1);
336
337 Diag(Loc, diag::warn_printf_format_string_contains_null_char,
338 Fn->getSourceRange());
339
340 return;
341 }
342
343 // Ordinary characters (not processing a format conversion).
344 if (CurrentState == state_OrdChr) {
345 if (Str[StrIdx] == '%') {
346 CurrentState = state_Conversion;
347 LastConversionIdx = StrIdx;
348 }
349 continue;
350 }
351
352 // Seen '%'. Now processing a format conversion.
353 switch (Str[StrIdx]) {
Ted Kremenek580b6642007-10-12 20:51:52 +0000354 // Handle dynamic precision or width specifier.
355 case '*': {
356 ++numConversions;
357
358 if (!HasVAListArg && numConversions > numDataArgs) {
359
360 SourceLocation Loc =
361 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
362 StrIdx+1);
363
364 if (Str[StrIdx-1] == '.')
365 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
366 Fn->getSourceRange());
367 else
368 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
369 Fn->getSourceRange());
370
371 // Don't do any more checking. We'll just emit spurious errors.
372 return;
373 }
374
375 // Perform type checking on width/precision specifier.
376 Expr* E = Args[format_idx+numConversions];
377 QualType T = E->getType().getCanonicalType();
378 if (BuiltinType *BT = dyn_cast<BuiltinType>(T))
379 if (BT->getKind() == BuiltinType::Int)
380 break;
381
382 SourceLocation Loc =
383 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
384 StrIdx+1);
385
386 if (Str[StrIdx-1] == '.')
387 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
388 T.getAsString(), E->getSourceRange());
389 else
390 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
391 T.getAsString(), E->getSourceRange());
392
Ted Kremenekbef679c2007-10-12 00:11:27 +0000393 break;
Ted Kremenek580b6642007-10-12 20:51:52 +0000394 }
Ted Kremenekbef679c2007-10-12 00:11:27 +0000395
Ted Kremenek71895b92007-08-14 17:39:48 +0000396 // Characters which can terminate a format conversion
397 // (e.g. "%d"). Characters that specify length modifiers or
398 // other flags are handled by the default case below.
399 //
Ted Kremenekbef679c2007-10-12 00:11:27 +0000400 // FIXME: additional checks will go into the following cases.
Ted Kremenek71895b92007-08-14 17:39:48 +0000401 case 'i':
402 case 'd':
403 case 'o':
404 case 'u':
405 case 'x':
406 case 'X':
407 case 'D':
408 case 'O':
409 case 'U':
410 case 'e':
411 case 'E':
412 case 'f':
413 case 'F':
414 case 'g':
415 case 'G':
416 case 'a':
417 case 'A':
418 case 'c':
419 case 'C':
420 case 'S':
421 case 's':
Chris Lattner5e9885d2007-08-26 17:39:38 +0000422 case 'p':
Ted Kremenek71895b92007-08-14 17:39:48 +0000423 ++numConversions;
424 CurrentState = state_OrdChr;
425 break;
426
427 // CHECK: Are we using "%n"? Issue a warning.
428 case 'n': {
429 ++numConversions;
430 CurrentState = state_OrdChr;
431 SourceLocation Loc =
432 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
433 LastConversionIdx+1);
434
435 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
436 break;
437 }
438
439 // Handle "%%"
440 case '%':
441 // Sanity check: Was the first "%" character the previous one?
442 // If not, we will assume that we have a malformed format
443 // conversion, and that the current "%" character is the start
444 // of a new conversion.
445 if (StrIdx - LastConversionIdx == 1)
446 CurrentState = state_OrdChr;
447 else {
448 // Issue a warning: invalid format conversion.
449 SourceLocation Loc =
450 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
451 LastConversionIdx+1);
452
453 Diag(Loc, diag::warn_printf_invalid_conversion,
Ted Kremenek580b6642007-10-12 20:51:52 +0000454 std::string(Str+LastConversionIdx, Str+StrIdx),
Ted Kremenek71895b92007-08-14 17:39:48 +0000455 Fn->getSourceRange());
456
457 // This conversion is broken. Advance to the next format
458 // conversion.
459 LastConversionIdx = StrIdx;
460 ++numConversions;
461 }
462
463 break;
464
465 default:
466 // This case catches all other characters: flags, widths, etc.
467 // We should eventually process those as well.
468 break;
469 }
470 }
471
472 if (CurrentState == state_Conversion) {
473 // Issue a warning: invalid format conversion.
474 SourceLocation Loc =
475 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
476 LastConversionIdx+1);
477
478 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000479 std::string(Str+LastConversionIdx,
480 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek71895b92007-08-14 17:39:48 +0000481 Fn->getSourceRange());
482 return;
483 }
484
485 if (!HasVAListArg) {
486 // CHECK: Does the number of format conversions exceed the number
487 // of data arguments?
488 if (numConversions > numDataArgs) {
489 SourceLocation Loc =
490 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
491 LastConversionIdx);
492
493 Diag(Loc, diag::warn_printf_insufficient_data_args,
494 Fn->getSourceRange());
495 }
496 // CHECK: Does the number of data arguments exceed the number of
497 // format conversions in the format string?
498 else if (numConversions < numDataArgs)
499 Diag(Args[format_idx+numConversions+1]->getLocStart(),
500 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
501 }
502}
Ted Kremenek06de2762007-08-17 16:46:58 +0000503
504//===--- CHECK: Return Address of Stack Variable --------------------------===//
505
506static DeclRefExpr* EvalVal(Expr *E);
507static DeclRefExpr* EvalAddr(Expr* E);
508
509/// CheckReturnStackAddr - Check if a return statement returns the address
510/// of a stack variable.
511void
512Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
513 SourceLocation ReturnLoc) {
514
515 // Perform checking for returned stack addresses.
516 if (lhsType->isPointerType()) {
517 if (DeclRefExpr *DR = EvalAddr(RetValExp))
518 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
519 DR->getDecl()->getIdentifier()->getName(),
520 RetValExp->getSourceRange());
521 }
522 // Perform checking for stack values returned by reference.
523 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000524 // Check for an implicit cast to a reference.
525 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
526 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
527 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
528 DR->getDecl()->getIdentifier()->getName(),
529 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000530 }
531}
532
533/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
534/// check if the expression in a return statement evaluates to an address
535/// to a location on the stack. The recursion is used to traverse the
536/// AST of the return expression, with recursion backtracking when we
537/// encounter a subexpression that (1) clearly does not lead to the address
538/// of a stack variable or (2) is something we cannot determine leads to
539/// the address of a stack variable based on such local checking.
540///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000541/// EvalAddr processes expressions that are pointers that are used as
542/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000543/// At the base case of the recursion is a check for a DeclRefExpr* in
544/// the refers to a stack variable.
545///
546/// This implementation handles:
547///
548/// * pointer-to-pointer casts
549/// * implicit conversions from array references to pointers
550/// * taking the address of fields
551/// * arbitrary interplay between "&" and "*" operators
552/// * pointer arithmetic from an address of a stack variable
553/// * taking the address of an array element where the array is on the stack
554static DeclRefExpr* EvalAddr(Expr *E) {
555
556 // We should only be called for evaluating pointer expressions.
557 assert (E->getType()->isPointerType() && "EvalAddr only works on pointers");
558
559 // Our "symbolic interpreter" is just a dispatch off the currently
560 // viewed AST node. We then recursively traverse the AST by calling
561 // EvalAddr and EvalVal appropriately.
562 switch (E->getStmtClass()) {
563
564 case Stmt::ParenExprClass:
565 // Ignore parentheses.
566 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
567
568 case Stmt::UnaryOperatorClass: {
569 // The only unary operator that make sense to handle here
570 // is AddrOf. All others don't make sense as pointers.
571 UnaryOperator *U = cast<UnaryOperator>(E);
572
573 if (U->getOpcode() == UnaryOperator::AddrOf)
574 return EvalVal(U->getSubExpr());
575 else
576 return NULL;
577 }
578
579 case Stmt::BinaryOperatorClass: {
580 // Handle pointer arithmetic. All other binary operators are not valid
581 // in this context.
582 BinaryOperator *B = cast<BinaryOperator>(E);
583 BinaryOperator::Opcode op = B->getOpcode();
584
585 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
586 return NULL;
587
588 Expr *Base = B->getLHS();
589
590 // Determine which argument is the real pointer base. It could be
591 // the RHS argument instead of the LHS.
592 if (!Base->getType()->isPointerType()) Base = B->getRHS();
593
594 assert (Base->getType()->isPointerType());
595 return EvalAddr(Base);
596 }
597
598 // For conditional operators we need to see if either the LHS or RHS are
599 // valid DeclRefExpr*s. If one of them is valid, we return it.
600 case Stmt::ConditionalOperatorClass: {
601 ConditionalOperator *C = cast<ConditionalOperator>(E);
602
Anders Carlsson39073232007-11-30 19:04:31 +0000603 // Handle the GNU extension for missing LHS.
604 if (Expr *lhsExpr = C->getLHS())
605 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
606 return LHS;
607
608 return EvalAddr(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000609 }
610
611 // For implicit casts, we need to handle conversions from arrays to
612 // pointer values, and implicit pointer-to-pointer conversions.
613 case Stmt::ImplicitCastExprClass: {
614 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
615 Expr* SubExpr = IE->getSubExpr();
616
617 if (SubExpr->getType()->isPointerType())
618 return EvalAddr(SubExpr);
619 else
620 return EvalVal(SubExpr);
621 }
622
623 // For casts, we handle pointer-to-pointer conversions (which
624 // is essentially a no-op from our mini-interpreter's standpoint).
625 // For other casts we abort.
626 case Stmt::CastExprClass: {
627 CastExpr *C = cast<CastExpr>(E);
628 Expr *SubExpr = C->getSubExpr();
629
630 if (SubExpr->getType()->isPointerType())
631 return EvalAddr(SubExpr);
632 else
633 return NULL;
634 }
635
Ted Kremenek23245122007-08-20 16:18:38 +0000636 // C++ casts. For dynamic casts, static casts, and const casts, we
637 // are always converting from a pointer-to-pointer, so we just blow
638 // through the cast. In the case the dynamic cast doesn't fail
639 // (and return NULL), we take the conservative route and report cases
640 // where we return the address of a stack variable. For Reinterpre
641 case Stmt::CXXCastExprClass: {
642 CXXCastExpr *C = cast<CXXCastExpr>(E);
643
644 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
645 Expr *S = C->getSubExpr();
646 if (S->getType()->isPointerType())
647 return EvalAddr(S);
648 else
649 return NULL;
650 }
651 else
652 return EvalAddr(C->getSubExpr());
653 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000654
655 // Everything else: we simply don't reason about them.
656 default:
657 return NULL;
658 }
659}
660
661
662/// EvalVal - This function is complements EvalAddr in the mutual recursion.
663/// See the comments for EvalAddr for more details.
664static DeclRefExpr* EvalVal(Expr *E) {
665
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000666 // We should only be called for evaluating non-pointer expressions, or
667 // expressions with a pointer type that are not used as references but instead
668 // are l-values (e.g., DeclRefExpr with a pointer type).
669
Ted Kremenek06de2762007-08-17 16:46:58 +0000670 // Our "symbolic interpreter" is just a dispatch off the currently
671 // viewed AST node. We then recursively traverse the AST by calling
672 // EvalAddr and EvalVal appropriately.
673 switch (E->getStmtClass()) {
674
675 case Stmt::DeclRefExprClass: {
676 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
677 // at code that refers to a variable's name. We check if it has local
678 // storage within the function, and if so, return the expression.
679 DeclRefExpr *DR = cast<DeclRefExpr>(E);
680
681 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
682 if(V->hasLocalStorage()) return DR;
683
684 return NULL;
685 }
686
687 case Stmt::ParenExprClass:
688 // Ignore parentheses.
689 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
690
691 case Stmt::UnaryOperatorClass: {
692 // The only unary operator that make sense to handle here
693 // is Deref. All others don't resolve to a "name." This includes
694 // handling all sorts of rvalues passed to a unary operator.
695 UnaryOperator *U = cast<UnaryOperator>(E);
696
697 if (U->getOpcode() == UnaryOperator::Deref)
698 return EvalAddr(U->getSubExpr());
699
700 return NULL;
701 }
702
703 case Stmt::ArraySubscriptExprClass: {
704 // Array subscripts are potential references to data on the stack. We
705 // retrieve the DeclRefExpr* for the array variable if it indeed
706 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000707 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000708 }
709
710 case Stmt::ConditionalOperatorClass: {
711 // For conditional operators we need to see if either the LHS or RHS are
712 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
713 ConditionalOperator *C = cast<ConditionalOperator>(E);
714
Anders Carlsson39073232007-11-30 19:04:31 +0000715 // Handle the GNU extension for missing LHS.
716 if (Expr *lhsExpr = C->getLHS())
717 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
718 return LHS;
719
720 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000721 }
722
723 // Accesses to members are potential references to data on the stack.
724 case Stmt::MemberExprClass: {
725 MemberExpr *M = cast<MemberExpr>(E);
726
727 // Check for indirect access. We only want direct field accesses.
728 if (!M->isArrow())
729 return EvalVal(M->getBase());
730 else
731 return NULL;
732 }
733
734 // Everything else: we simply don't reason about them.
735 default:
736 return NULL;
737 }
738}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000739
740//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
741
742/// Check for comparisons of floating point operands using != and ==.
743/// Issue a warning if these are no self-comparisons, as they are not likely
744/// to do what the programmer intended.
745void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
746 bool EmitWarning = true;
747
748 Expr* LeftExprSansParen = IgnoreParen(lex);
749 Expr* RightExprSansParen = IgnoreParen(rex);
750
751 // Special case: check for x == x (which is OK).
752 // Do not emit warnings for such cases.
753 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
754 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
755 if (DRL->getDecl() == DRR->getDecl())
756 EmitWarning = false;
757
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000758
759 // Special case: check for comparisons against literals that can be exactly
760 // represented by APFloat. In such cases, do not emit a warning. This
761 // is a heuristic: often comparison against such literals are used to
762 // detect if a value in a variable has not changed. This clearly can
763 // lead to false negatives.
764 if (EmitWarning) {
765 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
766 if (FLL->isExact())
767 EmitWarning = false;
768 }
769 else
770 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
771 if (FLR->isExact())
772 EmitWarning = false;
773 }
774 }
775
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000776 // Check for comparisons with builtin types.
777 if (EmitWarning)
778 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
779 if (isCallBuiltin(CL))
780 EmitWarning = false;
781
782 if (EmitWarning)
783 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
784 if (isCallBuiltin(CR))
785 EmitWarning = false;
786
787 // Emit the diagnostic.
788 if (EmitWarning)
789 Diag(loc, diag::warn_floatingpoint_eq,
790 lex->getSourceRange(),rex->getSourceRange());
791}