baksmali.java revision bbf4dbba6127ef96e316060b2b4ec292627a4078
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.jf.baksmali.Adaptors.ClassDefinition;
32import org.jf.dexlib.ClassDefItem;
33import org.jf.dexlib.Code.Analysis.ClassPath;
34import org.jf.dexlib.DexFile;
35import org.jf.util.ClassFileNameHandler;
36
37import java.io.*;
38import java.util.ArrayList;
39import java.util.Collections;
40import java.util.Comparator;
41import java.util.regex.Matcher;
42import java.util.regex.Pattern;
43
44public class baksmali {
45    public static boolean noParameterRegisters = false;
46    public static boolean useLocalsDirective = false;
47    public static boolean useSequentialLabels = false;
48    public static boolean outputDebugInfo = true;
49    public static boolean addCodeOffsets = false;
50    public static boolean deodex = false;
51    public static boolean verify = false;
52    public static int registerInfo = 0;
53    public static String bootClassPath;
54
55    public static void disassembleDexFile(String dexFilePath, DexFile dexFile, boolean deodex, String outputDirectory,
56                                          String[] classPathDirs, String bootClassPath, String extraBootClassPath,
57                                          boolean noParameterRegisters, boolean useLocalsDirective,
58                                          boolean useSequentialLabels, boolean outputDebugInfo, boolean addCodeOffsets,
59                                          int registerInfo, boolean verify, boolean ignoreErrors)
60    {
61        baksmali.noParameterRegisters = noParameterRegisters;
62        baksmali.useLocalsDirective = useLocalsDirective;
63        baksmali.useSequentialLabels = useSequentialLabels;
64        baksmali.outputDebugInfo = outputDebugInfo;
65        baksmali.addCodeOffsets = addCodeOffsets;
66        baksmali.deodex = deodex;
67        baksmali.registerInfo = registerInfo;
68        baksmali.bootClassPath = bootClassPath;
69        baksmali.verify = verify;
70
71        ClassPath.ClassPathErrorHandler classPathErrorHandler = null;
72        if (ignoreErrors) {
73            classPathErrorHandler = new ClassPath.ClassPathErrorHandler() {
74                public void ClassPathError(String className, Exception ex) {
75                    System.err.println(String.format("Skipping %s", className));
76                    ex.printStackTrace(System.err);
77                }
78            };
79        }
80
81        if (registerInfo != 0 || deodex || verify) {
82            try {
83                String[] extraBootClassPathArray = null;
84                if (extraBootClassPath != null && extraBootClassPath.length() > 0) {
85                    assert extraBootClassPath.charAt(0) == ':';
86                    extraBootClassPathArray = extraBootClassPath.substring(1).split(":");
87                }
88
89                if (dexFile.isOdex() && bootClassPath == null) {
90                    //ext.jar is a special case - it is typically the 2nd jar in the boot class path, but it also
91                    //depends on classes in framework.jar (typically the 3rd jar in the BCP). If the user didn't
92                    //specify a -c option, we should add framework.jar to the boot class path by default, so that it
93                    //"just works"
94                    if (extraBootClassPathArray == null && isExtJar(dexFilePath)) {
95                        extraBootClassPathArray = new String[] {"framework.jar"};
96                    }
97                    ClassPath.InitializeClassPathFromOdex(classPathDirs, extraBootClassPathArray, dexFilePath, dexFile,
98                            classPathErrorHandler);
99                } else {
100                    String[] bootClassPathArray = null;
101                    if (bootClassPath != null) {
102                        bootClassPathArray = bootClassPath.split(":");
103                    }
104                    ClassPath.InitializeClassPath(classPathDirs, bootClassPathArray, extraBootClassPathArray,
105                            dexFilePath, dexFile, classPathErrorHandler);
106                }
107            } catch (Exception ex) {
108                System.err.println("\n\nError occured while loading boot class path files. Aborting.");
109                ex.printStackTrace(System.err);
110                System.exit(1);
111            }
112        }
113
114        File outputDirectoryFile = new File(outputDirectory);
115        if (!outputDirectoryFile.exists()) {
116            if (!outputDirectoryFile.mkdirs()) {
117                System.err.println("Can't create the output directory " + outputDirectory);
118                System.exit(1);
119            }
120        }
121
122        //sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file
123        //name collisions, then we'll use the same name for each class, if the dex file goes through multiple
124        //baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames
125        //may still change of course
126        ArrayList<ClassDefItem> classDefItems = new ArrayList<ClassDefItem>(dexFile.ClassDefsSection.getItems());
127        Collections.sort(classDefItems, new Comparator<ClassDefItem>() {
128            public int compare(ClassDefItem classDefItem1, ClassDefItem classDefItem2) {
129                return classDefItem1.getClassType().getTypeDescriptor().compareTo(classDefItem1.getClassType().getTypeDescriptor());
130            }
131        });
132
133        ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali");
134
135        for (ClassDefItem classDefItem: classDefItems) {
136            /**
137             * The path for the disassembly file is based on the package name
138             * The class descriptor will look something like:
139             * Ljava/lang/Object;
140             * Where the there is leading 'L' and a trailing ';', and the parts of the
141             * package name are separated by '/'
142             */
143
144            if (registerInfo != 0 || deodex || verify) {
145                //If we are analyzing the bytecode, make sure that this class is loaded into the ClassPath. If it isn't
146                //then there was some error while loading it, and we should skip it
147                ClassPath.ClassDef classDef = ClassPath.getClassDef(classDefItem.getClassType(), false);
148                if (classDef == null || classDef instanceof ClassPath.UnresolvedClassDef) {
149                    continue;
150                }
151            }
152
153            String classDescriptor = classDefItem.getClassType().getTypeDescriptor();
154
155            //validate that the descriptor is formatted like we expect
156            if (classDescriptor.charAt(0) != 'L' ||
157                classDescriptor.charAt(classDescriptor.length()-1) != ';') {
158                System.err.println("Unrecognized class descriptor - " + classDescriptor + " - skipping class");
159                continue;
160            }
161
162            File smaliFile = fileNameHandler.getUniqueFilenameForClass(classDescriptor);
163
164            //create and initialize the top level string template
165            ClassDefinition classDefinition = new ClassDefinition(classDefItem);
166
167            //write the disassembly
168            Writer writer = null;
169            try
170            {
171                File smaliParent = smaliFile.getParentFile();
172                if (!smaliParent.exists()) {
173                    if (!smaliParent.mkdirs()) {
174                        System.err.println("Unable to create directory " + smaliParent.toString() + " - skipping class");
175                        continue;
176                    }
177                }
178
179                if (!smaliFile.exists()){
180                    if (!smaliFile.createNewFile()) {
181                        System.err.println("Unable to create file " + smaliFile.toString() + " - skipping class");
182                        continue;
183                    }
184                }
185
186                BufferedWriter bufWriter = new BufferedWriter(new OutputStreamWriter(
187                        new FileOutputStream(smaliFile), "UTF8"));
188
189                writer = new IndentingWriter(bufWriter);
190                classDefinition.writeTo((IndentingWriter)writer);
191            } catch (Exception ex) {
192                System.err.println("\n\nError occured while disassembling class " + classDescriptor.replace('/', '.') + " - skipping class");
193                ex.printStackTrace();
194            }
195            finally
196            {
197                if (writer != null) {
198                    try {
199                        writer.close();
200                    } catch (Throwable ex) {
201                        System.err.println("\n\nError occured while closing file " + smaliFile.toString());
202                        ex.printStackTrace();
203                    }
204                }
205            }
206
207            if (!ignoreErrors && classDefinition.hadValidationErrors()) {
208                System.exit(1);
209            }
210        }
211    }
212
213    private static final Pattern extJarPattern = Pattern.compile("(?:^|\\\\|/)ext.(?:jar|odex)$");
214    private static boolean isExtJar(String dexFilePath) {
215        Matcher m = extJarPattern.matcher(dexFilePath);
216        return m.find();
217    }
218}
219