blob: d13526b22a6a2875e2a7ed4de48ef8f4555eeb2f [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
Brian Carlstromfc0e3212013-07-17 14:40:12 -070017#ifndef ART_RUNTIME_INDIRECT_REFERENCE_TABLE_H_
18#define ART_RUNTIME_INDIRECT_REFERENCE_TABLE_H_
Elliott Hughes6c1a3942011-08-17 15:00:06 -070019
Elliott Hughes07ed66b2012-12-12 18:34:25 -080020#include <stdint.h>
Elliott Hughes6c1a3942011-08-17 15:00:06 -070021
22#include <iosfwd>
Elliott Hughes6c1a3942011-08-17 15:00:06 -070023#include <string>
24
Elliott Hughes07ed66b2012-12-12 18:34:25 -080025#include "base/logging.h"
Ian Rogers719d1a32014-03-06 12:13:39 -080026#include "base/mutex.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070027#include "gc_root.h"
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080028#include "object_callbacks.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "offsets.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070030#include "read_barrier_option.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080031
Elliott Hughes6c1a3942011-08-17 15:00:06 -070032namespace art {
Ian Rogers68d8b422014-07-17 11:09:10 -070033
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080034class RootInfo;
35
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036namespace mirror {
Elliott Hughes6c1a3942011-08-17 15:00:06 -070037class Object;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038} // namespace mirror
Elliott Hughes6c1a3942011-08-17 15:00:06 -070039
Ian Rogers68d8b422014-07-17 11:09:10 -070040class MemMap;
41
Elliott Hughes6c1a3942011-08-17 15:00:06 -070042/*
43 * Maintain a table of indirect references. Used for local/global JNI
44 * references.
45 *
46 * The table contains object references that are part of the GC root set.
47 * When an object is added we return an IndirectRef that is not a valid
48 * pointer but can be used to find the original value in O(1) time.
Elliott Hughes81ff3182012-03-23 20:35:56 -070049 * Conversions to and from indirect references are performed on upcalls
50 * and downcalls, so they need to be very fast.
Elliott Hughes6c1a3942011-08-17 15:00:06 -070051 *
52 * To be efficient for JNI local variable storage, we need to provide
53 * operations that allow us to operate on segments of the table, where
54 * segments are pushed and popped as if on a stack. For example, deletion
55 * of an entry should only succeed if it appears in the current segment,
56 * and we want to be able to strip off the current segment quickly when
57 * a method returns. Additions to the table must be made in the current
58 * segment even if space is available in an earlier area.
59 *
60 * A new segment is created when we call into native code from interpreted
61 * code, or when we handle the JNI PushLocalFrame function.
62 *
63 * The GC must be able to scan the entire table quickly.
64 *
65 * In summary, these must be very fast:
66 * - adding or removing a segment
67 * - adding references to a new segment
68 * - converting an indirect reference back to an Object
69 * These can be a little slower, but must still be pretty quick:
70 * - adding references to a "mature" segment
71 * - removing individual references
72 * - scanning the entire table straight through
73 *
74 * If there's more than one segment, we don't guarantee that the table
75 * will fill completely before we fail due to lack of space. We do ensure
76 * that the current segment will pack tightly, which should satisfy JNI
77 * requirements (e.g. EnsureLocalCapacity).
78 *
79 * To make everything fit nicely in 32-bit integers, the maximum size of
80 * the table is capped at 64K.
81 *
Mathieu Chartierc56057e2014-05-04 13:18:58 -070082 * Only SynchronizedGet is synchronized.
Elliott Hughes6c1a3942011-08-17 15:00:06 -070083 */
84
85/*
86 * Indirect reference definition. This must be interchangeable with JNI's
87 * jobject, and it's convenient to let null be null, so we use void*.
88 *
89 * We need a 16-bit table index and a 2-bit reference type (global, local,
90 * weak global). Real object pointers will have zeroes in the low 2 or 3
91 * bits (4- or 8-byte alignment), so it's useful to put the ref type
92 * in the low bits and reserve zero as an invalid value.
93 *
94 * The remaining 14 bits can be used to detect stale indirect references.
95 * For example, if objects don't move, we can use a hash of the original
96 * Object* to make sure the entry hasn't been re-used. (If the Object*
97 * we find there doesn't match because of heap movement, we could do a
98 * secondary check on the preserved hash value; this implies that creating
99 * a global/local ref queries the hash value and forces it to be saved.)
100 *
101 * A more rigorous approach would be to put a serial number in the extra
102 * bits, and keep a copy of the serial number in a parallel table. This is
103 * easier when objects can move, but requires 2x the memory and additional
104 * memory accesses on add/get. It will catch additional problems, e.g.:
105 * create iref1 for obj, delete iref1, create iref2 for same obj, lookup
106 * iref1. A pattern based on object bits will miss this.
107 */
108typedef void* IndirectRef;
109
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700110/*
111 * Indirect reference kind, used as the two low bits of IndirectRef.
112 *
113 * For convenience these match up with enum jobjectRefType from jni.h.
114 */
115enum IndirectRefKind {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700116 kHandleScopeOrInvalid = 0, // <<stack indirect reference table or invalid reference>>
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700117 kLocal = 1, // <<local reference>>
118 kGlobal = 2, // <<global reference>>
119 kWeakGlobal = 3 // <<weak global reference>>
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700120};
Elliott Hughes0e57ccb2012-04-03 16:04:52 -0700121std::ostream& operator<<(std::ostream& os, const IndirectRefKind& rhs);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700122
123/*
124 * Determine what kind of indirect reference this is.
125 */
126static inline IndirectRefKind GetIndirectRefKind(IndirectRef iref) {
127 return static_cast<IndirectRefKind>(reinterpret_cast<uintptr_t>(iref) & 0x03);
128}
129
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700130/* use as initial value for "cookie", and when table has only one segment */
131static const uint32_t IRT_FIRST_SEGMENT = 0;
132
133/*
134 * Table definition.
135 *
136 * For the global reference table, the expected common operations are
137 * adding a new entry and removing a recently-added entry (usually the
138 * most-recently-added entry). For JNI local references, the common
139 * operations are adding a new entry and removing an entire table segment.
140 *
141 * If "alloc_entries_" is not equal to "max_entries_", the table may expand
142 * when entries are added, which means the memory may move. If you want
143 * to keep pointers into "table" rather than offsets, you must use a
144 * fixed-size table.
145 *
146 * If we delete entries from the middle of the list, we will be left with
147 * "holes". We track the number of holes so that, when adding new elements,
148 * we can quickly decide to do a trivial append or go slot-hunting.
149 *
150 * When the top-most entry is removed, any holes immediately below it are
151 * also removed. Thus, deletion of an entry may reduce "topIndex" by more
152 * than one.
153 *
154 * To get the desired behavior for JNI locals, we need to know the bottom
155 * and top of the current "segment". The top is managed internally, and
Elliott Hughes81ff3182012-03-23 20:35:56 -0700156 * the bottom is passed in as a function argument. When we call a native method or
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700157 * push a local frame, the current top index gets pushed on, and serves
158 * as the new bottom. When we pop a frame off, the value from the stack
159 * becomes the new top index, and the value stored in the previous frame
160 * becomes the new bottom.
161 *
162 * To avoid having to re-scan the table after a pop, we want to push the
163 * number of holes in the table onto the stack. Because of our 64K-entry
164 * cap, we can combine the two into a single unsigned 32-bit value.
165 * Instead of a "bottom" argument we take a "cookie", which includes the
166 * bottom index and the count of holes below the bottom.
167 *
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700168 * Common alternative implementation: make IndirectRef a pointer to the
169 * actual reference slot. Instead of getting a table and doing a lookup,
170 * the lookup can be done instantly. Operations like determining the
171 * type and deleting the reference are more expensive because the table
172 * must be hunted for (i.e. you have to do a pointer comparison to see
173 * which table it's in), you can't move the table when expanding it (so
174 * realloc() is out), and tricks like serial number checking to detect
175 * stale references aren't possible (though we may be able to get similar
176 * benefits with other approaches).
177 *
178 * TODO: consider a "lastDeleteIndex" for quick hole-filling when an
179 * add immediately follows a delete; must invalidate after segment pop
180 * (which could increase the cost/complexity of method call/return).
181 * Might be worth only using it for JNI globals.
182 *
183 * TODO: may want completely different add/remove algorithms for global
184 * and local refs to improve performance. A large circular buffer might
185 * reduce the amortized cost of adding global references.
186 *
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700187 */
188union IRTSegmentState {
189 uint32_t all;
190 struct {
191 uint32_t topIndex:16; /* index of first unused entry */
192 uint32_t numHoles:16; /* #of holes in entire table */
193 } parts;
194};
195
Mathieu Chartier4838d662014-09-25 15:27:43 -0700196// Try to choose kIRTPrevCount so that sizeof(IrtEntry) is a power of 2.
197// Contains multiple entries but only one active one, this helps us detect use after free errors
198// since the serial stored in the indirect ref wont match.
199static const size_t kIRTPrevCount = kIsDebugBuild ? 7 : 3;
Hiroshi Yamauchi9e47bfa2015-02-23 11:14:40 -0800200class IrtEntry {
Mathieu Chartier4838d662014-09-25 15:27:43 -0700201 public:
Mathieu Chartier90443472015-07-16 20:32:27 -0700202 void Add(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier4838d662014-09-25 15:27:43 -0700203 ++serial_;
204 if (serial_ == kIRTPrevCount) {
205 serial_ = 0;
206 }
207 references_[serial_] = GcRoot<mirror::Object>(obj);
208 }
209 GcRoot<mirror::Object>* GetReference() {
210 DCHECK_LT(serial_, kIRTPrevCount);
211 return &references_[serial_];
212 }
213 uint32_t GetSerial() const {
214 return serial_;
215 }
Jeff Hao39b6c242015-05-19 20:30:23 -0700216 void SetReference(mirror::Object* obj) {
217 DCHECK_LT(serial_, kIRTPrevCount);
218 references_[serial_] = GcRoot<mirror::Object>(obj);
219 }
Mathieu Chartier4838d662014-09-25 15:27:43 -0700220
221 private:
222 uint32_t serial_;
223 GcRoot<mirror::Object> references_[kIRTPrevCount];
224};
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700225static_assert(sizeof(IrtEntry) == (1 + kIRTPrevCount) * sizeof(uint32_t),
Hiroshi Yamauchi9e47bfa2015-02-23 11:14:40 -0800226 "Unexpected sizeof(IrtEntry)");
Mathieu Chartier4838d662014-09-25 15:27:43 -0700227
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700228class IrtIterator {
229 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100230 IrtIterator(IrtEntry* table, size_t i, size_t capacity) SHARED_REQUIRES(Locks::mutator_lock_)
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700231 : table_(table), i_(i), capacity_(capacity) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700232 }
233
Mathieu Chartier90443472015-07-16 20:32:27 -0700234 IrtIterator& operator++() SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700235 ++i_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700236 return *this;
237 }
238
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700239 GcRoot<mirror::Object>* operator*() {
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700240 // This does not have a read barrier as this is used to visit roots.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700241 return table_[i_].GetReference();
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700242 }
243
244 bool equals(const IrtIterator& rhs) const {
245 return (i_ == rhs.i_ && table_ == rhs.table_);
246 }
247
248 private:
Mathieu Chartier4838d662014-09-25 15:27:43 -0700249 IrtEntry* const table_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700250 size_t i_;
Ian Rogersc0542af2014-09-03 16:16:56 -0700251 const size_t capacity_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700252};
253
Elliott Hughes726079d2011-10-07 18:43:44 -0700254bool inline operator==(const IrtIterator& lhs, const IrtIterator& rhs) {
255 return lhs.equals(rhs);
256}
257
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700258bool inline operator!=(const IrtIterator& lhs, const IrtIterator& rhs) {
259 return !lhs.equals(rhs);
260}
261
262class IndirectReferenceTable {
263 public:
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700264 // WARNING: When using with abort_on_error = false, the object may be in a partially
265 // initialized state. Use IsValid() to check.
266 IndirectReferenceTable(size_t initialCount, size_t maxCount, IndirectRefKind kind,
267 bool abort_on_error = true);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700268
269 ~IndirectReferenceTable();
270
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700271 bool IsValid() const;
272
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700273 /*
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700274 * Add a new entry. "obj" must be a valid non-nullptr object reference.
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700275 *
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700276 * Returns nullptr if the table is full (max entries reached, or alloc
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700277 * failed during expansion).
278 */
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700279 IndirectRef Add(uint32_t cookie, mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -0700280 SHARED_REQUIRES(Locks::mutator_lock_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700281
282 /*
283 * Given an IndirectRef in the table, return the Object it refers to.
284 *
285 * Returns kInvalidIndirectRefObject if iref is invalid.
286 */
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700287 template<ReadBarrierOption kReadBarrierOption = kWithReadBarrier>
Mathieu Chartier90443472015-07-16 20:32:27 -0700288 mirror::Object* Get(IndirectRef iref) const SHARED_REQUIRES(Locks::mutator_lock_)
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700289 ALWAYS_INLINE;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700290
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700291 // Synchronized get which reads a reference, acquiring a lock if necessary.
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700292 template<ReadBarrierOption kReadBarrierOption = kWithReadBarrier>
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700293 mirror::Object* SynchronizedGet(IndirectRef iref) const SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700294 return Get<kReadBarrierOption>(iref);
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700295 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700296
297 /*
Jeff Hao39b6c242015-05-19 20:30:23 -0700298 * Update an existing entry.
299 *
300 * Updates an existing indirect reference to point to a new object.
301 */
Mathieu Chartier90443472015-07-16 20:32:27 -0700302 void Update(IndirectRef iref, mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_);
Jeff Hao39b6c242015-05-19 20:30:23 -0700303
304 /*
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700305 * Remove an existing entry.
306 *
307 * If the entry is not between the current top index and the bottom index
308 * specified by the cookie, we don't remove anything. This is the behavior
309 * required by JNI's DeleteLocalRef function.
310 *
311 * Returns "false" if nothing was removed.
312 */
313 bool Remove(uint32_t cookie, IndirectRef iref);
314
Elliott Hughes726079d2011-10-07 18:43:44 -0700315 void AssertEmpty();
316
Mathieu Chartier90443472015-07-16 20:32:27 -0700317 void Dump(std::ostream& os) const SHARED_REQUIRES(Locks::mutator_lock_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700318
319 /*
320 * Return the #of entries in the entire table. This includes holes, and
321 * so may be larger than the actual number of "live" entries.
322 */
323 size_t Capacity() const {
Ian Rogersdc51b792011-09-22 20:41:37 -0700324 return segment_state_.parts.topIndex;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700325 }
326
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700327 // Note IrtIterator does not have a read barrier as it's used to visit roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700328 IrtIterator begin() {
329 return IrtIterator(table_, 0, Capacity());
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700330 }
331
Mathieu Chartier02e25112013-08-14 16:14:24 -0700332 IrtIterator end() {
333 return IrtIterator(table_, Capacity(), Capacity());
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700334 }
335
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700336 void VisitRoots(RootVisitor* visitor, const RootInfo& root_info)
Mathieu Chartier90443472015-07-16 20:32:27 -0700337 SHARED_REQUIRES(Locks::mutator_lock_);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700338
Ian Rogersad25ac52011-10-04 19:13:33 -0700339 uint32_t GetSegmentState() const {
340 return segment_state_.all;
341 }
342
343 void SetSegmentState(uint32_t new_state) {
344 segment_state_.all = new_state;
345 }
346
Ian Rogersdc51b792011-09-22 20:41:37 -0700347 static Offset SegmentStateOffset() {
348 return Offset(OFFSETOF_MEMBER(IndirectReferenceTable, segment_state_));
349 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800350
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800351 // Release pages past the end of the table that may have previously held references.
Mathieu Chartier90443472015-07-16 20:32:27 -0700352 void Trim() SHARED_REQUIRES(Locks::mutator_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800353
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700354 private:
Mathieu Chartier4838d662014-09-25 15:27:43 -0700355 // Extract the table index from an indirect reference.
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700356 static uint32_t ExtractIndex(IndirectRef iref) {
Ian Rogersf61db682014-01-23 20:26:01 -0800357 uintptr_t uref = reinterpret_cast<uintptr_t>(iref);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700358 return (uref >> 2) & 0xffff;
359 }
360
361 /*
362 * The object pointer itself is subject to relocation in some GC
363 * implementations, so we shouldn't really be using it here.
364 */
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700365 IndirectRef ToIndirectRef(uint32_t tableIndex) const {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700366 DCHECK_LT(tableIndex, 65536U);
Mathieu Chartier4838d662014-09-25 15:27:43 -0700367 uint32_t serialChunk = table_[tableIndex].GetSerial();
368 uintptr_t uref = (serialChunk << 20) | (tableIndex << 2) | kind_;
Ian Rogersf61db682014-01-23 20:26:01 -0800369 return reinterpret_cast<IndirectRef>(uref);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700370 }
371
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700372 // Abort if check_jni is not enabled.
373 static void AbortIfNoCheckJNI();
374
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700375 /* extra debugging checks */
376 bool GetChecked(IndirectRef) const;
377 bool CheckEntry(const char*, IndirectRef, int) const;
378
Ian Rogersdc51b792011-09-22 20:41:37 -0700379 /* semi-public - read/write by jni down calls */
380 IRTSegmentState segment_state_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700381
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700382 // Mem map where we store the indirect refs.
Ian Rogers700a4022014-05-19 16:49:03 -0700383 std::unique_ptr<MemMap> table_mem_map_;
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700384 // bottom of the stack. Do not directly access the object references
385 // in this as they are roots. Use Get() that has a read barrier.
Mathieu Chartier4838d662014-09-25 15:27:43 -0700386 IrtEntry* table_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700387 /* bit mask, ORed into all irefs */
Mathieu Chartier4838d662014-09-25 15:27:43 -0700388 const IndirectRefKind kind_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700389 /* max #of entries allowed */
Mathieu Chartier4838d662014-09-25 15:27:43 -0700390 const size_t max_entries_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700391};
392
393} // namespace art
394
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700395#endif // ART_RUNTIME_INDIRECT_REFERENCE_TABLE_H_