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