blob: fbe678bea251f49470e781ac69f191eb5e3394be [file] [log] [blame]
Elliott Hughes6c1a3942011-08-17 15:00:06 -07001/*
2 * Copyright (C) 2009 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
Alex Light3d9c0d92020-09-09 14:16:08 -070017#include "base/bit_utils.h"
18#include "base/globals.h"
Mathieu Chartierc56057e2014-05-04 13:18:58 -070019#include "indirect_reference_table-inl.h"
20
David Sehr1ce2b3b2018-04-05 11:02:03 -070021#include "base/mutator_locked_dumpable.h"
Mathieu Chartierdabdc0f2016-03-04 14:58:03 -080022#include "base/systrace.h"
David Sehrc431b9d2018-03-02 12:01:51 -080023#include "base/utils.h"
Alex Light3d9c0d92020-09-09 14:16:08 -070024#include "indirect_reference_table.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010025#include "jni/java_vm_ext.h"
26#include "jni/jni_internal.h"
Roland Levillain2e8aa8d2018-09-26 18:13:19 +010027#include "mirror/object-inl.h"
Mathieu Chartierff6d8cf2015-06-02 13:40:12 -070028#include "nth_caller_visitor.h"
Elliott Hughes6c1a3942011-08-17 15:00:06 -070029#include "reference_table.h"
Elliott Hughesa2501992011-08-26 19:39:54 -070030#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070031#include "scoped_thread_state_change-inl.h"
Ian Rogers5a7a74a2011-09-26 16:32:29 -070032#include "thread.h"
Elliott Hughes6c1a3942011-08-17 15:00:06 -070033
34#include <cstdlib>
35
36namespace art {
37
Mathieu Chartier2ada67b2015-07-30 11:41:04 -070038static constexpr bool kDumpStackOnNonLocalReference = false;
Andreas Gampee03662b2016-10-13 17:12:56 -070039static constexpr bool kDebugIRT = false;
Mathieu Chartier2ada67b2015-07-30 11:41:04 -070040
Andreas Gampe0ece10d2017-05-31 20:09:28 -070041// Maximum table size we allow.
42static constexpr size_t kMaxTableSizeInBytes = 128 * MB;
43
Andreas Gampef1e86302016-10-03 11:42:31 -070044const char* GetIndirectRefKindString(const IndirectRefKind& kind) {
45 switch (kind) {
Vladimir Markocedec9d2021-02-08 16:16:13 +000046 case kJniTransitionOrInvalid:
47 return "JniTransitionOrInvalid";
Andreas Gampef1e86302016-10-03 11:42:31 -070048 case kLocal:
49 return "Local";
50 case kGlobal:
51 return "Global";
52 case kWeakGlobal:
53 return "WeakGlobal";
54 }
55 return "IndirectRefKind Error";
56}
57
Andreas Gampef1e86302016-10-03 11:42:31 -070058void IndirectReferenceTable::AbortIfNoCheckJNI(const std::string& msg) {
Elliott Hughesa2501992011-08-26 19:39:54 -070059 // If -Xcheck:jni is on, it'll give a more detailed error before aborting.
Ian Rogers68d8b422014-07-17 11:09:10 -070060 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
61 if (!vm->IsCheckJniEnabled()) {
Elliott Hughesa2501992011-08-26 19:39:54 -070062 // Otherwise, we want to abort rather than hand back a bad reference.
Andreas Gampef1e86302016-10-03 11:42:31 -070063 LOG(FATAL) << msg;
64 } else {
65 LOG(ERROR) << msg;
Elliott Hughesa2501992011-08-26 19:39:54 -070066 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -070067}
68
Hans Boehm4dcac362021-09-23 12:26:04 -070069// Mmap an "indirect ref table region. Table_bytes is a multiple of a page size.
70static inline MemMap NewIRTMap(size_t table_bytes, std::string* error_msg) {
71 MemMap result = MemMap::MapAnonymous("indirect ref table",
72 table_bytes,
73 PROT_READ | PROT_WRITE,
74 /*low_4gb=*/ false,
75 error_msg);
76 if (!result.IsValid() && error_msg->empty()) {
77 *error_msg = "Unable to map memory for indirect ref table";
78 }
79 return result;
80}
81
82SmallIrtAllocator::SmallIrtAllocator()
Hans Boehm808d8cc2021-10-29 14:57:37 -070083 : small_irt_freelist_(nullptr), lock_("Small IRT table lock", LockLevel::kGenericBottomLock) {
Hans Boehm4dcac362021-09-23 12:26:04 -070084}
85
86// Allocate an IRT table for kSmallIrtEntries.
87IrtEntry* SmallIrtAllocator::Allocate(std::string* error_msg) {
88 MutexLock lock(Thread::Current(), lock_);
89 if (small_irt_freelist_ == nullptr) {
90 // Refill.
91 MemMap map = NewIRTMap(kPageSize, error_msg);
92 if (map.IsValid()) {
93 small_irt_freelist_ = reinterpret_cast<IrtEntry*>(map.Begin());
94 for (uint8_t* p = map.Begin(); p + kInitialIrtBytes < map.End(); p += kInitialIrtBytes) {
95 *reinterpret_cast<IrtEntry**>(p) = reinterpret_cast<IrtEntry*>(p + kInitialIrtBytes);
96 }
97 shared_irt_maps_.emplace_back(std::move(map));
98 }
99 }
100 if (small_irt_freelist_ == nullptr) {
101 return nullptr;
102 }
103 IrtEntry* result = small_irt_freelist_;
104 small_irt_freelist_ = *reinterpret_cast<IrtEntry**>(small_irt_freelist_);
105 // Clear pointer in first entry.
106 new(result) IrtEntry();
107 return result;
108}
109
110void SmallIrtAllocator::Deallocate(IrtEntry* unneeded) {
111 MutexLock lock(Thread::Current(), lock_);
112 *reinterpret_cast<IrtEntry**>(unneeded) = small_irt_freelist_;
113 small_irt_freelist_ = unneeded;
114}
115
Andreas Gampea8e3b862016-10-17 20:12:52 -0700116IndirectReferenceTable::IndirectReferenceTable(size_t max_count,
117 IndirectRefKind desired_kind,
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700118 ResizableCapacity resizable,
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100119 std::string* error_msg)
Andreas Gampee03662b2016-10-13 17:12:56 -0700120 : segment_state_(kIRTFirstSegment),
Hans Boehm4dcac362021-09-23 12:26:04 -0700121 table_(nullptr),
Andreas Gampee03662b2016-10-13 17:12:56 -0700122 kind_(desired_kind),
123 max_entries_(max_count),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700124 current_num_holes_(0),
125 resizable_(resizable) {
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100126 CHECK(error_msg != nullptr);
Vladimir Markocedec9d2021-02-08 16:16:13 +0000127 CHECK_NE(desired_kind, kJniTransitionOrInvalid);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700128
Andreas Gampe0ece10d2017-05-31 20:09:28 -0700129 // Overflow and maximum check.
130 CHECK_LE(max_count, kMaxTableSizeInBytes / sizeof(IrtEntry));
131
Hans Boehm4dcac362021-09-23 12:26:04 -0700132 if (max_entries_ <= kSmallIrtEntries) {
133 table_ = Runtime::Current()->GetSmallIrtAllocator()->Allocate(error_msg);
134 if (table_ != nullptr) {
135 max_entries_ = kSmallIrtEntries;
136 // table_mem_map_ remains invalid.
137 }
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700138 }
Hans Boehm4dcac362021-09-23 12:26:04 -0700139 if (table_ == nullptr) {
140 const size_t table_bytes = RoundUp(max_count * sizeof(IrtEntry), kPageSize);
141 table_mem_map_ = NewIRTMap(table_bytes, error_msg);
142 if (!table_mem_map_.IsValid() && error_msg->empty()) {
143 *error_msg = "Unable to map memory for indirect ref table";
144 }
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100145
Hans Boehm4dcac362021-09-23 12:26:04 -0700146 if (table_mem_map_.IsValid()) {
147 table_ = reinterpret_cast<IrtEntry*>(table_mem_map_.Begin());
148 } else {
149 table_ = nullptr;
150 }
151 // Take into account the actual length.
152 max_entries_ = table_bytes / sizeof(IrtEntry);
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100153 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700154 segment_state_ = kIRTFirstSegment;
Andreas Gampe94a52022016-10-25 12:01:48 -0700155 last_known_previous_state_ = kIRTFirstSegment;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700156}
157
158IndirectReferenceTable::~IndirectReferenceTable() {
Hans Boehm4dcac362021-09-23 12:26:04 -0700159 if (table_ != nullptr && !table_mem_map_.IsValid()) {
160 Runtime::Current()->GetSmallIrtAllocator()->Deallocate(table_);
161 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700162}
163
Andreas Gampedc061d02016-10-24 13:19:37 -0700164void IndirectReferenceTable::ConstexprChecks() {
165 // Use this for some assertions. They can't be put into the header as C++ wants the class
166 // to be complete.
167
168 // Check kind.
169 static_assert((EncodeIndirectRefKind(kLocal) & (~kKindMask)) == 0, "Kind encoding error");
170 static_assert((EncodeIndirectRefKind(kGlobal) & (~kKindMask)) == 0, "Kind encoding error");
171 static_assert((EncodeIndirectRefKind(kWeakGlobal) & (~kKindMask)) == 0, "Kind encoding error");
172 static_assert(DecodeIndirectRefKind(EncodeIndirectRefKind(kLocal)) == kLocal,
173 "Kind encoding error");
174 static_assert(DecodeIndirectRefKind(EncodeIndirectRefKind(kGlobal)) == kGlobal,
175 "Kind encoding error");
176 static_assert(DecodeIndirectRefKind(EncodeIndirectRefKind(kWeakGlobal)) == kWeakGlobal,
177 "Kind encoding error");
178
179 // Check serial.
180 static_assert(DecodeSerial(EncodeSerial(0u)) == 0u, "Serial encoding error");
181 static_assert(DecodeSerial(EncodeSerial(1u)) == 1u, "Serial encoding error");
182 static_assert(DecodeSerial(EncodeSerial(2u)) == 2u, "Serial encoding error");
183 static_assert(DecodeSerial(EncodeSerial(3u)) == 3u, "Serial encoding error");
184
185 // Table index.
186 static_assert(DecodeIndex(EncodeIndex(0u)) == 0u, "Index encoding error");
187 static_assert(DecodeIndex(EncodeIndex(1u)) == 1u, "Index encoding error");
188 static_assert(DecodeIndex(EncodeIndex(2u)) == 2u, "Index encoding error");
189 static_assert(DecodeIndex(EncodeIndex(3u)) == 3u, "Index encoding error");
190}
191
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700192bool IndirectReferenceTable::IsValid() const {
Hans Boehm4dcac362021-09-23 12:26:04 -0700193 return table_ != nullptr;
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700194}
195
Andreas Gampee03662b2016-10-13 17:12:56 -0700196// Holes:
197//
198// To keep the IRT compact, we want to fill "holes" created by non-stack-discipline Add & Remove
199// operation sequences. For simplicity and lower memory overhead, we do not use a free list or
200// similar. Instead, we scan for holes, with the expectation that we will find holes fast as they
201// are usually near the end of the table (see the header, TODO: verify this assumption). To avoid
202// scans when there are no holes, the number of known holes should be tracked.
203//
204// A previous implementation stored the top index and the number of holes as the segment state.
205// This constraints the maximum number of references to 16-bit. We want to relax this, as it
206// is easy to require more references (e.g., to list all classes in large applications). Thus,
207// the implicitly stack-stored state, the IRTSegmentState, is only the top index.
208//
209// Thus, hole count is a local property of the current segment, and needs to be recovered when
210// (or after) a frame is pushed or popped. To keep JNI transitions simple (and inlineable), we
211// cannot do work when the segment changes. Thus, Add and Remove need to ensure the current
212// hole count is correct.
213//
214// To be able to detect segment changes, we require an additional local field that can describe
215// the known segment. This is last_known_previous_state_. The requirement will become clear with
216// the following (some non-trivial) cases that have to be supported:
217//
218// 1) Segment with holes (current_num_holes_ > 0), push new segment, add/remove reference
219// 2) Segment with holes (current_num_holes_ > 0), pop segment, add/remove reference
220// 3) Segment with holes (current_num_holes_ > 0), push new segment, pop segment, add/remove
221// reference
222// 4) Empty segment, push new segment, create a hole, pop a segment, add/remove a reference
223// 5) Base segment, push new segment, create a hole, pop a segment, push new segment, add/remove
224// reference
225//
226// Storing the last known *previous* state (bottom index) allows conservatively detecting all the
227// segment changes above. The condition is simply that the last known state is greater than or
228// equal to the current previous state, and smaller than the current state (top index). The
229// condition is conservative as it adds O(1) overhead to operations on an empty segment.
230
231static size_t CountNullEntries(const IrtEntry* table, size_t from, size_t to) {
232 size_t count = 0;
233 for (size_t index = from; index != to; ++index) {
234 if (table[index].GetReference()->IsNull()) {
235 count++;
236 }
237 }
238 return count;
239}
240
241void IndirectReferenceTable::RecoverHoles(IRTSegmentState prev_state) {
242 if (last_known_previous_state_.top_index >= segment_state_.top_index ||
243 last_known_previous_state_.top_index < prev_state.top_index) {
244 const size_t top_index = segment_state_.top_index;
245 size_t count = CountNullEntries(table_, prev_state.top_index, top_index);
246
247 if (kDebugIRT) {
248 LOG(INFO) << "+++ Recovered holes: "
249 << " Current prev=" << prev_state.top_index
250 << " Current top_index=" << top_index
251 << " Old num_holes=" << current_num_holes_
252 << " New num_holes=" << count;
253 }
254
255 current_num_holes_ = count;
256 last_known_previous_state_ = prev_state;
257 } else if (kDebugIRT) {
258 LOG(INFO) << "No need to recover holes";
259 }
260}
261
262ALWAYS_INLINE
263static inline void CheckHoleCount(IrtEntry* table,
264 size_t exp_num_holes,
265 IRTSegmentState prev_state,
266 IRTSegmentState cur_state) {
267 if (kIsDebugBuild) {
268 size_t count = CountNullEntries(table, prev_state.top_index, cur_state.top_index);
269 CHECK_EQ(exp_num_holes, count) << "prevState=" << prev_state.top_index
270 << " topIndex=" << cur_state.top_index;
271 }
272}
273
274bool IndirectReferenceTable::Resize(size_t new_size, std::string* error_msg) {
275 CHECK_GT(new_size, max_entries_);
276
Andreas Gampe0ece10d2017-05-31 20:09:28 -0700277 constexpr size_t kMaxEntries = kMaxTableSizeInBytes / sizeof(IrtEntry);
278 if (new_size > kMaxEntries) {
279 *error_msg = android::base::StringPrintf("Requested size exceeds maximum: %zu", new_size);
280 return false;
281 }
282 // Note: the above check also ensures that there is no overflow below.
283
Alex Light3d9c0d92020-09-09 14:16:08 -0700284 const size_t table_bytes = RoundUp(new_size * sizeof(IrtEntry), kPageSize);
Hans Boehm4dcac362021-09-23 12:26:04 -0700285
286 MemMap new_map = NewIRTMap(table_bytes, error_msg);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100287 if (!new_map.IsValid()) {
Andreas Gampee03662b2016-10-13 17:12:56 -0700288 return false;
289 }
290
Hans Boehm4dcac362021-09-23 12:26:04 -0700291 memcpy(new_map.Begin(), table_, max_entries_ * sizeof(IrtEntry));
292 if (!table_mem_map_.IsValid()) {
293 // Didn't have its own map; deallocate old table.
294 Runtime::Current()->GetSmallIrtAllocator()->Deallocate(table_);
295 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700296 table_mem_map_ = std::move(new_map);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100297 table_ = reinterpret_cast<IrtEntry*>(table_mem_map_.Begin());
Alex Light3d9c0d92020-09-09 14:16:08 -0700298 const size_t real_new_size = table_bytes / sizeof(IrtEntry);
299 DCHECK_GE(real_new_size, new_size);
300 max_entries_ = real_new_size;
Andreas Gampee03662b2016-10-13 17:12:56 -0700301
302 return true;
303}
304
305IndirectRef IndirectReferenceTable::Add(IRTSegmentState previous_state,
Andreas Gampe25651122017-09-25 14:50:23 -0700306 ObjPtr<mirror::Object> obj,
307 std::string* error_msg) {
Andreas Gampee03662b2016-10-13 17:12:56 -0700308 if (kDebugIRT) {
309 LOG(INFO) << "+++ Add: previous_state=" << previous_state.top_index
310 << " top_index=" << segment_state_.top_index
311 << " last_known_prev_top_index=" << last_known_previous_state_.top_index
312 << " holes=" << current_num_holes_;
313 }
314
315 size_t top_index = segment_state_.top_index;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700316
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700317 CHECK(obj != nullptr);
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700318 VerifyObject(obj);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700319 DCHECK(table_ != nullptr);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700320
Andreas Gampee03662b2016-10-13 17:12:56 -0700321 if (top_index == max_entries_) {
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700322 if (resizable_ == ResizableCapacity::kNo) {
Andreas Gampe25651122017-09-25 14:50:23 -0700323 std::ostringstream oss;
324 oss << "JNI ERROR (app bug): " << kind_ << " table overflow "
325 << "(max=" << max_entries_ << ")"
326 << MutatorLockedDumpable<IndirectReferenceTable>(*this);
327 *error_msg = oss.str();
328 return nullptr;
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700329 }
330
331 // Try to double space.
Andreas Gampe0ece10d2017-05-31 20:09:28 -0700332 if (std::numeric_limits<size_t>::max() / 2 < max_entries_) {
Andreas Gampe25651122017-09-25 14:50:23 -0700333 std::ostringstream oss;
334 oss << "JNI ERROR (app bug): " << kind_ << " table overflow "
335 << "(max=" << max_entries_ << ")" << std::endl
336 << MutatorLockedDumpable<IndirectReferenceTable>(*this)
337 << " Resizing failed: exceeds size_t";
338 *error_msg = oss.str();
339 return nullptr;
Andreas Gampe0ece10d2017-05-31 20:09:28 -0700340 }
341
Andreas Gampe25651122017-09-25 14:50:23 -0700342 std::string inner_error_msg;
343 if (!Resize(max_entries_ * 2, &inner_error_msg)) {
344 std::ostringstream oss;
345 oss << "JNI ERROR (app bug): " << kind_ << " table overflow "
346 << "(max=" << max_entries_ << ")" << std::endl
347 << MutatorLockedDumpable<IndirectReferenceTable>(*this)
348 << " Resizing failed: " << inner_error_msg;
349 *error_msg = oss.str();
350 return nullptr;
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700351 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700352 }
353
Andreas Gampee03662b2016-10-13 17:12:56 -0700354 RecoverHoles(previous_state);
355 CheckHoleCount(table_, current_num_holes_, previous_state, segment_state_);
356
Elliott Hughes73e66f72012-05-09 09:34:45 -0700357 // We know there's enough room in the table. Now we just need to find
358 // the right spot. If there's a hole, find it and fill it; otherwise,
359 // add to the end of the list.
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700360 IndirectRef result;
Mathieu Chartier4838d662014-09-25 15:27:43 -0700361 size_t index;
Andreas Gampee03662b2016-10-13 17:12:56 -0700362 if (current_num_holes_ > 0) {
363 DCHECK_GT(top_index, 1U);
Elliott Hughes73e66f72012-05-09 09:34:45 -0700364 // Find the first hole; likely to be near the end of the list.
Andreas Gampee03662b2016-10-13 17:12:56 -0700365 IrtEntry* p_scan = &table_[top_index - 1];
366 DCHECK(!p_scan->GetReference()->IsNull());
367 --p_scan;
368 while (!p_scan->GetReference()->IsNull()) {
369 DCHECK_GE(p_scan, table_ + previous_state.top_index);
370 --p_scan;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700371 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700372 index = p_scan - table_;
373 current_num_holes_--;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700374 } else {
Elliott Hughes73e66f72012-05-09 09:34:45 -0700375 // Add to the end.
Andreas Gampee03662b2016-10-13 17:12:56 -0700376 index = top_index++;
377 segment_state_.top_index = top_index;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700378 }
Mathieu Chartier4838d662014-09-25 15:27:43 -0700379 table_[index].Add(obj);
380 result = ToIndirectRef(index);
Andreas Gampee03662b2016-10-13 17:12:56 -0700381 if (kDebugIRT) {
382 LOG(INFO) << "+++ added at " << ExtractIndex(result) << " top=" << segment_state_.top_index
383 << " holes=" << current_num_holes_;
Ian Rogers5a7a74a2011-09-26 16:32:29 -0700384 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700385
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700386 DCHECK(result != nullptr);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700387 return result;
388}
389
Elliott Hughes726079d2011-10-07 18:43:44 -0700390void IndirectReferenceTable::AssertEmpty() {
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700391 for (size_t i = 0; i < Capacity(); ++i) {
Mathieu Chartier4838d662014-09-25 15:27:43 -0700392 if (!table_[i].GetReference()->IsNull()) {
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700393 LOG(FATAL) << "Internal Error: non-empty local reference table\n"
394 << MutatorLockedDumpable<IndirectReferenceTable>(*this);
Mathieu Chartier8778c522016-10-04 19:06:30 -0700395 UNREACHABLE();
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700396 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700397 }
398}
399
Elliott Hughes73e66f72012-05-09 09:34:45 -0700400// Removes an object. We extract the table offset bits from "iref"
401// and zap the corresponding entry, leaving a hole if it's not at the top.
402// If the entry is not between the current top index and the bottom index
403// specified by the cookie, we don't remove anything. This is the behavior
404// required by JNI's DeleteLocalRef function.
405// This method is not called when a local frame is popped; this is only used
406// for explicit single removals.
407// Returns "false" if nothing was removed.
Andreas Gampee03662b2016-10-13 17:12:56 -0700408bool IndirectReferenceTable::Remove(IRTSegmentState previous_state, IndirectRef iref) {
409 if (kDebugIRT) {
410 LOG(INFO) << "+++ Remove: previous_state=" << previous_state.top_index
411 << " top_index=" << segment_state_.top_index
412 << " last_known_prev_top_index=" << last_known_previous_state_.top_index
413 << " holes=" << current_num_holes_;
414 }
415
416 const uint32_t top_index = segment_state_.top_index;
417 const uint32_t bottom_index = previous_state.top_index;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700418
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700419 DCHECK(table_ != nullptr);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700420
Vladimir Markocedec9d2021-02-08 16:16:13 +0000421 // TODO: We should eagerly check the ref kind against the `kind_` instead of
422 // relying on this weak check and postponing the rest until `CheckEntry()` below.
423 // Passing the wrong kind shall currently result in misleading warnings.
424 if (GetIndirectRefKind(iref) == kJniTransitionOrInvalid) {
Mathieu Chartierc263bf82015-04-29 09:57:48 -0700425 auto* self = Thread::Current();
Vladimir Markocedec9d2021-02-08 16:16:13 +0000426 ScopedObjectAccess soa(self);
427 if (self->IsJniTransitionReference(reinterpret_cast<jobject>(iref))) {
Mathieu Chartierc263bf82015-04-29 09:57:48 -0700428 auto* env = self->GetJniEnv();
429 DCHECK(env != nullptr);
Ian Rogers55256cb2017-12-21 17:07:11 -0800430 if (env->IsCheckJniEnabled()) {
Mathieu Chartierff6d8cf2015-06-02 13:40:12 -0700431 LOG(WARNING) << "Attempt to remove non-JNI local reference, dumping thread";
Mathieu Chartier2ada67b2015-07-30 11:41:04 -0700432 if (kDumpStackOnNonLocalReference) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700433 self->Dump(LOG_STREAM(WARNING));
Mathieu Chartier2ada67b2015-07-30 11:41:04 -0700434 }
Mathieu Chartierc263bf82015-04-29 09:57:48 -0700435 }
436 return true;
437 }
Ian Rogers5a7a74a2011-09-26 16:32:29 -0700438 }
Vladimir Markocedec9d2021-02-08 16:16:13 +0000439
Andreas Gampee03662b2016-10-13 17:12:56 -0700440 const uint32_t idx = ExtractIndex(iref);
441 if (idx < bottom_index) {
Elliott Hughes726079d2011-10-07 18:43:44 -0700442 // Wrong segment.
443 LOG(WARNING) << "Attempt to remove index outside index area (" << idx
Andreas Gampee03662b2016-10-13 17:12:56 -0700444 << " vs " << bottom_index << "-" << top_index << ")";
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700445 return false;
446 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700447 if (idx >= top_index) {
Elliott Hughes726079d2011-10-07 18:43:44 -0700448 // Bad --- stale reference?
449 LOG(WARNING) << "Attempt to remove invalid index " << idx
Andreas Gampee03662b2016-10-13 17:12:56 -0700450 << " (bottom=" << bottom_index << " top=" << top_index << ")";
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700451 return false;
452 }
453
Andreas Gampee03662b2016-10-13 17:12:56 -0700454 RecoverHoles(previous_state);
455 CheckHoleCount(table_, current_num_holes_, previous_state, segment_state_);
456
457 if (idx == top_index - 1) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700458 // Top-most entry. Scan up and consume holes.
459
Ian Rogers987560f2014-04-22 11:42:59 -0700460 if (!CheckEntry("remove", iref, idx)) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700461 return false;
462 }
463
Mathieu Chartier4838d662014-09-25 15:27:43 -0700464 *table_[idx].GetReference() = GcRoot<mirror::Object>(nullptr);
Andreas Gampee03662b2016-10-13 17:12:56 -0700465 if (current_num_holes_ != 0) {
466 uint32_t collapse_top_index = top_index;
467 while (--collapse_top_index > bottom_index && current_num_holes_ != 0) {
468 if (kDebugIRT) {
469 ScopedObjectAccess soa(Thread::Current());
470 LOG(INFO) << "+++ checking for hole at " << collapse_top_index - 1
471 << " (previous_state=" << bottom_index << ") val="
472 << table_[collapse_top_index - 1].GetReference()->Read<kWithoutReadBarrier>();
Ian Rogers5a7a74a2011-09-26 16:32:29 -0700473 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700474 if (!table_[collapse_top_index - 1].GetReference()->IsNull()) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700475 break;
476 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700477 if (kDebugIRT) {
478 LOG(INFO) << "+++ ate hole at " << (collapse_top_index - 1);
Ian Rogers5a7a74a2011-09-26 16:32:29 -0700479 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700480 current_num_holes_--;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700481 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700482 segment_state_.top_index = collapse_top_index;
483
484 CheckHoleCount(table_, current_num_holes_, previous_state, segment_state_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700485 } else {
Andreas Gampee03662b2016-10-13 17:12:56 -0700486 segment_state_.top_index = top_index - 1;
487 if (kDebugIRT) {
488 LOG(INFO) << "+++ ate last entry " << top_index - 1;
Ian Rogers5a7a74a2011-09-26 16:32:29 -0700489 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700490 }
491 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700492 // Not the top-most entry. This creates a hole. We null out the entry to prevent somebody
493 // from deleting it twice and screwing up the hole count.
Mathieu Chartier4838d662014-09-25 15:27:43 -0700494 if (table_[idx].GetReference()->IsNull()) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700495 LOG(INFO) << "--- WEIRD: removing null entry " << idx;
496 return false;
497 }
Ian Rogers987560f2014-04-22 11:42:59 -0700498 if (!CheckEntry("remove", iref, idx)) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700499 return false;
500 }
501
Mathieu Chartier4838d662014-09-25 15:27:43 -0700502 *table_[idx].GetReference() = GcRoot<mirror::Object>(nullptr);
Andreas Gampee03662b2016-10-13 17:12:56 -0700503 current_num_holes_++;
504 CheckHoleCount(table_, current_num_holes_, previous_state, segment_state_);
505 if (kDebugIRT) {
506 LOG(INFO) << "+++ left hole at " << idx << ", holes=" << current_num_holes_;
Ian Rogers5a7a74a2011-09-26 16:32:29 -0700507 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700508 }
509
510 return true;
511}
512
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800513void IndirectReferenceTable::Trim() {
Mathieu Chartierdabdc0f2016-03-04 14:58:03 -0800514 ScopedTrace trace(__PRETTY_FUNCTION__);
Hans Boehm4dcac362021-09-23 12:26:04 -0700515 if (!table_mem_map_.IsValid()) {
516 // Small table; nothing to do here.
517 return;
518 }
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800519 const size_t top_index = Capacity();
Alex Light3d9c0d92020-09-09 14:16:08 -0700520 uint8_t* release_start = AlignUp(reinterpret_cast<uint8_t*>(&table_[top_index]), kPageSize);
521 uint8_t* release_end = static_cast<uint8_t*>(table_mem_map_.BaseEnd());
522 DCHECK_GE(reinterpret_cast<uintptr_t>(release_end), reinterpret_cast<uintptr_t>(release_start));
523 DCHECK_ALIGNED(release_end, kPageSize);
524 DCHECK_ALIGNED(release_end - release_start, kPageSize);
Hans Boehm4dcac362021-09-23 12:26:04 -0700525 if (release_start != release_end) {
526 madvise(release_start, release_end - release_start, MADV_DONTNEED);
527 }
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800528}
529
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700530void IndirectReferenceTable::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -0700531 BufferedRootVisitor<kDefaultBufferedRootCount> root_visitor(visitor, root_info);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700532 for (auto ref : *this) {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700533 if (!ref->IsNull()) {
534 root_visitor.VisitRoot(*ref);
535 DCHECK(!ref->IsNull());
536 }
Elliott Hughes410c0c82011-09-01 17:58:25 -0700537 }
538}
539
Elliott Hughes73e66f72012-05-09 09:34:45 -0700540void IndirectReferenceTable::Dump(std::ostream& os) const {
541 os << kind_ << " table dump:\n";
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700542 ReferenceTable::Table entries;
543 for (size_t i = 0; i < Capacity(); ++i) {
Mathieu Chartier8778c522016-10-04 19:06:30 -0700544 ObjPtr<mirror::Object> obj = table_[i].GetReference()->Read<kWithoutReadBarrier>();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700545 if (obj != nullptr) {
Mathieu Chartier4838d662014-09-25 15:27:43 -0700546 obj = table_[i].GetReference()->Read();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700547 entries.push_back(GcRoot<mirror::Object>(obj));
Ian Rogers63818dc2012-09-26 12:23:04 -0700548 }
549 }
Elliott Hughes73e66f72012-05-09 09:34:45 -0700550 ReferenceTable::Dump(os, entries);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700551}
552
Andreas Gampee03662b2016-10-13 17:12:56 -0700553void IndirectReferenceTable::SetSegmentState(IRTSegmentState new_state) {
554 if (kDebugIRT) {
555 LOG(INFO) << "Setting segment state: "
556 << segment_state_.top_index
557 << " -> "
558 << new_state.top_index;
559 }
560 segment_state_ = new_state;
561}
562
Andreas Gampe88831082017-05-31 19:46:03 -0700563bool IndirectReferenceTable::EnsureFreeCapacity(size_t free_capacity, std::string* error_msg) {
564 size_t top_index = segment_state_.top_index;
565 if (top_index < max_entries_ && top_index + free_capacity <= max_entries_) {
566 return true;
567 }
568
569 // We're only gonna do a simple best-effort here, ensuring the asked-for capacity at the end.
570 if (resizable_ == ResizableCapacity::kNo) {
571 *error_msg = "Table is not resizable";
572 return false;
573 }
574
575 // Try to increase the table size.
576
577 // Would this overflow?
578 if (std::numeric_limits<size_t>::max() - free_capacity < top_index) {
579 *error_msg = "Cannot resize table, overflow.";
580 return false;
581 }
582
583 if (!Resize(top_index + free_capacity, error_msg)) {
584 LOG(WARNING) << "JNI ERROR: Unable to reserve space in EnsureFreeCapacity (" << free_capacity
585 << "): " << std::endl
586 << MutatorLockedDumpable<IndirectReferenceTable>(*this)
587 << " Resizing failed: " << *error_msg;
588 return false;
589 }
590 return true;
591}
592
Andreas Gampe1b35b462017-09-29 18:52:15 -0700593size_t IndirectReferenceTable::FreeCapacity() const {
Andreas Gampe88831082017-05-31 19:46:03 -0700594 return max_entries_ - segment_state_.top_index;
595}
596
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700597} // namespace art