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