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