main.java revision 78bde01ad4bf31ad44ad7bd0279b07fd2696b53c
1/*
2 * [The "BSD licence"]
3 * Copyright (c) 2010 Ben Gruver (JesusFreke)
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29package org.jf.baksmali;
30
31import org.apache.commons.cli.*;
32import org.jf.dexlib.DexFile;
33import org.jf.dexlib.OdexDependencies;
34import org.jf.dexlib.Util.ExceptionWithContext;
35import org.jf.util.*;
36
37import java.io.File;
38import java.io.InputStream;
39import java.io.IOException;
40import java.util.ArrayList;
41import java.util.List;
42import java.util.Properties;
43
44public class main {
45
46    public static final String VERSION;
47
48    private static final Options basicOptions;
49    private static final Options debugOptions;
50    private static final Options options;
51
52    public static final int ALL = 1;
53    public static final int ALLPRE = 2;
54    public static final int ALLPOST = 4;
55    public static final int ARGS = 8;
56    public static final int DEST = 16;
57    public static final int MERGE = 32;
58    public static final int FULLMERGE = 64;
59
60    static {
61        options = new Options();
62        basicOptions = new Options();
63        debugOptions = new Options();
64        buildOptions();
65
66        InputStream templateStream = baksmali.class.getClassLoader().getResourceAsStream("baksmali.properties");
67        Properties properties = new Properties();
68        String version = "(unknown)";
69        try {
70            properties.load(templateStream);
71            version = properties.getProperty("application.version");
72        } catch (IOException ex) {
73        }
74        VERSION = version;
75    }
76
77    /**
78     * This class is uninstantiable.
79     */
80    private main() {
81    }
82
83    /**
84     * Run!
85     */
86    public static void main(String[] args) {
87        CommandLineParser parser = new PosixParser();
88        CommandLine commandLine;
89
90        try {
91            commandLine = parser.parse(options, args);
92        } catch (ParseException ex) {
93            usage();
94            return;
95        }
96
97        boolean disassemble = true;
98        boolean doDump = false;
99        boolean write = false;
100        boolean sort = false;
101        boolean fixRegisters = false;
102        boolean noParameterRegisters = false;
103        boolean useLocalsDirective = false;
104        boolean useSequentialLabels = false;
105        boolean outputDebugInfo = true;
106        boolean addCodeOffsets = false;
107        boolean deodex = false;
108        boolean verify = false;
109
110        int registerInfo = 0;
111
112        String outputDirectory = "out";
113        String dumpFileName = null;
114        String outputDexFileName = null;
115        String inputDexFileName = null;
116        String bootClassPath = null;
117        StringBuffer extraBootClassPathEntries = new StringBuffer();
118        List<String> bootClassPathDirs = new ArrayList<String>();
119        bootClassPathDirs.add(".");
120
121
122        String[] remainingArgs = commandLine.getArgs();
123
124        Option[] options = commandLine.getOptions();
125
126        for (int i=0; i<options.length; i++) {
127            Option option = options[i];
128            String opt = option.getOpt();
129
130            switch (opt.charAt(0)) {
131                case 'v':
132                    version();
133                    return;
134                case '?':
135                    while (++i < options.length) {
136                        if (options[i].getOpt().charAt(0) == '?') {
137                            usage(true);
138                            return;
139                        }
140                    }
141                    usage(false);
142                    return;
143                case 'o':
144                    outputDirectory = commandLine.getOptionValue("o");
145                    break;
146                case 'p':
147                    noParameterRegisters = true;
148                    break;
149                case 'l':
150                    useLocalsDirective = true;
151                    break;
152                case 's':
153                    useSequentialLabels = true;
154                    break;
155                case 'b':
156                    outputDebugInfo = false;
157                    break;
158                case 'd':
159                    bootClassPathDirs.add(option.getValue());
160                    break;
161                case 'f':
162                    addCodeOffsets = true;
163                    break;
164                case 'r':
165                    String[] values = commandLine.getOptionValues('r');
166
167                    if (values == null || values.length == 0) {
168                        registerInfo = ARGS | DEST;
169                    } else {
170                        for (String value: values) {
171                            if (value.equalsIgnoreCase("ALL")) {
172                                registerInfo |= ALL;
173                            } else if (value.equalsIgnoreCase("ALLPRE")) {
174                                registerInfo |= ALLPRE;
175                            } else if (value.equalsIgnoreCase("ALLPOST")) {
176                                registerInfo |= ALLPOST;
177                            } else if (value.equalsIgnoreCase("ARGS")) {
178                                registerInfo |= ARGS;
179                            } else if (value.equalsIgnoreCase("DEST")) {
180                                registerInfo |= DEST;
181                            } else if (value.equalsIgnoreCase("MERGE")) {
182                                registerInfo |= MERGE;
183                            } else if (value.equalsIgnoreCase("FULLMERGE")) {
184                                registerInfo |= FULLMERGE;
185                            } else {
186                                usage();
187                                return;
188                            }
189                        }
190
191                        if ((registerInfo & FULLMERGE) != 0) {
192                            registerInfo &= ~MERGE;
193                        }
194                    }
195                    break;
196                case 'c':
197                    String bcp = commandLine.getOptionValue("c");
198                    if (bcp != null && bcp.charAt(0) == ':') {
199                        extraBootClassPathEntries.append(bcp);
200                    } else {
201                        bootClassPath = bcp;
202                    }
203                    break;
204                case 'x':
205                    deodex = true;
206                    break;
207                case 'N':
208                    disassemble = false;
209                    break;
210                case 'D':
211                    doDump = true;
212                    dumpFileName = commandLine.getOptionValue("D", inputDexFileName + ".dump");
213                    break;
214                case 'W':
215                    write = true;
216                    outputDexFileName = commandLine.getOptionValue("W");
217                    break;
218                case 'S':
219                    sort = true;
220                    break;
221                case 'F':
222                    fixRegisters = true;
223                    break;
224                case 'V':
225                    verify = true;
226                    break;
227                default:
228                    assert false;
229            }
230        }
231
232        if (remainingArgs.length != 1) {
233            usage();
234            return;
235        }
236
237        inputDexFileName = remainingArgs[0];
238
239        try {
240            File dexFileFile = new File(inputDexFileName);
241            if (!dexFileFile.exists()) {
242                System.err.println("Can't find the file " + inputDexFileName);
243                System.exit(1);
244            }
245
246            //Read in and parse the dex file
247            DexFile dexFile = new DexFile(dexFileFile, !fixRegisters, false);
248
249            if (dexFile.isOdex()) {
250                if (doDump) {
251                    System.err.println("-D cannot be used with on odex file. Ignoring -D");
252                }
253                if (write) {
254                    System.err.println("-W cannot be used with an odex file. Ignoring -W");
255                }
256                if (!deodex) {
257                    System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
258                    System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
259                    System.err.println("option");
260                }
261            } else {
262                deodex = false;
263
264                if (bootClassPath == null) {
265                    bootClassPath = "core.jar:ext.jar:framework.jar:android.policy.jar:services.jar";
266                }
267            }
268
269            if (disassemble) {
270                String[] bootClassPathDirsArray = new String[bootClassPathDirs.size()];
271                for (int i=0; i<bootClassPathDirsArray.length; i++) {
272                    bootClassPathDirsArray[i] = bootClassPathDirs.get(i);
273                }
274
275                baksmali.disassembleDexFile(dexFileFile.getPath(), dexFile, deodex, outputDirectory,
276                        bootClassPathDirsArray, bootClassPath, extraBootClassPathEntries.toString(),
277                        noParameterRegisters, useLocalsDirective, useSequentialLabels, outputDebugInfo, addCodeOffsets,
278                        registerInfo, verify);
279            }
280
281            if ((doDump || write) && !dexFile.isOdex()) {
282                try
283                {
284                    dump.dump(dexFile, dumpFileName, outputDexFileName, sort);
285                }catch (IOException ex) {
286                    System.err.println("Error occured while writing dump file");
287                    ex.printStackTrace();
288                }
289            }
290        } catch (RuntimeException ex) {
291            System.err.println("\n\nUNEXPECTED TOP-LEVEL EXCEPTION:");
292            ex.printStackTrace();
293            System.exit(1);
294        } catch (Throwable ex) {
295            System.err.println("\n\nUNEXPECTED TOP-LEVEL ERROR:");
296            ex.printStackTrace();
297            System.exit(1);
298        }
299    }
300
301    /**
302     * Prints the usage message.
303     */
304    private static void usage(boolean printDebugOptions) {
305        smaliHelpFormatter formatter = new smaliHelpFormatter();
306        formatter.setWidth(ConsoleUtil.getConsoleWidth());
307
308        formatter.printHelp("java -jar baksmali.jar [options] <dex-file>",
309                "disassembles and/or dumps a dex file", basicOptions, "");
310
311        if (printDebugOptions) {
312            System.out.println();
313            System.out.println("Debug Options:");
314
315            StringBuffer sb = new StringBuffer();
316            formatter.renderOptions(sb, debugOptions);
317            System.out.println(sb.toString());
318        }
319    }
320
321    private static void usage() {
322        usage(false);
323    }
324
325    /**
326     * Prints the version message.
327     */
328    protected static void version() {
329        System.out.println("baksmali " + VERSION + " (http://smali.googlecode.com)");
330        System.out.println("Copyright (C) 2010 Ben Gruver (JesusFreke@JesusFreke.com)");
331        System.out.println("BSD license (http://www.opensource.org/licenses/bsd-license.php)");
332        System.exit(0);
333    }
334
335    private static void buildOptions() {
336        Option versionOption = OptionBuilder.withLongOpt("version")
337                .withDescription("prints the version then exits")
338                .create("v");
339
340        Option helpOption = OptionBuilder.withLongOpt("help")
341                .withDescription("prints the help message then exits. Specify twice for debug options")
342                .create("?");
343
344        Option noDisassemblyOption = OptionBuilder.withLongOpt("no-disassembly")
345                .withDescription("suppresses the output of the disassembly")
346                .create("N");
347
348        Option dumpOption = OptionBuilder.withLongOpt("dump-to")
349                .withDescription("dumps the given dex file into a single annotated dump file named FILE" +
350                        " (<dexfile>.dump by default), along with the normal disassembly.")
351                .hasOptionalArg()
352                .withArgName("FILE")
353                .create("D");
354
355        Option writeDexOption = OptionBuilder.withLongOpt("write-dex")
356                .withDescription("additionally rewrites the input dex file to FILE")
357                .hasArg()
358                .withArgName("FILE")
359                .create("W");
360
361        Option outputDirOption = OptionBuilder.withLongOpt("output")
362                .withDescription("the directory where the disassembled files will be placed. The default is out")
363                .hasArg()
364                .withArgName("DIR")
365                .create("o");
366
367        Option sortOption = OptionBuilder.withLongOpt("sort")
368                .withDescription("sort the items in the dex file into a canonical order before dumping/writing")
369                .create("S");
370
371        Option fixSignedRegisterOption = OptionBuilder.withLongOpt("fix-signed-registers")
372                .withDescription("when dumping or rewriting, fix any registers in the debug info that are encoded as" +
373                        " a signed value")
374                .create("F");
375
376        Option noParameterRegistersOption = OptionBuilder.withLongOpt("no-parameter-registers")
377                .withDescription("use the v<n> syntax instead of the p<n> syntax for registers mapped to method " +
378                        "parameters")
379                .create("p");
380
381        Option deodexerantOption = OptionBuilder.withLongOpt("deodex")
382                .withDescription("deodex the given odex file. This option is ignored if the input file is not an " +
383                        "odex file.")
384                .create("x");
385
386        Option useLocalsOption = OptionBuilder.withLongOpt("use-locals")
387                .withDescription("output the .locals directive with the number of non-parameter registers, rather" +
388                        " than the .register directive with the total number of register")
389                .create("l");
390
391        Option sequentialLabelsOption = OptionBuilder.withLongOpt("sequential-labels")
392                .withDescription("create label names using a sequential numbering scheme per label type, rather than " +
393                        "using the bytecode address")
394                .create("s");
395
396        Option noDebugInfoOption = OptionBuilder.withLongOpt("no-debug-info")
397                .withDescription("don't write out debug info (.local, .param, .line, etc.)")
398                .create("b");
399
400        Option registerInfoOption = OptionBuilder.withLongOpt("register-info")
401                .hasOptionalArgs()
402                .withArgName("REGISTER_INFO_TYPES")
403                .withValueSeparator(',')
404                .withDescription("print the specificed type(s) of register information for each instruction. " +
405                        "\"ARGS,DEST\" is the default if no types are specified.\nValid values are:\nALL: all " +
406                        "pre- and post-instruction registers.\nALLPRE: all pre-instruction registers\nALLPOST: all " +
407                        "post-instruction registers\nARGS: any pre-instruction registers used as arguments to the " +
408                        "instruction\nDEST: the post-instruction destination register, if any\nMERGE: Any " +
409                        "pre-instruction register has been merged from more than 1 different post-instruction " +
410                        "register from its predecessors\nFULLMERGE: For each register that would be printed by " +
411                        "MERGE, also show the incoming register types that were merged")
412                .create("r");
413
414        Option classPathOption = OptionBuilder.withLongOpt("bootclasspath")
415                .withDescription("the bootclasspath jars to use, for analysis. Defaults to " +
416                        "core.jar:ext.jar:framework.jar:android.policy.jar:services.jar. If the value begins with a " +
417                        ":, it will be appended to the default bootclasspath instead of replacing it")
418                .hasOptionalArg()
419                .withArgName("BOOTCLASSPATH")
420                .create("c");
421
422        Option classPathDirOption = OptionBuilder.withLongOpt("bootclasspath-dir")
423                .withDescription("the base folder to look for the bootclasspath files in. Defaults to the current " +
424                        "directory")
425                .hasArg()
426                .withArgName("DIR")
427                .create("d");
428
429        Option codeOffsetOption = OptionBuilder.withLongOpt("code-offsets")
430                .withDescription("add comments to the disassembly containing the code offset for each address")
431                .create("f");
432
433        Option verifyDexOption = OptionBuilder.withLongOpt("verify")
434                .withDescription("perform bytecode verification")
435                .create("V");
436
437        basicOptions.addOption(versionOption);
438        basicOptions.addOption(helpOption);
439        basicOptions.addOption(outputDirOption);
440        basicOptions.addOption(noParameterRegistersOption);
441        basicOptions.addOption(deodexerantOption);
442        basicOptions.addOption(useLocalsOption);
443        basicOptions.addOption(sequentialLabelsOption);
444        basicOptions.addOption(noDebugInfoOption);
445        basicOptions.addOption(registerInfoOption);
446        basicOptions.addOption(classPathOption);
447        basicOptions.addOption(classPathDirOption);
448        basicOptions.addOption(codeOffsetOption);
449
450        debugOptions.addOption(dumpOption);
451        debugOptions.addOption(noDisassemblyOption);
452        debugOptions.addOption(writeDexOption);
453        debugOptions.addOption(sortOption);
454        debugOptions.addOption(fixSignedRegisterOption);
455        debugOptions.addOption(verifyDexOption);
456
457
458        for (Object option: basicOptions.getOptions()) {
459            options.addOption((Option)option);
460        }
461        for (Object option: debugOptions.getOptions()) {
462            options.addOption((Option)option);
463        }
464    }
465}