JumpDiagnostics.cpp revision 204643
1//===--- JumpDiagnostics.cpp - Analyze Jump Targets for VLA issues --------===// 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 VLA scope in an invalid way. 12// 13//===----------------------------------------------------------------------===// 14 15#include "Sema.h" 16#include "clang/AST/Expr.h" 17#include "clang/AST/StmtObjC.h" 18#include "clang/AST/StmtCXX.h" 19using namespace clang; 20 21namespace { 22 23/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps 24/// into VLA and other protected scopes. For example, this rejects: 25/// goto L; 26/// int a[n]; 27/// L: 28/// 29class JumpScopeChecker { 30 Sema &S; 31 32 /// GotoScope - This is a record that we use to keep track of all of the 33 /// scopes that are introduced by VLAs and other things that scope jumps like 34 /// gotos. This scope tree has nothing to do with the source scope tree, 35 /// because you can have multiple VLA scopes per compound statement, and most 36 /// compound statements don't introduce any scopes. 37 struct GotoScope { 38 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for 39 /// the parent scope is the function body. 40 unsigned ParentScope; 41 42 /// Diag - The diagnostic to emit if there is a jump into this scope. 43 unsigned Diag; 44 45 /// Loc - Location to emit the diagnostic. 46 SourceLocation Loc; 47 48 GotoScope(unsigned parentScope, unsigned diag, SourceLocation L) 49 : ParentScope(parentScope), Diag(diag), Loc(L) {} 50 }; 51 52 llvm::SmallVector<GotoScope, 48> Scopes; 53 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes; 54 llvm::SmallVector<Stmt*, 16> Jumps; 55public: 56 JumpScopeChecker(Stmt *Body, Sema &S); 57private: 58 void BuildScopeInformation(Stmt *S, unsigned ParentScope); 59 void VerifyJumps(); 60 void CheckJump(Stmt *From, Stmt *To, 61 SourceLocation DiagLoc, unsigned JumpDiag); 62}; 63} // end anonymous namespace 64 65 66JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) { 67 // Add a scope entry for function scope. 68 Scopes.push_back(GotoScope(~0U, ~0U, SourceLocation())); 69 70 // Build information for the top level compound statement, so that we have a 71 // defined scope record for every "goto" and label. 72 BuildScopeInformation(Body, 0); 73 74 // Check that all jumps we saw are kosher. 75 VerifyJumps(); 76} 77 78/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a 79/// diagnostic that should be emitted if control goes over it. If not, return 0. 80static unsigned GetDiagForGotoScopeDecl(const Decl *D, bool isCPlusPlus) { 81 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 82 if (VD->getType()->isVariablyModifiedType()) 83 return diag::note_protected_by_vla; 84 if (VD->hasAttr<CleanupAttr>()) 85 return diag::note_protected_by_cleanup; 86 if (VD->hasAttr<BlocksAttr>()) 87 return diag::note_protected_by___block; 88 if (isCPlusPlus && VD->hasLocalStorage() && VD->hasInit()) 89 return diag::note_protected_by_variable_init; 90 91 } else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { 92 if (TD->getUnderlyingType()->isVariablyModifiedType()) 93 return diag::note_protected_by_vla_typedef; 94 } 95 96 return 0; 97} 98 99 100/// BuildScopeInformation - The statements from CI to CE are known to form a 101/// coherent VLA scope with a specified parent node. Walk through the 102/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively 103/// walking the AST as needed. 104void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) { 105 106 // If we found a label, remember that it is in ParentScope scope. 107 if (isa<LabelStmt>(S) || isa<DefaultStmt>(S) || isa<CaseStmt>(S)) { 108 LabelAndGotoScopes[S] = ParentScope; 109 } else if (isa<GotoStmt>(S) || isa<SwitchStmt>(S) || 110 isa<IndirectGotoStmt>(S) || isa<AddrLabelExpr>(S)) { 111 // Remember both what scope a goto is in as well as the fact that we have 112 // it. This makes the second scan not have to walk the AST again. 113 LabelAndGotoScopes[S] = ParentScope; 114 Jumps.push_back(S); 115 } 116 117 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 118 ++CI) { 119 Stmt *SubStmt = *CI; 120 if (SubStmt == 0) continue; 121 122 bool isCPlusPlus = this->S.getLangOptions().CPlusPlus; 123 124 // If this is a declstmt with a VLA definition, it defines a scope from here 125 // to the end of the containing context. 126 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) { 127 // The decl statement creates a scope if any of the decls in it are VLAs 128 // or have the cleanup attribute. 129 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end(); 130 I != E; ++I) { 131 // If this decl causes a new scope, push and switch to it. 132 if (unsigned Diag = GetDiagForGotoScopeDecl(*I, isCPlusPlus)) { 133 Scopes.push_back(GotoScope(ParentScope, Diag, (*I)->getLocation())); 134 ParentScope = Scopes.size()-1; 135 } 136 137 // If the decl has an initializer, walk it with the potentially new 138 // scope we just installed. 139 if (VarDecl *VD = dyn_cast<VarDecl>(*I)) 140 if (Expr *Init = VD->getInit()) 141 BuildScopeInformation(Init, ParentScope); 142 } 143 continue; 144 } 145 146 // Disallow jumps into any part of an @try statement by pushing a scope and 147 // walking all sub-stmts in that scope. 148 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) { 149 // Recursively walk the AST for the @try part. 150 Scopes.push_back(GotoScope(ParentScope,diag::note_protected_by_objc_try, 151 AT->getAtTryLoc())); 152 if (Stmt *TryPart = AT->getTryBody()) 153 BuildScopeInformation(TryPart, Scopes.size()-1); 154 155 // Jump from the catch to the finally or try is not valid. 156 for (ObjCAtCatchStmt *AC = AT->getCatchStmts(); AC; 157 AC = AC->getNextCatchStmt()) { 158 Scopes.push_back(GotoScope(ParentScope, 159 diag::note_protected_by_objc_catch, 160 AC->getAtCatchLoc())); 161 // @catches are nested and it isn't 162 BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1); 163 } 164 165 // Jump from the finally to the try or catch is not valid. 166 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) { 167 Scopes.push_back(GotoScope(ParentScope, 168 diag::note_protected_by_objc_finally, 169 AF->getAtFinallyLoc())); 170 BuildScopeInformation(AF, Scopes.size()-1); 171 } 172 173 continue; 174 } 175 176 // Disallow jumps into the protected statement of an @synchronized, but 177 // allow jumps into the object expression it protects. 178 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){ 179 // Recursively walk the AST for the @synchronized object expr, it is 180 // evaluated in the normal scope. 181 BuildScopeInformation(AS->getSynchExpr(), ParentScope); 182 183 // Recursively walk the AST for the @synchronized part, protected by a new 184 // scope. 185 Scopes.push_back(GotoScope(ParentScope, 186 diag::note_protected_by_objc_synchronized, 187 AS->getAtSynchronizedLoc())); 188 BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1); 189 continue; 190 } 191 192 // Disallow jumps into any part of a C++ try statement. This is pretty 193 // much the same as for Obj-C. 194 if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) { 195 Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_cxx_try, 196 TS->getSourceRange().getBegin())); 197 if (Stmt *TryBlock = TS->getTryBlock()) 198 BuildScopeInformation(TryBlock, Scopes.size()-1); 199 200 // Jump from the catch into the try is not allowed either. 201 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) { 202 CXXCatchStmt *CS = TS->getHandler(I); 203 Scopes.push_back(GotoScope(ParentScope, 204 diag::note_protected_by_cxx_catch, 205 CS->getSourceRange().getBegin())); 206 BuildScopeInformation(CS->getHandlerBlock(), Scopes.size()-1); 207 } 208 209 continue; 210 } 211 212 // Recursively walk the AST. 213 BuildScopeInformation(SubStmt, ParentScope); 214 } 215} 216 217/// VerifyJumps - Verify each element of the Jumps array to see if they are 218/// valid, emitting diagnostics if not. 219void JumpScopeChecker::VerifyJumps() { 220 while (!Jumps.empty()) { 221 Stmt *Jump = Jumps.pop_back_val(); 222 223 // With a goto, 224 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) { 225 CheckJump(GS, GS->getLabel(), GS->getGotoLoc(), 226 diag::err_goto_into_protected_scope); 227 continue; 228 } 229 230 if (SwitchStmt *SS = dyn_cast<SwitchStmt>(Jump)) { 231 for (SwitchCase *SC = SS->getSwitchCaseList(); SC; 232 SC = SC->getNextSwitchCase()) { 233 assert(LabelAndGotoScopes.count(SC) && "Case not visited?"); 234 CheckJump(SS, SC, SC->getLocStart(), 235 diag::err_switch_into_protected_scope); 236 } 237 continue; 238 } 239 240 unsigned DiagnosticScope; 241 242 // We don't know where an indirect goto goes, require that it be at the 243 // top level of scoping. 244 if (IndirectGotoStmt *IG = dyn_cast<IndirectGotoStmt>(Jump)) { 245 assert(LabelAndGotoScopes.count(Jump) && 246 "Jump didn't get added to scopes?"); 247 unsigned GotoScope = LabelAndGotoScopes[IG]; 248 if (GotoScope == 0) continue; // indirect jump is ok. 249 S.Diag(IG->getGotoLoc(), diag::err_indirect_goto_in_protected_scope); 250 DiagnosticScope = GotoScope; 251 } else { 252 // We model &&Label as a jump for purposes of scope tracking. We actually 253 // don't care *where* the address of label is, but we require the *label 254 // itself* to be in scope 0. If it is nested inside of a VLA scope, then 255 // it is possible for an indirect goto to illegally enter the VLA scope by 256 // indirectly jumping to the label. 257 assert(isa<AddrLabelExpr>(Jump) && "Unknown jump type"); 258 LabelStmt *TheLabel = cast<AddrLabelExpr>(Jump)->getLabel(); 259 260 assert(LabelAndGotoScopes.count(TheLabel) && 261 "Referenced label didn't get added to scopes?"); 262 unsigned LabelScope = LabelAndGotoScopes[TheLabel]; 263 if (LabelScope == 0) continue; // Addr of label is ok. 264 265 S.Diag(Jump->getLocStart(), diag::err_addr_of_label_in_protected_scope); 266 DiagnosticScope = LabelScope; 267 } 268 269 // Report all the things that would be skipped over by this &&label or 270 // indirect goto. 271 while (DiagnosticScope != 0) { 272 S.Diag(Scopes[DiagnosticScope].Loc, Scopes[DiagnosticScope].Diag); 273 DiagnosticScope = Scopes[DiagnosticScope].ParentScope; 274 } 275 } 276} 277 278/// CheckJump - Validate that the specified jump statement is valid: that it is 279/// jumping within or out of its current scope, not into a deeper one. 280void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, 281 SourceLocation DiagLoc, unsigned JumpDiag) { 282 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?"); 283 unsigned FromScope = LabelAndGotoScopes[From]; 284 285 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?"); 286 unsigned ToScope = LabelAndGotoScopes[To]; 287 288 // Common case: exactly the same scope, which is fine. 289 if (FromScope == ToScope) return; 290 291 // The only valid mismatch jump case happens when the jump is more deeply 292 // nested inside the jump target. Do a quick scan to see if the jump is valid 293 // because valid code is more common than invalid code. 294 unsigned TestScope = Scopes[FromScope].ParentScope; 295 while (TestScope != ~0U) { 296 // If we found the jump target, then we're jumping out of our current scope, 297 // which is perfectly fine. 298 if (TestScope == ToScope) return; 299 300 // Otherwise, scan up the hierarchy. 301 TestScope = Scopes[TestScope].ParentScope; 302 } 303 304 // If we get here, then we know we have invalid code. Diagnose the bad jump, 305 // and then emit a note at each VLA being jumped out of. 306 S.Diag(DiagLoc, JumpDiag); 307 308 // Eliminate the common prefix of the jump and the target. Start by 309 // linearizing both scopes, reversing them as we go. 310 std::vector<unsigned> FromScopes, ToScopes; 311 for (TestScope = FromScope; TestScope != ~0U; 312 TestScope = Scopes[TestScope].ParentScope) 313 FromScopes.push_back(TestScope); 314 for (TestScope = ToScope; TestScope != ~0U; 315 TestScope = Scopes[TestScope].ParentScope) 316 ToScopes.push_back(TestScope); 317 318 // Remove any common entries (such as the top-level function scope). 319 while (!FromScopes.empty() && FromScopes.back() == ToScopes.back()) { 320 FromScopes.pop_back(); 321 ToScopes.pop_back(); 322 } 323 324 // Emit diagnostics for whatever is left in ToScopes. 325 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i) 326 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].Diag); 327} 328 329void Sema::DiagnoseInvalidJumps(Stmt *Body) { 330 (void)JumpScopeChecker(Body, *this); 331} 332