blob: 09304399e97f27c39525fb96f6bb2aa89d5623b0 [file] [log] [blame]
Chris Lattner2e64c072007-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 Kremenek1c1700f2007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner2e64c072007-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 Kremenek30c66752007-11-25 00:58:00 +000028#include "SemaUtil.h"
29
Chris Lattner2e64c072007-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 Carlssone7e7aa22007-08-17 05:31:46 +000034bool
Chris Lattnerf22a8502007-12-19 23:59:04 +000035Sema::CheckFunctionCall(Expr *Fn, SourceLocation RParenLoc,
Chris Lattner7c8d1af2007-12-20 00:26:33 +000036 FunctionDecl *FDecl, Expr** Args, unsigned NumArgs) {
Chris Lattner2e64c072007-08-10 20:18:51 +000037
38 // Get the IdentifierInfo* for the called function.
39 IdentifierInfo *FnInfo = FDecl->getIdentifier();
40
Chris Lattnerf22a8502007-12-19 23:59:04 +000041 switch (FnInfo->getBuiltinID()) {
42 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner7c8d1af2007-12-20 00:26:33 +000043 assert(NumArgs == 1 &&
44 "Wrong # arguments to builtin CFStringMakeConstantString");
Anders Carlssone7e7aa22007-08-17 05:31:46 +000045 return CheckBuiltinCFStringArgument(Args[0]);
Chris Lattnerf22a8502007-12-19 23:59:04 +000046 case Builtin::BI__builtin_va_start:
Chris Lattner7c8d1af2007-12-20 00:26:33 +000047 return SemaBuiltinVAStart(Fn, Args, NumArgs);
48
49 case Builtin::BI__builtin_isgreater:
50 case Builtin::BI__builtin_isgreaterequal:
51 case Builtin::BI__builtin_isless:
52 case Builtin::BI__builtin_islessequal:
53 case Builtin::BI__builtin_islessgreater:
54 case Builtin::BI__builtin_isunordered:
55 return SemaBuiltinUnorderedCompare(Fn, Args, NumArgs, RParenLoc);
Anders Carlssone7e7aa22007-08-17 05:31:46 +000056 }
57
Chris Lattner2e64c072007-08-10 20:18:51 +000058 // Search the KnownFunctionIDs for the identifier.
59 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek081ed872007-08-14 17:39:48 +000060 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Anders Carlsson3e9b43b2007-08-17 15:44:17 +000061 if (i == e) return false;
Chris Lattner2e64c072007-08-10 20:18:51 +000062
63 // Printf checking.
64 if (i <= id_vprintf) {
Ted Kremenek081ed872007-08-14 17:39:48 +000065 // Retrieve the index of the format string parameter and determine
66 // if the function is passed a va_arg argument.
Chris Lattner2e64c072007-08-10 20:18:51 +000067 unsigned format_idx = 0;
Ted Kremenek081ed872007-08-14 17:39:48 +000068 bool HasVAListArg = false;
69
Chris Lattner2e64c072007-08-10 20:18:51 +000070 switch (i) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000071 default: assert(false && "No format string argument index.");
72 case id_printf: format_idx = 0; break;
73 case id_fprintf: format_idx = 1; break;
74 case id_sprintf: format_idx = 1; break;
75 case id_snprintf: format_idx = 2; break;
76 case id_asprintf: format_idx = 1; break;
77 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
78 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
79 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
80 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
81 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek081ed872007-08-14 17:39:48 +000082 }
83
Chris Lattnerf22a8502007-12-19 23:59:04 +000084 CheckPrintfArguments(Fn, RParenLoc, HasVAListArg,
Chris Lattner7c8d1af2007-12-20 00:26:33 +000085 FDecl, format_idx, Args, NumArgs);
Chris Lattner2e64c072007-08-10 20:18:51 +000086 }
Anders Carlssone7e7aa22007-08-17 05:31:46 +000087
Anders Carlsson3e9b43b2007-08-17 15:44:17 +000088 return false;
Anders Carlssone7e7aa22007-08-17 05:31:46 +000089}
90
91/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
92/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +000093bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattnere65acc12007-08-25 05:36:18 +000094 // FIXME: This should go in a helper.
Chris Lattnerda050402007-08-25 05:30:33 +000095 while (1) {
96 if (ParenExpr *PE = dyn_cast<ParenExpr>(Arg))
97 Arg = PE->getSubExpr();
98 else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
99 Arg = ICE->getSubExpr();
100 else
101 break;
102 }
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000103
104 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
105
106 if (!Literal || Literal->isWide()) {
107 Diag(Arg->getLocStart(),
108 diag::err_cfstring_literal_not_string_constant,
109 Arg->getSourceRange());
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000110 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000111 }
112
113 const char *Data = Literal->getStrData();
114 unsigned Length = Literal->getByteLength();
115
116 for (unsigned i = 0; i < Length; ++i) {
117 if (!isascii(Data[i])) {
118 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
119 diag::warn_cfstring_literal_contains_non_ascii_character,
120 Arg->getSourceRange());
121 break;
122 }
123
124 if (!Data[i]) {
125 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
126 diag::warn_cfstring_literal_contains_nul_character,
127 Arg->getSourceRange());
128 break;
129 }
130 }
131
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000132 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000133}
134
Chris Lattner3b933692007-12-20 00:05:45 +0000135/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
136/// Emit an error and return true on failure, return false on success.
Chris Lattnerf22a8502007-12-19 23:59:04 +0000137bool Sema::SemaBuiltinVAStart(Expr *Fn, Expr** Args, unsigned NumArgs) {
138 if (NumArgs > 2) {
139 Diag(Args[2]->getLocStart(),
140 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
141 SourceRange(Args[2]->getLocStart(), Args[NumArgs-1]->getLocEnd()));
142 return true;
143 }
144
Chris Lattner3b933692007-12-20 00:05:45 +0000145 // Determine whether the current function is variadic or not.
146 bool isVariadic;
Chris Lattnerf22a8502007-12-19 23:59:04 +0000147 if (CurFunctionDecl)
Chris Lattner3b933692007-12-20 00:05:45 +0000148 isVariadic =
149 cast<FunctionTypeProto>(CurFunctionDecl->getType())->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000150 else
Chris Lattner3b933692007-12-20 00:05:45 +0000151 isVariadic = CurMethodDecl->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000152
Chris Lattner3b933692007-12-20 00:05:45 +0000153 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000154 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
155 return true;
156 }
157
158 // Verify that the second argument to the builtin is the last argument of the
159 // current function or method.
160 bool SecondArgIsLastNamedArgument = false;
161 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Args[1])) {
162 if (ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
163 // FIXME: This isn't correct for methods (results in bogus warning).
164 // Get the last formal in the current function.
165 ParmVarDecl *LastArg;
166 if (CurFunctionDecl)
167 LastArg = *(CurFunctionDecl->param_end()-1);
168 else
169 LastArg = *(CurMethodDecl->param_end()-1);
170 SecondArgIsLastNamedArgument = PV == LastArg;
171 }
172 }
173
174 if (!SecondArgIsLastNamedArgument)
175 Diag(Args[1]->getLocStart(),
176 diag::warn_second_parameter_of_va_start_not_last_named_argument);
177 return false;
178}
179
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000180/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
181/// friends. This is declared to take (...), so we have to check everything.
182bool Sema::SemaBuiltinUnorderedCompare(Expr *Fn, Expr** Args, unsigned NumArgs,
183 SourceLocation RParenLoc) {
184 if (NumArgs < 2)
185 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args);
186 if (NumArgs > 2)
187 return Diag(Args[2]->getLocStart(), diag::err_typecheck_call_too_many_args,
188 SourceRange(Args[2]->getLocStart(),
189 Args[NumArgs-1]->getLocEnd()));
190
191 Expr *OrigArg0 = Args[0];
192 Expr *OrigArg1 = Args[1];
193
194 // Do standard promotions between the two arguments, returning their common
195 // type.
196 QualType Res = UsualArithmeticConversions(Args[0], Args[1], false);
197
198 // If the common type isn't a real floating type, then the arguments were
199 // invalid for this operation.
200 if (!Res->isRealFloatingType())
201 return Diag(Args[0]->getLocStart(),
202 diag::err_typecheck_call_invalid_ordered_compare,
203 OrigArg0->getType().getAsString(),
204 OrigArg1->getType().getAsString(),
205 SourceRange(Args[0]->getLocStart(), Args[1]->getLocEnd()));
206
207 return false;
208}
209
Chris Lattnerf22a8502007-12-19 23:59:04 +0000210
Chris Lattner2e64c072007-08-10 20:18:51 +0000211/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000212/// correct use of format strings.
213///
214/// HasVAListArg - A predicate indicating whether the printf-like
215/// function is passed an explicit va_arg argument (e.g., vprintf)
216///
217/// format_idx - The index into Args for the format string.
218///
219/// Improper format strings to functions in the printf family can be
220/// the source of bizarre bugs and very serious security holes. A
221/// good source of information is available in the following paper
222/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000223///
224/// FormatGuard: Automatic Protection From printf Format String
225/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000226///
227/// Functionality implemented:
228///
229/// We can statically check the following properties for string
230/// literal format strings for non v.*printf functions (where the
231/// arguments are passed directly):
232//
233/// (1) Are the number of format conversions equal to the number of
234/// data arguments?
235///
236/// (2) Does each format conversion correctly match the type of the
237/// corresponding data argument? (TODO)
238///
239/// Moreover, for all printf functions we can:
240///
241/// (3) Check for a missing format string (when not caught by type checking).
242///
243/// (4) Check for no-operation flags; e.g. using "#" with format
244/// conversion 'c' (TODO)
245///
246/// (5) Check the use of '%n', a major source of security holes.
247///
248/// (6) Check for malformed format conversions that don't specify anything.
249///
250/// (7) Check for empty format strings. e.g: printf("");
251///
252/// (8) Check that the format string is a wide literal.
253///
254/// All of these checks can be done by parsing the format string.
255///
256/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000257void
Chris Lattnerf22a8502007-12-19 23:59:04 +0000258Sema::CheckPrintfArguments(Expr *Fn, SourceLocation RParenLoc,
Ted Kremenek081ed872007-08-14 17:39:48 +0000259 bool HasVAListArg, FunctionDecl *FDecl,
Ted Kremenek30596542007-08-10 21:21:05 +0000260 unsigned format_idx, Expr** Args,
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000261 unsigned NumArgs) {
Ted Kremenek081ed872007-08-14 17:39:48 +0000262 // CHECK: printf-like function is called with no format string.
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000263 if (format_idx >= NumArgs) {
Ted Kremenek081ed872007-08-14 17:39:48 +0000264 Diag(RParenLoc, diag::warn_printf_missing_format_string,
265 Fn->getSourceRange());
266 return;
267 }
268
Chris Lattnere65acc12007-08-25 05:36:18 +0000269 Expr *OrigFormatExpr = Args[format_idx];
270 // FIXME: This should go in a helper.
271 while (1) {
272 if (ParenExpr *PE = dyn_cast<ParenExpr>(OrigFormatExpr))
273 OrigFormatExpr = PE->getSubExpr();
274 else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(OrigFormatExpr))
275 OrigFormatExpr = ICE->getSubExpr();
276 else
277 break;
278 }
279
Chris Lattner2e64c072007-08-10 20:18:51 +0000280 // CHECK: format string is not a string literal.
281 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000282 // Dynamically generated format strings are difficult to
283 // automatically vet at compile time. Requiring that format strings
284 // are string literals: (1) permits the checking of format strings by
285 // the compiler and thereby (2) can practically remove the source of
286 // many format string exploits.
Chris Lattnere65acc12007-08-25 05:36:18 +0000287 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Chris Lattner2e64c072007-08-10 20:18:51 +0000288
Ted Kremenek081ed872007-08-14 17:39:48 +0000289 if (FExpr == NULL) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000290 // For vprintf* functions (i.e., HasVAListArg==true), we add a
291 // special check to see if the format string is a function parameter
292 // of the function calling the printf function. If the function
293 // has an attribute indicating it is a printf-like function, then we
294 // should suppress warnings concerning non-literals being used in a call
295 // to a vprintf function. For example:
296 //
297 // void
298 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
299 // va_list ap;
300 // va_start(ap, fmt);
301 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
302 // ...
303 //
304 //
305 // FIXME: We don't have full attribute support yet, so just check to see
306 // if the argument is a DeclRefExpr that references a parameter. We'll
307 // add proper support for checking the attribute later.
308 if (HasVAListArg)
309 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(IgnoreParen(OrigFormatExpr)))
310 if (isa<ParmVarDecl>(DR->getDecl()))
311 return;
312
313 Diag(Args[format_idx]->getLocStart(), diag::warn_printf_not_string_constant,
314 Fn->getSourceRange());
315
Ted Kremenek081ed872007-08-14 17:39:48 +0000316 return;
317 }
318
319 // CHECK: is the format string a wide literal?
320 if (FExpr->isWide()) {
321 Diag(Args[format_idx]->getLocStart(),
322 diag::warn_printf_format_string_is_wide_literal,
323 Fn->getSourceRange());
324 return;
325 }
326
327 // Str - The format string. NOTE: this is NOT null-terminated!
328 const char * const Str = FExpr->getStrData();
329
330 // CHECK: empty format string?
331 const unsigned StrLen = FExpr->getByteLength();
332
333 if (StrLen == 0) {
334 Diag(Args[format_idx]->getLocStart(),
335 diag::warn_printf_empty_format_string, Fn->getSourceRange());
336 return;
337 }
338
339 // We process the format string using a binary state machine. The
340 // current state is stored in CurrentState.
341 enum {
342 state_OrdChr,
343 state_Conversion
344 } CurrentState = state_OrdChr;
345
346 // numConversions - The number of conversions seen so far. This is
347 // incremented as we traverse the format string.
348 unsigned numConversions = 0;
349
350 // numDataArgs - The number of data arguments after the format
351 // string. This can only be determined for non vprintf-like
352 // functions. For those functions, this value is 1 (the sole
353 // va_arg argument).
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000354 unsigned numDataArgs = NumArgs-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000355
356 // Inspect the format string.
357 unsigned StrIdx = 0;
358
359 // LastConversionIdx - Index within the format string where we last saw
360 // a '%' character that starts a new format conversion.
361 unsigned LastConversionIdx = 0;
362
363 for ( ; StrIdx < StrLen ; ++StrIdx ) {
364
365 // Is the number of detected conversion conversions greater than
366 // the number of matching data arguments? If so, stop.
367 if (!HasVAListArg && numConversions > numDataArgs) break;
368
369 // Handle "\0"
370 if(Str[StrIdx] == '\0' ) {
371 // The string returned by getStrData() is not null-terminated,
372 // so the presence of a null character is likely an error.
373
374 SourceLocation Loc =
375 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),StrIdx+1);
376
377 Diag(Loc, diag::warn_printf_format_string_contains_null_char,
378 Fn->getSourceRange());
379
380 return;
381 }
382
383 // Ordinary characters (not processing a format conversion).
384 if (CurrentState == state_OrdChr) {
385 if (Str[StrIdx] == '%') {
386 CurrentState = state_Conversion;
387 LastConversionIdx = StrIdx;
388 }
389 continue;
390 }
391
392 // Seen '%'. Now processing a format conversion.
393 switch (Str[StrIdx]) {
Ted Kremenek035d8792007-10-12 20:51:52 +0000394 // Handle dynamic precision or width specifier.
395 case '*': {
396 ++numConversions;
397
398 if (!HasVAListArg && numConversions > numDataArgs) {
399
400 SourceLocation Loc =
401 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
402 StrIdx+1);
403
404 if (Str[StrIdx-1] == '.')
405 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
406 Fn->getSourceRange());
407 else
408 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
409 Fn->getSourceRange());
410
411 // Don't do any more checking. We'll just emit spurious errors.
412 return;
413 }
414
415 // Perform type checking on width/precision specifier.
416 Expr* E = Args[format_idx+numConversions];
417 QualType T = E->getType().getCanonicalType();
418 if (BuiltinType *BT = dyn_cast<BuiltinType>(T))
419 if (BT->getKind() == BuiltinType::Int)
420 break;
421
422 SourceLocation Loc =
423 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
424 StrIdx+1);
425
426 if (Str[StrIdx-1] == '.')
427 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
428 T.getAsString(), E->getSourceRange());
429 else
430 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
431 T.getAsString(), E->getSourceRange());
432
Ted Kremenek42166a82007-10-12 00:11:27 +0000433 break;
Ted Kremenek035d8792007-10-12 20:51:52 +0000434 }
Ted Kremenek42166a82007-10-12 00:11:27 +0000435
Ted Kremenek081ed872007-08-14 17:39:48 +0000436 // Characters which can terminate a format conversion
437 // (e.g. "%d"). Characters that specify length modifiers or
438 // other flags are handled by the default case below.
439 //
Ted Kremenek42166a82007-10-12 00:11:27 +0000440 // FIXME: additional checks will go into the following cases.
Ted Kremenek081ed872007-08-14 17:39:48 +0000441 case 'i':
442 case 'd':
443 case 'o':
444 case 'u':
445 case 'x':
446 case 'X':
447 case 'D':
448 case 'O':
449 case 'U':
450 case 'e':
451 case 'E':
452 case 'f':
453 case 'F':
454 case 'g':
455 case 'G':
456 case 'a':
457 case 'A':
458 case 'c':
459 case 'C':
460 case 'S':
461 case 's':
Chris Lattner04e04642007-08-26 17:39:38 +0000462 case 'p':
Ted Kremenek081ed872007-08-14 17:39:48 +0000463 ++numConversions;
464 CurrentState = state_OrdChr;
465 break;
466
467 // CHECK: Are we using "%n"? Issue a warning.
468 case 'n': {
469 ++numConversions;
470 CurrentState = state_OrdChr;
471 SourceLocation Loc =
472 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
473 LastConversionIdx+1);
474
475 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
476 break;
477 }
478
479 // Handle "%%"
480 case '%':
481 // Sanity check: Was the first "%" character the previous one?
482 // If not, we will assume that we have a malformed format
483 // conversion, and that the current "%" character is the start
484 // of a new conversion.
485 if (StrIdx - LastConversionIdx == 1)
486 CurrentState = state_OrdChr;
487 else {
488 // Issue a warning: invalid format conversion.
489 SourceLocation Loc =
490 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
491 LastConversionIdx+1);
492
493 Diag(Loc, diag::warn_printf_invalid_conversion,
Ted Kremenek035d8792007-10-12 20:51:52 +0000494 std::string(Str+LastConversionIdx, Str+StrIdx),
Ted Kremenek081ed872007-08-14 17:39:48 +0000495 Fn->getSourceRange());
496
497 // This conversion is broken. Advance to the next format
498 // conversion.
499 LastConversionIdx = StrIdx;
500 ++numConversions;
501 }
502
503 break;
504
505 default:
506 // This case catches all other characters: flags, widths, etc.
507 // We should eventually process those as well.
508 break;
509 }
510 }
511
512 if (CurrentState == state_Conversion) {
513 // Issue a warning: invalid format conversion.
514 SourceLocation Loc =
515 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
516 LastConversionIdx+1);
517
518 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattner6f65d202007-08-26 17:38:22 +0000519 std::string(Str+LastConversionIdx,
520 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek081ed872007-08-14 17:39:48 +0000521 Fn->getSourceRange());
522 return;
523 }
524
525 if (!HasVAListArg) {
526 // CHECK: Does the number of format conversions exceed the number
527 // of data arguments?
528 if (numConversions > numDataArgs) {
529 SourceLocation Loc =
530 PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),
531 LastConversionIdx);
532
533 Diag(Loc, diag::warn_printf_insufficient_data_args,
534 Fn->getSourceRange());
535 }
536 // CHECK: Does the number of data arguments exceed the number of
537 // format conversions in the format string?
538 else if (numConversions < numDataArgs)
539 Diag(Args[format_idx+numConversions+1]->getLocStart(),
540 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
541 }
542}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000543
544//===--- CHECK: Return Address of Stack Variable --------------------------===//
545
546static DeclRefExpr* EvalVal(Expr *E);
547static DeclRefExpr* EvalAddr(Expr* E);
548
549/// CheckReturnStackAddr - Check if a return statement returns the address
550/// of a stack variable.
551void
552Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
553 SourceLocation ReturnLoc) {
554
555 // Perform checking for returned stack addresses.
556 if (lhsType->isPointerType()) {
557 if (DeclRefExpr *DR = EvalAddr(RetValExp))
558 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
559 DR->getDecl()->getIdentifier()->getName(),
560 RetValExp->getSourceRange());
561 }
562 // Perform checking for stack values returned by reference.
563 else if (lhsType->isReferenceType()) {
Ted Kremenek1456f202007-08-27 16:39:17 +0000564 // Check for an implicit cast to a reference.
565 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
566 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
567 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
568 DR->getDecl()->getIdentifier()->getName(),
569 RetValExp->getSourceRange());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000570 }
571}
572
573/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
574/// check if the expression in a return statement evaluates to an address
575/// to a location on the stack. The recursion is used to traverse the
576/// AST of the return expression, with recursion backtracking when we
577/// encounter a subexpression that (1) clearly does not lead to the address
578/// of a stack variable or (2) is something we cannot determine leads to
579/// the address of a stack variable based on such local checking.
580///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000581/// EvalAddr processes expressions that are pointers that are used as
582/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000583/// At the base case of the recursion is a check for a DeclRefExpr* in
584/// the refers to a stack variable.
585///
586/// This implementation handles:
587///
588/// * pointer-to-pointer casts
589/// * implicit conversions from array references to pointers
590/// * taking the address of fields
591/// * arbitrary interplay between "&" and "*" operators
592/// * pointer arithmetic from an address of a stack variable
593/// * taking the address of an array element where the array is on the stack
594static DeclRefExpr* EvalAddr(Expr *E) {
595
596 // We should only be called for evaluating pointer expressions.
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +0000597 assert ((E->getType()->isPointerType() ||
598 E->getType()->isObjcQualifiedIdType())
599 && "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000600
601 // Our "symbolic interpreter" is just a dispatch off the currently
602 // viewed AST node. We then recursively traverse the AST by calling
603 // EvalAddr and EvalVal appropriately.
604 switch (E->getStmtClass()) {
605
606 case Stmt::ParenExprClass:
607 // Ignore parentheses.
608 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
609
610 case Stmt::UnaryOperatorClass: {
611 // The only unary operator that make sense to handle here
612 // is AddrOf. All others don't make sense as pointers.
613 UnaryOperator *U = cast<UnaryOperator>(E);
614
615 if (U->getOpcode() == UnaryOperator::AddrOf)
616 return EvalVal(U->getSubExpr());
617 else
618 return NULL;
619 }
620
621 case Stmt::BinaryOperatorClass: {
622 // Handle pointer arithmetic. All other binary operators are not valid
623 // in this context.
624 BinaryOperator *B = cast<BinaryOperator>(E);
625 BinaryOperator::Opcode op = B->getOpcode();
626
627 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
628 return NULL;
629
630 Expr *Base = B->getLHS();
631
632 // Determine which argument is the real pointer base. It could be
633 // the RHS argument instead of the LHS.
634 if (!Base->getType()->isPointerType()) Base = B->getRHS();
635
636 assert (Base->getType()->isPointerType());
637 return EvalAddr(Base);
638 }
639
640 // For conditional operators we need to see if either the LHS or RHS are
641 // valid DeclRefExpr*s. If one of them is valid, we return it.
642 case Stmt::ConditionalOperatorClass: {
643 ConditionalOperator *C = cast<ConditionalOperator>(E);
644
Anders Carlsson37365fc2007-11-30 19:04:31 +0000645 // Handle the GNU extension for missing LHS.
646 if (Expr *lhsExpr = C->getLHS())
647 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
648 return LHS;
649
650 return EvalAddr(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000651 }
652
653 // For implicit casts, we need to handle conversions from arrays to
654 // pointer values, and implicit pointer-to-pointer conversions.
655 case Stmt::ImplicitCastExprClass: {
656 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
657 Expr* SubExpr = IE->getSubExpr();
658
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +0000659 if (SubExpr->getType()->isPointerType() ||
660 SubExpr->getType()->isObjcQualifiedIdType())
Ted Kremenek45925ab2007-08-17 16:46:58 +0000661 return EvalAddr(SubExpr);
662 else
663 return EvalVal(SubExpr);
664 }
665
666 // For casts, we handle pointer-to-pointer conversions (which
667 // is essentially a no-op from our mini-interpreter's standpoint).
668 // For other casts we abort.
669 case Stmt::CastExprClass: {
670 CastExpr *C = cast<CastExpr>(E);
671 Expr *SubExpr = C->getSubExpr();
672
673 if (SubExpr->getType()->isPointerType())
674 return EvalAddr(SubExpr);
675 else
676 return NULL;
677 }
678
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000679 // C++ casts. For dynamic casts, static casts, and const casts, we
680 // are always converting from a pointer-to-pointer, so we just blow
681 // through the cast. In the case the dynamic cast doesn't fail
682 // (and return NULL), we take the conservative route and report cases
683 // where we return the address of a stack variable. For Reinterpre
684 case Stmt::CXXCastExprClass: {
685 CXXCastExpr *C = cast<CXXCastExpr>(E);
686
687 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
688 Expr *S = C->getSubExpr();
689 if (S->getType()->isPointerType())
690 return EvalAddr(S);
691 else
692 return NULL;
693 }
694 else
695 return EvalAddr(C->getSubExpr());
696 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000697
698 // Everything else: we simply don't reason about them.
699 default:
700 return NULL;
701 }
702}
703
704
705/// EvalVal - This function is complements EvalAddr in the mutual recursion.
706/// See the comments for EvalAddr for more details.
707static DeclRefExpr* EvalVal(Expr *E) {
708
Ted Kremenekda1300a2007-08-28 17:02:55 +0000709 // We should only be called for evaluating non-pointer expressions, or
710 // expressions with a pointer type that are not used as references but instead
711 // are l-values (e.g., DeclRefExpr with a pointer type).
712
Ted Kremenek45925ab2007-08-17 16:46:58 +0000713 // Our "symbolic interpreter" is just a dispatch off the currently
714 // viewed AST node. We then recursively traverse the AST by calling
715 // EvalAddr and EvalVal appropriately.
716 switch (E->getStmtClass()) {
717
718 case Stmt::DeclRefExprClass: {
719 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
720 // at code that refers to a variable's name. We check if it has local
721 // storage within the function, and if so, return the expression.
722 DeclRefExpr *DR = cast<DeclRefExpr>(E);
723
724 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
725 if(V->hasLocalStorage()) return DR;
726
727 return NULL;
728 }
729
730 case Stmt::ParenExprClass:
731 // Ignore parentheses.
732 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
733
734 case Stmt::UnaryOperatorClass: {
735 // The only unary operator that make sense to handle here
736 // is Deref. All others don't resolve to a "name." This includes
737 // handling all sorts of rvalues passed to a unary operator.
738 UnaryOperator *U = cast<UnaryOperator>(E);
739
740 if (U->getOpcode() == UnaryOperator::Deref)
741 return EvalAddr(U->getSubExpr());
742
743 return NULL;
744 }
745
746 case Stmt::ArraySubscriptExprClass: {
747 // Array subscripts are potential references to data on the stack. We
748 // retrieve the DeclRefExpr* for the array variable if it indeed
749 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000750 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000751 }
752
753 case Stmt::ConditionalOperatorClass: {
754 // For conditional operators we need to see if either the LHS or RHS are
755 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
756 ConditionalOperator *C = cast<ConditionalOperator>(E);
757
Anders Carlsson37365fc2007-11-30 19:04:31 +0000758 // Handle the GNU extension for missing LHS.
759 if (Expr *lhsExpr = C->getLHS())
760 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
761 return LHS;
762
763 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000764 }
765
766 // Accesses to members are potential references to data on the stack.
767 case Stmt::MemberExprClass: {
768 MemberExpr *M = cast<MemberExpr>(E);
769
770 // Check for indirect access. We only want direct field accesses.
771 if (!M->isArrow())
772 return EvalVal(M->getBase());
773 else
774 return NULL;
775 }
776
777 // Everything else: we simply don't reason about them.
778 default:
779 return NULL;
780 }
781}
Ted Kremenek30c66752007-11-25 00:58:00 +0000782
783//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
784
785/// Check for comparisons of floating point operands using != and ==.
786/// Issue a warning if these are no self-comparisons, as they are not likely
787/// to do what the programmer intended.
788void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
789 bool EmitWarning = true;
790
791 Expr* LeftExprSansParen = IgnoreParen(lex);
792 Expr* RightExprSansParen = IgnoreParen(rex);
793
794 // Special case: check for x == x (which is OK).
795 // Do not emit warnings for such cases.
796 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
797 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
798 if (DRL->getDecl() == DRR->getDecl())
799 EmitWarning = false;
800
Ted Kremenek33159832007-11-29 00:59:04 +0000801
802 // Special case: check for comparisons against literals that can be exactly
803 // represented by APFloat. In such cases, do not emit a warning. This
804 // is a heuristic: often comparison against such literals are used to
805 // detect if a value in a variable has not changed. This clearly can
806 // lead to false negatives.
807 if (EmitWarning) {
808 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
809 if (FLL->isExact())
810 EmitWarning = false;
811 }
812 else
813 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
814 if (FLR->isExact())
815 EmitWarning = false;
816 }
817 }
818
Ted Kremenek30c66752007-11-25 00:58:00 +0000819 // Check for comparisons with builtin types.
820 if (EmitWarning)
821 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
822 if (isCallBuiltin(CL))
823 EmitWarning = false;
824
825 if (EmitWarning)
826 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
827 if (isCallBuiltin(CR))
828 EmitWarning = false;
829
830 // Emit the diagnostic.
831 if (EmitWarning)
832 Diag(loc, diag::warn_floatingpoint_eq,
833 lex->getSourceRange(),rex->getSourceRange());
834}