jni_env_ext.cc revision 4b8f1ecd3aa5a29ec1463ff88fee9db365f257dc
1/*
2 * Copyright (C) 2011 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_env_ext.h"
18
19#include <algorithm>
20#include <vector>
21
22#include "check_jni.h"
23#include "indirect_reference_table.h"
24#include "java_vm_ext.h"
25#include "jni_internal.h"
26#include "lock_word.h"
27#include "mirror/object-inl.h"
28#include "nth_caller_visitor.h"
29#include "thread-inl.h"
30
31namespace art {
32
33static constexpr size_t kMonitorsInitial = 32;  // Arbitrary.
34static constexpr size_t kMonitorsMax = 4096;  // Arbitrary sanity check.
35
36static constexpr size_t kLocalsInitial = 64;  // Arbitrary.
37
38// Checking "locals" requires the mutator lock, but at creation time we're really only interested
39// in validity, which isn't changing. To avoid grabbing the mutator lock, factored out and tagged
40// with NO_THREAD_SAFETY_ANALYSIS.
41static bool CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS {
42  if (in == nullptr) {
43    return false;
44  }
45  return in->locals.IsValid();
46}
47
48JNIEnvExt* JNIEnvExt::Create(Thread* self_in, JavaVMExt* vm_in) {
49  std::unique_ptr<JNIEnvExt> ret(new JNIEnvExt(self_in, vm_in));
50  if (CheckLocalsValid(ret.get())) {
51    return ret.release();
52  }
53  return nullptr;
54}
55
56JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in)
57    : self(self_in),
58      vm(vm_in),
59      local_ref_cookie(IRT_FIRST_SEGMENT),
60      locals(kLocalsInitial, kLocalsMax, kLocal, false),
61      check_jni(false),
62      critical(0),
63      monitors("monitors", kMonitorsInitial, kMonitorsMax) {
64  functions = unchecked_functions = GetJniNativeInterface();
65  if (vm->IsCheckJniEnabled()) {
66    SetCheckJniEnabled(true);
67  }
68}
69
70JNIEnvExt::~JNIEnvExt() {
71}
72
73jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) {
74  if (obj == nullptr) {
75    return nullptr;
76  }
77  return reinterpret_cast<jobject>(locals.Add(local_ref_cookie, obj));
78}
79
80void JNIEnvExt::DeleteLocalRef(jobject obj) {
81  if (obj != nullptr) {
82    locals.Remove(local_ref_cookie, reinterpret_cast<IndirectRef>(obj));
83  }
84}
85
86void JNIEnvExt::SetCheckJniEnabled(bool enabled) {
87  check_jni = enabled;
88  functions = enabled ? GetCheckJniNativeInterface() : GetJniNativeInterface();
89}
90
91void JNIEnvExt::DumpReferenceTables(std::ostream& os) {
92  locals.Dump(os);
93  monitors.Dump(os);
94}
95
96void JNIEnvExt::PushFrame(int capacity ATTRIBUTE_UNUSED) {
97  // TODO: take 'capacity' into account.
98  stacked_local_ref_cookies.push_back(local_ref_cookie);
99  local_ref_cookie = locals.GetSegmentState();
100}
101
102void JNIEnvExt::PopFrame() {
103  locals.SetSegmentState(local_ref_cookie);
104  local_ref_cookie = stacked_local_ref_cookies.back();
105  stacked_local_ref_cookies.pop_back();
106}
107
108Offset JNIEnvExt::SegmentStateOffset() {
109  return Offset(OFFSETOF_MEMBER(JNIEnvExt, locals) +
110                IndirectReferenceTable::SegmentStateOffset().Int32Value());
111}
112
113// Use some defining part of the caller's frame as the identifying mark for the JNI segment.
114static uintptr_t GetJavaCallFrame(Thread* self) SHARED_REQUIRES(Locks::mutator_lock_) {
115  NthCallerVisitor zeroth_caller(self, 0, false);
116  zeroth_caller.WalkStack();
117  if (zeroth_caller.caller == nullptr) {
118    // No Java code, must be from pure native code.
119    return 0;
120  } else if (zeroth_caller.GetCurrentQuickFrame() == nullptr) {
121    // Shadow frame = interpreter. Use the actual shadow frame's address.
122    DCHECK(zeroth_caller.GetCurrentShadowFrame() != nullptr);
123    return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentShadowFrame());
124  } else {
125    // Quick frame = compiled code. Use the bottom of the frame.
126    return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentQuickFrame());
127  }
128}
129
130void JNIEnvExt::RecordMonitorEnter(jobject obj) {
131  locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self), obj));
132}
133
134static std::string ComputeMonitorDescription(Thread* self,
135                                             jobject obj) SHARED_REQUIRES(Locks::mutator_lock_) {
136  mirror::Object* o = self->DecodeJObject(obj);
137  if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
138      Locks::mutator_lock_->IsExclusiveHeld(self)) {
139    // Getting the identity hashcode here would result in lock inflation and suspension of the
140    // current thread, which isn't safe if this is the only runnable thread.
141    return StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
142                        reinterpret_cast<intptr_t>(o),
143                        PrettyTypeOf(o).c_str());
144  } else {
145    // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
146    // we get the pretty type before we call IdentityHashCode.
147    const std::string pretty_type(PrettyTypeOf(o));
148    return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
149  }
150}
151
152static void RemoveMonitors(Thread* self,
153                           uintptr_t frame,
154                           ReferenceTable* monitors,
155                           std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
156    SHARED_REQUIRES(Locks::mutator_lock_) {
157  auto kept_end = std::remove_if(
158      locked_objects->begin(),
159      locked_objects->end(),
160      [self, frame, monitors](const std::pair<uintptr_t, jobject>& pair)
161          SHARED_REQUIRES(Locks::mutator_lock_) {
162        if (frame == pair.first) {
163          mirror::Object* o = self->DecodeJObject(pair.second);
164          monitors->Remove(o);
165          return true;
166        }
167        return false;
168      });
169  locked_objects->erase(kept_end, locked_objects->end());
170}
171
172void JNIEnvExt::CheckMonitorRelease(jobject obj) {
173  uintptr_t current_frame = GetJavaCallFrame(self);
174  std::pair<uintptr_t, jobject> exact_pair = std::make_pair(current_frame, obj);
175  auto it = std::find(locked_objects_.begin(), locked_objects_.end(), exact_pair);
176  bool will_abort = false;
177  if (it != locked_objects_.end()) {
178    locked_objects_.erase(it);
179  } else {
180    // Check whether this monitor was locked in another JNI "session."
181    mirror::Object* mirror_obj = self->DecodeJObject(obj);
182    for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
183      if (self->DecodeJObject(pair.second) == mirror_obj) {
184        std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
185        vm->JniAbortF("<JNI MonitorExit>",
186                      "Unlocking monitor that wasn't locked here: %s",
187                      monitor_descr.c_str());
188        will_abort = true;
189        break;
190      }
191    }
192  }
193
194  // When we abort, also make sure that any locks from the current "session" are removed from
195  // the monitors table, otherwise we may visit local objects in GC during abort (which won't be
196  // valid anymore).
197  if (will_abort) {
198    RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
199  }
200}
201
202void JNIEnvExt::CheckNoHeldMonitors() {
203  uintptr_t current_frame = GetJavaCallFrame(self);
204  // The locked_objects_ are grouped by their stack frame component, as this enforces structured
205  // locking, and the groups form a stack. So the current frame entries are at the end. Check
206  // whether the vector is empty, and when there are elements, whether the last element belongs
207  // to this call - this signals that there are unlocked monitors.
208  if (!locked_objects_.empty()) {
209    std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
210    if (pair.first == current_frame) {
211      std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
212      vm->JniAbortF("<JNI End>",
213                    "Still holding a locked object on JNI end: %s",
214                    monitor_descr.c_str());
215      // When we abort, also make sure that any locks from the current "session" are removed from
216      // the monitors table, otherwise we may visit local objects in GC during abort.
217      RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
218    } else if (kIsDebugBuild) {
219      // Make sure there are really no other entries and our checking worked as expected.
220      for (std::pair<uintptr_t, jobject>& check_pair : locked_objects_) {
221        CHECK_NE(check_pair.first, current_frame);
222      }
223    }
224  }
225}
226
227}  // namespace art
228