aboutsummaryrefslogtreecommitdiff
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/DexDumpAction.java
blob: 78fcfd4488d40da84562d1320af7e81588307a53 (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
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
 *
 * 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.ide.eclipse.adt.internal.actions;

import com.android.SdkConstants;
import com.android.annotations.Nullable;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.sdklib.BuildToolInfo;
import com.android.utils.GrabProcessOutput;
import com.android.utils.GrabProcessOutput.IProcessOutput;
import com.android.utils.GrabProcessOutput.Wait;
import com.android.utils.SdkUtils;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

/**
 * Runs dexdump on the classes.dex of a selected project.
 */
public class DexDumpAction implements IObjectActionDelegate {

    private ISelection mSelection;

    @Override
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        // pass
    }

    @Override
    public void run(IAction action) {
        if (mSelection instanceof IStructuredSelection) {
            for (Iterator<?> it = ((IStructuredSelection)mSelection).iterator(); it.hasNext();) {
                Object element = it.next();
                IProject project = null;
                if (element instanceof IProject) {
                    project = (IProject)element;
                } else if (element instanceof IAdaptable) {
                    project = (IProject)((IAdaptable)element).getAdapter(IProject.class);
                }
                if (project != null) {
                    dexDumpProject(project);
                }
            }
        }
    }

    @Override
    public void selectionChanged(IAction action, ISelection selection) {
        mSelection = selection;
    }

    /**
     * Calls {@link #runDexDump(IProject, IProgressMonitor)} inside a job.
     *
     * @param project on which to run dexdump.
     */
    private void dexDumpProject(final IProject project) {
        new Job("Dexdump") {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                return runDexDump(project, monitor);
            }
        }.schedule();
    }

    /**
     * Runs <code>dexdump</code> on the classex.dex of the project.
     * Saves the output in a temporary file.
     * On success, opens the file in the default text editor.
     *
     * @param project on which to run dexdump.
     * @param monitor The job's monitor.
     */
    private IStatus runDexDump(final IProject project, IProgressMonitor monitor) {
        File dstFile = null;
        boolean removeDstFile = true;
        try {
            if (monitor != null) {
                monitor.beginTask(String.format("Dump dex of %1$s", project.getName()), 2);
            }

            Sdk current = Sdk.getCurrent();
            if (current == null) {
                AdtPlugin.printErrorToConsole(project,
                        "DexDump: missing current SDK");                            //$NON-NLS-1$
                return Status.OK_STATUS;
            }

            BuildToolInfo buildToolInfo = current.getLatestBuildTool();
            if (buildToolInfo == null) {
                AdtPlugin.printErrorToConsole(project,
                    "SDK missing build tools. Please install build tools using SDK Manager.");
                return Status.OK_STATUS;
            }

            File buildToolsFolder = buildToolInfo.getLocation();
            File dexDumpFile = new File(buildToolsFolder, SdkConstants.FN_DEXDUMP);

            IPath binPath = project.getFolder(SdkConstants.FD_OUTPUT).getLocation();
            if (binPath == null) {
                AdtPlugin.printErrorToConsole(project,
                    "DexDump: missing project /bin folder. Please compile first."); //$NON-NLS-1$
                return Status.OK_STATUS;
            }

            File classesDexFile =
                new File(binPath.toOSString(), SdkConstants.FN_APK_CLASSES_DEX);
            if (!classesDexFile.exists()) {
                AdtPlugin.printErrorToConsole(project,
                    "DexDump: missing classex.dex for project. Please compile first.");//$NON-NLS-1$
                return Status.OK_STATUS;
            }

            try {
                dstFile = File.createTempFile(
                        "dexdump_" + project.getName() + "_",         //$NON-NLS-1$ //$NON-NLS-2$
                        ".txt");                                                    //$NON-NLS-1$
            } catch (Exception e) {
                AdtPlugin.logAndPrintError(e, project.getName(),
                        "DexDump: createTempFile failed.");                         //$NON-NLS-1$
                return Status.OK_STATUS;
            }

            // --- Exec command line and save result to dst file

            String[] command = new String[2];
            command[0] = dexDumpFile.getAbsolutePath();
            command[1] = classesDexFile.getAbsolutePath();

            try {
                final Process process = Runtime.getRuntime().exec(command);

                final BufferedWriter writer = new BufferedWriter(new FileWriter(dstFile));
                try {
                    final String lineSep = SdkUtils.getLineSeparator();

                    int err = GrabProcessOutput.grabProcessOutput(
                            process,
                            Wait.WAIT_FOR_READERS,
                            new IProcessOutput() {
                                @Override
                                public void out(@Nullable String line) {
                                    if (line != null) {
                                        try {
                                            writer.write(line);
                                            writer.write(lineSep);
                                        } catch (IOException ignore) {}
                                    }
                                }

                                @Override
                                public void err(@Nullable String line) {
                                    if (line != null) {
                                        AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE,
                                                project, line);
                                    }
                                }
                            });

                    if (err == 0) {
                        // The command worked. In this case we don't remove the
                        // temp file in the finally block.
                        removeDstFile = false;
                    } else {
                        AdtPlugin.printErrorToConsole(project,
                            "DexDump failed with code " + Integer.toString(err));       //$NON-NLS-1$
                        return Status.OK_STATUS;
                    }
                } finally {
                    writer.close();
                }
            } catch (InterruptedException e) {
                // ?
            }

            if (monitor != null) {
                monitor.worked(1);
            }

            // --- Open the temp file in an editor

            final String dstPath = dstFile.getAbsolutePath();
            AdtPlugin.getDisplay().asyncExec(new Runnable() {
                @Override
                public void run() {
                    IFileStore fileStore =
                        EFS.getLocalFileSystem().getStore(new Path(dstPath));
                    if (!fileStore.fetchInfo().isDirectory() &&
                            fileStore.fetchInfo().exists()) {

                        IWorkbench wb = PlatformUI.getWorkbench();
                        IWorkbenchWindow win = wb == null ? null : wb.getActiveWorkbenchWindow();
                        final IWorkbenchPage page = win == null ? null : win.getActivePage();

                        if (page != null) {
                            try {
                                IDE.openEditorOnFileStore(page, fileStore);
                            } catch (PartInitException e) {
                                AdtPlugin.logAndPrintError(e, project.getName(),
                                "Opening DexDump result failed. Result is available at %1$s", //$NON-NLS-1$
                                dstPath);
                            }
                        }
                    }
                }
            });

            if (monitor != null) {
                monitor.worked(1);
            }

            return Status.OK_STATUS;

        } catch (IOException e) {
            AdtPlugin.logAndPrintError(e, project.getName(),
                    "DexDump failed.");                                     //$NON-NLS-1$
            return Status.OK_STATUS;

        } finally {
            // By default we remove the temp file on failure.
            if (removeDstFile && dstFile != null) {
                try {
                    dstFile.delete();
                } catch (Exception e) {
                    AdtPlugin.logAndPrintError(e, project.getName(),
                            "DexDump: can't delete temp file %1$s.",        //$NON-NLS-1$
                            dstFile.getAbsoluteFile());
                }
            }
            if (monitor != null) {
                monitor.done();
            }
        }
    }
}