blob: 63c1635ef2b0a1e1715f6f2364187d44e116cb50 [file] [log] [blame]
Chris Lattner2e64c072007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner2e64c072007-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 Kremenek1c1700f2007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner2e64c072007-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"
Eli Friedman798e4d52008-05-16 17:51:27 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000027#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/StringExtras.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000029#include "SemaUtil.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000030using namespace clang;
31
32/// CheckFunctionCall - Check a direct function call for various correctness
33/// and safety properties not strictly enforced by the C type system.
Eli Friedmand0e9d092008-05-14 19:38:39 +000034Action::ExprResult
Eli Friedman798e4d52008-05-16 17:51:27 +000035Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
36 llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
Chris Lattner2e64c072007-08-10 20:18:51 +000037 // Get the IdentifierInfo* for the called function.
38 IdentifierInfo *FnInfo = FDecl->getIdentifier();
39
Chris Lattnerf22a8502007-12-19 23:59:04 +000040 switch (FnInfo->getBuiltinID()) {
41 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +000042 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +000043 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedman798e4d52008-05-16 17:51:27 +000044 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand0e9d092008-05-14 19:38:39 +000045 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000046 return TheCall.take();
Chris Lattnerf22a8502007-12-19 23:59:04 +000047 case Builtin::BI__builtin_va_start:
Eli Friedman798e4d52008-05-16 17:51:27 +000048 if (SemaBuiltinVAStart(TheCall.get())) {
Eli Friedmand0e9d092008-05-14 19:38:39 +000049 return true;
50 }
Eli Friedman798e4d52008-05-16 17:51:27 +000051 return TheCall.take();
Chris Lattner7c8d1af2007-12-20 00:26:33 +000052 case Builtin::BI__builtin_isgreater:
53 case Builtin::BI__builtin_isgreaterequal:
54 case Builtin::BI__builtin_isless:
55 case Builtin::BI__builtin_islessequal:
56 case Builtin::BI__builtin_islessgreater:
57 case Builtin::BI__builtin_isunordered:
Eli Friedman798e4d52008-05-16 17:51:27 +000058 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand0e9d092008-05-14 19:38:39 +000059 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000060 return TheCall.take();
Eli Friedman8c50c622008-05-20 08:23:37 +000061 case Builtin::BI__builtin_return_address:
62 case Builtin::BI__builtin_frame_address:
63 if (SemaBuiltinStackAddress(TheCall.get()))
64 return true;
65 return TheCall.take();
Eli Friedmand0e9d092008-05-14 19:38:39 +000066 case Builtin::BI__builtin_shufflevector:
Eli Friedman798e4d52008-05-16 17:51:27 +000067 return SemaBuiltinShuffleVector(TheCall.get());
Anders Carlssone7e7aa22007-08-17 05:31:46 +000068 }
69
Chris Lattner2e64c072007-08-10 20:18:51 +000070 // Search the KnownFunctionIDs for the identifier.
71 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek081ed872007-08-14 17:39:48 +000072 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedman798e4d52008-05-16 17:51:27 +000073 if (i == e) return TheCall.take();
Chris Lattner2e64c072007-08-10 20:18:51 +000074
75 // Printf checking.
76 if (i <= id_vprintf) {
Ted Kremenek081ed872007-08-14 17:39:48 +000077 // Retrieve the index of the format string parameter and determine
78 // if the function is passed a va_arg argument.
Chris Lattner2e64c072007-08-10 20:18:51 +000079 unsigned format_idx = 0;
Ted Kremenek081ed872007-08-14 17:39:48 +000080 bool HasVAListArg = false;
81
Chris Lattner2e64c072007-08-10 20:18:51 +000082 switch (i) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000083 default: assert(false && "No format string argument index.");
84 case id_printf: format_idx = 0; break;
85 case id_fprintf: format_idx = 1; break;
86 case id_sprintf: format_idx = 1; break;
87 case id_snprintf: format_idx = 2; break;
88 case id_asprintf: format_idx = 1; break;
89 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
90 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
91 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
92 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
93 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek081ed872007-08-14 17:39:48 +000094 }
95
Eli Friedman798e4d52008-05-16 17:51:27 +000096 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner2e64c072007-08-10 20:18:51 +000097 }
Anders Carlssone7e7aa22007-08-17 05:31:46 +000098
Eli Friedman798e4d52008-05-16 17:51:27 +000099 return TheCall.take();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000100}
101
102/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
103/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +0000104bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000105 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000106
107 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
108
109 if (!Literal || Literal->isWide()) {
110 Diag(Arg->getLocStart(),
111 diag::err_cfstring_literal_not_string_constant,
112 Arg->getSourceRange());
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000113 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000114 }
115
116 const char *Data = Literal->getStrData();
117 unsigned Length = Literal->getByteLength();
118
119 for (unsigned i = 0; i < Length; ++i) {
120 if (!isascii(Data[i])) {
121 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
122 diag::warn_cfstring_literal_contains_non_ascii_character,
123 Arg->getSourceRange());
124 break;
125 }
126
127 if (!Data[i]) {
128 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
129 diag::warn_cfstring_literal_contains_nul_character,
130 Arg->getSourceRange());
131 break;
132 }
133 }
134
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000135 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000136}
137
Chris Lattner3b933692007-12-20 00:05:45 +0000138/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
139/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000140bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
141 Expr *Fn = TheCall->getCallee();
142 if (TheCall->getNumArgs() > 2) {
143 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000144 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000145 SourceRange(TheCall->getArg(2)->getLocStart(),
146 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattnerf22a8502007-12-19 23:59:04 +0000147 return true;
148 }
149
Chris Lattner3b933692007-12-20 00:05:45 +0000150 // Determine whether the current function is variadic or not.
151 bool isVariadic;
Chris Lattnerf22a8502007-12-19 23:59:04 +0000152 if (CurFunctionDecl)
Chris Lattner3b933692007-12-20 00:05:45 +0000153 isVariadic =
154 cast<FunctionTypeProto>(CurFunctionDecl->getType())->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000155 else
Chris Lattner3b933692007-12-20 00:05:45 +0000156 isVariadic = CurMethodDecl->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000157
Chris Lattner3b933692007-12-20 00:05:45 +0000158 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000159 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
160 return true;
161 }
162
163 // Verify that the second argument to the builtin is the last argument of the
164 // current function or method.
165 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000166 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000167
168 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
169 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000170 // FIXME: This isn't correct for methods (results in bogus warning).
171 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000172 const ParmVarDecl *LastArg;
Chris Lattnerf22a8502007-12-19 23:59:04 +0000173 if (CurFunctionDecl)
174 LastArg = *(CurFunctionDecl->param_end()-1);
175 else
176 LastArg = *(CurMethodDecl->param_end()-1);
177 SecondArgIsLastNamedArgument = PV == LastArg;
178 }
179 }
180
181 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000182 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000183 diag::warn_second_parameter_of_va_start_not_last_named_argument);
184 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000185}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000186
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000187/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
188/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000189bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
190 if (TheCall->getNumArgs() < 2)
191 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
192 if (TheCall->getNumArgs() > 2)
193 return Diag(TheCall->getArg(2)->getLocStart(),
194 diag::err_typecheck_call_too_many_args,
195 SourceRange(TheCall->getArg(2)->getLocStart(),
196 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000197
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000198 Expr *OrigArg0 = TheCall->getArg(0);
199 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000200
201 // Do standard promotions between the two arguments, returning their common
202 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000203 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000204
205 // If the common type isn't a real floating type, then the arguments were
206 // invalid for this operation.
207 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000208 return Diag(OrigArg0->getLocStart(),
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000209 diag::err_typecheck_call_invalid_ordered_compare,
210 OrigArg0->getType().getAsString(),
211 OrigArg1->getType().getAsString(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000212 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000213
214 return false;
215}
216
Eli Friedman8c50c622008-05-20 08:23:37 +0000217bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
218 // The signature for these builtins is exact; the only thing we need
219 // to check is that the argument is a constant.
220 SourceLocation Loc;
221 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) {
222 return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
223 }
224 return false;
225}
226
Eli Friedmand0e9d092008-05-14 19:38:39 +0000227/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
228// This is declared to take (...), so we have to check everything.
229Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
230 if (TheCall->getNumArgs() < 3)
231 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
232 TheCall->getSourceRange());
233
234 QualType FAType = TheCall->getArg(0)->getType();
235 QualType SAType = TheCall->getArg(1)->getType();
236
237 if (!FAType->isVectorType() || !SAType->isVectorType()) {
238 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector,
239 SourceRange(TheCall->getArg(0)->getLocStart(),
240 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000241 return true;
242 }
243
Eli Friedmand38439f2008-05-16 17:54:49 +0000244 if (FAType.getCanonicalType().getUnqualifiedType() !=
245 SAType.getCanonicalType().getUnqualifiedType()) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000246 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector,
247 SourceRange(TheCall->getArg(0)->getLocStart(),
248 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000249 return true;
250 }
251
252 unsigned numElements = FAType->getAsVectorType()->getNumElements();
253 if (TheCall->getNumArgs() != numElements+2) {
254 if (TheCall->getNumArgs() < numElements+2)
255 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
256 TheCall->getSourceRange());
257 else
258 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
259 TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000260 return true;
261 }
262
263 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
264 llvm::APSInt Result(32);
265 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) {
266 Diag(TheCall->getLocStart(),
267 diag::err_shufflevector_nonconstant_argument,
268 TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000269 return true;
270 }
271 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) {
272 Diag(TheCall->getLocStart(),
273 diag::err_shufflevector_argument_too_large,
274 TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000275 return true;
276 }
277 }
278
279 llvm::SmallVector<Expr*, 32> exprs;
280
281 for (unsigned i = 0; i < TheCall->getNumArgs(); i++) {
282 exprs.push_back(TheCall->getArg(i));
283 TheCall->setArg(i, 0);
284 }
285
286 ShuffleVectorExpr* E = new ShuffleVectorExpr(
287 exprs.begin(), numElements+2, FAType,
288 TheCall->getCallee()->getLocStart(),
289 TheCall->getRParenLoc());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000290
291 return E;
292}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000293
Chris Lattner2e64c072007-08-10 20:18:51 +0000294/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000295/// correct use of format strings.
296///
297/// HasVAListArg - A predicate indicating whether the printf-like
298/// function is passed an explicit va_arg argument (e.g., vprintf)
299///
300/// format_idx - The index into Args for the format string.
301///
302/// Improper format strings to functions in the printf family can be
303/// the source of bizarre bugs and very serious security holes. A
304/// good source of information is available in the following paper
305/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000306///
307/// FormatGuard: Automatic Protection From printf Format String
308/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000309///
310/// Functionality implemented:
311///
312/// We can statically check the following properties for string
313/// literal format strings for non v.*printf functions (where the
314/// arguments are passed directly):
315//
316/// (1) Are the number of format conversions equal to the number of
317/// data arguments?
318///
319/// (2) Does each format conversion correctly match the type of the
320/// corresponding data argument? (TODO)
321///
322/// Moreover, for all printf functions we can:
323///
324/// (3) Check for a missing format string (when not caught by type checking).
325///
326/// (4) Check for no-operation flags; e.g. using "#" with format
327/// conversion 'c' (TODO)
328///
329/// (5) Check the use of '%n', a major source of security holes.
330///
331/// (6) Check for malformed format conversions that don't specify anything.
332///
333/// (7) Check for empty format strings. e.g: printf("");
334///
335/// (8) Check that the format string is a wide literal.
336///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000337/// (9) Also check the arguments of functions with the __format__ attribute.
338/// (TODO).
339///
Ted Kremenek081ed872007-08-14 17:39:48 +0000340/// All of these checks can be done by parsing the format string.
341///
342/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000343void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000344Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
345 unsigned format_idx) {
346 Expr *Fn = TheCall->getCallee();
347
Ted Kremenek081ed872007-08-14 17:39:48 +0000348 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000349 if (format_idx >= TheCall->getNumArgs()) {
350 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek081ed872007-08-14 17:39:48 +0000351 Fn->getSourceRange());
352 return;
353 }
354
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000355 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000356
Chris Lattner2e64c072007-08-10 20:18:51 +0000357 // CHECK: format string is not a string literal.
358 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000359 // Dynamically generated format strings are difficult to
360 // automatically vet at compile time. Requiring that format strings
361 // are string literals: (1) permits the checking of format strings by
362 // the compiler and thereby (2) can practically remove the source of
363 // many format string exploits.
Chris Lattnere65acc12007-08-25 05:36:18 +0000364 StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
Ted Kremenek081ed872007-08-14 17:39:48 +0000365 if (FExpr == NULL) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000366 // For vprintf* functions (i.e., HasVAListArg==true), we add a
367 // special check to see if the format string is a function parameter
368 // of the function calling the printf function. If the function
369 // has an attribute indicating it is a printf-like function, then we
370 // should suppress warnings concerning non-literals being used in a call
371 // to a vprintf function. For example:
372 //
373 // void
374 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
375 // va_list ap;
376 // va_start(ap, fmt);
377 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
378 // ...
379 //
380 //
381 // FIXME: We don't have full attribute support yet, so just check to see
382 // if the argument is a DeclRefExpr that references a parameter. We'll
383 // add proper support for checking the attribute later.
384 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000385 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
386 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000387 return;
388
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000389 Diag(TheCall->getArg(format_idx)->getLocStart(),
390 diag::warn_printf_not_string_constant, Fn->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000391 return;
392 }
393
394 // CHECK: is the format string a wide literal?
395 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000396 Diag(FExpr->getLocStart(),
397 diag::warn_printf_format_string_is_wide_literal, Fn->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000398 return;
399 }
400
401 // Str - The format string. NOTE: this is NOT null-terminated!
402 const char * const Str = FExpr->getStrData();
403
404 // CHECK: empty format string?
405 const unsigned StrLen = FExpr->getByteLength();
406
407 if (StrLen == 0) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000408 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
409 Fn->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000410 return;
411 }
412
413 // We process the format string using a binary state machine. The
414 // current state is stored in CurrentState.
415 enum {
416 state_OrdChr,
417 state_Conversion
418 } CurrentState = state_OrdChr;
419
420 // numConversions - The number of conversions seen so far. This is
421 // incremented as we traverse the format string.
422 unsigned numConversions = 0;
423
424 // numDataArgs - The number of data arguments after the format
425 // string. This can only be determined for non vprintf-like
426 // functions. For those functions, this value is 1 (the sole
427 // va_arg argument).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000428 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000429
430 // Inspect the format string.
431 unsigned StrIdx = 0;
432
433 // LastConversionIdx - Index within the format string where we last saw
434 // a '%' character that starts a new format conversion.
435 unsigned LastConversionIdx = 0;
436
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000437 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000438
Ted Kremenek081ed872007-08-14 17:39:48 +0000439 // Is the number of detected conversion conversions greater than
440 // the number of matching data arguments? If so, stop.
441 if (!HasVAListArg && numConversions > numDataArgs) break;
442
443 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000444 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000445 // The string returned by getStrData() is not null-terminated,
446 // so the presence of a null character is likely an error.
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000447 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
448 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek081ed872007-08-14 17:39:48 +0000449 Fn->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000450 return;
451 }
452
453 // Ordinary characters (not processing a format conversion).
454 if (CurrentState == state_OrdChr) {
455 if (Str[StrIdx] == '%') {
456 CurrentState = state_Conversion;
457 LastConversionIdx = StrIdx;
458 }
459 continue;
460 }
461
462 // Seen '%'. Now processing a format conversion.
463 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000464 // Handle dynamic precision or width specifier.
465 case '*': {
466 ++numConversions;
467
468 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000469 SourceLocation Loc = FExpr->getLocStart();
470 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek035d8792007-10-12 20:51:52 +0000471
Ted Kremenek035d8792007-10-12 20:51:52 +0000472 if (Str[StrIdx-1] == '.')
Chris Lattner68d88f02007-12-28 05:31:15 +0000473 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
474 Fn->getSourceRange());
Ted Kremenek035d8792007-10-12 20:51:52 +0000475 else
Chris Lattner68d88f02007-12-28 05:31:15 +0000476 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
477 Fn->getSourceRange());
Ted Kremenek035d8792007-10-12 20:51:52 +0000478
Chris Lattner68d88f02007-12-28 05:31:15 +0000479 // Don't do any more checking. We'll just emit spurious errors.
480 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000481 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000482
483 // Perform type checking on width/precision specifier.
484 Expr *E = TheCall->getArg(format_idx+numConversions);
485 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
486 if (BT->getKind() == BuiltinType::Int)
487 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000488
Chris Lattner68d88f02007-12-28 05:31:15 +0000489 SourceLocation Loc =
490 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
491
492 if (Str[StrIdx-1] == '.')
493 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
494 E->getType().getAsString(), E->getSourceRange());
495 else
496 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
497 E->getType().getAsString(), E->getSourceRange());
498
499 break;
500 }
501
502 // Characters which can terminate a format conversion
503 // (e.g. "%d"). Characters that specify length modifiers or
504 // other flags are handled by the default case below.
505 //
506 // FIXME: additional checks will go into the following cases.
507 case 'i':
508 case 'd':
509 case 'o':
510 case 'u':
511 case 'x':
512 case 'X':
513 case 'D':
514 case 'O':
515 case 'U':
516 case 'e':
517 case 'E':
518 case 'f':
519 case 'F':
520 case 'g':
521 case 'G':
522 case 'a':
523 case 'A':
524 case 'c':
525 case 'C':
526 case 'S':
527 case 's':
528 case 'p':
529 ++numConversions;
530 CurrentState = state_OrdChr;
531 break;
532
533 // CHECK: Are we using "%n"? Issue a warning.
534 case 'n': {
535 ++numConversions;
536 CurrentState = state_OrdChr;
537 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
538 LastConversionIdx+1);
539
540 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
541 break;
542 }
543
544 // Handle "%%"
545 case '%':
546 // Sanity check: Was the first "%" character the previous one?
547 // If not, we will assume that we have a malformed format
548 // conversion, and that the current "%" character is the start
549 // of a new conversion.
550 if (StrIdx - LastConversionIdx == 1)
551 CurrentState = state_OrdChr;
552 else {
553 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000554 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
555 LastConversionIdx+1);
Chris Lattner68d88f02007-12-28 05:31:15 +0000556
557 Diag(Loc, diag::warn_printf_invalid_conversion,
558 std::string(Str+LastConversionIdx, Str+StrIdx),
559 Fn->getSourceRange());
560
561 // This conversion is broken. Advance to the next format
562 // conversion.
563 LastConversionIdx = StrIdx;
564 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000565 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000566 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000567
Chris Lattner68d88f02007-12-28 05:31:15 +0000568 default:
569 // This case catches all other characters: flags, widths, etc.
570 // We should eventually process those as well.
571 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000572 }
573 }
574
575 if (CurrentState == state_Conversion) {
576 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000577 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
578 LastConversionIdx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000579
580 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattner6f65d202007-08-26 17:38:22 +0000581 std::string(Str+LastConversionIdx,
582 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek081ed872007-08-14 17:39:48 +0000583 Fn->getSourceRange());
584 return;
585 }
586
587 if (!HasVAListArg) {
588 // CHECK: Does the number of format conversions exceed the number
589 // of data arguments?
590 if (numConversions > numDataArgs) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000591 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
592 LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000593
594 Diag(Loc, diag::warn_printf_insufficient_data_args,
595 Fn->getSourceRange());
596 }
597 // CHECK: Does the number of data arguments exceed the number of
598 // format conversions in the format string?
599 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000600 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek081ed872007-08-14 17:39:48 +0000601 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
602 }
603}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000604
605//===--- CHECK: Return Address of Stack Variable --------------------------===//
606
607static DeclRefExpr* EvalVal(Expr *E);
608static DeclRefExpr* EvalAddr(Expr* E);
609
610/// CheckReturnStackAddr - Check if a return statement returns the address
611/// of a stack variable.
612void
613Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
614 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000615
Ted Kremenek45925ab2007-08-17 16:46:58 +0000616 // Perform checking for returned stack addresses.
617 if (lhsType->isPointerType()) {
618 if (DeclRefExpr *DR = EvalAddr(RetValExp))
619 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
620 DR->getDecl()->getIdentifier()->getName(),
621 RetValExp->getSourceRange());
622 }
623 // Perform checking for stack values returned by reference.
624 else if (lhsType->isReferenceType()) {
Ted Kremenek1456f202007-08-27 16:39:17 +0000625 // Check for an implicit cast to a reference.
626 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
627 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
628 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
629 DR->getDecl()->getIdentifier()->getName(),
630 RetValExp->getSourceRange());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000631 }
632}
633
634/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
635/// check if the expression in a return statement evaluates to an address
636/// to a location on the stack. The recursion is used to traverse the
637/// AST of the return expression, with recursion backtracking when we
638/// encounter a subexpression that (1) clearly does not lead to the address
639/// of a stack variable or (2) is something we cannot determine leads to
640/// the address of a stack variable based on such local checking.
641///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000642/// EvalAddr processes expressions that are pointers that are used as
643/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000644/// At the base case of the recursion is a check for a DeclRefExpr* in
645/// the refers to a stack variable.
646///
647/// This implementation handles:
648///
649/// * pointer-to-pointer casts
650/// * implicit conversions from array references to pointers
651/// * taking the address of fields
652/// * arbitrary interplay between "&" and "*" operators
653/// * pointer arithmetic from an address of a stack variable
654/// * taking the address of an array element where the array is on the stack
655static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000656 // We should only be called for evaluating pointer expressions.
Chris Lattner68d88f02007-12-28 05:31:15 +0000657 assert((E->getType()->isPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000658 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000659 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000660
661 // Our "symbolic interpreter" is just a dispatch off the currently
662 // viewed AST node. We then recursively traverse the AST by calling
663 // EvalAddr and EvalVal appropriately.
664 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000665 case Stmt::ParenExprClass:
666 // Ignore parentheses.
667 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000668
Chris Lattner68d88f02007-12-28 05:31:15 +0000669 case Stmt::UnaryOperatorClass: {
670 // The only unary operator that make sense to handle here
671 // is AddrOf. All others don't make sense as pointers.
672 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000673
Chris Lattner68d88f02007-12-28 05:31:15 +0000674 if (U->getOpcode() == UnaryOperator::AddrOf)
675 return EvalVal(U->getSubExpr());
676 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000677 return NULL;
678 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000679
680 case Stmt::BinaryOperatorClass: {
681 // Handle pointer arithmetic. All other binary operators are not valid
682 // in this context.
683 BinaryOperator *B = cast<BinaryOperator>(E);
684 BinaryOperator::Opcode op = B->getOpcode();
685
686 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
687 return NULL;
688
689 Expr *Base = B->getLHS();
690
691 // Determine which argument is the real pointer base. It could be
692 // the RHS argument instead of the LHS.
693 if (!Base->getType()->isPointerType()) Base = B->getRHS();
694
695 assert (Base->getType()->isPointerType());
696 return EvalAddr(Base);
697 }
698
699 // For conditional operators we need to see if either the LHS or RHS are
700 // valid DeclRefExpr*s. If one of them is valid, we return it.
701 case Stmt::ConditionalOperatorClass: {
702 ConditionalOperator *C = cast<ConditionalOperator>(E);
703
704 // Handle the GNU extension for missing LHS.
705 if (Expr *lhsExpr = C->getLHS())
706 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
707 return LHS;
708
709 return EvalAddr(C->getRHS());
710 }
711
712 // For implicit casts, we need to handle conversions from arrays to
713 // pointer values, and implicit pointer-to-pointer conversions.
714 case Stmt::ImplicitCastExprClass: {
715 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
716 Expr* SubExpr = IE->getSubExpr();
717
718 if (SubExpr->getType()->isPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000719 SubExpr->getType()->isObjCQualifiedIdType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000720 return EvalAddr(SubExpr);
721 else
722 return EvalVal(SubExpr);
723 }
724
725 // For casts, we handle pointer-to-pointer conversions (which
726 // is essentially a no-op from our mini-interpreter's standpoint).
727 // For other casts we abort.
728 case Stmt::CastExprClass: {
729 CastExpr *C = cast<CastExpr>(E);
730 Expr *SubExpr = C->getSubExpr();
731
732 if (SubExpr->getType()->isPointerType())
733 return EvalAddr(SubExpr);
734 else
735 return NULL;
736 }
737
738 // C++ casts. For dynamic casts, static casts, and const casts, we
739 // are always converting from a pointer-to-pointer, so we just blow
740 // through the cast. In the case the dynamic cast doesn't fail
741 // (and return NULL), we take the conservative route and report cases
742 // where we return the address of a stack variable. For Reinterpre
743 case Stmt::CXXCastExprClass: {
744 CXXCastExpr *C = cast<CXXCastExpr>(E);
745
746 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
747 Expr *S = C->getSubExpr();
748 if (S->getType()->isPointerType())
749 return EvalAddr(S);
750 else
751 return NULL;
752 }
753 else
754 return EvalAddr(C->getSubExpr());
755 }
756
757 // Everything else: we simply don't reason about them.
758 default:
759 return NULL;
760 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000761}
762
763
764/// EvalVal - This function is complements EvalAddr in the mutual recursion.
765/// See the comments for EvalAddr for more details.
766static DeclRefExpr* EvalVal(Expr *E) {
767
Ted Kremenekda1300a2007-08-28 17:02:55 +0000768 // We should only be called for evaluating non-pointer expressions, or
769 // expressions with a pointer type that are not used as references but instead
770 // are l-values (e.g., DeclRefExpr with a pointer type).
771
Ted Kremenek45925ab2007-08-17 16:46:58 +0000772 // Our "symbolic interpreter" is just a dispatch off the currently
773 // viewed AST node. We then recursively traverse the AST by calling
774 // EvalAddr and EvalVal appropriately.
775 switch (E->getStmtClass()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000776 case Stmt::DeclRefExprClass: {
777 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
778 // at code that refers to a variable's name. We check if it has local
779 // storage within the function, and if so, return the expression.
780 DeclRefExpr *DR = cast<DeclRefExpr>(E);
781
782 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
783 if(V->hasLocalStorage()) return DR;
784
785 return NULL;
786 }
787
788 case Stmt::ParenExprClass:
789 // Ignore parentheses.
790 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
791
792 case Stmt::UnaryOperatorClass: {
793 // The only unary operator that make sense to handle here
794 // is Deref. All others don't resolve to a "name." This includes
795 // handling all sorts of rvalues passed to a unary operator.
796 UnaryOperator *U = cast<UnaryOperator>(E);
797
798 if (U->getOpcode() == UnaryOperator::Deref)
799 return EvalAddr(U->getSubExpr());
800
801 return NULL;
802 }
803
804 case Stmt::ArraySubscriptExprClass: {
805 // Array subscripts are potential references to data on the stack. We
806 // retrieve the DeclRefExpr* for the array variable if it indeed
807 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000808 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000809 }
810
811 case Stmt::ConditionalOperatorClass: {
812 // For conditional operators we need to see if either the LHS or RHS are
813 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
814 ConditionalOperator *C = cast<ConditionalOperator>(E);
815
Anders Carlsson37365fc2007-11-30 19:04:31 +0000816 // Handle the GNU extension for missing LHS.
817 if (Expr *lhsExpr = C->getLHS())
818 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
819 return LHS;
820
821 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000822 }
823
824 // Accesses to members are potential references to data on the stack.
825 case Stmt::MemberExprClass: {
826 MemberExpr *M = cast<MemberExpr>(E);
827
828 // Check for indirect access. We only want direct field accesses.
829 if (!M->isArrow())
830 return EvalVal(M->getBase());
831 else
832 return NULL;
833 }
834
835 // Everything else: we simply don't reason about them.
836 default:
837 return NULL;
838 }
839}
Ted Kremenek30c66752007-11-25 00:58:00 +0000840
841//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
842
843/// Check for comparisons of floating point operands using != and ==.
844/// Issue a warning if these are no self-comparisons, as they are not likely
845/// to do what the programmer intended.
846void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
847 bool EmitWarning = true;
848
Ted Kremenek87e30c52008-01-17 16:57:34 +0000849 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +0000850 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +0000851
852 // Special case: check for x == x (which is OK).
853 // Do not emit warnings for such cases.
854 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
855 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
856 if (DRL->getDecl() == DRR->getDecl())
857 EmitWarning = false;
858
Ted Kremenek33159832007-11-29 00:59:04 +0000859
860 // Special case: check for comparisons against literals that can be exactly
861 // represented by APFloat. In such cases, do not emit a warning. This
862 // is a heuristic: often comparison against such literals are used to
863 // detect if a value in a variable has not changed. This clearly can
864 // lead to false negatives.
865 if (EmitWarning) {
866 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
867 if (FLL->isExact())
868 EmitWarning = false;
869 }
870 else
871 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
872 if (FLR->isExact())
873 EmitWarning = false;
874 }
875 }
876
Ted Kremenek30c66752007-11-25 00:58:00 +0000877 // Check for comparisons with builtin types.
878 if (EmitWarning)
879 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
880 if (isCallBuiltin(CL))
881 EmitWarning = false;
882
883 if (EmitWarning)
884 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
885 if (isCallBuiltin(CR))
886 EmitWarning = false;
887
888 // Emit the diagnostic.
889 if (EmitWarning)
890 Diag(loc, diag::warn_floatingpoint_eq,
891 lex->getSourceRange(),rex->getSourceRange());
892}