blob: d25bc42dfcfe7782737978fb22daae62824c4e29 [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
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034namespace mirror {
Elliott Hughes6c1a3942011-08-17 15:00:06 -070035class Object;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036} // namespace mirror
Elliott Hughes6c1a3942011-08-17 15:00:06 -070037
Ian Rogers68d8b422014-07-17 11:09:10 -070038class MemMap;
39
Elliott Hughes6c1a3942011-08-17 15:00:06 -070040/*
41 * Maintain a table of indirect references. Used for local/global JNI
42 * references.
43 *
44 * The table contains object references that are part of the GC root set.
45 * When an object is added we return an IndirectRef that is not a valid
46 * pointer but can be used to find the original value in O(1) time.
Elliott Hughes81ff3182012-03-23 20:35:56 -070047 * Conversions to and from indirect references are performed on upcalls
48 * and downcalls, so they need to be very fast.
Elliott Hughes6c1a3942011-08-17 15:00:06 -070049 *
50 * To be efficient for JNI local variable storage, we need to provide
51 * operations that allow us to operate on segments of the table, where
52 * segments are pushed and popped as if on a stack. For example, deletion
53 * of an entry should only succeed if it appears in the current segment,
54 * and we want to be able to strip off the current segment quickly when
55 * a method returns. Additions to the table must be made in the current
56 * segment even if space is available in an earlier area.
57 *
58 * A new segment is created when we call into native code from interpreted
59 * code, or when we handle the JNI PushLocalFrame function.
60 *
61 * The GC must be able to scan the entire table quickly.
62 *
63 * In summary, these must be very fast:
64 * - adding or removing a segment
65 * - adding references to a new segment
66 * - converting an indirect reference back to an Object
67 * These can be a little slower, but must still be pretty quick:
68 * - adding references to a "mature" segment
69 * - removing individual references
70 * - scanning the entire table straight through
71 *
72 * If there's more than one segment, we don't guarantee that the table
73 * will fill completely before we fail due to lack of space. We do ensure
74 * that the current segment will pack tightly, which should satisfy JNI
75 * requirements (e.g. EnsureLocalCapacity).
76 *
77 * To make everything fit nicely in 32-bit integers, the maximum size of
78 * the table is capped at 64K.
79 *
Mathieu Chartierc56057e2014-05-04 13:18:58 -070080 * Only SynchronizedGet is synchronized.
Elliott Hughes6c1a3942011-08-17 15:00:06 -070081 */
82
83/*
84 * Indirect reference definition. This must be interchangeable with JNI's
85 * jobject, and it's convenient to let null be null, so we use void*.
86 *
87 * We need a 16-bit table index and a 2-bit reference type (global, local,
88 * weak global). Real object pointers will have zeroes in the low 2 or 3
89 * bits (4- or 8-byte alignment), so it's useful to put the ref type
90 * in the low bits and reserve zero as an invalid value.
91 *
92 * The remaining 14 bits can be used to detect stale indirect references.
93 * For example, if objects don't move, we can use a hash of the original
94 * Object* to make sure the entry hasn't been re-used. (If the Object*
95 * we find there doesn't match because of heap movement, we could do a
96 * secondary check on the preserved hash value; this implies that creating
97 * a global/local ref queries the hash value and forces it to be saved.)
98 *
99 * A more rigorous approach would be to put a serial number in the extra
100 * bits, and keep a copy of the serial number in a parallel table. This is
101 * easier when objects can move, but requires 2x the memory and additional
102 * memory accesses on add/get. It will catch additional problems, e.g.:
103 * create iref1 for obj, delete iref1, create iref2 for same obj, lookup
104 * iref1. A pattern based on object bits will miss this.
105 */
106typedef void* IndirectRef;
107
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800108// Magic failure values; must not pass Heap::ValidateObject() or Heap::IsHeapAddress().
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800109static mirror::Object* const kInvalidIndirectRefObject = reinterpret_cast<mirror::Object*>(0xdead4321);
110static mirror::Object* const kClearedJniWeakGlobal = reinterpret_cast<mirror::Object*>(0xdead1234);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700111
112/*
113 * Indirect reference kind, used as the two low bits of IndirectRef.
114 *
115 * For convenience these match up with enum jobjectRefType from jni.h.
116 */
117enum IndirectRefKind {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700118 kHandleScopeOrInvalid = 0, // <<stack indirect reference table or invalid reference>>
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700119 kLocal = 1, // <<local reference>>
120 kGlobal = 2, // <<global reference>>
121 kWeakGlobal = 3 // <<weak global reference>>
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700122};
Elliott Hughes0e57ccb2012-04-03 16:04:52 -0700123std::ostream& operator<<(std::ostream& os, const IndirectRefKind& rhs);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700124
125/*
126 * Determine what kind of indirect reference this is.
127 */
128static inline IndirectRefKind GetIndirectRefKind(IndirectRef iref) {
129 return static_cast<IndirectRefKind>(reinterpret_cast<uintptr_t>(iref) & 0x03);
130}
131
132/*
133 * Extended debugging structure. We keep a parallel array of these, one
134 * per slot in the table.
135 */
136static const size_t kIRTPrevCount = 4;
137struct IndirectRefSlot {
138 uint32_t serial;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800139 const mirror::Object* previous[kIRTPrevCount];
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700140};
141
142/* use as initial value for "cookie", and when table has only one segment */
143static const uint32_t IRT_FIRST_SEGMENT = 0;
144
145/*
146 * Table definition.
147 *
148 * For the global reference table, the expected common operations are
149 * adding a new entry and removing a recently-added entry (usually the
150 * most-recently-added entry). For JNI local references, the common
151 * operations are adding a new entry and removing an entire table segment.
152 *
153 * If "alloc_entries_" is not equal to "max_entries_", the table may expand
154 * when entries are added, which means the memory may move. If you want
155 * to keep pointers into "table" rather than offsets, you must use a
156 * fixed-size table.
157 *
158 * If we delete entries from the middle of the list, we will be left with
159 * "holes". We track the number of holes so that, when adding new elements,
160 * we can quickly decide to do a trivial append or go slot-hunting.
161 *
162 * When the top-most entry is removed, any holes immediately below it are
163 * also removed. Thus, deletion of an entry may reduce "topIndex" by more
164 * than one.
165 *
166 * To get the desired behavior for JNI locals, we need to know the bottom
167 * and top of the current "segment". The top is managed internally, and
Elliott Hughes81ff3182012-03-23 20:35:56 -0700168 * the bottom is passed in as a function argument. When we call a native method or
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700169 * push a local frame, the current top index gets pushed on, and serves
170 * as the new bottom. When we pop a frame off, the value from the stack
171 * becomes the new top index, and the value stored in the previous frame
172 * becomes the new bottom.
173 *
174 * To avoid having to re-scan the table after a pop, we want to push the
175 * number of holes in the table onto the stack. Because of our 64K-entry
176 * cap, we can combine the two into a single unsigned 32-bit value.
177 * Instead of a "bottom" argument we take a "cookie", which includes the
178 * bottom index and the count of holes below the bottom.
179 *
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700180 * Common alternative implementation: make IndirectRef a pointer to the
181 * actual reference slot. Instead of getting a table and doing a lookup,
182 * the lookup can be done instantly. Operations like determining the
183 * type and deleting the reference are more expensive because the table
184 * must be hunted for (i.e. you have to do a pointer comparison to see
185 * which table it's in), you can't move the table when expanding it (so
186 * realloc() is out), and tricks like serial number checking to detect
187 * stale references aren't possible (though we may be able to get similar
188 * benefits with other approaches).
189 *
190 * TODO: consider a "lastDeleteIndex" for quick hole-filling when an
191 * add immediately follows a delete; must invalidate after segment pop
192 * (which could increase the cost/complexity of method call/return).
193 * Might be worth only using it for JNI globals.
194 *
195 * TODO: may want completely different add/remove algorithms for global
196 * and local refs to improve performance. A large circular buffer might
197 * reduce the amortized cost of adding global references.
198 *
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700199 */
200union IRTSegmentState {
201 uint32_t all;
202 struct {
203 uint32_t topIndex:16; /* index of first unused entry */
204 uint32_t numHoles:16; /* #of holes in entire table */
205 } parts;
206};
207
208class IrtIterator {
209 public:
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700210 explicit IrtIterator(GcRoot<mirror::Object>* table, size_t i, size_t capacity)
211 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700212 : table_(table), i_(i), capacity_(capacity) {
213 SkipNullsAndTombstones();
214 }
215
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700216 IrtIterator& operator++() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700217 ++i_;
218 SkipNullsAndTombstones();
219 return *this;
220 }
221
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700222 mirror::Object** operator*() {
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700223 // This does not have a read barrier as this is used to visit roots.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700224 return table_[i_].AddressWithoutBarrier();
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700225 }
226
227 bool equals(const IrtIterator& rhs) const {
228 return (i_ == rhs.i_ && table_ == rhs.table_);
229 }
230
231 private:
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700232 void SkipNullsAndTombstones() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700233 // We skip NULLs and tombstones. Clients don't want to see implementation details.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700234 while (i_ < capacity_ &&
235 (table_[i_].IsNull() ||
236 table_[i_].Read<kWithoutReadBarrier>() == kClearedJniWeakGlobal)) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700237 ++i_;
238 }
239 }
240
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700241 GcRoot<mirror::Object>* const table_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700242 size_t i_;
243 size_t capacity_;
244};
245
Elliott Hughes726079d2011-10-07 18:43:44 -0700246bool inline operator==(const IrtIterator& lhs, const IrtIterator& rhs) {
247 return lhs.equals(rhs);
248}
249
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700250bool inline operator!=(const IrtIterator& lhs, const IrtIterator& rhs) {
251 return !lhs.equals(rhs);
252}
253
254class IndirectReferenceTable {
255 public:
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700256 IndirectReferenceTable(size_t initialCount, size_t maxCount, IndirectRefKind kind);
257
258 ~IndirectReferenceTable();
259
260 /*
Elliott Hughese84278b2012-03-22 10:06:53 -0700261 * Add a new entry. "obj" must be a valid non-NULL object reference.
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700262 *
263 * Returns NULL if the table is full (max entries reached, or alloc
264 * failed during expansion).
265 */
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700266 IndirectRef Add(uint32_t cookie, mirror::Object* obj)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700267 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700268
269 /*
270 * Given an IndirectRef in the table, return the Object it refers to.
271 *
272 * Returns kInvalidIndirectRefObject if iref is invalid.
273 */
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700274 template<ReadBarrierOption kReadBarrierOption = kWithReadBarrier>
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700275 mirror::Object* Get(IndirectRef iref) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
276 ALWAYS_INLINE;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700277
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700278 // Synchronized get which reads a reference, acquiring a lock if necessary.
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700279 template<ReadBarrierOption kReadBarrierOption = kWithReadBarrier>
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700280 mirror::Object* SynchronizedGet(Thread* /*self*/, ReaderWriterMutex* /*mutex*/,
281 IndirectRef iref) const
282 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -0700283 return Get<kReadBarrierOption>(iref);
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700284 }
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700285
286 /*
287 * Remove an existing entry.
288 *
289 * If the entry is not between the current top index and the bottom index
290 * specified by the cookie, we don't remove anything. This is the behavior
291 * required by JNI's DeleteLocalRef function.
292 *
293 * Returns "false" if nothing was removed.
294 */
295 bool Remove(uint32_t cookie, IndirectRef iref);
296
Elliott Hughes726079d2011-10-07 18:43:44 -0700297 void AssertEmpty();
298
Ian Rogersb726dcb2012-09-05 08:57:23 -0700299 void Dump(std::ostream& os) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700300
301 /*
302 * Return the #of entries in the entire table. This includes holes, and
303 * so may be larger than the actual number of "live" entries.
304 */
305 size_t Capacity() const {
Ian Rogersdc51b792011-09-22 20:41:37 -0700306 return segment_state_.parts.topIndex;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700307 }
308
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700309 // Note IrtIterator does not have a read barrier as it's used to visit roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700310 IrtIterator begin() {
311 return IrtIterator(table_, 0, Capacity());
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700312 }
313
Mathieu Chartier02e25112013-08-14 16:14:24 -0700314 IrtIterator end() {
315 return IrtIterator(table_, Capacity(), Capacity());
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700316 }
317
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700318 void VisitRoots(RootCallback* callback, void* arg, uint32_t tid, RootType root_type)
319 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700320
Ian Rogersad25ac52011-10-04 19:13:33 -0700321 uint32_t GetSegmentState() const {
322 return segment_state_.all;
323 }
324
325 void SetSegmentState(uint32_t new_state) {
326 segment_state_.all = new_state;
327 }
328
Ian Rogersdc51b792011-09-22 20:41:37 -0700329 static Offset SegmentStateOffset() {
330 return Offset(OFFSETOF_MEMBER(IndirectReferenceTable, segment_state_));
331 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800332
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700333 private:
334 /*
335 * Extract the table index from an indirect reference.
336 */
337 static uint32_t ExtractIndex(IndirectRef iref) {
Ian Rogersf61db682014-01-23 20:26:01 -0800338 uintptr_t uref = reinterpret_cast<uintptr_t>(iref);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700339 return (uref >> 2) & 0xffff;
340 }
341
342 /*
343 * The object pointer itself is subject to relocation in some GC
344 * implementations, so we shouldn't really be using it here.
345 */
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700346 IndirectRef ToIndirectRef(uint32_t tableIndex) const {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700347 DCHECK_LT(tableIndex, 65536U);
348 uint32_t serialChunk = slot_data_[tableIndex].serial;
Ian Rogersf61db682014-01-23 20:26:01 -0800349 uintptr_t uref = serialChunk << 20 | (tableIndex << 2) | kind_;
350 return reinterpret_cast<IndirectRef>(uref);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700351 }
352
353 /*
354 * Update extended debug info when an entry is added.
355 *
356 * We advance the serial number, invalidating any outstanding references to
357 * this slot.
358 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800359 void UpdateSlotAdd(const mirror::Object* obj, int slot) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700360 if (slot_data_ != NULL) {
361 IndirectRefSlot* pSlot = &slot_data_[slot];
362 pSlot->serial++;
363 pSlot->previous[pSlot->serial % kIRTPrevCount] = obj;
364 }
365 }
366
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700367 // Abort if check_jni is not enabled.
368 static void AbortIfNoCheckJNI();
369
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700370 /* extra debugging checks */
371 bool GetChecked(IndirectRef) const;
372 bool CheckEntry(const char*, IndirectRef, int) const;
373
Ian Rogersdc51b792011-09-22 20:41:37 -0700374 /* semi-public - read/write by jni down calls */
375 IRTSegmentState segment_state_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700376
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700377 // Mem map where we store the indirect refs.
Ian Rogers700a4022014-05-19 16:49:03 -0700378 std::unique_ptr<MemMap> table_mem_map_;
Mathieu Chartierc56057e2014-05-04 13:18:58 -0700379 // Mem map where we store the extended debugging info.
Ian Rogers700a4022014-05-19 16:49:03 -0700380 std::unique_ptr<MemMap> slot_mem_map_;
Hiroshi Yamauchiea2e1bd2014-06-18 13:47:35 -0700381 // bottom of the stack. Do not directly access the object references
382 // in this as they are roots. Use Get() that has a read barrier.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700383 GcRoot<mirror::Object>* table_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700384 /* bit mask, ORed into all irefs */
385 IndirectRefKind kind_;
386 /* extended debugging info */
387 IndirectRefSlot* slot_data_;
388 /* #of entries we have space for */
389 size_t alloc_entries_;
390 /* max #of entries allowed */
391 size_t max_entries_;
392};
393
394} // namespace art
395
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700396#endif // ART_RUNTIME_INDIRECT_REFERENCE_TABLE_H_