blob: 20473e4306f3a5189f2f711b95af6fc5e3af043b [file] [log] [blame]
Chris Lattner5af280c2009-04-19 04:46:21 +00001//===--- 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"
Chris Lattner16f00492009-04-26 01:32:48 +000017#include "clang/AST/StmtObjC.h"
Chris Lattner5af280c2009-04-19 04:46:21 +000018using namespace clang;
19
20namespace {
21
22/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
23/// into VLA and other protected scopes. For example, this rejects:
24/// goto L;
25/// int a[n];
26/// L:
27///
28class JumpScopeChecker {
29 Sema &S;
30
31 /// GotoScope - This is a record that we use to keep track of all of the
32 /// scopes that are introduced by VLAs and other things that scope jumps like
33 /// gotos. This scope tree has nothing to do with the source scope tree,
34 /// because you can have multiple VLA scopes per compound statement, and most
35 /// compound statements don't introduce any scopes.
36 struct GotoScope {
37 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
38 /// the parent scope is the function body.
39 unsigned ParentScope;
40
41 /// Diag - The diagnostic to emit if there is a jump into this scope.
42 unsigned Diag;
43
44 /// Loc - Location to emit the diagnostic.
45 SourceLocation Loc;
46
47 GotoScope(unsigned parentScope, unsigned diag, SourceLocation L)
48 : ParentScope(parentScope), Diag(diag), Loc(L) {}
49 };
50
51 llvm::SmallVector<GotoScope, 48> Scopes;
52 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
53 llvm::SmallVector<Stmt*, 16> Jumps;
54public:
55 JumpScopeChecker(Stmt *Body, Sema &S);
56private:
57 void BuildScopeInformation(Stmt *S, unsigned ParentScope);
58 void VerifyJumps();
59 void CheckJump(Stmt *From, Stmt *To,
60 SourceLocation DiagLoc, unsigned JumpDiag);
61};
62} // end anonymous namespace
63
64
65JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
66 // Add a scope entry for function scope.
67 Scopes.push_back(GotoScope(~0U, ~0U, SourceLocation()));
68
69 // Build information for the top level compound statement, so that we have a
70 // defined scope record for every "goto" and label.
71 BuildScopeInformation(Body, 0);
72
73 // Check that all jumps we saw are kosher.
74 VerifyJumps();
75}
76
77/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
78/// diagnostic that should be emitted if control goes over it. If not, return 0.
79static unsigned GetDiagForGotoScopeDecl(const Decl *D) {
80 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81 if (VD->getType()->isVariablyModifiedType())
82 return diag::note_protected_by_vla;
83 if (VD->hasAttr<CleanupAttr>())
84 return diag::note_protected_by_cleanup;
85 } else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
86 if (TD->getUnderlyingType()->isVariablyModifiedType())
87 return diag::note_protected_by_vla_typedef;
88 }
89
90 return 0;
91}
92
93
94/// BuildScopeInformation - The statements from CI to CE are known to form a
95/// coherent VLA scope with a specified parent node. Walk through the
96/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
97/// walking the AST as needed.
98void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
99
100 // If we found a label, remember that it is in ParentScope scope.
101 if (isa<LabelStmt>(S) || isa<DefaultStmt>(S) || isa<CaseStmt>(S)) {
102 LabelAndGotoScopes[S] = ParentScope;
103 } else if (isa<GotoStmt>(S) || isa<SwitchStmt>(S) ||
104 isa<IndirectGotoStmt>(S) || isa<AddrLabelExpr>(S)) {
105 // Remember both what scope a goto is in as well as the fact that we have
106 // it. This makes the second scan not have to walk the AST again.
107 LabelAndGotoScopes[S] = ParentScope;
108 Jumps.push_back(S);
109 }
110
111 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
112 ++CI) {
113 Stmt *SubStmt = *CI;
114 if (SubStmt == 0) continue;
115
116 // FIXME: diagnose jumps past initialization: required in C++, warning in C.
117 // goto L; int X = 4; L: ;
118 // FIXME: what about jumps into C++ catch blocks, what are the rules?
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
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000172 // 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
Chris Lattner5af280c2009-04-19 04:46:21 +0000188 // Recursively walk the AST.
189 BuildScopeInformation(SubStmt, ParentScope);
190 }
191}
192
193/// VerifyJumps - Verify each element of the Jumps array to see if they are
194/// valid, emitting diagnostics if not.
195void JumpScopeChecker::VerifyJumps() {
196 while (!Jumps.empty()) {
197 Stmt *Jump = Jumps.pop_back_val();
198
199 // With a goto,
200 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
201 CheckJump(GS, GS->getLabel(), GS->getGotoLoc(),
202 diag::err_goto_into_protected_scope);
203 continue;
204 }
205
206 if (SwitchStmt *SS = dyn_cast<SwitchStmt>(Jump)) {
207 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
208 SC = SC->getNextSwitchCase()) {
209 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
210 CheckJump(SS, SC, SC->getLocStart(),
211 diag::err_switch_into_protected_scope);
212 }
213 continue;
214 }
215
216 unsigned DiagnosticScope;
217
218 // We don't know where an indirect goto goes, require that it be at the
219 // top level of scoping.
220 if (IndirectGotoStmt *IG = dyn_cast<IndirectGotoStmt>(Jump)) {
221 assert(LabelAndGotoScopes.count(Jump) &&
222 "Jump didn't get added to scopes?");
223 unsigned GotoScope = LabelAndGotoScopes[IG];
224 if (GotoScope == 0) continue; // indirect jump is ok.
225 S.Diag(IG->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
226 DiagnosticScope = GotoScope;
227 } else {
228 // We model &&Label as a jump for purposes of scope tracking. We actually
229 // don't care *where* the address of label is, but we require the *label
230 // itself* to be in scope 0. If it is nested inside of a VLA scope, then
231 // it is possible for an indirect goto to illegally enter the VLA scope by
232 // indirectly jumping to the label.
233 assert(isa<AddrLabelExpr>(Jump) && "Unknown jump type");
234 LabelStmt *TheLabel = cast<AddrLabelExpr>(Jump)->getLabel();
235
236 assert(LabelAndGotoScopes.count(TheLabel) &&
237 "Referenced label didn't get added to scopes?");
238 unsigned LabelScope = LabelAndGotoScopes[TheLabel];
239 if (LabelScope == 0) continue; // Addr of label is ok.
240
241 S.Diag(Jump->getLocStart(), diag::err_addr_of_label_in_protected_scope);
242 DiagnosticScope = LabelScope;
243 }
244
245 // Report all the things that would be skipped over by this &&label or
246 // indirect goto.
247 while (DiagnosticScope != 0) {
248 S.Diag(Scopes[DiagnosticScope].Loc, Scopes[DiagnosticScope].Diag);
249 DiagnosticScope = Scopes[DiagnosticScope].ParentScope;
250 }
251 }
252}
253
254/// CheckJump - Validate that the specified jump statement is valid: that it is
255/// jumping within or out of its current scope, not into a deeper one.
256void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
257 SourceLocation DiagLoc, unsigned JumpDiag) {
258 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
259 unsigned FromScope = LabelAndGotoScopes[From];
260
261 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
262 unsigned ToScope = LabelAndGotoScopes[To];
263
264 // Common case: exactly the same scope, which is fine.
265 if (FromScope == ToScope) return;
266
267 // The only valid mismatch jump case happens when the jump is more deeply
268 // nested inside the jump target. Do a quick scan to see if the jump is valid
269 // because valid code is more common than invalid code.
270 unsigned TestScope = Scopes[FromScope].ParentScope;
271 while (TestScope != ~0U) {
272 // If we found the jump target, then we're jumping out of our current scope,
273 // which is perfectly fine.
274 if (TestScope == ToScope) return;
275
276 // Otherwise, scan up the hierarchy.
277 TestScope = Scopes[TestScope].ParentScope;
278 }
279
280 // If we get here, then we know we have invalid code. Diagnose the bad jump,
281 // and then emit a note at each VLA being jumped out of.
282 S.Diag(DiagLoc, JumpDiag);
283
284 // Eliminate the common prefix of the jump and the target. Start by
285 // linearizing both scopes, reversing them as we go.
286 std::vector<unsigned> FromScopes, ToScopes;
287 for (TestScope = FromScope; TestScope != ~0U;
288 TestScope = Scopes[TestScope].ParentScope)
289 FromScopes.push_back(TestScope);
290 for (TestScope = ToScope; TestScope != ~0U;
291 TestScope = Scopes[TestScope].ParentScope)
292 ToScopes.push_back(TestScope);
293
294 // Remove any common entries (such as the top-level function scope).
295 while (!FromScopes.empty() && FromScopes.back() == ToScopes.back()) {
296 FromScopes.pop_back();
297 ToScopes.pop_back();
298 }
299
300 // Emit diagnostics for whatever is left in ToScopes.
301 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
302 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].Diag);
303}
304
305void Sema::DiagnoseInvalidJumps(Stmt *Body) {
306 JumpScopeChecker(Body, *this);
307}