aboutsummaryrefslogtreecommitdiffstats
path: root/ddms/libs/ddmlib/src/com/android/ddmlib/NativeAllocationInfo.java
blob: 6730c8ccd36d8b8fa808829e22d8b9f3f1cabbed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ddmlib;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Stores native allocation information.
 * <p/>Contains number of allocations, their size and the stack trace.
 * <p/>Note: the ddmlib does not resolve the stack trace automatically. While this class provides
 * storage for resolved stack trace, this is merely for convenience.
 */
public final class NativeAllocationInfo {
    /* constants for flag bits */
    private static final int FLAG_ZYGOTE_CHILD  = (1<<31);
    private static final int FLAG_MASK          = (FLAG_ZYGOTE_CHILD);

    /** Libraries whose methods will be assumed to be not part of the user code. */
    private static final List<String> FILTERED_LIBRARIES = Arrays.asList(new String[] {
            "libc.so",
            "libc_malloc_debug_leak.so",
    });

    /** Method names that should be assumed to be not part of the user code. */
    private static final List<Pattern> FILTERED_METHOD_NAME_PATTERNS = Arrays.asList(new Pattern[] {
            Pattern.compile("malloc", Pattern.CASE_INSENSITIVE),
            Pattern.compile("calloc", Pattern.CASE_INSENSITIVE),
            Pattern.compile("realloc", Pattern.CASE_INSENSITIVE),
            Pattern.compile("operator new", Pattern.CASE_INSENSITIVE),
            Pattern.compile("memalign", Pattern.CASE_INSENSITIVE),
    });

    private final int mSize;

    private final boolean mIsZygoteChild;

    private final int mAllocations;

    private final ArrayList<Long> mStackCallAddresses = new ArrayList<Long>();

    private ArrayList<NativeStackCallInfo> mResolvedStackCall = null;

    private boolean mIsStackCallResolved = false;

    /**
     * Constructs a new {@link NativeAllocationInfo}.
     * @param size The size of the allocations.
     * @param allocations the allocation count
     */
    NativeAllocationInfo(int size, int allocations) {
        this.mSize = size & ~FLAG_MASK;
        this.mIsZygoteChild = ((size & FLAG_ZYGOTE_CHILD) != 0);
        this.mAllocations = allocations;
    }

    /**
     * Adds a stack call address for this allocation.
     * @param address The address to add.
     */
    void addStackCallAddress(long address) {
        mStackCallAddresses.add(address);
    }

    /**
     * Returns the total size of this allocation.
     */
    public int getSize() {
        return mSize;
    }

    /**
     * Returns whether the allocation happened in a child of the zygote
     * process.
     */
    public boolean isZygoteChild() {
        return mIsZygoteChild;
    }

    /**
     * Returns the allocation count.
     */
    public int getAllocationCount() {
        return mAllocations;
    }

    /**
     * Returns whether the stack call addresses have been resolved into
     * {@link NativeStackCallInfo} objects.
     */
    public boolean isStackCallResolved() {
        return mIsStackCallResolved;
    }

    /**
     * Returns the stack call of this allocation as raw addresses.
     * @return the list of addresses where the allocation happened.
     */
    public List<Long> getStackCallAddresses() {
        return mStackCallAddresses;
    }

    /**
     * Sets the resolved stack call for this allocation.
     * <p/>
     * If <code>resolvedStackCall</code> is non <code>null</code> then
     * {@link #isStackCallResolved()} will return <code>true</code> after this call.
     * @param resolvedStackCall The list of {@link NativeStackCallInfo}.
     */
    public synchronized void setResolvedStackCall(List<NativeStackCallInfo> resolvedStackCall) {
        if (mResolvedStackCall == null) {
            mResolvedStackCall = new ArrayList<NativeStackCallInfo>();
        } else {
            mResolvedStackCall.clear();
        }
        mResolvedStackCall.addAll(resolvedStackCall);
        mIsStackCallResolved = mResolvedStackCall.size() != 0;
    }

    /**
     * Returns the resolved stack call.
     * @return An array of {@link NativeStackCallInfo} or <code>null</code> if the stack call
     * was not resolved.
     * @see #setResolvedStackCall(ArrayList)
     * @see #isStackCallResolved()
     */
    public synchronized List<NativeStackCallInfo> getResolvedStackCall() {
        if (mIsStackCallResolved) {
            return mResolvedStackCall;
        }

        return null;
    }

