1 /*
2  * Copyright (C) 2017 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 #include "jni.h"
18 
19 #include <iostream>
20 
21 #include "android-base/logging.h"
22 
23 #include "arch/context.h"
24 #include "art_method.h"
25 #include "base/macros.h"
26 #include "base/mutex.h"
27 #include "mirror/object-inl.h"
28 #include "mirror/string.h"
29 #include "monitor.h"
30 #include "obj_ptr-inl.h"
31 #include "scoped_thread_state_change-inl.h"
32 #include "stack.h"
33 #include "thread-current-inl.h"
34 
35 namespace art {
36 
Java_Main_testVisitLocks(JNIEnv *,jclass)37 extern "C" JNIEXPORT void JNICALL Java_Main_testVisitLocks(JNIEnv*, jclass) {
38   ScopedObjectAccess soa(Thread::Current());
39 
40   class VisitLocks : public StackVisitor {
41    public:
42     VisitLocks(Thread* thread, Context* context)
43         : StackVisitor(thread, context, StackWalkKind::kIncludeInlinedFrames) {
44     }
45 
46     bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
47       ArtMethod* m = GetMethod();
48 
49       // Ignore runtime methods.
50       if (m == nullptr || m->IsRuntimeMethod()) {
51         return true;
52       }
53 
54       if (m->PrettyMethod() == "void TestSync.run()") {
55         // Interesting frame.
56         Monitor::VisitLocks(this, Callback, nullptr);
57         return false;
58       }
59 
60       return true;
61     }
62 
63     static void Callback(ObjPtr<mirror::Object> obj, void*) REQUIRES_SHARED(Locks::mutator_lock_) {
64       CHECK(obj != nullptr);
65       CHECK(obj->IsString());
66       std::cerr << obj->AsString()->ToModifiedUtf8() << std::endl;
67     }
68   };
69   Context* context = Context::Create();
70   VisitLocks vl(soa.Self(), context);
71   vl.WalkStack();
72   delete context;
73 }
74 
75 }  // namespace art
76