blob: 6e3ee259414689414dcb12994d9d39c9b8fc592e [file] [log] [blame]
Andy McFadden734155e2009-07-16 18:11:22 -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/*
18 * Indirect reference table management.
19 */
20#include "Dalvik.h"
21
22/*
23 * Initialize an IndirectRefTable structure.
24 */
25bool dvmInitIndirectRefTable(IndirectRefTable* pRef, int initialCount,
26 int maxCount, IndirectRefKind kind)
27{
28 assert(initialCount > 0);
29 assert(initialCount <= maxCount);
30 assert(kind == kIndirectKindLocal || kind == kIndirectKindGlobal);
31
32 pRef->table = (Object**) malloc(initialCount * sizeof(Object*));
33 if (pRef->table == NULL)
34 return false;
35#ifndef NDEBUG
36 memset(pRef->table, 0xd1, initialCount * sizeof(Object*));
37#endif
Andy McFaddenab00d452009-08-19 07:21:41 -070038 pRef->segmentState.all = IRT_FIRST_SEGMENT;
Andy McFadden734155e2009-07-16 18:11:22 -070039 pRef->allocEntries = initialCount;
40 pRef->maxEntries = maxCount;
41 pRef->kind = kind;
42
43 return true;
44}
45
46/*
47 * Clears out the contents of a IndirectRefTable, freeing allocated storage.
48 */
49void dvmClearIndirectRefTable(IndirectRefTable* pRef)
50{
51 free(pRef->table);
52 pRef->table = NULL;
53 pRef->allocEntries = pRef->maxEntries = -1;
54}
55
56/*
57 * Remove one or more segments from the top. The table entry identified
58 * by "cookie" becomes the new top-most entry.
59 *
60 * Returns false if "cookie" is invalid or the table has only one segment.
61 */
62bool dvmPopIndirectRefTableSegmentCheck(IndirectRefTable* pRef, u4 cookie)
63{
64 IRTSegmentState sst;
65
66 /*
67 * The new value for "top" must be <= the current value. Otherwise
68 * this would represent an expansion of the table.
69 */
70 sst.all = cookie;
71 if (sst.parts.topIndex > pRef->segmentState.parts.topIndex) {
72 LOGE("Attempt to expand table with segment pop (%d to %d)\n",
73 pRef->segmentState.parts.topIndex, sst.parts.topIndex);
74 return false;
75 }
76 if (sst.parts.numHoles >= sst.parts.topIndex) {
77 LOGE("Absurd numHoles in cookie (%d bi=%d)\n",
78 sst.parts.numHoles, sst.parts.topIndex);
79 return false;
80 }
81
82 LOGV("--- after pop, top=%d holes=%d\n",
83 sst.parts.topIndex, sst.parts.numHoles);
84
85 return true;
86}
87
88/*
89 * Make sure that the entry at "idx" is correctly paired with "iref".
90 */
91static bool checkEntry(IndirectRefTable* pRef, IndirectRef iref, int idx)
92{
93 Object* obj = pRef->table[idx];
94 IndirectRef checkRef = dvmObjectToIndirectRef(obj, idx, pRef->kind);
95 if (checkRef != iref) {
96 LOGW("iref mismatch: %p vs %p\n", iref, checkRef);
97 return false;
98 }
99 return true;
100}
101
102/*
103 * Add "obj" to "pRef".
104 */
105IndirectRef dvmAddToIndirectRefTable(IndirectRefTable* pRef, u4 cookie,
106 Object* obj)
107{
108 IRTSegmentState prevState;
109 prevState.all = cookie;
110 int topIndex = pRef->segmentState.parts.topIndex;
111 int bottomIndex = prevState.parts.topIndex;
112
113 assert(obj != NULL);
114 assert(dvmIsValidObject(obj));
115 assert(pRef->table != NULL);
116 assert(pRef->allocEntries <= pRef->maxEntries);
117 assert(pRef->segmentState.parts.numHoles >= prevState.parts.numHoles);
118
119 if (topIndex == pRef->allocEntries) {
120 /* reached end of allocated space; did we hit buffer max? */
121 if (topIndex == pRef->maxEntries) {
122 LOGW("ReferenceTable overflow (max=%d)\n", pRef->maxEntries);
123 return NULL;
124 }
125
126 Object** newTable;
127 int newSize;
128
129 newSize = pRef->allocEntries * 2;
130 if (newSize > pRef->maxEntries)
131 newSize = pRef->maxEntries;
132 assert(newSize > pRef->allocEntries);
133
134 newTable = (Object**) realloc(pRef->table, newSize * sizeof(Object*));
135 if (newTable == NULL) {
136 LOGE("Unable to expand iref table (from %d to %d entries)\n",
137 pRef->allocEntries, newSize);
138 return false;
139 }
140 LOGI("Growing %p from %d to %d\n", pRef, pRef->allocEntries, newSize);
141
142 /* update entries; adjust "nextEntry" in case memory moved */
143 pRef->table = newTable;
144 pRef->allocEntries = newSize;
145 }
146
147 IndirectRef result;
148
149 /*
150 * We know there's enough room in the table. Now we just need to find
151 * the right spot. If there's a hole, find it and fill it; otherwise,
152 * add to the end of the list.
153 */
154 int numHoles = pRef->segmentState.parts.numHoles - prevState.parts.numHoles;
155 if (numHoles > 0) {
156 assert(topIndex > 1);
157 /* find the first hole; likely to be near the end of the list */
158 Object** pScan = &pRef->table[topIndex - 1];
159 assert(*pScan != NULL);
160 while (*--pScan != NULL) {
161 assert(pScan >= pRef->table + bottomIndex);
162 }
163 result = dvmObjectToIndirectRef(obj, pScan - pRef->table, pRef->kind);
164 *pScan = obj;
165 pRef->segmentState.parts.numHoles--;
166 } else {
167 /* add to the end */
168 result = dvmObjectToIndirectRef(obj, topIndex, pRef->kind);
169 pRef->table[topIndex++] = obj;
170 pRef->segmentState.parts.topIndex = topIndex;
171 }
172
173 assert(result != NULL);
174 return result;
175}
176
177/*
178 * Verify that the indirect table lookup is valid.
179 *
180 * Returns "false" if something looks bad.
181 */
182bool dvmGetFromIndirectRefTableCheck(IndirectRefTable* pRef, IndirectRef iref)
183{
Andy McFaddenab00d452009-08-19 07:21:41 -0700184 if (dvmGetIndirectRefType(iref) == kIndirectKindInvalid) {
185 LOGW("Invalid indirect reference 0x%08x\n", (u4) iref);
186 return false;
187 }
188
Andy McFadden734155e2009-07-16 18:11:22 -0700189 int topIndex = pRef->segmentState.parts.topIndex;
190 int idx = dvmIndirectRefToIndex(iref);
191
192 if (iref == NULL) {
193 LOGI("--- lookup on NULL iref\n");
194 return false;
195 }
196 if (idx >= topIndex) {
197 /* bad -- stale reference? */
198 LOGI("Attempt to access invalid index %d (top=%d)\n",
199 idx, topIndex);
200 return false;
201 }
202
203 Object* obj = pRef->table[idx];
204 if (obj == NULL) {
205 LOGI("Attempt to read from hole, iref=%p\n", iref);
206 return false;
207 }
208 if (!checkEntry(pRef, iref, idx))
209 return false;
210
211 return true;
212}
213
214/*
215 * Remove "obj" from "pRef". We extract the table offset bits from "iref"
216 * and zap the corresponding entry, leaving a hole if it's not at the top.
217 *
218 * If the entry is not between the current top index and the bottom index
219 * specified by the cookie, we don't remove anything. This is the behavior
220 * required by JNI's DeleteLocalRef function.
221 *
222 * Returns "false" if nothing was removed.
223 */
224bool dvmRemoveFromIndirectRefTable(IndirectRefTable* pRef, u4 cookie,
225 IndirectRef iref)
226{
227 IRTSegmentState prevState;
228 prevState.all = cookie;
229 int topIndex = pRef->segmentState.parts.topIndex;
230 int bottomIndex = prevState.parts.topIndex;
231
232 assert(pRef->table != NULL);
233 assert(pRef->allocEntries <= pRef->maxEntries);
234 assert(pRef->segmentState.parts.numHoles >= prevState.parts.numHoles);
235
236 int idx = dvmIndirectRefToIndex(iref);
237 if (idx < bottomIndex) {
238 /* wrong segment */
239 LOGV("Attempt to remove index outside index area (%d vs %d-%d)\n",
240 idx, bottomIndex, topIndex);
241 return false;
242 }
243 if (idx >= topIndex) {
244 /* bad -- stale reference? */
245 LOGI("Attempt to remove invalid index %d (bottom=%d top=%d)\n",
246 idx, bottomIndex, topIndex);
247 return false;
248 }
249
250 if (idx == topIndex-1) {
251 /*
252 * Top-most entry. Scan up and consume holes. No need to NULL
253 * out the entry, since the test vs. topIndex will catch it.
254 */
255 if (!checkEntry(pRef, iref, idx))
256 return false;
257
258#ifndef NDEBUG
259 pRef->table[idx] = (IndirectRef) 0xd3d3d3d3;
260#endif
261
262 int numHoles =
263 pRef->segmentState.parts.numHoles - prevState.parts.numHoles;
264 if (numHoles != 0) {
265 while (--topIndex > bottomIndex && numHoles != 0) {
266 LOGV("+++ checking for hole at %d (cookie=0x%08x) val=%p\n",
267 topIndex-1, cookie, pRef->table[topIndex-1]);
268 if (pRef->table[topIndex-1] != NULL)
269 break;
270 LOGV("+++ ate hole at %d\n", topIndex-1);
271 numHoles--;
272 }
273 pRef->segmentState.parts.numHoles =
274 numHoles + prevState.parts.numHoles;
275 pRef->segmentState.parts.topIndex = topIndex;
276 } else {
277 pRef->segmentState.parts.topIndex = topIndex-1;
278 LOGV("+++ ate last entry %d\n", topIndex-1);
279 }
280 } else {
281 /*
282 * Not the top-most entry. This creates a hole. We NULL out the
283 * entry to prevent somebody from deleting it twice and screwing up
284 * the hole count.
285 */
286 if (pRef->table[idx] == NULL) {
287 LOGV("--- WEIRD: removing null entry %d\n", idx);
288 return false;
289 }
290 if (!checkEntry(pRef, iref, idx))
291 return false;
292
293 pRef->table[idx] = NULL;
294 pRef->segmentState.parts.numHoles++;
295 LOGV("+++ left hole at %d, holes=%d\n",
296 idx, pRef->segmentState.parts.numHoles);
297 }
298
299 return true;
300}
301
302/*
303 * This is a qsort() callback. We sort Object* by class, allocation size,
304 * and then by the Object* itself.
305 */
306static int compareObject(const void* vobj1, const void* vobj2)
307{
308 Object* obj1 = *((Object**) vobj1);
309 Object* obj2 = *((Object**) vobj2);
310
311 /* ensure null references appear at the end */
312 if (obj1 == NULL) {
313 if (obj2 == NULL) {
314 return 0;
315 } else {
316 return 1;
317 }
318 } else if (obj2 == NULL) {
319 return -1;
320 }
321
322 if (obj1->clazz != obj2->clazz) {
323 return (u1*)obj1->clazz - (u1*)obj2->clazz;
324 } else {
325 int size1 = dvmObjectSizeInHeap(obj1);
326 int size2 = dvmObjectSizeInHeap(obj2);
327 if (size1 != size2) {
328 return size1 - size2;
329 } else {
330 return (u1*)obj1 - (u1*)obj2;
331 }
332 }
333}
334
335/*
336 * Log an object with some additional info.
337 *
338 * Pass in the number of additional elements that are identical to or
339 * equivalent to the original.
340 */
341static void logObject(Object* obj, int size, int identical, int equiv)
342{
343 if (obj == NULL) {
344 LOGW(" NULL reference (count=%d)\n", equiv);
345 return;
346 }
347
348 if (identical + equiv != 0) {
349 LOGW("%5d of %s %dB (%d unique)\n", identical + equiv +1,
350 obj->clazz->descriptor, size, equiv +1);
351 } else {
352 LOGW("%5d of %s %dB\n", identical + equiv +1,
353 obj->clazz->descriptor, size);
354 }
355}
356
357/*
358 * Dump the contents of a IndirectRefTable to the log.
359 */
360void dvmDumpIndirectRefTable(const IndirectRefTable* pRef, const char* descr)
361{
362 const int kLast = 10;
363 int count = dvmIndirectRefTableEntries(pRef);
364 Object** refs;
365 int i;
366
367 if (count == 0) {
368 LOGW("Reference table has no entries\n");
369 return;
370 }
371 assert(count > 0);
372
373 /*
374 * Dump the most recent N entries. If there are holes, we will show
375 * fewer than N.
376 */
377 LOGW("Last %d entries in %s reference table:\n", kLast, descr);
378 refs = pRef->table; // use unsorted list
379 int size;
380 int start = count - kLast;
381 if (start < 0)
382 start = 0;
383
384 for (i = start; i < count; i++) {
385 if (refs[i] == NULL)
386 continue;
387 size = dvmObjectSizeInHeap(refs[i]);
388 Object* ref = refs[i];
389 if (ref->clazz == gDvm.classJavaLangClass) {
390 ClassObject* clazz = (ClassObject*) ref;
391 LOGW("%5d: %p cls=%s '%s' (%d bytes)\n", i, ref,
392 (refs[i] == NULL) ? "-" : ref->clazz->descriptor,
393 clazz->descriptor, size);
394 } else {
395 LOGW("%5d: %p cls=%s (%d bytes)\n", i, ref,
396 (refs[i] == NULL) ? "-" : ref->clazz->descriptor, size);
397 }
398 }
399
400 /*
401 * Make a copy of the table, and sort it.
402 *
403 * The NULL "holes" wind up at the end, so we can strip them off easily.
404 */
405 Object** tableCopy = (Object**)malloc(sizeof(Object*) * count);
406 memcpy(tableCopy, pRef->table, sizeof(Object*) * count);
407 qsort(tableCopy, count, sizeof(Object*), compareObject);
408 refs = tableCopy; // use sorted list
409
410 {
411 int q;
412 for (q = 0; q < count; q++)
413 LOGI("%d %p\n", q, refs[q]);
414 }
415
416 int holes = 0;
417 while (refs[count-1] == NULL) {
418 count--;
419 holes++;
420 }
421
422 /*
423 * Dump uniquified table summary. While we're at it, generate a
424 * cumulative total amount of pinned memory based on the unique entries.
425 */
426 LOGW("%s reference table summary (%d entries / %d holes):\n",
427 descr, count, holes);
428 int equiv, identical, total;
429 total = equiv = identical = 0;
430 for (i = 1; i < count; i++) {
431 size = dvmObjectSizeInHeap(refs[i-1]);
432
433 if (refs[i] == refs[i-1]) {
434 /* same reference, added more than once */
435 identical++;
436 } else if (refs[i]->clazz == refs[i-1]->clazz &&
437 (int) dvmObjectSizeInHeap(refs[i]) == size)
438 {
439 /* same class / size, different object */
440 total += size;
441 equiv++;
442 } else {
443 /* different class */
444 total += size;
445 logObject(refs[i-1], size, identical, equiv);
446 equiv = identical = 0;
447 }
448 }
449
450 /* handle the last entry (everything above outputs refs[i-1]) */
451 size = (refs[count-1] == NULL) ? 0 : dvmObjectSizeInHeap(refs[count-1]);
452 total += size;
453 logObject(refs[count-1], size, identical, equiv);
454
455 LOGW("Memory held directly by native code is %d bytes\n", total);
456 free(tableCopy);
457}
458