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
GotoScope__anonc436f3760111::JumpScopeChecker::GotoScope60 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
JumpScopeChecker(Stmt * Body,Sema & s)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.
GetDeepestCommonScope(unsigned A,unsigned B)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.
GetDiagForGotoScopeDecl(Sema & S,const Decl * D)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 case QualType::DK_objc_weak_lifetime:
151 return ScopePair(diag::note_protected_by_objc_ownership,
152 diag::note_exits_objc_ownership);
153
154 case QualType::DK_cxx_destructor:
155 OutDiag = diag::note_exits_dtor;
156 break;
157
158 case QualType::DK_none:
159 break;
160 }
161 }
162
163 const Expr *Init = VD->getInit();
164 if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
165 // C++11 [stmt.dcl]p3:
166 // A program that jumps from a point where a variable with automatic
167 // storage duration is not in scope to a point where it is in scope
168 // is ill-formed unless the variable has scalar type, class type with
169 // a trivial default constructor and a trivial destructor, a
170 // cv-qualified version of one of these types, or an array of one of
171 // the preceding types and is declared without an initializer.
172
173 // C++03 [stmt.dcl.p3:
174 // A program that jumps from a point where a local variable
175 // with automatic storage duration is not in scope to a point
176 // where it is in scope is ill-formed unless the variable has
177 // POD type and is declared without an initializer.
178
179 InDiag = diag::note_protected_by_variable_init;
180
181 // For a variable of (array of) class type declared without an
182 // initializer, we will have call-style initialization and the initializer
183 // will be the CXXConstructExpr with no intervening nodes.
184 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
185 const CXXConstructorDecl *Ctor = CCE->getConstructor();
186 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
187 VD->getInitStyle() == VarDecl::CallInit) {
188 if (OutDiag)
189 InDiag = diag::note_protected_by_variable_nontriv_destructor;
190 else if (!Ctor->getParent()->isPOD())
191 InDiag = diag::note_protected_by_variable_non_pod;
192 else
193 InDiag = 0;
194 }
195 }
196 }
197
198 return ScopePair(InDiag, OutDiag);
199 }
200
201 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
202 if (TD->getUnderlyingType()->isVariablyModifiedType())
203 return ScopePair(isa<TypedefDecl>(TD)
204 ? diag::note_protected_by_vla_typedef
205 : diag::note_protected_by_vla_type_alias,
206 0);
207 }
208
209 return ScopePair(0U, 0U);
210 }
211
212 /// \brief Build scope information for a declaration that is part of a DeclStmt.
BuildScopeInformation(Decl * D,unsigned & ParentScope)213 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
214 // If this decl causes a new scope, push and switch to it.
215 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
216 if (Diags.first || Diags.second) {
217 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
218 D->getLocation()));
219 ParentScope = Scopes.size()-1;
220 }
221
222 // If the decl has an initializer, walk it with the potentially new
223 // scope we just installed.
224 if (VarDecl *VD = dyn_cast<VarDecl>(D))
225 if (Expr *Init = VD->getInit())
226 BuildScopeInformation(Init, ParentScope);
227 }
228
229 /// \brief Build scope information for a captured block literal variables.
BuildScopeInformation(VarDecl * D,const BlockDecl * BDecl,unsigned & ParentScope)230 void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
231 const BlockDecl *BDecl,
232 unsigned &ParentScope) {
233 // exclude captured __block variables; there's no destructor
234 // associated with the block literal for them.
235 if (D->hasAttr<BlocksAttr>())
236 return;
237 QualType T = D->getType();
238 QualType::DestructionKind destructKind = T.isDestructedType();
239 if (destructKind != QualType::DK_none) {
240 std::pair<unsigned,unsigned> Diags;
241 switch (destructKind) {
242 case QualType::DK_cxx_destructor:
243 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
244 diag::note_exits_block_captures_cxx_obj);
245 break;
246 case QualType::DK_objc_strong_lifetime:
247 Diags = ScopePair(diag::note_enters_block_captures_strong,
248 diag::note_exits_block_captures_strong);
249 break;
250 case QualType::DK_objc_weak_lifetime:
251 Diags = ScopePair(diag::note_enters_block_captures_weak,
252 diag::note_exits_block_captures_weak);
253 break;
254 case QualType::DK_none:
255 llvm_unreachable("non-lifetime captured variable");
256 }
257 SourceLocation Loc = D->getLocation();
258 if (Loc.isInvalid())
259 Loc = BDecl->getLocation();
260 Scopes.push_back(GotoScope(ParentScope,
261 Diags.first, Diags.second, Loc));
262 ParentScope = Scopes.size()-1;
263 }
264 }
265
266 /// BuildScopeInformation - The statements from CI to CE are known to form a
267 /// coherent VLA scope with a specified parent node. Walk through the
268 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
269 /// walking the AST as needed.
BuildScopeInformation(Stmt * S,unsigned & origParentScope)270 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
271 // If this is a statement, rather than an expression, scopes within it don't
272 // propagate out into the enclosing scope. Otherwise we have to worry
273 // about block literals, which have the lifetime of their enclosing statement.
274 unsigned independentParentScope = origParentScope;
275 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
276 ? origParentScope : independentParentScope);
277
278 bool SkipFirstSubStmt = false;
279
280 // If we found a label, remember that it is in ParentScope scope.
281 switch (S->getStmtClass()) {
282 case Stmt::AddrLabelExprClass:
283 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
284 break;
285
286 case Stmt::IndirectGotoStmtClass:
287 // "goto *&&lbl;" is a special case which we treat as equivalent
288 // to a normal goto. In addition, we don't calculate scope in the
289 // operand (to avoid recording the address-of-label use), which
290 // works only because of the restricted set of expressions which
291 // we detect as constant targets.
292 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
293 LabelAndGotoScopes[S] = ParentScope;
294 Jumps.push_back(S);
295 return;
296 }
297
298 LabelAndGotoScopes[S] = ParentScope;
299 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
300 break;
301
302 case Stmt::SwitchStmtClass:
303 // Evaluate the condition variable before entering the scope of the switch
304 // statement.
305 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
306 BuildScopeInformation(Var, ParentScope);
307 SkipFirstSubStmt = true;
308 }
309 // Fall through
310
311 case Stmt::GotoStmtClass:
312 // Remember both what scope a goto is in as well as the fact that we have
313 // it. This makes the second scan not have to walk the AST again.
314 LabelAndGotoScopes[S] = ParentScope;
315 Jumps.push_back(S);
316 break;
317
318 case Stmt::CXXTryStmtClass: {
319 CXXTryStmt *TS = cast<CXXTryStmt>(S);
320 unsigned newParentScope;
321 Scopes.push_back(GotoScope(ParentScope,
322 diag::note_protected_by_cxx_try,
323 diag::note_exits_cxx_try,
324 TS->getSourceRange().getBegin()));
325 if (Stmt *TryBlock = TS->getTryBlock())
326 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
327
328 // Jump from the catch into the try is not allowed either.
329 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
330 CXXCatchStmt *CS = TS->getHandler(I);
331 Scopes.push_back(GotoScope(ParentScope,
332 diag::note_protected_by_cxx_catch,
333 diag::note_exits_cxx_catch,
334 CS->getSourceRange().getBegin()));
335 BuildScopeInformation(CS->getHandlerBlock(),
336 (newParentScope = Scopes.size()-1));
337 }
338 return;
339 }
340
341 default:
342 break;
343 }
344
345 for (Stmt::child_range CI = S->children(); CI; ++CI) {
346 if (SkipFirstSubStmt) {
347 SkipFirstSubStmt = false;
348 continue;
349 }
350
351 Stmt *SubStmt = *CI;
352 if (!SubStmt) continue;
353
354 // Cases, labels, and defaults aren't "scope parents". It's also
355 // important to handle these iteratively instead of recursively in
356 // order to avoid blowing out the stack.
357 while (true) {
358 Stmt *Next;
359 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
360 Next = CS->getSubStmt();
361 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
362 Next = DS->getSubStmt();
363 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
364 Next = LS->getSubStmt();
365 else
366 break;
367
368 LabelAndGotoScopes[SubStmt] = ParentScope;
369 SubStmt = Next;
370 }
371
372 // If this is a declstmt with a VLA definition, it defines a scope from here
373 // to the end of the containing context.
374 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
375 // The decl statement creates a scope if any of the decls in it are VLAs
376 // or have the cleanup attribute.
377 for (auto *I : DS->decls())
378 BuildScopeInformation(I, ParentScope);
379 continue;
380 }
381 // Disallow jumps into any part of an @try statement by pushing a scope and
382 // walking all sub-stmts in that scope.
383 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
384 unsigned newParentScope;
385 // Recursively walk the AST for the @try part.
386 Scopes.push_back(GotoScope(ParentScope,
387 diag::note_protected_by_objc_try,
388 diag::note_exits_objc_try,
389 AT->getAtTryLoc()));
390 if (Stmt *TryPart = AT->getTryBody())
391 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
392
393 // Jump from the catch to the finally or try is not valid.
394 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
395 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
396 Scopes.push_back(GotoScope(ParentScope,
397 diag::note_protected_by_objc_catch,
398 diag::note_exits_objc_catch,
399 AC->getAtCatchLoc()));
400 // @catches are nested and it isn't
401 BuildScopeInformation(AC->getCatchBody(),
402 (newParentScope = Scopes.size()-1));
403 }
404
405 // Jump from the finally to the try or catch is not valid.
406 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
407 Scopes.push_back(GotoScope(ParentScope,
408 diag::note_protected_by_objc_finally,
409 diag::note_exits_objc_finally,
410 AF->getAtFinallyLoc()));
411 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
412 }
413
414 continue;
415 }
416
417 unsigned newParentScope;
418 // Disallow jumps into the protected statement of an @synchronized, but
419 // allow jumps into the object expression it protects.
420 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
421 // Recursively walk the AST for the @synchronized object expr, it is
422 // evaluated in the normal scope.
423 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
424
425 // Recursively walk the AST for the @synchronized part, protected by a new
426 // scope.
427 Scopes.push_back(GotoScope(ParentScope,
428 diag::note_protected_by_objc_synchronized,
429 diag::note_exits_objc_synchronized,
430 AS->getAtSynchronizedLoc()));
431 BuildScopeInformation(AS->getSynchBody(),
432 (newParentScope = Scopes.size()-1));
433 continue;
434 }
435
436 // Disallow jumps into the protected statement of an @autoreleasepool.
437 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
438 // Recursively walk the AST for the @autoreleasepool part, protected by a new
439 // scope.
440 Scopes.push_back(GotoScope(ParentScope,
441 diag::note_protected_by_objc_autoreleasepool,
442 diag::note_exits_objc_autoreleasepool,
443 AS->getAtLoc()));
444 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
445 continue;
446 }
447
448 // Disallow jumps past full-expressions that use blocks with
449 // non-trivial cleanups of their captures. This is theoretically
450 // implementable but a lot of work which we haven't felt up to doing.
451 if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) {
452 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
453 const BlockDecl *BDecl = EWC->getObject(i);
454 for (const auto &CI : BDecl->captures()) {
455 VarDecl *variable = CI.getVariable();
456 BuildScopeInformation(variable, BDecl, ParentScope);
457 }
458 }
459 }
460
461 // Disallow jumps out of scopes containing temporaries lifetime-extended to
462 // automatic storage duration.
463 if (MaterializeTemporaryExpr *MTE =
464 dyn_cast<MaterializeTemporaryExpr>(SubStmt)) {
465 if (MTE->getStorageDuration() == SD_Automatic) {
466 SmallVector<const Expr *, 4> CommaLHS;
467 SmallVector<SubobjectAdjustment, 4> Adjustments;
468 const Expr *ExtendedObject =
469 MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
470 CommaLHS, Adjustments);
471 if (ExtendedObject->getType().isDestructedType()) {
472 Scopes.push_back(GotoScope(ParentScope, 0,
473 diag::note_exits_temporary_dtor,
474 ExtendedObject->getExprLoc()));
475 ParentScope = Scopes.size()-1;
476 }
477 }
478 }
479
480 // Recursively walk the AST.
481 BuildScopeInformation(SubStmt, ParentScope);
482 }
483 }
484
485 /// VerifyJumps - Verify each element of the Jumps array to see if they are
486 /// valid, emitting diagnostics if not.
VerifyJumps()487 void JumpScopeChecker::VerifyJumps() {
488 while (!Jumps.empty()) {
489 Stmt *Jump = Jumps.pop_back_val();
490
491 // With a goto,
492 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
493 // The label may not have a statement if it's coming from inline MS ASM.
494 if (GS->getLabel()->getStmt()) {
495 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
496 diag::err_goto_into_protected_scope,
497 diag::ext_goto_into_protected_scope,
498 diag::warn_cxx98_compat_goto_into_protected_scope);
499 }
500 CheckGotoStmt(GS);
501 continue;
502 }
503
504 // We only get indirect gotos here when they have a constant target.
505 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
506 LabelDecl *Target = IGS->getConstantTarget();
507 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
508 diag::err_goto_into_protected_scope,
509 diag::ext_goto_into_protected_scope,
510 diag::warn_cxx98_compat_goto_into_protected_scope);
511 continue;
512 }
513
514 SwitchStmt *SS = cast<SwitchStmt>(Jump);
515 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
516 SC = SC->getNextSwitchCase()) {
517 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
518 continue;
519 SourceLocation Loc;
520 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
521 Loc = CS->getLocStart();
522 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
523 Loc = DS->getLocStart();
524 else
525 Loc = SC->getLocStart();
526 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
527 diag::warn_cxx98_compat_switch_into_protected_scope);
528 }
529 }
530 }
531
532 /// VerifyIndirectJumps - Verify whether any possible indirect jump
533 /// might cross a protection boundary. Unlike direct jumps, indirect
534 /// jumps count cleanups as protection boundaries: since there's no
535 /// way to know where the jump is going, we can't implicitly run the
536 /// right cleanups the way we can with direct jumps.
537 ///
538 /// Thus, an indirect jump is "trivial" if it bypasses no
539 /// initializations and no teardowns. More formally, an indirect jump
540 /// from A to B is trivial if the path out from A to DCA(A,B) is
541 /// trivial and the path in from DCA(A,B) to B is trivial, where
542 /// DCA(A,B) is the deepest common ancestor of A and B.
543 /// Jump-triviality is transitive but asymmetric.
544 ///
545 /// A path in is trivial if none of the entered scopes have an InDiag.
546 /// A path out is trivial is none of the exited scopes have an OutDiag.
547 ///
548 /// Under these definitions, this function checks that the indirect
549 /// jump between A and B is trivial for every indirect goto statement A
550 /// and every label B whose address was taken in the function.
VerifyIndirectJumps()551 void JumpScopeChecker::VerifyIndirectJumps() {
552 if (IndirectJumps.empty()) return;
553
554 // If there aren't any address-of-label expressions in this function,
555 // complain about the first indirect goto.
556 if (IndirectJumpTargets.empty()) {
557 S.Diag(IndirectJumps[0]->getGotoLoc(),
558 diag::err_indirect_goto_without_addrlabel);
559 return;
560 }
561
562 // Collect a single representative of every scope containing an
563 // indirect goto. For most code bases, this substantially cuts
564 // down on the number of jump sites we'll have to consider later.
565 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
566 SmallVector<JumpScope, 32> JumpScopes;
567 {
568 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
569 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
570 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
571 IndirectGotoStmt *IG = *I;
572 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
573 continue;
574 unsigned IGScope = LabelAndGotoScopes[IG];
575 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
576 if (!Entry) Entry = IG;
577 }
578 JumpScopes.reserve(JumpScopesMap.size());
579 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
580 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
581 JumpScopes.push_back(*I);
582 }
583
584 // Collect a single representative of every scope containing a
585 // label whose address was taken somewhere in the function.
586 // For most code bases, there will be only one such scope.
587 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
588 for (SmallVectorImpl<LabelDecl*>::iterator
589 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
590 I != E; ++I) {
591 LabelDecl *TheLabel = *I;
592 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
593 continue;
594 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
595 LabelDecl *&Target = TargetScopes[LabelScope];
596 if (!Target) Target = TheLabel;
597 }
598
599 // For each target scope, make sure it's trivially reachable from
600 // every scope containing a jump site.
601 //
602 // A path between scopes always consists of exitting zero or more
603 // scopes, then entering zero or more scopes. We build a set of
604 // of scopes S from which the target scope can be trivially
605 // entered, then verify that every jump scope can be trivially
606 // exitted to reach a scope in S.
607 llvm::BitVector Reachable(Scopes.size(), false);
608 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
609 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
610 unsigned TargetScope = TI->first;
611 LabelDecl *TargetLabel = TI->second;
612
613 Reachable.reset();
614
615 // Mark all the enclosing scopes from which you can safely jump
616 // into the target scope. 'Min' will end up being the index of
617 // the shallowest such scope.
618 unsigned Min = TargetScope;
619 while (true) {
620 Reachable.set(Min);
621
622 // Don't go beyond the outermost scope.
623 if (Min == 0) break;
624
625 // Stop if we can't trivially enter the current scope.
626 if (Scopes[Min].InDiag) break;
627
628 Min = Scopes[Min].ParentScope;
629 }
630
631 // Walk through all the jump sites, checking that they can trivially
632 // reach this label scope.
633 for (SmallVectorImpl<JumpScope>::iterator
634 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
635 unsigned Scope = I->first;
636
637 // Walk out the "scope chain" for this scope, looking for a scope
638 // we've marked reachable. For well-formed code this amortizes
639 // to O(JumpScopes.size() / Scopes.size()): we only iterate
640 // when we see something unmarked, and in well-formed code we
641 // mark everything we iterate past.
642 bool IsReachable = false;
643 while (true) {
644 if (Reachable.test(Scope)) {
645 // If we find something reachable, mark all the scopes we just
646 // walked through as reachable.
647 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
648 Reachable.set(S);
649 IsReachable = true;
650 break;
651 }
652
653 // Don't walk out if we've reached the top-level scope or we've
654 // gotten shallower than the shallowest reachable scope.
655 if (Scope == 0 || Scope < Min) break;
656
657 // Don't walk out through an out-diagnostic.
658 if (Scopes[Scope].OutDiag) break;
659
660 Scope = Scopes[Scope].ParentScope;
661 }
662
663 // Only diagnose if we didn't find something.
664 if (IsReachable) continue;
665
666 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
667 }
668 }
669 }
670
671 /// Return true if a particular error+note combination must be downgraded to a
672 /// warning in Microsoft mode.
IsMicrosoftJumpWarning(unsigned JumpDiag,unsigned InDiagNote)673 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
674 return (JumpDiag == diag::err_goto_into_protected_scope &&
675 (InDiagNote == diag::note_protected_by_variable_init ||
676 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
677 }
678
679 /// Return true if a particular note should be downgraded to a compatibility
680 /// warning in C++11 mode.
IsCXX98CompatWarning(Sema & S,unsigned InDiagNote)681 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
682 return S.getLangOpts().CPlusPlus11 &&
683 InDiagNote == diag::note_protected_by_variable_non_pod;
684 }
685
686 /// Produce primary diagnostic for an indirect jump statement.
DiagnoseIndirectJumpStmt(Sema & S,IndirectGotoStmt * Jump,LabelDecl * Target,bool & Diagnosed)687 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
688 LabelDecl *Target, bool &Diagnosed) {
689 if (Diagnosed)
690 return;
691 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
692 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
693 Diagnosed = true;
694 }
695
696 /// Produce note diagnostics for a jump into a protected scope.
NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes)697 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
698 if (CHECK_PERMISSIVE(ToScopes.empty()))
699 return;
700 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
701 if (Scopes[ToScopes[I]].InDiag)
702 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
703 }
704
705 /// Diagnose an indirect jump which is known to cross scopes.
DiagnoseIndirectJump(IndirectGotoStmt * Jump,unsigned JumpScope,LabelDecl * Target,unsigned TargetScope)706 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
707 unsigned JumpScope,
708 LabelDecl *Target,
709 unsigned TargetScope) {
710 if (CHECK_PERMISSIVE(JumpScope == TargetScope))
711 return;
712
713 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
714 bool Diagnosed = false;
715
716 // Walk out the scope chain until we reach the common ancestor.
717 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
718 if (Scopes[I].OutDiag) {
719 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
720 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
721 }
722
723 SmallVector<unsigned, 10> ToScopesCXX98Compat;
724
725 // Now walk into the scopes containing the label whose address was taken.
726 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
727 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
728 ToScopesCXX98Compat.push_back(I);
729 else if (Scopes[I].InDiag) {
730 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
731 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
732 }
733
734 // Diagnose this jump if it would be ill-formed in C++98.
735 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
736 S.Diag(Jump->getGotoLoc(),
737 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
738 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
739 NoteJumpIntoScopes(ToScopesCXX98Compat);
740 }
741 }
742
743 /// CheckJump - Validate that the specified jump statement is valid: that it is
744 /// jumping within or out of its current scope, not into a deeper one.
CheckJump(Stmt * From,Stmt * To,SourceLocation DiagLoc,unsigned JumpDiagError,unsigned JumpDiagWarning,unsigned JumpDiagCXX98Compat)745 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
746 unsigned JumpDiagError, unsigned JumpDiagWarning,
747 unsigned JumpDiagCXX98Compat) {
748 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
749 return;
750 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
751 return;
752
753 unsigned FromScope = LabelAndGotoScopes[From];
754 unsigned ToScope = LabelAndGotoScopes[To];
755
756 // Common case: exactly the same scope, which is fine.
757 if (FromScope == ToScope) return;
758
759 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
760
761 // It's okay to jump out from a nested scope.
762 if (CommonScope == ToScope) return;
763
764 // Pull out (and reverse) any scopes we might need to diagnose skipping.
765 SmallVector<unsigned, 10> ToScopesCXX98Compat;
766 SmallVector<unsigned, 10> ToScopesError;
767 SmallVector<unsigned, 10> ToScopesWarning;
768 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
769 if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
770 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
771 ToScopesWarning.push_back(I);
772 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
773 ToScopesCXX98Compat.push_back(I);
774 else if (Scopes[I].InDiag)
775 ToScopesError.push_back(I);
776 }
777
778 // Handle warnings.
779 if (!ToScopesWarning.empty()) {
780 S.Diag(DiagLoc, JumpDiagWarning);
781 NoteJumpIntoScopes(ToScopesWarning);
782 }
783
784 // Handle errors.
785 if (!ToScopesError.empty()) {
786 S.Diag(DiagLoc, JumpDiagError);
787 NoteJumpIntoScopes(ToScopesError);
788 }
789
790 // Handle -Wc++98-compat warnings if the jump is well-formed.
791 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
792 S.Diag(DiagLoc, JumpDiagCXX98Compat);
793 NoteJumpIntoScopes(ToScopesCXX98Compat);
794 }
795 }
796
CheckGotoStmt(GotoStmt * GS)797 void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
798 if (GS->getLabel()->isMSAsmLabel()) {
799 S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
800 << GS->getLabel()->getIdentifier();
801 S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
802 << GS->getLabel()->getIdentifier();
803 }
804 }
805
DiagnoseInvalidJumps(Stmt * Body)806 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
807 (void)JumpScopeChecker(Body, *this);
808 }
809