1 21 package proguard.optimize.peephole; 22 23 import proguard.classfile.*; 24 import proguard.classfile.visitor.ClassPrinter; 25 import proguard.classfile.attribute.*; 26 import proguard.classfile.attribute.visitor.AttributeVisitor; 27 import proguard.classfile.editor.CodeAttributeEditor; 28 import proguard.classfile.instruction.*; 29 import proguard.classfile.instruction.visitor.InstructionVisitor; 30 import proguard.classfile.util.SimplifiedVisitor; 31 32 38 public class UnreachableCodeRemover 39 extends SimplifiedVisitor 40 implements AttributeVisitor, 41 InstructionVisitor 42 { 43 private static final boolean DEBUG = false; 45 48 49 private InstructionVisitor extraInstructionVisitor; 50 51 private ReachableCodeMarker reachableCodeMarker = new ReachableCodeMarker(); 52 private CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor(); 53 54 55 58 public UnreachableCodeRemover() 59 { 60 this(null); 61 } 62 63 64 69 public UnreachableCodeRemover(InstructionVisitor extraInstructionVisitor) 70 { 71 this.extraInstructionVisitor = extraInstructionVisitor; 72 } 73 74 75 77 public void visitAnyAttribute(Clazz clazz, Attribute attribute) {} 78 79 80 public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute) 81 { 82 86 try 89 { 90 visitCodeAttribute0(clazz, method, codeAttribute); 92 } 93 catch (RuntimeException ex) 94 { 95 System.err.println("Unexpected error while removing unreachable code:"); 96 System.err.println(" Class = ["+clazz.getName()+"]"); 97 System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]"); 98 System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")"); 99 100 throw ex; 101 } 102 } 103 104 105 public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute) 106 { 107 if (DEBUG) 108 { 109 System.out.println("UnreachableCodeRemover: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)); 110 } 111 112 reachableCodeMarker.visitCodeAttribute(clazz, method, codeAttribute); 113 114 codeAttributeEditor.reset(codeAttribute.u4codeLength); 115 116 codeAttribute.instructionsAccept(clazz, method, this); 117 118 codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute); 119 } 120 121 122 124 public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) 125 { 126 if (DEBUG) 127 { 128 System.out.println(" "+(reachableCodeMarker.isReachable(offset) ? "+" : "-")+" "+instruction.toString(offset)); 129 } 130 131 if (!reachableCodeMarker.isReachable(offset)) 133 { 134 codeAttributeEditor.deleteInstruction(offset); 136 137 if (extraInstructionVisitor != null) 139 { 140 instruction.accept(clazz, method, codeAttribute, offset, extraInstructionVisitor); 141 } 142 } 143 } 144 } 145 | Popular Tags |