main.java revision 373ff22ec69bb6e93646994347b6d80502be1588
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: implement rewrite + optional sort functionality 311 312 // TODO: need to check if odex file 313 if (doDump) { 314 try 315 { 316 dump.dump(dexFile, dumpFileName); 317 }catch (IOException ex) { 318 System.err.println("Error occured while writing dump file"); 319 ex.printStackTrace(); 320 } 321 } 322 } catch (RuntimeException ex) { 323 System.err.println("\n\nUNEXPECTED TOP-LEVEL EXCEPTION:"); 324 ex.printStackTrace(); 325 System.exit(1); 326 } catch (Throwable ex) { 327 System.err.println("\n\nUNEXPECTED TOP-LEVEL ERROR:"); 328 ex.printStackTrace(); 329 System.exit(1); 330 } 331 } 332 333 /** 334 * Prints the usage message. 335 */ 336 private static void usage(boolean printDebugOptions) { 337 SmaliHelpFormatter formatter = new SmaliHelpFormatter(); 338 int consoleWidth = ConsoleUtil.getConsoleWidth(); 339 if (consoleWidth <= 0) { 340 consoleWidth = 80; 341 } 342 343 formatter.setWidth(consoleWidth); 344 345 formatter.printHelp("java -jar baksmali.jar [options] <dex-file>", 346 "disassembles and/or dumps a dex file", basicOptions, printDebugOptions?debugOptions:null); 347 } 348 349 private static void usage() { 350 usage(false); 351 } 352 353 /** 354 * Prints the version message. 355 */ 356 protected static void version() { 357 System.out.println("baksmali " + VERSION + " (http://smali.googlecode.com)"); 358 System.out.println("Copyright (C) 2010 Ben Gruver (JesusFreke@JesusFreke.com)"); 359 System.out.println("BSD license (http://www.opensource.org/licenses/bsd-license.php)"); 360 System.exit(0); 361 } 362 363 private static void buildOptions() { 364 Option versionOption = OptionBuilder.withLongOpt("version") 365 .withDescription("prints the version then exits") 366 .create("v"); 367 368 Option helpOption = OptionBuilder.withLongOpt("help") 369 .withDescription("prints the help message then exits. Specify twice for debug options") 370 .create("?"); 371 372 Option outputDirOption = OptionBuilder.withLongOpt("output") 373 .withDescription("the directory where the disassembled files will be placed. The default is out") 374 .hasArg() 375 .withArgName("DIR") 376 .create("o"); 377 378 Option noParameterRegistersOption = OptionBuilder.withLongOpt("no-parameter-registers") 379 .withDescription("use the v<n> syntax instead of the p<n> syntax for registers mapped to method " + 380 "parameters") 381 .create("p"); 382 383 Option deodexerantOption = OptionBuilder.withLongOpt("deodex") 384 .withDescription("deodex the given odex file. This option is ignored if the input file is not an " + 385 "odex file") 386 .create("x"); 387 388 Option useLocalsOption = OptionBuilder.withLongOpt("use-locals") 389 .withDescription("output the .locals directive with the number of non-parameter registers, rather" + 390 " than the .register directive with the total number of register") 391 .create("l"); 392 393 Option sequentialLabelsOption = OptionBuilder.withLongOpt("sequential-labels") 394 .withDescription("create label names using a sequential numbering scheme per label type, rather than " + 395 "using the bytecode address") 396 .create("s"); 397 398 Option noDebugInfoOption = OptionBuilder.withLongOpt("no-debug-info") 399 .withDescription("don't write out debug info (.local, .param, .line, etc.)") 400 .create("b"); 401 402 Option registerInfoOption = OptionBuilder.withLongOpt("register-info") 403 .hasOptionalArgs() 404 .withArgName("REGISTER_INFO_TYPES") 405 .withValueSeparator(',') 406 .withDescription("print the specificed type(s) of register information for each instruction. " + 407 "\"ARGS,DEST\" is the default if no types are specified.\nValid values are:\nALL: all " + 408 "pre- and post-instruction registers.\nALLPRE: all pre-instruction registers\nALLPOST: all " + 409 "post-instruction registers\nARGS: any pre-instruction registers used as arguments to the " + 410 "instruction\nDEST: the post-instruction destination register, if any\nMERGE: Any " + 411 "pre-instruction register has been merged from more than 1 different post-instruction " + 412 "register from its predecessors\nFULLMERGE: For each register that would be printed by " + 413 "MERGE, also show the incoming register types that were merged") 414 .create("r"); 415 416 Option classPathOption = OptionBuilder.withLongOpt("bootclasspath") 417 .withDescription("the bootclasspath jars to use, for analysis. Defaults to " + 418 "core.jar:ext.jar:framework.jar:android.policy.jar:services.jar. If the value begins with a " + 419 ":, it will be appended to the default bootclasspath instead of replacing it") 420 .hasOptionalArg() 421 .withArgName("BOOTCLASSPATH") 422 .create("c"); 423 424 Option classPathDirOption = OptionBuilder.withLongOpt("bootclasspath-dir") 425 .withDescription("the base folder to look for the bootclasspath files in. Defaults to the current " + 426 "directory") 427 .hasArg() 428 .withArgName("DIR") 429 .create("d"); 430 431 Option codeOffsetOption = OptionBuilder.withLongOpt("code-offsets") 432 .withDescription("add comments to the disassembly containing the code offset for each address") 433 .create("f"); 434 435 Option noAccessorCommentsOption = OptionBuilder.withLongOpt("no-accessor-comments") 436 .withDescription("don't output helper comments for synthetic accessors") 437 .create("m"); 438 439 Option apiLevelOption = OptionBuilder.withLongOpt("api-level") 440 .withDescription("The numeric api-level of the file being disassembled. If not " + 441 "specified, it defaults to 14 (ICS).") 442 .hasArg() 443 .withArgName("API_LEVEL") 444 .create("a"); 445 446 Option dumpOption = OptionBuilder.withLongOpt("dump-to") 447 .withDescription("dumps the given dex file into a single annotated dump file named FILE" + 448 " (<dexfile>.dump by default), along with the normal disassembly") 449 .hasOptionalArg() 450 .withArgName("FILE") 451 .create("D"); 452 453 Option ignoreErrorsOption = OptionBuilder.withLongOpt("ignore-errors") 454 .withDescription("ignores any non-fatal errors that occur while disassembling/deodexing," + 455 " ignoring the class if needed, and continuing with the next class. The default" + 456 " behavior is to stop disassembling and exit once an error is encountered") 457 .create("I"); 458 459 460 Option noDisassemblyOption = OptionBuilder.withLongOpt("no-disassembly") 461 .withDescription("suppresses the output of the disassembly") 462 .create("N"); 463 464 Option writeDexOption = OptionBuilder.withLongOpt("write-dex") 465 .withDescription("additionally rewrites the input dex file to FILE") 466 .hasArg() 467 .withArgName("FILE") 468 .create("W"); 469 470 Option sortOption = OptionBuilder.withLongOpt("sort") 471 .withDescription("sort the items in the dex file into a canonical order before dumping/writing") 472 .create("S"); 473 474 Option fixSignedRegisterOption = OptionBuilder.withLongOpt("fix-signed-registers") 475 .withDescription("when dumping or rewriting, fix any registers in the debug info that are encoded as" + 476 " a signed value") 477 .create("F"); 478 479 Option verifyDexOption = OptionBuilder.withLongOpt("verify") 480 .withDescription("perform bytecode verification") 481 .create("V"); 482 483 Option inlineTableOption = OptionBuilder.withLongOpt("inline-table") 484 .withDescription("specify a file containing a custom inline method table to use for deodexing") 485 .hasArg() 486 .withArgName("FILE") 487 .create("T"); 488 489 Option checkPackagePrivateAccess = OptionBuilder.withLongOpt("check-package-private-access") 490 .withDescription("When deodexing, use the new virtual table generation logic that " + 491 "prevents overriding an inaccessible package private method. This is a temporary option " + 492 "that will be removed once this new functionality can be tied to a specific api level.") 493 .create("K"); 494 495 basicOptions.addOption(versionOption); 496 basicOptions.addOption(helpOption); 497 basicOptions.addOption(outputDirOption); 498 basicOptions.addOption(noParameterRegistersOption); 499 basicOptions.addOption(deodexerantOption); 500 basicOptions.addOption(useLocalsOption); 501 basicOptions.addOption(sequentialLabelsOption); 502 basicOptions.addOption(noDebugInfoOption); 503 basicOptions.addOption(registerInfoOption); 504 basicOptions.addOption(classPathOption); 505 basicOptions.addOption(classPathDirOption); 506 basicOptions.addOption(codeOffsetOption); 507 basicOptions.addOption(noAccessorCommentsOption); 508 basicOptions.addOption(apiLevelOption); 509 510 debugOptions.addOption(dumpOption); 511 debugOptions.addOption(ignoreErrorsOption); 512 debugOptions.addOption(noDisassemblyOption); 513 debugOptions.addOption(writeDexOption); 514 debugOptions.addOption(sortOption); 515 debugOptions.addOption(fixSignedRegisterOption); 516 debugOptions.addOption(verifyDexOption); 517 debugOptions.addOption(inlineTableOption); 518 debugOptions.addOption(checkPackagePrivateAccess); 519 520 for (Object option: basicOptions.getOptions()) { 521 options.addOption((Option)option); 522 } 523 for (Object option: debugOptions.getOptions()) { 524 options.addOption((Option)option); 525 } 526 } 527}