blob: e09043dba79040d2bb73da6c6fe63855b6c7d3a7 [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
17#ifndef ART_SRC_INDIRECT_REFERENCE_TABLE_H_
18#define ART_SRC_INDIRECT_REFERENCE_TABLE_H_
19
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 Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "offsets.h"
27#include "root_visitor.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028
Elliott Hughes6c1a3942011-08-17 15:00:06 -070029namespace art {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030namespace mirror {
Elliott Hughes6c1a3942011-08-17 15:00:06 -070031class Object;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032} // namespace mirror
Elliott Hughes6c1a3942011-08-17 15:00:06 -070033
34/*
35 * Maintain a table of indirect references. Used for local/global JNI
36 * references.
37 *
38 * The table contains object references that are part of the GC root set.
39 * When an object is added we return an IndirectRef that is not a valid
40 * pointer but can be used to find the original value in O(1) time.
Elliott Hughes81ff3182012-03-23 20:35:56 -070041 * Conversions to and from indirect references are performed on upcalls
42 * and downcalls, so they need to be very fast.
Elliott Hughes6c1a3942011-08-17 15:00:06 -070043 *
44 * To be efficient for JNI local variable storage, we need to provide
45 * operations that allow us to operate on segments of the table, where
46 * segments are pushed and popped as if on a stack. For example, deletion
47 * of an entry should only succeed if it appears in the current segment,
48 * and we want to be able to strip off the current segment quickly when
49 * a method returns. Additions to the table must be made in the current
50 * segment even if space is available in an earlier area.
51 *
52 * A new segment is created when we call into native code from interpreted
53 * code, or when we handle the JNI PushLocalFrame function.
54 *
55 * The GC must be able to scan the entire table quickly.
56 *
57 * In summary, these must be very fast:
58 * - adding or removing a segment
59 * - adding references to a new segment
60 * - converting an indirect reference back to an Object
61 * These can be a little slower, but must still be pretty quick:
62 * - adding references to a "mature" segment
63 * - removing individual references
64 * - scanning the entire table straight through
65 *
66 * If there's more than one segment, we don't guarantee that the table
67 * will fill completely before we fail due to lack of space. We do ensure
68 * that the current segment will pack tightly, which should satisfy JNI
69 * requirements (e.g. EnsureLocalCapacity).
70 *
71 * To make everything fit nicely in 32-bit integers, the maximum size of
72 * the table is capped at 64K.
73 *
74 * None of the table functions are synchronized.
75 */
76
77/*
78 * Indirect reference definition. This must be interchangeable with JNI's
79 * jobject, and it's convenient to let null be null, so we use void*.
80 *
81 * We need a 16-bit table index and a 2-bit reference type (global, local,
82 * weak global). Real object pointers will have zeroes in the low 2 or 3
83 * bits (4- or 8-byte alignment), so it's useful to put the ref type
84 * in the low bits and reserve zero as an invalid value.
85 *
86 * The remaining 14 bits can be used to detect stale indirect references.
87 * For example, if objects don't move, we can use a hash of the original
88 * Object* to make sure the entry hasn't been re-used. (If the Object*
89 * we find there doesn't match because of heap movement, we could do a
90 * secondary check on the preserved hash value; this implies that creating
91 * a global/local ref queries the hash value and forces it to be saved.)
92 *
93 * A more rigorous approach would be to put a serial number in the extra
94 * bits, and keep a copy of the serial number in a parallel table. This is
95 * easier when objects can move, but requires 2x the memory and additional
96 * memory accesses on add/get. It will catch additional problems, e.g.:
97 * create iref1 for obj, delete iref1, create iref2 for same obj, lookup
98 * iref1. A pattern based on object bits will miss this.
99 */
100typedef void* IndirectRef;
101
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800102// Magic failure values; must not pass Heap::ValidateObject() or Heap::IsHeapAddress().
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800103static mirror::Object* const kInvalidIndirectRefObject = reinterpret_cast<mirror::Object*>(0xdead4321);
104static mirror::Object* const kClearedJniWeakGlobal = reinterpret_cast<mirror::Object*>(0xdead1234);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700105
106/*
107 * Indirect reference kind, used as the two low bits of IndirectRef.
108 *
109 * For convenience these match up with enum jobjectRefType from jni.h.
110 */
111enum IndirectRefKind {
Elliott Hughes0e57ccb2012-04-03 16:04:52 -0700112 kSirtOrInvalid = 0, // <<stack indirect reference table or invalid reference>>
113 kLocal = 1, // <<local reference>>
114 kGlobal = 2, // <<global reference>>
115 kWeakGlobal = 3 // <<weak global reference>>
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700116};
Elliott Hughes0e57ccb2012-04-03 16:04:52 -0700117std::ostream& operator<<(std::ostream& os, const IndirectRefKind& rhs);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700118
119/*
120 * Determine what kind of indirect reference this is.
121 */
122static inline IndirectRefKind GetIndirectRefKind(IndirectRef iref) {
123 return static_cast<IndirectRefKind>(reinterpret_cast<uintptr_t>(iref) & 0x03);
124}
125
126/*
127 * Extended debugging structure. We keep a parallel array of these, one
128 * per slot in the table.
129 */
130static const size_t kIRTPrevCount = 4;
131struct IndirectRefSlot {
132 uint32_t serial;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800133 const mirror::Object* previous[kIRTPrevCount];
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700134};
135
136/* use as initial value for "cookie", and when table has only one segment */
137static const uint32_t IRT_FIRST_SEGMENT = 0;
138
139/*
140 * Table definition.
141 *
142 * For the global reference table, the expected common operations are
143 * adding a new entry and removing a recently-added entry (usually the
144 * most-recently-added entry). For JNI local references, the common
145 * operations are adding a new entry and removing an entire table segment.
146 *
147 * If "alloc_entries_" is not equal to "max_entries_", the table may expand
148 * when entries are added, which means the memory may move. If you want
149 * to keep pointers into "table" rather than offsets, you must use a
150 * fixed-size table.
151 *
152 * If we delete entries from the middle of the list, we will be left with
153 * "holes". We track the number of holes so that, when adding new elements,
154 * we can quickly decide to do a trivial append or go slot-hunting.
155 *
156 * When the top-most entry is removed, any holes immediately below it are
157 * also removed. Thus, deletion of an entry may reduce "topIndex" by more
158 * than one.
159 *
160 * To get the desired behavior for JNI locals, we need to know the bottom
161 * and top of the current "segment". The top is managed internally, and
Elliott Hughes81ff3182012-03-23 20:35:56 -0700162 * the bottom is passed in as a function argument. When we call a native method or
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700163 * push a local frame, the current top index gets pushed on, and serves
164 * as the new bottom. When we pop a frame off, the value from the stack
165 * becomes the new top index, and the value stored in the previous frame
166 * becomes the new bottom.
167 *
168 * To avoid having to re-scan the table after a pop, we want to push the
169 * number of holes in the table onto the stack. Because of our 64K-entry
170 * cap, we can combine the two into a single unsigned 32-bit value.
171 * Instead of a "bottom" argument we take a "cookie", which includes the
172 * bottom index and the count of holes below the bottom.
173 *
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700174 * Common alternative implementation: make IndirectRef a pointer to the
175 * actual reference slot. Instead of getting a table and doing a lookup,
176 * the lookup can be done instantly. Operations like determining the
177 * type and deleting the reference are more expensive because the table
178 * must be hunted for (i.e. you have to do a pointer comparison to see
179 * which table it's in), you can't move the table when expanding it (so
180 * realloc() is out), and tricks like serial number checking to detect
181 * stale references aren't possible (though we may be able to get similar
182 * benefits with other approaches).
183 *
184 * TODO: consider a "lastDeleteIndex" for quick hole-filling when an
185 * add immediately follows a delete; must invalidate after segment pop
186 * (which could increase the cost/complexity of method call/return).
187 * Might be worth only using it for JNI globals.
188 *
189 * TODO: may want completely different add/remove algorithms for global
190 * and local refs to improve performance. A large circular buffer might
191 * reduce the amortized cost of adding global references.
192 *
193 * TODO: if we can guarantee that the underlying storage doesn't move,
194 * e.g. by using oversized mmap regions to handle expanding tables, we may
195 * be able to avoid having to synchronize lookups. Might make sense to
196 * add a "synchronized lookup" call that takes the mutex as an argument,
197 * and either locks or doesn't lock based on internal details.
198 */
199union IRTSegmentState {
200 uint32_t all;
201 struct {
202 uint32_t topIndex:16; /* index of first unused entry */
203 uint32_t numHoles:16; /* #of holes in entire table */
204 } parts;
205};
206
207class IrtIterator {
208 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800209 explicit IrtIterator(const mirror::Object** table, size_t i, size_t capacity)
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700210 : table_(table), i_(i), capacity_(capacity) {
211 SkipNullsAndTombstones();
212 }
213
214 IrtIterator& operator++() {
215 ++i_;
216 SkipNullsAndTombstones();
217 return *this;
218 }
219
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800220 const mirror::Object** operator*() {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700221 return &table_[i_];
222 }
223
224 bool equals(const IrtIterator& rhs) const {
225 return (i_ == rhs.i_ && table_ == rhs.table_);
226 }
227
228 private:
229 void SkipNullsAndTombstones() {
230 // We skip NULLs and tombstones. Clients don't want to see implementation details.
231 while (i_ < capacity_ && (table_[i_] == NULL || table_[i_] == kClearedJniWeakGlobal)) {
232 ++i_;
233 }
234 }
235
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800236 const mirror::Object** table_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700237 size_t i_;
238 size_t capacity_;
239};
240
Elliott Hughes726079d2011-10-07 18:43:44 -0700241bool inline operator==(const IrtIterator& lhs, const IrtIterator& rhs) {
242 return lhs.equals(rhs);
243}
244
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700245bool inline operator!=(const IrtIterator& lhs, const IrtIterator& rhs) {
246 return !lhs.equals(rhs);
247}
248
249class IndirectReferenceTable {
250 public:
251 typedef IrtIterator iterator;
252
253 IndirectReferenceTable(size_t initialCount, size_t maxCount, IndirectRefKind kind);
254
255 ~IndirectReferenceTable();
256
257 /*
Elliott Hughese84278b2012-03-22 10:06:53 -0700258 * Add a new entry. "obj" must be a valid non-NULL object reference.
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700259 *
260 * Returns NULL if the table is full (max entries reached, or alloc
261 * failed during expansion).
262 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800263 IndirectRef Add(uint32_t cookie, const mirror::Object* obj)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700265
266 /*
267 * Given an IndirectRef in the table, return the Object it refers to.
268 *
269 * Returns kInvalidIndirectRefObject if iref is invalid.
270 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800271 const mirror::Object* Get(IndirectRef iref) const {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700272 if (!GetChecked(iref)) {
273 return kInvalidIndirectRefObject;
274 }
275 return table_[ExtractIndex(iref)];
276 }
277
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700278 // TODO: remove when we remove work_around_app_jni_bugs support.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800279 bool ContainsDirectPointer(mirror::Object* direct_pointer) const;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700280
281 /*
282 * Remove an existing entry.
283 *
284 * If the entry is not between the current top index and the bottom index
285 * specified by the cookie, we don't remove anything. This is the behavior
286 * required by JNI's DeleteLocalRef function.
287 *
288 * Returns "false" if nothing was removed.
289 */
290 bool Remove(uint32_t cookie, IndirectRef iref);
291
Elliott Hughes726079d2011-10-07 18:43:44 -0700292 void AssertEmpty();
293
Ian Rogersb726dcb2012-09-05 08:57:23 -0700294 void Dump(std::ostream& os) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700295
296 /*
297 * Return the #of entries in the entire table. This includes holes, and
298 * so may be larger than the actual number of "live" entries.
299 */
300 size_t Capacity() const {
Ian Rogersdc51b792011-09-22 20:41:37 -0700301 return segment_state_.parts.topIndex;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700302 }
303
304 iterator begin() {
305 return iterator(table_, 0, Capacity());
306 }
307
308 iterator end() {
309 return iterator(table_, Capacity(), Capacity());
310 }
311
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800312 void VisitRoots(RootVisitor* visitor, void* arg);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700313
Ian Rogersad25ac52011-10-04 19:13:33 -0700314 uint32_t GetSegmentState() const {
315 return segment_state_.all;
316 }
317
318 void SetSegmentState(uint32_t new_state) {
319 segment_state_.all = new_state;
320 }
321
Ian Rogersdc51b792011-09-22 20:41:37 -0700322 static Offset SegmentStateOffset() {
323 return Offset(OFFSETOF_MEMBER(IndirectReferenceTable, segment_state_));
324 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800325
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700326 private:
327 /*
328 * Extract the table index from an indirect reference.
329 */
330 static uint32_t ExtractIndex(IndirectRef iref) {
331 uint32_t uref = (uint32_t) iref;
332 return (uref >> 2) & 0xffff;
333 }
334
335 /*
336 * The object pointer itself is subject to relocation in some GC
337 * implementations, so we shouldn't really be using it here.
338 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800339 IndirectRef ToIndirectRef(const mirror::Object* /*o*/, uint32_t tableIndex) const {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700340 DCHECK_LT(tableIndex, 65536U);
341 uint32_t serialChunk = slot_data_[tableIndex].serial;
342 uint32_t uref = serialChunk << 20 | (tableIndex << 2) | kind_;
343 return (IndirectRef) uref;
344 }
345
346 /*
347 * Update extended debug info when an entry is added.
348 *
349 * We advance the serial number, invalidating any outstanding references to
350 * this slot.
351 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800352 void UpdateSlotAdd(const mirror::Object* obj, int slot) {
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700353 if (slot_data_ != NULL) {
354 IndirectRefSlot* pSlot = &slot_data_[slot];
355 pSlot->serial++;
356 pSlot->previous[pSlot->serial % kIRTPrevCount] = obj;
357 }
358 }
359
360 /* extra debugging checks */
361 bool GetChecked(IndirectRef) const;
362 bool CheckEntry(const char*, IndirectRef, int) const;
363
Ian Rogersdc51b792011-09-22 20:41:37 -0700364 /* semi-public - read/write by jni down calls */
365 IRTSegmentState segment_state_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700366
367 /* bottom of the stack */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800368 const mirror::Object** table_;
Elliott Hughes6c1a3942011-08-17 15:00:06 -0700369 /* bit mask, ORed into all irefs */
370 IndirectRefKind kind_;
371 /* extended debugging info */
372 IndirectRefSlot* slot_data_;
373 /* #of entries we have space for */
374 size_t alloc_entries_;
375 /* max #of entries allowed */
376 size_t max_entries_;
377};
378
379} // namespace art
380
381#endif // ART_SRC_INDIRECT_REFERENCE_TABLE_H_