1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_RUNTIME_NTH_CALLER_VISITOR_H_
18 #define ART_RUNTIME_NTH_CALLER_VISITOR_H_
19 
20 #include "base/macros.h"
21 #include "art_method.h"
22 #include "base/locks.h"
23 #include "stack.h"
24 
25 namespace art HIDDEN {
26 class Thread;
27 
28 // Walks up the stack 'n' callers, when used with Thread::WalkStack.
29 struct NthCallerVisitor : public StackVisitor {
30   NthCallerVisitor(Thread* thread, size_t n_in, bool include_runtime_and_upcalls = false)
StackVisitorNthCallerVisitor31       : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
32         n(n_in),
33         include_runtime_and_upcalls_(include_runtime_and_upcalls),
34         count(0),
35         caller(nullptr),
36         caller_pc(0) {}
37 
VisitFrameNthCallerVisitor38   bool VisitFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
39     ArtMethod* m = GetMethod();
40     bool do_count = false;
41     if (m == nullptr || m->IsRuntimeMethod()) {
42       // Upcall.
43       do_count = include_runtime_and_upcalls_;
44     } else {
45       do_count = true;
46     }
47     if (do_count) {
48       DCHECK(caller == nullptr);
49       if (count == n) {
50         caller = m;
51         caller_pc = GetCurrentQuickFramePc();
52         return false;
53       }
54       count++;
55     }
56     return true;
57   }
58 
59   const size_t n;
60   const bool include_runtime_and_upcalls_;
61   size_t count;
62   ArtMethod* caller;
63   uintptr_t caller_pc;
64 };
65 
66 }  // namespace art
67 
68 #endif  // ART_RUNTIME_NTH_CALLER_VISITOR_H_
69