SemaChecking.cpp revision 21fb98ee003e992b0c4e204d98a19e0ef544cae3
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements extra semantic analysis beyond what is enforced 11// by the C type system. 12// 13//===----------------------------------------------------------------------===// 14 15#include "Sema.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/Lex/LiteralSupport.h" 21#include "clang/Lex/Preprocessor.h" 22#include <limits> 23using namespace clang; 24 25/// getLocationOfStringLiteralByte - Return a source location that points to the 26/// specified byte of the specified string literal. 27/// 28/// Strings are amazingly complex. They can be formed from multiple tokens and 29/// can have escape sequences in them in addition to the usual trigraph and 30/// escaped newline business. This routine handles this complexity. 31/// 32SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 33 unsigned ByteNo) const { 34 assert(!SL->isWide() && "This doesn't work for wide strings yet"); 35 36 // Loop over all of the tokens in this string until we find the one that 37 // contains the byte we're looking for. 38 unsigned TokNo = 0; 39 while (1) { 40 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!"); 41 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo); 42 43 // Get the spelling of the string so that we can get the data that makes up 44 // the string literal, not the identifier for the macro it is potentially 45 // expanded through. 46 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc); 47 48 // Re-lex the token to get its length and original spelling. 49 std::pair<FileID, unsigned> LocInfo = 50 SourceMgr.getDecomposedLoc(StrTokSpellingLoc); 51 std::pair<const char *,const char *> Buffer = 52 SourceMgr.getBufferData(LocInfo.first); 53 const char *StrData = Buffer.first+LocInfo.second; 54 55 // Create a langops struct and enable trigraphs. This is sufficient for 56 // relexing tokens. 57 LangOptions LangOpts; 58 LangOpts.Trigraphs = true; 59 60 // Create a lexer starting at the beginning of this token. 61 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData, 62 Buffer.second); 63 Token TheTok; 64 TheLexer.LexFromRawLexer(TheTok); 65 66 // Use the StringLiteralParser to compute the length of the string in bytes. 67 StringLiteralParser SLP(&TheTok, 1, PP); 68 unsigned TokNumBytes = SLP.GetStringLength(); 69 70 // If the byte is in this token, return the location of the byte. 71 if (ByteNo < TokNumBytes || 72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) { 73 unsigned Offset = 74 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP); 75 76 // Now that we know the offset of the token in the spelling, use the 77 // preprocessor to get the offset in the original source. 78 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset); 79 } 80 81 // Move to the next string token. 82 ++TokNo; 83 ByteNo -= TokNumBytes; 84 } 85} 86 87/// CheckablePrintfAttr - does a function call have a "printf" attribute 88/// and arguments that merit checking? 89bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 90 if (Format->getType() == "printf") return true; 91 if (Format->getType() == "printf0") { 92 // printf0 allows null "format" string; if so don't check format/args 93 unsigned format_idx = Format->getFormatIdx() - 1; 94 if (format_idx < TheCall->getNumArgs()) { 95 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 96 if (!Format->isNullPointerConstant(Context)) 97 return true; 98 } 99 } 100 return false; 101} 102 103Action::OwningExprResult 104Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 105 OwningExprResult TheCallResult(Owned(TheCall)); 106 107 switch (BuiltinID) { 108 case Builtin::BI__builtin___CFStringMakeConstantString: 109 assert(TheCall->getNumArgs() == 1 && 110 "Wrong # arguments to builtin CFStringMakeConstantString"); 111 if (CheckObjCString(TheCall->getArg(0))) 112 return ExprError(); 113 break; 114 case Builtin::BI__builtin_stdarg_start: 115 case Builtin::BI__builtin_va_start: 116 if (SemaBuiltinVAStart(TheCall)) 117 return ExprError(); 118 break; 119 case Builtin::BI__builtin_isgreater: 120 case Builtin::BI__builtin_isgreaterequal: 121 case Builtin::BI__builtin_isless: 122 case Builtin::BI__builtin_islessequal: 123 case Builtin::BI__builtin_islessgreater: 124 case Builtin::BI__builtin_isunordered: 125 if (SemaBuiltinUnorderedCompare(TheCall)) 126 return ExprError(); 127 break; 128 case Builtin::BI__builtin_isfinite: 129 case Builtin::BI__builtin_isinf: 130 case Builtin::BI__builtin_isinf_sign: 131 case Builtin::BI__builtin_isnan: 132 case Builtin::BI__builtin_isnormal: 133 if (SemaBuiltinUnaryFP(TheCall)) 134 return ExprError(); 135 break; 136 case Builtin::BI__builtin_return_address: 137 case Builtin::BI__builtin_frame_address: 138 if (SemaBuiltinStackAddress(TheCall)) 139 return ExprError(); 140 break; 141 case Builtin::BI__builtin_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_Unknown, 385 /*isLvalue=*/false); 386 TheCall->setArg(0, FirstArg); 387 } 388 389 // Next, walk the valid ones promoting to the right type. 390 for (unsigned i = 0; i != NumFixed; ++i) { 391 Expr *Arg = TheCall->getArg(i+1); 392 393 // If the argument is an implicit cast, then there was a promotion due to 394 // "...", just remove it now. 395 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 396 Arg = ICE->getSubExpr(); 397 ICE->setSubExpr(0); 398 ICE->Destroy(Context); 399 TheCall->setArg(i+1, Arg); 400 } 401 402 // GCC does an implicit conversion to the pointer or integer ValType. This 403 // can fail in some cases (1i -> int**), check for this error case now. 404 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 405 CXXMethodDecl *ConversionDecl = 0; 406 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, 407 ConversionDecl)) 408 return true; 409 410 // Okay, we have something that *can* be converted to the right type. Check 411 // to see if there is a potentially weird extension going on here. This can 412 // happen when you do an atomic operation on something like an char* and 413 // pass in 42. The 42 gets converted to char. This is even more strange 414 // for things like 45.123 -> char, etc. 415 // FIXME: Do this check. 416 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false); 417 TheCall->setArg(i+1, Arg); 418 } 419 420 // Switch the DeclRefExpr to refer to the new decl. 421 DRE->setDecl(NewBuiltinDecl); 422 DRE->setType(NewBuiltinDecl->getType()); 423 424 // Set the callee in the CallExpr. 425 // FIXME: This leaks the original parens and implicit casts. 426 Expr *PromotedCall = DRE; 427 UsualUnaryConversions(PromotedCall); 428 TheCall->setCallee(PromotedCall); 429 430 431 // Change the result type of the call to match the result type of the decl. 432 TheCall->setType(NewBuiltinDecl->getResultType()); 433 return false; 434} 435 436 437/// CheckObjCString - Checks that the argument to the builtin 438/// CFString constructor is correct 439/// FIXME: GCC currently emits the following warning: 440/// "warning: input conversion stopped due to an input byte that does not 441/// belong to the input codeset UTF-8" 442/// Note: It might also make sense to do the UTF-16 conversion here (would 443/// simplify the backend). 444bool Sema::CheckObjCString(Expr *Arg) { 445 Arg = Arg->IgnoreParenCasts(); 446 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 447 448 if (!Literal || Literal->isWide()) { 449 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 450 << Arg->getSourceRange(); 451 return true; 452 } 453 454 const char *Data = Literal->getStrData(); 455 unsigned Length = Literal->getByteLength(); 456 457 for (unsigned i = 0; i < Length; ++i) { 458 if (!Data[i]) { 459 Diag(getLocationOfStringLiteralByte(Literal, i), 460 diag::warn_cfstring_literal_contains_nul_character) 461 << Arg->getSourceRange(); 462 break; 463 } 464 } 465 466 return false; 467} 468 469/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 470/// Emit an error and return true on failure, return false on success. 471bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 472 Expr *Fn = TheCall->getCallee(); 473 if (TheCall->getNumArgs() > 2) { 474 Diag(TheCall->getArg(2)->getLocStart(), 475 diag::err_typecheck_call_too_many_args) 476 << 0 /*function call*/ << Fn->getSourceRange() 477 << SourceRange(TheCall->getArg(2)->getLocStart(), 478 (*(TheCall->arg_end()-1))->getLocEnd()); 479 return true; 480 } 481 482 if (TheCall->getNumArgs() < 2) { 483 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 484 << 0 /*function call*/; 485 } 486 487 // Determine whether the current function is variadic or not. 488 bool isVariadic; 489 if (CurBlock) 490 isVariadic = CurBlock->isVariadic; 491 else if (getCurFunctionDecl()) { 492 if (FunctionProtoType* FTP = 493 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType())) 494 isVariadic = FTP->isVariadic(); 495 else 496 isVariadic = false; 497 } else { 498 isVariadic = getCurMethodDecl()->isVariadic(); 499 } 500 501 if (!isVariadic) { 502 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 503 return true; 504 } 505 506 // Verify that the second argument to the builtin is the last argument of the 507 // current function or method. 508 bool SecondArgIsLastNamedArgument = false; 509 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 510 511 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 512 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 513 // FIXME: This isn't correct for methods (results in bogus warning). 514 // Get the last formal in the current function. 515 const ParmVarDecl *LastArg; 516 if (CurBlock) 517 LastArg = *(CurBlock->TheDecl->param_end()-1); 518 else if (FunctionDecl *FD = getCurFunctionDecl()) 519 LastArg = *(FD->param_end()-1); 520 else 521 LastArg = *(getCurMethodDecl()->param_end()-1); 522 SecondArgIsLastNamedArgument = PV == LastArg; 523 } 524 } 525 526 if (!SecondArgIsLastNamedArgument) 527 Diag(TheCall->getArg(1)->getLocStart(), 528 diag::warn_second_parameter_of_va_start_not_last_named_argument); 529 return false; 530} 531 532/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 533/// friends. This is declared to take (...), so we have to check everything. 534bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 535 if (TheCall->getNumArgs() < 2) 536 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 537 << 0 /*function call*/; 538 if (TheCall->getNumArgs() > 2) 539 return Diag(TheCall->getArg(2)->getLocStart(), 540 diag::err_typecheck_call_too_many_args) 541 << 0 /*function call*/ 542 << SourceRange(TheCall->getArg(2)->getLocStart(), 543 (*(TheCall->arg_end()-1))->getLocEnd()); 544 545 Expr *OrigArg0 = TheCall->getArg(0); 546 Expr *OrigArg1 = TheCall->getArg(1); 547 548 // Do standard promotions between the two arguments, returning their common 549 // type. 550 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 551 552 // Make sure any conversions are pushed back into the call; this is 553 // type safe since unordered compare builtins are declared as "_Bool 554 // foo(...)". 555 TheCall->setArg(0, OrigArg0); 556 TheCall->setArg(1, OrigArg1); 557 558 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent()) 559 return false; 560 561 // If the common type isn't a real floating type, then the arguments were 562 // invalid for this operation. 563 if (!Res->isRealFloatingType()) 564 return Diag(OrigArg0->getLocStart(), 565 diag::err_typecheck_call_invalid_ordered_compare) 566 << OrigArg0->getType() << OrigArg1->getType() 567 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 568 569 return false; 570} 571 572/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and 573/// friends. This is declared to take (...), so we have to check everything. 574bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) { 575 if (TheCall->getNumArgs() < 1) 576 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 577 << 0 /*function call*/; 578 if (TheCall->getNumArgs() > 1) 579 return Diag(TheCall->getArg(1)->getLocStart(), 580 diag::err_typecheck_call_too_many_args) 581 << 0 /*function call*/ 582 << SourceRange(TheCall->getArg(1)->getLocStart(), 583 (*(TheCall->arg_end()-1))->getLocEnd()); 584 585 Expr *OrigArg = TheCall->getArg(0); 586 587 if (OrigArg->isTypeDependent()) 588 return false; 589 590 // This operation requires a floating-point number 591 if (!OrigArg->getType()->isRealFloatingType()) 592 return Diag(OrigArg->getLocStart(), 593 diag::err_typecheck_call_invalid_unary_fp) 594 << OrigArg->getType() << OrigArg->getSourceRange(); 595 596 return false; 597} 598 599bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { 600 // The signature for these builtins is exact; the only thing we need 601 // to check is that the argument is a constant. 602 SourceLocation Loc; 603 if (!TheCall->getArg(0)->isTypeDependent() && 604 !TheCall->getArg(0)->isValueDependent() && 605 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) 606 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); 607 608 return false; 609} 610 611/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 612// This is declared to take (...), so we have to check everything. 613Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 614 if (TheCall->getNumArgs() < 3) 615 return ExprError(Diag(TheCall->getLocEnd(), 616 diag::err_typecheck_call_too_few_args) 617 << 0 /*function call*/ << TheCall->getSourceRange()); 618 619 unsigned numElements = std::numeric_limits<unsigned>::max(); 620 if (!TheCall->getArg(0)->isTypeDependent() && 621 !TheCall->getArg(1)->isTypeDependent()) { 622 QualType FAType = TheCall->getArg(0)->getType(); 623 QualType SAType = TheCall->getArg(1)->getType(); 624 625 if (!FAType->isVectorType() || !SAType->isVectorType()) { 626 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 627 << SourceRange(TheCall->getArg(0)->getLocStart(), 628 TheCall->getArg(1)->getLocEnd()); 629 return ExprError(); 630 } 631 632 if (Context.getCanonicalType(FAType).getUnqualifiedType() != 633 Context.getCanonicalType(SAType).getUnqualifiedType()) { 634 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 635 << SourceRange(TheCall->getArg(0)->getLocStart(), 636 TheCall->getArg(1)->getLocEnd()); 637 return ExprError(); 638 } 639 640 numElements = FAType->getAs<VectorType>()->getNumElements(); 641 if (TheCall->getNumArgs() != numElements+2) { 642 if (TheCall->getNumArgs() < numElements+2) 643 return ExprError(Diag(TheCall->getLocEnd(), 644 diag::err_typecheck_call_too_few_args) 645 << 0 /*function call*/ << TheCall->getSourceRange()); 646 return ExprError(Diag(TheCall->getLocEnd(), 647 diag::err_typecheck_call_too_many_args) 648 << 0 /*function call*/ << TheCall->getSourceRange()); 649 } 650 } 651 652 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 653 if (TheCall->getArg(i)->isTypeDependent() || 654 TheCall->getArg(i)->isValueDependent()) 655 continue; 656 657 llvm::APSInt Result(32); 658 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 659 return ExprError(Diag(TheCall->getLocStart(), 660 diag::err_shufflevector_nonconstant_argument) 661 << TheCall->getArg(i)->getSourceRange()); 662 663 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 664 return ExprError(Diag(TheCall->getLocStart(), 665 diag::err_shufflevector_argument_too_large) 666 << TheCall->getArg(i)->getSourceRange()); 667 } 668 669 llvm::SmallVector<Expr*, 32> exprs; 670 671 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 672 exprs.push_back(TheCall->getArg(i)); 673 TheCall->setArg(i, 0); 674 } 675 676 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 677 exprs.size(), exprs[0]->getType(), 678 TheCall->getCallee()->getLocStart(), 679 TheCall->getRParenLoc())); 680} 681 682/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 683// This is declared to take (const void*, ...) and can take two 684// optional constant int args. 685bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 686 unsigned NumArgs = TheCall->getNumArgs(); 687 688 if (NumArgs > 3) 689 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 690 << 0 /*function call*/ << TheCall->getSourceRange(); 691 692 // Argument 0 is checked for us and the remaining arguments must be 693 // constant integers. 694 for (unsigned i = 1; i != NumArgs; ++i) { 695 Expr *Arg = TheCall->getArg(i); 696 if (Arg->isTypeDependent()) 697 continue; 698 699 QualType RWType = Arg->getType(); 700 701 const BuiltinType *BT = RWType->getAs<BuiltinType>(); 702 llvm::APSInt Result; 703 if (!BT || BT->getKind() != BuiltinType::Int) 704 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 705 << Arg->getSourceRange(); 706 707 if (Arg->isValueDependent()) 708 continue; 709 710 if (!Arg->isIntegerConstantExpr(Result, Context)) 711 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 712 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 713 714 // FIXME: gcc issues a warning and rewrites these to 0. These 715 // seems especially odd for the third argument since the default 716 // is 3. 717 if (i == 1) { 718 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1) 719 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 720 << "0" << "1" << Arg->getSourceRange(); 721 } else { 722 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) 723 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 724 << "0" << "3" << Arg->getSourceRange(); 725 } 726 } 727 728 return false; 729} 730 731/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the 732/// operand must be an integer constant. 733bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) { 734 llvm::APSInt Result; 735 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context)) 736 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice) 737 << TheCall->getArg(0)->getSourceRange(); 738 739 return false; 740} 741 742 743/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 744/// int type). This simply type checks that type is one of the defined 745/// constants (0-3). 746bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 747 Expr *Arg = TheCall->getArg(1); 748 if (Arg->isTypeDependent()) 749 return false; 750 751 QualType ArgType = Arg->getType(); 752 const BuiltinType *BT = ArgType->getAs<BuiltinType>(); 753 llvm::APSInt Result(32); 754 if (!BT || BT->getKind() != BuiltinType::Int) 755 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 756 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 757 758 if (Arg->isValueDependent()) 759 return false; 760 761 if (!Arg->isIntegerConstantExpr(Result, Context)) { 762 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 763 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 764 } 765 766 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 767 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 768 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 769 } 770 771 return false; 772} 773 774/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 775/// This checks that val is a constant 1. 776bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 777 Expr *Arg = TheCall->getArg(1); 778 if (Arg->isTypeDependent() || Arg->isValueDependent()) 779 return false; 780 781 llvm::APSInt Result(32); 782 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1) 783 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 784 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 785 786 return false; 787} 788 789// Handle i > 1 ? "x" : "y", recursivelly 790bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 791 bool HasVAListArg, 792 unsigned format_idx, unsigned firstDataArg) { 793 if (E->isTypeDependent() || E->isValueDependent()) 794 return false; 795 796 switch (E->getStmtClass()) { 797 case Stmt::ConditionalOperatorClass: { 798 const ConditionalOperator *C = cast<ConditionalOperator>(E); 799 return SemaCheckStringLiteral(C->getLHS(), TheCall, 800 HasVAListArg, format_idx, firstDataArg) 801 && SemaCheckStringLiteral(C->getRHS(), TheCall, 802 HasVAListArg, format_idx, firstDataArg); 803 } 804 805 case Stmt::ImplicitCastExprClass: { 806 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); 807 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 808 format_idx, firstDataArg); 809 } 810 811 case Stmt::ParenExprClass: { 812 const ParenExpr *Expr = cast<ParenExpr>(E); 813 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 814 format_idx, firstDataArg); 815 } 816 817 case Stmt::DeclRefExprClass: { 818 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 819 820 // As an exception, do not flag errors for variables binding to 821 // const string literals. 822 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 823 bool isConstant = false; 824 QualType T = DR->getType(); 825 826 if (const ArrayType *AT = Context.getAsArrayType(T)) { 827 isConstant = AT->getElementType().isConstant(Context); 828 } else if (const PointerType *PT = T->getAs<PointerType>()) { 829 isConstant = T.isConstant(Context) && 830 PT->getPointeeType().isConstant(Context); 831 } 832 833 if (isConstant) { 834 const VarDecl *Def = 0; 835 if (const Expr *Init = VD->getDefinition(Def)) 836 return SemaCheckStringLiteral(Init, TheCall, 837 HasVAListArg, format_idx, firstDataArg); 838 } 839 840 // For vprintf* functions (i.e., HasVAListArg==true), we add a 841 // special check to see if the format string is a function parameter 842 // of the function calling the printf function. If the function 843 // has an attribute indicating it is a printf-like function, then we 844 // should suppress warnings concerning non-literals being used in a call 845 // to a vprintf function. For example: 846 // 847 // void 848 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 849 // va_list ap; 850 // va_start(ap, fmt); 851 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 852 // ... 853 // 854 // 855 // FIXME: We don't have full attribute support yet, so just check to see 856 // if the argument is a DeclRefExpr that references a parameter. We'll 857 // add proper support for checking the attribute later. 858 if (HasVAListArg) 859 if (isa<ParmVarDecl>(VD)) 860 return true; 861 } 862 863 return false; 864 } 865 866 case Stmt::CallExprClass: { 867 const CallExpr *CE = cast<CallExpr>(E); 868 if (const ImplicitCastExpr *ICE 869 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 870 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 871 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 872 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 873 unsigned ArgIndex = FA->getFormatIdx(); 874 const Expr *Arg = CE->getArg(ArgIndex - 1); 875 876 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 877 format_idx, firstDataArg); 878 } 879 } 880 } 881 } 882 883 return false; 884 } 885 case Stmt::ObjCStringLiteralClass: 886 case Stmt::StringLiteralClass: { 887 const StringLiteral *StrE = NULL; 888 889 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 890 StrE = ObjCFExpr->getString(); 891 else 892 StrE = cast<StringLiteral>(E); 893 894 if (StrE) { 895 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, 896 firstDataArg); 897 return true; 898 } 899 900 return false; 901 } 902 903 default: 904 return false; 905 } 906} 907 908void 909Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 910 const CallExpr *TheCall) { 911 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end(); 912 i != e; ++i) { 913 const Expr *ArgExpr = TheCall->getArg(*i); 914 if (ArgExpr->isNullPointerConstant(Context)) 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_or_null<BlockExpr>(RetValExp)) 1276 if (C->hasBlockDeclRefExprs()) 1277 Diag(C->getLocStart(), diag::err_ret_local_block) 1278 << C->getSourceRange(); 1279 } else if (lhsType->isReferenceType()) { 1280 // Perform checking for stack values returned by reference. 1281 // Check for a reference to the stack 1282 if (DeclRefExpr *DR = EvalVal(RetValExp)) 1283 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 1284 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1285 } 1286} 1287 1288/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1289/// check if the expression in a return statement evaluates to an address 1290/// to a location on the stack. The recursion is used to traverse the 1291/// AST of the return expression, with recursion backtracking when we 1292/// encounter a subexpression that (1) clearly does not lead to the address 1293/// of a stack variable or (2) is something we cannot determine leads to 1294/// the address of a stack variable based on such local checking. 1295/// 1296/// EvalAddr processes expressions that are pointers that are used as 1297/// references (and not L-values). EvalVal handles all other values. 1298/// At the base case of the recursion is a check for a DeclRefExpr* in 1299/// the refers to a stack variable. 1300/// 1301/// This implementation handles: 1302/// 1303/// * pointer-to-pointer casts 1304/// * implicit conversions from array references to pointers 1305/// * taking the address of fields 1306/// * arbitrary interplay between "&" and "*" operators 1307/// * pointer arithmetic from an address of a stack variable 1308/// * taking the address of an array element where the array is on the stack 1309static DeclRefExpr* EvalAddr(Expr *E) { 1310 // We should only be called for evaluating pointer expressions. 1311 assert((E->getType()->isAnyPointerType() || 1312 E->getType()->isBlockPointerType() || 1313 E->getType()->isObjCQualifiedIdType()) && 1314 "EvalAddr only works on pointers"); 1315 1316 // Our "symbolic interpreter" is just a dispatch off the currently 1317 // viewed AST node. We then recursively traverse the AST by calling 1318 // EvalAddr and EvalVal appropriately. 1319 switch (E->getStmtClass()) { 1320 case Stmt::ParenExprClass: 1321 // Ignore parentheses. 1322 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 1323 1324 case Stmt::UnaryOperatorClass: { 1325 // The only unary operator that make sense to handle here 1326 // is AddrOf. All others don't make sense as pointers. 1327 UnaryOperator *U = cast<UnaryOperator>(E); 1328 1329 if (U->getOpcode() == UnaryOperator::AddrOf) 1330 return EvalVal(U->getSubExpr()); 1331 else 1332 return NULL; 1333 } 1334 1335 case Stmt::BinaryOperatorClass: { 1336 // Handle pointer arithmetic. All other binary operators are not valid 1337 // in this context. 1338 BinaryOperator *B = cast<BinaryOperator>(E); 1339 BinaryOperator::Opcode op = B->getOpcode(); 1340 1341 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 1342 return NULL; 1343 1344 Expr *Base = B->getLHS(); 1345 1346 // Determine which argument is the real pointer base. It could be 1347 // the RHS argument instead of the LHS. 1348 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1349 1350 assert (Base->getType()->isPointerType()); 1351 return EvalAddr(Base); 1352 } 1353 1354 // For conditional operators we need to see if either the LHS or RHS are 1355 // valid DeclRefExpr*s. If one of them is valid, we return it. 1356 case Stmt::ConditionalOperatorClass: { 1357 ConditionalOperator *C = cast<ConditionalOperator>(E); 1358 1359 // Handle the GNU extension for missing LHS. 1360 if (Expr *lhsExpr = C->getLHS()) 1361 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 1362 return LHS; 1363 1364 return EvalAddr(C->getRHS()); 1365 } 1366 1367 // For casts, we need to handle conversions from arrays to 1368 // pointer values, and pointer-to-pointer conversions. 1369 case Stmt::ImplicitCastExprClass: 1370 case Stmt::CStyleCastExprClass: 1371 case Stmt::CXXFunctionalCastExprClass: { 1372 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1373 QualType T = SubExpr->getType(); 1374 1375 if (SubExpr->getType()->isPointerType() || 1376 SubExpr->getType()->isBlockPointerType() || 1377 SubExpr->getType()->isObjCQualifiedIdType()) 1378 return EvalAddr(SubExpr); 1379 else if (T->isArrayType()) 1380 return EvalVal(SubExpr); 1381 else 1382 return 0; 1383 } 1384 1385 // C++ casts. For dynamic casts, static casts, and const casts, we 1386 // are always converting from a pointer-to-pointer, so we just blow 1387 // through the cast. In the case the dynamic cast doesn't fail (and 1388 // return NULL), we take the conservative route and report cases 1389 // where we return the address of a stack variable. For Reinterpre 1390 // FIXME: The comment about is wrong; we're not always converting 1391 // from pointer to pointer. I'm guessing that this code should also 1392 // handle references to objects. 1393 case Stmt::CXXStaticCastExprClass: 1394 case Stmt::CXXDynamicCastExprClass: 1395 case Stmt::CXXConstCastExprClass: 1396 case Stmt::CXXReinterpretCastExprClass: { 1397 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 1398 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 1399 return EvalAddr(S); 1400 else 1401 return NULL; 1402 } 1403 1404 // Everything else: we simply don't reason about them. 1405 default: 1406 return NULL; 1407 } 1408} 1409 1410 1411/// EvalVal - This function is complements EvalAddr in the mutual recursion. 1412/// See the comments for EvalAddr for more details. 1413static DeclRefExpr* EvalVal(Expr *E) { 1414 1415 // We should only be called for evaluating non-pointer expressions, or 1416 // expressions with a pointer type that are not used as references but instead 1417 // are l-values (e.g., DeclRefExpr with a pointer type). 1418 1419 // Our "symbolic interpreter" is just a dispatch off the currently 1420 // viewed AST node. We then recursively traverse the AST by calling 1421 // EvalAddr and EvalVal appropriately. 1422 switch (E->getStmtClass()) { 1423 case Stmt::DeclRefExprClass: 1424 case Stmt::QualifiedDeclRefExprClass: { 1425 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 1426 // at code that refers to a variable's name. We check if it has local 1427 // storage within the function, and if so, return the expression. 1428 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1429 1430 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1431 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 1432 1433 return NULL; 1434 } 1435 1436 case Stmt::ParenExprClass: 1437 // Ignore parentheses. 1438 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 1439 1440 case Stmt::UnaryOperatorClass: { 1441 // The only unary operator that make sense to handle here 1442 // is Deref. All others don't resolve to a "name." This includes 1443 // handling all sorts of rvalues passed to a unary operator. 1444 UnaryOperator *U = cast<UnaryOperator>(E); 1445 1446 if (U->getOpcode() == UnaryOperator::Deref) 1447 return EvalAddr(U->getSubExpr()); 1448 1449 return NULL; 1450 } 1451 1452 case Stmt::ArraySubscriptExprClass: { 1453 // Array subscripts are potential references to data on the stack. We 1454 // retrieve the DeclRefExpr* for the array variable if it indeed 1455 // has local storage. 1456 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 1457 } 1458 1459 case Stmt::ConditionalOperatorClass: { 1460 // For conditional operators we need to see if either the LHS or RHS are 1461 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 1462 ConditionalOperator *C = cast<ConditionalOperator>(E); 1463 1464 // Handle the GNU extension for missing LHS. 1465 if (Expr *lhsExpr = C->getLHS()) 1466 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 1467 return LHS; 1468 1469 return EvalVal(C->getRHS()); 1470 } 1471 1472 // Accesses to members are potential references to data on the stack. 1473 case Stmt::MemberExprClass: { 1474 MemberExpr *M = cast<MemberExpr>(E); 1475 1476 // Check for indirect access. We only want direct field accesses. 1477 if (!M->isArrow()) 1478 return EvalVal(M->getBase()); 1479 else 1480 return NULL; 1481 } 1482 1483 // Everything else: we simply don't reason about them. 1484 default: 1485 return NULL; 1486 } 1487} 1488 1489//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1490 1491/// Check for comparisons of floating point operands using != and ==. 1492/// Issue a warning if these are no self-comparisons, as they are not likely 1493/// to do what the programmer intended. 1494void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1495 bool EmitWarning = true; 1496 1497 Expr* LeftExprSansParen = lex->IgnoreParens(); 1498 Expr* RightExprSansParen = rex->IgnoreParens(); 1499 1500 // Special case: check for x == x (which is OK). 1501 // Do not emit warnings for such cases. 1502 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1503 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1504 if (DRL->getDecl() == DRR->getDecl()) 1505 EmitWarning = false; 1506 1507 1508 // Special case: check for comparisons against literals that can be exactly 1509 // represented by APFloat. In such cases, do not emit a warning. This 1510 // is a heuristic: often comparison against such literals are used to 1511 // detect if a value in a variable has not changed. This clearly can 1512 // lead to false negatives. 1513 if (EmitWarning) { 1514 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1515 if (FLL->isExact()) 1516 EmitWarning = false; 1517 } else 1518 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1519 if (FLR->isExact()) 1520 EmitWarning = false; 1521 } 1522 } 1523 1524 // Check for comparisons with builtin types. 1525 if (EmitWarning) 1526 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1527 if (CL->isBuiltinCall(Context)) 1528 EmitWarning = false; 1529 1530 if (EmitWarning) 1531 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1532 if (CR->isBuiltinCall(Context)) 1533 EmitWarning = false; 1534 1535 // Emit the diagnostic. 1536 if (EmitWarning) 1537 Diag(loc, diag::warn_floatingpoint_eq) 1538 << lex->getSourceRange() << rex->getSourceRange(); 1539} 1540