blob: 8f5189b58b524f89abf39f9cdf078dab2c2d0958 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 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 * Garbage-collecting memory allocator.
18 */
19#include "Dalvik.h"
Barry Hayes962adba2010-03-17 12:12:39 -070020#include "alloc/HeapBitmap.h"
21#include "alloc/Verify.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080022#include "alloc/HeapTable.h"
23#include "alloc/Heap.h"
24#include "alloc/HeapInternal.h"
25#include "alloc/DdmHeap.h"
26#include "alloc/HeapSource.h"
27#include "alloc/MarkSweep.h"
Carl Shapiro106c5fd2010-07-28 14:12:27 -070028#include "alloc/Visit.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080029
30#include "utils/threads.h" // need Android thread priorities
31#define kInvalidPriority 10000
32
San Mehat5a2056c2009-09-12 10:10:13 -070033#include <cutils/sched_policy.h>
34
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080035#include <sys/time.h>
36#include <sys/resource.h>
37#include <limits.h>
38#include <errno.h>
39
Barry Hayes1b9b4e42010-01-04 10:33:46 -080040static const char* GcReasonStr[] = {
41 [GC_FOR_MALLOC] = "GC_FOR_MALLOC",
Carl Shapiroec805ea2010-06-28 16:28:26 -070042 [GC_CONCURRENT] = "GC_CONCURRENT",
Barry Hayes1b9b4e42010-01-04 10:33:46 -080043 [GC_EXPLICIT] = "GC_EXPLICIT",
44 [GC_EXTERNAL_ALLOC] = "GC_EXTERNAL_ALLOC",
45 [GC_HPROF_DUMP_HEAP] = "GC_HPROF_DUMP_HEAP"
46};
47
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080048/*
49 * Initialize the GC heap.
50 *
51 * Returns true if successful, false otherwise.
52 */
53bool dvmHeapStartup()
54{
55 GcHeap *gcHeap;
56
57#if defined(WITH_ALLOC_LIMITS)
58 gDvm.checkAllocLimits = false;
59 gDvm.allocationLimit = -1;
60#endif
61
62 gcHeap = dvmHeapSourceStartup(gDvm.heapSizeStart, gDvm.heapSizeMax);
63 if (gcHeap == NULL) {
64 return false;
65 }
66 gcHeap->heapWorkerCurrentObject = NULL;
67 gcHeap->heapWorkerCurrentMethod = NULL;
68 gcHeap->heapWorkerInterpStartTime = 0LL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080069 gcHeap->ddmHpifWhen = 0;
70 gcHeap->ddmHpsgWhen = 0;
71 gcHeap->ddmHpsgWhat = 0;
72 gcHeap->ddmNhsgWhen = 0;
73 gcHeap->ddmNhsgWhat = 0;
74#if WITH_HPROF
75 gcHeap->hprofDumpOnGc = false;
76 gcHeap->hprofContext = NULL;
77#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080078 gDvm.gcHeap = gcHeap;
79
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080080 /* Set up the lists and lock we'll use for finalizable
81 * and reference objects.
82 */
83 dvmInitMutex(&gDvm.heapWorkerListLock);
84 gcHeap->finalizableRefs = NULL;
85 gcHeap->pendingFinalizationRefs = NULL;
86 gcHeap->referenceOperations = NULL;
87
Barry Hayesb874ab92010-07-14 08:13:18 -070088 if (!dvmCardTableStartup()) {
89 LOGE_HEAP("card table startup failed.");
90 return false;
91 }
92
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080093 /* Initialize the HeapWorker locks and other state
94 * that the GC uses.
95 */
96 dvmInitializeHeapWorkerState();
97
98 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080099}
100
Carl Shapiroec805ea2010-06-28 16:28:26 -0700101bool dvmHeapStartupAfterZygote(void)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800102{
Carl Shapiroec805ea2010-06-28 16:28:26 -0700103 return dvmHeapSourceStartupAfterZygote();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800104}
105
106void dvmHeapShutdown()
107{
108//TODO: make sure we're locked
109 if (gDvm.gcHeap != NULL) {
Barry Hayesb874ab92010-07-14 08:13:18 -0700110 dvmCardTableShutdown();
111 /* Tables are allocated on the native heap; they need to be
112 * cleaned up explicitly. The process may stick around, so we
113 * don't want to leak any native memory.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800114 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800115 dvmHeapFreeLargeTable(gDvm.gcHeap->finalizableRefs);
116 gDvm.gcHeap->finalizableRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117
Carl Shapiroa199eb72010-02-09 16:26:30 -0800118 dvmHeapFreeLargeTable(gDvm.gcHeap->pendingFinalizationRefs);
119 gDvm.gcHeap->pendingFinalizationRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800120
Carl Shapiroa199eb72010-02-09 16:26:30 -0800121 dvmHeapFreeLargeTable(gDvm.gcHeap->referenceOperations);
122 gDvm.gcHeap->referenceOperations = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800123
Barry Hayesb874ab92010-07-14 08:13:18 -0700124 /* Destroy the heap. Any outstanding pointers will point to
125 * unmapped memory (unless/until someone else maps it). This
126 * frees gDvm.gcHeap as a side-effect.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800127 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800128 dvmHeapSourceShutdown(&gDvm.gcHeap);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800129 }
130}
131
132/*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700133 * Shutdown any threads internal to the heap.
134 */
135void dvmHeapThreadShutdown(void)
136{
137 dvmHeapSourceThreadShutdown();
138}
139
140/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800141 * We've been asked to allocate something we can't, e.g. an array so
Andy McFadden6da743b2009-07-15 16:56:00 -0700142 * large that (length * elementWidth) is larger than 2^31.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800143 *
Andy McFadden6da743b2009-07-15 16:56:00 -0700144 * _The Java Programming Language_, 4th edition, says, "you can be sure
145 * that all SoftReferences to softly reachable objects will be cleared
146 * before an OutOfMemoryError is thrown."
147 *
148 * It's unclear whether that holds for all situations where an OOM can
149 * be thrown, or just in the context of an allocation that fails due
150 * to lack of heap space. For simplicity we just throw the exception.
151 *
152 * (OOM due to actually running out of space is handled elsewhere.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800153 */
154void dvmThrowBadAllocException(const char* msg)
155{
Andy McFadden6da743b2009-07-15 16:56:00 -0700156 dvmThrowException("Ljava/lang/OutOfMemoryError;", msg);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800157}
158
159/*
160 * Grab the lock, but put ourselves into THREAD_VMWAIT if it looks like
161 * we're going to have to wait on the mutex.
162 */
163bool dvmLockHeap()
164{
Carl Shapiro980ffb02010-03-13 22:34:01 -0800165 if (dvmTryLockMutex(&gDvm.gcHeapLock) != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800166 Thread *self;
167 ThreadStatus oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800168
169 self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -0700170 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800171 dvmLockMutex(&gDvm.gcHeapLock);
Carl Shapiro5617ad32010-07-02 10:50:57 -0700172 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800173 }
174
175 return true;
176}
177
178void dvmUnlockHeap()
179{
180 dvmUnlockMutex(&gDvm.gcHeapLock);
181}
182
183/* Pop an object from the list of pending finalizations and
184 * reference clears/enqueues, and return the object.
185 * The caller must call dvmReleaseTrackedAlloc()
186 * on the object when finished.
187 *
188 * Typically only called by the heap worker thread.
189 */
190Object *dvmGetNextHeapWorkerObject(HeapWorkerOperation *op)
191{
192 Object *obj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800193 GcHeap *gcHeap = gDvm.gcHeap;
194
195 assert(op != NULL);
196
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800197 dvmLockMutex(&gDvm.heapWorkerListLock);
198
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800199 obj = dvmHeapGetNextObjectFromLargeTable(&gcHeap->referenceOperations);
200 if (obj != NULL) {
Carl Shapiro646ba092010-06-10 15:17:00 -0700201 *op = WORKER_ENQUEUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800202 } else {
203 obj = dvmHeapGetNextObjectFromLargeTable(
204 &gcHeap->pendingFinalizationRefs);
205 if (obj != NULL) {
206 *op = WORKER_FINALIZE;
207 }
208 }
209
210 if (obj != NULL) {
211 /* Don't let the GC collect the object until the
212 * worker thread is done with it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800213 */
214 dvmAddTrackedAlloc(obj, NULL);
215 }
216
217 dvmUnlockMutex(&gDvm.heapWorkerListLock);
218
219 return obj;
220}
221
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800222/* Do a full garbage collection, which may grow the
223 * heap as a side-effect if the live set is large.
224 */
225static void gcForMalloc(bool collectSoftReferences)
226{
227#ifdef WITH_PROFILER
228 if (gDvm.allocProf.enabled) {
229 Thread* self = dvmThreadSelf();
230 gDvm.allocProf.gcCount++;
231 if (self != NULL) {
232 self->allocProf.gcCount++;
233 }
234 }
235#endif
236 /* This may adjust the soft limit as a side-effect.
237 */
238 LOGD_HEAP("dvmMalloc initiating GC%s\n",
239 collectSoftReferences ? "(collect SoftReferences)" : "");
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800240 dvmCollectGarbageInternal(collectSoftReferences, GC_FOR_MALLOC);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800241}
242
243/* Try as hard as possible to allocate some memory.
244 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800245static void *tryMalloc(size_t size)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800246{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800247 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800248
249 /* Don't try too hard if there's no way the allocation is
250 * going to succeed. We have to collect SoftReferences before
251 * throwing an OOME, though.
252 */
253 if (size >= gDvm.heapSizeMax) {
254 LOGW_HEAP("dvmMalloc(%zu/0x%08zx): "
255 "someone's allocating a huge buffer\n", size, size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800256 ptr = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800257 goto collect_soft_refs;
258 }
259
260//TODO: figure out better heuristics
261// There will be a lot of churn if someone allocates a bunch of
262// big objects in a row, and we hit the frag case each time.
263// A full GC for each.
264// Maybe we grow the heap in bigger leaps
265// Maybe we skip the GC if the size is large and we did one recently
266// (number of allocations ago) (watch for thread effects)
267// DeflateTest allocs a bunch of ~128k buffers w/in 0-5 allocs of each other
268// (or, at least, there are only 0-5 objects swept each time)
269
Carl Shapiro6343bd02010-02-16 17:40:19 -0800270 ptr = dvmHeapSourceAlloc(size);
271 if (ptr != NULL) {
272 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800273 }
274
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700275 /*
276 * The allocation failed. If the GC is running, block until it
277 * completes and retry.
278 */
279 if (gDvm.gcHeap->gcRunning) {
280 /*
281 * The GC is concurrently tracing the heap. Release the heap
282 * lock, wait for the GC to complete, and retrying allocating.
283 */
284 dvmWaitForConcurrentGcToComplete();
285 ptr = dvmHeapSourceAlloc(size);
286 if (ptr != NULL) {
287 return ptr;
288 }
289 }
290 /*
291 * Another failure. Our thread was starved or there may be too
292 * many live objects. Try a foreground GC. This will have no
293 * effect if the concurrent GC is already running.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800294 */
295 gcForMalloc(false);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800296 ptr = dvmHeapSourceAlloc(size);
297 if (ptr != NULL) {
298 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800299 }
300
301 /* Even that didn't work; this is an exceptional state.
302 * Try harder, growing the heap if necessary.
303 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800304 ptr = dvmHeapSourceAllocAndGrow(size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800305 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800306 size_t newHeapSize;
307
308 newHeapSize = dvmHeapSourceGetIdealFootprint();
309//TODO: may want to grow a little bit more so that the amount of free
310// space is equal to the old free space + the utilization slop for
311// the new allocation.
312 LOGI_HEAP("Grow heap (frag case) to "
313 "%zu.%03zuMB for %zu-byte allocation\n",
314 FRACTIONAL_MB(newHeapSize), size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800315 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800316 }
317
318 /* Most allocations should have succeeded by now, so the heap
319 * is really full, really fragmented, or the requested size is
320 * really big. Do another GC, collecting SoftReferences this
321 * time. The VM spec requires that all SoftReferences have
322 * been collected and cleared before throwing an OOME.
323 */
324//TODO: wait for the finalizers from the previous GC to finish
325collect_soft_refs:
326 LOGI_HEAP("Forcing collection of SoftReferences for %zu-byte allocation\n",
327 size);
328 gcForMalloc(true);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800329 ptr = dvmHeapSourceAllocAndGrow(size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800330 if (ptr != NULL) {
331 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800332 }
333//TODO: maybe wait for finalizers and try one last time
334
335 LOGE_HEAP("Out of memory on a %zd-byte allocation.\n", size);
336//TODO: tell the HeapSource to dump its state
337 dvmDumpThread(dvmThreadSelf(), false);
338
339 return NULL;
340}
341
342/* Throw an OutOfMemoryError if there's a thread to attach it to.
343 * Avoid recursing.
344 *
345 * The caller must not be holding the heap lock, or else the allocations
346 * in dvmThrowException() will deadlock.
347 */
348static void throwOOME()
349{
350 Thread *self;
351
352 if ((self = dvmThreadSelf()) != NULL) {
353 /* If the current (failing) dvmMalloc() happened as part of thread
354 * creation/attachment before the thread became part of the root set,
355 * we can't rely on the thread-local trackedAlloc table, so
356 * we can't keep track of a real allocated OOME object. But, since
357 * the thread is in the process of being created, it won't have
358 * a useful stack anyway, so we may as well make things easier
359 * by throwing the (stackless) pre-built OOME.
360 */
361 if (dvmIsOnThreadList(self) && !self->throwingOOME) {
362 /* Let ourselves know that we tried to throw an OOM
363 * error in the normal way in case we run out of
364 * memory trying to allocate it inside dvmThrowException().
365 */
366 self->throwingOOME = true;
367
368 /* Don't include a description string;
369 * one fewer allocation.
370 */
371 dvmThrowException("Ljava/lang/OutOfMemoryError;", NULL);
372 } else {
373 /*
374 * This thread has already tried to throw an OutOfMemoryError,
375 * which probably means that we're running out of memory
376 * while recursively trying to throw.
377 *
378 * To avoid any more allocation attempts, "throw" a pre-built
379 * OutOfMemoryError object (which won't have a useful stack trace).
380 *
381 * Note that since this call can't possibly allocate anything,
382 * we don't care about the state of self->throwingOOME
383 * (which will usually already be set).
384 */
385 dvmSetException(self, gDvm.outOfMemoryObj);
386 }
387 /* We're done with the possible recursion.
388 */
389 self->throwingOOME = false;
390 }
391}
392
393/*
394 * Allocate storage on the GC heap. We guarantee 8-byte alignment.
395 *
396 * The new storage is zeroed out.
397 *
398 * Note that, in rare cases, this could get called while a GC is in
399 * progress. If a non-VM thread tries to attach itself through JNI,
400 * it will need to allocate some objects. If this becomes annoying to
401 * deal with, we can block it at the source, but holding the allocation
402 * mutex should be enough.
403 *
404 * In rare circumstances (JNI AttachCurrentThread) we can be called
405 * from a non-VM thread.
406 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800407 * Use ALLOC_DONT_TRACK when we either don't want to track an allocation
408 * (because it's being done for the interpreter "new" operation and will
409 * be part of the root set immediately) or we can't (because this allocation
410 * is for a brand new thread).
411 *
412 * Returns NULL and throws an exception on failure.
413 *
414 * TODO: don't do a GC if the debugger thinks all threads are suspended
415 */
416void* dvmMalloc(size_t size, int flags)
417{
418 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800419 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800420
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800421#if defined(WITH_ALLOC_LIMITS)
422 /*
423 * See if they've exceeded the allocation limit for this thread.
424 *
425 * A limit value of -1 means "no limit".
426 *
427 * This is enabled at compile time because it requires us to do a
428 * TLS lookup for the Thread pointer. This has enough of a performance
429 * impact that we don't want to do it if we don't have to. (Now that
430 * we're using gDvm.checkAllocLimits we may want to reconsider this,
431 * but it's probably still best to just compile the check out of
432 * production code -- one less thing to hit on every allocation.)
433 */
434 if (gDvm.checkAllocLimits) {
435 Thread* self = dvmThreadSelf();
436 if (self != NULL) {
437 int count = self->allocLimit;
438 if (count > 0) {
439 self->allocLimit--;
440 } else if (count == 0) {
441 /* fail! */
442 assert(!gDvm.initializing);
443 self->allocLimit = -1;
444 dvmThrowException("Ldalvik/system/AllocationLimitError;",
445 "thread allocation limit exceeded");
446 return NULL;
447 }
448 }
449 }
450
451 if (gDvm.allocationLimit >= 0) {
452 assert(!gDvm.initializing);
453 gDvm.allocationLimit = -1;
454 dvmThrowException("Ldalvik/system/AllocationLimitError;",
455 "global allocation limit exceeded");
456 return NULL;
457 }
458#endif
459
460 dvmLockHeap();
461
462 /* Try as hard as possible to allocate some memory.
463 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800464 ptr = tryMalloc(size);
465 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800466 /* We've got the memory.
467 */
468 if ((flags & ALLOC_FINALIZABLE) != 0) {
469 /* This object is an instance of a class that
470 * overrides finalize(). Add it to the finalizable list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800471 */
472 if (!dvmHeapAddRefToLargeTable(&gcHeap->finalizableRefs,
Carl Shapiro6343bd02010-02-16 17:40:19 -0800473 (Object *)ptr))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800474 {
475 LOGE_HEAP("dvmMalloc(): no room for any more "
476 "finalizable objects\n");
477 dvmAbort();
478 }
479 }
480
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800481#ifdef WITH_PROFILER
482 if (gDvm.allocProf.enabled) {
483 Thread* self = dvmThreadSelf();
484 gDvm.allocProf.allocCount++;
485 gDvm.allocProf.allocSize += size;
486 if (self != NULL) {
487 self->allocProf.allocCount++;
488 self->allocProf.allocSize += size;
489 }
490 }
491#endif
492 } else {
493 /* The allocation failed.
494 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800495
496#ifdef WITH_PROFILER
497 if (gDvm.allocProf.enabled) {
498 Thread* self = dvmThreadSelf();
499 gDvm.allocProf.failedAllocCount++;
500 gDvm.allocProf.failedAllocSize += size;
501 if (self != NULL) {
502 self->allocProf.failedAllocCount++;
503 self->allocProf.failedAllocSize += size;
504 }
505 }
506#endif
507 }
508
509 dvmUnlockHeap();
510
511 if (ptr != NULL) {
512 /*
Barry Hayesd4f78d32010-06-08 09:34:42 -0700513 * If caller hasn't asked us not to track it, add it to the
514 * internal tracking list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800515 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700516 if ((flags & ALLOC_DONT_TRACK) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800517 dvmAddTrackedAlloc(ptr, NULL);
518 }
519 } else {
Ben Chengc3b92b22010-01-26 16:46:15 -0800520 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800521 * The allocation failed; throw an OutOfMemoryError.
522 */
523 throwOOME();
524 }
525
526 return ptr;
527}
528
529/*
530 * Returns true iff <obj> points to a valid allocated object.
531 */
532bool dvmIsValidObject(const Object* obj)
533{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800534 /* Don't bother if it's NULL or not 8-byte aligned.
535 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800536 if (obj != NULL && ((uintptr_t)obj & (8-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800537 /* Even if the heap isn't locked, this shouldn't return
538 * any false negatives. The only mutation that could
539 * be happening is allocation, which means that another
540 * thread could be in the middle of a read-modify-write
541 * to add a new bit for a new object. However, that
542 * RMW will have completed by the time any other thread
543 * could possibly see the new pointer, so there is no
544 * danger of dvmIsValidObject() being called on a valid
545 * pointer whose bit isn't set.
546 *
547 * Freeing will only happen during the sweep phase, which
548 * only happens while the heap is locked.
549 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800550 return dvmHeapSourceContains(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800551 }
552 return false;
553}
554
Barry Hayes364f9d92010-06-11 16:12:47 -0700555/*
556 * Returns true iff <obj> points to a word-aligned address within Heap
557 * address space.
558 */
559bool dvmIsValidObjectAddress(const void* ptr)
560{
561 /* Don't bother if it's not 4-byte aligned.
562 */
563 if (((uintptr_t)ptr & (4-1)) == 0) {
564 return dvmHeapSourceContainsAddress(ptr);
565 }
566 return false;
567}
568
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800569size_t dvmObjectSizeInHeap(const Object *obj)
570{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800571 return dvmHeapSourceChunkSize(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800572}
573
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700574static void verifyRootsAndHeap(void)
Barry Hayes962adba2010-03-17 12:12:39 -0700575{
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700576 dvmVerifyRoots();
577 dvmVerifyBitmap(dvmHeapSourceGetLiveBits());
Barry Hayes962adba2010-03-17 12:12:39 -0700578}
579
580/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800581 * Initiate garbage collection.
582 *
583 * NOTES:
584 * - If we don't hold gDvm.threadListLock, it's possible for a thread to
585 * be added to the thread list while we work. The thread should NOT
586 * start executing, so this is only interesting when we start chasing
587 * thread stacks. (Before we do so, grab the lock.)
588 *
589 * We are not allowed to GC when the debugger has suspended the VM, which
590 * is awkward because debugger requests can cause allocations. The easiest
591 * way to enforce this is to refuse to GC on an allocation made by the
592 * JDWP thread -- we have to expand the heap or fail.
593 */
Carl Shapiro29540742010-03-26 15:34:39 -0700594void dvmCollectGarbageInternal(bool clearSoftRefs, GcReason reason)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800595{
596 GcHeap *gcHeap = gDvm.gcHeap;
Carl Shapiro03f3b132010-07-27 17:25:31 -0700597 u4 suspendStart, totalTime;
598 u4 rootStart, rootEnd, rootTime, rootSuspendTime;
599 u4 dirtyStart, dirtyEnd, dirtyTime, dirtySuspendTime;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800600 int numFreed;
601 size_t sizeFreed;
Carl Shapirod25566d2010-03-11 20:39:47 -0800602 GcMode gcMode;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700603 int oldThreadPriority = kInvalidPriority;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800604
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800605 /* The heap lock must be held.
606 */
607
608 if (gcHeap->gcRunning) {
609 LOGW_HEAP("Attempted recursive GC\n");
610 return;
611 }
Carl Shapiro03f3b132010-07-27 17:25:31 -0700612
Carl Shapirod25566d2010-03-11 20:39:47 -0800613 gcMode = (reason == GC_FOR_MALLOC) ? GC_PARTIAL : GC_FULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800614 gcHeap->gcRunning = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800615
Carl Shapiro03f3b132010-07-27 17:25:31 -0700616 suspendStart = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800617 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700618 rootStart = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800619
Carl Shapiroec805ea2010-06-28 16:28:26 -0700620 /*
621 * If we are not marking concurrently raise the priority of the
622 * thread performing the garbage collection.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800623 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700624 if (reason != GC_CONCURRENT) {
625 /* Get the priority (the "nice" value) of the current thread. The
626 * getpriority() call can legitimately return -1, so we have to
627 * explicitly test errno.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800628 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700629 errno = 0;
630 int priorityResult = getpriority(PRIO_PROCESS, 0);
631 if (errno != 0) {
632 LOGI_HEAP("getpriority(self) failed: %s\n", strerror(errno));
633 } else if (priorityResult > ANDROID_PRIORITY_NORMAL) {
634 /* Current value is numerically greater than "normal", which
635 * in backward UNIX terms means lower priority.
636 */
San Mehat256fc152009-04-21 14:03:06 -0700637
Carl Shapiroec805ea2010-06-28 16:28:26 -0700638 if (priorityResult >= ANDROID_PRIORITY_BACKGROUND) {
639 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
640 }
San Mehat256fc152009-04-21 14:03:06 -0700641
Carl Shapiroec805ea2010-06-28 16:28:26 -0700642 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
643 LOGI_HEAP("Unable to elevate priority from %d to %d\n",
644 priorityResult, ANDROID_PRIORITY_NORMAL);
645 } else {
646 /* priority elevated; save value so we can restore it later */
647 LOGD_HEAP("Elevating priority from %d to %d\n",
648 priorityResult, ANDROID_PRIORITY_NORMAL);
649 oldThreadPriority = priorityResult;
650 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800651 }
652 }
653
654 /* Wait for the HeapWorker thread to block.
655 * (It may also already be suspended in interp code,
656 * in which case it's not holding heapWorkerLock.)
657 */
658 dvmLockMutex(&gDvm.heapWorkerLock);
659
660 /* Make sure that the HeapWorker thread hasn't become
661 * wedged inside interp code. If it has, this call will
662 * print a message and abort the VM.
663 */
664 dvmAssertHeapWorkerThreadRunning();
665
666 /* Lock the pendingFinalizationRefs list.
667 *
668 * Acquire the lock after suspending so the finalizer
669 * thread can't block in the RUNNING state while
670 * we try to suspend.
671 */
672 dvmLockMutex(&gDvm.heapWorkerListLock);
673
Barry Hayes962adba2010-03-17 12:12:39 -0700674 if (gDvm.preVerify) {
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700675 LOGV_HEAP("Verifying roots and heap before GC");
676 verifyRootsAndHeap();
Barry Hayes962adba2010-03-17 12:12:39 -0700677 }
678
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800679#ifdef WITH_PROFILER
680 dvmMethodTraceGCBegin();
681#endif
682
683#if WITH_HPROF
684
685/* Set DUMP_HEAP_ON_DDMS_UPDATE to 1 to enable heap dumps
686 * whenever DDMS requests a heap update (HPIF chunk).
687 * The output files will appear in /data/misc, which must
688 * already exist.
689 * You must define "WITH_HPROF := true" in your buildspec.mk
690 * and recompile libdvm for this to work.
691 *
692 * To enable stack traces for each allocation, define
693 * "WITH_HPROF_STACK := true" in buildspec.mk. This option slows down
694 * allocations and also requires 8 additional bytes per object on the
695 * GC heap.
696 */
697#define DUMP_HEAP_ON_DDMS_UPDATE 0
698#if DUMP_HEAP_ON_DDMS_UPDATE
699 gcHeap->hprofDumpOnGc |= (gcHeap->ddmHpifWhen != 0);
700#endif
701
702 if (gcHeap->hprofDumpOnGc) {
703 char nameBuf[128];
704
The Android Open Source Project99409882009-03-18 22:20:24 -0700705 gcHeap->hprofResult = -1;
706
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800707 if (gcHeap->hprofFileName == NULL) {
708 /* no filename was provided; invent one */
709 sprintf(nameBuf, "/data/misc/heap-dump-tm%d-pid%d.hprof",
710 (int) time(NULL), (int) getpid());
711 gcHeap->hprofFileName = nameBuf;
712 }
Andy McFadden6bf992c2010-01-28 17:01:39 -0800713 gcHeap->hprofContext = hprofStartup(gcHeap->hprofFileName,
Andy McFadden4b851a72010-07-09 16:50:05 -0700714 gcHeap->hprofFd, gcHeap->hprofDirectToDdms);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800715 if (gcHeap->hprofContext != NULL) {
716 hprofStartHeapDump(gcHeap->hprofContext);
717 }
718 gcHeap->hprofDumpOnGc = false;
719 gcHeap->hprofFileName = NULL;
720 }
721#endif
722
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800723 /* Set up the marking context.
724 */
Carl Shapirod25566d2010-03-11 20:39:47 -0800725 if (!dvmHeapBeginMarkStep(gcMode)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700726 LOGE_HEAP("dvmHeapBeginMarkStep failed; aborting\n");
727 dvmAbort();
728 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800729
730 /* Mark the set of objects that are strongly reachable from the roots.
731 */
732 LOGD_HEAP("Marking...");
733 dvmHeapMarkRootSet();
734
735 /* dvmHeapScanMarkedObjects() will build the lists of known
736 * instances of the Reference classes.
737 */
738 gcHeap->softReferences = NULL;
739 gcHeap->weakReferences = NULL;
740 gcHeap->phantomReferences = NULL;
741
Carl Shapiroec805ea2010-06-28 16:28:26 -0700742 if (reason == GC_CONCURRENT) {
743 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700744 * Resume threads while tracing from the roots. We unlock the
745 * heap to allow mutator threads to allocate from free space.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700746 */
Carl Shapiro03f3b132010-07-27 17:25:31 -0700747 rootEnd = dvmGetRelativeTimeMsec();
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700748 dvmClearCardTable();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700749 dvmUnlockHeap();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700750 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700751 rootSuspendTime = rootStart - suspendStart;
752 rootTime = rootEnd - rootStart;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700753 }
754
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800755 /* Recursively mark any objects that marked objects point to strongly.
756 * If we're not collecting soft references, soft-reachable
757 * objects will also be marked.
758 */
759 LOGD_HEAP("Recursing...");
760 dvmHeapScanMarkedObjects();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800761
Carl Shapiroec805ea2010-06-28 16:28:26 -0700762 if (reason == GC_CONCURRENT) {
763 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700764 * Re-acquire the heap lock and perform the final thread
765 * suspension.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700766 */
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700767 dvmLockHeap();
Carl Shapiro03f3b132010-07-27 17:25:31 -0700768 suspendStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700769 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700770 dirtyStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700771 /*
772 * As no barrier intercepts root updates, we conservatively
773 * assume all roots may be gray and re-mark them.
774 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700775 dvmHeapReMarkRootSet();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700776 /*
Carl Shapiro5ba39372010-08-06 17:07:53 -0700777 * With the exception of reference objects and weak interned
778 * strings, all gray objects should now be on dirty cards.
779 */
780 if (gDvm.verifyCardTable) {
781 dvmVerifyCardTable();
782 }
783 /*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700784 * Recursively mark gray objects pointed to by the roots or by
785 * heap objects dirtied during the concurrent mark.
786 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700787 dvmHeapReScanMarkedObjects();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700788 }
789
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800790 /* All strongly-reachable objects have now been marked.
791 */
Carl Shapiro29540742010-03-26 15:34:39 -0700792 LOGD_HEAP("Handling soft references...");
793 if (!clearSoftRefs) {
794 dvmHandleSoftRefs(&gcHeap->softReferences);
795 }
796 dvmClearWhiteRefs(&gcHeap->softReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800797
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800798 LOGD_HEAP("Handling weak references...");
Carl Shapiro29540742010-03-26 15:34:39 -0700799 dvmClearWhiteRefs(&gcHeap->weakReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800800
801 /* Once all weak-reachable objects have been taken
802 * care of, any remaining unmarked objects can be finalized.
803 */
804 LOGD_HEAP("Finding finalizations...");
805 dvmHeapScheduleFinalizations();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800806
Carl Shapiro29540742010-03-26 15:34:39 -0700807 LOGD_HEAP("Handling f-reachable soft references...");
808 dvmClearWhiteRefs(&gcHeap->softReferences);
809
810 LOGD_HEAP("Handling f-reachable weak references...");
811 dvmClearWhiteRefs(&gcHeap->weakReferences);
812
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800813 /* Any remaining objects that are not pending finalization
814 * could be phantom-reachable. This will mark any phantom-reachable
815 * objects, as well as enqueue their references.
816 */
817 LOGD_HEAP("Handling phantom references...");
Carl Shapiro29540742010-03-26 15:34:39 -0700818 dvmClearWhiteRefs(&gcHeap->phantomReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800819
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800820#ifdef WITH_DEADLOCK_PREDICTION
821 dvmDumpMonitorInfo("before sweep");
822#endif
823 LOGD_HEAP("Sweeping...");
Carl Shapirod25566d2010-03-11 20:39:47 -0800824 dvmHeapSweepUnmarkedObjects(gcMode, &numFreed, &sizeFreed);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800825#ifdef WITH_DEADLOCK_PREDICTION
826 dvmDumpMonitorInfo("after sweep");
827#endif
828
829 LOGD_HEAP("Cleaning up...");
830 dvmHeapFinishMarkStep();
831
832 LOGD_HEAP("Done.");
833
834 /* Now's a good time to adjust the heap size, since
835 * we know what our utilization is.
836 *
837 * This doesn't actually resize any memory;
838 * it just lets the heap grow more when necessary.
839 */
840 dvmHeapSourceGrowForUtilization();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800841
842#if WITH_HPROF
843 if (gcHeap->hprofContext != NULL) {
844 hprofFinishHeapDump(gcHeap->hprofContext);
845//TODO: write a HEAP_SUMMARY record
The Android Open Source Project99409882009-03-18 22:20:24 -0700846 if (hprofShutdown(gcHeap->hprofContext))
847 gcHeap->hprofResult = 0; /* indicate success */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800848 gcHeap->hprofContext = NULL;
849 }
850#endif
851
852 /* Now that we've freed up the GC heap, return any large
853 * free chunks back to the system. They'll get paged back
854 * in the next time they're used. Don't do it immediately,
855 * though; if the process is still allocating a bunch of
856 * memory, we'll be taking a ton of page faults that we don't
857 * necessarily need to.
858 *
859 * Cancel any old scheduled trims, and schedule a new one.
860 */
861 dvmScheduleHeapSourceTrim(5); // in seconds
862
863#ifdef WITH_PROFILER
864 dvmMethodTraceGCEnd();
865#endif
Barry Hayes962adba2010-03-17 12:12:39 -0700866 LOGV_HEAP("GC finished");
867
868 if (gDvm.postVerify) {
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700869 LOGV_HEAP("Verifying roots and heap after GC");
870 verifyRootsAndHeap();
Barry Hayes962adba2010-03-17 12:12:39 -0700871 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800872
873 gcHeap->gcRunning = false;
874
Barry Hayes962adba2010-03-17 12:12:39 -0700875 LOGV_HEAP("Resuming threads");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800876 dvmUnlockMutex(&gDvm.heapWorkerListLock);
877 dvmUnlockMutex(&gDvm.heapWorkerLock);
878
Ben Chengc3b92b22010-01-26 16:46:15 -0800879#if defined(WITH_JIT)
Ben Chengc3b92b22010-01-26 16:46:15 -0800880 /*
881 * Patching a chaining cell is very cheap as it only updates 4 words. It's
882 * the overhead of stopping all threads and synchronizing the I/D cache
883 * that makes it expensive.
884 *
885 * Therefore we batch those work orders in a queue and go through them
886 * when threads are suspended for GC.
887 */
888 dvmCompilerPerformSafePointChecks();
889#endif
890
Carl Shapiro03f3b132010-07-27 17:25:31 -0700891 dirtyEnd = dvmGetRelativeTimeMsec();
892
893 if (reason == GC_CONCURRENT) {
894 dirtySuspendTime = dirtyStart - suspendStart;
895 dirtyTime = dirtyEnd - dirtyStart;
896 }
897
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800898 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700899
900 if (reason == GC_CONCURRENT) {
901 /*
902 * Wake-up any threads that blocked after a failed allocation
903 * request.
904 */
905 dvmBroadcastCond(&gDvm.gcHeapCond);
906 }
907
Carl Shapiroec805ea2010-06-28 16:28:26 -0700908 if (reason != GC_CONCURRENT) {
909 if (oldThreadPriority != kInvalidPriority) {
910 if (setpriority(PRIO_PROCESS, 0, oldThreadPriority) != 0) {
911 LOGW_HEAP("Unable to reset priority to %d: %s\n",
912 oldThreadPriority, strerror(errno));
913 } else {
914 LOGD_HEAP("Reset priority to %d\n", oldThreadPriority);
915 }
San Mehat256fc152009-04-21 14:03:06 -0700916
Carl Shapiroec805ea2010-06-28 16:28:26 -0700917 if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
918 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
919 }
San Mehat256fc152009-04-21 14:03:06 -0700920 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800921 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800922
Carl Shapiro03f3b132010-07-27 17:25:31 -0700923 if (reason != GC_CONCURRENT) {
924 u4 suspendTime = rootStart - suspendStart;
925 u4 markSweepTime = dirtyEnd - rootStart;
926 totalTime = suspendTime + markSweepTime;
927 LOGD("%s freed %d objects / %zd bytes in (%ums) %ums",
928 GcReasonStr[reason], numFreed, sizeFreed,
929 suspendTime, markSweepTime);
930 } else {
931 totalTime = rootSuspendTime + rootTime + dirtySuspendTime + dirtyTime;
932 LOGD("%s freed %d objects / %zd bytes in (%ums) %ums (%ums) %ums",
933 GcReasonStr[reason], numFreed, sizeFreed,
934 rootSuspendTime, rootTime,
935 dirtySuspendTime, dirtyTime);
936 }
937 dvmLogGcStats(numFreed, sizeFreed, totalTime);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800938 if (gcHeap->ddmHpifWhen != 0) {
939 LOGD_HEAP("Sending VM heap info to DDM\n");
940 dvmDdmSendHeapInfo(gcHeap->ddmHpifWhen, false);
941 }
942 if (gcHeap->ddmHpsgWhen != 0) {
943 LOGD_HEAP("Dumping VM heap to DDM\n");
944 dvmDdmSendHeapSegments(false, false);
945 }
946 if (gcHeap->ddmNhsgWhen != 0) {
947 LOGD_HEAP("Dumping native heap to DDM\n");
948 dvmDdmSendHeapSegments(false, true);
949 }
950}
951
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700952void dvmWaitForConcurrentGcToComplete(void)
953{
954 Thread *self = dvmThreadSelf();
955 ThreadStatus oldStatus;
956 assert(self != NULL);
957 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
958 dvmWaitCond(&gDvm.gcHeapCond, &gDvm.gcHeapLock);
959 dvmChangeStatus(self, oldStatus);
960}
961
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800962#if WITH_HPROF
963/*
964 * Perform garbage collection, writing heap information to the specified file.
965 *
Andy McFadden4b851a72010-07-09 16:50:05 -0700966 * If "fd" is >= 0, the output will be written to that file descriptor.
967 * Otherwise, "fileName" is used to create an output file.
968 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800969 * If "fileName" is NULL, a suitable name will be generated automatically.
Andy McFadden4b851a72010-07-09 16:50:05 -0700970 * (TODO: remove this when the SIGUSR1 feature goes away)
971 *
972 * If "directToDdms" is set, the other arguments are ignored, and data is
973 * sent directly to DDMS.
The Android Open Source Project99409882009-03-18 22:20:24 -0700974 *
975 * Returns 0 on success, or an error code on failure.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800976 */
Andy McFadden4b851a72010-07-09 16:50:05 -0700977int hprofDumpHeap(const char* fileName, int fd, bool directToDdms)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800978{
The Android Open Source Project99409882009-03-18 22:20:24 -0700979 int result;
980
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800981 dvmLockMutex(&gDvm.gcHeapLock);
982
983 gDvm.gcHeap->hprofDumpOnGc = true;
984 gDvm.gcHeap->hprofFileName = fileName;
Andy McFadden4b851a72010-07-09 16:50:05 -0700985 gDvm.gcHeap->hprofFd = fd;
Andy McFadden6bf992c2010-01-28 17:01:39 -0800986 gDvm.gcHeap->hprofDirectToDdms = directToDdms;
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800987 dvmCollectGarbageInternal(false, GC_HPROF_DUMP_HEAP);
The Android Open Source Project99409882009-03-18 22:20:24 -0700988 result = gDvm.gcHeap->hprofResult;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800989
990 dvmUnlockMutex(&gDvm.gcHeapLock);
The Android Open Source Project99409882009-03-18 22:20:24 -0700991
992 return result;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800993}
994
995void dvmHeapSetHprofGcScanState(hprof_heap_tag_t state, u4 threadSerialNumber)
996{
997 if (gDvm.gcHeap->hprofContext != NULL) {
998 hprofSetGcScanState(gDvm.gcHeap->hprofContext, state,
999 threadSerialNumber);
1000 }
1001}
1002#endif