() {
51 | @Override
52 | protected Void doInBackground(Void... params) {
53 | // Do some slow work in background
54 | SystemClock.sleep(20000);
55 | return null;
56 | }
57 | }.execute();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [DEPARTED]
2 | 请参照 [Leakcanary](https://github.com/square/leakcanary) 使用方式。
3 |
4 | # LeakcanarySample-Eclipse
5 |
6 | 本项目是根据 [Leakcanary](https://github.com/square/leakcanary) 项目(version 1.3.1)改造为适用于Eclipse。
7 |
8 |
--------------------------------------------------------------------------------
/leakcanarylib/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/leakcanarylib/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Leakcanary
4 |
5 |
6 |
7 |
8 |
9 | com.android.ide.eclipse.adt.ResourceManagerBuilder
10 |
11 |
12 |
13 |
14 | com.android.ide.eclipse.adt.PreCompilerBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 | com.android.ide.eclipse.adt.ApkBuilder
25 |
26 |
27 |
28 |
29 |
30 | com.android.ide.eclipse.adt.AndroidNature
31 | org.eclipse.jdt.core.javanature
32 |
33 |
34 |
--------------------------------------------------------------------------------
/leakcanarylib/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.7
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.7
12 |
--------------------------------------------------------------------------------
/leakcanarylib/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
21 |
22 |
23 |
24 |
25 |
26 |
31 |
35 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/leakcanarylib/libs/haha-2.0.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/libs/haha-2.0.2.jar
--------------------------------------------------------------------------------
/leakcanarylib/lint.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/leakcanarylib/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/leakcanarylib/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-22
15 | android.library=true
16 |
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-hdpi-v11/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-hdpi-v11/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-hdpi/leak_canary_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-hdpi/leak_canary_icon.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-hdpi/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-hdpi/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-mdpi-v11/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-mdpi-v11/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-mdpi/leak_canary_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-mdpi/leak_canary_icon.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-mdpi/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-mdpi/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xhdpi-v11/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xhdpi-v11/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xhdpi/leak_canary_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xhdpi/leak_canary_icon.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xhdpi/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xhdpi/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xxhdpi-v11/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xxhdpi-v11/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xxhdpi/leak_canary_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xxhdpi/leak_canary_icon.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xxhdpi/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xxhdpi/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xxxhdpi-v11/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xxxhdpi-v11/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xxxhdpi/leak_canary_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xxxhdpi/leak_canary_icon.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable-xxxhdpi/leak_canary_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teffy/LeakcanarySample-Eclipse/10f59396a5a9e826b6090f8b483aef1a4ed3a52f/leakcanarylib/res/drawable-xxxhdpi/leak_canary_notification.png
--------------------------------------------------------------------------------
/leakcanarylib/res/drawable/leak_canary_toast_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/leakcanarylib/res/layout/leak_canary_display_leak.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
23 |
31 |
39 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/leakcanarylib/res/layout/leak_canary_heap_dump_toast.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
24 |
29 |
30 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/leakcanarylib/res/layout/leak_canary_leak_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
24 |
25 |
33 |
34 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/leakcanarylib/res/layout/leak_canary_ref_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
23 |
24 |
31 |
32 |
39 |
40 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/leakcanarylib/res/layout/leak_canary_ref_top_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
28 |
--------------------------------------------------------------------------------
/leakcanarylib/res/values-v14/leak_canary_themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
--------------------------------------------------------------------------------
/leakcanarylib/res/values-v21/leak_canary_themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
--------------------------------------------------------------------------------
/leakcanarylib/res/values/leak_canary_int.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | 7
19 |
--------------------------------------------------------------------------------
/leakcanarylib/res/values/leak_canary_strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | %s has leaked
20 | Ignored %s leak
21 | Leak analysis failed
22 | Leaks in %s
23 | Click to see previous leaks
24 | Click for more details
25 | Share info
26 | Share heap dump
27 | Share with…
28 | Leaks
29 | Dumping memory, app will freeze. Brrrr.
30 | Delete
31 | "Please report this failure to http://github.com/square/leakcanary\n"
32 | Delete all
33 |
34 |
--------------------------------------------------------------------------------
/leakcanarylib/res/values/leak_canary_themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/haha/perflib/HahaSpy.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.haha.perflib;
17 |
18 | public final class HahaSpy {
19 |
20 | public static Instance allocatingThread(Instance instance) {
21 | Snapshot snapshot = instance.mHeap.mSnapshot;
22 | int threadSerialNumber;
23 | if (instance instanceof RootObj) {
24 | threadSerialNumber = ((RootObj) instance).mThread;
25 | } else {
26 | threadSerialNumber = instance.mStack.mThreadSerialNumber;
27 | }
28 | ThreadObj thread = snapshot.getThread(threadSerialNumber);
29 | return snapshot.findInstance(thread.mId);
30 | }
31 |
32 | private HahaSpy() {
33 | throw new AssertionError();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/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/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/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/com/squareup/leakcanary/AndroidDebuggerControl.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.Debug;
19 |
20 | public final class AndroidDebuggerControl implements DebuggerControl {
21 | @Override public boolean isDebuggerAttached() {
22 | return Debug.isDebuggerConnected();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/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/CanaryLog.java:
--------------------------------------------------------------------------------
1 | package com.squareup.leakcanary;
2 |
3 | import android.util.Log;
4 |
5 | public final class CanaryLog {
6 |
7 | private static volatile Logger logger = new DefaultLogger();
8 |
9 | public interface Logger {
10 | void d(String message, Object... args);
11 |
12 | void d(Throwable throwable, String message, Object... args);
13 | }
14 |
15 | private static class DefaultLogger implements Logger {
16 |
17 | @Override public void d(String message, Object... args) {
18 | String formatted = String.format(message, args);
19 | if (formatted.length() < 4000) {
20 | Log.d("LeakCanary", formatted);
21 | } else {
22 | String[] lines = formatted.split("\n");
23 | for (String line : lines) {
24 | Log.d("LeakCanary", line);
25 | }
26 | }
27 | }
28 |
29 | @Override public void d(Throwable throwable, String message, Object... args) {
30 | d(String.format(message, args) + '\n' + Log.getStackTraceString(throwable));
31 | }
32 | }
33 |
34 | public static void setLogger(Logger logger) {
35 | CanaryLog.logger = logger;
36 | }
37 |
38 | public static void d(String message, Object... args) {
39 | // Local variable to prevent the ref from becoming null after the null check.
40 | Logger logger = CanaryLog.logger;
41 | if (logger == null) {
42 | return;
43 | }
44 | logger.d(message, args);
45 | }
46 |
47 | public static void d(Throwable throwable, String message, Object... args) {
48 | // Local variable to prevent the ref from becoming null after the null check.
49 | Logger logger = CanaryLog.logger;
50 | if (logger == null) {
51 | return;
52 | }
53 | logger.d(throwable, message, args);
54 | }
55 |
56 | private CanaryLog() {
57 | throw new AssertionError();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/DebuggerControl.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 | /**
19 | * Gives the opportunity to skip checking if a reference is gone when the debugger is connected.
20 | * An attached debugger might retain references and create false positives.
21 | */
22 | public interface DebuggerControl {
23 | DebuggerControl NONE = new DebuggerControl() {
24 | @Override public boolean isDebuggerAttached() {
25 | return false;
26 | }
27 | };
28 |
29 | boolean isDebuggerAttached();
30 | }
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/GcTrigger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 Google 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 | /**
19 | * Called when a watched reference is expected to be weakly reachable, but hasn't been enqueued
20 | * in the reference queue yet. This gives the application a hook to run the GC before the {@link
21 | * RefWatcher} checks the reference queue again, to avoid taking a heap dump if possible.
22 | */
23 | public interface GcTrigger {
24 | GcTrigger DEFAULT = new GcTrigger() {
25 | @Override public void runGc() {
26 | // Code taken from AOSP FinalizationTest:
27 | // https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/
28 | // java/lang/ref/FinalizationTester.java
29 | // System.gc() does not garbage collect every time. Runtime.gc() is
30 | // more likely to perfom a gc.
31 | Runtime.getRuntime().gc();
32 | enqueueReferences();
33 | System.runFinalization();
34 | }
35 |
36 | private void enqueueReferences() {
37 | // Hack. We don't have a programmatic way to wait for the reference queue daemon to move
38 | // references to the appropriate queues.
39 | try {
40 | Thread.sleep(100);
41 | } catch (InterruptedException e) {
42 | throw new AssertionError();
43 | }
44 | }
45 | };
46 |
47 | void runGc();
48 | }
--------------------------------------------------------------------------------
/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/com/squareup/leakcanary/HeapDumper.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 |
20 | public interface HeapDumper {
21 |
22 | File NO_DUMP = null;
23 |
24 | /**
25 | * @return a {@link File} referencing the heap dump, or {@link #NO_DUMP} if the heap could not be
26 | * dumped.
27 | */
28 | File dumpHeap();
29 | }
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/KeyedWeakReference.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.lang.ref.ReferenceQueue;
19 | import java.lang.ref.WeakReference;
20 |
21 | import static com.squareup.leakcanary.Preconditions.checkNotNull;
22 |
23 | /** @see {@link HeapDump#referenceKey}. */
24 | final class KeyedWeakReference extends WeakReference {
25 | public final String key;
26 | public final String name;
27 |
28 | KeyedWeakReference(Object referent, String key, String name,
29 | ReferenceQueue referenceQueue) {
30 | super(checkNotNull(referent, "referent"), checkNotNull(referenceQueue, "referenceQueue"));
31 | this.key = checkNotNull(key, "key");
32 | this.name = checkNotNull(name, "name");
33 | }
34 | }
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/LeakNode.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 com.squareup.haha.perflib.Instance;
19 |
20 | final class LeakNode {
21 | final Instance instance;
22 | final LeakNode parent;
23 | final String referenceName;
24 | final LeakTraceElement.Type referenceType;
25 |
26 | LeakNode(Instance instance, LeakNode parent, String referenceName,
27 | LeakTraceElement.Type referenceType) {
28 | this.instance = instance;
29 | this.parent = parent;
30 | this.referenceName = referenceName;
31 | this.referenceType = referenceType;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/LeakTrace.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 java.util.Collections.unmodifiableList;
23 |
24 | /**
25 | * A chain of references that constitute the shortest strong reference path from a leaking instance
26 | * to the GC roots. Fixing the leak usually means breaking one of the references in that chain.
27 | */
28 | public final class LeakTrace implements Serializable {
29 |
30 | public final List elements;
31 |
32 | LeakTrace(List elements) {
33 | this.elements = unmodifiableList(new ArrayList<>(elements));
34 | }
35 |
36 | @Override public String toString() {
37 | StringBuilder sb = new StringBuilder();
38 | for (int i = 0; i < elements.size(); i++) {
39 | LeakTraceElement element = elements.get(i);
40 | sb.append("* ");
41 | if (i == 0) {
42 | sb.append("GC ROOT ");
43 | } else if (i == elements.size() - 1) {
44 | sb.append("leaks ");
45 | } else {
46 | sb.append("references ");
47 | }
48 | sb.append(element).append("\n");
49 | }
50 | return sb.toString();
51 | }
52 |
53 | public String toDetailedString() {
54 | String string = "";
55 | for (LeakTraceElement element : elements) {
56 | string += element.toDetailedString();
57 | }
58 | return string;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/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/com/squareup/leakcanary/Preconditions.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 | final class Preconditions {
19 |
20 | /**
21 | * Returns instance unless it's null.
22 | *
23 | * @throws NullPointerException if instance is null
24 | */
25 | static T checkNotNull(T instance, String name) {
26 | if (instance == null) {
27 | throw new NullPointerException(name + " must not be null");
28 | }
29 | return instance;
30 | }
31 |
32 | private Preconditions() {
33 | throw new AssertionError();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/ServiceHeapDumpListener.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.content.Context;
19 | import com.squareup.leakcanary.internal.HeapAnalyzerService;
20 |
21 | import static com.squareup.leakcanary.Preconditions.checkNotNull;
22 | import static com.squareup.leakcanary.internal.LeakCanaryInternals.setEnabled;
23 |
24 | public final class ServiceHeapDumpListener implements HeapDump.Listener {
25 |
26 | private final Context context;
27 | private final Class extends AbstractAnalysisResultService> listenerServiceClass;
28 |
29 | public ServiceHeapDumpListener(Context context,
30 | Class extends AbstractAnalysisResultService> listenerServiceClass) {
31 | setEnabled(context, listenerServiceClass, true);
32 | setEnabled(context, HeapAnalyzerService.class, true);
33 | this.listenerServiceClass = checkNotNull(listenerServiceClass, "listenerServiceClass");
34 | this.context = checkNotNull(context, "context").getApplicationContext();
35 | }
36 |
37 | @Override public void analyze(HeapDump heapDump) {
38 | checkNotNull(heapDump, "heapDump");
39 | HeapAnalyzerService.runAnalysis(context, heapDump, listenerServiceClass);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/internal/FutureResult.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 java.util.concurrent.CountDownLatch;
19 | import java.util.concurrent.TimeUnit;
20 | import java.util.concurrent.atomic.AtomicReference;
21 |
22 | public final class FutureResult {
23 |
24 | private final AtomicReference resultHolder;
25 | private final CountDownLatch latch;
26 |
27 | public FutureResult() {
28 | resultHolder = new AtomicReference<>();
29 | latch = new CountDownLatch(1);
30 | }
31 |
32 | public boolean wait(long timeout, TimeUnit unit) {
33 | try {
34 | return latch.await(timeout, unit);
35 | } catch (InterruptedException e) {
36 | throw new RuntimeException("Did not expect thread to be interrupted", e);
37 | }
38 | }
39 |
40 | public T get() {
41 | if (latch.getCount() > 0) {
42 | throw new IllegalStateException("Call wait() and check its result");
43 | }
44 | return resultHolder.get();
45 | }
46 |
47 | public void set(T result) {
48 | resultHolder.set(result);
49 | latch.countDown();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/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/com/squareup/leakcanary/internal/LeakCanaryUi.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.res.Resources;
19 | import android.graphics.PorterDuffXfermode;
20 | import android.util.DisplayMetrics;
21 |
22 | import static android.graphics.PorterDuff.Mode.CLEAR;
23 |
24 | final class LeakCanaryUi {
25 | static final int LIGHT_GREY = 0xFFbababa;
26 | static final int ROOT_COLOR = 0xFF84a6c5;
27 | static final int LEAK_COLOR = 0xFFb1554e;
28 |
29 | static final PorterDuffXfermode CLEAR_XFER_MODE = new PorterDuffXfermode(CLEAR);
30 |
31 | /**
32 | * Converts from device independent pixels (dp or dip) to
33 | * device dependent pixels. This method returns the input
34 | * multiplied by the display's density. The result is not
35 | * rounded nor clamped.
36 | *
37 | * The value returned by this method is well suited for
38 | * drawing with the Canvas API but should not be used to
39 | * set layout dimensions.
40 | *
41 | * @param dp The value in dp to convert to pixels
42 | * @param resources An instances of Resources
43 | */
44 | static float dpToPixel(float dp, Resources resources) {
45 | DisplayMetrics metrics = resources.getDisplayMetrics();
46 | return metrics.density * dp;
47 | }
48 |
49 | private LeakCanaryUi() {
50 | throw new AssertionError();
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/leakcanarylib/src/com/squareup/leakcanary/internal/MoreDetailsView.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.Canvas;
20 | import android.graphics.Paint;
21 | import android.util.AttributeSet;
22 | import android.view.View;
23 |
24 | public final class MoreDetailsView extends View {
25 |
26 | private static final Paint iconPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
27 |
28 | static {
29 | iconPaint.setColor(LeakCanaryUi.ROOT_COLOR);
30 | }
31 |
32 | public MoreDetailsView(Context context, AttributeSet attrs) {
33 | super(context, attrs);
34 |
35 | float strokeSize = LeakCanaryUi.dpToPixel(2f, getResources());
36 | iconPaint.setStrokeWidth(strokeSize);
37 | }
38 |
39 | private boolean opened;
40 |
41 | @Override protected void onDraw(Canvas canvas) {
42 | int width = getWidth();
43 | int height = getHeight();
44 | int halfHeight = height / 2;
45 | int halfWidth = width / 2;
46 |
47 | if (opened) {
48 | canvas.drawLine(0, halfHeight, width, halfHeight, iconPaint);
49 | } else {
50 | canvas.drawLine(0, halfHeight, width, halfHeight, iconPaint);
51 | canvas.drawLine(halfWidth, 0, halfWidth, height, iconPaint);
52 | }
53 | }
54 |
55 | public void setOpened(boolean opened) {
56 | if (opened != this.opened) {
57 | this.opened = opened;
58 | invalidate();
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/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/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/collect/BitField.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.io.Serializable;
16 |
17 | /**
18 | * This class manages huge bit fields. It is much faster than
19 | * {@link java.util.BitSet} and was specifically developed to be used with huge
20 | * bit sets in ISnapshot (e.g. needed in virtual GC traces). Out of performance
21 | * reasons no method does any parameter checking, i.e. only valid values are
22 | * expected.
23 | */
24 | public final class BitField implements Serializable {
25 | private static final long serialVersionUID = 1L;
26 |
27 | private int[] bits;
28 |
29 | /**
30 | * Creates a bit field with the given number of bits. Size is expected to be
31 | * positive - out of performance reasons no checks are done!
32 | */
33 | public BitField(int size) {
34 | bits = new int[(((size) - 1) >>> 0x5) + 1];
35 | }
36 |
37 | /**
38 | * Sets the bit on the given index. Index is expected to be in range - out
39 | * of performance reasons no checks are done!
40 | */
41 | public final void set(int index) {
42 | bits[index >>> 0x5] |= (1 << (index & 0x1f));
43 | }
44 |
45 | /**
46 | * Clears the bit on the given index. Index is expected to be in range - out
47 | * of performance reasons no checks are done!
48 | */
49 | public final void clear(int index) {
50 | bits[index >>> 0x5] &= ~(1 << (index & 0x1f));
51 | }
52 |
53 | /**
54 | * Gets the bit on the given index. Index is expected to be in range - out
55 | * of performance reasons no checks are done!
56 | */
57 | public final boolean get(int index) {
58 | return (bits[index >>> 0x5] & (1 << (index & 0x1f))) != 0;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/collect/IteratorInt.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 | public interface IteratorInt {
16 | boolean hasNext();
17 |
18 | int next();
19 | }
20 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/collect/IteratorLong.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 | public interface IteratorLong {
16 | boolean hasNext();
17 |
18 | long next();
19 | }
20 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/collect/PrimeFinder.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 | /* package */class PrimeFinder {
16 | public static int findNextPrime(int floor) {
17 | boolean isPrime = false;
18 | while (!isPrime) {
19 | floor++;
20 | isPrime = true;
21 | int sqrt = (int) Math.sqrt(floor);
22 | for (int i = 2; i <= sqrt; i++) {
23 | if ((floor / i * i) == floor) {
24 | isPrime = false;
25 | }
26 | }
27 | }
28 | return floor;
29 | }
30 |
31 | public static int findPrevPrime(int ceil) {
32 | boolean isPrime = false;
33 | while (!isPrime) {
34 | ceil--;
35 | isPrime = true;
36 | int sqrt = (int) Math.sqrt(ceil);
37 | for (int i = 2; i <= sqrt; i++) {
38 | if ((ceil / i * i) == ceil) {
39 | isPrime = false;
40 | }
41 | }
42 | }
43 | return ceil;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/collect/QueueInt.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 |
14 | package org.eclipse.mat.collect;
15 |
16 | import org.eclipse.mat.hprof.Messages;
17 |
18 | /**
19 | * @since 0.8
20 | */
21 | public class QueueInt {
22 | int[] data;
23 | int headIdx;
24 | int tailIdx;
25 | int size;
26 | int capacity;
27 |
28 | public QueueInt(int capacity) {
29 | this.capacity = capacity;
30 | data = new int[capacity];
31 | }
32 |
33 | public final int get() {
34 |
35 | if (size == 0) {
36 | throw new ArrayIndexOutOfBoundsException(Messages.QueueInt_ZeroSizeQueue.pattern);
37 | }
38 | int result = data[headIdx];
39 | headIdx++;
40 | size--;
41 |
42 | if (headIdx == capacity) headIdx = 0;
43 |
44 | return result;
45 | }
46 |
47 | public final int size() {
48 | return size;
49 | }
50 |
51 | public final void put(int x) {
52 |
53 | if (tailIdx == capacity) tailIdx = 0;
54 |
55 | if (size == capacity) {
56 | // resize
57 | capacity <<= 1;
58 | int[] tmp = new int[capacity];
59 | int headToEnd = data.length - headIdx;
60 | System.arraycopy(data, headIdx, tmp, 0, headToEnd);
61 | if (tailIdx > 0) System.arraycopy(data, 0, tmp, headToEnd, tailIdx);
62 |
63 | headIdx = 0;
64 | tailIdx = data.length;
65 |
66 | data = tmp;
67 | }
68 |
69 | data[tailIdx] = x;
70 | size++;
71 | tailIdx++;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/hprof/ArrayDescription.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.lang.ref.SoftReference;
16 |
17 | /* package */class ArrayDescription {
18 | /* package */static class Offline extends ArrayDescription {
19 | boolean isPrimitive;
20 | long position;
21 | int arraySize;
22 | int elementSize;
23 |
24 | SoftReference lazyReadContent = new SoftReference(null);
25 |
26 | public Offline(boolean isPrimitive, long position, int elementSize, int arraySize) {
27 | this.isPrimitive = isPrimitive;
28 | this.position = position;
29 | this.elementSize = elementSize;
30 | this.arraySize = arraySize;
31 | }
32 |
33 | public boolean isPrimitive() {
34 | return isPrimitive;
35 | }
36 |
37 | public long getPosition() {
38 | return position;
39 | }
40 |
41 | public int getArraySize() {
42 | return arraySize;
43 | }
44 |
45 | public int getElementSize() {
46 | return elementSize;
47 | }
48 |
49 | public Object getLazyReadContent() {
50 | return lazyReadContent.get();
51 | }
52 |
53 | public void setLazyReadContent(Object content) {
54 | this.lazyReadContent = new SoftReference(content);
55 | }
56 | }
57 |
58 | /* package */static class Raw extends ArrayDescription {
59 | byte[] content;
60 |
61 | public Raw(byte[] content) {
62 | this.content = content;
63 | }
64 |
65 | public byte[] getContent() {
66 | return content;
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/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/hprof/extension/IParsingEnhancer.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.extension;
14 |
15 | import java.io.IOException;
16 |
17 | import org.eclipse.mat.SnapshotException;
18 | import org.eclipse.mat.snapshot.SnapshotInfo;
19 |
20 | public interface IParsingEnhancer {
21 | void onParsingCompleted(SnapshotInfo snapshotInfo) throws SnapshotException, IOException;
22 | }
23 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/hprof/extension/IRuntimeEnhancer.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.extension;
14 |
15 | import org.eclipse.mat.SnapshotException;
16 | import org.eclipse.mat.snapshot.ISnapshot;
17 |
18 | public interface IRuntimeEnhancer {
19 | A getAddon(ISnapshot snapshot, Class addon) throws SnapshotException;
20 | }
21 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/IIndexBuilder.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;
14 |
15 | import java.io.File;
16 | import java.io.IOException;
17 |
18 | import org.eclipse.mat.SnapshotException;
19 | import org.eclipse.mat.util.IProgressListener;
20 |
21 | public interface IIndexBuilder {
22 | /* initialize with file and prefix (needed for naming conventions) */
23 | void init(File file, String prefix) throws SnapshotException, IOException;
24 |
25 | /* hprof: pass1 and pass2 parsing */
26 | void fill(IPreliminaryIndex index, IProgressListener listener)
27 | throws SnapshotException, IOException;
28 |
29 | /* hprof: update object 2 file position index */
30 | void clean(final int[] purgedMapping, IProgressListener listener) throws IOException;
31 |
32 | /* called in case of error to delete any files / close any file handles */
33 | void cancel();
34 | }
35 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/IObjectReader.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;
14 |
15 | import java.io.IOException;
16 |
17 | import org.eclipse.mat.SnapshotException;
18 | import org.eclipse.mat.parser.model.ObjectArrayImpl;
19 | import org.eclipse.mat.parser.model.PrimitiveArrayImpl;
20 | import org.eclipse.mat.snapshot.ISnapshot;
21 | import org.eclipse.mat.snapshot.model.IObject;
22 |
23 | public interface IObjectReader {
24 | void open(ISnapshot snapshot) //
25 | throws SnapshotException, IOException;
26 |
27 | IObject read(int objectId, ISnapshot snapshot) //
28 | throws SnapshotException, IOException;
29 |
30 | Object readPrimitiveArrayContent(PrimitiveArrayImpl array, int offset, int length) //
31 | throws IOException, SnapshotException;
32 |
33 | long[] readObjectArrayContent(ObjectArrayImpl array, int offset, int length) //
34 | throws IOException, SnapshotException;
35 |
36 | A getAddon(Class addon) //
37 | throws SnapshotException;
38 |
39 | void close() throws IOException;
40 | }
41 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/IPreliminaryIndex.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;
14 |
15 | import java.util.List;
16 |
17 | import org.eclipse.mat.collect.HashMapIntObject;
18 | import org.eclipse.mat.parser.index.IIndexReader;
19 | import org.eclipse.mat.parser.model.ClassImpl;
20 | import org.eclipse.mat.parser.model.XGCRootInfo;
21 | import org.eclipse.mat.parser.model.XSnapshotInfo;
22 |
23 | /**
24 | * @noimplement
25 | */
26 | public interface IPreliminaryIndex {
27 | XSnapshotInfo getSnapshotInfo();
28 |
29 | void setClassesById(HashMapIntObject classesById);
30 |
31 | void setGcRoots(HashMapIntObject> gcRoots);
32 |
33 | void setThread2objects2roots(
34 | HashMapIntObject>> thread2objects2roots);
35 |
36 | void setOutbound(IIndexReader.IOne2ManyIndex outbound);
37 |
38 | void setIdentifiers(IIndexReader.IOne2LongIndex identifiers);
39 |
40 | void setObject2classId(IIndexReader.IOne2OneIndex object2classId);
41 |
42 | void setArray2size(IIndexReader.IOne2OneIndex array2size);
43 | }
44 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/index/IIndexReader.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.index;
14 |
15 | import java.io.IOException;
16 | import java.io.Serializable;
17 |
18 | import org.eclipse.mat.SnapshotException;
19 |
20 | public interface IIndexReader {
21 | public interface IOne2OneIndex extends IIndexReader {
22 | int get(int index);
23 |
24 | int[] getAll(int index[]);
25 |
26 | int[] getNext(int index, int length);
27 | }
28 |
29 | public interface IOne2LongIndex extends IIndexReader {
30 | long get(int index);
31 |
32 | int reverse(long value);
33 |
34 | long[] getNext(int index, int length);
35 | }
36 |
37 | public interface IOne2ManyIndex extends IIndexReader {
38 | int[] get(int index);
39 | }
40 |
41 | public interface IOne2ManyObjectsIndex extends IOne2ManyIndex {
42 | int[] getObjectsOf(Serializable key) throws SnapshotException, IOException;
43 | }
44 |
45 | int size();
46 |
47 | void unload() throws IOException;
48 |
49 | void close() throws IOException;
50 |
51 | void delete();
52 | }
53 |
--------------------------------------------------------------------------------
/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/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/org/eclipse/mat/parser/internal/StackFrameImpl.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 org.eclipse.mat.snapshot.model.IStackFrame;
16 |
17 | /**
18 | * @noextend This class is not intended to be subclassed by clients. May still
19 | * be subject of change
20 | */
21 | class StackFrameImpl implements IStackFrame {
22 | private String text;
23 |
24 | private int[] localObjectIds;
25 |
26 | public StackFrameImpl(String text, int[] localObjectIds) {
27 | this.text = text;
28 | this.localObjectIds = localObjectIds;
29 | }
30 |
31 | public int[] getLocalObjectsIds() {
32 | return localObjectIds == null ? new int[0] : localObjectIds;
33 | }
34 |
35 | public String getText() {
36 | return text;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/internal/ThreadStackImpl.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 org.eclipse.mat.snapshot.model.IStackFrame;
16 | import org.eclipse.mat.snapshot.model.IThreadStack;
17 |
18 | /**
19 | * @noextend This class is not intended to be subclassed by clients. May still
20 | * be subject of change
21 | */
22 | class ThreadStackImpl implements IThreadStack {
23 | private int threadId;
24 | private IStackFrame[] stackFrames;
25 |
26 | public ThreadStackImpl(int threadId, StackFrameImpl[] stackFrames) {
27 | this.threadId = threadId;
28 | this.stackFrames = stackFrames;
29 | }
30 |
31 | public IStackFrame[] getStackFrames() {
32 | return stackFrames;
33 | }
34 |
35 | public int getThreadId() {
36 | return threadId;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/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/parser/internal/snapshot/PathsFromGCRootsTreeBuilder.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.HashMap;
17 | import java.util.Map;
18 |
19 | import org.eclipse.mat.snapshot.PathsFromGCRootsTree;
20 |
21 | public class PathsFromGCRootsTreeBuilder {
22 | private int ownId;
23 | private ArrayList objectIds = new ArrayList();
24 | private HashMap objectInboundReferers;
25 |
26 | public PathsFromGCRootsTreeBuilder(int ownId) {
27 | this.ownId = ownId;
28 | objectInboundReferers = new HashMap();
29 | }
30 |
31 | public HashMap getObjectReferers() {
32 | return objectInboundReferers;
33 | }
34 |
35 | public PathsFromGCRootsTree toPathsFromGCRootsTree() {
36 | HashMap data =
37 | new HashMap(objectInboundReferers.size());
38 | for (Map.Entry 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/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/internal/util/IntStack.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 | public class IntStack {
16 | private int[] data;
17 | private int size;
18 |
19 | public IntStack() {
20 | this(16);
21 | }
22 |
23 | public IntStack(int capacity) {
24 | data = new int[capacity];
25 | }
26 |
27 | public final int pop() {
28 | return data[--size];
29 | }
30 |
31 | public final void push(int i) {
32 | if (size == data.length) {
33 | int[] newArr = new int[data.length << 1];
34 | System.arraycopy(data, 0, newArr, 0, data.length);
35 | data = newArr;
36 | }
37 | data[size++] = i;
38 | }
39 |
40 | public final int peek() {
41 | return data[size - 1];
42 | }
43 |
44 | public final int size() {
45 | return size;
46 | }
47 |
48 | public final int capacity() {
49 | return data.length;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/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/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/org/eclipse/mat/parser/model/AbstractArrayImpl.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 org.eclipse.mat.snapshot.model.IArray;
16 |
17 | /**
18 | * @noextend
19 | */
20 | public abstract class AbstractArrayImpl extends AbstractObjectImpl implements IArray {
21 | private static final long serialVersionUID = 2L;
22 |
23 | protected int length;
24 |
25 | private Object info;
26 |
27 | public AbstractArrayImpl(int objectId, long address, ClassImpl classInstance, int length) {
28 | super(objectId, address, classInstance);
29 | this.length = length;
30 | }
31 |
32 | public Object getInfo() {
33 | return info;
34 | }
35 |
36 | public void setInfo(Object content) {
37 | this.info = content;
38 | }
39 |
40 | public int getLength() {
41 | return length;
42 | }
43 |
44 | public void setLength(int i) {
45 | length = i;
46 | }
47 |
48 | protected StringBuffer appendFields(StringBuffer buf) {
49 | return super.appendFields(buf).append(";length=").append(length);//$NON-NLS-1$
50 | }
51 |
52 | public String getTechnicalName() {
53 | StringBuilder builder = new StringBuilder(256);
54 | String name = getClazz().getName();
55 |
56 | int p = name.indexOf('[');
57 | if (p < 0) {
58 | builder.append(name);
59 | } else {
60 | builder.append(name.subSequence(0, p + 1)).append(getLength()).append(name.substring(p + 1));
61 | }
62 |
63 | builder.append(" @ 0x");//$NON-NLS-1$
64 | builder.append(Long.toHexString(getObjectAddress()));
65 | return builder.toString();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/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/parser/model/XGCRootInfo.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 org.eclipse.mat.snapshot.model.GCRootInfo;
16 |
17 | public final class XGCRootInfo extends GCRootInfo {
18 | private static final long serialVersionUID = 1L;
19 |
20 | public XGCRootInfo(long objectAddress, long contextAddress, int type) {
21 | super(objectAddress, contextAddress, type);
22 | }
23 |
24 | public void setObjectId(int objectId) {
25 | this.objectId = objectId;
26 | }
27 |
28 | public void setContextId(int objectId) {
29 | this.contextId = objectId;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/parser/model/XSnapshotInfo.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.util.Date;
16 |
17 | import org.eclipse.mat.snapshot.SnapshotInfo;
18 |
19 | public final class XSnapshotInfo extends SnapshotInfo {
20 | private static final long serialVersionUID = 3L;
21 |
22 | public XSnapshotInfo() {
23 | super(null, null, null, 0, null, 0, 0, 0, 0, 0);
24 | }
25 |
26 | public void setPrefix(String prefix) {
27 | this.prefix = prefix;
28 | }
29 |
30 | public void setPath(String path) {
31 | this.path = path;
32 | }
33 |
34 | public void setCreationDate(Date creationDate) {
35 | this.creationDate = new Date(creationDate.getTime());
36 | }
37 |
38 | public void setIdentifierSize(int identifierSize) {
39 | this.identifierSize = identifierSize;
40 | }
41 |
42 | public void setJvmInfo(String jvmInfo) {
43 | this.jvmInfo = jvmInfo;
44 | }
45 |
46 | public void setNumberOfClasses(int numberOfClasses) {
47 | this.numberOfClasses = numberOfClasses;
48 | }
49 |
50 | public void setNumberOfClassLoaders(int numberOfClassLoaders) {
51 | this.numberOfClassLoaders = numberOfClassLoaders;
52 | }
53 |
54 | public void setNumberOfGCRoots(int numberOfGCRoots) {
55 | this.numberOfGCRoots = numberOfGCRoots;
56 | }
57 |
58 | public void setNumberOfObjects(int numberOfObjects) {
59 | this.numberOfObjects = numberOfObjects;
60 | }
61 |
62 | public void setUsedHeapSize(long usedHeapSize) {
63 | this.usedHeapSize = usedHeapSize;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/ExcludedReferencesDescriptor.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.Arrays;
16 | import java.util.HashSet;
17 | import java.util.Set;
18 |
19 | public final class ExcludedReferencesDescriptor {
20 | private int[] objectIds;
21 | private Set fields;
22 |
23 | public ExcludedReferencesDescriptor(int[] objectIds, Set fields) {
24 | this.fields = fields;
25 | this.objectIds = objectIds;
26 | Arrays.sort(this.objectIds);
27 | }
28 |
29 | public ExcludedReferencesDescriptor(int[] objectIds, String... fields) {
30 | this(objectIds, new HashSet(Arrays.asList(fields)));
31 | }
32 |
33 | public Set getFields() {
34 | return fields;
35 | }
36 |
37 | public boolean contains(int objectId) {
38 | return Arrays.binarySearch(objectIds, objectId) >= 0;
39 | }
40 |
41 | public int[] getObjectIds() {
42 | return objectIds;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/IMultiplePathsFromGCRootsComputer.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 org.eclipse.mat.SnapshotException;
16 | import org.eclipse.mat.util.IProgressListener;
17 |
18 | /**
19 | * Objects of this type can be used to work with paths to many objects
20 | *
21 | * @noimplement
22 | */
23 | public interface IMultiplePathsFromGCRootsComputer {
24 | /**
25 | * Calculates (if not yet calculated) and returns all the paths. The paths
26 | * are grouped by the GC root object, i.e. all paths starting from one and
27 | * the same GC root will be packed in one MultiplePathsFromGCRootsRecord.
28 | * This record can be used to get the objects at the next level in the path,
29 | * etc...
30 | *
31 | * @param progressListener - used to track the progress of the computation
32 | * @return MultiplePathsFromGCRootsRecord[] one record for each group of
33 | * paths starting from the same GC root
34 | * @throws SnapshotException
35 | */
36 | public MultiplePathsFromGCRootsRecord[] getPathsByGCRoot(IProgressListener progressListener)
37 | throws SnapshotException;
38 |
39 | /**
40 | * Calculates (if not yet calculated) and returns all the paths. Each
41 | * element in the Object[] is an int[] representing the path. The first
42 | * element in the int[] is the specified object, and the last is the GC root
43 | * object
44 | *
45 | * @param progressListener - used to track the progress of the computation
46 | * @return Object[] - each element in the array is an int[] representing a
47 | * path
48 | * @throws SnapshotException
49 | */
50 | public Object[] getAllPaths(IProgressListener progressListener) throws SnapshotException;
51 | }
52 |
--------------------------------------------------------------------------------
/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/org/eclipse/mat/snapshot/PathsFromGCRootsTree.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.HashMap;
16 |
17 | /**
18 | * This class holds the paths from one single object to its GC roots.
19 | *
20 | * @noinstantiate
21 | */
22 | public final class PathsFromGCRootsTree {
23 | private int ownId;
24 | private int[] objectIds;
25 | private HashMap objectInboundReferers;
26 |
27 | public PathsFromGCRootsTree(int ownId,
28 | HashMap objectInboundReferers, int[] objectIds) {
29 | this.ownId = ownId;
30 | this.objectInboundReferers = objectInboundReferers;
31 | this.objectIds = objectIds;
32 | }
33 |
34 | /**
35 | * Get object being the root for this tree.
36 | *
37 | * @return object being the root for this tree
38 | */
39 | public int getOwnId() {
40 | return ownId;
41 | }
42 |
43 | /**
44 | * Get referencing objects.
45 | *
46 | * @return referencing objects
47 | */
48 | public int[] getObjectIds() {
49 | return objectIds;
50 | }
51 |
52 | /**
53 | * Get sub tree for a referencing object.
54 | *
55 | * @param objId referencing object from which on the sub tree is requested
56 | * @return sub tree for a referencing object
57 | */
58 | public PathsFromGCRootsTree getBranch(int objId) {
59 | return objectInboundReferers.get(objId);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/SnapshotFormat.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 | /**
16 | * @noinstantiate
17 | */
18 | public class SnapshotFormat {
19 | private String name;
20 | private String[] fileExtensions;
21 |
22 | public SnapshotFormat(String name, String[] fileExtensions) {
23 | this.fileExtensions = fileExtensions;
24 | this.name = name;
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 |
31 | public String[] getFileExtensions() {
32 | return fileExtensions;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/extension/IClassSpecificNameResolver.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.extension;
14 |
15 | import org.eclipse.mat.SnapshotException;
16 | import org.eclipse.mat.snapshot.model.IObject;
17 |
18 | /**
19 | * Interface describing a name resolver for objects of specific classes (found
20 | * in an snapshot), e.g. String (where the char[] is evaluated) or as specific
21 | * class loader (where the appropriate field holding its name and thereby
22 | * deployment unit is evaluated). Objects of this interface need to be
23 | * registered with the nameResolver
extension point.
24 | */
25 | public interface IClassSpecificNameResolver {
26 | /**
27 | * Resolve the name for snapshot object.
28 | *
29 | * @param object object for which the name should be resolved
30 | * @return name for snapshot object
31 | * @throws SnapshotException
32 | */
33 | public String resolve(IObject object) throws SnapshotException;
34 | }
35 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/extension/Subject.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.extension;
14 |
15 | import static java.lang.annotation.ElementType.TYPE;
16 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
17 |
18 | import java.lang.annotation.Retention;
19 | import java.lang.annotation.Target;
20 |
21 | @Target({ TYPE }) @Retention(RUNTIME) public @interface Subject {
22 | String value();
23 | }
24 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/extension/Subjects.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.extension;
14 |
15 | import static java.lang.annotation.ElementType.TYPE;
16 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
17 |
18 | import java.lang.annotation.Retention;
19 | import java.lang.annotation.Target;
20 |
21 | @Target({ TYPE }) @Retention(RUNTIME) public @interface Subjects {
22 | String[] value();
23 | }
24 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/Field.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.io.Serializable;
16 |
17 | /**
18 | * Describes a member variable, i.e. name, signature and value.
19 | */
20 | public final class Field extends FieldDescriptor implements Serializable {
21 | private static final long serialVersionUID = 2L;
22 |
23 | protected Object value;
24 |
25 | public Field(String name, int type, Object value) {
26 | super(name, type);
27 | this.value = value;
28 | }
29 |
30 | public Object getValue() {
31 | return value;
32 | }
33 |
34 | public void setValue(Object object) {
35 | value = object;
36 | }
37 |
38 | public String toString() {
39 | return type + " " + name + ": \t" + value; //$NON-NLS-1$//$NON-NLS-2$
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/FieldDescriptor.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.io.Serializable;
16 |
17 | /**
18 | * Describes a field of an object, i.e. its name and signature.
19 | */
20 | public class FieldDescriptor implements Serializable {
21 | private static final long serialVersionUID = 2L;
22 |
23 | protected String name;
24 | protected int type;
25 |
26 | public FieldDescriptor(String name, int type) {
27 | this.name = name;
28 | this.type = type;
29 | }
30 |
31 | public String getName() {
32 | return name;
33 | }
34 |
35 | public int getType() {
36 | return type;
37 | }
38 |
39 | public void setName(String name) {
40 | this.name = name;
41 | }
42 |
43 | public void setType(int type) {
44 | this.type = type;
45 | }
46 |
47 | public String getVerboseSignature() {
48 | if (type == IObject.Type.OBJECT) return "ref"; //$NON-NLS-1$
49 |
50 | String t = IPrimitiveArray.TYPE[type];
51 | return t.substring(0, t.length() - 2);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/IArray.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 an array object in the heap dump.
17 | *
18 | * @noimplement
19 | */
20 | public interface IArray extends IObject {
21 | /**
22 | * Returns the length of the object.
23 | */
24 | public int getLength();
25 | }
26 |
--------------------------------------------------------------------------------
/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/org/eclipse/mat/snapshot/model/IClassLoader.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 | * An interface for class loader.
22 | *
23 | * @noimplement
24 | */
25 | public interface IClassLoader extends IInstance {
26 | /**
27 | * Returns the retained size of all objects and classes loaded by this class
28 | * loader.
29 | */
30 | long getRetainedHeapSizeOfObjects(boolean calculateIfNotAvailable,
31 | boolean calculateMinRetainedSize, IProgressListener listener) throws SnapshotException;
32 |
33 | /**
34 | * Returns the classes defined by this class loader instance.
35 | */
36 | List getDefinedClasses() throws SnapshotException;
37 | }
38 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/IInstance.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 | /**
18 | * Interface for a plain vanilla object instance in the heap dump.
19 | *
20 | * @noimplement
21 | */
22 | public interface IInstance extends IObject {
23 | /**
24 | * Returns all fields of the object.
25 | *
26 | * Fields are ordered in such a way, that first fields defined in the
27 | * current class and then fields of the super class and its super classes
28 | * are returned. This order is important to know, if a class declares a
29 | * field by the same name as the class it inherits from.
30 | */
31 | public List getFields();
32 |
33 | /**
34 | * Returns the field identified by the name.
35 | *
36 | * If declares a member variable by the same name as the parent class does,
37 | * then the result of this method is undefined.
38 | */
39 | public Field getField(String name);
40 | }
41 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/IObjectArray.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 | * Marker interface to represent object arrays in the heap dump.
17 | *
18 | * @noimplement
19 | */
20 | public interface IObjectArray extends IArray {
21 | /**
22 | * Get an array with the object addresses. 0 indicate null
23 | * values in the array.
24 | */
25 | long[] getReferenceArray();
26 |
27 | /**
28 | * Get an array with the object addresses, beginning at offset
29 | * and length
number of elements.
30 | */
31 | long[] getReferenceArray(int offset, int length);
32 | }
33 |
--------------------------------------------------------------------------------
/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/snapshot/model/IStackFrame.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 | * May be subject of change
17 | *
18 | * @noimplement
19 | * @since 0.8
20 | */
21 | public interface IStackFrame {
22 |
23 | /**
24 | * Returns the object IDs of all objects referenced from this stack frame -
25 | * both Java and JNI local objects
26 | *
27 | * @return int[] and array containing the object Ids. If there are no local
28 | * objects to the frame, and empty array will be returned
29 | */
30 | public int[] getLocalObjectsIds();
31 |
32 | /**
33 | * Get the text representation of the stack frame
34 | *
35 | * @return java.lang.String the text representation of the stack fame - class and method
36 | */
37 | public String getText();
38 | }
39 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/IThreadStack.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 | * May be subject of change
17 | *
18 | * @noimplement
19 | * @since 0.8
20 | */
21 | public interface IThreadStack {
22 |
23 | /**
24 | * Get the stack frames (i.e. the different method calls) of the thread
25 | * stack
26 | *
27 | * @return {@link IStackFrame}[] an array containing all stack frames. The
28 | * first element of the array contains the top of the stack, and the
29 | * last element the bottom of the stack
30 | */
31 | public IStackFrame[] getStackFrames();
32 |
33 | /**
34 | * Get the ID of the thread to which this stack belongs
35 | *
36 | * @return the object ID of the thread owning this stack
37 | */
38 | public int getThreadId();
39 | }
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/NamedReference.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.snapshot.ISnapshot;
16 |
17 | /**
18 | * A named reference.
19 | */
20 | public class NamedReference extends ObjectReference {
21 | private static final long serialVersionUID = 1L;
22 |
23 | private String name;
24 |
25 | public NamedReference(ISnapshot snapshot, long address, String name) {
26 | super(snapshot, address);
27 | this.name = name;
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/ObjectReference.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.io.Serializable;
16 |
17 | import org.eclipse.mat.SnapshotException;
18 | import org.eclipse.mat.snapshot.ISnapshot;
19 |
20 | /**
21 | * The value of a field if it is an object reference.
22 | */
23 | public class ObjectReference implements Serializable {
24 | private static final long serialVersionUID = 1L;
25 |
26 | private transient ISnapshot snapshot;
27 | private long address;
28 |
29 | public ObjectReference(ISnapshot snapshot, long address) {
30 | this.snapshot = snapshot;
31 | this.address = address;
32 | }
33 |
34 | public long getObjectAddress() {
35 | return address;
36 | }
37 |
38 | public int getObjectId() throws SnapshotException {
39 | return snapshot.mapAddressToId(address);
40 | }
41 |
42 | public IObject getObject() throws SnapshotException {
43 | return snapshot.getObject(getObjectId());
44 | }
45 |
46 | public String toString() {
47 | return "0x" + Long.toHexString(address); //$NON-NLS-1$
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/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/org/eclipse/mat/snapshot/model/PseudoReference.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.snapshot.ISnapshot;
16 |
17 | /**
18 | * Value of a field if it is a pseudo references. Some references do not
19 | * actually exist in the heap dump but are automatically generated because they
20 | * are maintained by the JVM. Examples are the link from an instance to the
21 | * class and from the class to the class loader.
22 | */
23 | public class PseudoReference extends NamedReference {
24 | private static final long serialVersionUID = 1L;
25 |
26 | public PseudoReference(ISnapshot snapshot, long address, String name) {
27 | super(snapshot, address, name);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/snapshot/model/ThreadToLocalReference.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.snapshot.ISnapshot;
16 |
17 | /**
18 | * The class represents a references from a running thread object to objects
19 | * which are local for this thread. Such objects could be for example java local
20 | * variables, objects used for synchronization in this thread, etc...
21 | */
22 | public class ThreadToLocalReference extends PseudoReference {
23 | private static final long serialVersionUID = 1L;
24 | private int localObjectId;
25 | private GCRootInfo[] gcRootInfo;
26 |
27 | public ThreadToLocalReference(ISnapshot snapshot, long address, String name, int localObjectId,
28 | GCRootInfo[] gcRootInfo) {
29 | super(snapshot, address, name);
30 | this.localObjectId = localObjectId;
31 | this.gcRootInfo = gcRootInfo;
32 | }
33 |
34 | public int getObjectId() {
35 | return localObjectId;
36 | }
37 |
38 | public GCRootInfo[] getGcRootInfo() {
39 | return gcRootInfo;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/util/MessageUtil.java:
--------------------------------------------------------------------------------
1 | package org.eclipse.mat.util;
2 |
3 | import java.text.MessageFormat;
4 |
5 | import org.eclipse.mat.hprof.Messages;
6 |
7 | public final class MessageUtil {
8 |
9 | public static String format(Messages message, Object... objects) {
10 | if (objects.length == 0) {
11 | return message.pattern;
12 | }
13 | return MessageFormat.format(message.pattern, objects);
14 | }
15 |
16 | private MessageUtil() {
17 | throw new AssertionError();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/leakcanarylib/src/org/eclipse/mat/util/SilentProgressListener.java:
--------------------------------------------------------------------------------
1 | /**
2 | * ****************************************************************************
3 | * Copyright (c) 2009 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 | * @since 0.8
19 | */
20 | public class SilentProgressListener implements IProgressListener {
21 | IProgressListener delegate;
22 |
23 | public SilentProgressListener(IProgressListener delegate) {
24 | this.delegate = delegate;
25 | }
26 |
27 | public void beginTask(String name, int totalWork) {
28 | }
29 |
30 | public final void beginTask(Messages name, int totalWork) {
31 | beginTask(name.pattern, totalWork);
32 | }
33 |
34 | public void done() {
35 | }
36 |
37 | public boolean isCanceled() {
38 | return delegate.isCanceled();
39 | }
40 |
41 | public void sendUserMessage(Severity severity, String message, Throwable exception) {
42 | delegate.sendUserMessage(severity, message, exception);
43 | }
44 |
45 | public void setCanceled(boolean value) {
46 | delegate.setCanceled(value);
47 | }
48 |
49 | public void subTask(String name) {
50 | }
51 |
52 | public void worked(int work) {
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/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/util/SimpleStringTokenizer.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 java.util.ArrayList;
16 | import java.util.Iterator;
17 | import java.util.List;
18 | import java.util.NoSuchElementException;
19 |
20 | public final class SimpleStringTokenizer implements Iterable {
21 | private String subject;
22 | private char delim;
23 |
24 | public SimpleStringTokenizer(String subject, char delim) {
25 | this.subject = subject;
26 | this.delim = delim;
27 | }
28 |
29 | public Iterator iterator() {
30 | return new Iterator() {
31 | int position = 0;
32 | int maxPosition = subject.length();
33 |
34 | public boolean hasNext() {
35 | return position < maxPosition;
36 | }
37 |
38 | public String next() {
39 | if (position >= maxPosition) throw new NoSuchElementException();
40 |
41 | String answer;
42 |
43 | int p = subject.indexOf(delim, position);
44 |
45 | if (p < 0) {
46 | answer = subject.substring(position);
47 | position = maxPosition;
48 | return answer;
49 | } else {
50 | answer = subject.substring(position, p);
51 | position = p + 1;
52 | }
53 |
54 | return answer;
55 | }
56 |
57 | public void remove() {
58 | throw new UnsupportedOperationException();
59 | }
60 | };
61 | }
62 |
63 | public static String[] split(String subject, char delim) {
64 | List answer = new ArrayList();
65 | for (String s : new SimpleStringTokenizer(subject, delim))
66 | answer.add(s.trim());
67 | return answer.toArray(new String[0]);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------