main.java revision a78d169848624b154ca80c500df707c26778f8f0
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.apache.commons.cli.*; 32import org.jf.dexlib2.DexFileFactory; 33import org.jf.dexlib2.Opcode; 34import org.jf.dexlib2.dexbacked.DexBackedDexFile; 35import org.jf.util.ConsoleUtil; 36import org.jf.util.SmaliHelpFormatter; 37 38import java.io.File; 39import java.io.IOException; 40import java.io.InputStream; 41import java.util.ArrayList; 42import java.util.List; 43import java.util.Locale; 44import java.util.Properties; 45 46public class main { 47 48 public static final String VERSION; 49 50 private static final Options basicOptions; 51 private static final Options debugOptions; 52 private static final Options options; 53 54 public static final int ALL = 1; 55 public static final int ALLPRE = 2; 56 public static final int ALLPOST = 4; 57 public static final int ARGS = 8; 58 public static final int DEST = 16; 59 public static final int MERGE = 32; 60 public static final int FULLMERGE = 64; 61 62 static { 63 options = new Options(); 64 basicOptions = new Options(); 65 debugOptions = new Options(); 66 buildOptions(); 67 68 InputStream templateStream = baksmali.class.getClassLoader().getResourceAsStream("baksmali.properties"); 69 Properties properties = new Properties(); 70 String version = "(unknown)"; 71 try { 72 properties.load(templateStream); 73 version = properties.getProperty("application.version"); 74 } catch (IOException ex) { 75 } 76 VERSION = version; 77 } 78 79 /** 80 * This class is uninstantiable. 81 */ 82 private main() { 83 } 84 85 /** 86 * Run! 87 */ 88 public static void main(String[] args) { 89 Locale locale = new Locale("en", "US"); 90 Locale.setDefault(locale); 91 92 CommandLineParser parser = new PosixParser(); 93 CommandLine commandLine; 94 95 try { 96 commandLine = parser.parse(options, args); 97 } catch (ParseException ex) { 98 usage(); 99 return; 100 } 101 102 boolean disassemble = true; 103 boolean doDump = false; 104 boolean write = false; 105 boolean sort = false; 106 boolean fixRegisters = false; 107 boolean noParameterRegisters = false; 108 boolean useLocalsDirective = false; 109 boolean useSequentialLabels = false; 110 boolean outputDebugInfo = true; 111 boolean addCodeOffsets = false; 112 boolean noAccessorComments = false; 113 boolean deodex = false; 114 boolean verify = false; 115 boolean ignoreErrors = false; 116 boolean checkPackagePrivateAccess = false; 117 118 int apiLevel = 14; 119 120 int registerInfo = 0; 121 122 String outputDirectory = "out"; 123 String dumpFileName = null; 124 String outputDexFileName = null; 125 String inputDexFileName = null; 126 String bootClassPath = null; 127 StringBuffer extraBootClassPathEntries = new StringBuffer(); 128 List<String> bootClassPathDirs = new ArrayList<String>(); 129 bootClassPathDirs.add("."); 130 String inlineTable = null; 131 132 String[] remainingArgs = commandLine.getArgs(); 133 134 Option[] options = commandLine.getOptions(); 135 136 for (int i=0; i<options.length; i++) { 137 Option option = options[i]; 138 String opt = option.getOpt(); 139 140 switch (opt.charAt(0)) { 141 case 'v': 142 version(); 143 return; 144 case '?': 145 while (++i < options.length) { 146 if (options[i].getOpt().charAt(0) == '?') { 147 usage(true); 148 return; 149 } 150 } 151 usage(false); 152 return; 153 case 'o': 154 outputDirectory = commandLine.getOptionValue("o"); 155 break; 156 case 'p': 157 noParameterRegisters = true; 158 break; 159 case 'l': 160 useLocalsDirective = true; 161 break; 162 case 's': 163 useSequentialLabels = true; 164 break; 165 case 'b': 166 outputDebugInfo = false; 167 break; 168 case 'd': 169 bootClassPathDirs.add(option.getValue()); 170 break; 171 case 'f': 172 addCodeOffsets = true; 173 break; 174 case 'r': 175 String[] values = commandLine.getOptionValues('r'); 176 177 if (values == null || values.length == 0) { 178 registerInfo = ARGS | DEST; 179 } else { 180 for (String value: values) { 181 if (value.equalsIgnoreCase("ALL")) { 182 registerInfo |= ALL; 183 } else if (value.equalsIgnoreCase("ALLPRE")) { 184 registerInfo |= ALLPRE; 185 } else if (value.equalsIgnoreCase("ALLPOST")) { 186 registerInfo |= ALLPOST; 187 } else if (value.equalsIgnoreCase("ARGS")) { 188 registerInfo |= ARGS; 189 } else if (value.equalsIgnoreCase("DEST")) { 190 registerInfo |= DEST; 191 } else if (value.equalsIgnoreCase("MERGE")) { 192 registerInfo |= MERGE; 193 } else if (value.equalsIgnoreCase("FULLMERGE")) { 194 registerInfo |= FULLMERGE; 195 } else { 196 usage(); 197 return; 198 } 199 } 200 201 if ((registerInfo & FULLMERGE) != 0) { 202 registerInfo &= ~MERGE; 203 } 204 } 205 break; 206 case 'c': 207 String bcp = commandLine.getOptionValue("c"); 208 if (bcp != null && bcp.charAt(0) == ':') { 209 extraBootClassPathEntries.append(bcp); 210 } else { 211 bootClassPath = bcp; 212 } 213 break; 214 case 'x': 215 deodex = true; 216 break; 217 case 'm': 218 noAccessorComments = true; 219 break; 220 case 'a': 221 apiLevel = Integer.parseInt(commandLine.getOptionValue("a")); 222 break; 223 case 'N': 224 disassemble = false; 225 break; 226 case 'D': 227 doDump = true; 228 dumpFileName = commandLine.getOptionValue("D", inputDexFileName + ".dump"); 229 break; 230 case 'I': 231 ignoreErrors = true; 232 break; 233 case 'W': 234 write = true; 235 outputDexFileName = commandLine.getOptionValue("W"); 236 break; 237 case 'S': 238 sort = true; 239 break; 240 case 'F': 241 fixRegisters = true; 242 break; 243 case 'V': 244 verify = true; 245 break; 246 case 'T': 247 inlineTable = commandLine.getOptionValue("T"); 248 break; 249 case 'K': 250 checkPackagePrivateAccess = true; 251 break; 252 default: 253 assert false; 254 } 255 } 256 257 if (remainingArgs.length != 1) { 258 usage(); 259 return; 260 } 261 262 inputDexFileName = remainingArgs[0]; 263 264 try { 265 File dexFileFile = new File(inputDexFileName); 266 if (!dexFileFile.exists()) { 267 System.err.println("Can't find the file " + inputDexFileName); 268 System.exit(1); 269 } 270 271 Opcode.updateMapsForApiLevel(apiLevel); 272 273 //Read in and parse the dex file 274 //TODO: add "fix registers" functionality? 275 DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile); 276 277 //TODO: uncomment 278 /*if (dexFile.isOdex()) { 279 if (doDump) { 280 System.err.println("-D cannot be used with on odex file. Ignoring -D"); 281 } 282 if (write) { 283 System.err.println("-W cannot be used with an odex file. Ignoring -W"); 284 } 285 if (!deodex) { 286 System.err.println("Warning: You are disassembling an odex file without deodexing it. You"); 287 System.err.println("won't be able to re-assemble the results unless you deodex it with the -x"); 288 System.err.println("option"); 289 } 290 } else {*/ 291 deodex = false; 292 293 if (bootClassPath == null) { 294 bootClassPath = "core.jar:ext.jar:framework.jar:android.policy.jar:services.jar"; 295 } 296 //} 297 298 if (disassemble) { 299 String[] bootClassPathDirsArray = new String[bootClassPathDirs.size()]; 300 for (int i=0; i<bootClassPathDirsArray.length; i++) { 301 bootClassPathDirsArray[i] = bootClassPathDirs.get(i); 302 } 303 304 baksmali.disassembleDexFile(dexFileFile.getPath(), dexFile, deodex, outputDirectory, 305 bootClassPathDirsArray, bootClassPath, extraBootClassPathEntries.toString(), 306 noParameterRegisters, useLocalsDirective, useSequentialLabels, outputDebugInfo, addCodeOffsets, 307 noAccessorComments, registerInfo, verify, ignoreErrors, inlineTable, checkPackagePrivateAccess); 308 } 309 310 //TODO: uncomment 311 /*if ((doDump || write) && !dexFile.isOdex()) { 312 try 313 { 314 dump.dump(dexFile, dumpFileName, outputDexFileName, sort); 315 }catch (IOException ex) { 316 System.err.println("Error occured while writing dump file"); 317 ex.printStackTrace(); 318 } 319 }*/ 320 } catch (RuntimeException ex) { 321 System.err.println("\n\nUNEXPECTED TOP-LEVEL EXCEPTION:"); 322 ex.printStackTrace(); 323 System.exit(1); 324 } catch (Throwable ex) { 325 System.err.println("\n\nUNEXPECTED TOP-LEVEL ERROR:"); 326 ex.printStackTrace(); 327 System.exit(1); 328 } 329 } 330 331 /** 332 * Prints the usage message. 333 */ 334 private static void usage(boolean printDebugOptions) { 335 SmaliHelpFormatter formatter = new SmaliHelpFormatter(); 336 int consoleWidth = ConsoleUtil.getConsoleWidth(); 337 if (consoleWidth <= 0) { 338 consoleWidth = 80; 339 } 340 341 formatter.setWidth(consoleWidth); 342 343 formatter.printHelp("java -jar baksmali.jar [options] <dex-file>", 344 "disassembles and/or dumps a dex file", basicOptions, printDebugOptions?debugOptions:null); 345 } 346 347 private static void usage() { 348 usage(false); 349 } 350 351 /** 352 * Prints the version message. 353 */ 354 protected static void version() { 355 System.out.println("baksmali " + VERSION + " (http://smali.googlecode.com)"); 356 System.out.println("Copyright (C) 2010 Ben Gruver (JesusFreke@JesusFreke.com)"); 357 System.out.println("BSD license (http://www.opensource.org/licenses/bsd-license.php)"); 358 System.exit(0); 359 } 360 361 private static void buildOptions() { 362 Option versionOption = OptionBuilder.withLongOpt("version") 363 .withDescription("prints the version then exits") 364 .create("v"); 365 366 Option helpOption = OptionBuilder.withLongOpt("help") 367 .withDescription("prints the help message then exits. Specify twice for debug options") 368 .create("?"); 369 370 Option outputDirOption = OptionBuilder.withLongOpt("output") 371 .withDescription("the directory where the disassembled files will be placed. The default is out") 372 .hasArg() 373 .withArgName("DIR") 374 .create("o"); 375 376 Option noParameterRegistersOption = OptionBuilder.withLongOpt("no-parameter-registers") 377 .withDescription("use the v<n> syntax instead of the p<n> syntax for registers mapped to method " + 378 "parameters") 379 .create("p"); 380 381 Option deodexerantOption = OptionBuilder.withLongOpt("deodex") 382 .withDescription("deodex the given odex file. This option is ignored if the input file is not an " + 383 "odex file") 384 .create("x"); 385 386 Option useLocalsOption = OptionBuilder.withLongOpt("use-locals") 387 .withDescription("output the .locals directive with the number of non-parameter registers, rather" + 388 " than the .register directive with the total number of register") 389 .create("l"); 390 391 Option sequentialLabelsOption = OptionBuilder.withLongOpt("sequential-labels") 392 .withDescription("create label names using a sequential numbering scheme per label type, rather than " + 393 "using the bytecode address") 394 .create("s"); 395 396 Option noDebugInfoOption = OptionBuilder.withLongOpt("no-debug-info") 397 .withDescription("don't write out debug info (.local, .param, .line, etc.)") 398 .create("b"); 399 400 Option registerInfoOption = OptionBuilder.withLongOpt("register-info") 401 .hasOptionalArgs() 402 .withArgName("REGISTER_INFO_TYPES") 403 .withValueSeparator(',') 404 .withDescription("print the specificed type(s) of register information for each instruction. " + 405 "\"ARGS,DEST\" is the default if no types are specified.\nValid values are:\nALL: all " + 406 "pre- and post-instruction registers.\nALLPRE: all pre-instruction registers\nALLPOST: all " + 407 "post-instruction registers\nARGS: any pre-instruction registers used as arguments to the " + 408 "instruction\nDEST: the post-instruction destination register, if any\nMERGE: Any " + 409 "pre-instruction register has been merged from more than 1 different post-instruction " + 410 "register from its predecessors\nFULLMERGE: For each register that would be printed by " + 411 "MERGE, also show the incoming register types that were merged") 412 .create("r"); 413 414 Option classPathOption = OptionBuilder.withLongOpt("bootclasspath") 415 .withDescription("the bootclasspath jars to use, for analysis. Defaults to " + 416 "core.jar:ext.jar:framework.jar:android.policy.jar:services.jar. If the value begins with a " + 417 ":, it will be appended to the default bootclasspath instead of replacing it") 418 .hasOptionalArg() 419 .withArgName("BOOTCLASSPATH") 420 .create("c"); 421 422 Option classPathDirOption = OptionBuilder.withLongOpt("bootclasspath-dir") 423 .withDescription("the base folder to look for the bootclasspath files in. Defaults to the current " + 424 "directory") 425 .hasArg() 426 .withArgName("DIR") 427 .create("d"); 428 429 Option codeOffsetOption = OptionBuilder.withLongOpt("code-offsets") 430 .withDescription("add comments to the disassembly containing the code offset for each address") 431 .create("f"); 432 433 Option noAccessorCommentsOption = OptionBuilder.withLongOpt("no-accessor-comments") 434 .withDescription("don't output helper comments for synthetic accessors") 435 .create("m"); 436 437 Option apiLevelOption = OptionBuilder.withLongOpt("api-level") 438 .withDescription("The numeric api-level of the file being disassembled. If not " + 439 "specified, it defaults to 14 (ICS).") 440 .hasArg() 441 .withArgName("API_LEVEL") 442 .create("a"); 443 444 Option dumpOption = OptionBuilder.withLongOpt("dump-to") 445 .withDescription("dumps the given dex file into a single annotated dump file named FILE" + 446 " (<dexfile>.dump by default), along with the normal disassembly") 447 .hasOptionalArg() 448 .withArgName("FILE") 449 .create("D"); 450 451 Option ignoreErrorsOption = OptionBuilder.withLongOpt("ignore-errors") 452 .withDescription("ignores any non-fatal errors that occur while disassembling/deodexing," + 453 " ignoring the class if needed, and continuing with the next class. The default" + 454 " behavior is to stop disassembling and exit once an error is encountered") 455 .create("I"); 456 457 458 Option noDisassemblyOption = OptionBuilder.withLongOpt("no-disassembly") 459 .withDescription("suppresses the output of the disassembly") 460 .create("N"); 461 462 Option writeDexOption = OptionBuilder.withLongOpt("write-dex") 463 .withDescription("additionally rewrites the input dex file to FILE") 464 .hasArg() 465 .withArgName("FILE") 466 .create("W"); 467 468 Option sortOption = OptionBuilder.withLongOpt("sort") 469 .withDescription("sort the items in the dex file into a canonical order before dumping/writing") 470 .create("S"); 471 472 Option fixSignedRegisterOption = OptionBuilder.withLongOpt("fix-signed-registers") 473 .withDescription("when dumping or rewriting, fix any registers in the debug info that are encoded as" + 474 " a signed value") 475 .create("F"); 476 477 Option verifyDexOption = OptionBuilder.withLongOpt("verify") 478 .withDescription("perform bytecode verification") 479 .create("V"); 480 481 Option inlineTableOption = OptionBuilder.withLongOpt("inline-table") 482 .withDescription("specify a file containing a custom inline method table to use for deodexing") 483 .hasArg() 484 .withArgName("FILE") 485 .create("T"); 486 487 Option checkPackagePrivateAccess = OptionBuilder.withLongOpt("check-package-private-access") 488 .withDescription("When deodexing, use the new virtual table generation logic that " + 489 "prevents overriding an inaccessible package private method. This is a temporary option " + 490 "that will be removed once this new functionality can be tied to a specific api level.") 491 .create("K"); 492 493 basicOptions.addOption(versionOption); 494 basicOptions.addOption(helpOption); 495 basicOptions.addOption(outputDirOption); 496 basicOptions.addOption(noParameterRegistersOption); 497 basicOptions.addOption(deodexerantOption); 498 basicOptions.addOption(useLocalsOption); 499 basicOptions.addOption(sequentialLabelsOption); 500 basicOptions.addOption(noDebugInfoOption); 501 basicOptions.addOption(registerInfoOption); 502 basicOptions.addOption(classPathOption); 503 basicOptions.addOption(classPathDirOption); 504 basicOptions.addOption(codeOffsetOption); 505 basicOptions.addOption(noAccessorCommentsOption); 506 basicOptions.addOption(apiLevelOption); 507 508 debugOptions.addOption(dumpOption); 509 debugOptions.addOption(ignoreErrorsOption); 510 debugOptions.addOption(noDisassemblyOption); 511 debugOptions.addOption(writeDexOption); 512 debugOptions.addOption(sortOption); 513 debugOptions.addOption(fixSignedRegisterOption); 514 debugOptions.addOption(verifyDexOption); 515 debugOptions.addOption(inlineTableOption); 516 debugOptions.addOption(checkPackagePrivateAccess); 517 518 for (Object option: basicOptions.getOptions()) { 519 options.addOption((Option)option); 520 } 521 for (Object option: debugOptions.getOptions()) { 522 options.addOption((Option)option); 523 } 524 } 525}