blob: f469684e50323a3f6e555e4782a3c5a051bb2c8b [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"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021using namespace clang;
22
Chris Lattner60800082009-02-18 17:49:48 +000023/// getLocationOfStringLiteralByte - Return a source location that points to the
24/// specified byte of the specified string literal.
25///
26/// Strings are amazingly complex. They can be formed from multiple tokens and
27/// can have escape sequences in them in addition to the usual trigraph and
28/// escaped newline business. This routine handles this complexity.
29///
30SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
31 unsigned ByteNo) const {
32 assert(!SL->isWide() && "This doesn't work for wide strings yet");
33
34 // Loop over all of the tokens in this string until we find the one that
35 // contains the byte we're looking for.
36 unsigned TokNo = 0;
37 while (1) {
38 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
39 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
40
41 // Get the spelling of the string so that we can get the data that makes up
42 // the string literal, not the identifier for the macro it is potentially
43 // expanded through.
44 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
45
46 // Re-lex the token to get its length and original spelling.
47 std::pair<FileID, unsigned> LocInfo =
48 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
49 std::pair<const char *,const char *> Buffer =
50 SourceMgr.getBufferData(LocInfo.first);
51 const char *StrData = Buffer.first+LocInfo.second;
52
53 // Create a langops struct and enable trigraphs. This is sufficient for
54 // relexing tokens.
55 LangOptions LangOpts;
56 LangOpts.Trigraphs = true;
57
58 // Create a lexer starting at the beginning of this token.
59 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
60 Buffer.second);
61 Token TheTok;
62 TheLexer.LexFromRawLexer(TheTok);
63
64 // The length of the string is the token length minus the two quotes.
65 unsigned TokNumBytes = TheTok.getLength()-2;
66
67 // If we found the token we're looking for, return the location.
68 // FIXME: This should consider character escapes!
69 if (ByteNo < TokNumBytes ||
70 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
71 // If the original token came from a macro expansion, just return the
72 // start of the token. We don't want to magically jump to the spelling
73 // for a diagnostic. We do the above business in case some tokens come
74 // from a macro expansion but others don't.
75 if (!StrTokLoc.isFileID()) return StrTokLoc;
76
77 // We advance +1 to step over the '"'.
78 return PP.AdvanceToTokenCharacter(StrTokLoc, ByteNo+1);
79 }
80
81 // Move to the next string token.
82 ++TokNo;
83 ByteNo -= TokNumBytes;
84 }
85}
86
87
Chris Lattner59907c42007-08-10 20:18:51 +000088/// CheckFunctionCall - Check a direct function call for various correctness
89/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000090Action::OwningExprResult
91Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
92 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000093 // Get the IdentifierInfo* for the called function.
94 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000095
96 // None of the checks below are needed for functions that don't have
97 // simple names (e.g., C++ conversion functions).
98 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000099 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +0000100
Douglas Gregor3c385e52009-02-14 18:57:46 +0000101 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000102 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000103 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000104 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000105 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000106 return ExprError();
107 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000108 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000109 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000110 if (SemaBuiltinVAStart(TheCall))
111 return ExprError();
112 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000113 case Builtin::BI__builtin_isgreater:
114 case Builtin::BI__builtin_isgreaterequal:
115 case Builtin::BI__builtin_isless:
116 case Builtin::BI__builtin_islessequal:
117 case Builtin::BI__builtin_islessgreater:
118 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119 if (SemaBuiltinUnorderedCompare(TheCall))
120 return ExprError();
121 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000122 case Builtin::BI__builtin_return_address:
123 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000124 if (SemaBuiltinStackAddress(TheCall))
125 return ExprError();
126 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000127 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 return SemaBuiltinShuffleVector(TheCall);
129 // TheCall will be freed by the smart pointer here, but that's fine, since
130 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000131 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 if (SemaBuiltinPrefetch(TheCall))
133 return ExprError();
134 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000135 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinObjectSize(TheCall))
137 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000138 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000139
140 // FIXME: This mechanism should be abstracted to be less fragile and
141 // more efficient. For example, just map function ids to custom
142 // handlers.
143
Chris Lattner59907c42007-08-10 20:18:51 +0000144 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000145 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
146 if (Format->getType() == "printf") {
147 bool HasVAListArg = false;
148 if (const FunctionTypeProto *Proto
149 = FDecl->getType()->getAsFunctionTypeProto())
150 HasVAListArg = !Proto->isVariadic();
151 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
152 Format->getFirstArg() - 1);
153 }
Chris Lattner59907c42007-08-10 20:18:51 +0000154 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155
156 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000157}
158
Chris Lattner69039812009-02-18 06:01:06 +0000159/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000160/// CFString constructor is correct
Chris Lattner69039812009-02-18 06:01:06 +0000161bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000162 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000163 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
164
165 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000166 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
167 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000168 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000169 }
170
171 const char *Data = Literal->getStrData();
172 unsigned Length = Literal->getByteLength();
173
174 for (unsigned i = 0; i < Length; ++i) {
175 if (!isascii(Data[i])) {
Chris Lattner60800082009-02-18 17:49:48 +0000176 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000177 diag::warn_cfstring_literal_contains_non_ascii_character)
178 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000179 break;
180 }
181
182 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000183 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000184 diag::warn_cfstring_literal_contains_nul_character)
185 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000186 break;
187 }
188 }
189
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000190 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000191}
192
Chris Lattnerc27c6652007-12-20 00:05:45 +0000193/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
194/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000195bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
196 Expr *Fn = TheCall->getCallee();
197 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000198 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000199 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000200 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000201 << SourceRange(TheCall->getArg(2)->getLocStart(),
202 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000203 return true;
204 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000205
206 if (TheCall->getNumArgs() < 2) {
207 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
208 << 0 /*function call*/;
209 }
210
Chris Lattnerc27c6652007-12-20 00:05:45 +0000211 // Determine whether the current function is variadic or not.
212 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000213 if (getCurFunctionDecl()) {
214 if (FunctionTypeProto* FTP =
215 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
216 isVariadic = FTP->isVariadic();
217 else
218 isVariadic = false;
219 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000220 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000221 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000222
Chris Lattnerc27c6652007-12-20 00:05:45 +0000223 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000224 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
225 return true;
226 }
227
228 // Verify that the second argument to the builtin is the last argument of the
229 // current function or method.
230 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000231 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000232
233 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
234 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000235 // FIXME: This isn't correct for methods (results in bogus warning).
236 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000237 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000238 if (FunctionDecl *FD = getCurFunctionDecl())
239 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000240 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000241 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000242 SecondArgIsLastNamedArgument = PV == LastArg;
243 }
244 }
245
246 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000247 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000248 diag::warn_second_parameter_of_va_start_not_last_named_argument);
249 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000250}
Chris Lattner30ce3442007-12-19 23:59:04 +0000251
Chris Lattner1b9a0792007-12-20 00:26:33 +0000252/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
253/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000254bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
255 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000256 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
257 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000258 if (TheCall->getNumArgs() > 2)
259 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000260 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000261 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000262 << SourceRange(TheCall->getArg(2)->getLocStart(),
263 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000264
Chris Lattner925e60d2007-12-28 05:29:59 +0000265 Expr *OrigArg0 = TheCall->getArg(0);
266 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000267
268 // Do standard promotions between the two arguments, returning their common
269 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000270 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000271
272 // If the common type isn't a real floating type, then the arguments were
273 // invalid for this operation.
274 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000275 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000276 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000277 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000278 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000279
280 return false;
281}
282
Eli Friedman6cfda232008-05-20 08:23:37 +0000283bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
284 // The signature for these builtins is exact; the only thing we need
285 // to check is that the argument is a constant.
286 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000287 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000288 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000289
Eli Friedman6cfda232008-05-20 08:23:37 +0000290 return false;
291}
292
Eli Friedmand38617c2008-05-14 19:38:39 +0000293/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
294// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000295Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000296 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000297 return ExprError(Diag(TheCall->getLocEnd(),
298 diag::err_typecheck_call_too_few_args)
299 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000300
301 QualType FAType = TheCall->getArg(0)->getType();
302 QualType SAType = TheCall->getArg(1)->getType();
303
304 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000305 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
306 << SourceRange(TheCall->getArg(0)->getLocStart(),
307 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000308 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000309 }
310
Chris Lattnerb77792e2008-07-26 22:17:49 +0000311 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
312 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000313 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
314 << SourceRange(TheCall->getArg(0)->getLocStart(),
315 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000316 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000317 }
318
319 unsigned numElements = FAType->getAsVectorType()->getNumElements();
320 if (TheCall->getNumArgs() != numElements+2) {
321 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000322 return ExprError(Diag(TheCall->getLocEnd(),
323 diag::err_typecheck_call_too_few_args)
324 << 0 /*function call*/ << TheCall->getSourceRange());
325 return ExprError(Diag(TheCall->getLocEnd(),
326 diag::err_typecheck_call_too_many_args)
327 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000328 }
329
330 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
331 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000332 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000333 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000334 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000335 << TheCall->getArg(i)->getSourceRange());
336
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000337 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000338 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000339 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000340 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000341 }
342
343 llvm::SmallVector<Expr*, 32> exprs;
344
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000345 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000346 exprs.push_back(TheCall->getArg(i));
347 TheCall->setArg(i, 0);
348 }
349
Ted Kremenek8189cde2009-02-07 01:47:29 +0000350 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
351 FAType,
352 TheCall->getCallee()->getLocStart(),
353 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000354}
Chris Lattner30ce3442007-12-19 23:59:04 +0000355
Daniel Dunbar4493f792008-07-21 22:59:13 +0000356/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
357// This is declared to take (const void*, ...) and can take two
358// optional constant int args.
359bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000360 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000361
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000362 if (NumArgs > 3)
363 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000364 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000365
366 // Argument 0 is checked for us and the remaining arguments must be
367 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000368 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000369 Expr *Arg = TheCall->getArg(i);
370 QualType RWType = Arg->getType();
371
372 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000373 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000374 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000375 !Arg->isIntegerConstantExpr(Result, Context))
376 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
377 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000378
379 // FIXME: gcc issues a warning and rewrites these to 0. These
380 // seems especially odd for the third argument since the default
381 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000382 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000383 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000384 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
385 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000386 } else {
387 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000388 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
389 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000390 }
391 }
392
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000393 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000394}
395
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000396/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
397/// int type). This simply type checks that type is one of the defined
398/// constants (0-3).
399bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
400 Expr *Arg = TheCall->getArg(1);
401 QualType ArgType = Arg->getType();
402 const BuiltinType *BT = ArgType->getAsBuiltinType();
403 llvm::APSInt Result(32);
404 if (!BT || BT->getKind() != BuiltinType::Int ||
405 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000406 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
407 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000408 }
409
410 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000411 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
412 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000413 }
414
415 return false;
416}
417
Ted Kremenekd30ef872009-01-12 23:09:09 +0000418// Handle i > 1 ? "x" : "y", recursivelly
419bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000420 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000421
422 switch (E->getStmtClass()) {
423 case Stmt::ConditionalOperatorClass: {
424 ConditionalOperator *C = cast<ConditionalOperator>(E);
425 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000426 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000427 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000428 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000429 }
430
431 case Stmt::ImplicitCastExprClass: {
432 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
433 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000434 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000435 }
436
437 case Stmt::ParenExprClass: {
438 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
439 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000440 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000441 }
442
443 default: {
444 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
445 StringLiteral *StrE = NULL;
446
447 if (ObjCFExpr)
448 StrE = ObjCFExpr->getString();
449 else
450 StrE = dyn_cast<StringLiteral>(E);
451
452 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000453 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
454 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000455 return true;
456 }
457
458 return false;
459 }
460 }
461}
462
463
Chris Lattner59907c42007-08-10 20:18:51 +0000464/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000465/// correct use of format strings.
466///
467/// HasVAListArg - A predicate indicating whether the printf-like
468/// function is passed an explicit va_arg argument (e.g., vprintf)
469///
470/// format_idx - The index into Args for the format string.
471///
472/// Improper format strings to functions in the printf family can be
473/// the source of bizarre bugs and very serious security holes. A
474/// good source of information is available in the following paper
475/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000476///
477/// FormatGuard: Automatic Protection From printf Format String
478/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000479///
480/// Functionality implemented:
481///
482/// We can statically check the following properties for string
483/// literal format strings for non v.*printf functions (where the
484/// arguments are passed directly):
485//
486/// (1) Are the number of format conversions equal to the number of
487/// data arguments?
488///
489/// (2) Does each format conversion correctly match the type of the
490/// corresponding data argument? (TODO)
491///
492/// Moreover, for all printf functions we can:
493///
494/// (3) Check for a missing format string (when not caught by type checking).
495///
496/// (4) Check for no-operation flags; e.g. using "#" with format
497/// conversion 'c' (TODO)
498///
499/// (5) Check the use of '%n', a major source of security holes.
500///
501/// (6) Check for malformed format conversions that don't specify anything.
502///
503/// (7) Check for empty format strings. e.g: printf("");
504///
505/// (8) Check that the format string is a wide literal.
506///
Ted Kremenek6d439592008-03-03 16:50:00 +0000507/// (9) Also check the arguments of functions with the __format__ attribute.
508/// (TODO).
509///
Ted Kremenek71895b92007-08-14 17:39:48 +0000510/// All of these checks can be done by parsing the format string.
511///
512/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000513void
Chris Lattner925e60d2007-12-28 05:29:59 +0000514Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000515 unsigned format_idx, unsigned firstDataArg) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000516 Expr *Fn = TheCall->getCallee();
517
Ted Kremenek71895b92007-08-14 17:39:48 +0000518 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000519 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000520 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
521 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000522 return;
523 }
524
Chris Lattner56f34942008-02-13 01:02:39 +0000525 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000526
Chris Lattner59907c42007-08-10 20:18:51 +0000527 // CHECK: format string is not a string literal.
528 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000529 // Dynamically generated format strings are difficult to
530 // automatically vet at compile time. Requiring that format strings
531 // are string literals: (1) permits the checking of format strings by
532 // the compiler and thereby (2) can practically remove the source of
533 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000534
535 // Format string can be either ObjC string (e.g. @"%d") or
536 // C string (e.g. "%d")
537 // ObjC string uses the same format specifiers as C string, so we can use
538 // the same format string checking logic for both ObjC and C strings.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000539 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
540 HasVAListArg, format_idx,
541 firstDataArg);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000542
Ted Kremenekd30ef872009-01-12 23:09:09 +0000543 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000544 // For vprintf* functions (i.e., HasVAListArg==true), we add a
545 // special check to see if the format string is a function parameter
546 // of the function calling the printf function. If the function
547 // has an attribute indicating it is a printf-like function, then we
548 // should suppress warnings concerning non-literals being used in a call
549 // to a vprintf function. For example:
550 //
551 // void
552 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
553 // va_list ap;
554 // va_start(ap, fmt);
555 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
556 // ...
557 //
558 //
559 // FIXME: We don't have full attribute support yet, so just check to see
560 // if the argument is a DeclRefExpr that references a parameter. We'll
561 // add proper support for checking the attribute later.
562 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000563 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
564 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000565 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000566
Chris Lattner925e60d2007-12-28 05:29:59 +0000567 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000568 diag::warn_printf_not_string_constant)
569 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000570 return;
571 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000572}
Ted Kremenek71895b92007-08-14 17:39:48 +0000573
Ted Kremenekd30ef872009-01-12 23:09:09 +0000574void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000575 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx,
576 unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000577
578 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000579 // CHECK: is the format string a wide literal?
580 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000581 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000582 diag::warn_printf_format_string_is_wide_literal)
583 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000584 return;
585 }
586
587 // Str - The format string. NOTE: this is NOT null-terminated!
588 const char * const Str = FExpr->getStrData();
589
590 // CHECK: empty format string?
591 const unsigned StrLen = FExpr->getByteLength();
592
593 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000594 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
595 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000596 return;
597 }
598
599 // We process the format string using a binary state machine. The
600 // current state is stored in CurrentState.
601 enum {
602 state_OrdChr,
603 state_Conversion
604 } CurrentState = state_OrdChr;
605
606 // numConversions - The number of conversions seen so far. This is
607 // incremented as we traverse the format string.
608 unsigned numConversions = 0;
609
610 // numDataArgs - The number of data arguments after the format
611 // string. This can only be determined for non vprintf-like
612 // functions. For those functions, this value is 1 (the sole
613 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000614 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000615
616 // Inspect the format string.
617 unsigned StrIdx = 0;
618
619 // LastConversionIdx - Index within the format string where we last saw
620 // a '%' character that starts a new format conversion.
621 unsigned LastConversionIdx = 0;
622
Chris Lattner925e60d2007-12-28 05:29:59 +0000623 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000624
Ted Kremenek71895b92007-08-14 17:39:48 +0000625 // Is the number of detected conversion conversions greater than
626 // the number of matching data arguments? If so, stop.
627 if (!HasVAListArg && numConversions > numDataArgs) break;
628
629 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000630 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000631 // The string returned by getStrData() is not null-terminated,
632 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000633 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000634 diag::warn_printf_format_string_contains_null_char)
635 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000636 return;
637 }
638
639 // Ordinary characters (not processing a format conversion).
640 if (CurrentState == state_OrdChr) {
641 if (Str[StrIdx] == '%') {
642 CurrentState = state_Conversion;
643 LastConversionIdx = StrIdx;
644 }
645 continue;
646 }
647
648 // Seen '%'. Now processing a format conversion.
649 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000650 // Handle dynamic precision or width specifier.
651 case '*': {
652 ++numConversions;
653
654 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000655 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000656
Ted Kremenek580b6642007-10-12 20:51:52 +0000657 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000658 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
659 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000660 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000661 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
662 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000663
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000664 // Don't do any more checking. We'll just emit spurious errors.
665 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000666 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000667
668 // Perform type checking on width/precision specifier.
669 Expr *E = TheCall->getArg(format_idx+numConversions);
670 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
671 if (BT->getKind() == BuiltinType::Int)
672 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000673
Chris Lattner60800082009-02-18 17:49:48 +0000674 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000675
676 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000677 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000678 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000679 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000680 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000681 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000682
683 break;
684 }
685
686 // Characters which can terminate a format conversion
687 // (e.g. "%d"). Characters that specify length modifiers or
688 // other flags are handled by the default case below.
689 //
690 // FIXME: additional checks will go into the following cases.
691 case 'i':
692 case 'd':
693 case 'o':
694 case 'u':
695 case 'x':
696 case 'X':
697 case 'D':
698 case 'O':
699 case 'U':
700 case 'e':
701 case 'E':
702 case 'f':
703 case 'F':
704 case 'g':
705 case 'G':
706 case 'a':
707 case 'A':
708 case 'c':
709 case 'C':
710 case 'S':
711 case 's':
712 case 'p':
713 ++numConversions;
714 CurrentState = state_OrdChr;
715 break;
716
717 // CHECK: Are we using "%n"? Issue a warning.
718 case 'n': {
719 ++numConversions;
720 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000721 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
722 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000723
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000724 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000725 break;
726 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000727
728 // Handle "%@"
729 case '@':
730 // %@ is allowed in ObjC format strings only.
731 if(ObjCFExpr != NULL)
732 CurrentState = state_OrdChr;
733 else {
734 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000735 SourceLocation Loc =
736 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000737
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000738 Diag(Loc, diag::warn_printf_invalid_conversion)
739 << std::string(Str+LastConversionIdx,
740 Str+std::min(LastConversionIdx+2, StrLen))
741 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000742 }
743 ++numConversions;
744 break;
745
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000746 // Handle "%%"
747 case '%':
748 // Sanity check: Was the first "%" character the previous one?
749 // If not, we will assume that we have a malformed format
750 // conversion, and that the current "%" character is the start
751 // of a new conversion.
752 if (StrIdx - LastConversionIdx == 1)
753 CurrentState = state_OrdChr;
754 else {
755 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000756 SourceLocation Loc =
757 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000758
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000759 Diag(Loc, diag::warn_printf_invalid_conversion)
760 << std::string(Str+LastConversionIdx, Str+StrIdx)
761 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000762
763 // This conversion is broken. Advance to the next format
764 // conversion.
765 LastConversionIdx = StrIdx;
766 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000767 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000768 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000769
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000770 default:
771 // This case catches all other characters: flags, widths, etc.
772 // We should eventually process those as well.
773 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000774 }
775 }
776
777 if (CurrentState == state_Conversion) {
778 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000779 SourceLocation Loc =
780 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000781
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000782 Diag(Loc, diag::warn_printf_invalid_conversion)
783 << std::string(Str+LastConversionIdx,
784 Str+std::min(LastConversionIdx+2, StrLen))
785 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000786 return;
787 }
788
789 if (!HasVAListArg) {
790 // CHECK: Does the number of format conversions exceed the number
791 // of data arguments?
792 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000793 SourceLocation Loc =
794 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000795
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000796 Diag(Loc, diag::warn_printf_insufficient_data_args)
797 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000798 }
799 // CHECK: Does the number of data arguments exceed the number of
800 // format conversions in the format string?
801 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000802 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000803 diag::warn_printf_too_many_data_args)
804 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000805 }
806}
Ted Kremenek06de2762007-08-17 16:46:58 +0000807
808//===--- CHECK: Return Address of Stack Variable --------------------------===//
809
810static DeclRefExpr* EvalVal(Expr *E);
811static DeclRefExpr* EvalAddr(Expr* E);
812
813/// CheckReturnStackAddr - Check if a return statement returns the address
814/// of a stack variable.
815void
816Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
817 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000818
Ted Kremenek06de2762007-08-17 16:46:58 +0000819 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000820 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000821 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000822 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000823 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000824
825 // Skip over implicit cast expressions when checking for block expressions.
826 if (ImplicitCastExpr *IcExpr =
827 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
828 RetValExp = IcExpr->getSubExpr();
829
Steve Naroff61f40a22008-09-10 19:17:48 +0000830 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000831 Diag(C->getLocStart(), diag::err_ret_local_block)
832 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000833 }
834 // Perform checking for stack values returned by reference.
835 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000836 // Check for a reference to the stack
837 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000838 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000839 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000840 }
841}
842
843/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
844/// check if the expression in a return statement evaluates to an address
845/// to a location on the stack. The recursion is used to traverse the
846/// AST of the return expression, with recursion backtracking when we
847/// encounter a subexpression that (1) clearly does not lead to the address
848/// of a stack variable or (2) is something we cannot determine leads to
849/// the address of a stack variable based on such local checking.
850///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000851/// EvalAddr processes expressions that are pointers that are used as
852/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000853/// At the base case of the recursion is a check for a DeclRefExpr* in
854/// the refers to a stack variable.
855///
856/// This implementation handles:
857///
858/// * pointer-to-pointer casts
859/// * implicit conversions from array references to pointers
860/// * taking the address of fields
861/// * arbitrary interplay between "&" and "*" operators
862/// * pointer arithmetic from an address of a stack variable
863/// * taking the address of an array element where the array is on the stack
864static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000865 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000866 assert((E->getType()->isPointerType() ||
867 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000868 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000869 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000870
871 // Our "symbolic interpreter" is just a dispatch off the currently
872 // viewed AST node. We then recursively traverse the AST by calling
873 // EvalAddr and EvalVal appropriately.
874 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000875 case Stmt::ParenExprClass:
876 // Ignore parentheses.
877 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000878
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000879 case Stmt::UnaryOperatorClass: {
880 // The only unary operator that make sense to handle here
881 // is AddrOf. All others don't make sense as pointers.
882 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000883
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000884 if (U->getOpcode() == UnaryOperator::AddrOf)
885 return EvalVal(U->getSubExpr());
886 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000887 return NULL;
888 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000889
890 case Stmt::BinaryOperatorClass: {
891 // Handle pointer arithmetic. All other binary operators are not valid
892 // in this context.
893 BinaryOperator *B = cast<BinaryOperator>(E);
894 BinaryOperator::Opcode op = B->getOpcode();
895
896 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
897 return NULL;
898
899 Expr *Base = B->getLHS();
900
901 // Determine which argument is the real pointer base. It could be
902 // the RHS argument instead of the LHS.
903 if (!Base->getType()->isPointerType()) Base = B->getRHS();
904
905 assert (Base->getType()->isPointerType());
906 return EvalAddr(Base);
907 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000908
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000909 // For conditional operators we need to see if either the LHS or RHS are
910 // valid DeclRefExpr*s. If one of them is valid, we return it.
911 case Stmt::ConditionalOperatorClass: {
912 ConditionalOperator *C = cast<ConditionalOperator>(E);
913
914 // Handle the GNU extension for missing LHS.
915 if (Expr *lhsExpr = C->getLHS())
916 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
917 return LHS;
918
919 return EvalAddr(C->getRHS());
920 }
921
Ted Kremenek54b52742008-08-07 00:49:01 +0000922 // For casts, we need to handle conversions from arrays to
923 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000924 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000925 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000926 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000927 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000928 QualType T = SubExpr->getType();
929
Steve Naroffdd972f22008-09-05 22:11:13 +0000930 if (SubExpr->getType()->isPointerType() ||
931 SubExpr->getType()->isBlockPointerType() ||
932 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000933 return EvalAddr(SubExpr);
934 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000935 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000936 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000937 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000938 }
939
940 // C++ casts. For dynamic casts, static casts, and const casts, we
941 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000942 // through the cast. In the case the dynamic cast doesn't fail (and
943 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000944 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000945 // FIXME: The comment about is wrong; we're not always converting
946 // from pointer to pointer. I'm guessing that this code should also
947 // handle references to objects.
948 case Stmt::CXXStaticCastExprClass:
949 case Stmt::CXXDynamicCastExprClass:
950 case Stmt::CXXConstCastExprClass:
951 case Stmt::CXXReinterpretCastExprClass: {
952 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000953 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000954 return EvalAddr(S);
955 else
956 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000957 }
958
959 // Everything else: we simply don't reason about them.
960 default:
961 return NULL;
962 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000963}
964
965
966/// EvalVal - This function is complements EvalAddr in the mutual recursion.
967/// See the comments for EvalAddr for more details.
968static DeclRefExpr* EvalVal(Expr *E) {
969
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000970 // We should only be called for evaluating non-pointer expressions, or
971 // expressions with a pointer type that are not used as references but instead
972 // are l-values (e.g., DeclRefExpr with a pointer type).
973
Ted Kremenek06de2762007-08-17 16:46:58 +0000974 // Our "symbolic interpreter" is just a dispatch off the currently
975 // viewed AST node. We then recursively traverse the AST by calling
976 // EvalAddr and EvalVal appropriately.
977 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000978 case Stmt::DeclRefExprClass:
979 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000980 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
981 // at code that refers to a variable's name. We check if it has local
982 // storage within the function, and if so, return the expression.
983 DeclRefExpr *DR = cast<DeclRefExpr>(E);
984
985 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000986 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000987
988 return NULL;
989 }
990
991 case Stmt::ParenExprClass:
992 // Ignore parentheses.
993 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
994
995 case Stmt::UnaryOperatorClass: {
996 // The only unary operator that make sense to handle here
997 // is Deref. All others don't resolve to a "name." This includes
998 // handling all sorts of rvalues passed to a unary operator.
999 UnaryOperator *U = cast<UnaryOperator>(E);
1000
1001 if (U->getOpcode() == UnaryOperator::Deref)
1002 return EvalAddr(U->getSubExpr());
1003
1004 return NULL;
1005 }
1006
1007 case Stmt::ArraySubscriptExprClass: {
1008 // Array subscripts are potential references to data on the stack. We
1009 // retrieve the DeclRefExpr* for the array variable if it indeed
1010 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001011 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001012 }
1013
1014 case Stmt::ConditionalOperatorClass: {
1015 // For conditional operators we need to see if either the LHS or RHS are
1016 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1017 ConditionalOperator *C = cast<ConditionalOperator>(E);
1018
Anders Carlsson39073232007-11-30 19:04:31 +00001019 // Handle the GNU extension for missing LHS.
1020 if (Expr *lhsExpr = C->getLHS())
1021 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1022 return LHS;
1023
1024 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001025 }
1026
1027 // Accesses to members are potential references to data on the stack.
1028 case Stmt::MemberExprClass: {
1029 MemberExpr *M = cast<MemberExpr>(E);
1030
1031 // Check for indirect access. We only want direct field accesses.
1032 if (!M->isArrow())
1033 return EvalVal(M->getBase());
1034 else
1035 return NULL;
1036 }
1037
1038 // Everything else: we simply don't reason about them.
1039 default:
1040 return NULL;
1041 }
1042}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001043
1044//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1045
1046/// Check for comparisons of floating point operands using != and ==.
1047/// Issue a warning if these are no self-comparisons, as they are not likely
1048/// to do what the programmer intended.
1049void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1050 bool EmitWarning = true;
1051
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001052 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001053 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001054
1055 // Special case: check for x == x (which is OK).
1056 // Do not emit warnings for such cases.
1057 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1058 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1059 if (DRL->getDecl() == DRR->getDecl())
1060 EmitWarning = false;
1061
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001062
1063 // Special case: check for comparisons against literals that can be exactly
1064 // represented by APFloat. In such cases, do not emit a warning. This
1065 // is a heuristic: often comparison against such literals are used to
1066 // detect if a value in a variable has not changed. This clearly can
1067 // lead to false negatives.
1068 if (EmitWarning) {
1069 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1070 if (FLL->isExact())
1071 EmitWarning = false;
1072 }
1073 else
1074 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1075 if (FLR->isExact())
1076 EmitWarning = false;
1077 }
1078 }
1079
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001080 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001081 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001082 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001083 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001084 EmitWarning = false;
1085
Sebastian Redl0eb23302009-01-19 00:08:26 +00001086 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001087 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001088 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001089 EmitWarning = false;
1090
1091 // Emit the diagnostic.
1092 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001093 Diag(loc, diag::warn_floatingpoint_eq)
1094 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001095}