1 //===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=// 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 the JumpScopeChecker class, which is used to diagnose 11 // jumps that enter a protected scope in an invalid way. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Sema/SemaInternal.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/StmtCXX.h" 20 #include "clang/AST/StmtObjC.h" 21 #include "llvm/ADT/BitVector.h" 22 using namespace clang; 23 24 namespace { 25 26 /// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps 27 /// into VLA and other protected scopes. For example, this rejects: 28 /// goto L; 29 /// int a[n]; 30 /// L: 31 /// 32 class JumpScopeChecker { 33 Sema &S; 34 35 /// Permissive - True when recovering from errors, in which case precautions 36 /// are taken to handle incomplete scope information. 37 const bool Permissive; 38 39 /// GotoScope - This is a record that we use to keep track of all of the 40 /// scopes that are introduced by VLAs and other things that scope jumps like 41 /// gotos. This scope tree has nothing to do with the source scope tree, 42 /// because you can have multiple VLA scopes per compound statement, and most 43 /// compound statements don't introduce any scopes. 44 struct GotoScope { 45 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for 46 /// the parent scope is the function body. 47 unsigned ParentScope; 48 49 /// InDiag - The note to emit if there is a jump into this scope. 50 unsigned InDiag; 51 52 /// OutDiag - The note to emit if there is an indirect jump out 53 /// of this scope. Direct jumps always clean up their current scope 54 /// in an orderly way. 55 unsigned OutDiag; 56 57 /// Loc - Location to emit the diagnostic. 58 SourceLocation Loc; 59 60 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag, 61 SourceLocation L) 62 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {} 63 }; 64 65 SmallVector<GotoScope, 48> Scopes; 66 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes; 67 SmallVector<Stmt*, 16> Jumps; 68 69 SmallVector<IndirectGotoStmt*, 4> IndirectJumps; 70 SmallVector<LabelDecl*, 4> IndirectJumpTargets; 71 public: 72 JumpScopeChecker(Stmt *Body, Sema &S); 73 private: 74 void BuildScopeInformation(Decl *D, unsigned &ParentScope); 75 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl, 76 unsigned &ParentScope); 77 void BuildScopeInformation(Stmt *S, unsigned &origParentScope); 78 79 void VerifyJumps(); 80 void VerifyIndirectJumps(); 81 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes); 82 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope, 83 LabelDecl *Target, unsigned TargetScope); 84 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, 85 unsigned JumpDiag, unsigned JumpDiagWarning, 86 unsigned JumpDiagCXX98Compat); 87 void CheckGotoStmt(GotoStmt *GS); 88 89 unsigned GetDeepestCommonScope(unsigned A, unsigned B); 90 }; 91 } // end anonymous namespace 92 93 #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x))) 94 95 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) 96 : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) { 97 // Add a scope entry for function scope. 98 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation())); 99 100 // Build information for the top level compound statement, so that we have a 101 // defined scope record for every "goto" and label. 102 unsigned BodyParentScope = 0; 103 BuildScopeInformation(Body, BodyParentScope); 104 105 // Check that all jumps we saw are kosher. 106 VerifyJumps(); 107 VerifyIndirectJumps(); 108 } 109 110 /// GetDeepestCommonScope - Finds the innermost scope enclosing the 111 /// two scopes. 112 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) { 113 while (A != B) { 114 // Inner scopes are created after outer scopes and therefore have 115 // higher indices. 116 if (A < B) { 117 assert(Scopes[B].ParentScope < B); 118 B = Scopes[B].ParentScope; 119 } else { 120 assert(Scopes[A].ParentScope < A); 121 A = Scopes[A].ParentScope; 122 } 123 } 124 return A; 125 } 126 127 typedef std::pair<unsigned,unsigned> ScopePair; 128 129 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a 130 /// diagnostic that should be emitted if control goes over it. If not, return 0. 131 static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) { 132 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 133 unsigned InDiag = 0; 134 unsigned OutDiag = 0; 135 136 if (VD->getType()->isVariablyModifiedType()) 137 InDiag = diag::note_protected_by_vla; 138 139 if (VD->hasAttr<BlocksAttr>()) 140 return ScopePair(diag::note_protected_by___block, 141 diag::note_exits___block); 142 143 if (VD->hasAttr<CleanupAttr>()) 144 return ScopePair(diag::note_protected_by_cleanup, 145 diag::note_exits_cleanup); 146 147 if (VD->hasLocalStorage()) { 148 switch (VD->getType().isDestructedType()) { 149 case QualType::DK_objc_strong_lifetime: 150 return ScopePair(diag::note_protected_by_objc_strong_init, 151 diag::note_exits_objc_strong); 152 153 case QualType::DK_objc_weak_lifetime: 154 return ScopePair(diag::note_protected_by_objc_weak_init, 155 diag::note_exits_objc_weak); 156 157 case QualType::DK_cxx_destructor: 158 OutDiag = diag::note_exits_dtor; 159 break; 160 161 case QualType::DK_none: 162 break; 163 } 164 } 165 166 const Expr *Init = VD->getInit(); 167 if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) { 168 // C++11 [stmt.dcl]p3: 169 // A program that jumps from a point where a variable with automatic 170 // storage duration is not in scope to a point where it is in scope 171 // is ill-formed unless the variable has scalar type, class type with 172 // a trivial default constructor and a trivial destructor, a 173 // cv-qualified version of one of these types, or an array of one of 174 // the preceding types and is declared without an initializer. 175 176 // C++03 [stmt.dcl.p3: 177 // A program that jumps from a point where a local variable 178 // with automatic storage duration is not in scope to a point 179 // where it is in scope is ill-formed unless the variable has 180 // POD type and is declared without an initializer. 181 182 InDiag = diag::note_protected_by_variable_init; 183 184 // For a variable of (array of) class type declared without an 185 // initializer, we will have call-style initialization and the initializer 186 // will be the CXXConstructExpr with no intervening nodes. 187 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 188 const CXXConstructorDecl *Ctor = CCE->getConstructor(); 189 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() && 190 VD->getInitStyle() == VarDecl::CallInit) { 191 if (OutDiag) 192 InDiag = diag::note_protected_by_variable_nontriv_destructor; 193 else if (!Ctor->getParent()->isPOD()) 194 InDiag = diag::note_protected_by_variable_non_pod; 195 else 196 InDiag = 0; 197 } 198 } 199 } 200 201 return ScopePair(InDiag, OutDiag); 202 } 203 204 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 205 if (TD->getUnderlyingType()->isVariablyModifiedType()) 206 return ScopePair(isa<TypedefDecl>(TD) 207 ? diag::note_protected_by_vla_typedef 208 : diag::note_protected_by_vla_type_alias, 209 0); 210 } 211 212 return ScopePair(0U, 0U); 213 } 214 215 /// \brief Build scope information for a declaration that is part of a DeclStmt. 216 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) { 217 // If this decl causes a new scope, push and switch to it. 218 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D); 219 if (Diags.first || Diags.second) { 220 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second, 221 D->getLocation())); 222 ParentScope = Scopes.size()-1; 223 } 224 225 // If the decl has an initializer, walk it with the potentially new 226 // scope we just installed. 227 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 228 if (Expr *Init = VD->getInit()) 229 BuildScopeInformation(Init, ParentScope); 230 } 231 232 /// \brief Build scope information for a captured block literal variables. 233 void JumpScopeChecker::BuildScopeInformation(VarDecl *D, 234 const BlockDecl *BDecl, 235 unsigned &ParentScope) { 236 // exclude captured __block variables; there's no destructor 237 // associated with the block literal for them. 238 if (D->hasAttr<BlocksAttr>()) 239 return; 240 QualType T = D->getType(); 241 QualType::DestructionKind destructKind = T.isDestructedType(); 242 if (destructKind != QualType::DK_none) { 243 std::pair<unsigned,unsigned> Diags; 244 switch (destructKind) { 245 case QualType::DK_cxx_destructor: 246 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj, 247 diag::note_exits_block_captures_cxx_obj); 248 break; 249 case QualType::DK_objc_strong_lifetime: 250 Diags = ScopePair(diag::note_enters_block_captures_strong, 251 diag::note_exits_block_captures_strong); 252 break; 253 case QualType::DK_objc_weak_lifetime: 254 Diags = ScopePair(diag::note_enters_block_captures_weak, 255 diag::note_exits_block_captures_weak); 256 break; 257 case QualType::DK_none: 258 llvm_unreachable("non-lifetime captured variable"); 259 } 260 SourceLocation Loc = D->getLocation(); 261 if (Loc.isInvalid()) 262 Loc = BDecl->getLocation(); 263 Scopes.push_back(GotoScope(ParentScope, 264 Diags.first, Diags.second, Loc)); 265 ParentScope = Scopes.size()-1; 266 } 267 } 268 269 /// BuildScopeInformation - The statements from CI to CE are known to form a 270 /// coherent VLA scope with a specified parent node. Walk through the 271 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively 272 /// walking the AST as needed. 273 void JumpScopeChecker::BuildScopeInformation(Stmt *S, 274 unsigned &origParentScope) { 275 // If this is a statement, rather than an expression, scopes within it don't 276 // propagate out into the enclosing scope. Otherwise we have to worry 277 // about block literals, which have the lifetime of their enclosing statement. 278 unsigned independentParentScope = origParentScope; 279 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S)) 280 ? origParentScope : independentParentScope); 281 282 bool SkipFirstSubStmt = false; 283 284 // If we found a label, remember that it is in ParentScope scope. 285 switch (S->getStmtClass()) { 286 case Stmt::AddrLabelExprClass: 287 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel()); 288 break; 289 290 case Stmt::IndirectGotoStmtClass: 291 // "goto *&&lbl;" is a special case which we treat as equivalent 292 // to a normal goto. In addition, we don't calculate scope in the 293 // operand (to avoid recording the address-of-label use), which 294 // works only because of the restricted set of expressions which 295 // we detect as constant targets. 296 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) { 297 LabelAndGotoScopes[S] = ParentScope; 298 Jumps.push_back(S); 299 return; 300 } 301 302 LabelAndGotoScopes[S] = ParentScope; 303 IndirectJumps.push_back(cast<IndirectGotoStmt>(S)); 304 break; 305 306 case Stmt::SwitchStmtClass: 307 // Evaluate the condition variable before entering the scope of the switch 308 // statement. 309 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) { 310 BuildScopeInformation(Var, ParentScope); 311 SkipFirstSubStmt = true; 312 } 313 // Fall through 314 315 case Stmt::GotoStmtClass: 316 // Remember both what scope a goto is in as well as the fact that we have 317 // it. This makes the second scan not have to walk the AST again. 318 LabelAndGotoScopes[S] = ParentScope; 319 Jumps.push_back(S); 320 break; 321 322 case Stmt::IfStmtClass: { 323 IfStmt *IS = cast<IfStmt>(S); 324 if (!IS->isConstexpr()) 325 break; 326 327 if (VarDecl *Var = IS->getConditionVariable()) 328 BuildScopeInformation(Var, ParentScope); 329 330 // Cannot jump into the middle of the condition. 331 unsigned NewParentScope = Scopes.size(); 332 Scopes.push_back(GotoScope(ParentScope, 333 diag::note_protected_by_constexpr_if, 0, 334 IS->getLocStart())); 335 BuildScopeInformation(IS->getCond(), NewParentScope); 336 337 // Jumps into either arm of an 'if constexpr' are not allowed. 338 NewParentScope = Scopes.size(); 339 Scopes.push_back(GotoScope(ParentScope, 340 diag::note_protected_by_constexpr_if, 0, 341 IS->getLocStart())); 342 BuildScopeInformation(IS->getThen(), NewParentScope); 343 if (Stmt *Else = IS->getElse()) { 344 NewParentScope = Scopes.size(); 345 Scopes.push_back(GotoScope(ParentScope, 346 diag::note_protected_by_constexpr_if, 0, 347 IS->getLocStart())); 348 BuildScopeInformation(Else, NewParentScope); 349 } 350 return; 351 } 352 353 case Stmt::CXXTryStmtClass: { 354 CXXTryStmt *TS = cast<CXXTryStmt>(S); 355 { 356 unsigned NewParentScope = Scopes.size(); 357 Scopes.push_back(GotoScope(ParentScope, 358 diag::note_protected_by_cxx_try, 359 diag::note_exits_cxx_try, 360 TS->getSourceRange().getBegin())); 361 if (Stmt *TryBlock = TS->getTryBlock()) 362 BuildScopeInformation(TryBlock, NewParentScope); 363 } 364 365 // Jump from the catch into the try is not allowed either. 366 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) { 367 CXXCatchStmt *CS = TS->getHandler(I); 368 unsigned NewParentScope = Scopes.size(); 369 Scopes.push_back(GotoScope(ParentScope, 370 diag::note_protected_by_cxx_catch, 371 diag::note_exits_cxx_catch, 372 CS->getSourceRange().getBegin())); 373 BuildScopeInformation(CS->getHandlerBlock(), NewParentScope); 374 } 375 return; 376 } 377 378 case Stmt::SEHTryStmtClass: { 379 SEHTryStmt *TS = cast<SEHTryStmt>(S); 380 { 381 unsigned NewParentScope = Scopes.size(); 382 Scopes.push_back(GotoScope(ParentScope, 383 diag::note_protected_by_seh_try, 384 diag::note_exits_seh_try, 385 TS->getSourceRange().getBegin())); 386 if (Stmt *TryBlock = TS->getTryBlock()) 387 BuildScopeInformation(TryBlock, NewParentScope); 388 } 389 390 // Jump from __except or __finally into the __try are not allowed either. 391 if (SEHExceptStmt *Except = TS->getExceptHandler()) { 392 unsigned NewParentScope = Scopes.size(); 393 Scopes.push_back(GotoScope(ParentScope, 394 diag::note_protected_by_seh_except, 395 diag::note_exits_seh_except, 396 Except->getSourceRange().getBegin())); 397 BuildScopeInformation(Except->getBlock(), NewParentScope); 398 } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) { 399 unsigned NewParentScope = Scopes.size(); 400 Scopes.push_back(GotoScope(ParentScope, 401 diag::note_protected_by_seh_finally, 402 diag::note_exits_seh_finally, 403 Finally->getSourceRange().getBegin())); 404 BuildScopeInformation(Finally->getBlock(), NewParentScope); 405 } 406 407 return; 408 } 409 410 case Stmt::DeclStmtClass: { 411 // If this is a declstmt with a VLA definition, it defines a scope from here 412 // to the end of the containing context. 413 DeclStmt *DS = cast<DeclStmt>(S); 414 // The decl statement creates a scope if any of the decls in it are VLAs 415 // or have the cleanup attribute. 416 for (auto *I : DS->decls()) 417 BuildScopeInformation(I, origParentScope); 418 return; 419 } 420 421 case Stmt::ObjCAtTryStmtClass: { 422 // Disallow jumps into any part of an @try statement by pushing a scope and 423 // walking all sub-stmts in that scope. 424 ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S); 425 // Recursively walk the AST for the @try part. 426 { 427 unsigned NewParentScope = Scopes.size(); 428 Scopes.push_back(GotoScope(ParentScope, 429 diag::note_protected_by_objc_try, 430 diag::note_exits_objc_try, 431 AT->getAtTryLoc())); 432 if (Stmt *TryPart = AT->getTryBody()) 433 BuildScopeInformation(TryPart, NewParentScope); 434 } 435 436 // Jump from the catch to the finally or try is not valid. 437 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) { 438 ObjCAtCatchStmt *AC = AT->getCatchStmt(I); 439 unsigned NewParentScope = Scopes.size(); 440 Scopes.push_back(GotoScope(ParentScope, 441 diag::note_protected_by_objc_catch, 442 diag::note_exits_objc_catch, 443 AC->getAtCatchLoc())); 444 // @catches are nested and it isn't 445 BuildScopeInformation(AC->getCatchBody(), NewParentScope); 446 } 447 448 // Jump from the finally to the try or catch is not valid. 449 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) { 450 unsigned NewParentScope = Scopes.size(); 451 Scopes.push_back(GotoScope(ParentScope, 452 diag::note_protected_by_objc_finally, 453 diag::note_exits_objc_finally, 454 AF->getAtFinallyLoc())); 455 BuildScopeInformation(AF, NewParentScope); 456 } 457 458 return; 459 } 460 461 case Stmt::ObjCAtSynchronizedStmtClass: { 462 // Disallow jumps into the protected statement of an @synchronized, but 463 // allow jumps into the object expression it protects. 464 ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S); 465 // Recursively walk the AST for the @synchronized object expr, it is 466 // evaluated in the normal scope. 467 BuildScopeInformation(AS->getSynchExpr(), ParentScope); 468 469 // Recursively walk the AST for the @synchronized part, protected by a new 470 // scope. 471 unsigned NewParentScope = Scopes.size(); 472 Scopes.push_back(GotoScope(ParentScope, 473 diag::note_protected_by_objc_synchronized, 474 diag::note_exits_objc_synchronized, 475 AS->getAtSynchronizedLoc())); 476 BuildScopeInformation(AS->getSynchBody(), NewParentScope); 477 return; 478 } 479 480 case Stmt::ObjCAutoreleasePoolStmtClass: { 481 // Disallow jumps into the protected statement of an @autoreleasepool. 482 ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S); 483 // Recursively walk the AST for the @autoreleasepool part, protected by a 484 // new scope. 485 unsigned NewParentScope = Scopes.size(); 486 Scopes.push_back(GotoScope(ParentScope, 487 diag::note_protected_by_objc_autoreleasepool, 488 diag::note_exits_objc_autoreleasepool, 489 AS->getAtLoc())); 490 BuildScopeInformation(AS->getSubStmt(), NewParentScope); 491 return; 492 } 493 494 case Stmt::ExprWithCleanupsClass: { 495 // Disallow jumps past full-expressions that use blocks with 496 // non-trivial cleanups of their captures. This is theoretically 497 // implementable but a lot of work which we haven't felt up to doing. 498 ExprWithCleanups *EWC = cast<ExprWithCleanups>(S); 499 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) { 500 const BlockDecl *BDecl = EWC->getObject(i); 501 for (const auto &CI : BDecl->captures()) { 502 VarDecl *variable = CI.getVariable(); 503 BuildScopeInformation(variable, BDecl, origParentScope); 504 } 505 } 506 break; 507 } 508 509 case Stmt::MaterializeTemporaryExprClass: { 510 // Disallow jumps out of scopes containing temporaries lifetime-extended to 511 // automatic storage duration. 512 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 513 if (MTE->getStorageDuration() == SD_Automatic) { 514 SmallVector<const Expr *, 4> CommaLHS; 515 SmallVector<SubobjectAdjustment, 4> Adjustments; 516 const Expr *ExtendedObject = 517 MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments( 518 CommaLHS, Adjustments); 519 if (ExtendedObject->getType().isDestructedType()) { 520 Scopes.push_back(GotoScope(ParentScope, 0, 521 diag::note_exits_temporary_dtor, 522 ExtendedObject->getExprLoc())); 523 origParentScope = Scopes.size()-1; 524 } 525 } 526 break; 527 } 528 529 case Stmt::CaseStmtClass: 530 case Stmt::DefaultStmtClass: 531 case Stmt::LabelStmtClass: 532 LabelAndGotoScopes[S] = ParentScope; 533 break; 534 535 default: 536 break; 537 } 538 539 for (Stmt *SubStmt : S->children()) { 540 if (SkipFirstSubStmt) { 541 SkipFirstSubStmt = false; 542 continue; 543 } 544 545 if (!SubStmt) continue; 546 547 // Cases, labels, and defaults aren't "scope parents". It's also 548 // important to handle these iteratively instead of recursively in 549 // order to avoid blowing out the stack. 550 while (true) { 551 Stmt *Next; 552 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt)) 553 Next = CS->getSubStmt(); 554 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt)) 555 Next = DS->getSubStmt(); 556 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt)) 557 Next = LS->getSubStmt(); 558 else 559 break; 560 561 LabelAndGotoScopes[SubStmt] = ParentScope; 562 SubStmt = Next; 563 } 564 565 // Recursively walk the AST. 566 BuildScopeInformation(SubStmt, ParentScope); 567 } 568 } 569 570 /// VerifyJumps - Verify each element of the Jumps array to see if they are 571 /// valid, emitting diagnostics if not. 572 void JumpScopeChecker::VerifyJumps() { 573 while (!Jumps.empty()) { 574 Stmt *Jump = Jumps.pop_back_val(); 575 576 // With a goto, 577 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) { 578 // The label may not have a statement if it's coming from inline MS ASM. 579 if (GS->getLabel()->getStmt()) { 580 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(), 581 diag::err_goto_into_protected_scope, 582 diag::ext_goto_into_protected_scope, 583 diag::warn_cxx98_compat_goto_into_protected_scope); 584 } 585 CheckGotoStmt(GS); 586 continue; 587 } 588 589 // We only get indirect gotos here when they have a constant target. 590 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) { 591 LabelDecl *Target = IGS->getConstantTarget(); 592 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(), 593 diag::err_goto_into_protected_scope, 594 diag::ext_goto_into_protected_scope, 595 diag::warn_cxx98_compat_goto_into_protected_scope); 596 continue; 597 } 598 599 SwitchStmt *SS = cast<SwitchStmt>(Jump); 600 for (SwitchCase *SC = SS->getSwitchCaseList(); SC; 601 SC = SC->getNextSwitchCase()) { 602 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC))) 603 continue; 604 SourceLocation Loc; 605 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC)) 606 Loc = CS->getLocStart(); 607 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) 608 Loc = DS->getLocStart(); 609 else 610 Loc = SC->getLocStart(); 611 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0, 612 diag::warn_cxx98_compat_switch_into_protected_scope); 613 } 614 } 615 } 616 617 /// VerifyIndirectJumps - Verify whether any possible indirect jump 618 /// might cross a protection boundary. Unlike direct jumps, indirect 619 /// jumps count cleanups as protection boundaries: since there's no 620 /// way to know where the jump is going, we can't implicitly run the 621 /// right cleanups the way we can with direct jumps. 622 /// 623 /// Thus, an indirect jump is "trivial" if it bypasses no 624 /// initializations and no teardowns. More formally, an indirect jump 625 /// from A to B is trivial if the path out from A to DCA(A,B) is 626 /// trivial and the path in from DCA(A,B) to B is trivial, where 627 /// DCA(A,B) is the deepest common ancestor of A and B. 628 /// Jump-triviality is transitive but asymmetric. 629 /// 630 /// A path in is trivial if none of the entered scopes have an InDiag. 631 /// A path out is trivial is none of the exited scopes have an OutDiag. 632 /// 633 /// Under these definitions, this function checks that the indirect 634 /// jump between A and B is trivial for every indirect goto statement A 635 /// and every label B whose address was taken in the function. 636 void JumpScopeChecker::VerifyIndirectJumps() { 637 if (IndirectJumps.empty()) return; 638 639 // If there aren't any address-of-label expressions in this function, 640 // complain about the first indirect goto. 641 if (IndirectJumpTargets.empty()) { 642 S.Diag(IndirectJumps[0]->getGotoLoc(), 643 diag::err_indirect_goto_without_addrlabel); 644 return; 645 } 646 647 // Collect a single representative of every scope containing an 648 // indirect goto. For most code bases, this substantially cuts 649 // down on the number of jump sites we'll have to consider later. 650 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope; 651 SmallVector<JumpScope, 32> JumpScopes; 652 { 653 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap; 654 for (SmallVectorImpl<IndirectGotoStmt*>::iterator 655 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) { 656 IndirectGotoStmt *IG = *I; 657 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG))) 658 continue; 659 unsigned IGScope = LabelAndGotoScopes[IG]; 660 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope]; 661 if (!Entry) Entry = IG; 662 } 663 JumpScopes.reserve(JumpScopesMap.size()); 664 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator 665 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I) 666 JumpScopes.push_back(*I); 667 } 668 669 // Collect a single representative of every scope containing a 670 // label whose address was taken somewhere in the function. 671 // For most code bases, there will be only one such scope. 672 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes; 673 for (SmallVectorImpl<LabelDecl*>::iterator 674 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end(); 675 I != E; ++I) { 676 LabelDecl *TheLabel = *I; 677 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt()))) 678 continue; 679 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()]; 680 LabelDecl *&Target = TargetScopes[LabelScope]; 681 if (!Target) Target = TheLabel; 682 } 683 684 // For each target scope, make sure it's trivially reachable from 685 // every scope containing a jump site. 686 // 687 // A path between scopes always consists of exitting zero or more 688 // scopes, then entering zero or more scopes. We build a set of 689 // of scopes S from which the target scope can be trivially 690 // entered, then verify that every jump scope can be trivially 691 // exitted to reach a scope in S. 692 llvm::BitVector Reachable(Scopes.size(), false); 693 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator 694 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) { 695 unsigned TargetScope = TI->first; 696 LabelDecl *TargetLabel = TI->second; 697 698 Reachable.reset(); 699 700 // Mark all the enclosing scopes from which you can safely jump 701 // into the target scope. 'Min' will end up being the index of 702 // the shallowest such scope. 703 unsigned Min = TargetScope; 704 while (true) { 705 Reachable.set(Min); 706 707 // Don't go beyond the outermost scope. 708 if (Min == 0) break; 709 710 // Stop if we can't trivially enter the current scope. 711 if (Scopes[Min].InDiag) break; 712 713 Min = Scopes[Min].ParentScope; 714 } 715 716 // Walk through all the jump sites, checking that they can trivially 717 // reach this label scope. 718 for (SmallVectorImpl<JumpScope>::iterator 719 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) { 720 unsigned Scope = I->first; 721 722 // Walk out the "scope chain" for this scope, looking for a scope 723 // we've marked reachable. For well-formed code this amortizes 724 // to O(JumpScopes.size() / Scopes.size()): we only iterate 725 // when we see something unmarked, and in well-formed code we 726 // mark everything we iterate past. 727 bool IsReachable = false; 728 while (true) { 729 if (Reachable.test(Scope)) { 730 // If we find something reachable, mark all the scopes we just 731 // walked through as reachable. 732 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope) 733 Reachable.set(S); 734 IsReachable = true; 735 break; 736 } 737 738 // Don't walk out if we've reached the top-level scope or we've 739 // gotten shallower than the shallowest reachable scope. 740 if (Scope == 0 || Scope < Min) break; 741 742 // Don't walk out through an out-diagnostic. 743 if (Scopes[Scope].OutDiag) break; 744 745 Scope = Scopes[Scope].ParentScope; 746 } 747 748 // Only diagnose if we didn't find something. 749 if (IsReachable) continue; 750 751 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope); 752 } 753 } 754 } 755 756 /// Return true if a particular error+note combination must be downgraded to a 757 /// warning in Microsoft mode. 758 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) { 759 return (JumpDiag == diag::err_goto_into_protected_scope && 760 (InDiagNote == diag::note_protected_by_variable_init || 761 InDiagNote == diag::note_protected_by_variable_nontriv_destructor)); 762 } 763 764 /// Return true if a particular note should be downgraded to a compatibility 765 /// warning in C++11 mode. 766 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) { 767 return S.getLangOpts().CPlusPlus11 && 768 InDiagNote == diag::note_protected_by_variable_non_pod; 769 } 770 771 /// Produce primary diagnostic for an indirect jump statement. 772 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump, 773 LabelDecl *Target, bool &Diagnosed) { 774 if (Diagnosed) 775 return; 776 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope); 777 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target); 778 Diagnosed = true; 779 } 780 781 /// Produce note diagnostics for a jump into a protected scope. 782 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) { 783 if (CHECK_PERMISSIVE(ToScopes.empty())) 784 return; 785 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I) 786 if (Scopes[ToScopes[I]].InDiag) 787 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag); 788 } 789 790 /// Diagnose an indirect jump which is known to cross scopes. 791 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump, 792 unsigned JumpScope, 793 LabelDecl *Target, 794 unsigned TargetScope) { 795 if (CHECK_PERMISSIVE(JumpScope == TargetScope)) 796 return; 797 798 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope); 799 bool Diagnosed = false; 800 801 // Walk out the scope chain until we reach the common ancestor. 802 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope) 803 if (Scopes[I].OutDiag) { 804 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed); 805 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag); 806 } 807 808 SmallVector<unsigned, 10> ToScopesCXX98Compat; 809 810 // Now walk into the scopes containing the label whose address was taken. 811 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope) 812 if (IsCXX98CompatWarning(S, Scopes[I].InDiag)) 813 ToScopesCXX98Compat.push_back(I); 814 else if (Scopes[I].InDiag) { 815 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed); 816 S.Diag(Scopes[I].Loc, Scopes[I].InDiag); 817 } 818 819 // Diagnose this jump if it would be ill-formed in C++98. 820 if (!Diagnosed && !ToScopesCXX98Compat.empty()) { 821 S.Diag(Jump->getGotoLoc(), 822 diag::warn_cxx98_compat_indirect_goto_in_protected_scope); 823 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target); 824 NoteJumpIntoScopes(ToScopesCXX98Compat); 825 } 826 } 827 828 /// CheckJump - Validate that the specified jump statement is valid: that it is 829 /// jumping within or out of its current scope, not into a deeper one. 830 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, 831 unsigned JumpDiagError, unsigned JumpDiagWarning, 832 unsigned JumpDiagCXX98Compat) { 833 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From))) 834 return; 835 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To))) 836 return; 837 838 unsigned FromScope = LabelAndGotoScopes[From]; 839 unsigned ToScope = LabelAndGotoScopes[To]; 840 841 // Common case: exactly the same scope, which is fine. 842 if (FromScope == ToScope) return; 843 844 // Warn on gotos out of __finally blocks. 845 if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) { 846 // If FromScope > ToScope, FromScope is more nested and the jump goes to a 847 // less nested scope. Check if it crosses a __finally along the way. 848 for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) { 849 if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) { 850 S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally); 851 break; 852 } 853 } 854 } 855 856 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope); 857 858 // It's okay to jump out from a nested scope. 859 if (CommonScope == ToScope) return; 860 861 // Pull out (and reverse) any scopes we might need to diagnose skipping. 862 SmallVector<unsigned, 10> ToScopesCXX98Compat; 863 SmallVector<unsigned, 10> ToScopesError; 864 SmallVector<unsigned, 10> ToScopesWarning; 865 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) { 866 if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 && 867 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag)) 868 ToScopesWarning.push_back(I); 869 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag)) 870 ToScopesCXX98Compat.push_back(I); 871 else if (Scopes[I].InDiag) 872 ToScopesError.push_back(I); 873 } 874 875 // Handle warnings. 876 if (!ToScopesWarning.empty()) { 877 S.Diag(DiagLoc, JumpDiagWarning); 878 NoteJumpIntoScopes(ToScopesWarning); 879 } 880 881 // Handle errors. 882 if (!ToScopesError.empty()) { 883 S.Diag(DiagLoc, JumpDiagError); 884 NoteJumpIntoScopes(ToScopesError); 885 } 886 887 // Handle -Wc++98-compat warnings if the jump is well-formed. 888 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) { 889 S.Diag(DiagLoc, JumpDiagCXX98Compat); 890 NoteJumpIntoScopes(ToScopesCXX98Compat); 891 } 892 } 893 894 void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) { 895 if (GS->getLabel()->isMSAsmLabel()) { 896 S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label) 897 << GS->getLabel()->getIdentifier(); 898 S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label) 899 << GS->getLabel()->getIdentifier(); 900 } 901 } 902 903 void Sema::DiagnoseInvalidJumps(Stmt *Body) { 904 (void)JumpScopeChecker(Body, *this); 905 } 906