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