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