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