main.java revision 65cb1628a00f853705955056f4c4e7161ad124fb
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 'R': 219 String rif = commandLine.getOptionValue("R"); 220 options.setResourceIdFiles(rif); 221 break; 222 default: 223 assert false; 224 } 225 } 226 227 if (remainingArgs.length != 1) { 228 usage(); 229 return; 230 } 231 232 if (options.jobs <= 0) { 233 options.jobs = Runtime.getRuntime().availableProcessors(); 234 if (options.jobs > 6) { 235 options.jobs = 6; 236 } 237 } 238 239 if (options.apiLevel >= 17) { 240 options.checkPackagePrivateAccess = true; 241 } 242 243 String inputDexFileName = remainingArgs[0]; 244 245 File dexFileFile = new File(inputDexFileName); 246 if (!dexFileFile.exists()) { 247 System.err.println("Can't find the file " + inputDexFileName); 248 System.exit(1); 249 } 250 251 //Read in and parse the dex file 252 DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.apiLevel); 253 254 if (dexFile.isOdexFile()) { 255 if (!options.deodex) { 256 System.err.println("Warning: You are disassembling an odex file without deodexing it. You"); 257 System.err.println("won't be able to re-assemble the results unless you deodex it with the -x"); 258 System.err.println("option"); 259 options.allowOdex = true; 260 } 261 } else { 262 options.deodex = false; 263 } 264 265 if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) { 266 if (dexFile instanceof DexBackedOdexFile) { 267 options.bootClassPathEntries = ((DexBackedOdexFile)dexFile).getDependencies(); 268 } else { 269 options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel); 270 } 271 } 272 273 if (options.inlineResolver == null && dexFile instanceof DexBackedOdexFile) { 274 options.inlineResolver = 275 InlineMethodResolver.createInlineMethodResolver(((DexBackedOdexFile)dexFile).getOdexVersion()); 276 } 277 278 boolean errorOccurred = false; 279 if (disassemble) { 280 errorOccurred = !baksmali.disassembleDexFile(dexFile, options); 281 } 282 283 if (doDump) { 284 if (dumpFileName == null) { 285 dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump"); 286 } 287 dump.dump(dexFile, dumpFileName, options.apiLevel); 288 } 289 290 if (errorOccurred) { 291 System.exit(1); 292 } 293 } 294 295 /** 296 * Prints the usage message. 297 */ 298 private static void usage(boolean printDebugOptions) { 299 SmaliHelpFormatter formatter = new SmaliHelpFormatter(); 300 int consoleWidth = ConsoleUtil.getConsoleWidth(); 301 if (consoleWidth <= 0) { 302 consoleWidth = 80; 303 } 304 305 formatter.setWidth(consoleWidth); 306 307 formatter.printHelp("java -jar baksmali.jar [options] <dex-file>", 308 "disassembles and/or dumps a dex file", basicOptions, printDebugOptions?debugOptions:null); 309 } 310 311 private static void usage() { 312 usage(false); 313 } 314 315 /** 316 * Prints the version message. 317 */ 318 protected static void version() { 319 System.out.println("baksmali " + VERSION + " (http://smali.googlecode.com)"); 320 System.out.println("Copyright (C) 2010 Ben Gruver (JesusFreke@JesusFreke.com)"); 321 System.out.println("BSD license (http://www.opensource.org/licenses/bsd-license.php)"); 322 System.exit(0); 323 } 324 325 @SuppressWarnings("AccessStaticViaInstance") 326 private static void buildOptions() { 327 Option versionOption = OptionBuilder.withLongOpt("version") 328 .withDescription("prints the version then exits") 329 .create("v"); 330 331 Option helpOption = OptionBuilder.withLongOpt("help") 332 .withDescription("prints the help message then exits. Specify twice for debug options") 333 .create("?"); 334 335 Option outputDirOption = OptionBuilder.withLongOpt("output") 336 .withDescription("the directory where the disassembled files will be placed. The default is out") 337 .hasArg() 338 .withArgName("DIR") 339 .create("o"); 340 341 Option noParameterRegistersOption = OptionBuilder.withLongOpt("no-parameter-registers") 342 .withDescription("use the v<n> syntax instead of the p<n> syntax for registers mapped to method " + 343 "parameters") 344 .create("p"); 345 346 Option deodexerantOption = OptionBuilder.withLongOpt("deodex") 347 .withDescription("deodex the given odex file. This option is ignored if the input file is not an " + 348 "odex file") 349 .create("x"); 350 351 Option useLocalsOption = OptionBuilder.withLongOpt("use-locals") 352 .withDescription("output the .locals directive with the number of non-parameter registers, rather" + 353 " than the .register directive with the total number of register") 354 .create("l"); 355 356 Option sequentialLabelsOption = OptionBuilder.withLongOpt("sequential-labels") 357 .withDescription("create label names using a sequential numbering scheme per label type, rather than " + 358 "using the bytecode address") 359 .create("s"); 360 361 Option noDebugInfoOption = OptionBuilder.withLongOpt("no-debug-info") 362 .withDescription("don't write out debug info (.local, .param, .line, etc.)") 363 .create("b"); 364 365 Option registerInfoOption = OptionBuilder.withLongOpt("register-info") 366 .hasOptionalArgs() 367 .withArgName("REGISTER_INFO_TYPES") 368 .withValueSeparator(',') 369 .withDescription("print the specificed type(s) of register information for each instruction. " + 370 "\"ARGS,DEST\" is the default if no types are specified.\nValid values are:\nALL: all " + 371 "pre- and post-instruction registers.\nALLPRE: all pre-instruction registers\nALLPOST: all " + 372 "post-instruction registers\nARGS: any pre-instruction registers used as arguments to the " + 373 "instruction\nDEST: the post-instruction destination register, if any\nMERGE: Any " + 374 "pre-instruction register has been merged from more than 1 different post-instruction " + 375 "register from its predecessors\nFULLMERGE: For each register that would be printed by " + 376 "MERGE, also show the incoming register types that were merged") 377 .create("r"); 378 379 Option classPathOption = OptionBuilder.withLongOpt("bootclasspath") 380 .withDescription("the bootclasspath jars to use, for analysis. Defaults to " + 381 "core.jar:ext.jar:framework.jar:android.policy.jar:services.jar. If the value begins with a " + 382 ":, it will be appended to the default bootclasspath instead of replacing it") 383 .hasOptionalArg() 384 .withArgName("BOOTCLASSPATH") 385 .create("c"); 386 387 Option classPathDirOption = OptionBuilder.withLongOpt("bootclasspath-dir") 388 .withDescription("the base folder to look for the bootclasspath files in. Defaults to the current " + 389 "directory") 390 .hasArg() 391 .withArgName("DIR") 392 .create("d"); 393 394 Option codeOffsetOption = OptionBuilder.withLongOpt("code-offsets") 395 .withDescription("add comments to the disassembly containing the code offset for each address") 396 .create("f"); 397 398 Option noAccessorCommentsOption = OptionBuilder.withLongOpt("no-accessor-comments") 399 .withDescription("don't output helper comments for synthetic accessors") 400 .create("m"); 401 402 Option apiLevelOption = OptionBuilder.withLongOpt("api-level") 403 .withDescription("The numeric api-level of the file being disassembled. If not " + 404 "specified, it defaults to 15 (ICS).") 405 .hasArg() 406 .withArgName("API_LEVEL") 407 .create("a"); 408 409 Option jobsOption = OptionBuilder.withLongOpt("jobs") 410 .withDescription("The number of threads to use. Defaults to the number of cores available, up to a " + 411 "maximum of 6") 412 .hasArg() 413 .withArgName("NUM_THREADS") 414 .create("j"); 415 416 Option resourceIdFilesOption = OptionBuilder.withLongOpt("resource-id-files") 417 .withDescription("the resource ID files to use, for analysis. A colon-separated list of prefix=file " + 418 "pairs. For example R=res/values/public.xml:" + 419 "android.R=$ANDROID_HOME/platforms/android-19/data/res/values/public.xml") 420 .hasArg() 421 .withArgName("FILES") 422 .create("i"); 423 424 Option dumpOption = OptionBuilder.withLongOpt("dump-to") 425 .withDescription("dumps the given dex file into a single annotated dump file named FILE" + 426 " (<dexfile>.dump by default), along with the normal disassembly") 427 .hasOptionalArg() 428 .withArgName("FILE") 429 .create("D"); 430 431 Option ignoreErrorsOption = OptionBuilder.withLongOpt("ignore-errors") 432 .withDescription("ignores any non-fatal errors that occur while disassembling/deodexing," + 433 " ignoring the class if needed, and continuing with the next class. The default" + 434 " behavior is to stop disassembling and exit once an error is encountered") 435 .create("I"); 436 437 Option noDisassemblyOption = OptionBuilder.withLongOpt("no-disassembly") 438 .withDescription("suppresses the output of the disassembly") 439 .create("N"); 440 441 Option inlineTableOption = OptionBuilder.withLongOpt("inline-table") 442 .withDescription("specify a file containing a custom inline method table to use for deodexing") 443 .hasArg() 444 .withArgName("FILE") 445 .create("T"); 446 447 basicOptions.addOption(versionOption); 448 basicOptions.addOption(helpOption); 449 basicOptions.addOption(outputDirOption); 450 basicOptions.addOption(noParameterRegistersOption); 451 basicOptions.addOption(deodexerantOption); 452 basicOptions.addOption(useLocalsOption); 453 basicOptions.addOption(sequentialLabelsOption); 454 basicOptions.addOption(noDebugInfoOption); 455 basicOptions.addOption(registerInfoOption); 456 basicOptions.addOption(classPathOption); 457 basicOptions.addOption(classPathDirOption); 458 basicOptions.addOption(codeOffsetOption); 459 basicOptions.addOption(noAccessorCommentsOption); 460 basicOptions.addOption(apiLevelOption); 461 basicOptions.addOption(jobsOption); 462 basicOptions.addOption(resourceIdFilesOption); 463 464 debugOptions.addOption(dumpOption); 465 debugOptions.addOption(ignoreErrorsOption); 466 debugOptions.addOption(noDisassemblyOption); 467 debugOptions.addOption(inlineTableOption); 468 469 for (Object option: basicOptions.getOptions()) { 470 options.addOption((Option)option); 471 } 472 for (Object option: debugOptions.getOptions()) { 473 options.addOption((Option)option); 474 } 475 } 476 477 @Nonnull 478 private static List<String> getDefaultBootClassPathForApi(int apiLevel) { 479 if (apiLevel < 9) { 480 return Lists.newArrayList( 481 "/system/framework/core.jar", 482 "/system/framework/ext.jar", 483 "/system/framework/framework.jar", 484 "/system/framework/android.policy.jar", 485 "/system/framework/services.jar"); 486 } else if (apiLevel < 12) { 487 return Lists.newArrayList( 488 "/system/framework/core.jar", 489 "/system/framework/bouncycastle.jar", 490 "/system/framework/ext.jar", 491 "/system/framework/framework.jar", 492 "/system/framework/android.policy.jar", 493 "/system/framework/services.jar", 494 "/system/framework/core-junit.jar"); 495 } else if (apiLevel < 14) { 496 return Lists.newArrayList( 497 "/system/framework/core.jar", 498 "/system/framework/apache-xml.jar", 499 "/system/framework/bouncycastle.jar", 500 "/system/framework/ext.jar", 501 "/system/framework/framework.jar", 502 "/system/framework/android.policy.jar", 503 "/system/framework/services.jar", 504 "/system/framework/core-junit.jar"); 505 } else if (apiLevel < 16) { 506 return Lists.newArrayList( 507 "/system/framework/core.jar", 508 "/system/framework/core-junit.jar", 509 "/system/framework/bouncycastle.jar", 510 "/system/framework/ext.jar", 511 "/system/framework/framework.jar", 512 "/system/framework/android.policy.jar", 513 "/system/framework/services.jar", 514 "/system/framework/apache-xml.jar", 515 "/system/framework/filterfw.jar"); 516 517 } else { 518 // this is correct as of api 17/4.2.2 519 return Lists.newArrayList( 520 "/system/framework/core.jar", 521 "/system/framework/core-junit.jar", 522 "/system/framework/bouncycastle.jar", 523 "/system/framework/ext.jar", 524 "/system/framework/framework.jar", 525 "/system/framework/telephony-common.jar", 526 "/system/framework/mms-common.jar", 527 "/system/framework/android.policy.jar", 528 "/system/framework/services.jar", 529 "/system/framework/apache-xml.jar"); 530 } 531 } 532} 533