SemaChecking.cpp revision df4eee9b035cc4b95b1ea72635e7429d06b0ecc8
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/LiteralSupport.h" 21#include "clang/Lex/Preprocessor.h" 22#include <limits> 23using namespace clang; 24 25/// getLocationOfStringLiteralByte - Return a source location that points to the 26/// specified byte of the specified string literal. 27/// 28/// Strings are amazingly complex. They can be formed from multiple tokens and 29/// can have escape sequences in them in addition to the usual trigraph and 30/// escaped newline business. This routine handles this complexity. 31/// 32SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 33 unsigned ByteNo) const { 34 assert(!SL->isWide() && "This doesn't work for wide strings yet"); 35 36 // Loop over all of the tokens in this string until we find the one that 37 // contains the byte we're looking for. 38 unsigned TokNo = 0; 39 while (1) { 40 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!"); 41 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo); 42 43 // Get the spelling of the string so that we can get the data that makes up 44 // the string literal, not the identifier for the macro it is potentially 45 // expanded through. 46 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc); 47 48 // Re-lex the token to get its length and original spelling. 49 std::pair<FileID, unsigned> LocInfo = 50 SourceMgr.getDecomposedLoc(StrTokSpellingLoc); 51 std::pair<const char *,const char *> Buffer = 52 SourceMgr.getBufferData(LocInfo.first); 53 const char *StrData = Buffer.first+LocInfo.second; 54 55 // Create a langops struct and enable trigraphs. This is sufficient for 56 // relexing tokens. 57 LangOptions LangOpts; 58 LangOpts.Trigraphs = true; 59 60 // Create a lexer starting at the beginning of this token. 61 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData, 62 Buffer.second); 63 Token TheTok; 64 TheLexer.LexFromRawLexer(TheTok); 65 66 // Use the StringLiteralParser to compute the length of the string in bytes. 67 StringLiteralParser SLP(&TheTok, 1, PP); 68 unsigned TokNumBytes = SLP.GetStringLength(); 69 70 // If the byte is in this token, return the location of the byte. 71 if (ByteNo < TokNumBytes || 72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) { 73 unsigned Offset = 74 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP); 75 76 // Now that we know the offset of the token in the spelling, use the 77 // preprocessor to get the offset in the original source. 78 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset); 79 } 80 81 // Move to the next string token. 82 ++TokNo; 83 ByteNo -= TokNumBytes; 84 } 85} 86 87/// CheckablePrintfAttr - does a function call have a "printf" attribute 88/// and arguments that merit checking? 89bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 90 if (Format->getType() == "printf") return true; 91 if (Format->getType() == "printf0") { 92 // printf0 allows null "format" string; if so don't check format/args 93 unsigned format_idx = Format->getFormatIdx() - 1; 94 if (format_idx < TheCall->getNumArgs()) { 95 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 96 if (!Format->isNullPointerConstant(Context)) 97 return true; 98 } 99 } 100 return false; 101} 102 103Action::OwningExprResult 104Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 105 OwningExprResult TheCallResult(Owned(TheCall)); 106 107 switch (BuiltinID) { 108 case Builtin::BI__builtin___CFStringMakeConstantString: 109 assert(TheCall->getNumArgs() == 1 && 110 "Wrong # arguments to builtin CFStringMakeConstantString"); 111 if (CheckObjCString(TheCall->getArg(0))) 112 return ExprError(); 113 break; 114 case Builtin::BI__builtin_stdarg_start: 115 case Builtin::BI__builtin_va_start: 116 if (SemaBuiltinVAStart(TheCall)) 117 return ExprError(); 118 break; 119 case Builtin::BI__builtin_isgreater: 120 case Builtin::BI__builtin_isgreaterequal: 121 case Builtin::BI__builtin_isless: 122 case Builtin::BI__builtin_islessequal: 123 case Builtin::BI__builtin_islessgreater: 124 case Builtin::BI__builtin_isunordered: 125 if (SemaBuiltinUnorderedCompare(TheCall)) 126 return ExprError(); 127 break; 128 case Builtin::BI__builtin_isfinite: 129 case Builtin::BI__builtin_isinf: 130 case Builtin::BI__builtin_isinf_sign: 131 case Builtin::BI__builtin_isnan: 132 case Builtin::BI__builtin_isnormal: 133 if (SemaBuiltinUnaryFP(TheCall)) 134 return ExprError(); 135 break; 136 case Builtin::BI__builtin_return_address: 137 case Builtin::BI__builtin_frame_address: 138 if (SemaBuiltinStackAddress(TheCall)) 139 return ExprError(); 140 break; 141 case Builtin::BI__builtin_shufflevector: 142 return SemaBuiltinShuffleVector(TheCall); 143 // TheCall will be freed by the smart pointer here, but that's fine, since 144 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 145 case Builtin::BI__builtin_prefetch: 146 if (SemaBuiltinPrefetch(TheCall)) 147 return ExprError(); 148 break; 149 case Builtin::BI__builtin_object_size: 150 if (SemaBuiltinObjectSize(TheCall)) 151 return ExprError(); 152 break; 153 case Builtin::BI__builtin_longjmp: 154 if (SemaBuiltinLongjmp(TheCall)) 155 return ExprError(); 156 break; 157 case Builtin::BI__sync_fetch_and_add: 158 case Builtin::BI__sync_fetch_and_sub: 159 case Builtin::BI__sync_fetch_and_or: 160 case Builtin::BI__sync_fetch_and_and: 161 case Builtin::BI__sync_fetch_and_xor: 162 case Builtin::BI__sync_fetch_and_nand: 163 case Builtin::BI__sync_add_and_fetch: 164 case Builtin::BI__sync_sub_and_fetch: 165 case Builtin::BI__sync_and_and_fetch: 166 case Builtin::BI__sync_or_and_fetch: 167 case Builtin::BI__sync_xor_and_fetch: 168 case Builtin::BI__sync_nand_and_fetch: 169 case Builtin::BI__sync_val_compare_and_swap: 170 case Builtin::BI__sync_bool_compare_and_swap: 171 case Builtin::BI__sync_lock_test_and_set: 172 case Builtin::BI__sync_lock_release: 173 if (SemaBuiltinAtomicOverloaded(TheCall)) 174 return ExprError(); 175 break; 176 } 177 178 return move(TheCallResult); 179} 180 181/// CheckFunctionCall - Check a direct function call for various correctness 182/// and safety properties not strictly enforced by the C type system. 183bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 184 // Get the IdentifierInfo* for the called function. 185 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 186 187 // None of the checks below are needed for functions that don't have 188 // simple names (e.g., C++ conversion functions). 189 if (!FnInfo) 190 return false; 191 192 // FIXME: This mechanism should be abstracted to be less fragile and 193 // more efficient. For example, just map function ids to custom 194 // handlers. 195 196 // Printf checking. 197 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) { 198 if (CheckablePrintfAttr(Format, TheCall)) { 199 bool HasVAListArg = Format->getFirstArg() == 0; 200 if (!HasVAListArg) { 201 if (const FunctionProtoType *Proto 202 = FDecl->getType()->getAs<FunctionProtoType>()) 203 HasVAListArg = !Proto->isVariadic(); 204 } 205 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 206 HasVAListArg ? 0 : Format->getFirstArg() - 1); 207 } 208 } 209 210 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull; 211 NonNull = NonNull->getNext<NonNullAttr>()) 212 CheckNonNullArguments(NonNull, TheCall); 213 214 return false; 215} 216 217bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 218 // Printf checking. 219 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 220 if (!Format) 221 return false; 222 223 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 224 if (!V) 225 return false; 226 227 QualType Ty = V->getType(); 228 if (!Ty->isBlockPointerType()) 229 return false; 230 231 if (!CheckablePrintfAttr(Format, TheCall)) 232 return false; 233 234 bool HasVAListArg = Format->getFirstArg() == 0; 235 if (!HasVAListArg) { 236 const FunctionType *FT = 237 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 238 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 239 HasVAListArg = !Proto->isVariadic(); 240 } 241 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 242 HasVAListArg ? 0 : Format->getFirstArg() - 1); 243 244 return false; 245} 246 247/// SemaBuiltinAtomicOverloaded - We have a call to a function like 248/// __sync_fetch_and_add, which is an overloaded function based on the pointer 249/// type of its first argument. The main ActOnCallExpr routines have already 250/// promoted the types of arguments because all of these calls are prototyped as 251/// void(...). 252/// 253/// This function goes through and does final semantic checking for these 254/// builtins, 255bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) { 256 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 257 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 258 259 // Ensure that we have at least one argument to do type inference from. 260 if (TheCall->getNumArgs() < 1) 261 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 262 << 0 << TheCall->getCallee()->getSourceRange(); 263 264 // Inspect the first argument of the atomic builtin. This should always be 265 // a pointer type, whose element is an integral scalar or pointer type. 266 // Because it is a pointer type, we don't have to worry about any implicit 267 // casts here. 268 Expr *FirstArg = TheCall->getArg(0); 269 if (!FirstArg->getType()->isPointerType()) 270 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 271 << FirstArg->getType() << FirstArg->getSourceRange(); 272 273 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType(); 274 if (!ValType->isIntegerType() && !ValType->isPointerType() && 275 !ValType->isBlockPointerType()) 276 return Diag(DRE->getLocStart(), 277 diag::err_atomic_builtin_must_be_pointer_intptr) 278 << FirstArg->getType() << FirstArg->getSourceRange(); 279 280 // We need to figure out which concrete builtin this maps onto. For example, 281 // __sync_fetch_and_add with a 2 byte object turns into 282 // __sync_fetch_and_add_2. 283#define BUILTIN_ROW(x) \ 284 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 285 Builtin::BI##x##_8, Builtin::BI##x##_16 } 286 287 static const unsigned BuiltinIndices[][5] = { 288 BUILTIN_ROW(__sync_fetch_and_add), 289 BUILTIN_ROW(__sync_fetch_and_sub), 290 BUILTIN_ROW(__sync_fetch_and_or), 291 BUILTIN_ROW(__sync_fetch_and_and), 292 BUILTIN_ROW(__sync_fetch_and_xor), 293 BUILTIN_ROW(__sync_fetch_and_nand), 294 295 BUILTIN_ROW(__sync_add_and_fetch), 296 BUILTIN_ROW(__sync_sub_and_fetch), 297 BUILTIN_ROW(__sync_and_and_fetch), 298 BUILTIN_ROW(__sync_or_and_fetch), 299 BUILTIN_ROW(__sync_xor_and_fetch), 300 BUILTIN_ROW(__sync_nand_and_fetch), 301 302 BUILTIN_ROW(__sync_val_compare_and_swap), 303 BUILTIN_ROW(__sync_bool_compare_and_swap), 304 BUILTIN_ROW(__sync_lock_test_and_set), 305 BUILTIN_ROW(__sync_lock_release) 306 }; 307#undef BUILTIN_ROW 308 309 // Determine the index of the size. 310 unsigned SizeIndex; 311 switch (Context.getTypeSize(ValType)/8) { 312 case 1: SizeIndex = 0; break; 313 case 2: SizeIndex = 1; break; 314 case 4: SizeIndex = 2; break; 315 case 8: SizeIndex = 3; break; 316 case 16: SizeIndex = 4; break; 317 default: 318 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 319 << FirstArg->getType() << FirstArg->getSourceRange(); 320 } 321 322 // Each of these builtins has one pointer argument, followed by some number of 323 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 324 // that we ignore. Find out which row of BuiltinIndices to read from as well 325 // as the number of fixed args. 326 unsigned BuiltinID = FDecl->getBuiltinID(); 327 unsigned BuiltinIndex, NumFixed = 1; 328 switch (BuiltinID) { 329 default: assert(0 && "Unknown overloaded atomic builtin!"); 330 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 331 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 332 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 333 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 334 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 335 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break; 336 337 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break; 338 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break; 339 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break; 340 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break; 341 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break; 342 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break; 343 344 case Builtin::BI__sync_val_compare_and_swap: 345 BuiltinIndex = 12; 346 NumFixed = 2; 347 break; 348 case Builtin::BI__sync_bool_compare_and_swap: 349 BuiltinIndex = 13; 350 NumFixed = 2; 351 break; 352 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break; 353 case Builtin::BI__sync_lock_release: 354 BuiltinIndex = 15; 355 NumFixed = 0; 356 break; 357 } 358 359 // Now that we know how many fixed arguments we expect, first check that we 360 // have at least that many. 361 if (TheCall->getNumArgs() < 1+NumFixed) 362 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 363 << 0 << TheCall->getCallee()->getSourceRange(); 364 365 366 // Get the decl for the concrete builtin from this, we can tell what the 367 // concrete integer type we should convert to is. 368 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 369 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 370 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 371 FunctionDecl *NewBuiltinDecl = 372 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 373 TUScope, false, DRE->getLocStart())); 374 const FunctionProtoType *BuiltinFT = 375 NewBuiltinDecl->getType()->getAs<FunctionProtoType>(); 376 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType(); 377 378 // If the first type needs to be converted (e.g. void** -> int*), do it now. 379 if (BuiltinFT->getArgType(0) != FirstArg->getType()) { 380 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_Unknown, 381 /*isLvalue=*/false); 382 TheCall->setArg(0, FirstArg); 383 } 384 385 // Next, walk the valid ones promoting to the right type. 386 for (unsigned i = 0; i != NumFixed; ++i) { 387 Expr *Arg = TheCall->getArg(i+1); 388 389 // If the argument is an implicit cast, then there was a promotion due to 390 // "...", just remove it now. 391 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 392 Arg = ICE->getSubExpr(); 393 ICE->setSubExpr(0); 394 ICE->Destroy(Context); 395 TheCall->setArg(i+1, Arg); 396 } 397 398 // GCC does an implicit conversion to the pointer or integer ValType. This 399 // can fail in some cases (1i -> int**), check for this error case now. 400 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 401 CXXMethodDecl *ConversionDecl = 0; 402 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, 403 ConversionDecl)) 404 return true; 405 406 // Okay, we have something that *can* be converted to the right type. Check 407 // to see if there is a potentially weird extension going on here. This can 408 // happen when you do an atomic operation on something like an char* and 409 // pass in 42. The 42 gets converted to char. This is even more strange 410 // for things like 45.123 -> char, etc. 411 // FIXME: Do this check. 412 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false); 413 TheCall->setArg(i+1, Arg); 414 } 415 416 // Switch the DeclRefExpr to refer to the new decl. 417 DRE->setDecl(NewBuiltinDecl); 418 DRE->setType(NewBuiltinDecl->getType()); 419 420 // Set the callee in the CallExpr. 421 // FIXME: This leaks the original parens and implicit casts. 422 Expr *PromotedCall = DRE; 423 UsualUnaryConversions(PromotedCall); 424 TheCall->setCallee(PromotedCall); 425 426 427 // Change the result type of the call to match the result type of the decl. 428 TheCall->setType(NewBuiltinDecl->getResultType()); 429 return false; 430} 431 432 433/// CheckObjCString - Checks that the argument to the builtin 434/// CFString constructor is correct 435/// FIXME: GCC currently emits the following warning: 436/// "warning: input conversion stopped due to an input byte that does not 437/// belong to the input codeset UTF-8" 438/// Note: It might also make sense to do the UTF-16 conversion here (would 439/// simplify the backend). 440bool Sema::CheckObjCString(Expr *Arg) { 441 Arg = Arg->IgnoreParenCasts(); 442 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 443 444 if (!Literal || Literal->isWide()) { 445 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 446 << Arg->getSourceRange(); 447 return true; 448 } 449 450 llvm::StringRef Str = Literal->getString(); 451 size_t NullLoc = Str.find('\0'); 452 453 if (NullLoc != llvm::StringRef::npos) 454 Diag(getLocationOfStringLiteralByte(Literal, NullLoc), 455 diag::warn_cfstring_literal_contains_nul_character) 456 << Arg->getSourceRange(); 457 458 return false; 459} 460 461/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 462/// Emit an error and return true on failure, return false on success. 463bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 464 Expr *Fn = TheCall->getCallee(); 465 if (TheCall->getNumArgs() > 2) { 466 Diag(TheCall->getArg(2)->getLocStart(), 467 diag::err_typecheck_call_too_many_args) 468 << 0 /*function call*/ << Fn->getSourceRange() 469 << SourceRange(TheCall->getArg(2)->getLocStart(), 470 (*(TheCall->arg_end()-1))->getLocEnd()); 471 return true; 472 } 473 474 if (TheCall->getNumArgs() < 2) { 475 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 476 << 0 /*function call*/; 477 } 478 479 // Determine whether the current function is variadic or not. 480 bool isVariadic; 481 if (CurBlock) 482 isVariadic = CurBlock->isVariadic; 483 else if (getCurFunctionDecl()) { 484 if (FunctionProtoType* FTP = 485 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType())) 486 isVariadic = FTP->isVariadic(); 487 else 488 isVariadic = false; 489 } else { 490 isVariadic = getCurMethodDecl()->isVariadic(); 491 } 492 493 if (!isVariadic) { 494 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 495 return true; 496 } 497 498 // Verify that the second argument to the builtin is the last argument of the 499 // current function or method. 500 bool SecondArgIsLastNamedArgument = false; 501 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 502 503 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 504 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 505 // FIXME: This isn't correct for methods (results in bogus warning). 506 // Get the last formal in the current function. 507 const ParmVarDecl *LastArg; 508 if (CurBlock) 509 LastArg = *(CurBlock->TheDecl->param_end()-1); 510 else if (FunctionDecl *FD = getCurFunctionDecl()) 511 LastArg = *(FD->param_end()-1); 512 else 513 LastArg = *(getCurMethodDecl()->param_end()-1); 514 SecondArgIsLastNamedArgument = PV == LastArg; 515 } 516 } 517 518 if (!SecondArgIsLastNamedArgument) 519 Diag(TheCall->getArg(1)->getLocStart(), 520 diag::warn_second_parameter_of_va_start_not_last_named_argument); 521 return false; 522} 523 524/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 525/// friends. This is declared to take (...), so we have to check everything. 526bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 527 if (TheCall->getNumArgs() < 2) 528 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 529 << 0 /*function call*/; 530 if (TheCall->getNumArgs() > 2) 531 return Diag(TheCall->getArg(2)->getLocStart(), 532 diag::err_typecheck_call_too_many_args) 533 << 0 /*function call*/ 534 << SourceRange(TheCall->getArg(2)->getLocStart(), 535 (*(TheCall->arg_end()-1))->getLocEnd()); 536 537 Expr *OrigArg0 = TheCall->getArg(0); 538 Expr *OrigArg1 = TheCall->getArg(1); 539 540 // Do standard promotions between the two arguments, returning their common 541 // type. 542 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 543 544 // Make sure any conversions are pushed back into the call; this is 545 // type safe since unordered compare builtins are declared as "_Bool 546 // foo(...)". 547 TheCall->setArg(0, OrigArg0); 548 TheCall->setArg(1, OrigArg1); 549 550 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent()) 551 return false; 552 553 // If the common type isn't a real floating type, then the arguments were 554 // invalid for this operation. 555 if (!Res->isRealFloatingType()) 556 return Diag(OrigArg0->getLocStart(), 557 diag::err_typecheck_call_invalid_ordered_compare) 558 << OrigArg0->getType() << OrigArg1->getType() 559 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 560 561 return false; 562} 563 564/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and 565/// friends. This is declared to take (...), so we have to check everything. 566bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) { 567 if (TheCall->getNumArgs() < 1) 568 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 569 << 0 /*function call*/; 570 if (TheCall->getNumArgs() > 1) 571 return Diag(TheCall->getArg(1)->getLocStart(), 572 diag::err_typecheck_call_too_many_args) 573 << 0 /*function call*/ 574 << SourceRange(TheCall->getArg(1)->getLocStart(), 575 (*(TheCall->arg_end()-1))->getLocEnd()); 576 577 Expr *OrigArg = TheCall->getArg(0); 578 579 if (OrigArg->isTypeDependent()) 580 return false; 581 582 // This operation requires a floating-point number 583 if (!OrigArg->getType()->isRealFloatingType()) 584 return Diag(OrigArg->getLocStart(), 585 diag::err_typecheck_call_invalid_unary_fp) 586 << OrigArg->getType() << OrigArg->getSourceRange(); 587 588 return false; 589} 590 591bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { 592 // The signature for these builtins is exact; the only thing we need 593 // to check is that the argument is a constant. 594 SourceLocation Loc; 595 if (!TheCall->getArg(0)->isTypeDependent() && 596 !TheCall->getArg(0)->isValueDependent() && 597 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) 598 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); 599 600 return false; 601} 602 603/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 604// This is declared to take (...), so we have to check everything. 605Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 606 if (TheCall->getNumArgs() < 3) 607 return ExprError(Diag(TheCall->getLocEnd(), 608 diag::err_typecheck_call_too_few_args) 609 << 0 /*function call*/ << TheCall->getSourceRange()); 610 611 unsigned numElements = std::numeric_limits<unsigned>::max(); 612 if (!TheCall->getArg(0)->isTypeDependent() && 613 !TheCall->getArg(1)->isTypeDependent()) { 614 QualType FAType = TheCall->getArg(0)->getType(); 615 QualType SAType = TheCall->getArg(1)->getType(); 616 617 if (!FAType->isVectorType() || !SAType->isVectorType()) { 618 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 619 << SourceRange(TheCall->getArg(0)->getLocStart(), 620 TheCall->getArg(1)->getLocEnd()); 621 return ExprError(); 622 } 623 624 if (Context.getCanonicalType(FAType).getUnqualifiedType() != 625 Context.getCanonicalType(SAType).getUnqualifiedType()) { 626 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 627 << SourceRange(TheCall->getArg(0)->getLocStart(), 628 TheCall->getArg(1)->getLocEnd()); 629 return ExprError(); 630 } 631 632 numElements = FAType->getAs<VectorType>()->getNumElements(); 633 if (TheCall->getNumArgs() != numElements+2) { 634 if (TheCall->getNumArgs() < numElements+2) 635 return ExprError(Diag(TheCall->getLocEnd(), 636 diag::err_typecheck_call_too_few_args) 637 << 0 /*function call*/ << TheCall->getSourceRange()); 638 return ExprError(Diag(TheCall->getLocEnd(), 639 diag::err_typecheck_call_too_many_args) 640 << 0 /*function call*/ << TheCall->getSourceRange()); 641 } 642 } 643 644 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 645 if (TheCall->getArg(i)->isTypeDependent() || 646 TheCall->getArg(i)->isValueDependent()) 647 continue; 648 649 llvm::APSInt Result(32); 650 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 651 return ExprError(Diag(TheCall->getLocStart(), 652 diag::err_shufflevector_nonconstant_argument) 653 << TheCall->getArg(i)->getSourceRange()); 654 655 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 656 return ExprError(Diag(TheCall->getLocStart(), 657 diag::err_shufflevector_argument_too_large) 658 << TheCall->getArg(i)->getSourceRange()); 659 } 660 661 llvm::SmallVector<Expr*, 32> exprs; 662 663 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 664 exprs.push_back(TheCall->getArg(i)); 665 TheCall->setArg(i, 0); 666 } 667 668 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 669 exprs.size(), exprs[0]->getType(), 670 TheCall->getCallee()->getLocStart(), 671 TheCall->getRParenLoc())); 672} 673 674/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 675// This is declared to take (const void*, ...) and can take two 676// optional constant int args. 677bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 678 unsigned NumArgs = TheCall->getNumArgs(); 679 680 if (NumArgs > 3) 681 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 682 << 0 /*function call*/ << TheCall->getSourceRange(); 683 684 // Argument 0 is checked for us and the remaining arguments must be 685 // constant integers. 686 for (unsigned i = 1; i != NumArgs; ++i) { 687 Expr *Arg = TheCall->getArg(i); 688 if (Arg->isTypeDependent()) 689 continue; 690 691 QualType RWType = Arg->getType(); 692 693 const BuiltinType *BT = RWType->getAs<BuiltinType>(); 694 llvm::APSInt Result; 695 if (!BT || BT->getKind() != BuiltinType::Int) 696 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 697 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 698 699 if (Arg->isValueDependent()) 700 continue; 701 702 if (!Arg->isIntegerConstantExpr(Result, Context)) 703 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 704 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 705 706 // FIXME: gcc issues a warning and rewrites these to 0. These 707 // seems especially odd for the third argument since the default 708 // is 3. 709 if (i == 1) { 710 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1) 711 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 712 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 713 } else { 714 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) 715 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 716 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 717 } 718 } 719 720 return false; 721} 722 723/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 724/// int type). This simply type checks that type is one of the defined 725/// constants (0-3). 726bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 727 Expr *Arg = TheCall->getArg(1); 728 if (Arg->isTypeDependent()) 729 return false; 730 731 QualType ArgType = Arg->getType(); 732 const BuiltinType *BT = ArgType->getAs<BuiltinType>(); 733 llvm::APSInt Result(32); 734 if (!BT || BT->getKind() != BuiltinType::Int) 735 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 736 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 737 738 if (Arg->isValueDependent()) 739 return false; 740 741 if (!Arg->isIntegerConstantExpr(Result, Context)) { 742 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 743 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 744 } 745 746 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 747 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 748 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 749 } 750 751 return false; 752} 753 754/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 755/// This checks that val is a constant 1. 756bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 757 Expr *Arg = TheCall->getArg(1); 758 if (Arg->isTypeDependent() || Arg->isValueDependent()) 759 return false; 760 761 llvm::APSInt Result(32); 762 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1) 763 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 764 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 765 766 return false; 767} 768 769// Handle i > 1 ? "x" : "y", recursivelly 770bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 771 bool HasVAListArg, 772 unsigned format_idx, unsigned firstDataArg) { 773 if (E->isTypeDependent() || E->isValueDependent()) 774 return false; 775 776 switch (E->getStmtClass()) { 777 case Stmt::ConditionalOperatorClass: { 778 const ConditionalOperator *C = cast<ConditionalOperator>(E); 779 return SemaCheckStringLiteral(C->getLHS(), TheCall, 780 HasVAListArg, format_idx, firstDataArg) 781 && SemaCheckStringLiteral(C->getRHS(), TheCall, 782 HasVAListArg, format_idx, firstDataArg); 783 } 784 785 case Stmt::ImplicitCastExprClass: { 786 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); 787 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 788 format_idx, firstDataArg); 789 } 790 791 case Stmt::ParenExprClass: { 792 const ParenExpr *Expr = cast<ParenExpr>(E); 793 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 794 format_idx, firstDataArg); 795 } 796 797 case Stmt::DeclRefExprClass: { 798 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 799 800 // As an exception, do not flag errors for variables binding to 801 // const string literals. 802 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 803 bool isConstant = false; 804 QualType T = DR->getType(); 805 806 if (const ArrayType *AT = Context.getAsArrayType(T)) { 807 isConstant = AT->getElementType().isConstant(Context); 808 } else if (const PointerType *PT = T->getAs<PointerType>()) { 809 isConstant = T.isConstant(Context) && 810 PT->getPointeeType().isConstant(Context); 811 } 812 813 if (isConstant) { 814 const VarDecl *Def = 0; 815 if (const Expr *Init = VD->getDefinition(Def)) 816 return SemaCheckStringLiteral(Init, TheCall, 817 HasVAListArg, format_idx, firstDataArg); 818 } 819 820 // For vprintf* functions (i.e., HasVAListArg==true), we add a 821 // special check to see if the format string is a function parameter 822 // of the function calling the printf function. If the function 823 // has an attribute indicating it is a printf-like function, then we 824 // should suppress warnings concerning non-literals being used in a call 825 // to a vprintf function. For example: 826 // 827 // void 828 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 829 // va_list ap; 830 // va_start(ap, fmt); 831 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 832 // ... 833 // 834 // 835 // FIXME: We don't have full attribute support yet, so just check to see 836 // if the argument is a DeclRefExpr that references a parameter. We'll 837 // add proper support for checking the attribute later. 838 if (HasVAListArg) 839 if (isa<ParmVarDecl>(VD)) 840 return true; 841 } 842 843 return false; 844 } 845 846 case Stmt::CallExprClass: { 847 const CallExpr *CE = cast<CallExpr>(E); 848 if (const ImplicitCastExpr *ICE 849 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 850 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 851 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 852 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 853 unsigned ArgIndex = FA->getFormatIdx(); 854 const Expr *Arg = CE->getArg(ArgIndex - 1); 855 856 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 857 format_idx, firstDataArg); 858 } 859 } 860 } 861 } 862 863 return false; 864 } 865 case Stmt::ObjCStringLiteralClass: 866 case Stmt::StringLiteralClass: { 867 const StringLiteral *StrE = NULL; 868 869 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 870 StrE = ObjCFExpr->getString(); 871 else 872 StrE = cast<StringLiteral>(E); 873 874 if (StrE) { 875 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, 876 firstDataArg); 877 return true; 878 } 879 880 return false; 881 } 882 883 default: 884 return false; 885 } 886} 887 888void 889Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 890 const CallExpr *TheCall) { 891 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end(); 892 i != e; ++i) { 893 const Expr *ArgExpr = TheCall->getArg(*i); 894 if (ArgExpr->isNullPointerConstant(Context)) 895 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg) 896 << ArgExpr->getSourceRange(); 897 } 898} 899 900/// CheckPrintfArguments - Check calls to printf (and similar functions) for 901/// correct use of format strings. 902/// 903/// HasVAListArg - A predicate indicating whether the printf-like 904/// function is passed an explicit va_arg argument (e.g., vprintf) 905/// 906/// format_idx - The index into Args for the format string. 907/// 908/// Improper format strings to functions in the printf family can be 909/// the source of bizarre bugs and very serious security holes. A 910/// good source of information is available in the following paper 911/// (which includes additional references): 912/// 913/// FormatGuard: Automatic Protection From printf Format String 914/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. 915/// 916/// Functionality implemented: 917/// 918/// We can statically check the following properties for string 919/// literal format strings for non v.*printf functions (where the 920/// arguments are passed directly): 921// 922/// (1) Are the number of format conversions equal to the number of 923/// data arguments? 924/// 925/// (2) Does each format conversion correctly match the type of the 926/// corresponding data argument? (TODO) 927/// 928/// Moreover, for all printf functions we can: 929/// 930/// (3) Check for a missing format string (when not caught by type checking). 931/// 932/// (4) Check for no-operation flags; e.g. using "#" with format 933/// conversion 'c' (TODO) 934/// 935/// (5) Check the use of '%n', a major source of security holes. 936/// 937/// (6) Check for malformed format conversions that don't specify anything. 938/// 939/// (7) Check for empty format strings. e.g: printf(""); 940/// 941/// (8) Check that the format string is a wide literal. 942/// 943/// (9) Also check the arguments of functions with the __format__ attribute. 944/// (TODO). 945/// 946/// All of these checks can be done by parsing the format string. 947/// 948/// For now, we ONLY do (1), (3), (5), (6), (7), and (8). 949void 950Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg, 951 unsigned format_idx, unsigned firstDataArg) { 952 const Expr *Fn = TheCall->getCallee(); 953 954 // CHECK: printf-like function is called with no format string. 955 if (format_idx >= TheCall->getNumArgs()) { 956 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) 957 << Fn->getSourceRange(); 958 return; 959 } 960 961 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 962 963 // CHECK: format string is not a string literal. 964 // 965 // Dynamically generated format strings are difficult to 966 // automatically vet at compile time. Requiring that format strings 967 // are string literals: (1) permits the checking of format strings by 968 // the compiler and thereby (2) can practically remove the source of 969 // many format string exploits. 970 971 // Format string can be either ObjC string (e.g. @"%d") or 972 // C string (e.g. "%d") 973 // ObjC string uses the same format specifiers as C string, so we can use 974 // the same format string checking logic for both ObjC and C strings. 975 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 976 firstDataArg)) 977 return; // Literal format string found, check done! 978 979 // If there are no arguments specified, warn with -Wformat-security, otherwise 980 // warn only with -Wformat-nonliteral. 981 if (TheCall->getNumArgs() == format_idx+1) 982 Diag(TheCall->getArg(format_idx)->getLocStart(), 983 diag::warn_printf_nonliteral_noargs) 984 << OrigFormatExpr->getSourceRange(); 985 else 986 Diag(TheCall->getArg(format_idx)->getLocStart(), 987 diag::warn_printf_nonliteral) 988 << OrigFormatExpr->getSourceRange(); 989} 990 991void Sema::CheckPrintfString(const StringLiteral *FExpr, 992 const Expr *OrigFormatExpr, 993 const CallExpr *TheCall, bool HasVAListArg, 994 unsigned format_idx, unsigned firstDataArg) { 995 996 const ObjCStringLiteral *ObjCFExpr = 997 dyn_cast<ObjCStringLiteral>(OrigFormatExpr); 998 999 // CHECK: is the format string a wide literal? 1000 if (FExpr->isWide()) { 1001 Diag(FExpr->getLocStart(), 1002 diag::warn_printf_format_string_is_wide_literal) 1003 << OrigFormatExpr->getSourceRange(); 1004 return; 1005 } 1006 1007 // Str - The format string. NOTE: this is NOT null-terminated! 1008 const char *Str = FExpr->getStrData(); 1009 1010 // CHECK: empty format string? 1011 unsigned StrLen = FExpr->getByteLength(); 1012 1013 if (StrLen == 0) { 1014 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) 1015 << OrigFormatExpr->getSourceRange(); 1016 return; 1017 } 1018 1019 // We process the format string using a binary state machine. The 1020 // current state is stored in CurrentState. 1021 enum { 1022 state_OrdChr, 1023 state_Conversion 1024 } CurrentState = state_OrdChr; 1025 1026 // numConversions - The number of conversions seen so far. This is 1027 // incremented as we traverse the format string. 1028 unsigned numConversions = 0; 1029 1030 // numDataArgs - The number of data arguments after the format 1031 // string. This can only be determined for non vprintf-like 1032 // functions. For those functions, this value is 1 (the sole 1033 // va_arg argument). 1034 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg; 1035 1036 // Inspect the format string. 1037 unsigned StrIdx = 0; 1038 1039 // LastConversionIdx - Index within the format string where we last saw 1040 // a '%' character that starts a new format conversion. 1041 unsigned LastConversionIdx = 0; 1042 1043 for (; StrIdx < StrLen; ++StrIdx) { 1044 1045 // Is the number of detected conversion conversions greater than 1046 // the number of matching data arguments? If so, stop. 1047 if (!HasVAListArg && numConversions > numDataArgs) break; 1048 1049 // Handle "\0" 1050 if (Str[StrIdx] == '\0') { 1051 // The string returned by getStrData() is not null-terminated, 1052 // so the presence of a null character is likely an error. 1053 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx), 1054 diag::warn_printf_format_string_contains_null_char) 1055 << OrigFormatExpr->getSourceRange(); 1056 return; 1057 } 1058 1059 // Ordinary characters (not processing a format conversion). 1060 if (CurrentState == state_OrdChr) { 1061 if (Str[StrIdx] == '%') { 1062 CurrentState = state_Conversion; 1063 LastConversionIdx = StrIdx; 1064 } 1065 continue; 1066 } 1067 1068 // Seen '%'. Now processing a format conversion. 1069 switch (Str[StrIdx]) { 1070 // Handle dynamic precision or width specifier. 1071 case '*': { 1072 ++numConversions; 1073 1074 if (!HasVAListArg) { 1075 if (numConversions > numDataArgs) { 1076 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); 1077 1078 if (Str[StrIdx-1] == '.') 1079 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg) 1080 << OrigFormatExpr->getSourceRange(); 1081 else 1082 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg) 1083 << OrigFormatExpr->getSourceRange(); 1084 1085 // Don't do any more checking. We'll just emit spurious errors. 1086 return; 1087 } 1088 1089 // Perform type checking on width/precision specifier. 1090 const Expr *E = TheCall->getArg(format_idx+numConversions); 1091 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>()) 1092 if (BT->getKind() == BuiltinType::Int) 1093 break; 1094 1095 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); 1096 1097 if (Str[StrIdx-1] == '.') 1098 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type) 1099 << E->getType() << E->getSourceRange(); 1100 else 1101 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type) 1102 << E->getType() << E->getSourceRange(); 1103 1104 break; 1105 } 1106 } 1107 1108 // Characters which can terminate a format conversion 1109 // (e.g. "%d"). Characters that specify length modifiers or 1110 // other flags are handled by the default case below. 1111 // 1112 // FIXME: additional checks will go into the following cases. 1113 case 'i': 1114 case 'd': 1115 case 'o': 1116 case 'u': 1117 case 'x': 1118 case 'X': 1119 case 'D': 1120 case 'O': 1121 case 'U': 1122 case 'e': 1123 case 'E': 1124 case 'f': 1125 case 'F': 1126 case 'g': 1127 case 'G': 1128 case 'a': 1129 case 'A': 1130 case 'c': 1131 case 'C': 1132 case 'S': 1133 case 's': 1134 case 'p': 1135 ++numConversions; 1136 CurrentState = state_OrdChr; 1137 break; 1138 1139 case 'm': 1140 // FIXME: Warn in situations where this isn't supported! 1141 CurrentState = state_OrdChr; 1142 break; 1143 1144 // CHECK: Are we using "%n"? Issue a warning. 1145 case 'n': { 1146 ++numConversions; 1147 CurrentState = state_OrdChr; 1148 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, 1149 LastConversionIdx); 1150 1151 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange(); 1152 break; 1153 } 1154 1155 // Handle "%@" 1156 case '@': 1157 // %@ is allowed in ObjC format strings only. 1158 if (ObjCFExpr != NULL) 1159 CurrentState = state_OrdChr; 1160 else { 1161 // Issue a warning: invalid format conversion. 1162 SourceLocation Loc = 1163 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1164 1165 Diag(Loc, diag::warn_printf_invalid_conversion) 1166 << std::string(Str+LastConversionIdx, 1167 Str+std::min(LastConversionIdx+2, StrLen)) 1168 << OrigFormatExpr->getSourceRange(); 1169 } 1170 ++numConversions; 1171 break; 1172 1173 // Handle "%%" 1174 case '%': 1175 // Sanity check: Was the first "%" character the previous one? 1176 // If not, we will assume that we have a malformed format 1177 // conversion, and that the current "%" character is the start 1178 // of a new conversion. 1179 if (StrIdx - LastConversionIdx == 1) 1180 CurrentState = state_OrdChr; 1181 else { 1182 // Issue a warning: invalid format conversion. 1183 SourceLocation Loc = 1184 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1185 1186 Diag(Loc, diag::warn_printf_invalid_conversion) 1187 << std::string(Str+LastConversionIdx, Str+StrIdx) 1188 << OrigFormatExpr->getSourceRange(); 1189 1190 // This conversion is broken. Advance to the next format 1191 // conversion. 1192 LastConversionIdx = StrIdx; 1193 ++numConversions; 1194 } 1195 break; 1196 1197 default: 1198 // This case catches all other characters: flags, widths, etc. 1199 // We should eventually process those as well. 1200 break; 1201 } 1202 } 1203 1204 if (CurrentState == state_Conversion) { 1205 // Issue a warning: invalid format conversion. 1206 SourceLocation Loc = 1207 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1208 1209 Diag(Loc, diag::warn_printf_invalid_conversion) 1210 << std::string(Str+LastConversionIdx, 1211 Str+std::min(LastConversionIdx+2, StrLen)) 1212 << OrigFormatExpr->getSourceRange(); 1213 return; 1214 } 1215 1216 if (!HasVAListArg) { 1217 // CHECK: Does the number of format conversions exceed the number 1218 // of data arguments? 1219 if (numConversions > numDataArgs) { 1220 SourceLocation Loc = 1221 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1222 1223 Diag(Loc, diag::warn_printf_insufficient_data_args) 1224 << OrigFormatExpr->getSourceRange(); 1225 } 1226 // CHECK: Does the number of data arguments exceed the number of 1227 // format conversions in the format string? 1228 else if (numConversions < numDataArgs) 1229 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(), 1230 diag::warn_printf_too_many_data_args) 1231 << OrigFormatExpr->getSourceRange(); 1232 } 1233} 1234 1235//===--- CHECK: Return Address of Stack Variable --------------------------===// 1236 1237static DeclRefExpr* EvalVal(Expr *E); 1238static DeclRefExpr* EvalAddr(Expr* E); 1239 1240/// CheckReturnStackAddr - Check if a return statement returns the address 1241/// of a stack variable. 1242void 1243Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1244 SourceLocation ReturnLoc) { 1245 1246 // Perform checking for returned stack addresses. 1247 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1248 if (DeclRefExpr *DR = EvalAddr(RetValExp)) 1249 Diag(DR->getLocStart(), diag::warn_ret_stack_addr) 1250 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1251 1252 // Skip over implicit cast expressions when checking for block expressions. 1253 RetValExp = RetValExp->IgnoreParenCasts(); 1254 1255 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp)) 1256 if (C->hasBlockDeclRefExprs()) 1257 Diag(C->getLocStart(), diag::err_ret_local_block) 1258 << C->getSourceRange(); 1259 } else if (lhsType->isReferenceType()) { 1260 // Perform checking for stack values returned by reference. 1261 // Check for a reference to the stack 1262 if (DeclRefExpr *DR = EvalVal(RetValExp)) 1263 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 1264 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1265 } 1266} 1267 1268/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1269/// check if the expression in a return statement evaluates to an address 1270/// to a location on the stack. The recursion is used to traverse the 1271/// AST of the return expression, with recursion backtracking when we 1272/// encounter a subexpression that (1) clearly does not lead to the address 1273/// of a stack variable or (2) is something we cannot determine leads to 1274/// the address of a stack variable based on such local checking. 1275/// 1276/// EvalAddr processes expressions that are pointers that are used as 1277/// references (and not L-values). EvalVal handles all other values. 1278/// At the base case of the recursion is a check for a DeclRefExpr* in 1279/// the refers to a stack variable. 1280/// 1281/// This implementation handles: 1282/// 1283/// * pointer-to-pointer casts 1284/// * implicit conversions from array references to pointers 1285/// * taking the address of fields 1286/// * arbitrary interplay between "&" and "*" operators 1287/// * pointer arithmetic from an address of a stack variable 1288/// * taking the address of an array element where the array is on the stack 1289static DeclRefExpr* EvalAddr(Expr *E) { 1290 // We should only be called for evaluating pointer expressions. 1291 assert((E->getType()->isAnyPointerType() || 1292 E->getType()->isBlockPointerType() || 1293 E->getType()->isObjCQualifiedIdType()) && 1294 "EvalAddr only works on pointers"); 1295 1296 // Our "symbolic interpreter" is just a dispatch off the currently 1297 // viewed AST node. We then recursively traverse the AST by calling 1298 // EvalAddr and EvalVal appropriately. 1299 switch (E->getStmtClass()) { 1300 case Stmt::ParenExprClass: 1301 // Ignore parentheses. 1302 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 1303 1304 case Stmt::UnaryOperatorClass: { 1305 // The only unary operator that make sense to handle here 1306 // is AddrOf. All others don't make sense as pointers. 1307 UnaryOperator *U = cast<UnaryOperator>(E); 1308 1309 if (U->getOpcode() == UnaryOperator::AddrOf) 1310 return EvalVal(U->getSubExpr()); 1311 else 1312 return NULL; 1313 } 1314 1315 case Stmt::BinaryOperatorClass: { 1316 // Handle pointer arithmetic. All other binary operators are not valid 1317 // in this context. 1318 BinaryOperator *B = cast<BinaryOperator>(E); 1319 BinaryOperator::Opcode op = B->getOpcode(); 1320 1321 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 1322 return NULL; 1323 1324 Expr *Base = B->getLHS(); 1325 1326 // Determine which argument is the real pointer base. It could be 1327 // the RHS argument instead of the LHS. 1328 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1329 1330 assert (Base->getType()->isPointerType()); 1331 return EvalAddr(Base); 1332 } 1333 1334 // For conditional operators we need to see if either the LHS or RHS are 1335 // valid DeclRefExpr*s. If one of them is valid, we return it. 1336 case Stmt::ConditionalOperatorClass: { 1337 ConditionalOperator *C = cast<ConditionalOperator>(E); 1338 1339 // Handle the GNU extension for missing LHS. 1340 if (Expr *lhsExpr = C->getLHS()) 1341 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 1342 return LHS; 1343 1344 return EvalAddr(C->getRHS()); 1345 } 1346 1347 // For casts, we need to handle conversions from arrays to 1348 // pointer values, and pointer-to-pointer conversions. 1349 case Stmt::ImplicitCastExprClass: 1350 case Stmt::CStyleCastExprClass: 1351 case Stmt::CXXFunctionalCastExprClass: { 1352 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1353 QualType T = SubExpr->getType(); 1354 1355 if (SubExpr->getType()->isPointerType() || 1356 SubExpr->getType()->isBlockPointerType() || 1357 SubExpr->getType()->isObjCQualifiedIdType()) 1358 return EvalAddr(SubExpr); 1359 else if (T->isArrayType()) 1360 return EvalVal(SubExpr); 1361 else 1362 return 0; 1363 } 1364 1365 // C++ casts. For dynamic casts, static casts, and const casts, we 1366 // are always converting from a pointer-to-pointer, so we just blow 1367 // through the cast. In the case the dynamic cast doesn't fail (and 1368 // return NULL), we take the conservative route and report cases 1369 // where we return the address of a stack variable. For Reinterpre 1370 // FIXME: The comment about is wrong; we're not always converting 1371 // from pointer to pointer. I'm guessing that this code should also 1372 // handle references to objects. 1373 case Stmt::CXXStaticCastExprClass: 1374 case Stmt::CXXDynamicCastExprClass: 1375 case Stmt::CXXConstCastExprClass: 1376 case Stmt::CXXReinterpretCastExprClass: { 1377 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 1378 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 1379 return EvalAddr(S); 1380 else 1381 return NULL; 1382 } 1383 1384 // Everything else: we simply don't reason about them. 1385 default: 1386 return NULL; 1387 } 1388} 1389 1390 1391/// EvalVal - This function is complements EvalAddr in the mutual recursion. 1392/// See the comments for EvalAddr for more details. 1393static DeclRefExpr* EvalVal(Expr *E) { 1394 1395 // We should only be called for evaluating non-pointer expressions, or 1396 // expressions with a pointer type that are not used as references but instead 1397 // are l-values (e.g., DeclRefExpr with a pointer type). 1398 1399 // Our "symbolic interpreter" is just a dispatch off the currently 1400 // viewed AST node. We then recursively traverse the AST by calling 1401 // EvalAddr and EvalVal appropriately. 1402 switch (E->getStmtClass()) { 1403 case Stmt::DeclRefExprClass: 1404 case Stmt::QualifiedDeclRefExprClass: { 1405 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 1406 // at code that refers to a variable's name. We check if it has local 1407 // storage within the function, and if so, return the expression. 1408 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1409 1410 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1411 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 1412 1413 return NULL; 1414 } 1415 1416 case Stmt::ParenExprClass: 1417 // Ignore parentheses. 1418 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 1419 1420 case Stmt::UnaryOperatorClass: { 1421 // The only unary operator that make sense to handle here 1422 // is Deref. All others don't resolve to a "name." This includes 1423 // handling all sorts of rvalues passed to a unary operator. 1424 UnaryOperator *U = cast<UnaryOperator>(E); 1425 1426 if (U->getOpcode() == UnaryOperator::Deref) 1427 return EvalAddr(U->getSubExpr()); 1428 1429 return NULL; 1430 } 1431 1432 case Stmt::ArraySubscriptExprClass: { 1433 // Array subscripts are potential references to data on the stack. We 1434 // retrieve the DeclRefExpr* for the array variable if it indeed 1435 // has local storage. 1436 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 1437 } 1438 1439 case Stmt::ConditionalOperatorClass: { 1440 // For conditional operators we need to see if either the LHS or RHS are 1441 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 1442 ConditionalOperator *C = cast<ConditionalOperator>(E); 1443 1444 // Handle the GNU extension for missing LHS. 1445 if (Expr *lhsExpr = C->getLHS()) 1446 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 1447 return LHS; 1448 1449 return EvalVal(C->getRHS()); 1450 } 1451 1452 // Accesses to members are potential references to data on the stack. 1453 case Stmt::MemberExprClass: { 1454 MemberExpr *M = cast<MemberExpr>(E); 1455 1456 // Check for indirect access. We only want direct field accesses. 1457 if (!M->isArrow()) 1458 return EvalVal(M->getBase()); 1459 else 1460 return NULL; 1461 } 1462 1463 // Everything else: we simply don't reason about them. 1464 default: 1465 return NULL; 1466 } 1467} 1468 1469//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1470 1471/// Check for comparisons of floating point operands using != and ==. 1472/// Issue a warning if these are no self-comparisons, as they are not likely 1473/// to do what the programmer intended. 1474void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1475 bool EmitWarning = true; 1476 1477 Expr* LeftExprSansParen = lex->IgnoreParens(); 1478 Expr* RightExprSansParen = rex->IgnoreParens(); 1479 1480 // Special case: check for x == x (which is OK). 1481 // Do not emit warnings for such cases. 1482 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1483 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1484 if (DRL->getDecl() == DRR->getDecl()) 1485 EmitWarning = false; 1486 1487 1488 // Special case: check for comparisons against literals that can be exactly 1489 // represented by APFloat. In such cases, do not emit a warning. This 1490 // is a heuristic: often comparison against such literals are used to 1491 // detect if a value in a variable has not changed. This clearly can 1492 // lead to false negatives. 1493 if (EmitWarning) { 1494 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1495 if (FLL->isExact()) 1496 EmitWarning = false; 1497 } else 1498 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1499 if (FLR->isExact()) 1500 EmitWarning = false; 1501 } 1502 } 1503 1504 // Check for comparisons with builtin types. 1505 if (EmitWarning) 1506 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1507 if (CL->isBuiltinCall(Context)) 1508 EmitWarning = false; 1509 1510 if (EmitWarning) 1511 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1512 if (CR->isBuiltinCall(Context)) 1513 EmitWarning = false; 1514 1515 // Emit the diagnostic. 1516 if (EmitWarning) 1517 Diag(loc, diag::warn_floatingpoint_eq) 1518 << lex->getSourceRange() << rex->getSourceRange(); 1519} 1520