blob: fe82ea6b85fc6d164a2ca11a6f23149833386ce2 [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"
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"
Chris Lattner59907c42007-08-10 20:18:51 +000029using namespace clang;
30
31/// CheckFunctionCall - Check a direct function call for various correctness
32/// and safety properties not strictly enforced by the C type system.
Anders Carlsson71993dd2007-08-17 05:31:46 +000033bool
Chris Lattner925e60d2007-12-28 05:29:59 +000034Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
Chris Lattner59907c42007-08-10 20:18:51 +000035
36 // Get the IdentifierInfo* for the called function.
37 IdentifierInfo *FnInfo = FDecl->getIdentifier();
38
Chris Lattner30ce3442007-12-19 23:59:04 +000039 switch (FnInfo->getBuiltinID()) {
40 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000041 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000042 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner925e60d2007-12-28 05:29:59 +000043 return CheckBuiltinCFStringArgument(TheCall->getArg(0));
Chris Lattner30ce3442007-12-19 23:59:04 +000044 case Builtin::BI__builtin_va_start:
Chris Lattner925e60d2007-12-28 05:29:59 +000045 return SemaBuiltinVAStart(TheCall);
Chris Lattner1b9a0792007-12-20 00:26:33 +000046
47 case Builtin::BI__builtin_isgreater:
48 case Builtin::BI__builtin_isgreaterequal:
49 case Builtin::BI__builtin_isless:
50 case Builtin::BI__builtin_islessequal:
51 case Builtin::BI__builtin_islessgreater:
52 case Builtin::BI__builtin_isunordered:
Chris Lattner925e60d2007-12-28 05:29:59 +000053 return SemaBuiltinUnorderedCompare(TheCall);
Anders Carlsson71993dd2007-08-17 05:31:46 +000054 }
55
Chris Lattner59907c42007-08-10 20:18:51 +000056 // Search the KnownFunctionIDs for the identifier.
57 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000058 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +000059 if (i == e) return false;
Chris Lattner59907c42007-08-10 20:18:51 +000060
61 // Printf checking.
62 if (i <= id_vprintf) {
Ted Kremenek71895b92007-08-14 17:39:48 +000063 // Retrieve the index of the format string parameter and determine
64 // if the function is passed a va_arg argument.
Chris Lattner59907c42007-08-10 20:18:51 +000065 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000066 bool HasVAListArg = false;
67
Chris Lattner59907c42007-08-10 20:18:51 +000068 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000069 default: assert(false && "No format string argument index.");
70 case id_printf: format_idx = 0; break;
71 case id_fprintf: format_idx = 1; break;
72 case id_sprintf: format_idx = 1; break;
73 case id_snprintf: format_idx = 2; break;
74 case id_asprintf: format_idx = 1; break;
75 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
76 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
77 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
78 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
79 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek71895b92007-08-14 17:39:48 +000080 }
81
Chris Lattner925e60d2007-12-28 05:29:59 +000082 CheckPrintfArguments(TheCall, HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +000083 }
Anders Carlsson71993dd2007-08-17 05:31:46 +000084
Anders Carlsson9cdc4d32007-08-17 15:44:17 +000085 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +000086}
87
88/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
89/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +000090bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +000091 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +000092
93 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
94
95 if (!Literal || Literal->isWide()) {
96 Diag(Arg->getLocStart(),
97 diag::err_cfstring_literal_not_string_constant,
98 Arg->getSourceRange());
Anders Carlsson9cdc4d32007-08-17 15:44:17 +000099 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000100 }
101
102 const char *Data = Literal->getStrData();
103 unsigned Length = Literal->getByteLength();
104
105 for (unsigned i = 0; i < Length; ++i) {
106 if (!isascii(Data[i])) {
107 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
108 diag::warn_cfstring_literal_contains_non_ascii_character,
109 Arg->getSourceRange());
110 break;
111 }
112
113 if (!Data[i]) {
114 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
115 diag::warn_cfstring_literal_contains_nul_character,
116 Arg->getSourceRange());
117 break;
118 }
119 }
120
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000121 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000122}
123
Chris Lattnerc27c6652007-12-20 00:05:45 +0000124/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
125/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000126bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
127 Expr *Fn = TheCall->getCallee();
128 if (TheCall->getNumArgs() > 2) {
129 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000130 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000131 SourceRange(TheCall->getArg(2)->getLocStart(),
132 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner30ce3442007-12-19 23:59:04 +0000133 return true;
134 }
135
Chris Lattnerc27c6652007-12-20 00:05:45 +0000136 // Determine whether the current function is variadic or not.
137 bool isVariadic;
Chris Lattner30ce3442007-12-19 23:59:04 +0000138 if (CurFunctionDecl)
Chris Lattnerc27c6652007-12-20 00:05:45 +0000139 isVariadic =
140 cast<FunctionTypeProto>(CurFunctionDecl->getType())->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000141 else
Chris Lattnerc27c6652007-12-20 00:05:45 +0000142 isVariadic = CurMethodDecl->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000143
Chris Lattnerc27c6652007-12-20 00:05:45 +0000144 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000145 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
146 return true;
147 }
148
149 // Verify that the second argument to the builtin is the last argument of the
150 // current function or method.
151 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000152 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000153
154 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
155 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000156 // FIXME: This isn't correct for methods (results in bogus warning).
157 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000158 const ParmVarDecl *LastArg;
Chris Lattner30ce3442007-12-19 23:59:04 +0000159 if (CurFunctionDecl)
160 LastArg = *(CurFunctionDecl->param_end()-1);
161 else
162 LastArg = *(CurMethodDecl->param_end()-1);
163 SecondArgIsLastNamedArgument = PV == LastArg;
164 }
165 }
166
167 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000168 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000169 diag::warn_second_parameter_of_va_start_not_last_named_argument);
170 return false;
171}
172
Chris Lattner1b9a0792007-12-20 00:26:33 +0000173/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
174/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000175bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
176 if (TheCall->getNumArgs() < 2)
177 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
178 if (TheCall->getNumArgs() > 2)
179 return Diag(TheCall->getArg(2)->getLocStart(),
180 diag::err_typecheck_call_too_many_args,
181 SourceRange(TheCall->getArg(2)->getLocStart(),
182 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000183
Chris Lattner925e60d2007-12-28 05:29:59 +0000184 Expr *OrigArg0 = TheCall->getArg(0);
185 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000186
187 // Do standard promotions between the two arguments, returning their common
188 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000189 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000190
191 // If the common type isn't a real floating type, then the arguments were
192 // invalid for this operation.
193 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000194 return Diag(OrigArg0->getLocStart(),
Chris Lattner1b9a0792007-12-20 00:26:33 +0000195 diag::err_typecheck_call_invalid_ordered_compare,
196 OrigArg0->getType().getAsString(),
197 OrigArg1->getType().getAsString(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000198 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000199
200 return false;
201}
202
Chris Lattner30ce3442007-12-19 23:59:04 +0000203
Chris Lattner59907c42007-08-10 20:18:51 +0000204/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000205/// correct use of format strings.
206///
207/// HasVAListArg - A predicate indicating whether the printf-like
208/// function is passed an explicit va_arg argument (e.g., vprintf)
209///
210/// format_idx - The index into Args for the format string.
211///
212/// Improper format strings to functions in the printf family can be
213/// the source of bizarre bugs and very serious security holes. A
214/// good source of information is available in the following paper
215/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000216///
217/// FormatGuard: Automatic Protection From printf Format String
218/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000219///
220/// Functionality implemented:
221///
222/// We can statically check the following properties for string
223/// literal format strings for non v.*printf functions (where the
224/// arguments are passed directly):
225//
226/// (1) Are the number of format conversions equal to the number of
227/// data arguments?
228///
229/// (2) Does each format conversion correctly match the type of the
230/// corresponding data argument? (TODO)
231///
232/// Moreover, for all printf functions we can:
233///
234/// (3) Check for a missing format string (when not caught by type checking).
235///
236/// (4) Check for no-operation flags; e.g. using "#" with format
237/// conversion 'c' (TODO)
238///
239/// (5) Check the use of '%n', a major source of security holes.
240///
241/// (6) Check for malformed format conversions that don't specify anything.
242///
243/// (7) Check for empty format strings. e.g: printf("");
244///
245/// (8) Check that the format string is a wide literal.
246///
247/// All of these checks can be done by parsing the format string.
248///
249/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000250void
Chris Lattner925e60d2007-12-28 05:29:59 +0000251Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
252 unsigned format_idx) {
253 Expr *Fn = TheCall->getCallee();
254
Ted Kremenek71895b92007-08-14 17:39:48 +0000255 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000256 if (format_idx >= TheCall->getNumArgs()) {
257 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000258 Fn->getSourceRange());
259 return;
260 }
261
Chris Lattner56f34942008-02-13 01:02:39 +0000262 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000263
Chris Lattner59907c42007-08-10 20:18:51 +0000264 // CHECK: format string is not a string literal.
265 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000266 // Dynamically generated format strings are difficult to
267 // automatically vet at compile time. Requiring that format strings
268 // are string literals: (1) permits the checking of format strings by
269 // the compiler and thereby (2) can practically remove the source of
270 // many format string exploits.
Chris Lattner459e8482007-08-25 05:36:18 +0000271 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000272 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000273 // For vprintf* functions (i.e., HasVAListArg==true), we add a
274 // special check to see if the format string is a function parameter
275 // of the function calling the printf function. If the function
276 // has an attribute indicating it is a printf-like function, then we
277 // should suppress warnings concerning non-literals being used in a call
278 // to a vprintf function. For example:
279 //
280 // void
281 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
282 // va_list ap;
283 // va_start(ap, fmt);
284 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
285 // ...
286 //
287 //
288 // FIXME: We don't have full attribute support yet, so just check to see
289 // if the argument is a DeclRefExpr that references a parameter. We'll
290 // add proper support for checking the attribute later.
291 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000292 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
293 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000294 return;
295
Chris Lattner925e60d2007-12-28 05:29:59 +0000296 Diag(TheCall->getArg(format_idx)->getLocStart(),
297 diag::warn_printf_not_string_constant, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000298 return;
299 }
300
301 // CHECK: is the format string a wide literal?
302 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000303 Diag(FExpr->getLocStart(),
304 diag::warn_printf_format_string_is_wide_literal, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000305 return;
306 }
307
308 // Str - The format string. NOTE: this is NOT null-terminated!
309 const char * const Str = FExpr->getStrData();
310
311 // CHECK: empty format string?
312 const unsigned StrLen = FExpr->getByteLength();
313
314 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000315 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
316 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000317 return;
318 }
319
320 // We process the format string using a binary state machine. The
321 // current state is stored in CurrentState.
322 enum {
323 state_OrdChr,
324 state_Conversion
325 } CurrentState = state_OrdChr;
326
327 // numConversions - The number of conversions seen so far. This is
328 // incremented as we traverse the format string.
329 unsigned numConversions = 0;
330
331 // numDataArgs - The number of data arguments after the format
332 // string. This can only be determined for non vprintf-like
333 // functions. For those functions, this value is 1 (the sole
334 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000335 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000336
337 // Inspect the format string.
338 unsigned StrIdx = 0;
339
340 // LastConversionIdx - Index within the format string where we last saw
341 // a '%' character that starts a new format conversion.
342 unsigned LastConversionIdx = 0;
343
Chris Lattner925e60d2007-12-28 05:29:59 +0000344 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000345
Ted Kremenek71895b92007-08-14 17:39:48 +0000346 // Is the number of detected conversion conversions greater than
347 // the number of matching data arguments? If so, stop.
348 if (!HasVAListArg && numConversions > numDataArgs) break;
349
350 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000351 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000352 // The string returned by getStrData() is not null-terminated,
353 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000354 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
355 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek71895b92007-08-14 17:39:48 +0000356 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000357 return;
358 }
359
360 // Ordinary characters (not processing a format conversion).
361 if (CurrentState == state_OrdChr) {
362 if (Str[StrIdx] == '%') {
363 CurrentState = state_Conversion;
364 LastConversionIdx = StrIdx;
365 }
366 continue;
367 }
368
369 // Seen '%'. Now processing a format conversion.
370 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000371 // Handle dynamic precision or width specifier.
372 case '*': {
373 ++numConversions;
374
375 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000376 SourceLocation Loc = FExpr->getLocStart();
377 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000378
Ted Kremenek580b6642007-10-12 20:51:52 +0000379 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000380 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
381 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000382 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000383 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
384 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000385
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000386 // Don't do any more checking. We'll just emit spurious errors.
387 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000388 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000389
390 // Perform type checking on width/precision specifier.
391 Expr *E = TheCall->getArg(format_idx+numConversions);
392 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
393 if (BT->getKind() == BuiltinType::Int)
394 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000395
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000396 SourceLocation Loc =
397 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
398
399 if (Str[StrIdx-1] == '.')
400 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
401 E->getType().getAsString(), E->getSourceRange());
402 else
403 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
404 E->getType().getAsString(), E->getSourceRange());
405
406 break;
407 }
408
409 // Characters which can terminate a format conversion
410 // (e.g. "%d"). Characters that specify length modifiers or
411 // other flags are handled by the default case below.
412 //
413 // FIXME: additional checks will go into the following cases.
414 case 'i':
415 case 'd':
416 case 'o':
417 case 'u':
418 case 'x':
419 case 'X':
420 case 'D':
421 case 'O':
422 case 'U':
423 case 'e':
424 case 'E':
425 case 'f':
426 case 'F':
427 case 'g':
428 case 'G':
429 case 'a':
430 case 'A':
431 case 'c':
432 case 'C':
433 case 'S':
434 case 's':
435 case 'p':
436 ++numConversions;
437 CurrentState = state_OrdChr;
438 break;
439
440 // CHECK: Are we using "%n"? Issue a warning.
441 case 'n': {
442 ++numConversions;
443 CurrentState = state_OrdChr;
444 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
445 LastConversionIdx+1);
446
447 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
448 break;
449 }
450
451 // Handle "%%"
452 case '%':
453 // Sanity check: Was the first "%" character the previous one?
454 // If not, we will assume that we have a malformed format
455 // conversion, and that the current "%" character is the start
456 // of a new conversion.
457 if (StrIdx - LastConversionIdx == 1)
458 CurrentState = state_OrdChr;
459 else {
460 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000461 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
462 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000463
464 Diag(Loc, diag::warn_printf_invalid_conversion,
465 std::string(Str+LastConversionIdx, Str+StrIdx),
466 Fn->getSourceRange());
467
468 // This conversion is broken. Advance to the next format
469 // conversion.
470 LastConversionIdx = StrIdx;
471 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000472 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000473 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000474
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000475 default:
476 // This case catches all other characters: flags, widths, etc.
477 // We should eventually process those as well.
478 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000479 }
480 }
481
482 if (CurrentState == state_Conversion) {
483 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000484 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
485 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000486
487 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000488 std::string(Str+LastConversionIdx,
489 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek71895b92007-08-14 17:39:48 +0000490 Fn->getSourceRange());
491 return;
492 }
493
494 if (!HasVAListArg) {
495 // CHECK: Does the number of format conversions exceed the number
496 // of data arguments?
497 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000498 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
499 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000500
501 Diag(Loc, diag::warn_printf_insufficient_data_args,
502 Fn->getSourceRange());
503 }
504 // CHECK: Does the number of data arguments exceed the number of
505 // format conversions in the format string?
506 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000507 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek71895b92007-08-14 17:39:48 +0000508 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
509 }
510}
Ted Kremenek06de2762007-08-17 16:46:58 +0000511
512//===--- CHECK: Return Address of Stack Variable --------------------------===//
513
514static DeclRefExpr* EvalVal(Expr *E);
515static DeclRefExpr* EvalAddr(Expr* E);
516
517/// CheckReturnStackAddr - Check if a return statement returns the address
518/// of a stack variable.
519void
520Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
521 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000522
Ted Kremenek06de2762007-08-17 16:46:58 +0000523 // Perform checking for returned stack addresses.
524 if (lhsType->isPointerType()) {
525 if (DeclRefExpr *DR = EvalAddr(RetValExp))
526 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
527 DR->getDecl()->getIdentifier()->getName(),
528 RetValExp->getSourceRange());
529 }
530 // Perform checking for stack values returned by reference.
531 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000532 // Check for an implicit cast to a reference.
533 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
534 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
535 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
536 DR->getDecl()->getIdentifier()->getName(),
537 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000538 }
539}
540
541/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
542/// check if the expression in a return statement evaluates to an address
543/// to a location on the stack. The recursion is used to traverse the
544/// AST of the return expression, with recursion backtracking when we
545/// encounter a subexpression that (1) clearly does not lead to the address
546/// of a stack variable or (2) is something we cannot determine leads to
547/// the address of a stack variable based on such local checking.
548///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000549/// EvalAddr processes expressions that are pointers that are used as
550/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000551/// At the base case of the recursion is a check for a DeclRefExpr* in
552/// the refers to a stack variable.
553///
554/// This implementation handles:
555///
556/// * pointer-to-pointer casts
557/// * implicit conversions from array references to pointers
558/// * taking the address of fields
559/// * arbitrary interplay between "&" and "*" operators
560/// * pointer arithmetic from an address of a stack variable
561/// * taking the address of an array element where the array is on the stack
562static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000563 // We should only be called for evaluating pointer expressions.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000564 assert((E->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000565 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000566 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000567
568 // Our "symbolic interpreter" is just a dispatch off the currently
569 // viewed AST node. We then recursively traverse the AST by calling
570 // EvalAddr and EvalVal appropriately.
571 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000572 case Stmt::ParenExprClass:
573 // Ignore parentheses.
574 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000575
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000576 case Stmt::UnaryOperatorClass: {
577 // The only unary operator that make sense to handle here
578 // is AddrOf. All others don't make sense as pointers.
579 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000580
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000581 if (U->getOpcode() == UnaryOperator::AddrOf)
582 return EvalVal(U->getSubExpr());
583 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000584 return NULL;
585 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000586
587 case Stmt::BinaryOperatorClass: {
588 // Handle pointer arithmetic. All other binary operators are not valid
589 // in this context.
590 BinaryOperator *B = cast<BinaryOperator>(E);
591 BinaryOperator::Opcode op = B->getOpcode();
592
593 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
594 return NULL;
595
596 Expr *Base = B->getLHS();
597
598 // Determine which argument is the real pointer base. It could be
599 // the RHS argument instead of the LHS.
600 if (!Base->getType()->isPointerType()) Base = B->getRHS();
601
602 assert (Base->getType()->isPointerType());
603 return EvalAddr(Base);
604 }
605
606 // For conditional operators we need to see if either the LHS or RHS are
607 // valid DeclRefExpr*s. If one of them is valid, we return it.
608 case Stmt::ConditionalOperatorClass: {
609 ConditionalOperator *C = cast<ConditionalOperator>(E);
610
611 // Handle the GNU extension for missing LHS.
612 if (Expr *lhsExpr = C->getLHS())
613 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
614 return LHS;
615
616 return EvalAddr(C->getRHS());
617 }
618
619 // For implicit casts, we need to handle conversions from arrays to
620 // pointer values, and implicit pointer-to-pointer conversions.
621 case Stmt::ImplicitCastExprClass: {
622 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
623 Expr* SubExpr = IE->getSubExpr();
624
625 if (SubExpr->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000626 SubExpr->getType()->isObjCQualifiedIdType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000627 return EvalAddr(SubExpr);
628 else
629 return EvalVal(SubExpr);
630 }
631
632 // For casts, we handle pointer-to-pointer conversions (which
633 // is essentially a no-op from our mini-interpreter's standpoint).
634 // For other casts we abort.
635 case Stmt::CastExprClass: {
636 CastExpr *C = cast<CastExpr>(E);
637 Expr *SubExpr = C->getSubExpr();
638
639 if (SubExpr->getType()->isPointerType())
640 return EvalAddr(SubExpr);
641 else
642 return NULL;
643 }
644
645 // C++ casts. For dynamic casts, static casts, and const casts, we
646 // are always converting from a pointer-to-pointer, so we just blow
647 // through the cast. In the case the dynamic cast doesn't fail
648 // (and return NULL), we take the conservative route and report cases
649 // where we return the address of a stack variable. For Reinterpre
650 case Stmt::CXXCastExprClass: {
651 CXXCastExpr *C = cast<CXXCastExpr>(E);
652
653 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
654 Expr *S = C->getSubExpr();
655 if (S->getType()->isPointerType())
656 return EvalAddr(S);
657 else
658 return NULL;
659 }
660 else
661 return EvalAddr(C->getSubExpr());
662 }
663
664 // Everything else: we simply don't reason about them.
665 default:
666 return NULL;
667 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000668}
669
670
671/// EvalVal - This function is complements EvalAddr in the mutual recursion.
672/// See the comments for EvalAddr for more details.
673static DeclRefExpr* EvalVal(Expr *E) {
674
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000675 // We should only be called for evaluating non-pointer expressions, or
676 // expressions with a pointer type that are not used as references but instead
677 // are l-values (e.g., DeclRefExpr with a pointer type).
678
Ted Kremenek06de2762007-08-17 16:46:58 +0000679 // Our "symbolic interpreter" is just a dispatch off the currently
680 // viewed AST node. We then recursively traverse the AST by calling
681 // EvalAddr and EvalVal appropriately.
682 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000683 case Stmt::DeclRefExprClass: {
684 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
685 // at code that refers to a variable's name. We check if it has local
686 // storage within the function, and if so, return the expression.
687 DeclRefExpr *DR = cast<DeclRefExpr>(E);
688
689 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
690 if(V->hasLocalStorage()) return DR;
691
692 return NULL;
693 }
694
695 case Stmt::ParenExprClass:
696 // Ignore parentheses.
697 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
698
699 case Stmt::UnaryOperatorClass: {
700 // The only unary operator that make sense to handle here
701 // is Deref. All others don't resolve to a "name." This includes
702 // handling all sorts of rvalues passed to a unary operator.
703 UnaryOperator *U = cast<UnaryOperator>(E);
704
705 if (U->getOpcode() == UnaryOperator::Deref)
706 return EvalAddr(U->getSubExpr());
707
708 return NULL;
709 }
710
711 case Stmt::ArraySubscriptExprClass: {
712 // Array subscripts are potential references to data on the stack. We
713 // retrieve the DeclRefExpr* for the array variable if it indeed
714 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000715 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000716 }
717
718 case Stmt::ConditionalOperatorClass: {
719 // For conditional operators we need to see if either the LHS or RHS are
720 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
721 ConditionalOperator *C = cast<ConditionalOperator>(E);
722
Anders Carlsson39073232007-11-30 19:04:31 +0000723 // Handle the GNU extension for missing LHS.
724 if (Expr *lhsExpr = C->getLHS())
725 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
726 return LHS;
727
728 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000729 }
730
731 // Accesses to members are potential references to data on the stack.
732 case Stmt::MemberExprClass: {
733 MemberExpr *M = cast<MemberExpr>(E);
734
735 // Check for indirect access. We only want direct field accesses.
736 if (!M->isArrow())
737 return EvalVal(M->getBase());
738 else
739 return NULL;
740 }
741
742 // Everything else: we simply don't reason about them.
743 default:
744 return NULL;
745 }
746}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000747
748//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
749
750/// Check for comparisons of floating point operands using != and ==.
751/// Issue a warning if these are no self-comparisons, as they are not likely
752/// to do what the programmer intended.
753void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
754 bool EmitWarning = true;
755
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000756 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000757 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000758
759 // Special case: check for x == x (which is OK).
760 // Do not emit warnings for such cases.
761 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
762 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
763 if (DRL->getDecl() == DRR->getDecl())
764 EmitWarning = false;
765
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000766
767 // Special case: check for comparisons against literals that can be exactly
768 // represented by APFloat. In such cases, do not emit a warning. This
769 // is a heuristic: often comparison against such literals are used to
770 // detect if a value in a variable has not changed. This clearly can
771 // lead to false negatives.
772 if (EmitWarning) {
773 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
774 if (FLL->isExact())
775 EmitWarning = false;
776 }
777 else
778 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
779 if (FLR->isExact())
780 EmitWarning = false;
781 }
782 }
783
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000784 // Check for comparisons with builtin types.
785 if (EmitWarning)
786 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
787 if (isCallBuiltin(CL))
788 EmitWarning = false;
789
790 if (EmitWarning)
791 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
792 if (isCallBuiltin(CR))
793 EmitWarning = false;
794
795 // Emit the diagnostic.
796 if (EmitWarning)
797 Diag(loc, diag::warn_floatingpoint_eq,
798 lex->getSourceRange(),rex->getSourceRange());
799}