blob: b25e3a43e84241d25834a22b208ef79ec2536f02 [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"
28
29#include "utils/threads.h" // need Android thread priorities
30#define kInvalidPriority 10000
31
San Mehat5a2056c2009-09-12 10:10:13 -070032#include <cutils/sched_policy.h>
33
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080034#include <sys/time.h>
35#include <sys/resource.h>
36#include <limits.h>
37#include <errno.h>
38
Barry Hayes1b9b4e42010-01-04 10:33:46 -080039static const char* GcReasonStr[] = {
40 [GC_FOR_MALLOC] = "GC_FOR_MALLOC",
Carl Shapiroec805ea2010-06-28 16:28:26 -070041 [GC_CONCURRENT] = "GC_CONCURRENT",
Barry Hayes1b9b4e42010-01-04 10:33:46 -080042 [GC_EXPLICIT] = "GC_EXPLICIT",
43 [GC_EXTERNAL_ALLOC] = "GC_EXTERNAL_ALLOC",
44 [GC_HPROF_DUMP_HEAP] = "GC_HPROF_DUMP_HEAP"
45};
46
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080047/*
48 * Initialize the GC heap.
49 *
50 * Returns true if successful, false otherwise.
51 */
52bool dvmHeapStartup()
53{
54 GcHeap *gcHeap;
55
56#if defined(WITH_ALLOC_LIMITS)
57 gDvm.checkAllocLimits = false;
58 gDvm.allocationLimit = -1;
59#endif
60
61 gcHeap = dvmHeapSourceStartup(gDvm.heapSizeStart, gDvm.heapSizeMax);
62 if (gcHeap == NULL) {
63 return false;
64 }
65 gcHeap->heapWorkerCurrentObject = NULL;
66 gcHeap->heapWorkerCurrentMethod = NULL;
67 gcHeap->heapWorkerInterpStartTime = 0LL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080068 gcHeap->ddmHpifWhen = 0;
69 gcHeap->ddmHpsgWhen = 0;
70 gcHeap->ddmHpsgWhat = 0;
71 gcHeap->ddmNhsgWhen = 0;
72 gcHeap->ddmNhsgWhat = 0;
73#if WITH_HPROF
74 gcHeap->hprofDumpOnGc = false;
75 gcHeap->hprofContext = NULL;
76#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080077 gDvm.gcHeap = gcHeap;
78
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080079 /* Set up the lists and lock we'll use for finalizable
80 * and reference objects.
81 */
82 dvmInitMutex(&gDvm.heapWorkerListLock);
83 gcHeap->finalizableRefs = NULL;
84 gcHeap->pendingFinalizationRefs = NULL;
85 gcHeap->referenceOperations = NULL;
86
Barry Hayesb874ab92010-07-14 08:13:18 -070087 if (!dvmCardTableStartup()) {
88 LOGE_HEAP("card table startup failed.");
89 return false;
90 }
91
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080092 /* Initialize the HeapWorker locks and other state
93 * that the GC uses.
94 */
95 dvmInitializeHeapWorkerState();
96
97 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080098}
99
Carl Shapiroec805ea2010-06-28 16:28:26 -0700100bool dvmHeapStartupAfterZygote(void)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800101{
102 /* Update our idea of the last GC start time so that we
103 * don't use the last time that Zygote happened to GC.
104 */
105 gDvm.gcHeap->gcStartTime = dvmGetRelativeTimeUsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700106 return dvmHeapSourceStartupAfterZygote();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800107}
108
109void dvmHeapShutdown()
110{
111//TODO: make sure we're locked
112 if (gDvm.gcHeap != NULL) {
Barry Hayesb874ab92010-07-14 08:13:18 -0700113 dvmCardTableShutdown();
114 /* Tables are allocated on the native heap; they need to be
115 * cleaned up explicitly. The process may stick around, so we
116 * don't want to leak any native memory.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800118 dvmHeapFreeLargeTable(gDvm.gcHeap->finalizableRefs);
119 gDvm.gcHeap->finalizableRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800120
Carl Shapiroa199eb72010-02-09 16:26:30 -0800121 dvmHeapFreeLargeTable(gDvm.gcHeap->pendingFinalizationRefs);
122 gDvm.gcHeap->pendingFinalizationRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800123
Carl Shapiroa199eb72010-02-09 16:26:30 -0800124 dvmHeapFreeLargeTable(gDvm.gcHeap->referenceOperations);
125 gDvm.gcHeap->referenceOperations = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800126
Barry Hayesb874ab92010-07-14 08:13:18 -0700127 /* Destroy the heap. Any outstanding pointers will point to
128 * unmapped memory (unless/until someone else maps it). This
129 * frees gDvm.gcHeap as a side-effect.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800130 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800131 dvmHeapSourceShutdown(&gDvm.gcHeap);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800132 }
133}
134
135/*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700136 * Shutdown any threads internal to the heap.
137 */
138void dvmHeapThreadShutdown(void)
139{
140 dvmHeapSourceThreadShutdown();
141}
142
143/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800144 * We've been asked to allocate something we can't, e.g. an array so
Andy McFadden6da743b2009-07-15 16:56:00 -0700145 * large that (length * elementWidth) is larger than 2^31.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800146 *
Andy McFadden6da743b2009-07-15 16:56:00 -0700147 * _The Java Programming Language_, 4th edition, says, "you can be sure
148 * that all SoftReferences to softly reachable objects will be cleared
149 * before an OutOfMemoryError is thrown."
150 *
151 * It's unclear whether that holds for all situations where an OOM can
152 * be thrown, or just in the context of an allocation that fails due
153 * to lack of heap space. For simplicity we just throw the exception.
154 *
155 * (OOM due to actually running out of space is handled elsewhere.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800156 */
157void dvmThrowBadAllocException(const char* msg)
158{
Andy McFadden6da743b2009-07-15 16:56:00 -0700159 dvmThrowException("Ljava/lang/OutOfMemoryError;", msg);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800160}
161
162/*
163 * Grab the lock, but put ourselves into THREAD_VMWAIT if it looks like
164 * we're going to have to wait on the mutex.
165 */
166bool dvmLockHeap()
167{
Carl Shapiro980ffb02010-03-13 22:34:01 -0800168 if (dvmTryLockMutex(&gDvm.gcHeapLock) != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800169 Thread *self;
170 ThreadStatus oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800171
172 self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -0700173 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800174 dvmLockMutex(&gDvm.gcHeapLock);
Carl Shapiro5617ad32010-07-02 10:50:57 -0700175 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800176 }
177
178 return true;
179}
180
181void dvmUnlockHeap()
182{
183 dvmUnlockMutex(&gDvm.gcHeapLock);
184}
185
186/* Pop an object from the list of pending finalizations and
187 * reference clears/enqueues, and return the object.
188 * The caller must call dvmReleaseTrackedAlloc()
189 * on the object when finished.
190 *
191 * Typically only called by the heap worker thread.
192 */
193Object *dvmGetNextHeapWorkerObject(HeapWorkerOperation *op)
194{
195 Object *obj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800196 GcHeap *gcHeap = gDvm.gcHeap;
197
198 assert(op != NULL);
199
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800200 dvmLockMutex(&gDvm.heapWorkerListLock);
201
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800202 obj = dvmHeapGetNextObjectFromLargeTable(&gcHeap->referenceOperations);
203 if (obj != NULL) {
Carl Shapiro646ba092010-06-10 15:17:00 -0700204 *op = WORKER_ENQUEUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800205 } else {
206 obj = dvmHeapGetNextObjectFromLargeTable(
207 &gcHeap->pendingFinalizationRefs);
208 if (obj != NULL) {
209 *op = WORKER_FINALIZE;
210 }
211 }
212
213 if (obj != NULL) {
214 /* Don't let the GC collect the object until the
215 * worker thread is done with it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800216 */
217 dvmAddTrackedAlloc(obj, NULL);
218 }
219
220 dvmUnlockMutex(&gDvm.heapWorkerListLock);
221
222 return obj;
223}
224
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800225/* Whenever the effective heap size may have changed,
226 * this function must be called.
227 */
228void dvmHeapSizeChanged()
229{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800230}
231
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800232/* Do a full garbage collection, which may grow the
233 * heap as a side-effect if the live set is large.
234 */
235static void gcForMalloc(bool collectSoftReferences)
236{
237#ifdef WITH_PROFILER
238 if (gDvm.allocProf.enabled) {
239 Thread* self = dvmThreadSelf();
240 gDvm.allocProf.gcCount++;
241 if (self != NULL) {
242 self->allocProf.gcCount++;
243 }
244 }
245#endif
246 /* This may adjust the soft limit as a side-effect.
247 */
248 LOGD_HEAP("dvmMalloc initiating GC%s\n",
249 collectSoftReferences ? "(collect SoftReferences)" : "");
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800250 dvmCollectGarbageInternal(collectSoftReferences, GC_FOR_MALLOC);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800251}
252
253/* Try as hard as possible to allocate some memory.
254 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800255static void *tryMalloc(size_t size)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800256{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800257 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800258
259 /* Don't try too hard if there's no way the allocation is
260 * going to succeed. We have to collect SoftReferences before
261 * throwing an OOME, though.
262 */
263 if (size >= gDvm.heapSizeMax) {
264 LOGW_HEAP("dvmMalloc(%zu/0x%08zx): "
265 "someone's allocating a huge buffer\n", size, size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800266 ptr = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800267 goto collect_soft_refs;
268 }
269
270//TODO: figure out better heuristics
271// There will be a lot of churn if someone allocates a bunch of
272// big objects in a row, and we hit the frag case each time.
273// A full GC for each.
274// Maybe we grow the heap in bigger leaps
275// Maybe we skip the GC if the size is large and we did one recently
276// (number of allocations ago) (watch for thread effects)
277// DeflateTest allocs a bunch of ~128k buffers w/in 0-5 allocs of each other
278// (or, at least, there are only 0-5 objects swept each time)
279
Carl Shapiro6343bd02010-02-16 17:40:19 -0800280 ptr = dvmHeapSourceAlloc(size);
281 if (ptr != NULL) {
282 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800283 }
284
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700285 /*
286 * The allocation failed. If the GC is running, block until it
287 * completes and retry.
288 */
289 if (gDvm.gcHeap->gcRunning) {
290 /*
291 * The GC is concurrently tracing the heap. Release the heap
292 * lock, wait for the GC to complete, and retrying allocating.
293 */
294 dvmWaitForConcurrentGcToComplete();
295 ptr = dvmHeapSourceAlloc(size);
296 if (ptr != NULL) {
297 return ptr;
298 }
299 }
300 /*
301 * Another failure. Our thread was starved or there may be too
302 * many live objects. Try a foreground GC. This will have no
303 * effect if the concurrent GC is already running.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800304 */
305 gcForMalloc(false);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800306 ptr = dvmHeapSourceAlloc(size);
307 if (ptr != NULL) {
308 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800309 }
310
311 /* Even that didn't work; this is an exceptional state.
312 * Try harder, growing the heap if necessary.
313 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800314 ptr = dvmHeapSourceAllocAndGrow(size);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800315 dvmHeapSizeChanged();
Carl Shapiro6343bd02010-02-16 17:40:19 -0800316 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800317 size_t newHeapSize;
318
319 newHeapSize = dvmHeapSourceGetIdealFootprint();
320//TODO: may want to grow a little bit more so that the amount of free
321// space is equal to the old free space + the utilization slop for
322// the new allocation.
323 LOGI_HEAP("Grow heap (frag case) to "
324 "%zu.%03zuMB for %zu-byte allocation\n",
325 FRACTIONAL_MB(newHeapSize), size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800326 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800327 }
328
329 /* Most allocations should have succeeded by now, so the heap
330 * is really full, really fragmented, or the requested size is
331 * really big. Do another GC, collecting SoftReferences this
332 * time. The VM spec requires that all SoftReferences have
333 * been collected and cleared before throwing an OOME.
334 */
335//TODO: wait for the finalizers from the previous GC to finish
336collect_soft_refs:
337 LOGI_HEAP("Forcing collection of SoftReferences for %zu-byte allocation\n",
338 size);
339 gcForMalloc(true);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800340 ptr = dvmHeapSourceAllocAndGrow(size);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800341 dvmHeapSizeChanged();
Carl Shapiro6343bd02010-02-16 17:40:19 -0800342 if (ptr != NULL) {
343 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800344 }
345//TODO: maybe wait for finalizers and try one last time
346
347 LOGE_HEAP("Out of memory on a %zd-byte allocation.\n", size);
348//TODO: tell the HeapSource to dump its state
349 dvmDumpThread(dvmThreadSelf(), false);
350
351 return NULL;
352}
353
354/* Throw an OutOfMemoryError if there's a thread to attach it to.
355 * Avoid recursing.
356 *
357 * The caller must not be holding the heap lock, or else the allocations
358 * in dvmThrowException() will deadlock.
359 */
360static void throwOOME()
361{
362 Thread *self;
363
364 if ((self = dvmThreadSelf()) != NULL) {
365 /* If the current (failing) dvmMalloc() happened as part of thread
366 * creation/attachment before the thread became part of the root set,
367 * we can't rely on the thread-local trackedAlloc table, so
368 * we can't keep track of a real allocated OOME object. But, since
369 * the thread is in the process of being created, it won't have
370 * a useful stack anyway, so we may as well make things easier
371 * by throwing the (stackless) pre-built OOME.
372 */
373 if (dvmIsOnThreadList(self) && !self->throwingOOME) {
374 /* Let ourselves know that we tried to throw an OOM
375 * error in the normal way in case we run out of
376 * memory trying to allocate it inside dvmThrowException().
377 */
378 self->throwingOOME = true;
379
380 /* Don't include a description string;
381 * one fewer allocation.
382 */
383 dvmThrowException("Ljava/lang/OutOfMemoryError;", NULL);
384 } else {
385 /*
386 * This thread has already tried to throw an OutOfMemoryError,
387 * which probably means that we're running out of memory
388 * while recursively trying to throw.
389 *
390 * To avoid any more allocation attempts, "throw" a pre-built
391 * OutOfMemoryError object (which won't have a useful stack trace).
392 *
393 * Note that since this call can't possibly allocate anything,
394 * we don't care about the state of self->throwingOOME
395 * (which will usually already be set).
396 */
397 dvmSetException(self, gDvm.outOfMemoryObj);
398 }
399 /* We're done with the possible recursion.
400 */
401 self->throwingOOME = false;
402 }
403}
404
405/*
406 * Allocate storage on the GC heap. We guarantee 8-byte alignment.
407 *
408 * The new storage is zeroed out.
409 *
410 * Note that, in rare cases, this could get called while a GC is in
411 * progress. If a non-VM thread tries to attach itself through JNI,
412 * it will need to allocate some objects. If this becomes annoying to
413 * deal with, we can block it at the source, but holding the allocation
414 * mutex should be enough.
415 *
416 * In rare circumstances (JNI AttachCurrentThread) we can be called
417 * from a non-VM thread.
418 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800419 * Use ALLOC_DONT_TRACK when we either don't want to track an allocation
420 * (because it's being done for the interpreter "new" operation and will
421 * be part of the root set immediately) or we can't (because this allocation
422 * is for a brand new thread).
423 *
424 * Returns NULL and throws an exception on failure.
425 *
426 * TODO: don't do a GC if the debugger thinks all threads are suspended
427 */
428void* dvmMalloc(size_t size, int flags)
429{
430 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800431 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800432
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800433#if defined(WITH_ALLOC_LIMITS)
434 /*
435 * See if they've exceeded the allocation limit for this thread.
436 *
437 * A limit value of -1 means "no limit".
438 *
439 * This is enabled at compile time because it requires us to do a
440 * TLS lookup for the Thread pointer. This has enough of a performance
441 * impact that we don't want to do it if we don't have to. (Now that
442 * we're using gDvm.checkAllocLimits we may want to reconsider this,
443 * but it's probably still best to just compile the check out of
444 * production code -- one less thing to hit on every allocation.)
445 */
446 if (gDvm.checkAllocLimits) {
447 Thread* self = dvmThreadSelf();
448 if (self != NULL) {
449 int count = self->allocLimit;
450 if (count > 0) {
451 self->allocLimit--;
452 } else if (count == 0) {
453 /* fail! */
454 assert(!gDvm.initializing);
455 self->allocLimit = -1;
456 dvmThrowException("Ldalvik/system/AllocationLimitError;",
457 "thread allocation limit exceeded");
458 return NULL;
459 }
460 }
461 }
462
463 if (gDvm.allocationLimit >= 0) {
464 assert(!gDvm.initializing);
465 gDvm.allocationLimit = -1;
466 dvmThrowException("Ldalvik/system/AllocationLimitError;",
467 "global allocation limit exceeded");
468 return NULL;
469 }
470#endif
471
472 dvmLockHeap();
473
474 /* Try as hard as possible to allocate some memory.
475 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800476 ptr = tryMalloc(size);
477 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800478 /* We've got the memory.
479 */
480 if ((flags & ALLOC_FINALIZABLE) != 0) {
481 /* This object is an instance of a class that
482 * overrides finalize(). Add it to the finalizable list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800483 */
484 if (!dvmHeapAddRefToLargeTable(&gcHeap->finalizableRefs,
Carl Shapiro6343bd02010-02-16 17:40:19 -0800485 (Object *)ptr))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800486 {
487 LOGE_HEAP("dvmMalloc(): no room for any more "
488 "finalizable objects\n");
489 dvmAbort();
490 }
491 }
492
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800493#ifdef WITH_PROFILER
494 if (gDvm.allocProf.enabled) {
495 Thread* self = dvmThreadSelf();
496 gDvm.allocProf.allocCount++;
497 gDvm.allocProf.allocSize += size;
498 if (self != NULL) {
499 self->allocProf.allocCount++;
500 self->allocProf.allocSize += size;
501 }
502 }
503#endif
504 } else {
505 /* The allocation failed.
506 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800507
508#ifdef WITH_PROFILER
509 if (gDvm.allocProf.enabled) {
510 Thread* self = dvmThreadSelf();
511 gDvm.allocProf.failedAllocCount++;
512 gDvm.allocProf.failedAllocSize += size;
513 if (self != NULL) {
514 self->allocProf.failedAllocCount++;
515 self->allocProf.failedAllocSize += size;
516 }
517 }
518#endif
519 }
520
521 dvmUnlockHeap();
522
523 if (ptr != NULL) {
524 /*
Barry Hayesd4f78d32010-06-08 09:34:42 -0700525 * If caller hasn't asked us not to track it, add it to the
526 * internal tracking list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800527 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700528 if ((flags & ALLOC_DONT_TRACK) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800529 dvmAddTrackedAlloc(ptr, NULL);
530 }
531 } else {
Ben Chengc3b92b22010-01-26 16:46:15 -0800532 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800533 * The allocation failed; throw an OutOfMemoryError.
534 */
535 throwOOME();
536 }
537
538 return ptr;
539}
540
541/*
542 * Returns true iff <obj> points to a valid allocated object.
543 */
544bool dvmIsValidObject(const Object* obj)
545{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546 /* Don't bother if it's NULL or not 8-byte aligned.
547 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800548 if (obj != NULL && ((uintptr_t)obj & (8-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800549 /* Even if the heap isn't locked, this shouldn't return
550 * any false negatives. The only mutation that could
551 * be happening is allocation, which means that another
552 * thread could be in the middle of a read-modify-write
553 * to add a new bit for a new object. However, that
554 * RMW will have completed by the time any other thread
555 * could possibly see the new pointer, so there is no
556 * danger of dvmIsValidObject() being called on a valid
557 * pointer whose bit isn't set.
558 *
559 * Freeing will only happen during the sweep phase, which
560 * only happens while the heap is locked.
561 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800562 return dvmHeapSourceContains(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800563 }
564 return false;
565}
566
Barry Hayes364f9d92010-06-11 16:12:47 -0700567/*
568 * Returns true iff <obj> points to a word-aligned address within Heap
569 * address space.
570 */
571bool dvmIsValidObjectAddress(const void* ptr)
572{
573 /* Don't bother if it's not 4-byte aligned.
574 */
575 if (((uintptr_t)ptr & (4-1)) == 0) {
576 return dvmHeapSourceContainsAddress(ptr);
577 }
578 return false;
579}
580
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800581size_t dvmObjectSizeInHeap(const Object *obj)
582{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800583 return dvmHeapSourceChunkSize(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800584}
585
586/*
Barry Hayes962adba2010-03-17 12:12:39 -0700587 * Scan every live object in the heap, holding the locks.
588 */
589static void verifyHeap()
590{
591 // TODO: check the locks.
592 HeapBitmap *liveBits = dvmHeapSourceGetLiveBits();
593 dvmVerifyBitmap(liveBits);
594}
595
596/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800597 * Initiate garbage collection.
598 *
599 * NOTES:
600 * - If we don't hold gDvm.threadListLock, it's possible for a thread to
601 * be added to the thread list while we work. The thread should NOT
602 * start executing, so this is only interesting when we start chasing
603 * thread stacks. (Before we do so, grab the lock.)
604 *
605 * We are not allowed to GC when the debugger has suspended the VM, which
606 * is awkward because debugger requests can cause allocations. The easiest
607 * way to enforce this is to refuse to GC on an allocation made by the
608 * JDWP thread -- we have to expand the heap or fail.
609 */
Carl Shapiro29540742010-03-26 15:34:39 -0700610void dvmCollectGarbageInternal(bool clearSoftRefs, GcReason reason)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800611{
612 GcHeap *gcHeap = gDvm.gcHeap;
Carl Shapiro03f3b132010-07-27 17:25:31 -0700613 u4 suspendStart, totalTime;
614 u4 rootStart, rootEnd, rootTime, rootSuspendTime;
615 u4 dirtyStart, dirtyEnd, dirtyTime, dirtySuspendTime;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800616 int numFreed;
617 size_t sizeFreed;
Carl Shapirod25566d2010-03-11 20:39:47 -0800618 GcMode gcMode;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700619 int oldThreadPriority = kInvalidPriority;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800620
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800621 /* The heap lock must be held.
622 */
623
624 if (gcHeap->gcRunning) {
625 LOGW_HEAP("Attempted recursive GC\n");
626 return;
627 }
Carl Shapiro03f3b132010-07-27 17:25:31 -0700628
Carl Shapirod25566d2010-03-11 20:39:47 -0800629 gcMode = (reason == GC_FOR_MALLOC) ? GC_PARTIAL : GC_FULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800630 gcHeap->gcRunning = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800631
Carl Shapiro03f3b132010-07-27 17:25:31 -0700632 suspendStart = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800633 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700634 rootStart = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800635
Carl Shapiroec805ea2010-06-28 16:28:26 -0700636 /*
637 * If we are not marking concurrently raise the priority of the
638 * thread performing the garbage collection.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800639 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700640 if (reason != GC_CONCURRENT) {
641 /* Get the priority (the "nice" value) of the current thread. The
642 * getpriority() call can legitimately return -1, so we have to
643 * explicitly test errno.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800644 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700645 errno = 0;
646 int priorityResult = getpriority(PRIO_PROCESS, 0);
647 if (errno != 0) {
648 LOGI_HEAP("getpriority(self) failed: %s\n", strerror(errno));
649 } else if (priorityResult > ANDROID_PRIORITY_NORMAL) {
650 /* Current value is numerically greater than "normal", which
651 * in backward UNIX terms means lower priority.
652 */
San Mehat256fc152009-04-21 14:03:06 -0700653
Carl Shapiroec805ea2010-06-28 16:28:26 -0700654 if (priorityResult >= ANDROID_PRIORITY_BACKGROUND) {
655 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
656 }
San Mehat256fc152009-04-21 14:03:06 -0700657
Carl Shapiroec805ea2010-06-28 16:28:26 -0700658 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
659 LOGI_HEAP("Unable to elevate priority from %d to %d\n",
660 priorityResult, ANDROID_PRIORITY_NORMAL);
661 } else {
662 /* priority elevated; save value so we can restore it later */
663 LOGD_HEAP("Elevating priority from %d to %d\n",
664 priorityResult, ANDROID_PRIORITY_NORMAL);
665 oldThreadPriority = priorityResult;
666 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800667 }
668 }
669
670 /* Wait for the HeapWorker thread to block.
671 * (It may also already be suspended in interp code,
672 * in which case it's not holding heapWorkerLock.)
673 */
674 dvmLockMutex(&gDvm.heapWorkerLock);
675
676 /* Make sure that the HeapWorker thread hasn't become
677 * wedged inside interp code. If it has, this call will
678 * print a message and abort the VM.
679 */
680 dvmAssertHeapWorkerThreadRunning();
681
682 /* Lock the pendingFinalizationRefs list.
683 *
684 * Acquire the lock after suspending so the finalizer
685 * thread can't block in the RUNNING state while
686 * we try to suspend.
687 */
688 dvmLockMutex(&gDvm.heapWorkerListLock);
689
Barry Hayes962adba2010-03-17 12:12:39 -0700690 if (gDvm.preVerify) {
691 LOGV_HEAP("Verifying heap before GC");
692 verifyHeap();
693 }
694
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800695#ifdef WITH_PROFILER
696 dvmMethodTraceGCBegin();
697#endif
698
699#if WITH_HPROF
700
701/* Set DUMP_HEAP_ON_DDMS_UPDATE to 1 to enable heap dumps
702 * whenever DDMS requests a heap update (HPIF chunk).
703 * The output files will appear in /data/misc, which must
704 * already exist.
705 * You must define "WITH_HPROF := true" in your buildspec.mk
706 * and recompile libdvm for this to work.
707 *
708 * To enable stack traces for each allocation, define
709 * "WITH_HPROF_STACK := true" in buildspec.mk. This option slows down
710 * allocations and also requires 8 additional bytes per object on the
711 * GC heap.
712 */
713#define DUMP_HEAP_ON_DDMS_UPDATE 0
714#if DUMP_HEAP_ON_DDMS_UPDATE
715 gcHeap->hprofDumpOnGc |= (gcHeap->ddmHpifWhen != 0);
716#endif
717
718 if (gcHeap->hprofDumpOnGc) {
719 char nameBuf[128];
720
The Android Open Source Project99409882009-03-18 22:20:24 -0700721 gcHeap->hprofResult = -1;
722
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800723 if (gcHeap->hprofFileName == NULL) {
724 /* no filename was provided; invent one */
725 sprintf(nameBuf, "/data/misc/heap-dump-tm%d-pid%d.hprof",
726 (int) time(NULL), (int) getpid());
727 gcHeap->hprofFileName = nameBuf;
728 }
Andy McFadden6bf992c2010-01-28 17:01:39 -0800729 gcHeap->hprofContext = hprofStartup(gcHeap->hprofFileName,
Andy McFadden4b851a72010-07-09 16:50:05 -0700730 gcHeap->hprofFd, gcHeap->hprofDirectToDdms);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800731 if (gcHeap->hprofContext != NULL) {
732 hprofStartHeapDump(gcHeap->hprofContext);
733 }
734 gcHeap->hprofDumpOnGc = false;
735 gcHeap->hprofFileName = NULL;
736 }
737#endif
738
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800739 /* Set up the marking context.
740 */
Carl Shapirod25566d2010-03-11 20:39:47 -0800741 if (!dvmHeapBeginMarkStep(gcMode)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700742 LOGE_HEAP("dvmHeapBeginMarkStep failed; aborting\n");
743 dvmAbort();
744 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800745
746 /* Mark the set of objects that are strongly reachable from the roots.
747 */
748 LOGD_HEAP("Marking...");
749 dvmHeapMarkRootSet();
750
751 /* dvmHeapScanMarkedObjects() will build the lists of known
752 * instances of the Reference classes.
753 */
754 gcHeap->softReferences = NULL;
755 gcHeap->weakReferences = NULL;
756 gcHeap->phantomReferences = NULL;
757
Carl Shapiroec805ea2010-06-28 16:28:26 -0700758 if (reason == GC_CONCURRENT) {
759 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700760 * Resume threads while tracing from the roots. We unlock the
761 * heap to allow mutator threads to allocate from free space.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700762 */
Carl Shapiro03f3b132010-07-27 17:25:31 -0700763 rootEnd = dvmGetRelativeTimeMsec();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700764 dvmUnlockHeap();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700765 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700766 rootSuspendTime = rootStart - suspendStart;
767 rootTime = rootEnd - rootStart;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700768 }
769
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800770 /* Recursively mark any objects that marked objects point to strongly.
771 * If we're not collecting soft references, soft-reachable
772 * objects will also be marked.
773 */
774 LOGD_HEAP("Recursing...");
775 dvmHeapScanMarkedObjects();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800776
Carl Shapiroec805ea2010-06-28 16:28:26 -0700777 if (reason == GC_CONCURRENT) {
778 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700779 * Re-acquire the heap lock and perform the final thread
780 * suspension.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700781 */
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700782 dvmLockHeap();
Carl Shapiro03f3b132010-07-27 17:25:31 -0700783 suspendStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700784 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700785 dirtyStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700786 /*
787 * As no barrier intercepts root updates, we conservatively
788 * assume all roots may be gray and re-mark them.
789 */
790 dvmHeapMarkRootSet();
791 /*
792 * Recursively mark gray objects pointed to by the roots or by
793 * heap objects dirtied during the concurrent mark.
794 */
795 dvmMarkDirtyObjects();
796 }
797
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800798 /* All strongly-reachable objects have now been marked.
799 */
Carl Shapiro29540742010-03-26 15:34:39 -0700800 LOGD_HEAP("Handling soft references...");
801 if (!clearSoftRefs) {
802 dvmHandleSoftRefs(&gcHeap->softReferences);
803 }
804 dvmClearWhiteRefs(&gcHeap->softReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800805
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800806 LOGD_HEAP("Handling weak references...");
Carl Shapiro29540742010-03-26 15:34:39 -0700807 dvmClearWhiteRefs(&gcHeap->weakReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800808
809 /* Once all weak-reachable objects have been taken
810 * care of, any remaining unmarked objects can be finalized.
811 */
812 LOGD_HEAP("Finding finalizations...");
813 dvmHeapScheduleFinalizations();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800814
Carl Shapiro29540742010-03-26 15:34:39 -0700815 LOGD_HEAP("Handling f-reachable soft references...");
816 dvmClearWhiteRefs(&gcHeap->softReferences);
817
818 LOGD_HEAP("Handling f-reachable weak references...");
819 dvmClearWhiteRefs(&gcHeap->weakReferences);
820
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800821 /* Any remaining objects that are not pending finalization
822 * could be phantom-reachable. This will mark any phantom-reachable
823 * objects, as well as enqueue their references.
824 */
825 LOGD_HEAP("Handling phantom references...");
Carl Shapiro29540742010-03-26 15:34:39 -0700826 dvmClearWhiteRefs(&gcHeap->phantomReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800827
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800828#ifdef WITH_DEADLOCK_PREDICTION
829 dvmDumpMonitorInfo("before sweep");
830#endif
831 LOGD_HEAP("Sweeping...");
Carl Shapirod25566d2010-03-11 20:39:47 -0800832 dvmHeapSweepUnmarkedObjects(gcMode, &numFreed, &sizeFreed);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800833#ifdef WITH_DEADLOCK_PREDICTION
834 dvmDumpMonitorInfo("after sweep");
835#endif
836
837 LOGD_HEAP("Cleaning up...");
838 dvmHeapFinishMarkStep();
839
840 LOGD_HEAP("Done.");
841
842 /* Now's a good time to adjust the heap size, since
843 * we know what our utilization is.
844 *
845 * This doesn't actually resize any memory;
846 * it just lets the heap grow more when necessary.
847 */
848 dvmHeapSourceGrowForUtilization();
849 dvmHeapSizeChanged();
850
851#if WITH_HPROF
852 if (gcHeap->hprofContext != NULL) {
853 hprofFinishHeapDump(gcHeap->hprofContext);
854//TODO: write a HEAP_SUMMARY record
The Android Open Source Project99409882009-03-18 22:20:24 -0700855 if (hprofShutdown(gcHeap->hprofContext))
856 gcHeap->hprofResult = 0; /* indicate success */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800857 gcHeap->hprofContext = NULL;
858 }
859#endif
860
861 /* Now that we've freed up the GC heap, return any large
862 * free chunks back to the system. They'll get paged back
863 * in the next time they're used. Don't do it immediately,
864 * though; if the process is still allocating a bunch of
865 * memory, we'll be taking a ton of page faults that we don't
866 * necessarily need to.
867 *
868 * Cancel any old scheduled trims, and schedule a new one.
869 */
870 dvmScheduleHeapSourceTrim(5); // in seconds
871
872#ifdef WITH_PROFILER
873 dvmMethodTraceGCEnd();
874#endif
Barry Hayes962adba2010-03-17 12:12:39 -0700875 LOGV_HEAP("GC finished");
876
877 if (gDvm.postVerify) {
878 LOGV_HEAP("Verifying heap after GC");
879 verifyHeap();
880 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800881
882 gcHeap->gcRunning = false;
883
Barry Hayes962adba2010-03-17 12:12:39 -0700884 LOGV_HEAP("Resuming threads");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800885 dvmUnlockMutex(&gDvm.heapWorkerListLock);
886 dvmUnlockMutex(&gDvm.heapWorkerLock);
887
Ben Chengc3b92b22010-01-26 16:46:15 -0800888#if defined(WITH_JIT)
Ben Chengc3b92b22010-01-26 16:46:15 -0800889 /*
890 * Patching a chaining cell is very cheap as it only updates 4 words. It's
891 * the overhead of stopping all threads and synchronizing the I/D cache
892 * that makes it expensive.
893 *
894 * Therefore we batch those work orders in a queue and go through them
895 * when threads are suspended for GC.
896 */
897 dvmCompilerPerformSafePointChecks();
898#endif
899
Carl Shapiro03f3b132010-07-27 17:25:31 -0700900 dirtyEnd = dvmGetRelativeTimeMsec();
901
902 if (reason == GC_CONCURRENT) {
903 dirtySuspendTime = dirtyStart - suspendStart;
904 dirtyTime = dirtyEnd - dirtyStart;
905 }
906
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800907 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700908
909 if (reason == GC_CONCURRENT) {
910 /*
911 * Wake-up any threads that blocked after a failed allocation
912 * request.
913 */
914 dvmBroadcastCond(&gDvm.gcHeapCond);
915 }
916
Carl Shapiroec805ea2010-06-28 16:28:26 -0700917 if (reason != GC_CONCURRENT) {
918 if (oldThreadPriority != kInvalidPriority) {
919 if (setpriority(PRIO_PROCESS, 0, oldThreadPriority) != 0) {
920 LOGW_HEAP("Unable to reset priority to %d: %s\n",
921 oldThreadPriority, strerror(errno));
922 } else {
923 LOGD_HEAP("Reset priority to %d\n", oldThreadPriority);
924 }
San Mehat256fc152009-04-21 14:03:06 -0700925
Carl Shapiroec805ea2010-06-28 16:28:26 -0700926 if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
927 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
928 }
San Mehat256fc152009-04-21 14:03:06 -0700929 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800930 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800931
Carl Shapiro03f3b132010-07-27 17:25:31 -0700932 if (reason != GC_CONCURRENT) {
933 u4 suspendTime = rootStart - suspendStart;
934 u4 markSweepTime = dirtyEnd - rootStart;
935 totalTime = suspendTime + markSweepTime;
936 LOGD("%s freed %d objects / %zd bytes in (%ums) %ums",
937 GcReasonStr[reason], numFreed, sizeFreed,
938 suspendTime, markSweepTime);
939 } else {
940 totalTime = rootSuspendTime + rootTime + dirtySuspendTime + dirtyTime;
941 LOGD("%s freed %d objects / %zd bytes in (%ums) %ums (%ums) %ums",
942 GcReasonStr[reason], numFreed, sizeFreed,
943 rootSuspendTime, rootTime,
944 dirtySuspendTime, dirtyTime);
945 }
946 dvmLogGcStats(numFreed, sizeFreed, totalTime);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800947 if (gcHeap->ddmHpifWhen != 0) {
948 LOGD_HEAP("Sending VM heap info to DDM\n");
949 dvmDdmSendHeapInfo(gcHeap->ddmHpifWhen, false);
950 }
951 if (gcHeap->ddmHpsgWhen != 0) {
952 LOGD_HEAP("Dumping VM heap to DDM\n");
953 dvmDdmSendHeapSegments(false, false);
954 }
955 if (gcHeap->ddmNhsgWhen != 0) {
956 LOGD_HEAP("Dumping native heap to DDM\n");
957 dvmDdmSendHeapSegments(false, true);
958 }
959}
960
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700961void dvmWaitForConcurrentGcToComplete(void)
962{
963 Thread *self = dvmThreadSelf();
964 ThreadStatus oldStatus;
965 assert(self != NULL);
966 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
967 dvmWaitCond(&gDvm.gcHeapCond, &gDvm.gcHeapLock);
968 dvmChangeStatus(self, oldStatus);
969}
970
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800971#if WITH_HPROF
972/*
973 * Perform garbage collection, writing heap information to the specified file.
974 *
Andy McFadden4b851a72010-07-09 16:50:05 -0700975 * If "fd" is >= 0, the output will be written to that file descriptor.
976 * Otherwise, "fileName" is used to create an output file.
977 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800978 * If "fileName" is NULL, a suitable name will be generated automatically.
Andy McFadden4b851a72010-07-09 16:50:05 -0700979 * (TODO: remove this when the SIGUSR1 feature goes away)
980 *
981 * If "directToDdms" is set, the other arguments are ignored, and data is
982 * sent directly to DDMS.
The Android Open Source Project99409882009-03-18 22:20:24 -0700983 *
984 * Returns 0 on success, or an error code on failure.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800985 */
Andy McFadden4b851a72010-07-09 16:50:05 -0700986int hprofDumpHeap(const char* fileName, int fd, bool directToDdms)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800987{
The Android Open Source Project99409882009-03-18 22:20:24 -0700988 int result;
989
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800990 dvmLockMutex(&gDvm.gcHeapLock);
991
992 gDvm.gcHeap->hprofDumpOnGc = true;
993 gDvm.gcHeap->hprofFileName = fileName;
Andy McFadden4b851a72010-07-09 16:50:05 -0700994 gDvm.gcHeap->hprofFd = fd;
Andy McFadden6bf992c2010-01-28 17:01:39 -0800995 gDvm.gcHeap->hprofDirectToDdms = directToDdms;
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800996 dvmCollectGarbageInternal(false, GC_HPROF_DUMP_HEAP);
The Android Open Source Project99409882009-03-18 22:20:24 -0700997 result = gDvm.gcHeap->hprofResult;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800998
999 dvmUnlockMutex(&gDvm.gcHeapLock);
The Android Open Source Project99409882009-03-18 22:20:24 -07001000
1001 return result;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001002}
1003
1004void dvmHeapSetHprofGcScanState(hprof_heap_tag_t state, u4 threadSerialNumber)
1005{
1006 if (gDvm.gcHeap->hprofContext != NULL) {
1007 hprofSetGcScanState(gDvm.gcHeap->hprofContext, state,
1008 threadSerialNumber);
1009 }
1010}
1011#endif