MethodDefinition.java revision c91b03ba45ccacfa7b0ad52592a42e8fd8c18da1
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.Adaptors; 30 31import com.google.common.collect.ImmutableList; 32import org.jf.baksmali.Adaptors.Debug.DebugMethodItem; 33import org.jf.baksmali.Adaptors.Format.InstructionMethodItemFactory; 34import org.jf.baksmali.baksmali; 35import org.jf.dexlib2.AccessFlags; 36import org.jf.dexlib2.Format; 37import org.jf.dexlib2.Opcode; 38import org.jf.dexlib2.ReferenceType; 39import org.jf.dexlib2.analysis.AnalysisException; 40import org.jf.dexlib2.analysis.AnalyzedInstruction; 41import org.jf.dexlib2.analysis.MethodAnalyzer; 42import org.jf.dexlib2.iface.*; 43import org.jf.dexlib2.iface.debug.DebugItem; 44import org.jf.dexlib2.iface.instruction.Instruction; 45import org.jf.dexlib2.iface.instruction.OffsetInstruction; 46import org.jf.dexlib2.iface.instruction.ReferenceInstruction; 47import org.jf.dexlib2.iface.reference.MethodReference; 48import org.jf.dexlib2.util.InstructionOffsetMap; 49import org.jf.dexlib2.util.ReferenceUtil; 50import org.jf.dexlib2.util.SyntheticAccessorResolver; 51import org.jf.dexlib2.util.TypeUtils; 52import org.jf.util.ExceptionWithContext; 53import org.jf.util.IndentingWriter; 54import org.jf.util.SparseIntArray; 55 56import javax.annotation.Nonnull; 57import java.io.IOException; 58import java.util.*; 59 60public class MethodDefinition { 61 @Nonnull public final ClassDefinition classDef; 62 @Nonnull public final Method method; 63 @Nonnull public final MethodImplementation methodImpl; 64 @Nonnull public final ImmutableList<Instruction> instructions; 65 @Nonnull public final ImmutableList<MethodParameter> methodParameters; 66 public RegisterFormatter registerFormatter; 67 68 @Nonnull private final LabelCache labelCache = new LabelCache(); 69 70 @Nonnull private final SparseIntArray packedSwitchMap; 71 @Nonnull private final SparseIntArray sparseSwitchMap; 72 @Nonnull private final InstructionOffsetMap instructionOffsetMap; 73 74 public MethodDefinition(@Nonnull ClassDefinition classDef, @Nonnull Method method, 75 @Nonnull MethodImplementation methodImpl) { 76 this.classDef = classDef; 77 this.method = method; 78 this.methodImpl = methodImpl; 79 80 try { 81 //TODO: what about try/catch blocks inside the dead code? those will need to be commented out too. ugh. 82 83 instructions = ImmutableList.copyOf(methodImpl.getInstructions()); 84 methodParameters = ImmutableList.copyOf(method.getParameters()); 85 86 packedSwitchMap = new SparseIntArray(0); 87 sparseSwitchMap = new SparseIntArray(0); 88 instructionOffsetMap = new InstructionOffsetMap(instructions); 89 90 for (int i=0; i<instructions.size(); i++) { 91 Instruction instruction = instructions.get(i); 92 93 Opcode opcode = instruction.getOpcode(); 94 if (opcode == Opcode.PACKED_SWITCH) { 95 int codeOffset = instructionOffsetMap.getInstructionCodeOffset(i); 96 int targetOffset = codeOffset + ((OffsetInstruction)instruction).getCodeOffset(); 97 targetOffset = findSwitchPayload(targetOffset, Opcode.PACKED_SWITCH_PAYLOAD); 98 packedSwitchMap.append(targetOffset, codeOffset); 99 } else if (opcode == Opcode.SPARSE_SWITCH) { 100 int codeOffset = instructionOffsetMap.getInstructionCodeOffset(i); 101 int targetOffset = codeOffset + ((OffsetInstruction)instruction).getCodeOffset(); 102 targetOffset = findSwitchPayload(targetOffset, Opcode.SPARSE_SWITCH_PAYLOAD); 103 sparseSwitchMap.append(targetOffset, codeOffset); 104 } 105 } 106 }catch (Exception ex) { 107 String methodString; 108 try { 109 methodString = ReferenceUtil.getMethodDescriptor(method); 110 } catch (Exception ex2) { 111 throw ExceptionWithContext.withContext(ex, "Error while processing method"); 112 } 113 throw ExceptionWithContext.withContext(ex, "Error while processing method %s", methodString); 114 } 115 } 116 117 public static void writeEmptyMethodTo(IndentingWriter writer, Method method) throws IOException { 118 writer.write(".method "); 119 writeAccessFlags(writer, method.getAccessFlags()); 120 writer.write(method.getName()); 121 writer.write("("); 122 ImmutableList<MethodParameter> methodParameters = ImmutableList.copyOf(method.getParameters()); 123 for (MethodParameter parameter: methodParameters) { 124 writer.write(parameter.getType()); 125 } 126 writer.write(")"); 127 writer.write(method.getReturnType()); 128 writer.write('\n'); 129 130 writer.indent(4); 131 writeParameters(writer, method, methodParameters); 132 AnnotationFormatter.writeTo(writer, method.getAnnotations()); 133 writer.deindent(4); 134 writer.write(".end method\n"); 135 } 136 137 public void writeTo(IndentingWriter writer) throws IOException { 138 int parameterRegisterCount = 0; 139 if (!AccessFlags.STATIC.isSet(method.getAccessFlags())) { 140 parameterRegisterCount++; 141 } 142 143 writer.write(".method "); 144 writeAccessFlags(writer, method.getAccessFlags()); 145 writer.write(method.getName()); 146 writer.write("("); 147 for (MethodParameter parameter: methodParameters) { 148 String type = parameter.getType(); 149 writer.write(type); 150 parameterRegisterCount++; 151 if (TypeUtils.isWideType(type)) { 152 parameterRegisterCount++; 153 } 154 } 155 writer.write(")"); 156 writer.write(method.getReturnType()); 157 writer.write('\n'); 158 159 writer.indent(4); 160 if (baksmali.useLocalsDirective) { 161 writer.write(".locals "); 162 writer.printSignedIntAsDec(methodImpl.getRegisterCount() - parameterRegisterCount); 163 } else { 164 writer.write(".registers "); 165 writer.printSignedIntAsDec(methodImpl.getRegisterCount()); 166 } 167 writer.write('\n'); 168 writeParameters(writer, method, methodParameters); 169 170 if (registerFormatter == null) { 171 registerFormatter = new RegisterFormatter(methodImpl.getRegisterCount(), parameterRegisterCount); 172 } 173 174 AnnotationFormatter.writeTo(writer, method.getAnnotations()); 175 176 writer.write('\n'); 177 178 List<MethodItem> methodItems = getMethodItems(); 179 int size = methodItems.size(); 180 for (int i=0; i<size; i++) { 181 MethodItem methodItem = methodItems.get(i); 182 if (methodItem.writeTo(writer)) { 183 writer.write('\n'); 184 } 185 } 186 writer.deindent(4); 187 writer.write(".end method\n"); 188 } 189 190 private int findSwitchPayload(int targetOffset, Opcode type) { 191 int targetIndex = instructionOffsetMap.getInstructionIndexAtCodeOffset(targetOffset); 192 193 //TODO: does dalvik let you pad with multiple nops? 194 //TODO: does dalvik let a switch instruction point to a non-payload instruction? 195 196 Instruction instruction = instructions.get(targetIndex); 197 if (instruction.getOpcode() != type) { 198 // maybe it's pointing to a NOP padding instruction. Look at the next instruction 199 if (instruction.getOpcode() == Opcode.NOP) { 200 targetIndex += 1; 201 if (targetIndex < instructions.size()) { 202 instruction = instructions.get(targetIndex); 203 if (instruction.getOpcode() == type) { 204 return instructionOffsetMap.getInstructionCodeOffset(targetIndex); 205 } 206 } 207 } 208 throw new ExceptionWithContext("No switch payload at offset 0x%x", targetOffset); 209 } else { 210 return targetOffset; 211 } 212 } 213 214 private static void writeAccessFlags(IndentingWriter writer, int accessFlags) 215 throws IOException { 216 for (AccessFlags accessFlag: AccessFlags.getAccessFlagsForMethod(accessFlags)) { 217 writer.write(accessFlag.toString()); 218 writer.write(' '); 219 } 220 } 221 222 private static void writeParameters(IndentingWriter writer, Method method, 223 List<? extends MethodParameter> parameters) throws IOException { 224 boolean isStatic = AccessFlags.STATIC.isSet(method.getAccessFlags()); 225 int registerNumber = isStatic?0:1; 226 for (MethodParameter parameter: parameters) { 227 String parameterType = parameter.getType(); 228 String parameterName = parameter.getName(); 229 Collection<? extends Annotation> annotations = parameter.getAnnotations(); 230 if (parameterName != null || annotations.size() != 0) { 231 writer.write(".param p"); 232 writer.printSignedIntAsDec(registerNumber); 233 if (parameterName != null) { 234 writer.write(", "); 235 // TODO: does dalvik allow non-identifier parameter and/or local names? 236 writer.write(parameterName); 237 } 238 writer.write(" # "); 239 writer.write(parameterType); 240 writer.write("\n"); 241 if (annotations.size() > 0) { 242 writer.indent(4); 243 AnnotationFormatter.writeTo(writer, annotations); 244 writer.deindent(4); 245 writer.write(".end param\n"); 246 } 247 } 248 249 registerNumber++; 250 if (TypeUtils.isWideType(parameterType)) { 251 registerNumber++; 252 } 253 } 254 } 255 256 @Nonnull public LabelCache getLabelCache() { 257 return labelCache; 258 } 259 260 public int getPackedSwitchBaseAddress(int packedSwitchPayloadCodeOffset) { 261 return packedSwitchMap.get(packedSwitchPayloadCodeOffset, -1); 262 } 263 264 public int getSparseSwitchBaseAddress(int sparseSwitchPayloadCodeOffset) { 265 return sparseSwitchMap.get(sparseSwitchPayloadCodeOffset, -1); 266 } 267 268 private List<MethodItem> getMethodItems() { 269 ArrayList<MethodItem> methodItems = new ArrayList<MethodItem>(); 270 271 if ((baksmali.registerInfo != 0) || (baksmali.deodex && needsAnalyzed())) { 272 addAnalyzedInstructionMethodItems(methodItems); 273 } else { 274 addInstructionMethodItems(methodItems); 275 } 276 277 addTries(methodItems); 278 if (baksmali.outputDebugInfo) { 279 addDebugInfo(methodItems); 280 } 281 282 if (baksmali.useSequentialLabels) { 283 setLabelSequentialNumbers(); 284 } 285 286 for (LabelMethodItem labelMethodItem: labelCache.getLabels()) { 287 methodItems.add(labelMethodItem); 288 } 289 290 Collections.sort(methodItems); 291 292 return methodItems; 293 } 294 295 private boolean needsAnalyzed() { 296 for (Instruction instruction: methodImpl.getInstructions()) { 297 if (instruction.getOpcode().odexOnly()) { 298 return true; 299 } 300 } 301 return false; 302 } 303 304 private void addInstructionMethodItems(List<MethodItem> methodItems) { 305 int currentCodeAddress = 0; 306 for (int i=0; i<instructions.size(); i++) { 307 Instruction instruction = instructions.get(i); 308 309 MethodItem methodItem = InstructionMethodItemFactory.makeInstructionFormatMethodItem(this, 310 currentCodeAddress, instruction); 311 312 methodItems.add(methodItem); 313 314 if (i != instructions.size() - 1) { 315 methodItems.add(new BlankMethodItem(currentCodeAddress)); 316 } 317 318 if (baksmali.addCodeOffsets) { 319 methodItems.add(new MethodItem(currentCodeAddress) { 320 321 @Override 322 public double getSortOrder() { 323 return -1000; 324 } 325 326 @Override 327 public boolean writeTo(IndentingWriter writer) throws IOException { 328 writer.write("#@"); 329 writer.printUnsignedLongAsHex(codeAddress & 0xFFFFFFFFL); 330 return true; 331 } 332 }); 333 } 334 335 if (!baksmali.noAccessorComments && (instruction instanceof ReferenceInstruction)) { 336 Opcode opcode = instruction.getOpcode(); 337 338 if (opcode.referenceType == ReferenceType.METHOD) { 339 MethodReference methodReference = 340 (MethodReference)((ReferenceInstruction)instruction).getReference(); 341 342 if (SyntheticAccessorResolver.looksLikeSyntheticAccessor(methodReference.getName())) { 343 SyntheticAccessorResolver.AccessedMember accessedMember = 344 baksmali.syntheticAccessorResolver.getAccessedMember(methodReference); 345 if (accessedMember != null) { 346 methodItems.add(new SyntheticAccessCommentMethodItem(accessedMember, currentCodeAddress)); 347 } 348 } 349 } 350 } 351 352 currentCodeAddress += instruction.getCodeUnits(); 353 } 354 } 355 356 private void addAnalyzedInstructionMethodItems(List<MethodItem> methodItems) { 357 MethodAnalyzer methodAnalyzer = new MethodAnalyzer(baksmali.classPath, method, baksmali.inlineResolver); 358 359 AnalysisException analysisException = methodAnalyzer.getAnalysisException(); 360 if (analysisException != null) { 361 methodItems.add(new CommentMethodItem( 362 String.format("AnalysisException: %s" ,analysisException.getMessage()), 363 analysisException.codeAddress, Integer.MIN_VALUE)); 364 } 365 366 List<AnalyzedInstruction> instructions = methodAnalyzer.getAnalyzedInstructions(); 367 368 int currentCodeAddress = 0; 369 for (int i=0; i<instructions.size(); i++) { 370 AnalyzedInstruction instruction = instructions.get(i); 371 372 MethodItem methodItem = InstructionMethodItemFactory.makeInstructionFormatMethodItem( 373 this, currentCodeAddress, instruction.getInstruction()); 374 375 methodItems.add(methodItem); 376 377 if (instruction.getInstruction().getOpcode().format == Format.UnresolvedOdexInstruction) { 378 methodItems.add(new CommentedOutMethodItem( 379 InstructionMethodItemFactory.makeInstructionFormatMethodItem( 380 this, currentCodeAddress, instruction.getOriginalInstruction()))); 381 } 382 383 if (i != instructions.size() - 1) { 384 methodItems.add(new BlankMethodItem(currentCodeAddress)); 385 } 386 387 if (baksmali.addCodeOffsets) { 388 methodItems.add(new MethodItem(currentCodeAddress) { 389 390 @Override 391 public double getSortOrder() { 392 return -1000; 393 } 394 395 @Override 396 public boolean writeTo(IndentingWriter writer) throws IOException { 397 writer.write("#@"); 398 writer.printUnsignedLongAsHex(codeAddress & 0xFFFFFFFFL); 399 return true; 400 } 401 }); 402 } 403 404 if (baksmali.registerInfo != 0 && !instruction.getInstruction().getOpcode().format.isPayloadFormat) { 405 methodItems.add( 406 new PreInstructionRegisterInfoMethodItem( 407 methodAnalyzer, registerFormatter, instruction, currentCodeAddress)); 408 409 methodItems.add( 410 new PostInstructionRegisterInfoMethodItem(registerFormatter, instruction, currentCodeAddress)); 411 } 412 413 currentCodeAddress += instruction.getInstruction().getCodeUnits(); 414 } 415 } 416 417 private void addTries(List<MethodItem> methodItems) { 418 List<? extends TryBlock> tryBlocks = methodImpl.getTryBlocks(); 419 if (tryBlocks.size() == 0) { 420 return; 421 } 422 423 int lastInstructionAddress = instructionOffsetMap.getInstructionCodeOffset(instructions.size() - 1); 424 int codeSize = lastInstructionAddress + instructions.get(instructions.size() - 1).getCodeUnits(); 425 426 for (TryBlock tryBlock: tryBlocks) { 427 int startAddress = tryBlock.getStartCodeAddress(); 428 int endAddress = startAddress + tryBlock.getCodeUnitCount(); 429 430 if (startAddress >= codeSize) { 431 throw new RuntimeException(String.format("Try start offset %d is past the end of the code block.", 432 startAddress)); 433 } 434 // Note: not >=. endAddress == codeSize is valid, when the try covers the last instruction 435 if (endAddress > codeSize) { 436 throw new RuntimeException(String.format("Try end offset %d is past the end of the code block.", 437 endAddress)); 438 } 439 440 /** 441 * The end address points to the address immediately after the end of the last 442 * instruction that the try block covers. We want the .catch directive and end_try 443 * label to be associated with the last covered instruction, so we need to get 444 * the address for that instruction 445 */ 446 447 int lastCoveredIndex = instructionOffsetMap.getInstructionIndexAtCodeOffset(endAddress - 1, false); 448 int lastCoveredAddress = instructionOffsetMap.getInstructionCodeOffset(lastCoveredIndex); 449 450 for (ExceptionHandler handler: tryBlock.getExceptionHandlers()) { 451 int handlerAddress = handler.getHandlerCodeAddress(); 452 if (handlerAddress >= codeSize) { 453 throw new ExceptionWithContext( 454 "Exception handler offset %d is past the end of the code block.", handlerAddress); 455 } 456 457 //use the address from the last covered instruction 458 CatchMethodItem catchMethodItem = new CatchMethodItem(labelCache, lastCoveredAddress, 459 handler.getExceptionType(), startAddress, endAddress, handlerAddress); 460 methodItems.add(catchMethodItem); 461 } 462 } 463 } 464 465 private void addDebugInfo(final List<MethodItem> methodItems) { 466 for (DebugItem debugItem: methodImpl.getDebugItems()) { 467 methodItems.add(DebugMethodItem.build(registerFormatter, debugItem)); 468 } 469 } 470 471 private void setLabelSequentialNumbers() { 472 HashMap<String, Integer> nextLabelSequenceByType = new HashMap<String, Integer>(); 473 ArrayList<LabelMethodItem> sortedLabels = new ArrayList<LabelMethodItem>(labelCache.getLabels()); 474 475 //sort the labels by their location in the method 476 Collections.sort(sortedLabels); 477 478 for (LabelMethodItem labelMethodItem: sortedLabels) { 479 Integer labelSequence = nextLabelSequenceByType.get(labelMethodItem.getLabelPrefix()); 480 if (labelSequence == null) { 481 labelSequence = 0; 482 } 483 labelMethodItem.setLabelSequence(labelSequence); 484 nextLabelSequenceByType.put(labelMethodItem.getLabelPrefix(), labelSequence + 1); 485 } 486 } 487 488 public static class LabelCache { 489 protected HashMap<LabelMethodItem, LabelMethodItem> labels = new HashMap<LabelMethodItem, LabelMethodItem>(); 490 491 public LabelCache() { 492 } 493 494 public LabelMethodItem internLabel(LabelMethodItem labelMethodItem) { 495 LabelMethodItem internedLabelMethodItem = labels.get(labelMethodItem); 496 if (internedLabelMethodItem != null) { 497 return internedLabelMethodItem; 498 } 499 labels.put(labelMethodItem, labelMethodItem); 500 return labelMethodItem; 501 } 502 503 504 public Collection<LabelMethodItem> getLabels() { 505 return labels.values(); 506 } 507 } 508} 509