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