blob: d7b8de2f1597a6d6a2e89369433b45a4fa4cca9b [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Ted Kremenek and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringExtras.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000028#include "SemaUtil.h"
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 Lattner459e8482007-08-25 05:36:18 +000091 // FIXME: This should go in a helper.
Chris Lattnercc6f65d2007-08-25 05:30:33 +000092 while (1) {
93 if (ParenExpr *PE = dyn_cast<ParenExpr>(Arg))
94 Arg = PE->getSubExpr();
95 else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
96 Arg = ICE->getSubExpr();
97 else
98 break;
99 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000100
101 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
102
103 if (!Literal || Literal->isWide()) {
104 Diag(Arg->getLocStart(),
105 diag::err_cfstring_literal_not_string_constant,
106 Arg->getSourceRange());
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000107 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000108 }
109
110 const char *Data = Literal->getStrData();
111 unsigned Length = Literal->getByteLength();
112
113 for (unsigned i = 0; i < Length; ++i) {
114 if (!isascii(Data[i])) {
115 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
116 diag::warn_cfstring_literal_contains_non_ascii_character,
117 Arg->getSourceRange());
118 break;
119 }
120
121 if (!Data[i]) {
122 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
123 diag::warn_cfstring_literal_contains_nul_character,
124 Arg->getSourceRange());
125 break;
126 }
127 }
128
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000129 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000130}
131
Chris Lattnerc27c6652007-12-20 00:05:45 +0000132/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
133/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000134bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
135 Expr *Fn = TheCall->getCallee();
136 if (TheCall->getNumArgs() > 2) {
137 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000138 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000139 SourceRange(TheCall->getArg(2)->getLocStart(),
140 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner30ce3442007-12-19 23:59:04 +0000141 return true;
142 }
143
Chris Lattnerc27c6652007-12-20 00:05:45 +0000144 // Determine whether the current function is variadic or not.
145 bool isVariadic;
Chris Lattner30ce3442007-12-19 23:59:04 +0000146 if (CurFunctionDecl)
Chris Lattnerc27c6652007-12-20 00:05:45 +0000147 isVariadic =
148 cast<FunctionTypeProto>(CurFunctionDecl->getType())->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000149 else
Chris Lattnerc27c6652007-12-20 00:05:45 +0000150 isVariadic = CurMethodDecl->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000151
Chris Lattnerc27c6652007-12-20 00:05:45 +0000152 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000153 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
154 return true;
155 }
156
157 // Verify that the second argument to the builtin is the last argument of the
158 // current function or method.
159 bool SecondArgIsLastNamedArgument = false;
Chris Lattner925e60d2007-12-28 05:29:59 +0000160 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(TheCall->getArg(1))) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000161 if (ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
162 // FIXME: This isn't correct for methods (results in bogus warning).
163 // Get the last formal in the current function.
164 ParmVarDecl *LastArg;
165 if (CurFunctionDecl)
166 LastArg = *(CurFunctionDecl->param_end()-1);
167 else
168 LastArg = *(CurMethodDecl->param_end()-1);
169 SecondArgIsLastNamedArgument = PV == LastArg;
170 }
171 }
172
173 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000174 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000175 diag::warn_second_parameter_of_va_start_not_last_named_argument);
176 return false;
177}
178
Chris Lattner1b9a0792007-12-20 00:26:33 +0000179/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
180/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000181bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
182 if (TheCall->getNumArgs() < 2)
183 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
184 if (TheCall->getNumArgs() > 2)
185 return Diag(TheCall->getArg(2)->getLocStart(),
186 diag::err_typecheck_call_too_many_args,
187 SourceRange(TheCall->getArg(2)->getLocStart(),
188 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000189
Chris Lattner925e60d2007-12-28 05:29:59 +0000190 Expr *OrigArg0 = TheCall->getArg(0);
191 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000192
193 // Do standard promotions between the two arguments, returning their common
194 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000195 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000196
197 // If the common type isn't a real floating type, then the arguments were
198 // invalid for this operation.
199 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000200 return Diag(OrigArg0->getLocStart(),
Chris Lattner1b9a0792007-12-20 00:26:33 +0000201 diag::err_typecheck_call_invalid_ordered_compare,
202 OrigArg0->getType().getAsString(),
203 OrigArg1->getType().getAsString(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000204 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000205
206 return false;
207}
208
Chris Lattner30ce3442007-12-19 23:59:04 +0000209
Chris Lattner59907c42007-08-10 20:18:51 +0000210/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000211/// correct use of format strings.
212///
213/// HasVAListArg - A predicate indicating whether the printf-like
214/// function is passed an explicit va_arg argument (e.g., vprintf)
215///
216/// format_idx - The index into Args for the format string.
217///
218/// Improper format strings to functions in the printf family can be
219/// the source of bizarre bugs and very serious security holes. A
220/// good source of information is available in the following paper
221/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000222///
223/// FormatGuard: Automatic Protection From printf Format String
224/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000225///
226/// Functionality implemented:
227///
228/// We can statically check the following properties for string
229/// literal format strings for non v.*printf functions (where the
230/// arguments are passed directly):
231//
232/// (1) Are the number of format conversions equal to the number of
233/// data arguments?
234///
235/// (2) Does each format conversion correctly match the type of the
236/// corresponding data argument? (TODO)
237///
238/// Moreover, for all printf functions we can:
239///
240/// (3) Check for a missing format string (when not caught by type checking).
241///
242/// (4) Check for no-operation flags; e.g. using "#" with format
243/// conversion 'c' (TODO)
244///
245/// (5) Check the use of '%n', a major source of security holes.
246///
247/// (6) Check for malformed format conversions that don't specify anything.
248///
249/// (7) Check for empty format strings. e.g: printf("");
250///
251/// (8) Check that the format string is a wide literal.
252///
253/// All of these checks can be done by parsing the format string.
254///
255/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000256void
Chris Lattner925e60d2007-12-28 05:29:59 +0000257Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
258 unsigned format_idx) {
259 Expr *Fn = TheCall->getCallee();
260
Ted Kremenek71895b92007-08-14 17:39:48 +0000261 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000262 if (format_idx >= TheCall->getNumArgs()) {
263 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000264 Fn->getSourceRange());
265 return;
266 }
267
Chris Lattner925e60d2007-12-28 05:29:59 +0000268 Expr *OrigFormatExpr = TheCall->getArg(format_idx);
Chris Lattner459e8482007-08-25 05:36:18 +0000269 // FIXME: This should go in a helper.
270 while (1) {
271 if (ParenExpr *PE = dyn_cast<ParenExpr>(OrigFormatExpr))
272 OrigFormatExpr = PE->getSubExpr();
273 else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(OrigFormatExpr))
274 OrigFormatExpr = ICE->getSubExpr();
275 else
276 break;
277 }
278
Chris Lattner59907c42007-08-10 20:18:51 +0000279 // CHECK: format string is not a string literal.
280 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000281 // Dynamically generated format strings are difficult to
282 // automatically vet at compile time. Requiring that format strings
283 // are string literals: (1) permits the checking of format strings by
284 // the compiler and thereby (2) can practically remove the source of
285 // many format string exploits.
Chris Lattner459e8482007-08-25 05:36:18 +0000286 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Chris Lattner59907c42007-08-10 20:18:51 +0000287
Ted Kremenek71895b92007-08-14 17:39:48 +0000288 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000289 // For vprintf* functions (i.e., HasVAListArg==true), we add a
290 // special check to see if the format string is a function parameter
291 // of the function calling the printf function. If the function
292 // has an attribute indicating it is a printf-like function, then we
293 // should suppress warnings concerning non-literals being used in a call
294 // to a vprintf function. For example:
295 //
296 // void
297 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
298 // va_list ap;
299 // va_start(ap, fmt);
300 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
301 // ...
302 //
303 //
304 // FIXME: We don't have full attribute support yet, so just check to see
305 // if the argument is a DeclRefExpr that references a parameter. We'll
306 // add proper support for checking the attribute later.
307 if (HasVAListArg)
308 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(IgnoreParen(OrigFormatExpr)))
309 if (isa<ParmVarDecl>(DR->getDecl()))
310 return;
311
Chris Lattner925e60d2007-12-28 05:29:59 +0000312 Diag(TheCall->getArg(format_idx)->getLocStart(),
313 diag::warn_printf_not_string_constant, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000314 return;
315 }
316
317 // CHECK: is the format string a wide literal?
318 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000319 Diag(FExpr->getLocStart(),
320 diag::warn_printf_format_string_is_wide_literal, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000321 return;
322 }
323
324 // Str - The format string. NOTE: this is NOT null-terminated!
325 const char * const Str = FExpr->getStrData();
326
327 // CHECK: empty format string?
328 const unsigned StrLen = FExpr->getByteLength();
329
330 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000331 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
332 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000333 return;
334 }
335
336 // We process the format string using a binary state machine. The
337 // current state is stored in CurrentState.
338 enum {
339 state_OrdChr,
340 state_Conversion
341 } CurrentState = state_OrdChr;
342
343 // numConversions - The number of conversions seen so far. This is
344 // incremented as we traverse the format string.
345 unsigned numConversions = 0;
346
347 // numDataArgs - The number of data arguments after the format
348 // string. This can only be determined for non vprintf-like
349 // functions. For those functions, this value is 1 (the sole
350 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000351 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000352
353 // Inspect the format string.
354 unsigned StrIdx = 0;
355
356 // LastConversionIdx - Index within the format string where we last saw
357 // a '%' character that starts a new format conversion.
358 unsigned LastConversionIdx = 0;
359
Chris Lattner925e60d2007-12-28 05:29:59 +0000360 for (; StrIdx < StrLen; ++StrIdx) {
Ted Kremenek71895b92007-08-14 17:39:48 +0000361
362 // Is the number of detected conversion conversions greater than
363 // the number of matching data arguments? If so, stop.
364 if (!HasVAListArg && numConversions > numDataArgs) break;
365
366 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000367 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000368 // The string returned by getStrData() is not null-terminated,
369 // so the presence of a null character is likely an error.
Chris Lattner925e60d2007-12-28 05:29:59 +0000370 SourceLocation Loc = FExpr->getLocStart();
371 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000372
373 Diag(Loc, diag::warn_printf_format_string_contains_null_char,
374 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000375 return;
376 }
377
378 // Ordinary characters (not processing a format conversion).
379 if (CurrentState == state_OrdChr) {
380 if (Str[StrIdx] == '%') {
381 CurrentState = state_Conversion;
382 LastConversionIdx = StrIdx;
383 }
384 continue;
385 }
386
387 // Seen '%'. Now processing a format conversion.
388 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000389 // Handle dynamic precision or width specifier.
390 case '*': {
391 ++numConversions;
392
393 if (!HasVAListArg && numConversions > numDataArgs) {
Ted Kremenek580b6642007-10-12 20:51:52 +0000394
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000395 SourceLocation Loc = FExpr->getLocStart();
396 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000397
Ted Kremenek580b6642007-10-12 20:51:52 +0000398 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000399 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
400 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000401 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000402 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
403 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000404
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000405 // Don't do any more checking. We'll just emit spurious errors.
406 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000407 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000408
409 // Perform type checking on width/precision specifier.
410 Expr *E = TheCall->getArg(format_idx+numConversions);
411 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
412 if (BT->getKind() == BuiltinType::Int)
413 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000414
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000415 SourceLocation Loc =
416 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
417
418 if (Str[StrIdx-1] == '.')
419 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
420 E->getType().getAsString(), E->getSourceRange());
421 else
422 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
423 E->getType().getAsString(), E->getSourceRange());
424
425 break;
426 }
427
428 // Characters which can terminate a format conversion
429 // (e.g. "%d"). Characters that specify length modifiers or
430 // other flags are handled by the default case below.
431 //
432 // FIXME: additional checks will go into the following cases.
433 case 'i':
434 case 'd':
435 case 'o':
436 case 'u':
437 case 'x':
438 case 'X':
439 case 'D':
440 case 'O':
441 case 'U':
442 case 'e':
443 case 'E':
444 case 'f':
445 case 'F':
446 case 'g':
447 case 'G':
448 case 'a':
449 case 'A':
450 case 'c':
451 case 'C':
452 case 'S':
453 case 's':
454 case 'p':
455 ++numConversions;
456 CurrentState = state_OrdChr;
457 break;
458
459 // CHECK: Are we using "%n"? Issue a warning.
460 case 'n': {
461 ++numConversions;
462 CurrentState = state_OrdChr;
463 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
464 LastConversionIdx+1);
465
466 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
467 break;
468 }
469
470 // Handle "%%"
471 case '%':
472 // Sanity check: Was the first "%" character the previous one?
473 // If not, we will assume that we have a malformed format
474 // conversion, and that the current "%" character is the start
475 // of a new conversion.
476 if (StrIdx - LastConversionIdx == 1)
477 CurrentState = state_OrdChr;
478 else {
479 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000480 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
481 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000482
483 Diag(Loc, diag::warn_printf_invalid_conversion,
484 std::string(Str+LastConversionIdx, Str+StrIdx),
485 Fn->getSourceRange());
486
487 // This conversion is broken. Advance to the next format
488 // conversion.
489 LastConversionIdx = StrIdx;
490 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000491 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000492
493 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000494
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000495 default:
496 // This case catches all other characters: flags, widths, etc.
497 // We should eventually process those as well.
498 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000499 }
500 }
501
502 if (CurrentState == state_Conversion) {
503 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000504 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
505 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000506
507 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000508 std::string(Str+LastConversionIdx,
509 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek71895b92007-08-14 17:39:48 +0000510 Fn->getSourceRange());
511 return;
512 }
513
514 if (!HasVAListArg) {
515 // CHECK: Does the number of format conversions exceed the number
516 // of data arguments?
517 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000518 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
519 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000520
521 Diag(Loc, diag::warn_printf_insufficient_data_args,
522 Fn->getSourceRange());
523 }
524 // CHECK: Does the number of data arguments exceed the number of
525 // format conversions in the format string?
526 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000527 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek71895b92007-08-14 17:39:48 +0000528 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
529 }
530}
Ted Kremenek06de2762007-08-17 16:46:58 +0000531
532//===--- CHECK: Return Address of Stack Variable --------------------------===//
533
534static DeclRefExpr* EvalVal(Expr *E);
535static DeclRefExpr* EvalAddr(Expr* E);
536
537/// CheckReturnStackAddr - Check if a return statement returns the address
538/// of a stack variable.
539void
540Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
541 SourceLocation ReturnLoc) {
542
543 // Perform checking for returned stack addresses.
544 if (lhsType->isPointerType()) {
545 if (DeclRefExpr *DR = EvalAddr(RetValExp))
546 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
547 DR->getDecl()->getIdentifier()->getName(),
548 RetValExp->getSourceRange());
549 }
550 // Perform checking for stack values returned by reference.
551 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000552 // Check for an implicit cast to a reference.
553 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
554 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
555 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
556 DR->getDecl()->getIdentifier()->getName(),
557 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000558 }
559}
560
561/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
562/// check if the expression in a return statement evaluates to an address
563/// to a location on the stack. The recursion is used to traverse the
564/// AST of the return expression, with recursion backtracking when we
565/// encounter a subexpression that (1) clearly does not lead to the address
566/// of a stack variable or (2) is something we cannot determine leads to
567/// the address of a stack variable based on such local checking.
568///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000569/// EvalAddr processes expressions that are pointers that are used as
570/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000571/// At the base case of the recursion is a check for a DeclRefExpr* in
572/// the refers to a stack variable.
573///
574/// This implementation handles:
575///
576/// * pointer-to-pointer casts
577/// * implicit conversions from array references to pointers
578/// * taking the address of fields
579/// * arbitrary interplay between "&" and "*" operators
580/// * pointer arithmetic from an address of a stack variable
581/// * taking the address of an array element where the array is on the stack
582static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000583 // We should only be called for evaluating pointer expressions.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000584 assert((E->getType()->isPointerType() ||
585 E->getType()->isObjcQualifiedIdType()) &&
586 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000587
588 // Our "symbolic interpreter" is just a dispatch off the currently
589 // viewed AST node. We then recursively traverse the AST by calling
590 // EvalAddr and EvalVal appropriately.
591 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000592 case Stmt::ParenExprClass:
593 // Ignore parentheses.
594 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000595
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000596 case Stmt::UnaryOperatorClass: {
597 // The only unary operator that make sense to handle here
598 // is AddrOf. All others don't make sense as pointers.
599 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000600
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000601 if (U->getOpcode() == UnaryOperator::AddrOf)
602 return EvalVal(U->getSubExpr());
603 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000604 return NULL;
605 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000606
607 case Stmt::BinaryOperatorClass: {
608 // Handle pointer arithmetic. All other binary operators are not valid
609 // in this context.
610 BinaryOperator *B = cast<BinaryOperator>(E);
611 BinaryOperator::Opcode op = B->getOpcode();
612
613 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
614 return NULL;
615
616 Expr *Base = B->getLHS();
617
618 // Determine which argument is the real pointer base. It could be
619 // the RHS argument instead of the LHS.
620 if (!Base->getType()->isPointerType()) Base = B->getRHS();
621
622 assert (Base->getType()->isPointerType());
623 return EvalAddr(Base);
624 }
625
626 // For conditional operators we need to see if either the LHS or RHS are
627 // valid DeclRefExpr*s. If one of them is valid, we return it.
628 case Stmt::ConditionalOperatorClass: {
629 ConditionalOperator *C = cast<ConditionalOperator>(E);
630
631 // Handle the GNU extension for missing LHS.
632 if (Expr *lhsExpr = C->getLHS())
633 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
634 return LHS;
635
636 return EvalAddr(C->getRHS());
637 }
638
639 // For implicit casts, we need to handle conversions from arrays to
640 // pointer values, and implicit pointer-to-pointer conversions.
641 case Stmt::ImplicitCastExprClass: {
642 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
643 Expr* SubExpr = IE->getSubExpr();
644
645 if (SubExpr->getType()->isPointerType() ||
646 SubExpr->getType()->isObjcQualifiedIdType())
647 return EvalAddr(SubExpr);
648 else
649 return EvalVal(SubExpr);
650 }
651
652 // For casts, we handle pointer-to-pointer conversions (which
653 // is essentially a no-op from our mini-interpreter's standpoint).
654 // For other casts we abort.
655 case Stmt::CastExprClass: {
656 CastExpr *C = cast<CastExpr>(E);
657 Expr *SubExpr = C->getSubExpr();
658
659 if (SubExpr->getType()->isPointerType())
660 return EvalAddr(SubExpr);
661 else
662 return NULL;
663 }
664
665 // C++ casts. For dynamic casts, static casts, and const casts, we
666 // are always converting from a pointer-to-pointer, so we just blow
667 // through the cast. In the case the dynamic cast doesn't fail
668 // (and return NULL), we take the conservative route and report cases
669 // where we return the address of a stack variable. For Reinterpre
670 case Stmt::CXXCastExprClass: {
671 CXXCastExpr *C = cast<CXXCastExpr>(E);
672
673 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
674 Expr *S = C->getSubExpr();
675 if (S->getType()->isPointerType())
676 return EvalAddr(S);
677 else
678 return NULL;
679 }
680 else
681 return EvalAddr(C->getSubExpr());
682 }
683
684 // Everything else: we simply don't reason about them.
685 default:
686 return NULL;
687 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000688}
689
690
691/// EvalVal - This function is complements EvalAddr in the mutual recursion.
692/// See the comments for EvalAddr for more details.
693static DeclRefExpr* EvalVal(Expr *E) {
694
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000695 // We should only be called for evaluating non-pointer expressions, or
696 // expressions with a pointer type that are not used as references but instead
697 // are l-values (e.g., DeclRefExpr with a pointer type).
698
Ted Kremenek06de2762007-08-17 16:46:58 +0000699 // Our "symbolic interpreter" is just a dispatch off the currently
700 // viewed AST node. We then recursively traverse the AST by calling
701 // EvalAddr and EvalVal appropriately.
702 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000703 case Stmt::DeclRefExprClass: {
704 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
705 // at code that refers to a variable's name. We check if it has local
706 // storage within the function, and if so, return the expression.
707 DeclRefExpr *DR = cast<DeclRefExpr>(E);
708
709 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
710 if(V->hasLocalStorage()) return DR;
711
712 return NULL;
713 }
714
715 case Stmt::ParenExprClass:
716 // Ignore parentheses.
717 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
718
719 case Stmt::UnaryOperatorClass: {
720 // The only unary operator that make sense to handle here
721 // is Deref. All others don't resolve to a "name." This includes
722 // handling all sorts of rvalues passed to a unary operator.
723 UnaryOperator *U = cast<UnaryOperator>(E);
724
725 if (U->getOpcode() == UnaryOperator::Deref)
726 return EvalAddr(U->getSubExpr());
727
728 return NULL;
729 }
730
731 case Stmt::ArraySubscriptExprClass: {
732 // Array subscripts are potential references to data on the stack. We
733 // retrieve the DeclRefExpr* for the array variable if it indeed
734 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000735 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000736 }
737
738 case Stmt::ConditionalOperatorClass: {
739 // For conditional operators we need to see if either the LHS or RHS are
740 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
741 ConditionalOperator *C = cast<ConditionalOperator>(E);
742
Anders Carlsson39073232007-11-30 19:04:31 +0000743 // Handle the GNU extension for missing LHS.
744 if (Expr *lhsExpr = C->getLHS())
745 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
746 return LHS;
747
748 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000749 }
750
751 // Accesses to members are potential references to data on the stack.
752 case Stmt::MemberExprClass: {
753 MemberExpr *M = cast<MemberExpr>(E);
754
755 // Check for indirect access. We only want direct field accesses.
756 if (!M->isArrow())
757 return EvalVal(M->getBase());
758 else
759 return NULL;
760 }
761
762 // Everything else: we simply don't reason about them.
763 default:
764 return NULL;
765 }
766}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000767
768//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
769
770/// Check for comparisons of floating point operands using != and ==.
771/// Issue a warning if these are no self-comparisons, as they are not likely
772/// to do what the programmer intended.
773void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
774 bool EmitWarning = true;
775
776 Expr* LeftExprSansParen = IgnoreParen(lex);
777 Expr* RightExprSansParen = IgnoreParen(rex);
778
779 // Special case: check for x == x (which is OK).
780 // Do not emit warnings for such cases.
781 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
782 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
783 if (DRL->getDecl() == DRR->getDecl())
784 EmitWarning = false;
785
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000786
787 // Special case: check for comparisons against literals that can be exactly
788 // represented by APFloat. In such cases, do not emit a warning. This
789 // is a heuristic: often comparison against such literals are used to
790 // detect if a value in a variable has not changed. This clearly can
791 // lead to false negatives.
792 if (EmitWarning) {
793 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
794 if (FLL->isExact())
795 EmitWarning = false;
796 }
797 else
798 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
799 if (FLR->isExact())
800 EmitWarning = false;
801 }
802 }
803
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000804 // Check for comparisons with builtin types.
805 if (EmitWarning)
806 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
807 if (isCallBuiltin(CL))
808 EmitWarning = false;
809
810 if (EmitWarning)
811 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
812 if (isCallBuiltin(CR))
813 EmitWarning = false;
814
815 // Emit the diagnostic.
816 if (EmitWarning)
817 Diag(loc, diag::warn_floatingpoint_eq,
818 lex->getSourceRange(),rex->getSourceRange());
819}