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