jni_env_ext.cc revision 5f4a09a54eed55de89e194780214a2acfd2cb431
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) {
97  UNUSED(capacity);  // cpplint gets confused with (int) and thinks its a cast.
98  // TODO: take 'capacity' into account.
99  stacked_local_ref_cookies.push_back(local_ref_cookie);
100  local_ref_cookie = locals.GetSegmentState();
101}
102
103void JNIEnvExt::PopFrame() {
104  locals.SetSegmentState(local_ref_cookie);
105  local_ref_cookie = stacked_local_ref_cookies.back();
106  stacked_local_ref_cookies.pop_back();
107}
108
109Offset JNIEnvExt::SegmentStateOffset() {
110  return Offset(OFFSETOF_MEMBER(JNIEnvExt, locals) +
111                IndirectReferenceTable::SegmentStateOffset().Int32Value());
112}
113
114// Use some defining part of the caller's frame as the identifying mark for the JNI segment.
115static uintptr_t GetJavaCallFrame(Thread* self) SHARED_REQUIRES(Locks::mutator_lock_) {
116  NthCallerVisitor zeroth_caller(self, 0, false);
117  zeroth_caller.WalkStack();
118  if (zeroth_caller.caller == nullptr) {
119    // No Java code, must be from pure native code.
120    return 0;
121  } else if (zeroth_caller.GetCurrentQuickFrame() == nullptr) {
122    // Shadow frame = interpreter. Use the actual shadow frame's address.
123    DCHECK(zeroth_caller.GetCurrentShadowFrame() != nullptr);
124    return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentShadowFrame());
125  } else {
126    // Quick frame = compiled code. Use the bottom of the frame.
127    return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentQuickFrame());
128  }
129}
130
131void JNIEnvExt::RecordMonitorEnter(jobject obj) {
132  locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self), obj));
133}
134
135static std::string ComputeMonitorDescription(Thread* self,
136                                             jobject obj) SHARED_REQUIRES(Locks::mutator_lock_) {
137  mirror::Object* o = self->DecodeJObject(obj);
138  if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
139      Locks::mutator_lock_->IsExclusiveHeld(self)) {
140    // Getting the identity hashcode here would result in lock inflation and suspension of the
141    // current thread, which isn't safe if this is the only runnable thread.
142    return StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
143                        reinterpret_cast<intptr_t>(o),
144                        PrettyTypeOf(o).c_str());
145  } else {
146    // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
147    // we get the pretty type before we call IdentityHashCode.
148    const std::string pretty_type(PrettyTypeOf(o));
149    return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
150  }
151}
152
153static void RemoveMonitors(Thread* self,
154                           uintptr_t frame,
155                           ReferenceTable* monitors,
156                           std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
157    SHARED_REQUIRES(Locks::mutator_lock_) {
158  auto kept_end = std::remove_if(
159      locked_objects->begin(),
160      locked_objects->end(),
161      [self, frame, monitors](const std::pair<uintptr_t, jobject>& pair)
162          SHARED_REQUIRES(Locks::mutator_lock_) {
163        if (frame == pair.first) {
164          mirror::Object* o = self->DecodeJObject(pair.second);
165          monitors->Remove(o);
166          return true;
167        }
168        return false;
169      });
170  locked_objects->erase(kept_end, locked_objects->end());
171}
172
173void JNIEnvExt::CheckMonitorRelease(jobject obj) {
174  uintptr_t current_frame = GetJavaCallFrame(self);
175  std::pair<uintptr_t, jobject> exact_pair = std::make_pair(current_frame, obj);
176  auto it = std::find(locked_objects_.begin(), locked_objects_.end(), exact_pair);
177  bool will_abort = false;
178  if (it != locked_objects_.end()) {
179    locked_objects_.erase(it);
180  } else {
181    // Check whether this monitor was locked in another JNI "session."
182    mirror::Object* mirror_obj = self->DecodeJObject(obj);
183    for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
184      if (self->DecodeJObject(pair.second) == mirror_obj) {
185        std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
186        vm->JniAbortF("<JNI MonitorExit>",
187                      "Unlocking monitor that wasn't locked here: %s",
188                      monitor_descr.c_str());
189        will_abort = true;
190        break;
191      }
192    }
193  }
194
195  // When we abort, also make sure that any locks from the current "session" are removed from
196  // the monitors table, otherwise we may visit local objects in GC during abort (which won't be
197  // valid anymore).
198  if (will_abort) {
199    RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
200  }
201}
202
203void JNIEnvExt::CheckNoHeldMonitors() {
204  uintptr_t current_frame = GetJavaCallFrame(self);
205  // The locked_objects_ are grouped by their stack frame component, as this enforces structured
206  // locking, and the groups form a stack. So the current frame entries are at the end. Check
207  // whether the vector is empty, and when there are elements, whether the last element belongs
208  // to this call - this signals that there are unlocked monitors.
209  if (!locked_objects_.empty()) {
210    std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
211    if (pair.first == current_frame) {
212      std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
213      vm->JniAbortF("<JNI End>",
214                    "Still holding a locked object on JNI end: %s",
215                    monitor_descr.c_str());
216      // When we abort, also make sure that any locks from the current "session" are removed from
217      // the monitors table, otherwise we may visit local objects in GC during abort.
218      RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
219    } else if (kIsDebugBuild) {
220      // Make sure there are really no other entries and our checking worked as expected.
221      for (std::pair<uintptr_t, jobject>& check_pair : locked_objects_) {
222        CHECK_NE(check_pair.first, current_frame);
223      }
224    }
225  }
226}
227
228}  // namespace art
229