SemaChecking.cpp revision 0eb23307222bda7ad95d968eac4e1ab30864b213
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements extra semantic analysis beyond what is enforced 11// by the C type system. 12// 13//===----------------------------------------------------------------------===// 14 15#include "Sema.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Basic/Diagnostic.h" 22#include "SemaUtil.h" 23using namespace clang; 24 25/// CheckFunctionCall - Check a direct function call for various correctness 26/// and safety properties not strictly enforced by the C type system. 27Action::OwningExprResult 28Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 29 OwningExprResult TheCallResult(Owned(TheCall)); 30 // Get the IdentifierInfo* for the called function. 31 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 32 33 // None of the checks below are needed for functions that don't have 34 // simple names (e.g., C++ conversion functions). 35 if (!FnInfo) 36 return move(TheCallResult); 37 38 switch (FnInfo->getBuiltinID()) { 39 case Builtin::BI__builtin___CFStringMakeConstantString: 40 assert(TheCall->getNumArgs() == 1 && 41 "Wrong # arguments to builtin CFStringMakeConstantString"); 42 if (CheckBuiltinCFStringArgument(TheCall->getArg(0))) 43 return ExprError(); 44 return move(TheCallResult); 45 case Builtin::BI__builtin_stdarg_start: 46 case Builtin::BI__builtin_va_start: 47 if (SemaBuiltinVAStart(TheCall)) 48 return ExprError(); 49 return move(TheCallResult); 50 case Builtin::BI__builtin_isgreater: 51 case Builtin::BI__builtin_isgreaterequal: 52 case Builtin::BI__builtin_isless: 53 case Builtin::BI__builtin_islessequal: 54 case Builtin::BI__builtin_islessgreater: 55 case Builtin::BI__builtin_isunordered: 56 if (SemaBuiltinUnorderedCompare(TheCall)) 57 return ExprError(); 58 return move(TheCallResult); 59 case Builtin::BI__builtin_return_address: 60 case Builtin::BI__builtin_frame_address: 61 if (SemaBuiltinStackAddress(TheCall)) 62 return ExprError(); 63 return move(TheCallResult); 64 case Builtin::BI__builtin_shufflevector: 65 return SemaBuiltinShuffleVector(TheCall); 66 // TheCall will be freed by the smart pointer here, but that's fine, since 67 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 68 case Builtin::BI__builtin_prefetch: 69 if (SemaBuiltinPrefetch(TheCall)) 70 return ExprError(); 71 return move(TheCallResult); 72 case Builtin::BI__builtin_object_size: 73 if (SemaBuiltinObjectSize(TheCall)) 74 return ExprError(); 75 } 76 77 // FIXME: This mechanism should be abstracted to be less fragile and 78 // more efficient. For example, just map function ids to custom 79 // handlers. 80 81 // Search the KnownFunctionIDs for the identifier. 82 unsigned i = 0, e = id_num_known_functions; 83 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; } 84 if (i == e) return move(TheCallResult); 85 86 // Printf checking. 87 if (i <= id_vprintf) { 88 // Retrieve the index of the format string parameter and determine 89 // if the function is passed a va_arg argument. 90 unsigned format_idx = 0; 91 bool HasVAListArg = false; 92 93 switch (i) { 94 default: assert(false && "No format string argument index."); 95 case id_NSLog: format_idx = 0; break; 96 case id_asprintf: format_idx = 1; break; 97 case id_fprintf: format_idx = 1; break; 98 case id_printf: format_idx = 0; break; 99 case id_snprintf: format_idx = 2; break; 100 case id_snprintf_chk: format_idx = 4; break; 101 case id_sprintf: format_idx = 1; break; 102 case id_sprintf_chk: format_idx = 3; break; 103 case id_vasprintf: format_idx = 1; HasVAListArg = true; break; 104 case id_vfprintf: format_idx = 1; HasVAListArg = true; break; 105 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break; 106 case id_vsnprintf_chk: format_idx = 4; HasVAListArg = true; break; 107 case id_vsprintf: format_idx = 1; HasVAListArg = true; break; 108 case id_vsprintf_chk: format_idx = 3; HasVAListArg = true; break; 109 case id_vprintf: format_idx = 0; HasVAListArg = true; break; 110 } 111 112 CheckPrintfArguments(TheCall, HasVAListArg, format_idx); 113 } 114 115 return move(TheCallResult); 116} 117 118/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin 119/// CFString constructor is correct 120bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) { 121 Arg = Arg->IgnoreParenCasts(); 122 123 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 124 125 if (!Literal || Literal->isWide()) { 126 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 127 << Arg->getSourceRange(); 128 return true; 129 } 130 131 const char *Data = Literal->getStrData(); 132 unsigned Length = Literal->getByteLength(); 133 134 for (unsigned i = 0; i < Length; ++i) { 135 if (!isascii(Data[i])) { 136 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1), 137 diag::warn_cfstring_literal_contains_non_ascii_character) 138 << Arg->getSourceRange(); 139 break; 140 } 141 142 if (!Data[i]) { 143 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1), 144 diag::warn_cfstring_literal_contains_nul_character) 145 << Arg->getSourceRange(); 146 break; 147 } 148 } 149 150 return false; 151} 152 153/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 154/// Emit an error and return true on failure, return false on success. 155bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 156 Expr *Fn = TheCall->getCallee(); 157 if (TheCall->getNumArgs() > 2) { 158 Diag(TheCall->getArg(2)->getLocStart(), 159 diag::err_typecheck_call_too_many_args) 160 << 0 /*function call*/ << Fn->getSourceRange() 161 << SourceRange(TheCall->getArg(2)->getLocStart(), 162 (*(TheCall->arg_end()-1))->getLocEnd()); 163 return true; 164 } 165 166 if (TheCall->getNumArgs() < 2) { 167 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 168 << 0 /*function call*/; 169 } 170 171 // Determine whether the current function is variadic or not. 172 bool isVariadic; 173 if (getCurFunctionDecl()) { 174 if (FunctionTypeProto* FTP = 175 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType())) 176 isVariadic = FTP->isVariadic(); 177 else 178 isVariadic = false; 179 } else { 180 isVariadic = getCurMethodDecl()->isVariadic(); 181 } 182 183 if (!isVariadic) { 184 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 185 return true; 186 } 187 188 // Verify that the second argument to the builtin is the last argument of the 189 // current function or method. 190 bool SecondArgIsLastNamedArgument = false; 191 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 192 193 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 194 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 195 // FIXME: This isn't correct for methods (results in bogus warning). 196 // Get the last formal in the current function. 197 const ParmVarDecl *LastArg; 198 if (FunctionDecl *FD = getCurFunctionDecl()) 199 LastArg = *(FD->param_end()-1); 200 else 201 LastArg = *(getCurMethodDecl()->param_end()-1); 202 SecondArgIsLastNamedArgument = PV == LastArg; 203 } 204 } 205 206 if (!SecondArgIsLastNamedArgument) 207 Diag(TheCall->getArg(1)->getLocStart(), 208 diag::warn_second_parameter_of_va_start_not_last_named_argument); 209 return false; 210} 211 212/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 213/// friends. This is declared to take (...), so we have to check everything. 214bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 215 if (TheCall->getNumArgs() < 2) 216 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 217 << 0 /*function call*/; 218 if (TheCall->getNumArgs() > 2) 219 return Diag(TheCall->getArg(2)->getLocStart(), 220 diag::err_typecheck_call_too_many_args) 221 << 0 /*function call*/ 222 << SourceRange(TheCall->getArg(2)->getLocStart(), 223 (*(TheCall->arg_end()-1))->getLocEnd()); 224 225 Expr *OrigArg0 = TheCall->getArg(0); 226 Expr *OrigArg1 = TheCall->getArg(1); 227 228 // Do standard promotions between the two arguments, returning their common 229 // type. 230 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 231 232 // If the common type isn't a real floating type, then the arguments were 233 // invalid for this operation. 234 if (!Res->isRealFloatingType()) 235 return Diag(OrigArg0->getLocStart(), 236 diag::err_typecheck_call_invalid_ordered_compare) 237 << OrigArg0->getType() << OrigArg1->getType() 238 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 239 240 return false; 241} 242 243bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { 244 // The signature for these builtins is exact; the only thing we need 245 // to check is that the argument is a constant. 246 SourceLocation Loc; 247 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) 248 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); 249 250 return false; 251} 252 253/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 254// This is declared to take (...), so we have to check everything. 255Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 256 if (TheCall->getNumArgs() < 3) 257 return ExprError(Diag(TheCall->getLocEnd(), 258 diag::err_typecheck_call_too_few_args) 259 << 0 /*function call*/ << TheCall->getSourceRange()); 260 261 QualType FAType = TheCall->getArg(0)->getType(); 262 QualType SAType = TheCall->getArg(1)->getType(); 263 264 if (!FAType->isVectorType() || !SAType->isVectorType()) { 265 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 266 << SourceRange(TheCall->getArg(0)->getLocStart(), 267 TheCall->getArg(1)->getLocEnd()); 268 return ExprError(); 269 } 270 271 if (Context.getCanonicalType(FAType).getUnqualifiedType() != 272 Context.getCanonicalType(SAType).getUnqualifiedType()) { 273 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 274 << SourceRange(TheCall->getArg(0)->getLocStart(), 275 TheCall->getArg(1)->getLocEnd()); 276 return ExprError(); 277 } 278 279 unsigned numElements = FAType->getAsVectorType()->getNumElements(); 280 if (TheCall->getNumArgs() != numElements+2) { 281 if (TheCall->getNumArgs() < numElements+2) 282 return ExprError(Diag(TheCall->getLocEnd(), 283 diag::err_typecheck_call_too_few_args) 284 << 0 /*function call*/ << TheCall->getSourceRange()); 285 return ExprError(Diag(TheCall->getLocEnd(), 286 diag::err_typecheck_call_too_many_args) 287 << 0 /*function call*/ << TheCall->getSourceRange()); 288 } 289 290 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 291 llvm::APSInt Result(32); 292 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 293 return ExprError(Diag(TheCall->getLocStart(), 294 diag::err_shufflevector_nonconstant_argument) 295 << TheCall->getArg(i)->getSourceRange()); 296 297 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 298 return ExprError(Diag(TheCall->getLocStart(), 299 diag::err_shufflevector_argument_too_large) 300 << TheCall->getArg(i)->getSourceRange()); 301 } 302 303 llvm::SmallVector<Expr*, 32> exprs; 304 305 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 306 exprs.push_back(TheCall->getArg(i)); 307 TheCall->setArg(i, 0); 308 } 309 310 return Owned(new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType, 311 TheCall->getCallee()->getLocStart(), 312 TheCall->getRParenLoc())); 313} 314 315/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 316// This is declared to take (const void*, ...) and can take two 317// optional constant int args. 318bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 319 unsigned NumArgs = TheCall->getNumArgs(); 320 321 if (NumArgs > 3) 322 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 323 << 0 /*function call*/ << TheCall->getSourceRange(); 324 325 // Argument 0 is checked for us and the remaining arguments must be 326 // constant integers. 327 for (unsigned i = 1; i != NumArgs; ++i) { 328 Expr *Arg = TheCall->getArg(i); 329 QualType RWType = Arg->getType(); 330 331 const BuiltinType *BT = RWType->getAsBuiltinType(); 332 llvm::APSInt Result; 333 if (!BT || BT->getKind() != BuiltinType::Int || 334 !Arg->isIntegerConstantExpr(Result, Context)) 335 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 336 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 337 338 // FIXME: gcc issues a warning and rewrites these to 0. These 339 // seems especially odd for the third argument since the default 340 // is 3. 341 if (i == 1) { 342 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1) 343 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 344 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 345 } else { 346 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) 347 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 348 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 349 } 350 } 351 352 return false; 353} 354 355/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 356/// int type). This simply type checks that type is one of the defined 357/// constants (0-3). 358bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 359 Expr *Arg = TheCall->getArg(1); 360 QualType ArgType = Arg->getType(); 361 const BuiltinType *BT = ArgType->getAsBuiltinType(); 362 llvm::APSInt Result(32); 363 if (!BT || BT->getKind() != BuiltinType::Int || 364 !Arg->isIntegerConstantExpr(Result, Context)) { 365 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 366 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 367 } 368 369 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 370 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 371 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 372 } 373 374 return false; 375} 376 377// Handle i > 1 ? "x" : "y", recursivelly 378bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg, 379 unsigned format_idx) { 380 381 switch (E->getStmtClass()) { 382 case Stmt::ConditionalOperatorClass: { 383 ConditionalOperator *C = cast<ConditionalOperator>(E); 384 return SemaCheckStringLiteral(C->getLHS(), TheCall, 385 HasVAListArg, format_idx) 386 && SemaCheckStringLiteral(C->getRHS(), TheCall, 387 HasVAListArg, format_idx); 388 } 389 390 case Stmt::ImplicitCastExprClass: { 391 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E); 392 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 393 format_idx); 394 } 395 396 case Stmt::ParenExprClass: { 397 ParenExpr *Expr = dyn_cast<ParenExpr>(E); 398 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 399 format_idx); 400 } 401 402 default: { 403 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E); 404 StringLiteral *StrE = NULL; 405 406 if (ObjCFExpr) 407 StrE = ObjCFExpr->getString(); 408 else 409 StrE = dyn_cast<StringLiteral>(E); 410 411 if (StrE) { 412 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx); 413 return true; 414 } 415 416 return false; 417 } 418 } 419} 420 421 422/// CheckPrintfArguments - Check calls to printf (and similar functions) for 423/// correct use of format strings. 424/// 425/// HasVAListArg - A predicate indicating whether the printf-like 426/// function is passed an explicit va_arg argument (e.g., vprintf) 427/// 428/// format_idx - The index into Args for the format string. 429/// 430/// Improper format strings to functions in the printf family can be 431/// the source of bizarre bugs and very serious security holes. A 432/// good source of information is available in the following paper 433/// (which includes additional references): 434/// 435/// FormatGuard: Automatic Protection From printf Format String 436/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. 437/// 438/// Functionality implemented: 439/// 440/// We can statically check the following properties for string 441/// literal format strings for non v.*printf functions (where the 442/// arguments are passed directly): 443// 444/// (1) Are the number of format conversions equal to the number of 445/// data arguments? 446/// 447/// (2) Does each format conversion correctly match the type of the 448/// corresponding data argument? (TODO) 449/// 450/// Moreover, for all printf functions we can: 451/// 452/// (3) Check for a missing format string (when not caught by type checking). 453/// 454/// (4) Check for no-operation flags; e.g. using "#" with format 455/// conversion 'c' (TODO) 456/// 457/// (5) Check the use of '%n', a major source of security holes. 458/// 459/// (6) Check for malformed format conversions that don't specify anything. 460/// 461/// (7) Check for empty format strings. e.g: printf(""); 462/// 463/// (8) Check that the format string is a wide literal. 464/// 465/// (9) Also check the arguments of functions with the __format__ attribute. 466/// (TODO). 467/// 468/// All of these checks can be done by parsing the format string. 469/// 470/// For now, we ONLY do (1), (3), (5), (6), (7), and (8). 471void 472Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg, 473 unsigned format_idx) { 474 Expr *Fn = TheCall->getCallee(); 475 476 // CHECK: printf-like function is called with no format string. 477 if (format_idx >= TheCall->getNumArgs()) { 478 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) 479 << Fn->getSourceRange(); 480 return; 481 } 482 483 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 484 485 // CHECK: format string is not a string literal. 486 // 487 // Dynamically generated format strings are difficult to 488 // automatically vet at compile time. Requiring that format strings 489 // are string literals: (1) permits the checking of format strings by 490 // the compiler and thereby (2) can practically remove the source of 491 // many format string exploits. 492 493 // Format string can be either ObjC string (e.g. @"%d") or 494 // C string (e.g. "%d") 495 // ObjC string uses the same format specifiers as C string, so we can use 496 // the same format string checking logic for both ObjC and C strings. 497 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx); 498 499 if (!isFExpr) { 500 // For vprintf* functions (i.e., HasVAListArg==true), we add a 501 // special check to see if the format string is a function parameter 502 // of the function calling the printf function. If the function 503 // has an attribute indicating it is a printf-like function, then we 504 // should suppress warnings concerning non-literals being used in a call 505 // to a vprintf function. For example: 506 // 507 // void 508 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) { 509 // va_list ap; 510 // va_start(ap, fmt); 511 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 512 // ... 513 // 514 // 515 // FIXME: We don't have full attribute support yet, so just check to see 516 // if the argument is a DeclRefExpr that references a parameter. We'll 517 // add proper support for checking the attribute later. 518 if (HasVAListArg) 519 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr)) 520 if (isa<ParmVarDecl>(DR->getDecl())) 521 return; 522 523 Diag(TheCall->getArg(format_idx)->getLocStart(), 524 diag::warn_printf_not_string_constant) 525 << OrigFormatExpr->getSourceRange(); 526 return; 527 } 528} 529 530void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr, 531 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) { 532 533 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr); 534 // CHECK: is the format string a wide literal? 535 if (FExpr->isWide()) { 536 Diag(FExpr->getLocStart(), 537 diag::warn_printf_format_string_is_wide_literal) 538 << OrigFormatExpr->getSourceRange(); 539 return; 540 } 541 542 // Str - The format string. NOTE: this is NOT null-terminated! 543 const char * const Str = FExpr->getStrData(); 544 545 // CHECK: empty format string? 546 const unsigned StrLen = FExpr->getByteLength(); 547 548 if (StrLen == 0) { 549 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) 550 << OrigFormatExpr->getSourceRange(); 551 return; 552 } 553 554 // We process the format string using a binary state machine. The 555 // current state is stored in CurrentState. 556 enum { 557 state_OrdChr, 558 state_Conversion 559 } CurrentState = state_OrdChr; 560 561 // numConversions - The number of conversions seen so far. This is 562 // incremented as we traverse the format string. 563 unsigned numConversions = 0; 564 565 // numDataArgs - The number of data arguments after the format 566 // string. This can only be determined for non vprintf-like 567 // functions. For those functions, this value is 1 (the sole 568 // va_arg argument). 569 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1); 570 571 // Inspect the format string. 572 unsigned StrIdx = 0; 573 574 // LastConversionIdx - Index within the format string where we last saw 575 // a '%' character that starts a new format conversion. 576 unsigned LastConversionIdx = 0; 577 578 for (; StrIdx < StrLen; ++StrIdx) { 579 580 // Is the number of detected conversion conversions greater than 581 // the number of matching data arguments? If so, stop. 582 if (!HasVAListArg && numConversions > numDataArgs) break; 583 584 // Handle "\0" 585 if (Str[StrIdx] == '\0') { 586 // The string returned by getStrData() is not null-terminated, 587 // so the presence of a null character is likely an error. 588 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1), 589 diag::warn_printf_format_string_contains_null_char) 590 << OrigFormatExpr->getSourceRange(); 591 return; 592 } 593 594 // Ordinary characters (not processing a format conversion). 595 if (CurrentState == state_OrdChr) { 596 if (Str[StrIdx] == '%') { 597 CurrentState = state_Conversion; 598 LastConversionIdx = StrIdx; 599 } 600 continue; 601 } 602 603 // Seen '%'. Now processing a format conversion. 604 switch (Str[StrIdx]) { 605 // Handle dynamic precision or width specifier. 606 case '*': { 607 ++numConversions; 608 609 if (!HasVAListArg && numConversions > numDataArgs) { 610 SourceLocation Loc = FExpr->getLocStart(); 611 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1); 612 613 if (Str[StrIdx-1] == '.') 614 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg) 615 << OrigFormatExpr->getSourceRange(); 616 else 617 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg) 618 << OrigFormatExpr->getSourceRange(); 619 620 // Don't do any more checking. We'll just emit spurious errors. 621 return; 622 } 623 624 // Perform type checking on width/precision specifier. 625 Expr *E = TheCall->getArg(format_idx+numConversions); 626 if (const BuiltinType *BT = E->getType()->getAsBuiltinType()) 627 if (BT->getKind() == BuiltinType::Int) 628 break; 629 630 SourceLocation Loc = 631 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1); 632 633 if (Str[StrIdx-1] == '.') 634 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type) 635 << E->getType() << E->getSourceRange(); 636 else 637 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type) 638 << E->getType() << E->getSourceRange(); 639 640 break; 641 } 642 643 // Characters which can terminate a format conversion 644 // (e.g. "%d"). Characters that specify length modifiers or 645 // other flags are handled by the default case below. 646 // 647 // FIXME: additional checks will go into the following cases. 648 case 'i': 649 case 'd': 650 case 'o': 651 case 'u': 652 case 'x': 653 case 'X': 654 case 'D': 655 case 'O': 656 case 'U': 657 case 'e': 658 case 'E': 659 case 'f': 660 case 'F': 661 case 'g': 662 case 'G': 663 case 'a': 664 case 'A': 665 case 'c': 666 case 'C': 667 case 'S': 668 case 's': 669 case 'p': 670 ++numConversions; 671 CurrentState = state_OrdChr; 672 break; 673 674 // CHECK: Are we using "%n"? Issue a warning. 675 case 'n': { 676 ++numConversions; 677 CurrentState = state_OrdChr; 678 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(), 679 LastConversionIdx+1); 680 681 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange(); 682 break; 683 } 684 685 // Handle "%@" 686 case '@': 687 // %@ is allowed in ObjC format strings only. 688 if(ObjCFExpr != NULL) 689 CurrentState = state_OrdChr; 690 else { 691 // Issue a warning: invalid format conversion. 692 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(), 693 LastConversionIdx+1); 694 695 Diag(Loc, diag::warn_printf_invalid_conversion) 696 << std::string(Str+LastConversionIdx, 697 Str+std::min(LastConversionIdx+2, StrLen)) 698 << OrigFormatExpr->getSourceRange(); 699 } 700 ++numConversions; 701 break; 702 703 // Handle "%%" 704 case '%': 705 // Sanity check: Was the first "%" character the previous one? 706 // If not, we will assume that we have a malformed format 707 // conversion, and that the current "%" character is the start 708 // of a new conversion. 709 if (StrIdx - LastConversionIdx == 1) 710 CurrentState = state_OrdChr; 711 else { 712 // Issue a warning: invalid format conversion. 713 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(), 714 LastConversionIdx+1); 715 716 Diag(Loc, diag::warn_printf_invalid_conversion) 717 << std::string(Str+LastConversionIdx, Str+StrIdx) 718 << OrigFormatExpr->getSourceRange(); 719 720 // This conversion is broken. Advance to the next format 721 // conversion. 722 LastConversionIdx = StrIdx; 723 ++numConversions; 724 } 725 break; 726 727 default: 728 // This case catches all other characters: flags, widths, etc. 729 // We should eventually process those as well. 730 break; 731 } 732 } 733 734 if (CurrentState == state_Conversion) { 735 // Issue a warning: invalid format conversion. 736 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(), 737 LastConversionIdx+1); 738 739 Diag(Loc, diag::warn_printf_invalid_conversion) 740 << std::string(Str+LastConversionIdx, 741 Str+std::min(LastConversionIdx+2, StrLen)) 742 << OrigFormatExpr->getSourceRange(); 743 return; 744 } 745 746 if (!HasVAListArg) { 747 // CHECK: Does the number of format conversions exceed the number 748 // of data arguments? 749 if (numConversions > numDataArgs) { 750 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(), 751 LastConversionIdx); 752 753 Diag(Loc, diag::warn_printf_insufficient_data_args) 754 << OrigFormatExpr->getSourceRange(); 755 } 756 // CHECK: Does the number of data arguments exceed the number of 757 // format conversions in the format string? 758 else if (numConversions < numDataArgs) 759 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(), 760 diag::warn_printf_too_many_data_args) 761 << OrigFormatExpr->getSourceRange(); 762 } 763} 764 765//===--- CHECK: Return Address of Stack Variable --------------------------===// 766 767static DeclRefExpr* EvalVal(Expr *E); 768static DeclRefExpr* EvalAddr(Expr* E); 769 770/// CheckReturnStackAddr - Check if a return statement returns the address 771/// of a stack variable. 772void 773Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 774 SourceLocation ReturnLoc) { 775 776 // Perform checking for returned stack addresses. 777 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 778 if (DeclRefExpr *DR = EvalAddr(RetValExp)) 779 Diag(DR->getLocStart(), diag::warn_ret_stack_addr) 780 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 781 782 // Skip over implicit cast expressions when checking for block expressions. 783 if (ImplicitCastExpr *IcExpr = 784 dyn_cast_or_null<ImplicitCastExpr>(RetValExp)) 785 RetValExp = IcExpr->getSubExpr(); 786 787 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp)) 788 Diag(C->getLocStart(), diag::err_ret_local_block) 789 << C->getSourceRange(); 790 } 791 // Perform checking for stack values returned by reference. 792 else if (lhsType->isReferenceType()) { 793 // Check for a reference to the stack 794 if (DeclRefExpr *DR = EvalVal(RetValExp)) 795 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 796 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 797 } 798} 799 800/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 801/// check if the expression in a return statement evaluates to an address 802/// to a location on the stack. The recursion is used to traverse the 803/// AST of the return expression, with recursion backtracking when we 804/// encounter a subexpression that (1) clearly does not lead to the address 805/// of a stack variable or (2) is something we cannot determine leads to 806/// the address of a stack variable based on such local checking. 807/// 808/// EvalAddr processes expressions that are pointers that are used as 809/// references (and not L-values). EvalVal handles all other values. 810/// At the base case of the recursion is a check for a DeclRefExpr* in 811/// the refers to a stack variable. 812/// 813/// This implementation handles: 814/// 815/// * pointer-to-pointer casts 816/// * implicit conversions from array references to pointers 817/// * taking the address of fields 818/// * arbitrary interplay between "&" and "*" operators 819/// * pointer arithmetic from an address of a stack variable 820/// * taking the address of an array element where the array is on the stack 821static DeclRefExpr* EvalAddr(Expr *E) { 822 // We should only be called for evaluating pointer expressions. 823 assert((E->getType()->isPointerType() || 824 E->getType()->isBlockPointerType() || 825 E->getType()->isObjCQualifiedIdType()) && 826 "EvalAddr only works on pointers"); 827 828 // Our "symbolic interpreter" is just a dispatch off the currently 829 // viewed AST node. We then recursively traverse the AST by calling 830 // EvalAddr and EvalVal appropriately. 831 switch (E->getStmtClass()) { 832 case Stmt::ParenExprClass: 833 // Ignore parentheses. 834 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 835 836 case Stmt::UnaryOperatorClass: { 837 // The only unary operator that make sense to handle here 838 // is AddrOf. All others don't make sense as pointers. 839 UnaryOperator *U = cast<UnaryOperator>(E); 840 841 if (U->getOpcode() == UnaryOperator::AddrOf) 842 return EvalVal(U->getSubExpr()); 843 else 844 return NULL; 845 } 846 847 case Stmt::BinaryOperatorClass: { 848 // Handle pointer arithmetic. All other binary operators are not valid 849 // in this context. 850 BinaryOperator *B = cast<BinaryOperator>(E); 851 BinaryOperator::Opcode op = B->getOpcode(); 852 853 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 854 return NULL; 855 856 Expr *Base = B->getLHS(); 857 858 // Determine which argument is the real pointer base. It could be 859 // the RHS argument instead of the LHS. 860 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 861 862 assert (Base->getType()->isPointerType()); 863 return EvalAddr(Base); 864 } 865 866 // For conditional operators we need to see if either the LHS or RHS are 867 // valid DeclRefExpr*s. If one of them is valid, we return it. 868 case Stmt::ConditionalOperatorClass: { 869 ConditionalOperator *C = cast<ConditionalOperator>(E); 870 871 // Handle the GNU extension for missing LHS. 872 if (Expr *lhsExpr = C->getLHS()) 873 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 874 return LHS; 875 876 return EvalAddr(C->getRHS()); 877 } 878 879 // For casts, we need to handle conversions from arrays to 880 // pointer values, and pointer-to-pointer conversions. 881 case Stmt::ImplicitCastExprClass: 882 case Stmt::CStyleCastExprClass: 883 case Stmt::CXXFunctionalCastExprClass: { 884 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 885 QualType T = SubExpr->getType(); 886 887 if (SubExpr->getType()->isPointerType() || 888 SubExpr->getType()->isBlockPointerType() || 889 SubExpr->getType()->isObjCQualifiedIdType()) 890 return EvalAddr(SubExpr); 891 else if (T->isArrayType()) 892 return EvalVal(SubExpr); 893 else 894 return 0; 895 } 896 897 // C++ casts. For dynamic casts, static casts, and const casts, we 898 // are always converting from a pointer-to-pointer, so we just blow 899 // through the cast. In the case the dynamic cast doesn't fail (and 900 // return NULL), we take the conservative route and report cases 901 // where we return the address of a stack variable. For Reinterpre 902 // FIXME: The comment about is wrong; we're not always converting 903 // from pointer to pointer. I'm guessing that this code should also 904 // handle references to objects. 905 case Stmt::CXXStaticCastExprClass: 906 case Stmt::CXXDynamicCastExprClass: 907 case Stmt::CXXConstCastExprClass: 908 case Stmt::CXXReinterpretCastExprClass: { 909 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 910 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 911 return EvalAddr(S); 912 else 913 return NULL; 914 } 915 916 // Everything else: we simply don't reason about them. 917 default: 918 return NULL; 919 } 920} 921 922 923/// EvalVal - This function is complements EvalAddr in the mutual recursion. 924/// See the comments for EvalAddr for more details. 925static DeclRefExpr* EvalVal(Expr *E) { 926 927 // We should only be called for evaluating non-pointer expressions, or 928 // expressions with a pointer type that are not used as references but instead 929 // are l-values (e.g., DeclRefExpr with a pointer type). 930 931 // Our "symbolic interpreter" is just a dispatch off the currently 932 // viewed AST node. We then recursively traverse the AST by calling 933 // EvalAddr and EvalVal appropriately. 934 switch (E->getStmtClass()) { 935 case Stmt::DeclRefExprClass: 936 case Stmt::QualifiedDeclRefExprClass: { 937 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 938 // at code that refers to a variable's name. We check if it has local 939 // storage within the function, and if so, return the expression. 940 DeclRefExpr *DR = cast<DeclRefExpr>(E); 941 942 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 943 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 944 945 return NULL; 946 } 947 948 case Stmt::ParenExprClass: 949 // Ignore parentheses. 950 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 951 952 case Stmt::UnaryOperatorClass: { 953 // The only unary operator that make sense to handle here 954 // is Deref. All others don't resolve to a "name." This includes 955 // handling all sorts of rvalues passed to a unary operator. 956 UnaryOperator *U = cast<UnaryOperator>(E); 957 958 if (U->getOpcode() == UnaryOperator::Deref) 959 return EvalAddr(U->getSubExpr()); 960 961 return NULL; 962 } 963 964 case Stmt::ArraySubscriptExprClass: { 965 // Array subscripts are potential references to data on the stack. We 966 // retrieve the DeclRefExpr* for the array variable if it indeed 967 // has local storage. 968 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 969 } 970 971 case Stmt::ConditionalOperatorClass: { 972 // For conditional operators we need to see if either the LHS or RHS are 973 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 974 ConditionalOperator *C = cast<ConditionalOperator>(E); 975 976 // Handle the GNU extension for missing LHS. 977 if (Expr *lhsExpr = C->getLHS()) 978 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 979 return LHS; 980 981 return EvalVal(C->getRHS()); 982 } 983 984 // Accesses to members are potential references to data on the stack. 985 case Stmt::MemberExprClass: { 986 MemberExpr *M = cast<MemberExpr>(E); 987 988 // Check for indirect access. We only want direct field accesses. 989 if (!M->isArrow()) 990 return EvalVal(M->getBase()); 991 else 992 return NULL; 993 } 994 995 // Everything else: we simply don't reason about them. 996 default: 997 return NULL; 998 } 999} 1000 1001//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1002 1003/// Check for comparisons of floating point operands using != and ==. 1004/// Issue a warning if these are no self-comparisons, as they are not likely 1005/// to do what the programmer intended. 1006void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1007 bool EmitWarning = true; 1008 1009 Expr* LeftExprSansParen = lex->IgnoreParens(); 1010 Expr* RightExprSansParen = rex->IgnoreParens(); 1011 1012 // Special case: check for x == x (which is OK). 1013 // Do not emit warnings for such cases. 1014 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1015 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1016 if (DRL->getDecl() == DRR->getDecl()) 1017 EmitWarning = false; 1018 1019 1020 // Special case: check for comparisons against literals that can be exactly 1021 // represented by APFloat. In such cases, do not emit a warning. This 1022 // is a heuristic: often comparison against such literals are used to 1023 // detect if a value in a variable has not changed. This clearly can 1024 // lead to false negatives. 1025 if (EmitWarning) { 1026 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1027 if (FLL->isExact()) 1028 EmitWarning = false; 1029 } 1030 else 1031 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1032 if (FLR->isExact()) 1033 EmitWarning = false; 1034 } 1035 } 1036 1037 // Check for comparisons with builtin types. 1038 if (EmitWarning) 1039 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1040 if (isCallBuiltin(CL)) 1041 EmitWarning = false; 1042 1043 if (EmitWarning) 1044 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1045 if (isCallBuiltin(CR)) 1046 EmitWarning = false; 1047 1048 // Emit the diagnostic. 1049 if (EmitWarning) 1050 Diag(loc, diag::warn_floatingpoint_eq) 1051 << lex->getSourceRange() << rex->getSourceRange(); 1052} 1053