SemaChecking.cpp revision a4923eb7c4b04d360cb2747641a5e92818edf804
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.hasSameUnqualifiedType(FAType, SAType)) { 632 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 633 << SourceRange(TheCall->getArg(0)->getLocStart(), 634 TheCall->getArg(1)->getLocEnd()); 635 return ExprError(); 636 } 637 638 numElements = FAType->getAs<VectorType>()->getNumElements(); 639 if (TheCall->getNumArgs() != numElements+2) { 640 if (TheCall->getNumArgs() < numElements+2) 641 return ExprError(Diag(TheCall->getLocEnd(), 642 diag::err_typecheck_call_too_few_args) 643 << 0 /*function call*/ << TheCall->getSourceRange()); 644 return ExprError(Diag(TheCall->getLocEnd(), 645 diag::err_typecheck_call_too_many_args) 646 << 0 /*function call*/ << TheCall->getSourceRange()); 647 } 648 } 649 650 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 651 if (TheCall->getArg(i)->isTypeDependent() || 652 TheCall->getArg(i)->isValueDependent()) 653 continue; 654 655 llvm::APSInt Result(32); 656 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 657 return ExprError(Diag(TheCall->getLocStart(), 658 diag::err_shufflevector_nonconstant_argument) 659 << TheCall->getArg(i)->getSourceRange()); 660 661 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 662 return ExprError(Diag(TheCall->getLocStart(), 663 diag::err_shufflevector_argument_too_large) 664 << TheCall->getArg(i)->getSourceRange()); 665 } 666 667 llvm::SmallVector<Expr*, 32> exprs; 668 669 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 670 exprs.push_back(TheCall->getArg(i)); 671 TheCall->setArg(i, 0); 672 } 673 674 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 675 exprs.size(), exprs[0]->getType(), 676 TheCall->getCallee()->getLocStart(), 677 TheCall->getRParenLoc())); 678} 679 680/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 681// This is declared to take (const void*, ...) and can take two 682// optional constant int args. 683bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 684 unsigned NumArgs = TheCall->getNumArgs(); 685 686 if (NumArgs > 3) 687 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 688 << 0 /*function call*/ << TheCall->getSourceRange(); 689 690 // Argument 0 is checked for us and the remaining arguments must be 691 // constant integers. 692 for (unsigned i = 1; i != NumArgs; ++i) { 693 Expr *Arg = TheCall->getArg(i); 694 if (Arg->isTypeDependent()) 695 continue; 696 697 QualType RWType = Arg->getType(); 698 699 const BuiltinType *BT = RWType->getAs<BuiltinType>(); 700 llvm::APSInt Result; 701 if (!BT || BT->getKind() != BuiltinType::Int) 702 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 703 << Arg->getSourceRange(); 704 705 if (Arg->isValueDependent()) 706 continue; 707 708 if (!Arg->isIntegerConstantExpr(Result, Context)) 709 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 710 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 711 712 // FIXME: gcc issues a warning and rewrites these to 0. These 713 // seems especially odd for the third argument since the default 714 // is 3. 715 if (i == 1) { 716 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1) 717 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 718 << "0" << "1" << Arg->getSourceRange(); 719 } else { 720 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) 721 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 722 << "0" << "3" << Arg->getSourceRange(); 723 } 724 } 725 726 return false; 727} 728 729/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the 730/// operand must be an integer constant. 731bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) { 732 llvm::APSInt Result; 733 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context)) 734 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice) 735 << TheCall->getArg(0)->getSourceRange(); 736 737 return false; 738} 739 740 741/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 742/// int type). This simply type checks that type is one of the defined 743/// constants (0-3). 744bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 745 Expr *Arg = TheCall->getArg(1); 746 if (Arg->isTypeDependent()) 747 return false; 748 749 QualType ArgType = Arg->getType(); 750 const BuiltinType *BT = ArgType->getAs<BuiltinType>(); 751 llvm::APSInt Result(32); 752 if (!BT || BT->getKind() != BuiltinType::Int) 753 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 754 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 755 756 if (Arg->isValueDependent()) 757 return false; 758 759 if (!Arg->isIntegerConstantExpr(Result, Context)) { 760 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 761 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 762 } 763 764 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 765 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 766 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 767 } 768 769 return false; 770} 771 772/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 773/// This checks that val is a constant 1. 774bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 775 Expr *Arg = TheCall->getArg(1); 776 if (Arg->isTypeDependent() || Arg->isValueDependent()) 777 return false; 778 779 llvm::APSInt Result(32); 780 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1) 781 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 782 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 783 784 return false; 785} 786 787// Handle i > 1 ? "x" : "y", recursivelly 788bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 789 bool HasVAListArg, 790 unsigned format_idx, unsigned firstDataArg) { 791 if (E->isTypeDependent() || E->isValueDependent()) 792 return false; 793 794 switch (E->getStmtClass()) { 795 case Stmt::ConditionalOperatorClass: { 796 const ConditionalOperator *C = cast<ConditionalOperator>(E); 797 return SemaCheckStringLiteral(C->getLHS(), TheCall, 798 HasVAListArg, format_idx, firstDataArg) 799 && SemaCheckStringLiteral(C->getRHS(), TheCall, 800 HasVAListArg, format_idx, firstDataArg); 801 } 802 803 case Stmt::ImplicitCastExprClass: { 804 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); 805 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 806 format_idx, firstDataArg); 807 } 808 809 case Stmt::ParenExprClass: { 810 const ParenExpr *Expr = cast<ParenExpr>(E); 811 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 812 format_idx, firstDataArg); 813 } 814 815 case Stmt::DeclRefExprClass: { 816 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 817 818 // As an exception, do not flag errors for variables binding to 819 // const string literals. 820 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 821 bool isConstant = false; 822 QualType T = DR->getType(); 823 824 if (const ArrayType *AT = Context.getAsArrayType(T)) { 825 isConstant = AT->getElementType().isConstant(Context); 826 } else if (const PointerType *PT = T->getAs<PointerType>()) { 827 isConstant = T.isConstant(Context) && 828 PT->getPointeeType().isConstant(Context); 829 } 830 831 if (isConstant) { 832 const VarDecl *Def = 0; 833 if (const Expr *Init = VD->getDefinition(Def)) 834 return SemaCheckStringLiteral(Init, TheCall, 835 HasVAListArg, format_idx, firstDataArg); 836 } 837 838 // For vprintf* functions (i.e., HasVAListArg==true), we add a 839 // special check to see if the format string is a function parameter 840 // of the function calling the printf function. If the function 841 // has an attribute indicating it is a printf-like function, then we 842 // should suppress warnings concerning non-literals being used in a call 843 // to a vprintf function. For example: 844 // 845 // void 846 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 847 // va_list ap; 848 // va_start(ap, fmt); 849 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 850 // ... 851 // 852 // 853 // FIXME: We don't have full attribute support yet, so just check to see 854 // if the argument is a DeclRefExpr that references a parameter. We'll 855 // add proper support for checking the attribute later. 856 if (HasVAListArg) 857 if (isa<ParmVarDecl>(VD)) 858 return true; 859 } 860 861 return false; 862 } 863 864 case Stmt::CallExprClass: { 865 const CallExpr *CE = cast<CallExpr>(E); 866 if (const ImplicitCastExpr *ICE 867 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 869 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 870 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 871 unsigned ArgIndex = FA->getFormatIdx(); 872 const Expr *Arg = CE->getArg(ArgIndex - 1); 873 874 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 875 format_idx, firstDataArg); 876 } 877 } 878 } 879 } 880 881 return false; 882 } 883 case Stmt::ObjCStringLiteralClass: 884 case Stmt::StringLiteralClass: { 885 const StringLiteral *StrE = NULL; 886 887 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 888 StrE = ObjCFExpr->getString(); 889 else 890 StrE = cast<StringLiteral>(E); 891 892 if (StrE) { 893 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, 894 firstDataArg); 895 return true; 896 } 897 898 return false; 899 } 900 901 default: 902 return false; 903 } 904} 905 906void 907Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 908 const CallExpr *TheCall) { 909 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end(); 910 i != e; ++i) { 911 const Expr *ArgExpr = TheCall->getArg(*i); 912 if (ArgExpr->isNullPointerConstant(Context, 913 Expr::NPC_ValueDependentIsNotNull)) 914 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg) 915 << ArgExpr->getSourceRange(); 916 } 917} 918 919/// CheckPrintfArguments - Check calls to printf (and similar functions) for 920/// correct use of format strings. 921/// 922/// HasVAListArg - A predicate indicating whether the printf-like 923/// function is passed an explicit va_arg argument (e.g., vprintf) 924/// 925/// format_idx - The index into Args for the format string. 926/// 927/// Improper format strings to functions in the printf family can be 928/// the source of bizarre bugs and very serious security holes. A 929/// good source of information is available in the following paper 930/// (which includes additional references): 931/// 932/// FormatGuard: Automatic Protection From printf Format String 933/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. 934/// 935/// Functionality implemented: 936/// 937/// We can statically check the following properties for string 938/// literal format strings for non v.*printf functions (where the 939/// arguments are passed directly): 940// 941/// (1) Are the number of format conversions equal to the number of 942/// data arguments? 943/// 944/// (2) Does each format conversion correctly match the type of the 945/// corresponding data argument? (TODO) 946/// 947/// Moreover, for all printf functions we can: 948/// 949/// (3) Check for a missing format string (when not caught by type checking). 950/// 951/// (4) Check for no-operation flags; e.g. using "#" with format 952/// conversion 'c' (TODO) 953/// 954/// (5) Check the use of '%n', a major source of security holes. 955/// 956/// (6) Check for malformed format conversions that don't specify anything. 957/// 958/// (7) Check for empty format strings. e.g: printf(""); 959/// 960/// (8) Check that the format string is a wide literal. 961/// 962/// (9) Also check the arguments of functions with the __format__ attribute. 963/// (TODO). 964/// 965/// All of these checks can be done by parsing the format string. 966/// 967/// For now, we ONLY do (1), (3), (5), (6), (7), and (8). 968void 969Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg, 970 unsigned format_idx, unsigned firstDataArg) { 971 const Expr *Fn = TheCall->getCallee(); 972 973 // CHECK: printf-like function is called with no format string. 974 if (format_idx >= TheCall->getNumArgs()) { 975 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) 976 << Fn->getSourceRange(); 977 return; 978 } 979 980 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 981 982 // CHECK: format string is not a string literal. 983 // 984 // Dynamically generated format strings are difficult to 985 // automatically vet at compile time. Requiring that format strings 986 // are string literals: (1) permits the checking of format strings by 987 // the compiler and thereby (2) can practically remove the source of 988 // many format string exploits. 989 990 // Format string can be either ObjC string (e.g. @"%d") or 991 // C string (e.g. "%d") 992 // ObjC string uses the same format specifiers as C string, so we can use 993 // the same format string checking logic for both ObjC and C strings. 994 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 995 firstDataArg)) 996 return; // Literal format string found, check done! 997 998 // If there are no arguments specified, warn with -Wformat-security, otherwise 999 // warn only with -Wformat-nonliteral. 1000 if (TheCall->getNumArgs() == format_idx+1) 1001 Diag(TheCall->getArg(format_idx)->getLocStart(), 1002 diag::warn_printf_nonliteral_noargs) 1003 << OrigFormatExpr->getSourceRange(); 1004 else 1005 Diag(TheCall->getArg(format_idx)->getLocStart(), 1006 diag::warn_printf_nonliteral) 1007 << OrigFormatExpr->getSourceRange(); 1008} 1009 1010void Sema::CheckPrintfString(const StringLiteral *FExpr, 1011 const Expr *OrigFormatExpr, 1012 const CallExpr *TheCall, bool HasVAListArg, 1013 unsigned format_idx, unsigned firstDataArg) { 1014 1015 const ObjCStringLiteral *ObjCFExpr = 1016 dyn_cast<ObjCStringLiteral>(OrigFormatExpr); 1017 1018 // CHECK: is the format string a wide literal? 1019 if (FExpr->isWide()) { 1020 Diag(FExpr->getLocStart(), 1021 diag::warn_printf_format_string_is_wide_literal) 1022 << OrigFormatExpr->getSourceRange(); 1023 return; 1024 } 1025 1026 // Str - The format string. NOTE: this is NOT null-terminated! 1027 const char *Str = FExpr->getStrData(); 1028 1029 // CHECK: empty format string? 1030 unsigned StrLen = FExpr->getByteLength(); 1031 1032 if (StrLen == 0) { 1033 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) 1034 << OrigFormatExpr->getSourceRange(); 1035 return; 1036 } 1037 1038 // We process the format string using a binary state machine. The 1039 // current state is stored in CurrentState. 1040 enum { 1041 state_OrdChr, 1042 state_Conversion 1043 } CurrentState = state_OrdChr; 1044 1045 // numConversions - The number of conversions seen so far. This is 1046 // incremented as we traverse the format string. 1047 unsigned numConversions = 0; 1048 1049 // numDataArgs - The number of data arguments after the format 1050 // string. This can only be determined for non vprintf-like 1051 // functions. For those functions, this value is 1 (the sole 1052 // va_arg argument). 1053 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg; 1054 1055 // Inspect the format string. 1056 unsigned StrIdx = 0; 1057 1058 // LastConversionIdx - Index within the format string where we last saw 1059 // a '%' character that starts a new format conversion. 1060 unsigned LastConversionIdx = 0; 1061 1062 for (; StrIdx < StrLen; ++StrIdx) { 1063 1064 // Is the number of detected conversion conversions greater than 1065 // the number of matching data arguments? If so, stop. 1066 if (!HasVAListArg && numConversions > numDataArgs) break; 1067 1068 // Handle "\0" 1069 if (Str[StrIdx] == '\0') { 1070 // The string returned by getStrData() is not null-terminated, 1071 // so the presence of a null character is likely an error. 1072 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx), 1073 diag::warn_printf_format_string_contains_null_char) 1074 << OrigFormatExpr->getSourceRange(); 1075 return; 1076 } 1077 1078 // Ordinary characters (not processing a format conversion). 1079 if (CurrentState == state_OrdChr) { 1080 if (Str[StrIdx] == '%') { 1081 CurrentState = state_Conversion; 1082 LastConversionIdx = StrIdx; 1083 } 1084 continue; 1085 } 1086 1087 // Seen '%'. Now processing a format conversion. 1088 switch (Str[StrIdx]) { 1089 // Handle dynamic precision or width specifier. 1090 case '*': { 1091 ++numConversions; 1092 1093 if (!HasVAListArg) { 1094 if (numConversions > numDataArgs) { 1095 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); 1096 1097 if (Str[StrIdx-1] == '.') 1098 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg) 1099 << OrigFormatExpr->getSourceRange(); 1100 else 1101 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg) 1102 << OrigFormatExpr->getSourceRange(); 1103 1104 // Don't do any more checking. We'll just emit spurious errors. 1105 return; 1106 } 1107 1108 // Perform type checking on width/precision specifier. 1109 const Expr *E = TheCall->getArg(format_idx+numConversions); 1110 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>()) 1111 if (BT->getKind() == BuiltinType::Int) 1112 break; 1113 1114 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); 1115 1116 if (Str[StrIdx-1] == '.') 1117 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type) 1118 << E->getType() << E->getSourceRange(); 1119 else 1120 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type) 1121 << E->getType() << E->getSourceRange(); 1122 1123 break; 1124 } 1125 } 1126 1127 // Characters which can terminate a format conversion 1128 // (e.g. "%d"). Characters that specify length modifiers or 1129 // other flags are handled by the default case below. 1130 // 1131 // FIXME: additional checks will go into the following cases. 1132 case 'i': 1133 case 'd': 1134 case 'o': 1135 case 'u': 1136 case 'x': 1137 case 'X': 1138 case 'D': 1139 case 'O': 1140 case 'U': 1141 case 'e': 1142 case 'E': 1143 case 'f': 1144 case 'F': 1145 case 'g': 1146 case 'G': 1147 case 'a': 1148 case 'A': 1149 case 'c': 1150 case 'C': 1151 case 'S': 1152 case 's': 1153 case 'p': 1154 ++numConversions; 1155 CurrentState = state_OrdChr; 1156 break; 1157 1158 case 'm': 1159 // FIXME: Warn in situations where this isn't supported! 1160 CurrentState = state_OrdChr; 1161 break; 1162 1163 // CHECK: Are we using "%n"? Issue a warning. 1164 case 'n': { 1165 ++numConversions; 1166 CurrentState = state_OrdChr; 1167 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, 1168 LastConversionIdx); 1169 1170 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange(); 1171 break; 1172 } 1173 1174 // Handle "%@" 1175 case '@': 1176 // %@ is allowed in ObjC format strings only. 1177 if (ObjCFExpr != NULL) 1178 CurrentState = state_OrdChr; 1179 else { 1180 // Issue a warning: invalid format conversion. 1181 SourceLocation Loc = 1182 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1183 1184 Diag(Loc, diag::warn_printf_invalid_conversion) 1185 << std::string(Str+LastConversionIdx, 1186 Str+std::min(LastConversionIdx+2, StrLen)) 1187 << OrigFormatExpr->getSourceRange(); 1188 } 1189 ++numConversions; 1190 break; 1191 1192 // Handle "%%" 1193 case '%': 1194 // Sanity check: Was the first "%" character the previous one? 1195 // If not, we will assume that we have a malformed format 1196 // conversion, and that the current "%" character is the start 1197 // of a new conversion. 1198 if (StrIdx - LastConversionIdx == 1) 1199 CurrentState = state_OrdChr; 1200 else { 1201 // Issue a warning: invalid format conversion. 1202 SourceLocation Loc = 1203 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1204 1205 Diag(Loc, diag::warn_printf_invalid_conversion) 1206 << std::string(Str+LastConversionIdx, Str+StrIdx) 1207 << OrigFormatExpr->getSourceRange(); 1208 1209 // This conversion is broken. Advance to the next format 1210 // conversion. 1211 LastConversionIdx = StrIdx; 1212 ++numConversions; 1213 } 1214 break; 1215 1216 default: 1217 // This case catches all other characters: flags, widths, etc. 1218 // We should eventually process those as well. 1219 break; 1220 } 1221 } 1222 1223 if (CurrentState == state_Conversion) { 1224 // Issue a warning: invalid format conversion. 1225 SourceLocation Loc = 1226 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1227 1228 Diag(Loc, diag::warn_printf_invalid_conversion) 1229 << std::string(Str+LastConversionIdx, 1230 Str+std::min(LastConversionIdx+2, StrLen)) 1231 << OrigFormatExpr->getSourceRange(); 1232 return; 1233 } 1234 1235 if (!HasVAListArg) { 1236 // CHECK: Does the number of format conversions exceed the number 1237 // of data arguments? 1238 if (numConversions > numDataArgs) { 1239 SourceLocation Loc = 1240 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1241 1242 Diag(Loc, diag::warn_printf_insufficient_data_args) 1243 << OrigFormatExpr->getSourceRange(); 1244 } 1245 // CHECK: Does the number of data arguments exceed the number of 1246 // format conversions in the format string? 1247 else if (numConversions < numDataArgs) 1248 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(), 1249 diag::warn_printf_too_many_data_args) 1250 << OrigFormatExpr->getSourceRange(); 1251 } 1252} 1253 1254//===--- CHECK: Return Address of Stack Variable --------------------------===// 1255 1256static DeclRefExpr* EvalVal(Expr *E); 1257static DeclRefExpr* EvalAddr(Expr* E); 1258 1259/// CheckReturnStackAddr - Check if a return statement returns the address 1260/// of a stack variable. 1261void 1262Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1263 SourceLocation ReturnLoc) { 1264 1265 // Perform checking for returned stack addresses. 1266 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1267 if (DeclRefExpr *DR = EvalAddr(RetValExp)) 1268 Diag(DR->getLocStart(), diag::warn_ret_stack_addr) 1269 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1270 1271 // Skip over implicit cast expressions when checking for block expressions. 1272 RetValExp = RetValExp->IgnoreParenCasts(); 1273 1274 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp)) 1275 if (C->hasBlockDeclRefExprs()) 1276 Diag(C->getLocStart(), diag::err_ret_local_block) 1277 << C->getSourceRange(); 1278 1279 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp)) 1280 Diag(ALE->getLocStart(), diag::warn_ret_addr_label) 1281 << ALE->getSourceRange(); 1282 1283 } else if (lhsType->isReferenceType()) { 1284 // Perform checking for stack values returned by reference. 1285 // Check for a reference to the stack 1286 if (DeclRefExpr *DR = EvalVal(RetValExp)) 1287 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 1288 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1289 } 1290} 1291 1292/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1293/// check if the expression in a return statement evaluates to an address 1294/// to a location on the stack. The recursion is used to traverse the 1295/// AST of the return expression, with recursion backtracking when we 1296/// encounter a subexpression that (1) clearly does not lead to the address 1297/// of a stack variable or (2) is something we cannot determine leads to 1298/// the address of a stack variable based on such local checking. 1299/// 1300/// EvalAddr processes expressions that are pointers that are used as 1301/// references (and not L-values). EvalVal handles all other values. 1302/// At the base case of the recursion is a check for a DeclRefExpr* in 1303/// the refers to a stack variable. 1304/// 1305/// This implementation handles: 1306/// 1307/// * pointer-to-pointer casts 1308/// * implicit conversions from array references to pointers 1309/// * taking the address of fields 1310/// * arbitrary interplay between "&" and "*" operators 1311/// * pointer arithmetic from an address of a stack variable 1312/// * taking the address of an array element where the array is on the stack 1313static DeclRefExpr* EvalAddr(Expr *E) { 1314 // We should only be called for evaluating pointer expressions. 1315 assert((E->getType()->isAnyPointerType() || 1316 E->getType()->isBlockPointerType() || 1317 E->getType()->isObjCQualifiedIdType()) && 1318 "EvalAddr only works on pointers"); 1319 1320 // Our "symbolic interpreter" is just a dispatch off the currently 1321 // viewed AST node. We then recursively traverse the AST by calling 1322 // EvalAddr and EvalVal appropriately. 1323 switch (E->getStmtClass()) { 1324 case Stmt::ParenExprClass: 1325 // Ignore parentheses. 1326 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 1327 1328 case Stmt::UnaryOperatorClass: { 1329 // The only unary operator that make sense to handle here 1330 // is AddrOf. All others don't make sense as pointers. 1331 UnaryOperator *U = cast<UnaryOperator>(E); 1332 1333 if (U->getOpcode() == UnaryOperator::AddrOf) 1334 return EvalVal(U->getSubExpr()); 1335 else 1336 return NULL; 1337 } 1338 1339 case Stmt::BinaryOperatorClass: { 1340 // Handle pointer arithmetic. All other binary operators are not valid 1341 // in this context. 1342 BinaryOperator *B = cast<BinaryOperator>(E); 1343 BinaryOperator::Opcode op = B->getOpcode(); 1344 1345 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 1346 return NULL; 1347 1348 Expr *Base = B->getLHS(); 1349 1350 // Determine which argument is the real pointer base. It could be 1351 // the RHS argument instead of the LHS. 1352 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1353 1354 assert (Base->getType()->isPointerType()); 1355 return EvalAddr(Base); 1356 } 1357 1358 // For conditional operators we need to see if either the LHS or RHS are 1359 // valid DeclRefExpr*s. If one of them is valid, we return it. 1360 case Stmt::ConditionalOperatorClass: { 1361 ConditionalOperator *C = cast<ConditionalOperator>(E); 1362 1363 // Handle the GNU extension for missing LHS. 1364 if (Expr *lhsExpr = C->getLHS()) 1365 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 1366 return LHS; 1367 1368 return EvalAddr(C->getRHS()); 1369 } 1370 1371 // For casts, we need to handle conversions from arrays to 1372 // pointer values, and pointer-to-pointer conversions. 1373 case Stmt::ImplicitCastExprClass: 1374 case Stmt::CStyleCastExprClass: 1375 case Stmt::CXXFunctionalCastExprClass: { 1376 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1377 QualType T = SubExpr->getType(); 1378 1379 if (SubExpr->getType()->isPointerType() || 1380 SubExpr->getType()->isBlockPointerType() || 1381 SubExpr->getType()->isObjCQualifiedIdType()) 1382 return EvalAddr(SubExpr); 1383 else if (T->isArrayType()) 1384 return EvalVal(SubExpr); 1385 else 1386 return 0; 1387 } 1388 1389 // C++ casts. For dynamic casts, static casts, and const casts, we 1390 // are always converting from a pointer-to-pointer, so we just blow 1391 // through the cast. In the case the dynamic cast doesn't fail (and 1392 // return NULL), we take the conservative route and report cases 1393 // where we return the address of a stack variable. For Reinterpre 1394 // FIXME: The comment about is wrong; we're not always converting 1395 // from pointer to pointer. I'm guessing that this code should also 1396 // handle references to objects. 1397 case Stmt::CXXStaticCastExprClass: 1398 case Stmt::CXXDynamicCastExprClass: 1399 case Stmt::CXXConstCastExprClass: 1400 case Stmt::CXXReinterpretCastExprClass: { 1401 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 1402 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 1403 return EvalAddr(S); 1404 else 1405 return NULL; 1406 } 1407 1408 // Everything else: we simply don't reason about them. 1409 default: 1410 return NULL; 1411 } 1412} 1413 1414 1415/// EvalVal - This function is complements EvalAddr in the mutual recursion. 1416/// See the comments for EvalAddr for more details. 1417static DeclRefExpr* EvalVal(Expr *E) { 1418 1419 // We should only be called for evaluating non-pointer expressions, or 1420 // expressions with a pointer type that are not used as references but instead 1421 // are l-values (e.g., DeclRefExpr with a pointer type). 1422 1423 // Our "symbolic interpreter" is just a dispatch off the currently 1424 // viewed AST node. We then recursively traverse the AST by calling 1425 // EvalAddr and EvalVal appropriately. 1426 switch (E->getStmtClass()) { 1427 case Stmt::DeclRefExprClass: { 1428 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 1429 // at code that refers to a variable's name. We check if it has local 1430 // storage within the function, and if so, return the expression. 1431 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1432 1433 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1434 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 1435 1436 return NULL; 1437 } 1438 1439 case Stmt::ParenExprClass: 1440 // Ignore parentheses. 1441 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 1442 1443 case Stmt::UnaryOperatorClass: { 1444 // The only unary operator that make sense to handle here 1445 // is Deref. All others don't resolve to a "name." This includes 1446 // handling all sorts of rvalues passed to a unary operator. 1447 UnaryOperator *U = cast<UnaryOperator>(E); 1448 1449 if (U->getOpcode() == UnaryOperator::Deref) 1450 return EvalAddr(U->getSubExpr()); 1451 1452 return NULL; 1453 } 1454 1455 case Stmt::ArraySubscriptExprClass: { 1456 // Array subscripts are potential references to data on the stack. We 1457 // retrieve the DeclRefExpr* for the array variable if it indeed 1458 // has local storage. 1459 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 1460 } 1461 1462 case Stmt::ConditionalOperatorClass: { 1463 // For conditional operators we need to see if either the LHS or RHS are 1464 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 1465 ConditionalOperator *C = cast<ConditionalOperator>(E); 1466 1467 // Handle the GNU extension for missing LHS. 1468 if (Expr *lhsExpr = C->getLHS()) 1469 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 1470 return LHS; 1471 1472 return EvalVal(C->getRHS()); 1473 } 1474 1475 // Accesses to members are potential references to data on the stack. 1476 case Stmt::MemberExprClass: { 1477 MemberExpr *M = cast<MemberExpr>(E); 1478 1479 // Check for indirect access. We only want direct field accesses. 1480 if (!M->isArrow()) 1481 return EvalVal(M->getBase()); 1482 else 1483 return NULL; 1484 } 1485 1486 // Everything else: we simply don't reason about them. 1487 default: 1488 return NULL; 1489 } 1490} 1491 1492//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1493 1494/// Check for comparisons of floating point operands using != and ==. 1495/// Issue a warning if these are no self-comparisons, as they are not likely 1496/// to do what the programmer intended. 1497void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1498 bool EmitWarning = true; 1499 1500 Expr* LeftExprSansParen = lex->IgnoreParens(); 1501 Expr* RightExprSansParen = rex->IgnoreParens(); 1502 1503 // Special case: check for x == x (which is OK). 1504 // Do not emit warnings for such cases. 1505 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1506 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1507 if (DRL->getDecl() == DRR->getDecl()) 1508 EmitWarning = false; 1509 1510 1511 // Special case: check for comparisons against literals that can be exactly 1512 // represented by APFloat. In such cases, do not emit a warning. This 1513 // is a heuristic: often comparison against such literals are used to 1514 // detect if a value in a variable has not changed. This clearly can 1515 // lead to false negatives. 1516 if (EmitWarning) { 1517 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1518 if (FLL->isExact()) 1519 EmitWarning = false; 1520 } else 1521 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1522 if (FLR->isExact()) 1523 EmitWarning = false; 1524 } 1525 } 1526 1527 // Check for comparisons with builtin types. 1528 if (EmitWarning) 1529 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1530 if (CL->isBuiltinCall(Context)) 1531 EmitWarning = false; 1532 1533 if (EmitWarning) 1534 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1535 if (CR->isBuiltinCall(Context)) 1536 EmitWarning = false; 1537 1538 // Emit the diagnostic. 1539 if (EmitWarning) 1540 Diag(loc, diag::warn_floatingpoint_eq) 1541 << lex->getSourceRange() << rex->getSourceRange(); 1542} 1543