baksmali.java revision e9b722eab0b0932be59cb99c8c6f403b00abad6f
1/*
2 * [The "BSD licence"]
3 * Copyright (c) 2009 Ben Gruver
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.antlr.stringtemplate.StringTemplate;
32import org.antlr.stringtemplate.StringTemplateGroup;
33import org.jf.baksmali.Adaptors.ClassDefinition;
34import org.jf.baksmali.Renderers.*;
35import org.jf.dexlib.Code.Analysis.ClassPath;
36import org.jf.dexlib.DexFile;
37import org.jf.dexlib.ClassDefItem;
38import org.jf.dexlib.StringIdItem;
39
40import java.io.*;
41
42public class baksmali {
43    public static boolean noParameterRegisters = false;
44    public static boolean useLocalsDirective = false;
45    public static boolean useSequentialLabels = false;
46    public static boolean outputDebugInfo = true;
47    public static boolean addCodeOffsets = false;
48    public static boolean deodex = false;
49    public static int registerInfo = 0;
50    public static String bootClassPath;
51
52    public static void disassembleDexFile(DexFile dexFile, boolean deodex, String outputDirectory,
53                                          String bootClassPathDir, String bootClassPath, boolean noParameterRegisters,
54                                          boolean useLocalsDirective, boolean useSequentialLabels,
55                                          boolean outputDebugInfo, boolean addCodeOffsets, int registerInfo)
56    {
57        baksmali.noParameterRegisters = noParameterRegisters;
58        baksmali.useLocalsDirective = useLocalsDirective;
59        baksmali.useSequentialLabels = useSequentialLabels;
60        baksmali.outputDebugInfo = outputDebugInfo;
61        baksmali.addCodeOffsets = addCodeOffsets;
62        baksmali.deodex = deodex;
63        baksmali.registerInfo = registerInfo;
64        baksmali.bootClassPath = bootClassPath;
65
66        if (registerInfo != 0 || deodex) {
67            try {
68                ClassPath.InitializeClassPath(bootClassPathDir, bootClassPath==null?null:bootClassPath.split(":"), dexFile);
69            } catch (Exception ex) {
70                System.err.println("\n\nError occured while loading boot class path files. Aborting.");
71                ex.printStackTrace(System.err);
72                System.exit(1);
73            }
74        }
75
76        File outputDirectoryFile = new File(outputDirectory);
77        if (!outputDirectoryFile.exists()) {
78            if (!outputDirectoryFile.mkdirs()) {
79                System.err.println("Can't create the output directory " + outputDirectory);
80                System.exit(1);
81            }
82        }
83
84        //load and initialize the templates
85        InputStream templateStream = baksmali.class.getClassLoader().getResourceAsStream("templates/baksmali.stg");
86        StringTemplateGroup templates = new StringTemplateGroup(new InputStreamReader(templateStream));
87        templates.registerRenderer(Long.class, new LongRenderer());
88        templates.registerRenderer(Integer.class,  new IntegerRenderer());
89        templates.registerRenderer(Short.class, new ShortRenderer());
90        templates.registerRenderer(Byte.class, new ByteRenderer());
91        templates.registerRenderer(Float.class, new FloatRenderer());
92        templates.registerRenderer(Character.class, new CharRenderer());
93        templates.registerRenderer(StringIdItem.class, new StringIdItemRenderer());
94
95
96        for (ClassDefItem classDefItem: dexFile.ClassDefsSection.getItems()) {
97            /**
98             * The path for the disassembly file is based on the package name
99             * The class descriptor will look something like:
100             * Ljava/lang/Object;
101             * Where the there is leading 'L' and a trailing ';', and the parts of the
102             * package name are separated by '/'
103             */
104
105            String classDescriptor = classDefItem.getClassType().getTypeDescriptor();
106
107            //validate that the descriptor is formatted like we expect
108            if (classDescriptor.charAt(0) != 'L' ||
109                classDescriptor.charAt(classDescriptor.length()-1) != ';') {
110                System.err.println("Unrecognized class descriptor - " + classDescriptor + " - skipping class");
111                continue;
112            }
113
114            //trim off the leading L and trailing ;
115            classDescriptor = classDescriptor.substring(1, classDescriptor.length()-1);
116
117            //trim off the leading 'L' and trailing ';', and get the individual package elements
118            String[] pathElements = classDescriptor.split("/");
119
120            //build the path to the smali file to generate for this class
121            StringBuilder smaliPath = new StringBuilder(outputDirectory);
122            for (String pathElement: pathElements) {
123                smaliPath.append(File.separatorChar);
124                smaliPath.append(pathElement);
125            }
126            smaliPath.append(".smali");
127
128            File smaliFile = new File(smaliPath.toString());
129
130            //create and initialize the top level string template
131            ClassDefinition classDefinition = new ClassDefinition(templates, classDefItem);
132
133            StringTemplate smaliFileST = classDefinition.createTemplate();
134
135            //generate the disassembly
136            String output = smaliFileST.toString();
137
138            //write the disassembly
139            FileWriter writer = null;
140            try
141            {
142                File smaliParent = smaliFile.getParentFile();
143                if (!smaliParent.exists()) {
144                    if (!smaliParent.mkdirs()) {
145                        System.err.println("Unable to create directory " + smaliParent.toString() + " - skipping class");
146                        continue;
147                    }
148                }
149
150                if (!smaliFile.exists()){
151                    if (!smaliFile.createNewFile()) {
152                        System.err.println("Unable to create file " + smaliFile.toString() + " - skipping class");
153                        continue;
154                    }
155                }
156
157                writer = new FileWriter(smaliFile);
158                writer.write(output);
159            } catch (Exception ex) {
160                System.err.println("\n\nError occured while disassembling class " + classDescriptor.replace('/', '.') + " - skipping class");
161                ex.printStackTrace();
162            }
163            finally
164            {
165                if (writer != null) {
166                    try {
167                        writer.close();
168                    } catch (Throwable ex) {
169                        System.err.println("\n\nError occured while closing file " + smaliFile.toString());
170                        ex.printStackTrace();
171                    }
172                }
173            }
174
175            //TODO: GROT
176            if (classDefinition.hadValidationErrors()) {
177                System.exit(1);
178            }
179        }
180    }
181}
182