aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tradefed/targetprep/NativeLeakCollector.java
blob: 9bc2e4e8dcb22f4c7955b10d9421c8be168d8dd1 (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
/*
 * Copyright (C) 2016 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.tradefed.targetprep;

import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.config.Option;
import com.android.tradefed.config.OptionClass;
import com.android.tradefed.device.CollectingOutputReceiver;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.ITestLogger;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ByteArrayInputStreamSource;
import com.android.tradefed.result.ITestLoggerReceiver;
import com.android.tradefed.result.LogDataType;
import com.android.tradefed.util.StreamUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * A {@link ITargetCleaner} that runs 'dumpsys meminfo --unreachable -a' to identify the unreachable
 * native memory currently held by each process.
 * <p>
 * Note: this preparer requires N platform or newer.
 */
@OptionClass(alias = "native-leak-collector")
public class NativeLeakCollector implements ITestLoggerReceiver, ITargetCleaner {
    private static final String UNREACHABLE_MEMINFO_CMD = "dumpsys -t %d meminfo --unreachable -a";
    private static final String DIRECT_UNREACHABLE_CMD = "dumpsys -t %d %s --unreachable";
    private static final String OUTPUT_HEADER = "\nExecuted command: %s\n";

    private ITestLogger mTestLogger;

    @Option(name = "disable", description = "If this preparer should be disabled.")
    private boolean mDisable = false;

    @Option(name = "dump-timeout", description = "Timeout limit for dumping unreachable native "
            + "memory allocation information. Can be in any valid duration format, e.g. 5m, 1h.",
            isTimeVal = true)
    private long mDumpTimeout = 5 * 60 * 1000; // defaults to 5m

    @Option(name = "log-filename", description = "The filename to give this log.")
    private String mLogFilename = "unreachable-meminfo";

    @Option(name = "additional-proc", description = "A list indicating any additional names to "
            + "query for unreachable native memory.")
    private List<String> mAdditionalProc = new ArrayList<String>();

    @Option(name = "additional-dump-timeout", description = "An additional timeout limit for any "
            + "direct unreachable memory dump commands specified by the 'additional-procs' option. "
            + "Can be in any valid duration format, e.g. 5m, 1h.",
            isTimeVal = true)
    private long mAdditionalDumpTimeout = 1 * 60 * 1000; // defaults to 1m

    /**
     * {@inheritDoc}
     */
    @Override
    public void setUp(ITestDevice device, IBuildInfo buildInfo)
            throws TargetSetupError, BuildError, DeviceNotAvailableException {
        // No-op
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e)
            throws DeviceNotAvailableException {
        if (mDisable || (e instanceof DeviceNotAvailableException)) {
            return;
        }

        CollectingOutputReceiver receiver = new CollectingOutputReceiver();
        String allCommand = String.format(UNREACHABLE_MEMINFO_CMD, mDumpTimeout / 1000);
        writeToReceiver(String.format(OUTPUT_HEADER, allCommand), receiver);
        device.executeShellCommand(allCommand, receiver, mDumpTimeout, TimeUnit.MILLISECONDS, 1);

        for (String proc : mAdditionalProc) {
            String procCommand = String.format(DIRECT_UNREACHABLE_CMD,
                    mAdditionalDumpTimeout / 1000, proc);
            writeToReceiver(String.format(OUTPUT_HEADER, procCommand), receiver);
            device.executeShellCommand(procCommand, receiver, mAdditionalDumpTimeout,
                    TimeUnit.MILLISECONDS, 1);
        }

        if (receiver.getOutput() != null && !receiver.getOutput().isEmpty()) {
            if (mTestLogger != null) {
                ByteArrayInputStreamSource byteOutput =
                        new ByteArrayInputStreamSource(receiver.getOutput().getBytes());
                mTestLogger.testLog(mLogFilename, LogDataType.TEXT, byteOutput);
                StreamUtil.cancel(byteOutput);
            } else {
                CLog.w("No test logger available, printing output here:\n%s", receiver.getOutput());
            }
        }
    }

    private void writeToReceiver (String msg, CollectingOutputReceiver receiver) {
        byte[] msgBytes = msg.getBytes();
        int byteCount = msgBytes.length;
        receiver.addOutput(msgBytes, 0, byteCount);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setTestLogger(ITestLogger testLogger) {
        mTestLogger = testLogger;
    }
}