entry : objectInboundReferers.entrySet()) {
39 | data.put(entry.getKey(), entry.getValue().toPathsFromGCRootsTree());
40 | }
41 | int[] children = new int[objectIds.size()];
42 | for (int i = 0; i < children.length; i++) {
43 | children[i] = objectIds.get(i);
44 | }
45 | return new PathsFromGCRootsTree(ownId, data, children);
46 | }
47 |
48 | public int getOwnId() {
49 | return ownId;
50 | }
51 |
52 | public void addObjectReferer(PathsFromGCRootsTreeBuilder referer) {
53 | if (objectInboundReferers.put(referer.getOwnId(), referer) == null) {
54 | objectIds.add(referer.getOwnId());
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/SnapshotException.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat;
14 |
15 | import org.eclipse.mat.hprof.Messages;
16 | import org.eclipse.mat.util.MessageUtil;
17 |
18 | /**
19 | * Exception used to indicate a problem different from the standard Java
20 | * exceptions while performing an operation on an snapshot.
21 | */
22 | public class SnapshotException extends Exception {
23 | private static final long serialVersionUID = 1L;
24 |
25 | /**
26 | * Create snapshot exception - should not be used except during
27 | * deserialization.
28 | */
29 | public SnapshotException() {
30 | }
31 |
32 | /**
33 | * Create snapshot exception with message and root cause.
34 | */
35 | public SnapshotException(String message, Throwable cause) {
36 | super(message, cause);
37 | }
38 |
39 | /**
40 | * Create snapshot exception with message only.
41 | */
42 | public SnapshotException(String message) {
43 | super(message);
44 | }
45 |
46 | /**
47 | * Create snapshot exception with root cause only.
48 | */
49 | public SnapshotException(Throwable cause) {
50 | super(cause);
51 | }
52 |
53 | public SnapshotException(Messages messages) {
54 | super(MessageUtil.format(messages));
55 | }
56 |
57 | /**
58 | * Wrap, if necessary, and return a SnapshotException.
59 | */
60 | public static final SnapshotException rethrow(Throwable e) {
61 | if (e instanceof RuntimeException) {
62 | // if we wrap an SnapshotException, pass the snapshot exception on
63 | if (((RuntimeException) e).getCause() instanceof SnapshotException) {
64 | return (SnapshotException) ((RuntimeException) e).getCause();
65 | }
66 | throw (RuntimeException) e;
67 | } else if (e instanceof SnapshotException) {
68 | return (SnapshotException) e;
69 | } else {
70 | return new SnapshotException(e);
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/util/VoidProgressListener.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.util;
14 |
15 | import org.eclipse.mat.hprof.Messages;
16 |
17 | /**
18 | * Empty implementation of {@link IProgressListener} which is frequently used
19 | * throughout the snapshot API in ISnapshot to get feedback for long running
20 | * operations. This implementation does nothing.
21 | *
22 | * @see IProgressListener
23 | */
24 | public class VoidProgressListener implements IProgressListener {
25 | private boolean cancelled = false;
26 |
27 | /**
28 | * Does nothing.
29 | *
30 | * @see IProgressListener#beginTask(String, int)
31 | */
32 | public void beginTask(String name, int totalWork) {
33 | }
34 |
35 | public final void beginTask(Messages name, int totalWork) {
36 | beginTask(name.pattern, totalWork);
37 | }
38 |
39 | /**
40 | * Does nothing.
41 | *
42 | * @see IProgressListener#done()
43 | */
44 | public void done() {
45 | }
46 |
47 | /**
48 | * Gets the cancel state.
49 | *
50 | * @see IProgressListener#isCanceled()
51 | */
52 | public boolean isCanceled() {
53 | return cancelled;
54 | }
55 |
56 | /**
57 | * Sets the cancel state.
58 | *
59 | * @see IProgressListener#setCanceled(boolean)
60 | */
61 | public void setCanceled(boolean value) {
62 | cancelled = value;
63 | }
64 |
65 | /**
66 | * Does nothing.
67 | *
68 | * @see IProgressListener#subTask(String)
69 | */
70 | public void subTask(String name) {
71 | }
72 |
73 | /**
74 | * Does nothing.
75 | *
76 | * @see IProgressListener#worked(int)
77 | */
78 | public void worked(int work) {
79 | }
80 |
81 | /**
82 | * Does nothing
83 | *
84 | * @see IProgressListener#sendUserMessage(Severity, String, Throwable)
85 | */
86 | public void sendUserMessage(Severity severity, String message, Throwable exception) {
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/io/BitInputStream.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.io;
14 |
15 | import java.io.Closeable;
16 | import java.io.EOFException;
17 | import java.io.Flushable;
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 |
21 | public class BitInputStream implements Flushable, Closeable {
22 | public final static int DEFAULT_BUFFER_SIZE = 16 * 1024;
23 |
24 | private InputStream is;
25 | private int current;
26 | private byte[] buffer;
27 | private int fill;
28 | private int pos;
29 | private int avail;
30 |
31 | public BitInputStream(final InputStream is) {
32 | this.is = is;
33 | this.buffer = new byte[DEFAULT_BUFFER_SIZE];
34 | }
35 |
36 | public void flush() {
37 | avail = 0;
38 | pos = 0;
39 | fill = 0;
40 | }
41 |
42 | public void close() throws IOException {
43 | is.close();
44 | is = null;
45 | buffer = null;
46 | }
47 |
48 | private int read() throws IOException {
49 | if (avail == 0) {
50 | avail = is.read(buffer);
51 | if (avail == -1) {
52 | avail = 0;
53 | throw new EOFException();
54 | } else {
55 | pos = 0;
56 | }
57 | }
58 |
59 | avail--;
60 | return buffer[pos++] & 0xFF;
61 | }
62 |
63 | private int readFromCurrent(final int len) throws IOException {
64 | if (len == 0) return 0;
65 |
66 | if (fill == 0) {
67 | current = read();
68 | fill = 8;
69 | }
70 |
71 | return current >>> (fill -= len) & (1 << len) - 1;
72 | }
73 |
74 | public int readBit() throws IOException {
75 | return readFromCurrent(1);
76 | }
77 |
78 | public int readInt(int len) throws IOException {
79 | int i, x = 0;
80 |
81 | if (len <= fill) return readFromCurrent(len);
82 |
83 | len -= fill;
84 | x = readFromCurrent(fill);
85 |
86 | i = len >> 3;
87 | while (i-- != 0) x = x << 8 | read();
88 |
89 | len &= 7;
90 |
91 | return (x << len) | readFromCurrent(len);
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/LeakcanarySample/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
10 |
11 |
12 |
13 |
19 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
34 |
37 |
38 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
55 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/AndroidWatchExecutor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary;
17 |
18 | import android.os.Handler;
19 | import android.os.HandlerThread;
20 | import android.os.Looper;
21 | import android.os.MessageQueue;
22 | import java.util.concurrent.Executor;
23 |
24 | /**
25 | * {@link Executor} suitable for watching Android reference leaks. This executor waits for the main
26 | * thread to be idle then posts to a serial background thread with a delay of {@link
27 | * #DELAY_MILLIS} milliseconds.
28 | */
29 | public final class AndroidWatchExecutor implements Executor {
30 |
31 | static final String LEAK_CANARY_THREAD_NAME = "LeakCanary-Heap-Dump";
32 | private static final int DELAY_MILLIS = 5000;
33 |
34 | private final Handler mainHandler;
35 | private final Handler backgroundHandler;
36 |
37 | public AndroidWatchExecutor() {
38 | mainHandler = new Handler(Looper.getMainLooper());
39 | HandlerThread handlerThread = new HandlerThread(LEAK_CANARY_THREAD_NAME);
40 | handlerThread.start();
41 | backgroundHandler = new Handler(handlerThread.getLooper());
42 | }
43 |
44 | @Override public void execute(final Runnable command) {
45 | if (isOnMainThread()) {
46 | executeDelayedAfterIdleUnsafe(command);
47 | } else {
48 | mainHandler.post(new Runnable() {
49 | @Override public void run() {
50 | executeDelayedAfterIdleUnsafe(command);
51 | }
52 | });
53 | }
54 | }
55 |
56 | private boolean isOnMainThread() {
57 | return Looper.getMainLooper().getThread() == Thread.currentThread();
58 | }
59 |
60 | private void executeDelayedAfterIdleUnsafe(final Runnable runnable) {
61 | // This needs to be called from the main thread.
62 | Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
63 | @Override public boolean queueIdle() {
64 | backgroundHandler.postDelayed(runnable, DELAY_MILLIS);
65 | return false;
66 | }
67 | });
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/internal/HeapAnalyzerService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary.internal;
17 |
18 | import android.app.IntentService;
19 | import android.content.Context;
20 | import android.content.Intent;
21 | import com.squareup.leakcanary.AbstractAnalysisResultService;
22 | import com.squareup.leakcanary.AnalysisResult;
23 | import com.squareup.leakcanary.CanaryLog;
24 | import com.squareup.leakcanary.HeapAnalyzer;
25 | import com.squareup.leakcanary.HeapDump;
26 |
27 | /**
28 | * This service runs in a separate process to avoid slowing down the app process or making it run
29 | * out of memory.
30 | */
31 | public final class HeapAnalyzerService extends IntentService {
32 |
33 | private static final String LISTENER_CLASS_EXTRA = "listener_class_extra";
34 | private static final String HEAPDUMP_EXTRA = "heapdump_extra";
35 |
36 | public static void runAnalysis(Context context, HeapDump heapDump,
37 | Class extends AbstractAnalysisResultService> listenerServiceClass) {
38 | Intent intent = new Intent(context, HeapAnalyzerService.class);
39 | intent.putExtra(LISTENER_CLASS_EXTRA, listenerServiceClass.getName());
40 | intent.putExtra(HEAPDUMP_EXTRA, heapDump);
41 | context.startService(intent);
42 | }
43 |
44 | public HeapAnalyzerService() {
45 | super(HeapAnalyzerService.class.getSimpleName());
46 | }
47 |
48 | @Override protected void onHandleIntent(Intent intent) {
49 | if (intent == null) {
50 | CanaryLog.d("HeapAnalyzerService received a null intent, ignoring.");
51 | return;
52 | }
53 | String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
54 | HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);
55 |
56 | HeapAnalyzer heapAnalyzer = new HeapAnalyzer(heapDump.excludedRefs);
57 |
58 | AnalysisResult result = heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey);
59 | AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/PrettyPrinter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.snapshot.model;
14 |
15 | import org.eclipse.mat.SnapshotException;
16 |
17 | /**
18 | * Utility class to extract String representations of heap dump objects.
19 | */
20 | public final class PrettyPrinter {
21 | /**
22 | * Convert a java.lang.String object into a String.
23 | */
24 | public static String objectAsString(IObject stringObject, int limit) throws SnapshotException {
25 | Integer count = (Integer) stringObject.resolveValue("count"); //$NON-NLS-1$
26 | if (count == null) return null;
27 | if (count.intValue() == 0) return ""; //$NON-NLS-1$
28 |
29 | IPrimitiveArray charArray = (IPrimitiveArray) stringObject.resolveValue("value"); //$NON-NLS-1$
30 | if (charArray == null) return null;
31 |
32 | Integer offset = (Integer) stringObject.resolveValue("offset"); //$NON-NLS-1$
33 | if (offset == null) return null;
34 |
35 | return arrayAsString(charArray, offset, count, limit);
36 | }
37 |
38 | /**
39 | * Convert a char[] object into a String.
40 | */
41 | public static String arrayAsString(IPrimitiveArray charArray, int offset, int count, int limit) {
42 | if (charArray.getType() != IObject.Type.CHAR) return null;
43 |
44 | int length = charArray.getLength();
45 |
46 | int contentToRead = count <= limit ? count : limit;
47 | if (contentToRead > length - offset) contentToRead = length - offset;
48 |
49 | char[] value;
50 | if (offset == 0 && length == contentToRead) {
51 | value = (char[]) charArray.getValueArray();
52 | } else {
53 | value = (char[]) charArray.getValueArray(offset, contentToRead);
54 | }
55 |
56 | if (value == null) return null;
57 |
58 | StringBuilder result = new StringBuilder(value.length);
59 | for (int ii = 0; ii < value.length; ii++) {
60 | char val = value[ii];
61 | if (val >= 32 && val < 127) {
62 | result.append(val);
63 | } else {
64 | result.append("\\u").append(String.format("%04x", 0xFFFF & val)); //$NON-NLS-1$//$NON-NLS-2$
65 | }
66 | }
67 | if (limit < count) result.append("..."); //$NON-NLS-1$
68 | return result.toString();
69 | }
70 |
71 | private PrettyPrinter() {
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/AbstractAnalysisResultService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary;
17 |
18 | import android.app.IntentService;
19 | import android.content.Context;
20 | import android.content.Intent;
21 |
22 | public abstract class AbstractAnalysisResultService extends IntentService {
23 |
24 | private static final String HEAP_DUMP_EXTRA = "heap_dump_extra";
25 | private static final String RESULT_EXTRA = "result_extra";
26 |
27 | public static void sendResultToListener(Context context, String listenerServiceClassName,
28 | HeapDump heapDump, AnalysisResult result) {
29 | Class> listenerServiceClass;
30 | try {
31 | listenerServiceClass = Class.forName(listenerServiceClassName);
32 | } catch (ClassNotFoundException e) {
33 | throw new RuntimeException(e);
34 | }
35 | Intent intent = new Intent(context, listenerServiceClass);
36 | intent.putExtra(HEAP_DUMP_EXTRA, heapDump);
37 | intent.putExtra(RESULT_EXTRA, result);
38 | context.startService(intent);
39 | }
40 |
41 | public AbstractAnalysisResultService() {
42 | super(AbstractAnalysisResultService.class.getName());
43 | }
44 |
45 | @Override protected final void onHandleIntent(Intent intent) {
46 | HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAP_DUMP_EXTRA);
47 | AnalysisResult result = (AnalysisResult) intent.getSerializableExtra(RESULT_EXTRA);
48 | try {
49 | onHeapAnalyzed(heapDump, result);
50 | } finally {
51 | //noinspection ResultOfMethodCallIgnored
52 | heapDump.heapDumpFile.delete();
53 | }
54 | }
55 |
56 | /**
57 | * Called after a heap dump is analyzed, whether or not a leak was found.
58 | * Check {@link AnalysisResult#leakFound} and {@link AnalysisResult#excludedLeak} to see if there
59 | * was a leak and if it can be ignored.
60 | *
61 | * This will be called from a background intent service thread.
62 | *
63 | * It's OK to block here and wait for the heap dump to be uploaded.
64 | *
65 | * The heap dump file will be deleted immediately after this callback returns.
66 | */
67 | protected abstract void onHeapAnalyzed(HeapDump heapDump, AnalysisResult result);
68 | }
69 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/IPathsFromGCRootsComputer.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.snapshot;
14 |
15 | import java.util.Collection;
16 |
17 | import org.eclipse.mat.SnapshotException;
18 |
19 | /**
20 | * Interface describing an interactive computer for paths from GC roots to an
21 | * object. You will get such a computer from the {@link ISnapshot} API.
22 | *
23 | * Finding paths from GC roots to an object is handy if you want to learn which
24 | * objects are responsible for the given object to remain in memory. Since the
25 | * snapshot implementation artificially creates references from the object to
26 | * its class and from the class to its class loader you can even see why a class
27 | * or class loader remains in memory, i.e. which other objects hold references
28 | * to objects of the class or class loader of interest.
29 | *
30 | * @noimplement
31 | */
32 | public interface IPathsFromGCRootsComputer {
33 | /**
34 | * Get next shortest path. The computer holds the state of the computation
35 | * and allows to continuously ask for the next path. If null is returned no
36 | * path is available anymore.
37 | *
38 | * This method allows you either to ask for all paths (which could take
39 | * quite some time and memory but shows you the complete picture) or one by
40 | * one (the shortest paths are returned first; more useful in an UI as a
41 | * user might find a problem faster among just a few shorter paths).
42 | *
43 | * @return int array holding the object ids of the objects forming the path
44 | * from the first element at index 0 (object for which the
45 | * computation was started) to the last element in the int array
46 | * (object identified as GC root)
47 | * @throws SnapshotException
48 | */
49 | public int[] getNextShortestPath() throws SnapshotException;
50 |
51 | /**
52 | * Helper method constructing a tree like data structure from the given
53 | * paths. Either all so far collected paths could be dropped in here or just
54 | * the last ones if you want to limit the view.
55 | *
56 | * @param paths paths from GC roots previously returned by
57 | * {@link #getNextShortestPath}
58 | * @return tree like data structure holding the paths from GC roots
59 | */
60 | public PathsFromGCRootsTree getTree(Collection paths);
61 | }
62 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/AnalysisResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary;
17 |
18 | import java.io.Serializable;
19 |
20 | public final class AnalysisResult implements Serializable {
21 |
22 | public static AnalysisResult noLeak(long analysisDurationMs) {
23 | return new AnalysisResult(false, false, null, null, null, analysisDurationMs);
24 | }
25 |
26 | public static AnalysisResult leakDetected(boolean excludedLeak, String className,
27 | LeakTrace leakTrace, long analysisDurationMs) {
28 | return new AnalysisResult(true, excludedLeak, className, leakTrace, null, analysisDurationMs);
29 | }
30 |
31 | public static AnalysisResult failure(Throwable failure, long analysisDurationMs) {
32 | return new AnalysisResult(false, false, null, null, failure, analysisDurationMs);
33 | }
34 |
35 | /** True if a leak was found in the heap dump. */
36 | public final boolean leakFound;
37 |
38 | /**
39 | * True if {@link #leakFound} is true and the only path to the leaking reference is
40 | * through excluded references. Usually, that means you can safely ignore this report.
41 | */
42 | public final boolean excludedLeak;
43 |
44 | /**
45 | * Class name of the object that leaked if {@link #leakFound} is true, null otherwise.
46 | * The class name format is the same as what would be returned by {@link Class#getName()}.
47 | */
48 | public final String className;
49 |
50 | /**
51 | * Shortest path to GC roots for the leaking object if {@link #leakFound} is true, null
52 | * otherwise. This can be used as a unique signature for the leak.
53 | */
54 | public final LeakTrace leakTrace;
55 |
56 | /** Null unless the analysis failed. */
57 | public final Throwable failure;
58 |
59 | /** Total time spent analyzing the heap. */
60 | public final long analysisDurationMs;
61 |
62 | private AnalysisResult(boolean leakFound, boolean excludedLeak, String className,
63 | LeakTrace leakTrace, Throwable failure, long analysisDurationMs) {
64 | this.leakFound = leakFound;
65 | this.excludedLeak = excludedLeak;
66 | this.className = className;
67 | this.leakTrace = leakTrace;
68 | this.failure = failure;
69 | this.analysisDurationMs = analysisDurationMs;
70 | }
71 | }
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/internal/PreliminaryIndexImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.internal;
14 |
15 | import java.util.List;
16 |
17 | import org.eclipse.mat.collect.HashMapIntObject;
18 | import org.eclipse.mat.parser.IPreliminaryIndex;
19 | import org.eclipse.mat.parser.index.IIndexReader;
20 | import org.eclipse.mat.parser.model.ClassImpl;
21 | import org.eclipse.mat.parser.model.XGCRootInfo;
22 | import org.eclipse.mat.parser.model.XSnapshotInfo;
23 |
24 | /* package */class PreliminaryIndexImpl implements IPreliminaryIndex {
25 | XSnapshotInfo snapshotInfo;
26 |
27 | // id -> class impl
28 | HashMapIntObject classesById;
29 |
30 | // GC roots (by ids)
31 | HashMapIntObject> gcRoots;
32 | HashMapIntObject>> thread2objects2roots;
33 |
34 | // id -> id*
35 | IIndexReader.IOne2ManyIndex outbound = null;
36 |
37 | // id -> address
38 | IIndexReader.IOne2LongIndex identifiers = null;
39 |
40 | // id -> id
41 | IIndexReader.IOne2OneIndex object2classId = null;
42 |
43 | // id -> int (size)
44 | IIndexReader.IOne2OneIndex array2size = null;
45 |
46 | public PreliminaryIndexImpl(XSnapshotInfo snapshotInfo) {
47 | this.snapshotInfo = snapshotInfo;
48 | }
49 |
50 | public XSnapshotInfo getSnapshotInfo() {
51 | return snapshotInfo;
52 | }
53 |
54 | public void setClassesById(HashMapIntObject classesById) {
55 | this.classesById = classesById;
56 | }
57 |
58 | public void setGcRoots(HashMapIntObject> gcRoots) {
59 | this.gcRoots = gcRoots;
60 | }
61 |
62 | public void setThread2objects2roots(
63 | HashMapIntObject>> thread2objects2roots) {
64 | this.thread2objects2roots = thread2objects2roots;
65 | }
66 |
67 | public void setOutbound(IIndexReader.IOne2ManyIndex outbound) {
68 | this.outbound = outbound;
69 | }
70 |
71 | public void setIdentifiers(IIndexReader.IOne2LongIndex identifiers) {
72 | this.identifiers = identifiers;
73 | }
74 |
75 | public void setObject2classId(IIndexReader.IOne2OneIndex object2classId) {
76 | this.object2classId = object2classId;
77 | }
78 |
79 | public void setArray2size(IIndexReader.IOne2OneIndex array2size) {
80 | this.array2size = array2size;
81 | }
82 |
83 | public void delete() {
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/HeapDump.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary;
17 |
18 | import java.io.File;
19 | import java.io.Serializable;
20 |
21 | import static com.squareup.leakcanary.Preconditions.checkNotNull;
22 |
23 | public final class HeapDump implements Serializable {
24 |
25 | public interface Listener {
26 | void analyze(HeapDump heapDump);
27 | }
28 |
29 | /** The heap dump file, which you might want to upload somewhere. */
30 | public final File heapDumpFile;
31 |
32 | /**
33 | * Key associated to the {@link KeyedWeakReference} used to detect the memory leak.
34 | * When analyzing a heap dump, search for all {@link KeyedWeakReference} instances, then open
35 | * the one that has its "key" field set to this value. Its "referent" field contains the
36 | * leaking object. Computing the shortest path to GC roots on that leaking object should enable
37 | * you to figure out the cause of the leak.
38 | */
39 | public final String referenceKey;
40 |
41 | /**
42 | * User defined name to help identify the leaking instance.
43 | */
44 | public final String referenceName;
45 |
46 | /** References that should be ignored when analyzing this heap dump. */
47 | public final ExcludedRefs excludedRefs;
48 |
49 | /** Time from the request to watch the reference until the GC was triggered. */
50 | public final long watchDurationMs;
51 | public final long gcDurationMs;
52 | public final long heapDumpDurationMs;
53 |
54 | public HeapDump(File heapDumpFile, String referenceKey, String referenceName,
55 | ExcludedRefs excludedRefs, long watchDurationMs, long gcDurationMs, long heapDumpDurationMs) {
56 | this.heapDumpFile = checkNotNull(heapDumpFile, "heapDumpFile");
57 | this.referenceKey = checkNotNull(referenceKey, "referenceKey");
58 | this.referenceName = checkNotNull(referenceName, "referenceName");
59 | this.excludedRefs = checkNotNull(excludedRefs, "excludedRefs");
60 | this.watchDurationMs = watchDurationMs;
61 | this.gcDurationMs = gcDurationMs;
62 | this.heapDumpDurationMs = heapDumpDurationMs;
63 | }
64 |
65 | /** Renames the heap dump file and creates a new {@link HeapDump} pointing to it. */
66 | public HeapDump renameFile(File newFile) {
67 | heapDumpFile.renameTo(newFile);
68 | return new HeapDump(newFile, referenceKey, referenceName, excludedRefs, watchDurationMs,
69 | gcDurationMs, heapDumpDurationMs);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/IPrimitiveArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.snapshot.model;
14 |
15 | /**
16 | * Interface for primitive arrays in the heap dump.
17 | *
18 | * @noimplement
19 | */
20 | public interface IPrimitiveArray extends IArray {
21 | /**
22 | * Primitive signatures.
23 | */
24 | public static final byte[] SIGNATURES = {
25 | -1, -1, -1, -1, (byte) 'Z', (byte) 'C', (byte) 'F', (byte) 'D', (byte) 'B', (byte) 'S',
26 | (byte) 'I', (byte) 'J'
27 | };
28 |
29 | /**
30 | * Element sizes inside the array.
31 | */
32 | public static final int[] ELEMENT_SIZE = { -1, -1, -1, -1, 1, 2, 4, 8, 1, 2, 4, 8 };
33 |
34 | /**
35 | * Display string of the type.
36 | */
37 | @SuppressWarnings("nls") public static final String[] TYPE = {
38 | null, null, null, null, "boolean[]", "char[]", "float[]", "double[]", "byte[]", "short[]",
39 | "int[]", "long[]"
40 | };
41 |
42 | /**
43 | * Java component type of the primitive array.
44 | */
45 | public static final Class>[] COMPONENT_TYPE = {
46 | null, null, null, null, boolean.class, char.class, float.class, double.class, byte.class,
47 | short.class, int.class, long.class
48 | };
49 |
50 | /**
51 | * Returns the {@link IObject.Type} of the primitive array.
52 | */
53 | public int getType();
54 |
55 | /**
56 | * Returns the component type of the array.
57 | */
58 | public Class> getComponentType();
59 |
60 | /**
61 | * Returns the Object at a given index.
62 | */
63 | public Object getValueAt(int index);
64 |
65 | /**
66 | * Get the primitive Java array. The return value can be casted into the
67 | * correct component type, e.g.
68 | *
69 | *
70 | * if (char.class == array.getComponentType())
71 | * {
72 | * char[] content = (char[]) array.getValueArray();
73 | * System.out.println(content.length);
74 | * }
75 | *
76 | *
77 | * The return value must not be modified because it is cached by the heap
78 | * dump adapter. This method does not return a copy of the array for
79 | * performance reasons.
80 | */
81 | public Object getValueArray();
82 |
83 | /**
84 | * Get the primitive Java array, beginning at offset and
85 | * length number of elements.
86 | *
87 | * The return value must not be modified because it is cached by the heap
88 | * dump adapter. This method does not return a copy of the array for
89 | * performance reasons.
90 | */
91 | public Object getValueArray(int offset, int length);
92 | }
93 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/internal/SnapshotImplBuilder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.internal;
14 |
15 | import java.io.IOException;
16 | import java.util.List;
17 | import java.util.Map;
18 |
19 | import org.eclipse.mat.SnapshotException;
20 | import org.eclipse.mat.collect.BitField;
21 | import org.eclipse.mat.collect.HashMapIntObject;
22 | import org.eclipse.mat.parser.IObjectReader;
23 | import org.eclipse.mat.parser.index.IndexManager;
24 | import org.eclipse.mat.parser.internal.util.ParserRegistry.Parser;
25 | import org.eclipse.mat.parser.model.ClassImpl;
26 | import org.eclipse.mat.parser.model.XGCRootInfo;
27 | import org.eclipse.mat.parser.model.XSnapshotInfo;
28 | import org.eclipse.mat.snapshot.model.IClass;
29 |
30 | public class SnapshotImplBuilder {
31 | private XSnapshotInfo snapshotInfo;
32 | /* package */ HashMapIntObject classCache;
33 | /* package */ Map> classCacheByName;
34 | private HashMapIntObject roots;
35 | private HashMapIntObject> rootsPerThread;
36 |
37 | /* package */ BitField arrayObjects;
38 |
39 | /* package */ IndexManager indexManager;
40 |
41 | public SnapshotImplBuilder(XSnapshotInfo snapshotInfo) {
42 | this.snapshotInfo = snapshotInfo;
43 | }
44 |
45 | public XSnapshotInfo getSnapshotInfo() {
46 | return snapshotInfo;
47 | }
48 |
49 | public void setIndexManager(IndexManager indexManager) {
50 | this.indexManager = indexManager;
51 | }
52 |
53 | public IndexManager getIndexManager() {
54 | return indexManager;
55 | }
56 |
57 | public void setClassCache(HashMapIntObject classCache) {
58 | this.classCache = classCache;
59 | }
60 |
61 | public HashMapIntObject getClassCache() {
62 | return classCache;
63 | }
64 |
65 | public void setRoots(HashMapIntObject roots) {
66 | this.roots = roots;
67 | }
68 |
69 | public HashMapIntObject getRoots() {
70 | return roots;
71 | }
72 |
73 | public void setRootsPerThread(HashMapIntObject> rootsPerThread) {
74 | this.rootsPerThread = rootsPerThread;
75 | }
76 |
77 | public void setArrayObjects(BitField arrayObjects) {
78 | this.arrayObjects = arrayObjects;
79 | }
80 |
81 | public SnapshotImpl create(Parser parser) throws IOException, SnapshotException {
82 | IObjectReader heapObjectReader = parser.getObjectReader();
83 | return SnapshotImpl.create(snapshotInfo, heapObjectReader, classCache, roots, rootsPerThread,
84 | arrayObjects, indexManager);
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/ActivityRefWatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary;
17 |
18 | import android.annotation.TargetApi;
19 | import android.app.Activity;
20 | import android.app.Application;
21 | import android.os.Bundle;
22 |
23 | import static android.os.Build.VERSION.SDK_INT;
24 | import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
25 | import static com.squareup.leakcanary.Preconditions.checkNotNull;
26 |
27 | @TargetApi(ICE_CREAM_SANDWICH) public final class ActivityRefWatcher {
28 |
29 | public static void installOnIcsPlus(Application application, RefWatcher refWatcher) {
30 | if (SDK_INT < ICE_CREAM_SANDWICH) {
31 | // If you need to support Android < ICS, override onDestroy() in your base activity.
32 | return;
33 | }
34 | ActivityRefWatcher activityRefWatcher = new ActivityRefWatcher(application, refWatcher);
35 | activityRefWatcher.watchActivities();
36 | }
37 |
38 | private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
39 | new Application.ActivityLifecycleCallbacks() {
40 | @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
41 | }
42 |
43 | @Override public void onActivityStarted(Activity activity) {
44 | }
45 |
46 | @Override public void onActivityResumed(Activity activity) {
47 | }
48 |
49 | @Override public void onActivityPaused(Activity activity) {
50 | }
51 |
52 | @Override public void onActivityStopped(Activity activity) {
53 | }
54 |
55 | @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
56 | }
57 |
58 | @Override public void onActivityDestroyed(Activity activity) {
59 | ActivityRefWatcher.this.onActivityDestroyed(activity);
60 | }
61 | };
62 |
63 | private final Application application;
64 | private final RefWatcher refWatcher;
65 |
66 | /**
67 | * Constructs an {@link ActivityRefWatcher} that will make sure the activities are not leaking
68 | * after they have been destroyed.
69 | */
70 | public ActivityRefWatcher(Application application, final RefWatcher refWatcher) {
71 | this.application = checkNotNull(application, "application");
72 | this.refWatcher = checkNotNull(refWatcher, "refWatcher");
73 | }
74 |
75 | void onActivityDestroyed(Activity activity) {
76 | refWatcher.watch(activity);
77 | }
78 |
79 | public void watchActivities() {
80 | // Make sure you don't get installed twice.
81 | stopWatchingActivities();
82 | application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
83 | }
84 |
85 | public void stopWatchingActivities() {
86 | application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/internal/snapshot/ObjectCache.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.internal.snapshot;
14 |
15 | import java.util.ArrayList;
16 | import java.util.LinkedList;
17 | import java.util.List;
18 |
19 | import org.eclipse.mat.collect.HashMapIntObject;
20 |
21 | abstract public class ObjectCache {
22 | static class Entry {
23 | E object;
24 | int key;
25 | int numUsages;
26 | }
27 |
28 | private int maxSize;
29 | private final HashMapIntObject> map;
30 | private final List>> lfus;
31 | private int maxLfuBuckets = 0;
32 | private int lowestNonEmptyLfu = 0;
33 |
34 | public ObjectCache(int maxSize) {
35 | this.maxSize = maxSize;
36 | this.map = new HashMapIntObject>(maxSize);
37 | this.lfus = new ArrayList>>(5);
38 | this.maxLfuBuckets = maxSize / 3;
39 | }
40 |
41 | public synchronized E get(int objectId) {
42 | Entry e = map.get(objectId);
43 | if (e != null) {
44 | revalueEntry(e);
45 | } else {
46 | e = new Entry();
47 | e.object = load(objectId);
48 | e.key = objectId;
49 |
50 | doInsert(e);
51 |
52 | while (map.size() > maxSize) removeLeastValuableNode();
53 | }
54 |
55 | return e.object;
56 | }
57 |
58 | public synchronized void clear() {
59 | this.map.clear();
60 | this.lfus.clear();
61 | }
62 |
63 | protected abstract E load(int key);
64 |
65 | protected synchronized void doInsert(final Entry e) {
66 | lfu(e.numUsages).addFirst(e);
67 | Entry> p = map.put(e.key, e);
68 | lowestNonEmptyLfu = 0;
69 |
70 | if (p != null) lfu(p.numUsages).remove(p);
71 | }
72 |
73 | protected final LinkedList> lfu(int numUsageIndex) {
74 | int lfuIndex = Math.min(maxLfuBuckets, numUsageIndex);
75 |
76 | if (lfuIndex >= lfus.size()) {
77 | LinkedList> lfu = new LinkedList>();
78 | lfus.add(lfuIndex, lfu);
79 | return lfu;
80 | } else {
81 | return lfus.get(lfuIndex);
82 | }
83 | }
84 |
85 | protected void revalueEntry(Entry entry) {
86 | LinkedList> currBucket = lfu(entry.numUsages);
87 | LinkedList> nextBucket = lfu(++entry.numUsages);
88 |
89 | currBucket.remove(entry);
90 | nextBucket.addFirst(entry);
91 | }
92 |
93 | protected LinkedList> getLowestNonEmptyLfu() {
94 | LinkedList> lfu = null;
95 | for (int i = lowestNonEmptyLfu; i < lfus.size(); i++) {
96 | lfu = lfu(i);
97 |
98 | if (lfu.size() != 0) {
99 | lowestNonEmptyLfu = i;
100 | return lfu;
101 | }
102 | }
103 | return lfu;
104 | }
105 |
106 | protected void removeLeastValuableNode() {
107 | LinkedList> lfu = getLowestNonEmptyLfu();
108 | Entry> lln = lfu.remove(lfu.size() - 1);
109 | map.remove(lln.key);
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/IClass.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.snapshot.model;
14 |
15 | import java.util.List;
16 |
17 | import org.eclipse.mat.SnapshotException;
18 | import org.eclipse.mat.util.IProgressListener;
19 |
20 | /**
21 | * Interface for a class instance in the heap dump.
22 | *
23 | * @noimplement
24 | */
25 | public interface IClass extends IObject {
26 | String JAVA_LANG_CLASS = "java.lang.Class"; //$NON-NLS-1$
27 | String JAVA_LANG_CLASSLOADER = "java.lang.ClassLoader"; //$NON-NLS-1$
28 |
29 | /**
30 | * Returns the fully qualified class name of this class.
31 | */
32 | public String getName();
33 |
34 | /**
35 | * Returns the number of instances of this class present in the heap dump.
36 | */
37 | public int getNumberOfObjects();
38 |
39 | /**
40 | * Ids of all instances of this class (an empty array if there are no instances of the class)
41 | */
42 | public int[] getObjectIds() throws SnapshotException;
43 |
44 | /**
45 | * Returns the id of the class loader which loaded this class.
46 | */
47 | public int getClassLoaderId();
48 |
49 | /**
50 | * Returns the address of the class loader which loaded this class.
51 | */
52 | public long getClassLoaderAddress();
53 |
54 | /**
55 | * Returns field descriptors for all member variables of instances of this
56 | * class.
57 | */
58 | public List getFieldDescriptors();
59 |
60 | /**
61 | * Returns the static fields and it values.
62 | */
63 | public List getStaticFields();
64 |
65 | /**
66 | * Returns the heap size of one instance of this class. Not valid if this
67 | * class represents an array.
68 | */
69 | public int getHeapSizePerInstance();
70 |
71 | /**
72 | * Returns the retained size of all objects of this instance including the
73 | * class instance.
74 | */
75 | public long getRetainedHeapSizeOfObjects(boolean calculateIfNotAvailable,
76 | boolean calculateMinRetainedSize, IProgressListener listener) throws SnapshotException;
77 |
78 | /**
79 | * Returns the id of the super class. -1 if it has no super class, i.e. if
80 | * it is java.lang.Object.
81 | */
82 | public int getSuperClassId();
83 |
84 | /**
85 | * Returns the super class.
86 | */
87 | public IClass getSuperClass();
88 |
89 | /**
90 | * Returns true if the class has a super class.
91 | */
92 | public boolean hasSuperClass();
93 |
94 | /**
95 | * Returns the direct sub-classes.
96 | */
97 | public List getSubclasses();
98 |
99 | /**
100 | * Returns all sub-classes including sub-classes of its sub-classes.
101 | */
102 | public List getAllSubclasses();
103 |
104 | public boolean doesExtend(String className) throws SnapshotException;
105 |
106 | /**
107 | * Returns true if the class is an array class.
108 | */
109 | public boolean isArrayType();
110 | }
111 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/LeakTraceElement.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary;
17 |
18 | import java.io.Serializable;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import static com.squareup.leakcanary.LeakTraceElement.Holder.ARRAY;
23 | import static com.squareup.leakcanary.LeakTraceElement.Holder.CLASS;
24 | import static com.squareup.leakcanary.LeakTraceElement.Holder.THREAD;
25 | import static com.squareup.leakcanary.LeakTraceElement.Type.STATIC_FIELD;
26 | import static java.util.Collections.unmodifiableList;
27 | import static java.util.Locale.US;
28 |
29 | /** Represents one reference in the chain of references that holds a leaking object in memory. */
30 | public final class LeakTraceElement implements Serializable {
31 |
32 | public enum Type {
33 | INSTANCE_FIELD, STATIC_FIELD, LOCAL, ARRAY_ENTRY
34 | }
35 |
36 | public enum Holder {
37 | OBJECT, CLASS, THREAD, ARRAY
38 | }
39 |
40 | /** Null if this is the last element in the leak trace, ie the leaking object. */
41 | public final String referenceName;
42 |
43 | /** Null if this is the last element in the leak trace, ie the leaking object. */
44 | public final Type type;
45 | public final Holder holder;
46 | public final String className;
47 |
48 | /** Additional information, may be null. */
49 | public final String extra;
50 |
51 | /** List of all fields (member and static) for that object. */
52 | public final List fields;
53 |
54 | LeakTraceElement(String referenceName, Type type, Holder holder, String className, String extra,
55 | List fields) {
56 | this.referenceName = referenceName;
57 | this.type = type;
58 | this.holder = holder;
59 | this.className = className;
60 | this.extra = extra;
61 | this.fields = unmodifiableList(new ArrayList<>(fields));
62 | }
63 |
64 | @Override public String toString() {
65 | String string = "";
66 |
67 | if (type == STATIC_FIELD) {
68 | string += "static ";
69 | }
70 |
71 | if (holder == ARRAY || holder == THREAD) {
72 | string += holder.name().toLowerCase(US) + " ";
73 | }
74 |
75 | string += className;
76 |
77 | if (referenceName != null) {
78 | string += "." + referenceName;
79 | } else {
80 | string += " instance";
81 | }
82 |
83 | if (extra != null) {
84 | string += " " + extra;
85 | }
86 | return string;
87 | }
88 |
89 | public String toDetailedString() {
90 | String string = "* ";
91 | if (holder == ARRAY) {
92 | string += "Array of";
93 | } else if (holder == CLASS) {
94 | string += "Class";
95 | } else {
96 | string += "Instance of";
97 | }
98 | string += " " + className + "\n";
99 | for (String field : fields) {
100 | string += "| " + field + "\n";
101 | }
102 | return string;
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/util/SimpleMonitor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.util;
14 |
15 | import org.eclipse.mat.hprof.Messages;
16 |
17 | public class SimpleMonitor {
18 | String task;
19 | IProgressListener delegate;
20 | int currentMonitor;
21 | int[] percentages;
22 |
23 | public SimpleMonitor(String task, IProgressListener monitor, int[] percentages) {
24 | this.task = task;
25 | this.delegate = monitor;
26 | this.percentages = percentages;
27 | }
28 |
29 | public IProgressListener nextMonitor() {
30 | if (currentMonitor == 0) {
31 | int total = 0;
32 | for (int ii : percentages)
33 | total += ii;
34 | delegate.beginTask(task, total);
35 | }
36 |
37 | return new Listener(percentages[currentMonitor++]);
38 | }
39 |
40 | public class Listener implements IProgressListener {
41 | long counter;
42 |
43 | int majorUnits;
44 | int unitsReported;
45 | long workDone;
46 | long workPerUnit;
47 |
48 | boolean isSmaller;
49 |
50 | public Listener(int majorUnits) {
51 | this.majorUnits = majorUnits;
52 | }
53 |
54 | public final void beginTask(Messages name, int totalWork) {
55 | beginTask(name.pattern, totalWork);
56 | }
57 |
58 | public void beginTask(String name, int totalWork) {
59 | if (name != null) delegate.subTask(name);
60 |
61 | if (totalWork == 0) return;
62 |
63 | isSmaller = totalWork < majorUnits;
64 | workPerUnit = isSmaller ? majorUnits / totalWork : totalWork / majorUnits;
65 | unitsReported = 0;
66 | }
67 |
68 | public void subTask(String name) {
69 | delegate.subTask(name);
70 | }
71 |
72 | public void done() {
73 | if (majorUnits - unitsReported > 0) delegate.worked(majorUnits - unitsReported);
74 | }
75 |
76 | public boolean isCanceled() {
77 | return delegate.isCanceled();
78 | }
79 |
80 | public boolean isProbablyCanceled() {
81 | return counter++ % 5000 == 0 ? isCanceled() : false;
82 | }
83 |
84 | public void totalWorkDone(long work) {
85 | if (workDone == work) return;
86 |
87 | if (workPerUnit == 0) return;
88 |
89 | workDone = work;
90 | int unitsWorked = isSmaller ? (int) (work * workPerUnit) : (int) (work / workPerUnit);
91 | int unitsToReport = unitsWorked - unitsReported;
92 |
93 | if (unitsToReport > 0) {
94 | delegate.worked(unitsToReport);
95 | unitsReported += unitsToReport;
96 | }
97 | }
98 |
99 | public void worked(int work) {
100 | totalWorkDone(workDone + work);
101 | }
102 |
103 | public void setCanceled(boolean value) {
104 | delegate.setCanceled(value);
105 | }
106 |
107 | public void sendUserMessage(Severity severity, String message, Throwable exception) {
108 | delegate.sendUserMessage(severity, message, exception);
109 | }
110 |
111 | public long getWorkDone() {
112 | return workDone;
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/io/BitOutputStream.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.io;
14 |
15 | import java.io.Closeable;
16 | import java.io.Flushable;
17 | import java.io.IOException;
18 | import java.io.OutputStream;
19 |
20 | import org.eclipse.mat.hprof.Messages;
21 |
22 | public class BitOutputStream implements Flushable, Closeable {
23 |
24 | public final static int DEFAULT_BUFFER_SIZE = 16 * 1024;
25 |
26 | private OutputStream os;
27 | private int current;
28 | private byte[] buffer;
29 | private int free;
30 | private int pos;
31 | private int avail;
32 |
33 | final static int TEMP_BUFFER_SIZE = 128;
34 | private byte[] tempBuffer = new byte[TEMP_BUFFER_SIZE];
35 |
36 | public BitOutputStream(final OutputStream os) {
37 | this.os = os;
38 | this.buffer = new byte[DEFAULT_BUFFER_SIZE];
39 | avail = DEFAULT_BUFFER_SIZE;
40 | free = 8;
41 | }
42 |
43 | public void flush() throws IOException {
44 | align();
45 |
46 | os.write(buffer, 0, pos);
47 | pos = 0;
48 | avail = buffer.length;
49 |
50 | os.flush();
51 | }
52 |
53 | public void close() throws IOException {
54 | flush();
55 | os.close();
56 | os = null;
57 | buffer = null;
58 | tempBuffer = null;
59 | }
60 |
61 | private void write(final int b) throws IOException {
62 | if (avail-- == 0) {
63 | if (os == null) {
64 | avail = 0;
65 | throw new IOException(Messages.BitOutputStream_Error_ArrayFull.pattern);
66 | }
67 |
68 | if (buffer == null) {
69 | os.write(b);
70 | avail = 0;
71 | return;
72 | }
73 | os.write(buffer);
74 | avail = buffer.length - 1;
75 | pos = 0;
76 | }
77 |
78 | buffer[pos++] = (byte) b;
79 | }
80 |
81 | private int writeInCurrent(final int b, final int len) throws IOException {
82 | current |= (b & ((1 << len) - 1)) << (free -= len);
83 | if (free == 0) {
84 | write(current);
85 | free = 8;
86 | current = 0;
87 | }
88 |
89 | return len;
90 | }
91 |
92 | private int align() throws IOException {
93 | if (free != 8) {
94 | return writeInCurrent(0, free);
95 | } else {
96 | return 0;
97 | }
98 | }
99 |
100 | public int writeBit(final int bit) throws IOException {
101 | return writeInCurrent(bit, 1);
102 | }
103 |
104 | public int writeInt(int x, final int len) throws IOException {
105 | if (len <= free) return writeInCurrent(x, len);
106 |
107 | final int queue = (len - free) & 7, blocks = (len - free) >> 3;
108 | int i = blocks;
109 |
110 | if (queue != 0) {
111 | tempBuffer[blocks] = (byte) x;
112 | x >>= queue;
113 | }
114 |
115 | while (i-- != 0) {
116 | tempBuffer[i] = (byte) x;
117 | x >>>= 8;
118 | }
119 |
120 | writeInCurrent(x, free);
121 | for (i = 0; i < blocks; i++)
122 | write(tempBuffer[i]);
123 |
124 | if (queue != 0) writeInCurrent(tempBuffer[blocks], queue);
125 | return len;
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/hprof/IHprofParserHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.hprof;
14 |
15 | import java.io.IOException;
16 | import java.util.List;
17 |
18 | import org.eclipse.mat.SnapshotException;
19 | import org.eclipse.mat.collect.ArrayLong;
20 | import org.eclipse.mat.collect.HashMapLongObject;
21 | import org.eclipse.mat.parser.IPreliminaryIndex;
22 | import org.eclipse.mat.parser.index.IIndexReader.IOne2LongIndex;
23 | import org.eclipse.mat.parser.model.ClassImpl;
24 | import org.eclipse.mat.parser.model.XSnapshotInfo;
25 | import org.eclipse.mat.snapshot.model.IClass;
26 | import org.eclipse.mat.util.IProgressListener;
27 |
28 | public interface IHprofParserHandler {
29 | String IDENTIFIER_SIZE = "ID_SIZE"; //$NON-NLS-1$
30 | String CREATION_DATE = "CREATION_DATE"; //$NON-NLS-1$
31 | String VERSION = "VERSION";//$NON-NLS-1$
32 |
33 | public class HeapObject {
34 | public int objectId;
35 | public long objectAddress;
36 | public ClassImpl clazz;
37 | public int usedHeapSize;
38 | public ArrayLong references = new ArrayLong();
39 | public boolean isArray = false;
40 |
41 | public HeapObject(int objectId, long objectAddress, ClassImpl clazz, int usedHeapSize) {
42 | super();
43 | this.objectId = objectId;
44 | this.objectAddress = objectAddress;
45 | this.clazz = clazz;
46 | this.usedHeapSize = usedHeapSize;
47 | this.isArray = false;
48 | }
49 | }
50 |
51 | // //////////////////////////////////////////////////////////////
52 | // lifecycle
53 | // //////////////////////////////////////////////////////////////
54 |
55 | void beforePass1(XSnapshotInfo snapshotInfo) throws IOException;
56 |
57 | void beforePass2(IProgressListener monitor) throws IOException, SnapshotException;
58 |
59 | IOne2LongIndex fillIn(IPreliminaryIndex index) throws IOException;
60 |
61 | void cancel();
62 |
63 | // //////////////////////////////////////////////////////////////
64 | // report parsed entities
65 | // //////////////////////////////////////////////////////////////
66 |
67 | void addProperty(String name, String value) throws IOException;
68 |
69 | void addGCRoot(long id, long referrer, int rootType) throws IOException;
70 |
71 | void addClass(ClassImpl clazz, long filePosition) throws IOException;
72 |
73 | void addObject(HeapObject object, long filePosition) throws IOException;
74 |
75 | void reportInstance(long id, long filePosition);
76 |
77 | void reportRequiredObjectArray(long arrayClassID);
78 |
79 | void reportRequiredPrimitiveArray(int arrayType);
80 |
81 | // //////////////////////////////////////////////////////////////
82 | // lookup heap infos
83 | // //////////////////////////////////////////////////////////////
84 |
85 | int getIdentifierSize();
86 |
87 | HashMapLongObject getConstantPool();
88 |
89 | IClass lookupClass(long classId);
90 |
91 | IClass lookupClassByName(String name, boolean failOnMultipleInstances);
92 |
93 | IClass lookupClassByIndex(int objIndex);
94 |
95 | List resolveClassHierarchy(long classId);
96 |
97 | int mapAddressToId(long address);
98 |
99 | XSnapshotInfo getSnapshotInfo();
100 | }
101 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/model/PrimitiveArrayImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.model;
14 |
15 | import java.io.IOException;
16 | import java.lang.reflect.Array;
17 | import java.util.ArrayList;
18 | import java.util.List;
19 |
20 | import org.eclipse.mat.SnapshotException;
21 | import org.eclipse.mat.collect.ArrayLong;
22 | import org.eclipse.mat.snapshot.model.Field;
23 | import org.eclipse.mat.snapshot.model.IPrimitiveArray;
24 | import org.eclipse.mat.snapshot.model.NamedReference;
25 | import org.eclipse.mat.snapshot.model.PseudoReference;
26 |
27 | /**
28 | * @noextend
29 | */
30 | public class PrimitiveArrayImpl extends AbstractArrayImpl implements IPrimitiveArray {
31 | private static final long serialVersionUID = 2L;
32 |
33 | private int type;
34 |
35 | public PrimitiveArrayImpl(int objectId, long address, ClassImpl classInstance, int length,
36 | int type) {
37 | super(objectId, address, classInstance, length);
38 | this.type = type;
39 | }
40 |
41 | public int getType() {
42 | return type;
43 | }
44 |
45 | public Class> getComponentType() {
46 | return COMPONENT_TYPE[type];
47 | }
48 |
49 | public Object getValueAt(int index) {
50 | Object data = getValueArray(index, 1);
51 | return data != null ? Array.get(data, 0) : null;
52 | }
53 |
54 | public Object getValueArray() {
55 | try {
56 | return source.getHeapObjectReader().readPrimitiveArrayContent(this, 0, getLength());
57 | } catch (SnapshotException e) {
58 | throw new RuntimeException(e);
59 | } catch (IOException e) {
60 | throw new RuntimeException(e);
61 | }
62 | }
63 |
64 | public Object getValueArray(int offset, int length) {
65 | try {
66 | return source.getHeapObjectReader().readPrimitiveArrayContent(this, offset, length);
67 | } catch (SnapshotException e) {
68 | throw new RuntimeException(e);
69 | } catch (IOException e) {
70 | throw new RuntimeException(e);
71 | }
72 | }
73 |
74 | protected Field internalGetField(String name) {
75 | return null;
76 | }
77 |
78 | @Override public ArrayLong getReferences() {
79 | ArrayLong references = new ArrayLong(1);
80 | references.add(classInstance.getObjectAddress());
81 | return references;
82 | }
83 |
84 | public List getOutboundReferences() {
85 | List references = new ArrayList(1);
86 | references.add(
87 | new PseudoReference(source, classInstance.getObjectAddress(), ""));//$NON-NLS-1$
88 | return references;
89 | }
90 |
91 | @Override protected StringBuffer appendFields(StringBuffer buf) {
92 | return super.appendFields(buf).append(";size=").append(getUsedHeapSize());//$NON-NLS-1$
93 | }
94 |
95 | @Override public int getUsedHeapSize() {
96 | try {
97 | return getSnapshot().getHeapSize(getObjectId());
98 | } catch (SnapshotException e) {
99 | return doGetUsedHeapSize(classInstance, length, type);
100 | }
101 | }
102 |
103 | public static int doGetUsedHeapSize(ClassImpl clazz, int length, int type) {
104 | return alignUpTo8(2 * clazz.getHeapSizePerInstance() + 4 + length * ELEMENT_SIZE[type]);
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/collect/ArrayInt.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.collect;
14 |
15 | import java.util.Arrays;
16 |
17 | public final class ArrayInt {
18 | int elements[];
19 | int size;
20 |
21 | public ArrayInt() {
22 | this(10);
23 | }
24 |
25 | public ArrayInt(int initialCapacity) {
26 | elements = new int[initialCapacity];
27 | size = 0;
28 | }
29 |
30 | public ArrayInt(int[] initialValues) {
31 | this(initialValues.length);
32 | System.arraycopy(initialValues, 0, elements, 0, initialValues.length);
33 | size = initialValues.length;
34 | }
35 |
36 | public ArrayInt(ArrayInt template) {
37 | this(template.size);
38 | System.arraycopy(template.elements, 0, elements, 0, template.size);
39 | size = template.size;
40 | }
41 |
42 | public void add(int element) {
43 | ensureCapacity(size + 1);
44 | elements[size++] = element;
45 | }
46 |
47 | public void addAll(int[] elements) {
48 | ensureCapacity(size + elements.length);
49 | System.arraycopy(elements, 0, this.elements, size, elements.length);
50 | size += elements.length;
51 | }
52 |
53 | public void addAll(ArrayInt template) {
54 | ensureCapacity(size + template.size);
55 | System.arraycopy(template.elements, 0, elements, size, template.size);
56 | size += template.size;
57 | }
58 |
59 | public int set(int index, int element) {
60 | if (index < 0 || index >= size) throw new ArrayIndexOutOfBoundsException(index);
61 |
62 | int oldValue = elements[index];
63 | elements[index] = element;
64 | return oldValue;
65 | }
66 |
67 | public int get(int index) {
68 | if (index < 0 || index >= size) throw new ArrayIndexOutOfBoundsException(index);
69 | return elements[index];
70 | }
71 |
72 | public int size() {
73 | return size;
74 | }
75 |
76 | public int[] toArray() {
77 | int[] result = new int[size];
78 | System.arraycopy(elements, 0, result, 0, size);
79 | return result;
80 | }
81 |
82 | public boolean isEmpty() {
83 | return size == 0;
84 | }
85 |
86 | public IteratorInt iterator() {
87 | return new IteratorInt() {
88 | int index = 0;
89 |
90 | public boolean hasNext() {
91 | return index < size;
92 | }
93 |
94 | public int next() {
95 | return elements[index++];
96 | }
97 | };
98 | }
99 |
100 | public void clear() {
101 | size = 0;
102 | }
103 |
104 | public long lastElement() {
105 | return elements[size - 1];
106 | }
107 |
108 | public long firstElement() {
109 | if (size == 0) throw new ArrayIndexOutOfBoundsException();
110 |
111 | return elements[0];
112 | }
113 |
114 | public void sort() {
115 | Arrays.sort(elements, 0, size);
116 | }
117 |
118 | // //////////////////////////////////////////////////////////////
119 | // implementation stuff
120 | // //////////////////////////////////////////////////////////////
121 |
122 | private void ensureCapacity(int minCapacity) {
123 | int oldCapacity = elements.length;
124 | if (minCapacity > oldCapacity) {
125 | int oldData[] = elements;
126 | int newCapacity = (oldCapacity * 3) / 2 + 1;
127 | if (newCapacity < minCapacity) newCapacity = minCapacity;
128 | elements = new int[newCapacity];
129 | System.arraycopy(oldData, 0, elements, 0, size);
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/collect/ArrayLong.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.collect;
14 |
15 | import java.util.Arrays;
16 |
17 | public final class ArrayLong {
18 | long elements[];
19 | int size;
20 |
21 | public ArrayLong() {
22 | this(10);
23 | }
24 |
25 | public ArrayLong(int initialCapacity) {
26 | elements = new long[initialCapacity];
27 | size = 0;
28 | }
29 |
30 | public ArrayLong(long[] initialValues) {
31 | this(initialValues.length);
32 | System.arraycopy(initialValues, 0, elements, 0, initialValues.length);
33 | size = initialValues.length;
34 | }
35 |
36 | public ArrayLong(ArrayLong template) {
37 | this(template.size);
38 | System.arraycopy(template.elements, 0, elements, 0, template.size);
39 | size = template.size;
40 | }
41 |
42 | public void add(long element) {
43 | ensureCapacity(size + 1);
44 | elements[size++] = element;
45 | }
46 |
47 | public void addAll(long[] elements) {
48 | ensureCapacity(size + elements.length);
49 | System.arraycopy(elements, 0, this.elements, size, elements.length);
50 | size += elements.length;
51 | }
52 |
53 | public void addAll(ArrayLong template) {
54 | ensureCapacity(size + template.size);
55 | System.arraycopy(template.elements, 0, elements, size, template.size);
56 | size += template.size;
57 | }
58 |
59 | public long set(int index, long element) {
60 | if (index < 0 || index >= size) throw new ArrayIndexOutOfBoundsException(index);
61 |
62 | long oldValue = elements[index];
63 | elements[index] = element;
64 | return oldValue;
65 | }
66 |
67 | public long get(int index) {
68 | if (index < 0 || index >= size) throw new ArrayIndexOutOfBoundsException(index);
69 | return elements[index];
70 | }
71 |
72 | public int size() {
73 | return size;
74 | }
75 |
76 | public long[] toArray() {
77 | long[] result = new long[size];
78 | System.arraycopy(elements, 0, result, 0, size);
79 | return result;
80 | }
81 |
82 | public boolean isEmpty() {
83 | return size == 0;
84 | }
85 |
86 | public IteratorLong iterator() {
87 | return new IteratorLong() {
88 | int index = 0;
89 |
90 | public boolean hasNext() {
91 | return index < size;
92 | }
93 |
94 | public long next() {
95 | return elements[index++];
96 | }
97 | };
98 | }
99 |
100 | public void clear() {
101 | size = 0;
102 | }
103 |
104 | public long lastElement() {
105 | return elements[size - 1];
106 | }
107 |
108 | public long firstElement() {
109 | if (size == 0) throw new ArrayIndexOutOfBoundsException();
110 |
111 | return elements[0];
112 | }
113 |
114 | public void sort() {
115 | Arrays.sort(elements, 0, size);
116 | }
117 |
118 | // //////////////////////////////////////////////////////////////
119 | // implementation stuff
120 | // //////////////////////////////////////////////////////////////
121 |
122 | private void ensureCapacity(int minCapacity) {
123 | int oldCapacity = elements.length;
124 | if (minCapacity > oldCapacity) {
125 | long oldData[] = elements;
126 | int newCapacity = (oldCapacity * 3) / 2 + 1;
127 | if (newCapacity < minCapacity) newCapacity = minCapacity;
128 | elements = new long[newCapacity];
129 | System.arraycopy(oldData, 0, elements, 0, size);
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/internal/util/ParserRegistry.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.internal.util;
14 |
15 | import java.util.ArrayList;
16 | import java.util.List;
17 | import java.util.regex.Pattern;
18 |
19 | import org.eclipse.mat.parser.IIndexBuilder;
20 | import org.eclipse.mat.parser.IObjectReader;
21 | import org.eclipse.mat.snapshot.SnapshotFormat;
22 |
23 | public class ParserRegistry {
24 | public static final String INDEX_BUILDER = "indexBuilder";
25 | public static final String OBJECT_READER = "objectReader";
26 |
27 | public List parsers = new ArrayList();
28 |
29 | private static ParserRegistry instance = new ParserRegistry();
30 |
31 | static {
32 | addParser("hprof", "hprof", new String[] { "hprof", "bin" },
33 | new org.eclipse.mat.hprof.HprofHeapObjectReader(),
34 | new org.eclipse.mat.hprof.HprofIndexBuilder());
35 | }
36 |
37 | public static class Parser {
38 | private IObjectReader objectReader;
39 | private IIndexBuilder indexBuilder;
40 |
41 | private String id;
42 | private SnapshotFormat snapshotFormat;
43 | private Pattern[] patterns;
44 |
45 | public Parser(String id, SnapshotFormat snapshotFormat, IObjectReader objectReader,
46 | IIndexBuilder indexBuilder) {
47 | this.id = id;
48 | this.snapshotFormat = snapshotFormat;
49 |
50 | this.patterns = new Pattern[snapshotFormat.getFileExtensions().length];
51 | for (int ii = 0; ii < snapshotFormat.getFileExtensions().length; ii++) {
52 | patterns[ii] = Pattern.compile(
53 | "(.*\\.)((?i)" + snapshotFormat.getFileExtensions()[ii] + ")(\\.[0-9]*)?");
54 | }
55 | this.objectReader = objectReader;
56 | this.indexBuilder = indexBuilder;
57 | }
58 |
59 | public IObjectReader getObjectReader() {
60 | return this.objectReader;
61 | }
62 |
63 | public IIndexBuilder getIndexBuilder() {
64 | return this.indexBuilder;
65 | }
66 |
67 | public String getId() {
68 | return id;
69 | }
70 |
71 | public String getUniqueIdentifier() {
72 | return id;
73 | }
74 |
75 | public SnapshotFormat getSnapshotFormat() {
76 | return snapshotFormat;
77 | }
78 | }
79 |
80 | private ParserRegistry() {
81 |
82 | }
83 |
84 | public static void addParser(String id, String snapshotFormat, String[] extensions,
85 | IObjectReader objectReader, IIndexBuilder indexBuilder) {
86 | SnapshotFormat sf = new SnapshotFormat(snapshotFormat, extensions);
87 | Parser p = new Parser(id, sf, objectReader, indexBuilder);
88 | instance.parsers.add(p);
89 | }
90 |
91 | public static Parser lookupParser(String uniqueIdentifier) {
92 | for (Parser p : instance.parsers)
93 | if (uniqueIdentifier.equals(p.getUniqueIdentifier())) return p;
94 | return null;
95 | }
96 |
97 | public static List matchParser(String fileName) {
98 | List answer = new ArrayList();
99 | for (Parser p : instance.parsers) {
100 | for (Pattern regex : p.patterns) {
101 | if (regex.matcher(fileName).matches()) {
102 | answer.add(p);
103 | // Only need to add a parser once
104 | break;
105 | }
106 | }
107 | }
108 | return answer;
109 | }
110 |
111 | public static List allParsers() {
112 | return instance.parsers;
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/internal/snapshot/RetainedSizeCache.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.internal.snapshot;
14 |
15 | import java.io.BufferedInputStream;
16 | import java.io.DataInputStream;
17 | import java.io.DataOutputStream;
18 | import java.io.File;
19 | import java.io.FileInputStream;
20 | import java.io.FileOutputStream;
21 | import java.io.IOException;
22 | import java.util.NoSuchElementException;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 |
26 | import org.eclipse.mat.collect.HashMapIntLong;
27 | import org.eclipse.mat.hprof.Messages;
28 | import org.eclipse.mat.parser.model.XSnapshotInfo;
29 |
30 | public class RetainedSizeCache {
31 | private String filename;
32 | private HashMapIntLong id2size;
33 | private boolean isDirty = false;
34 |
35 | public RetainedSizeCache(XSnapshotInfo snapshotInfo) {
36 | this.filename = snapshotInfo.getPrefix() + "i2sv2.index"; //$NON-NLS-1$
37 | readId2Size(snapshotInfo.getPrefix());
38 | }
39 |
40 | public long get(int key) {
41 | try {
42 | return id2size.get(key);
43 | } catch (NoSuchElementException e) {
44 | // $JL-EXC$
45 | return 0;
46 | }
47 | }
48 |
49 | public void put(int key, long value) {
50 | id2size.put(key, value);
51 | isDirty = true;
52 | }
53 |
54 | public void close() {
55 | if (!isDirty) return;
56 |
57 | try {
58 | File file = new File(filename);
59 |
60 | DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
61 |
62 | for (int key : id2size.getAllKeys()) {
63 | out.writeInt(key);
64 | out.writeLong(id2size.get(key));
65 | }
66 |
67 | out.close();
68 |
69 | isDirty = false;
70 | } catch (IOException e) {
71 | Logger.getLogger(RetainedSizeCache.class.getName())
72 | .log(Level.WARNING, Messages.RetainedSizeCache_Warning_IgnoreError.pattern, e);
73 | }
74 | }
75 |
76 | private void doRead(File file, boolean readOldFormat) {
77 | DataInputStream in = null;
78 | boolean delete = false;
79 |
80 | try {
81 | id2size = new HashMapIntLong((int) file.length() / 8);
82 |
83 | in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
84 |
85 | while (in.available() > 0) {
86 | int key = in.readInt();
87 | long value = in.readLong();
88 | if (value < 0 && readOldFormat) value = -(value - (Long.MIN_VALUE + 1));
89 | id2size.put(key, value);
90 | }
91 | } catch (IOException e) {
92 | Logger.getLogger(RetainedSizeCache.class.getName())
93 | .log(Level.WARNING, Messages.RetainedSizeCache_ErrorReadingRetainedSizes.pattern, e);
94 |
95 | // might have read corrupt data
96 | id2size.clear();
97 | delete = true;
98 | } finally {
99 | try {
100 | if (in != null) {
101 | in.close();
102 | }
103 | } catch (IOException ignore) {
104 | // $JL-EXC$
105 | }
106 | try {
107 | if (delete) {
108 | file.delete();
109 | }
110 | } catch (RuntimeException ignore) {
111 | // $JL-EXC$
112 | }
113 | }
114 | }
115 |
116 | private void readId2Size(String prefix) {
117 | File file = new File(filename);
118 | if (file.exists()) {
119 | doRead(file, false);
120 | } else {
121 | File legacyFile = new File(prefix + "i2s.index");//$NON-NLS-1$
122 | if (legacyFile.exists()) {
123 | doRead(legacyFile, true);
124 | } else {
125 | id2size = new HashMapIntLong();
126 | }
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/io/BufferedRandomAccessInputStream.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2008 SAP AG.
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * which accompanies this distribution, and is available at
7 | * http://www.eclipse.org/legal/epl-v10.html
8 | *
9 | * Contributors:
10 | * SAP AG - initial API and implementation
11 | * *****************************************************************************
12 | */
13 | package org.eclipse.mat.parser.io;
14 |
15 | import java.io.IOException;
16 | import java.io.InputStream;
17 | import java.io.RandomAccessFile;
18 | import java.lang.ref.SoftReference;
19 |
20 | import org.eclipse.mat.collect.HashMapLongObject;
21 |
22 | public class BufferedRandomAccessInputStream extends InputStream {
23 | RandomAccessFile raf;
24 |
25 | private class Page {
26 | long real_pos_start;
27 | byte[] buffer;
28 | int buf_end;
29 |
30 | public Page() {
31 | buffer = new byte[bufsize];
32 | }
33 | }
34 |
35 | int bufsize;
36 | long fileLength;
37 | long real_pos;
38 | long reported_pos;
39 |
40 | HashMapLongObject> pages = new HashMapLongObject>();
41 |
42 | Page current;
43 |
44 | public BufferedRandomAccessInputStream(RandomAccessFile in) throws IOException {
45 | this(in, 1024);
46 | }
47 |
48 | public BufferedRandomAccessInputStream(RandomAccessFile in, int bufsize) throws IOException {
49 | this.bufsize = bufsize;
50 | this.raf = in;
51 | this.fileLength = in.length();
52 | }
53 |
54 | public final int read() throws IOException {
55 | if (reported_pos == fileLength) return -1;
56 |
57 | if (current == null || (reported_pos - current.real_pos_start) >= current.buf_end) {
58 | current = getPage(reported_pos);
59 | }
60 |
61 | return current.buffer[((int) (reported_pos++ - current.real_pos_start))] & 0xff;
62 | }
63 |
64 | @Override public int read(byte[] b, int off, int len) throws IOException {
65 | if (b == null) {
66 | throw new NullPointerException();
67 | } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off
68 | + len) < 0)) {
69 | throw new IndexOutOfBoundsException();
70 | } else if (len == 0) {
71 | return 0;
72 | }
73 |
74 | if (reported_pos == fileLength) return -1;
75 |
76 | int copied = 0;
77 |
78 | while (copied < len) {
79 | if (reported_pos == fileLength) return copied;
80 |
81 | if (current == null || (reported_pos - current.real_pos_start) >= current.buf_end) {
82 | current = getPage(reported_pos);
83 | }
84 |
85 | int buf_pos = (int) (reported_pos - current.real_pos_start);
86 | int length = Math.min(len - copied, current.buf_end - buf_pos);
87 | System.arraycopy(current.buffer, buf_pos, b, off + copied, length);
88 |
89 | reported_pos += length;
90 | copied += length;
91 | }
92 |
93 | return copied;
94 | }
95 |
96 | private Page getPage(long pos) throws IOException {
97 | long key = pos / bufsize;
98 |
99 | SoftReference r = pages.get(key);
100 | Page p = r == null ? null : r.get();
101 |
102 | if (p != null) return p;
103 |
104 | long page_start = key * bufsize;
105 |
106 | if (page_start != real_pos) {
107 | raf.seek(page_start);
108 | real_pos = page_start;
109 | }
110 |
111 | p = new Page();
112 |
113 | int n = raf.read(p.buffer);
114 | if (n >= 0) {
115 | p.real_pos_start = real_pos;
116 | p.buf_end = n;
117 | real_pos += n;
118 | }
119 |
120 | pages.put(key, new SoftReference(p));
121 |
122 | return p;
123 | }
124 |
125 | public boolean markSupported() {
126 | return false;
127 | }
128 |
129 | public void close() throws IOException {
130 | raf.close();
131 | }
132 |
133 | /**
134 | * @throws IOException
135 | */
136 | public void seek(long pos) throws IOException {
137 | reported_pos = pos;
138 | current = null;
139 | }
140 |
141 | public long getFilePointer() {
142 | return reported_pos;
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/internal/DisplayLeakConnectorView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
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 | package com.squareup.leakcanary.internal;
17 |
18 | import android.content.Context;
19 | import android.graphics.Bitmap;
20 | import android.graphics.Canvas;
21 | import android.graphics.Color;
22 | import android.graphics.Paint;
23 | import android.util.AttributeSet;
24 | import android.view.View;
25 |
26 | import static android.graphics.Bitmap.Config.ARGB_8888;
27 |
28 | public final class DisplayLeakConnectorView extends View {
29 |
30 | private static final Paint iconPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
31 | private static final Paint rootPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
32 | private static final Paint leakPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
33 | private static final Paint clearPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
34 |
35 | static {
36 | iconPaint.setColor(LeakCanaryUi.LIGHT_GREY);
37 | rootPaint.setColor(LeakCanaryUi.ROOT_COLOR);
38 | leakPaint.setColor(LeakCanaryUi.LEAK_COLOR);
39 | clearPaint.setColor(Color.TRANSPARENT);
40 | clearPaint.setXfermode(LeakCanaryUi.CLEAR_XFER_MODE);
41 | }
42 |
43 | public enum Type {
44 | START, NODE, END
45 | }
46 |
47 | private Type type;
48 | private Bitmap cache;
49 |
50 | public DisplayLeakConnectorView(Context context, AttributeSet attrs) {
51 | super(context, attrs);
52 |
53 | type = Type.NODE;
54 | }
55 |
56 | @SuppressWarnings("SuspiciousNameCombination") @Override protected void onDraw(Canvas canvas) {
57 | int width = getWidth();
58 | int height = getHeight();
59 |
60 | if (cache != null && (cache.getWidth() != width || cache.getHeight() != height)) {
61 | cache.recycle();
62 | cache = null;
63 | }
64 |
65 | if (cache == null) {
66 | cache = Bitmap.createBitmap(width, height, ARGB_8888);
67 |
68 | Canvas cacheCanvas = new Canvas(cache);
69 |
70 | float halfWidth = width / 2f;
71 | float halfHeight = height / 2f;
72 | float thirdWidth = width / 3f;
73 |
74 | float strokeSize = LeakCanaryUi.dpToPixel(4f, getResources());
75 |
76 | iconPaint.setStrokeWidth(strokeSize);
77 | rootPaint.setStrokeWidth(strokeSize);
78 |
79 | switch (type) {
80 | case NODE:
81 | cacheCanvas.drawLine(halfWidth, 0, halfWidth, height, iconPaint);
82 | cacheCanvas.drawCircle(halfWidth, halfHeight, halfWidth, iconPaint);
83 | cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, clearPaint);
84 | break;
85 | case START:
86 | float radiusClear = halfWidth - strokeSize / 2f;
87 | cacheCanvas.drawRect(0, 0, width, radiusClear, rootPaint);
88 | cacheCanvas.drawCircle(0, radiusClear, radiusClear, clearPaint);
89 | cacheCanvas.drawCircle(width, radiusClear, radiusClear, clearPaint);
90 | cacheCanvas.drawLine(halfWidth, 0, halfWidth, halfHeight, rootPaint);
91 | cacheCanvas.drawLine(halfWidth, halfHeight, halfWidth, height, iconPaint);
92 | cacheCanvas.drawCircle(halfWidth, halfHeight, halfWidth, iconPaint);
93 | cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, clearPaint);
94 | break;
95 | default:
96 | cacheCanvas.drawLine(halfWidth, 0, halfWidth, halfHeight, iconPaint);
97 | cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, leakPaint);
98 | break;
99 | }
100 | }
101 | canvas.drawBitmap(cache, 0, 0, null);
102 | }
103 |
104 | public void setType(Type type) {
105 | if (type != this.type) {
106 | this.type = type;
107 | if (cache != null) {
108 | cache.recycle();
109 | cache = null;
110 | }
111 | invalidate();
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------