blob: 61c67f02feede6b718a53219aaae3be3d440bf8f [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 Lattner998568f2007-12-28 05:38:24 +000091 Arg = IgnoreParenCasts(Arg);
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;
Chris Lattner925e60d2007-12-28 05:29:59 +0000152 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(TheCall->getArg(1))) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000153 if (ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
154 // FIXME: This isn't correct for methods (results in bogus warning).
155 // Get the last formal in the current function.
156 ParmVarDecl *LastArg;
157 if (CurFunctionDecl)
158 LastArg = *(CurFunctionDecl->param_end()-1);
159 else
160 LastArg = *(CurMethodDecl->param_end()-1);
161 SecondArgIsLastNamedArgument = PV == LastArg;
162 }
163 }
164
165 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000166 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000167 diag::warn_second_parameter_of_va_start_not_last_named_argument);
168 return false;
169}
170
Chris Lattner1b9a0792007-12-20 00:26:33 +0000171/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
172/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000173bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
174 if (TheCall->getNumArgs() < 2)
175 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
176 if (TheCall->getNumArgs() > 2)
177 return Diag(TheCall->getArg(2)->getLocStart(),
178 diag::err_typecheck_call_too_many_args,
179 SourceRange(TheCall->getArg(2)->getLocStart(),
180 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000181
Chris Lattner925e60d2007-12-28 05:29:59 +0000182 Expr *OrigArg0 = TheCall->getArg(0);
183 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000184
185 // Do standard promotions between the two arguments, returning their common
186 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000187 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000188
189 // If the common type isn't a real floating type, then the arguments were
190 // invalid for this operation.
191 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000192 return Diag(OrigArg0->getLocStart(),
Chris Lattner1b9a0792007-12-20 00:26:33 +0000193 diag::err_typecheck_call_invalid_ordered_compare,
194 OrigArg0->getType().getAsString(),
195 OrigArg1->getType().getAsString(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000196 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000197
198 return false;
199}
200
Chris Lattner30ce3442007-12-19 23:59:04 +0000201
Chris Lattner59907c42007-08-10 20:18:51 +0000202/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000203/// correct use of format strings.
204///
205/// HasVAListArg - A predicate indicating whether the printf-like
206/// function is passed an explicit va_arg argument (e.g., vprintf)
207///
208/// format_idx - The index into Args for the format string.
209///
210/// Improper format strings to functions in the printf family can be
211/// the source of bizarre bugs and very serious security holes. A
212/// good source of information is available in the following paper
213/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000214///
215/// FormatGuard: Automatic Protection From printf Format String
216/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000217///
218/// Functionality implemented:
219///
220/// We can statically check the following properties for string
221/// literal format strings for non v.*printf functions (where the
222/// arguments are passed directly):
223//
224/// (1) Are the number of format conversions equal to the number of
225/// data arguments?
226///
227/// (2) Does each format conversion correctly match the type of the
228/// corresponding data argument? (TODO)
229///
230/// Moreover, for all printf functions we can:
231///
232/// (3) Check for a missing format string (when not caught by type checking).
233///
234/// (4) Check for no-operation flags; e.g. using "#" with format
235/// conversion 'c' (TODO)
236///
237/// (5) Check the use of '%n', a major source of security holes.
238///
239/// (6) Check for malformed format conversions that don't specify anything.
240///
241/// (7) Check for empty format strings. e.g: printf("");
242///
243/// (8) Check that the format string is a wide literal.
244///
245/// All of these checks can be done by parsing the format string.
246///
247/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000248void
Chris Lattner925e60d2007-12-28 05:29:59 +0000249Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
250 unsigned format_idx) {
251 Expr *Fn = TheCall->getCallee();
252
Ted Kremenek71895b92007-08-14 17:39:48 +0000253 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000254 if (format_idx >= TheCall->getNumArgs()) {
255 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000256 Fn->getSourceRange());
257 return;
258 }
259
Chris Lattner998568f2007-12-28 05:38:24 +0000260 Expr *OrigFormatExpr = IgnoreParenCasts(TheCall->getArg(format_idx));
Chris Lattner459e8482007-08-25 05:36:18 +0000261
Chris Lattner59907c42007-08-10 20:18:51 +0000262 // CHECK: format string is not a string literal.
263 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000264 // Dynamically generated format strings are difficult to
265 // automatically vet at compile time. Requiring that format strings
266 // are string literals: (1) permits the checking of format strings by
267 // the compiler and thereby (2) can practically remove the source of
268 // many format string exploits.
Chris Lattner459e8482007-08-25 05:36:18 +0000269 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000270 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000271 // For vprintf* functions (i.e., HasVAListArg==true), we add a
272 // special check to see if the format string is a function parameter
273 // of the function calling the printf function. If the function
274 // has an attribute indicating it is a printf-like function, then we
275 // should suppress warnings concerning non-literals being used in a call
276 // to a vprintf function. For example:
277 //
278 // void
279 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
280 // va_list ap;
281 // va_start(ap, fmt);
282 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
283 // ...
284 //
285 //
286 // FIXME: We don't have full attribute support yet, so just check to see
287 // if the argument is a DeclRefExpr that references a parameter. We'll
288 // add proper support for checking the attribute later.
289 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000290 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
291 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000292 return;
293
Chris Lattner925e60d2007-12-28 05:29:59 +0000294 Diag(TheCall->getArg(format_idx)->getLocStart(),
295 diag::warn_printf_not_string_constant, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000296 return;
297 }
298
299 // CHECK: is the format string a wide literal?
300 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000301 Diag(FExpr->getLocStart(),
302 diag::warn_printf_format_string_is_wide_literal, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000303 return;
304 }
305
306 // Str - The format string. NOTE: this is NOT null-terminated!
307 const char * const Str = FExpr->getStrData();
308
309 // CHECK: empty format string?
310 const unsigned StrLen = FExpr->getByteLength();
311
312 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000313 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
314 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000315 return;
316 }
317
318 // We process the format string using a binary state machine. The
319 // current state is stored in CurrentState.
320 enum {
321 state_OrdChr,
322 state_Conversion
323 } CurrentState = state_OrdChr;
324
325 // numConversions - The number of conversions seen so far. This is
326 // incremented as we traverse the format string.
327 unsigned numConversions = 0;
328
329 // numDataArgs - The number of data arguments after the format
330 // string. This can only be determined for non vprintf-like
331 // functions. For those functions, this value is 1 (the sole
332 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000333 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000334
335 // Inspect the format string.
336 unsigned StrIdx = 0;
337
338 // LastConversionIdx - Index within the format string where we last saw
339 // a '%' character that starts a new format conversion.
340 unsigned LastConversionIdx = 0;
341
Chris Lattner925e60d2007-12-28 05:29:59 +0000342 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000343
Ted Kremenek71895b92007-08-14 17:39:48 +0000344 // Is the number of detected conversion conversions greater than
345 // the number of matching data arguments? If so, stop.
346 if (!HasVAListArg && numConversions > numDataArgs) break;
347
348 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000349 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000350 // The string returned by getStrData() is not null-terminated,
351 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000352 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
353 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek71895b92007-08-14 17:39:48 +0000354 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000355 return;
356 }
357
358 // Ordinary characters (not processing a format conversion).
359 if (CurrentState == state_OrdChr) {
360 if (Str[StrIdx] == '%') {
361 CurrentState = state_Conversion;
362 LastConversionIdx = StrIdx;
363 }
364 continue;
365 }
366
367 // Seen '%'. Now processing a format conversion.
368 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000369 // Handle dynamic precision or width specifier.
370 case '*': {
371 ++numConversions;
372
373 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000374 SourceLocation Loc = FExpr->getLocStart();
375 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000376
Ted Kremenek580b6642007-10-12 20:51:52 +0000377 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000378 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
379 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000380 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000381 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
382 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000383
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000384 // Don't do any more checking. We'll just emit spurious errors.
385 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000386 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000387
388 // Perform type checking on width/precision specifier.
389 Expr *E = TheCall->getArg(format_idx+numConversions);
390 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
391 if (BT->getKind() == BuiltinType::Int)
392 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000393
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000394 SourceLocation Loc =
395 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
396
397 if (Str[StrIdx-1] == '.')
398 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
399 E->getType().getAsString(), E->getSourceRange());
400 else
401 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
402 E->getType().getAsString(), E->getSourceRange());
403
404 break;
405 }
406
407 // Characters which can terminate a format conversion
408 // (e.g. "%d"). Characters that specify length modifiers or
409 // other flags are handled by the default case below.
410 //
411 // FIXME: additional checks will go into the following cases.
412 case 'i':
413 case 'd':
414 case 'o':
415 case 'u':
416 case 'x':
417 case 'X':
418 case 'D':
419 case 'O':
420 case 'U':
421 case 'e':
422 case 'E':
423 case 'f':
424 case 'F':
425 case 'g':
426 case 'G':
427 case 'a':
428 case 'A':
429 case 'c':
430 case 'C':
431 case 'S':
432 case 's':
433 case 'p':
434 ++numConversions;
435 CurrentState = state_OrdChr;
436 break;
437
438 // CHECK: Are we using "%n"? Issue a warning.
439 case 'n': {
440 ++numConversions;
441 CurrentState = state_OrdChr;
442 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
443 LastConversionIdx+1);
444
445 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
446 break;
447 }
448
449 // Handle "%%"
450 case '%':
451 // Sanity check: Was the first "%" character the previous one?
452 // If not, we will assume that we have a malformed format
453 // conversion, and that the current "%" character is the start
454 // of a new conversion.
455 if (StrIdx - LastConversionIdx == 1)
456 CurrentState = state_OrdChr;
457 else {
458 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000459 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
460 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000461
462 Diag(Loc, diag::warn_printf_invalid_conversion,
463 std::string(Str+LastConversionIdx, Str+StrIdx),
464 Fn->getSourceRange());
465
466 // This conversion is broken. Advance to the next format
467 // conversion.
468 LastConversionIdx = StrIdx;
469 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000470 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000471 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000472
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000473 default:
474 // This case catches all other characters: flags, widths, etc.
475 // We should eventually process those as well.
476 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000477 }
478 }
479
480 if (CurrentState == state_Conversion) {
481 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000482 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
483 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000484
485 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000486 std::string(Str+LastConversionIdx,
487 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek71895b92007-08-14 17:39:48 +0000488 Fn->getSourceRange());
489 return;
490 }
491
492 if (!HasVAListArg) {
493 // CHECK: Does the number of format conversions exceed the number
494 // of data arguments?
495 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000496 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
497 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000498
499 Diag(Loc, diag::warn_printf_insufficient_data_args,
500 Fn->getSourceRange());
501 }
502 // CHECK: Does the number of data arguments exceed the number of
503 // format conversions in the format string?
504 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000505 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek71895b92007-08-14 17:39:48 +0000506 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
507 }
508}
Ted Kremenek06de2762007-08-17 16:46:58 +0000509
510//===--- CHECK: Return Address of Stack Variable --------------------------===//
511
512static DeclRefExpr* EvalVal(Expr *E);
513static DeclRefExpr* EvalAddr(Expr* E);
514
515/// CheckReturnStackAddr - Check if a return statement returns the address
516/// of a stack variable.
517void
518Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
519 SourceLocation ReturnLoc) {
520
521 // Perform checking for returned stack addresses.
522 if (lhsType->isPointerType()) {
523 if (DeclRefExpr *DR = EvalAddr(RetValExp))
524 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
525 DR->getDecl()->getIdentifier()->getName(),
526 RetValExp->getSourceRange());
527 }
528 // Perform checking for stack values returned by reference.
529 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000530 // Check for an implicit cast to a reference.
531 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
532 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
533 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
534 DR->getDecl()->getIdentifier()->getName(),
535 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000536 }
537}
538
539/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
540/// check if the expression in a return statement evaluates to an address
541/// to a location on the stack. The recursion is used to traverse the
542/// AST of the return expression, with recursion backtracking when we
543/// encounter a subexpression that (1) clearly does not lead to the address
544/// of a stack variable or (2) is something we cannot determine leads to
545/// the address of a stack variable based on such local checking.
546///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000547/// EvalAddr processes expressions that are pointers that are used as
548/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000549/// At the base case of the recursion is a check for a DeclRefExpr* in
550/// the refers to a stack variable.
551///
552/// This implementation handles:
553///
554/// * pointer-to-pointer casts
555/// * implicit conversions from array references to pointers
556/// * taking the address of fields
557/// * arbitrary interplay between "&" and "*" operators
558/// * pointer arithmetic from an address of a stack variable
559/// * taking the address of an array element where the array is on the stack
560static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000561 // We should only be called for evaluating pointer expressions.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000562 assert((E->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000563 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000564 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000565
566 // Our "symbolic interpreter" is just a dispatch off the currently
567 // viewed AST node. We then recursively traverse the AST by calling
568 // EvalAddr and EvalVal appropriately.
569 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000570 case Stmt::ParenExprClass:
571 // Ignore parentheses.
572 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000573
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000574 case Stmt::UnaryOperatorClass: {
575 // The only unary operator that make sense to handle here
576 // is AddrOf. All others don't make sense as pointers.
577 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000578
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000579 if (U->getOpcode() == UnaryOperator::AddrOf)
580 return EvalVal(U->getSubExpr());
581 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000582 return NULL;
583 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000584
585 case Stmt::BinaryOperatorClass: {
586 // Handle pointer arithmetic. All other binary operators are not valid
587 // in this context.
588 BinaryOperator *B = cast<BinaryOperator>(E);
589 BinaryOperator::Opcode op = B->getOpcode();
590
591 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
592 return NULL;
593
594 Expr *Base = B->getLHS();
595
596 // Determine which argument is the real pointer base. It could be
597 // the RHS argument instead of the LHS.
598 if (!Base->getType()->isPointerType()) Base = B->getRHS();
599
600 assert (Base->getType()->isPointerType());
601 return EvalAddr(Base);
602 }
603
604 // For conditional operators we need to see if either the LHS or RHS are
605 // valid DeclRefExpr*s. If one of them is valid, we return it.
606 case Stmt::ConditionalOperatorClass: {
607 ConditionalOperator *C = cast<ConditionalOperator>(E);
608
609 // Handle the GNU extension for missing LHS.
610 if (Expr *lhsExpr = C->getLHS())
611 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
612 return LHS;
613
614 return EvalAddr(C->getRHS());
615 }
616
617 // For implicit casts, we need to handle conversions from arrays to
618 // pointer values, and implicit pointer-to-pointer conversions.
619 case Stmt::ImplicitCastExprClass: {
620 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
621 Expr* SubExpr = IE->getSubExpr();
622
623 if (SubExpr->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000624 SubExpr->getType()->isObjCQualifiedIdType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000625 return EvalAddr(SubExpr);
626 else
627 return EvalVal(SubExpr);
628 }
629
630 // For casts, we handle pointer-to-pointer conversions (which
631 // is essentially a no-op from our mini-interpreter's standpoint).
632 // For other casts we abort.
633 case Stmt::CastExprClass: {
634 CastExpr *C = cast<CastExpr>(E);
635 Expr *SubExpr = C->getSubExpr();
636
637 if (SubExpr->getType()->isPointerType())
638 return EvalAddr(SubExpr);
639 else
640 return NULL;
641 }
642
643 // C++ casts. For dynamic casts, static casts, and const casts, we
644 // are always converting from a pointer-to-pointer, so we just blow
645 // through the cast. In the case the dynamic cast doesn't fail
646 // (and return NULL), we take the conservative route and report cases
647 // where we return the address of a stack variable. For Reinterpre
648 case Stmt::CXXCastExprClass: {
649 CXXCastExpr *C = cast<CXXCastExpr>(E);
650
651 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
652 Expr *S = C->getSubExpr();
653 if (S->getType()->isPointerType())
654 return EvalAddr(S);
655 else
656 return NULL;
657 }
658 else
659 return EvalAddr(C->getSubExpr());
660 }
661
662 // Everything else: we simply don't reason about them.
663 default:
664 return NULL;
665 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000666}
667
668
669/// EvalVal - This function is complements EvalAddr in the mutual recursion.
670/// See the comments for EvalAddr for more details.
671static DeclRefExpr* EvalVal(Expr *E) {
672
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000673 // We should only be called for evaluating non-pointer expressions, or
674 // expressions with a pointer type that are not used as references but instead
675 // are l-values (e.g., DeclRefExpr with a pointer type).
676
Ted Kremenek06de2762007-08-17 16:46:58 +0000677 // Our "symbolic interpreter" is just a dispatch off the currently
678 // viewed AST node. We then recursively traverse the AST by calling
679 // EvalAddr and EvalVal appropriately.
680 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000681 case Stmt::DeclRefExprClass: {
682 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
683 // at code that refers to a variable's name. We check if it has local
684 // storage within the function, and if so, return the expression.
685 DeclRefExpr *DR = cast<DeclRefExpr>(E);
686
687 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
688 if(V->hasLocalStorage()) return DR;
689
690 return NULL;
691 }
692
693 case Stmt::ParenExprClass:
694 // Ignore parentheses.
695 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
696
697 case Stmt::UnaryOperatorClass: {
698 // The only unary operator that make sense to handle here
699 // is Deref. All others don't resolve to a "name." This includes
700 // handling all sorts of rvalues passed to a unary operator.
701 UnaryOperator *U = cast<UnaryOperator>(E);
702
703 if (U->getOpcode() == UnaryOperator::Deref)
704 return EvalAddr(U->getSubExpr());
705
706 return NULL;
707 }
708
709 case Stmt::ArraySubscriptExprClass: {
710 // Array subscripts are potential references to data on the stack. We
711 // retrieve the DeclRefExpr* for the array variable if it indeed
712 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000713 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000714 }
715
716 case Stmt::ConditionalOperatorClass: {
717 // For conditional operators we need to see if either the LHS or RHS are
718 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
719 ConditionalOperator *C = cast<ConditionalOperator>(E);
720
Anders Carlsson39073232007-11-30 19:04:31 +0000721 // Handle the GNU extension for missing LHS.
722 if (Expr *lhsExpr = C->getLHS())
723 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
724 return LHS;
725
726 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000727 }
728
729 // Accesses to members are potential references to data on the stack.
730 case Stmt::MemberExprClass: {
731 MemberExpr *M = cast<MemberExpr>(E);
732
733 // Check for indirect access. We only want direct field accesses.
734 if (!M->isArrow())
735 return EvalVal(M->getBase());
736 else
737 return NULL;
738 }
739
740 // Everything else: we simply don't reason about them.
741 default:
742 return NULL;
743 }
744}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000745
746//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
747
748/// Check for comparisons of floating point operands using != and ==.
749/// Issue a warning if these are no self-comparisons, as they are not likely
750/// to do what the programmer intended.
751void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
752 bool EmitWarning = true;
753
754 Expr* LeftExprSansParen = IgnoreParen(lex);
755 Expr* RightExprSansParen = IgnoreParen(rex);
756
757 // Special case: check for x == x (which is OK).
758 // Do not emit warnings for such cases.
759 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
760 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
761 if (DRL->getDecl() == DRR->getDecl())
762 EmitWarning = false;
763
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000764
765 // Special case: check for comparisons against literals that can be exactly
766 // represented by APFloat. In such cases, do not emit a warning. This
767 // is a heuristic: often comparison against such literals are used to
768 // detect if a value in a variable has not changed. This clearly can
769 // lead to false negatives.
770 if (EmitWarning) {
771 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
772 if (FLL->isExact())
773 EmitWarning = false;
774 }
775 else
776 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
777 if (FLR->isExact())
778 EmitWarning = false;
779 }
780 }
781
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000782 // Check for comparisons with builtin types.
783 if (EmitWarning)
784 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
785 if (isCallBuiltin(CL))
786 EmitWarning = false;
787
788 if (EmitWarning)
789 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
790 if (isCallBuiltin(CR))
791 EmitWarning = false;
792
793 // Emit the diagnostic.
794 if (EmitWarning)
795 Diag(loc, diag::warn_floatingpoint_eq,
796 lex->getSourceRange(),rex->getSourceRange());
797}