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