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