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