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