    /**
     * Indicates whether some other object is "equal to" this one.
     * @param obj the reference object with which to compare.
     * @return <code>true</code> if this object is equal to the obj argument;
     * <code>false</code> otherwise.
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (obj instanceof NativeAllocationInfo) {
            NativeAllocationInfo mi = (NativeAllocationInfo)obj;
            // quick compare of size, alloc, and stackcall size
            if (mSize != mi.mSize || mAllocations != mi.mAllocations ||
                    mStackCallAddresses.size() != mi.mStackCallAddresses.size()) {
                return false;
            }
            // compare the stack addresses
            int count = mStackCallAddresses.size();
            for (int i = 0 ; i < count ; i++) {
                long a = mStackCallAddresses.get(i);
                long b = mi.mStackCallAddresses.get(i);
                if (a != b) {
                    return false;
                }
            }

            return true;
        }
        return false;
    }


    @Override
    public int hashCode() {
        // Follow Effective Java's recipe re hash codes.
        // Includes all the fields looked at by equals().

        int result = 17;    // arbitrary starting point

        result = 31 * result + mSize;
        result = 31 * result + mAllocations;
        result = 31 * result + mStackCallAddresses.size();

        for (long addr : mStackCallAddresses) {
            result = 31 * result + (int) (addr ^ (addr >>> 32));
        }

        return result;
    }

    /**
     * Returns a string representation of the object.
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Allocations: ");
        buffer.append(mAllocations);
        buffer.append("\n"); //$NON-NLS-1$

        buffer.append("Size: ");
        buffer.append(mSize);
        buffer.append("\n"); //$NON-NLS-1$

        buffer.append("Total Size: ");
        buffer.append(mSize * mAllocations);
        buffer.append("\n"); //$NON-NLS-1$

        Iterator<Long> addrIterator = mStackCallAddresses.iterator();

        if (mResolvedStackCall == null) {
            return buffer.toString();
        }

        Iterator<NativeStackCallInfo> sourceIterator = mResolvedStackCall.iterator();

        while (sourceIterator.hasNext()) {
            long addr = addrIterator.next();
            NativeStackCallInfo source = sourceIterator.next();
            if (addr == 0)
                continue;

            if (source.getLineNumber() != -1) {
                buffer.append(String.format("\t%1$08x\t%2$s --- %3$s --- %4$s:%5$d\n", addr,
                        source.getLibraryName(), source.getMethodName(),
                        source.getSourceFile(), source.getLineNumber()));
            } else {
                buffer.append(String.format("\t%1$08x\t%2$s --- %3$s --- %4$s\n", addr,
                        source.getLibraryName(), source.getMethodName(), source.getSourceFile()));
            }
        }

        return buffer.toString();
    }

    /**
     * Returns the first {@link NativeStackCallInfo} that is relevant.
     * <p/>
     * A relevant <code>NativeStackCallInfo</code> is a stack call that is not deep in the
     * lower level of the libc, but the actual method that performed the allocation.
     * @return a <code>NativeStackCallInfo</code> or <code>null</code> if the stack call has not
     * been processed from the raw addresses.
     * @see #setResolvedStackCall(ArrayList)
     * @see #isStackCallResolved()
     */
    public synchronized NativeStackCallInfo getRelevantStackCallInfo() {
        if (mIsStackCallResolved && mResolvedStackCall != null) {
            for (NativeStackCallInfo info : mResolvedStackCall) {
                if (isRelevantLibrary(info.getLibraryName())
                        && isRelevantMethod(info.getMethodName())) {
                    return info;
                }
            }

            // couldnt find a relevant one, so we'll return the first one if it exists.
            if (mResolvedStackCall.size() > 0)
                return mResolvedStackCall.get(0);
        }

        return null;
    }

    private boolean isRelevantLibrary(String libPath) {
        for (String l : FILTERED_LIBRARIES) {
            if (libPath.endsWith(l)) {
                return false;
            }
        }

        return true;
    }

    private boolean isRelevantMethod(String methodName) {
        for (Pattern p : FILTERED_METHOD_NAME_PATTERNS) {
            Matcher m = p.matcher(methodName);
            if (m.find()) {
                return false;
            }
        }

        return true;
    }
}