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