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