blob: 6d3eea5e730b56365fbf5e95affc4f7e84547926 [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///
Ted Kremenek6d439592008-03-03 16:50:00 +0000247/// (9) Also check the arguments of functions with the __format__ attribute.
248/// (TODO).
249///
Ted Kremenek71895b92007-08-14 17:39:48 +0000250/// All of these checks can be done by parsing the format string.
251///
252/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000253void
Chris Lattner925e60d2007-12-28 05:29:59 +0000254Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
255 unsigned format_idx) {
256 Expr *Fn = TheCall->getCallee();
257
Ted Kremenek71895b92007-08-14 17:39:48 +0000258 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000259 if (format_idx >= TheCall->getNumArgs()) {
260 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000261 Fn->getSourceRange());
262 return;
263 }
264
Chris Lattner56f34942008-02-13 01:02:39 +0000265 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000266
Chris Lattner59907c42007-08-10 20:18:51 +0000267 // CHECK: format string is not a string literal.
268 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000269 // Dynamically generated format strings are difficult to
270 // automatically vet at compile time. Requiring that format strings
271 // are string literals: (1) permits the checking of format strings by
272 // the compiler and thereby (2) can practically remove the source of
273 // many format string exploits.
Chris Lattner459e8482007-08-25 05:36:18 +0000274 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000275 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000276 // For vprintf* functions (i.e., HasVAListArg==true), we add a
277 // special check to see if the format string is a function parameter
278 // of the function calling the printf function. If the function
279 // has an attribute indicating it is a printf-like function, then we
280 // should suppress warnings concerning non-literals being used in a call
281 // to a vprintf function. For example:
282 //
283 // void
284 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
285 // va_list ap;
286 // va_start(ap, fmt);
287 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
288 // ...
289 //
290 //
291 // FIXME: We don't have full attribute support yet, so just check to see
292 // if the argument is a DeclRefExpr that references a parameter. We'll
293 // add proper support for checking the attribute later.
294 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000295 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
296 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000297 return;
298
Chris Lattner925e60d2007-12-28 05:29:59 +0000299 Diag(TheCall->getArg(format_idx)->getLocStart(),
300 diag::warn_printf_not_string_constant, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000301 return;
302 }
303
304 // CHECK: is the format string a wide literal?
305 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000306 Diag(FExpr->getLocStart(),
307 diag::warn_printf_format_string_is_wide_literal, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000308 return;
309 }
310
311 // Str - The format string. NOTE: this is NOT null-terminated!
312 const char * const Str = FExpr->getStrData();
313
314 // CHECK: empty format string?
315 const unsigned StrLen = FExpr->getByteLength();
316
317 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000318 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
319 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000320 return;
321 }
322
323 // We process the format string using a binary state machine. The
324 // current state is stored in CurrentState.
325 enum {
326 state_OrdChr,
327 state_Conversion
328 } CurrentState = state_OrdChr;
329
330 // numConversions - The number of conversions seen so far. This is
331 // incremented as we traverse the format string.
332 unsigned numConversions = 0;
333
334 // numDataArgs - The number of data arguments after the format
335 // string. This can only be determined for non vprintf-like
336 // functions. For those functions, this value is 1 (the sole
337 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000338 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000339
340 // Inspect the format string.
341 unsigned StrIdx = 0;
342
343 // LastConversionIdx - Index within the format string where we last saw
344 // a '%' character that starts a new format conversion.
345 unsigned LastConversionIdx = 0;
346
Chris Lattner925e60d2007-12-28 05:29:59 +0000347 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000348
Ted Kremenek71895b92007-08-14 17:39:48 +0000349 // Is the number of detected conversion conversions greater than
350 // the number of matching data arguments? If so, stop.
351 if (!HasVAListArg && numConversions > numDataArgs) break;
352
353 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000354 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000355 // The string returned by getStrData() is not null-terminated,
356 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000357 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
358 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek71895b92007-08-14 17:39:48 +0000359 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000360 return;
361 }
362
363 // Ordinary characters (not processing a format conversion).
364 if (CurrentState == state_OrdChr) {
365 if (Str[StrIdx] == '%') {
366 CurrentState = state_Conversion;
367 LastConversionIdx = StrIdx;
368 }
369 continue;
370 }
371
372 // Seen '%'. Now processing a format conversion.
373 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000374 // Handle dynamic precision or width specifier.
375 case '*': {
376 ++numConversions;
377
378 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000379 SourceLocation Loc = FExpr->getLocStart();
380 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000381
Ted Kremenek580b6642007-10-12 20:51:52 +0000382 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000383 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
384 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000385 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000386 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
387 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000388
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000389 // Don't do any more checking. We'll just emit spurious errors.
390 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000391 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000392
393 // Perform type checking on width/precision specifier.
394 Expr *E = TheCall->getArg(format_idx+numConversions);
395 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
396 if (BT->getKind() == BuiltinType::Int)
397 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000398
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000399 SourceLocation Loc =
400 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
401
402 if (Str[StrIdx-1] == '.')
403 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
404 E->getType().getAsString(), E->getSourceRange());
405 else
406 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
407 E->getType().getAsString(), E->getSourceRange());
408
409 break;
410 }
411
412 // Characters which can terminate a format conversion
413 // (e.g. "%d"). Characters that specify length modifiers or
414 // other flags are handled by the default case below.
415 //
416 // FIXME: additional checks will go into the following cases.
417 case 'i':
418 case 'd':
419 case 'o':
420 case 'u':
421 case 'x':
422 case 'X':
423 case 'D':
424 case 'O':
425 case 'U':
426 case 'e':
427 case 'E':
428 case 'f':
429 case 'F':
430 case 'g':
431 case 'G':
432 case 'a':
433 case 'A':
434 case 'c':
435 case 'C':
436 case 'S':
437 case 's':
438 case 'p':
439 ++numConversions;
440 CurrentState = state_OrdChr;
441 break;
442
443 // CHECK: Are we using "%n"? Issue a warning.
444 case 'n': {
445 ++numConversions;
446 CurrentState = state_OrdChr;
447 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
448 LastConversionIdx+1);
449
450 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
451 break;
452 }
453
454 // Handle "%%"
455 case '%':
456 // Sanity check: Was the first "%" character the previous one?
457 // If not, we will assume that we have a malformed format
458 // conversion, and that the current "%" character is the start
459 // of a new conversion.
460 if (StrIdx - LastConversionIdx == 1)
461 CurrentState = state_OrdChr;
462 else {
463 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000464 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
465 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000466
467 Diag(Loc, diag::warn_printf_invalid_conversion,
468 std::string(Str+LastConversionIdx, Str+StrIdx),
469 Fn->getSourceRange());
470
471 // This conversion is broken. Advance to the next format
472 // conversion.
473 LastConversionIdx = StrIdx;
474 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000475 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000476 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000477
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000478 default:
479 // This case catches all other characters: flags, widths, etc.
480 // We should eventually process those as well.
481 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000482 }
483 }
484
485 if (CurrentState == state_Conversion) {
486 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000487 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
488 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000489
490 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000491 std::string(Str+LastConversionIdx,
492 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek71895b92007-08-14 17:39:48 +0000493 Fn->getSourceRange());
494 return;
495 }
496
497 if (!HasVAListArg) {
498 // CHECK: Does the number of format conversions exceed the number
499 // of data arguments?
500 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000501 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
502 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000503
504 Diag(Loc, diag::warn_printf_insufficient_data_args,
505 Fn->getSourceRange());
506 }
507 // CHECK: Does the number of data arguments exceed the number of
508 // format conversions in the format string?
509 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000510 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek71895b92007-08-14 17:39:48 +0000511 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
512 }
513}
Ted Kremenek06de2762007-08-17 16:46:58 +0000514
515//===--- CHECK: Return Address of Stack Variable --------------------------===//
516
517static DeclRefExpr* EvalVal(Expr *E);
518static DeclRefExpr* EvalAddr(Expr* E);
519
520/// CheckReturnStackAddr - Check if a return statement returns the address
521/// of a stack variable.
522void
523Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
524 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000525
Ted Kremenek06de2762007-08-17 16:46:58 +0000526 // Perform checking for returned stack addresses.
527 if (lhsType->isPointerType()) {
528 if (DeclRefExpr *DR = EvalAddr(RetValExp))
529 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
530 DR->getDecl()->getIdentifier()->getName(),
531 RetValExp->getSourceRange());
532 }
533 // Perform checking for stack values returned by reference.
534 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000535 // Check for an implicit cast to a reference.
536 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
537 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
538 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
539 DR->getDecl()->getIdentifier()->getName(),
540 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000541 }
542}
543
544/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
545/// check if the expression in a return statement evaluates to an address
546/// to a location on the stack. The recursion is used to traverse the
547/// AST of the return expression, with recursion backtracking when we
548/// encounter a subexpression that (1) clearly does not lead to the address
549/// of a stack variable or (2) is something we cannot determine leads to
550/// the address of a stack variable based on such local checking.
551///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000552/// EvalAddr processes expressions that are pointers that are used as
553/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000554/// At the base case of the recursion is a check for a DeclRefExpr* in
555/// the refers to a stack variable.
556///
557/// This implementation handles:
558///
559/// * pointer-to-pointer casts
560/// * implicit conversions from array references to pointers
561/// * taking the address of fields
562/// * arbitrary interplay between "&" and "*" operators
563/// * pointer arithmetic from an address of a stack variable
564/// * taking the address of an array element where the array is on the stack
565static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000566 // We should only be called for evaluating pointer expressions.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000567 assert((E->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000568 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000569 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000570
571 // Our "symbolic interpreter" is just a dispatch off the currently
572 // viewed AST node. We then recursively traverse the AST by calling
573 // EvalAddr and EvalVal appropriately.
574 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000575 case Stmt::ParenExprClass:
576 // Ignore parentheses.
577 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000578
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000579 case Stmt::UnaryOperatorClass: {
580 // The only unary operator that make sense to handle here
581 // is AddrOf. All others don't make sense as pointers.
582 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000583
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000584 if (U->getOpcode() == UnaryOperator::AddrOf)
585 return EvalVal(U->getSubExpr());
586 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000587 return NULL;
588 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000589
590 case Stmt::BinaryOperatorClass: {
591 // Handle pointer arithmetic. All other binary operators are not valid
592 // in this context.
593 BinaryOperator *B = cast<BinaryOperator>(E);
594 BinaryOperator::Opcode op = B->getOpcode();
595
596 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
597 return NULL;
598
599 Expr *Base = B->getLHS();
600
601 // Determine which argument is the real pointer base. It could be
602 // the RHS argument instead of the LHS.
603 if (!Base->getType()->isPointerType()) Base = B->getRHS();
604
605 assert (Base->getType()->isPointerType());
606 return EvalAddr(Base);
607 }
608
609 // For conditional operators we need to see if either the LHS or RHS are
610 // valid DeclRefExpr*s. If one of them is valid, we return it.
611 case Stmt::ConditionalOperatorClass: {
612 ConditionalOperator *C = cast<ConditionalOperator>(E);
613
614 // Handle the GNU extension for missing LHS.
615 if (Expr *lhsExpr = C->getLHS())
616 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
617 return LHS;
618
619 return EvalAddr(C->getRHS());
620 }
621
622 // For implicit casts, we need to handle conversions from arrays to
623 // pointer values, and implicit pointer-to-pointer conversions.
624 case Stmt::ImplicitCastExprClass: {
625 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
626 Expr* SubExpr = IE->getSubExpr();
627
628 if (SubExpr->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000629 SubExpr->getType()->isObjCQualifiedIdType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000630 return EvalAddr(SubExpr);
631 else
632 return EvalVal(SubExpr);
633 }
634
635 // For casts, we handle pointer-to-pointer conversions (which
636 // is essentially a no-op from our mini-interpreter's standpoint).
637 // For other casts we abort.
638 case Stmt::CastExprClass: {
639 CastExpr *C = cast<CastExpr>(E);
640 Expr *SubExpr = C->getSubExpr();
641
642 if (SubExpr->getType()->isPointerType())
643 return EvalAddr(SubExpr);
644 else
645 return NULL;
646 }
647
648 // C++ casts. For dynamic casts, static casts, and const casts, we
649 // are always converting from a pointer-to-pointer, so we just blow
650 // through the cast. In the case the dynamic cast doesn't fail
651 // (and return NULL), we take the conservative route and report cases
652 // where we return the address of a stack variable. For Reinterpre
653 case Stmt::CXXCastExprClass: {
654 CXXCastExpr *C = cast<CXXCastExpr>(E);
655
656 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
657 Expr *S = C->getSubExpr();
658 if (S->getType()->isPointerType())
659 return EvalAddr(S);
660 else
661 return NULL;
662 }
663 else
664 return EvalAddr(C->getSubExpr());
665 }
666
667 // Everything else: we simply don't reason about them.
668 default:
669 return NULL;
670 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000671}
672
673
674/// EvalVal - This function is complements EvalAddr in the mutual recursion.
675/// See the comments for EvalAddr for more details.
676static DeclRefExpr* EvalVal(Expr *E) {
677
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000678 // We should only be called for evaluating non-pointer expressions, or
679 // expressions with a pointer type that are not used as references but instead
680 // are l-values (e.g., DeclRefExpr with a pointer type).
681
Ted Kremenek06de2762007-08-17 16:46:58 +0000682 // Our "symbolic interpreter" is just a dispatch off the currently
683 // viewed AST node. We then recursively traverse the AST by calling
684 // EvalAddr and EvalVal appropriately.
685 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000686 case Stmt::DeclRefExprClass: {
687 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
688 // at code that refers to a variable's name. We check if it has local
689 // storage within the function, and if so, return the expression.
690 DeclRefExpr *DR = cast<DeclRefExpr>(E);
691
692 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
693 if(V->hasLocalStorage()) return DR;
694
695 return NULL;
696 }
697
698 case Stmt::ParenExprClass:
699 // Ignore parentheses.
700 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
701
702 case Stmt::UnaryOperatorClass: {
703 // The only unary operator that make sense to handle here
704 // is Deref. All others don't resolve to a "name." This includes
705 // handling all sorts of rvalues passed to a unary operator.
706 UnaryOperator *U = cast<UnaryOperator>(E);
707
708 if (U->getOpcode() == UnaryOperator::Deref)
709 return EvalAddr(U->getSubExpr());
710
711 return NULL;
712 }
713
714 case Stmt::ArraySubscriptExprClass: {
715 // Array subscripts are potential references to data on the stack. We
716 // retrieve the DeclRefExpr* for the array variable if it indeed
717 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000718 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000719 }
720
721 case Stmt::ConditionalOperatorClass: {
722 // For conditional operators we need to see if either the LHS or RHS are
723 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
724 ConditionalOperator *C = cast<ConditionalOperator>(E);
725
Anders Carlsson39073232007-11-30 19:04:31 +0000726 // Handle the GNU extension for missing LHS.
727 if (Expr *lhsExpr = C->getLHS())
728 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
729 return LHS;
730
731 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000732 }
733
734 // Accesses to members are potential references to data on the stack.
735 case Stmt::MemberExprClass: {
736 MemberExpr *M = cast<MemberExpr>(E);
737
738 // Check for indirect access. We only want direct field accesses.
739 if (!M->isArrow())
740 return EvalVal(M->getBase());
741 else
742 return NULL;
743 }
744
745 // Everything else: we simply don't reason about them.
746 default:
747 return NULL;
748 }
749}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000750
751//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
752
753/// Check for comparisons of floating point operands using != and ==.
754/// Issue a warning if these are no self-comparisons, as they are not likely
755/// to do what the programmer intended.
756void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
757 bool EmitWarning = true;
758
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000759 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000760 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000761
762 // Special case: check for x == x (which is OK).
763 // Do not emit warnings for such cases.
764 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
765 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
766 if (DRL->getDecl() == DRR->getDecl())
767 EmitWarning = false;
768
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000769
770 // Special case: check for comparisons against literals that can be exactly
771 // represented by APFloat. In such cases, do not emit a warning. This
772 // is a heuristic: often comparison against such literals are used to
773 // detect if a value in a variable has not changed. This clearly can
774 // lead to false negatives.
775 if (EmitWarning) {
776 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
777 if (FLL->isExact())
778 EmitWarning = false;
779 }
780 else
781 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
782 if (FLR->isExact())
783 EmitWarning = false;
784 }
785 }
786
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000787 // Check for comparisons with builtin types.
788 if (EmitWarning)
789 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
790 if (isCallBuiltin(CL))
791 EmitWarning = false;
792
793 if (EmitWarning)
794 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
795 if (isCallBuiltin(CR))
796 EmitWarning = false;
797
798 // Emit the diagnostic.
799 if (EmitWarning)
800 Diag(loc, diag::warn_floatingpoint_eq,
801 lex->getSourceRange(),rex->getSourceRange());
802}