1. package com.sun.org.apache.bcel.internal.generic;
  2. /* ====================================================================
  3. * The Apache Software License, Version 1.1
  4. *
  5. * Copyright (c) 2001 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Apache" and "Apache Software Foundation" and
  28. * "Apache BCEL" must not be used to endorse or promote products
  29. * derived from this software without prior written permission. For
  30. * written permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * "Apache BCEL", nor may "Apache" appear in their name, without
  34. * prior written permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation. For more
  52. * information on the Apache Software Foundation, please see
  53. * <http://www.apache.org/>.
  54. */
  55. import com.sun.org.apache.bcel.internal.Constants;
  56. import com.sun.org.apache.bcel.internal.classfile.Utility;
  57. import com.sun.org.apache.bcel.internal.classfile.ConstantPool;
  58. import java.io.*;
  59. import com.sun.org.apache.bcel.internal.util.ByteSequence;
  60. /**
  61. * Abstract super class for all Java byte codes.
  62. *
  63. * @version $Id: Instruction.java,v 1.1.1.1 2001/10/29 20:00:18 jvanzyl Exp $
  64. * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
  65. */
  66. public abstract class Instruction implements Cloneable, Serializable {
  67. protected short length = 1; // Length of instruction in bytes
  68. protected short opcode = -1; // Opcode number
  69. /**
  70. * Empty constructor needed for the Class.newInstance() statement in
  71. * Instruction.readInstruction(). Not to be used otherwise.
  72. */
  73. Instruction() {}
  74. public Instruction(short opcode, short length) {
  75. this.length = length;
  76. this.opcode = opcode;
  77. }
  78. /**
  79. * Dump instruction as byte code to stream out.
  80. * @param out Output stream
  81. */
  82. public void dump(DataOutputStream out) throws IOException {
  83. out.writeByte(opcode); // Common for all instructions
  84. }
  85. /**
  86. * Long output format:
  87. *
  88. * <name of opcode> "["<opcode number>"]"
  89. * "("<length of instruction>")"
  90. *
  91. * @param verbose long/short format switch
  92. * @return mnemonic for instruction
  93. */
  94. public String toString(boolean verbose) {
  95. if(verbose)
  96. return Constants.OPCODE_NAMES[opcode] + "[" + opcode + "](" + length + ")";
  97. else
  98. return Constants.OPCODE_NAMES[opcode];
  99. }
  100. /**
  101. * @return mnemonic for instruction in verbose format
  102. */
  103. public String toString() {
  104. return toString(true);
  105. }
  106. /**
  107. * @return mnemonic for instruction with sumbolic references resolved
  108. */
  109. public String toString(ConstantPool cp) {
  110. return toString(false);
  111. }
  112. /**
  113. * Use with caution, since `BranchInstruction's have a `target' reference which
  114. * is not copied correctly (only basic types are). This also applies for
  115. * `Select' instructions with their multiple branch targets.
  116. *
  117. * @see BranchInstruction
  118. * @return (shallow) copy of an instruction
  119. */
  120. public Instruction copy() {
  121. Instruction i = null;
  122. // "Constant" instruction, no need to duplicate
  123. if(InstructionConstants.INSTRUCTIONS[this.getOpcode()] != null)
  124. i = this;
  125. else {
  126. try {
  127. i = (Instruction)clone();
  128. } catch(CloneNotSupportedException e) {
  129. System.err.println(e);
  130. }
  131. }
  132. return i;
  133. }
  134. /**
  135. * Read needed data (e.g. index) from file.
  136. *
  137. * @param bytes byte sequence to read from
  138. * @param wide "wide" instruction flag
  139. */
  140. protected void initFromFile(ByteSequence bytes, boolean wide)
  141. throws IOException
  142. {}
  143. /**
  144. * Read an instruction from (byte code) input stream and return the
  145. * appropiate object.
  146. *
  147. * @param file file to read from
  148. * @return instruction object being read
  149. */
  150. public static final Instruction readInstruction(ByteSequence bytes)
  151. throws IOException
  152. {
  153. boolean wide = false;
  154. short opcode = (short)bytes.readUnsignedByte();
  155. Instruction obj = null;
  156. if(opcode == Constants.WIDE) { // Read next opcode after wide byte
  157. wide = true;
  158. opcode = (short)bytes.readUnsignedByte();
  159. }
  160. if(InstructionConstants.INSTRUCTIONS[opcode] != null)
  161. return InstructionConstants.INSTRUCTIONS[opcode]; // Used predefined immutable object, if available
  162. /* Find appropiate class, instantiate an (empty) instruction object
  163. * and initialize it by hand.
  164. */
  165. Class clazz;
  166. try {
  167. clazz = Class.forName(className(opcode));
  168. }
  169. catch (ClassNotFoundException cnfe){
  170. // If a class by that name does not exist, the opcode is illegal.
  171. // Note that IMPDEP1, IMPDEP2, BREAKPOINT are also illegal in a sense.
  172. throw new ClassGenException("Illegal opcode detected.");
  173. }
  174. try {
  175. obj = (Instruction)clazz.newInstance();
  176. if(wide && !((obj instanceof LocalVariableInstruction) || (obj instanceof IINC) ||
  177. (obj instanceof RET)))
  178. throw new Exception("Illegal opcode after wide: " + opcode);
  179. obj.setOpcode(opcode);
  180. obj.initFromFile(bytes, wide); // Do further initializations, if any
  181. // Byte code offset set in InstructionList
  182. } catch(Exception e) { throw new ClassGenException(e.toString()); }
  183. return obj;
  184. }
  185. private static final String className(short opcode) {
  186. String name = Constants.OPCODE_NAMES[opcode].toUpperCase();
  187. /* ICONST_0, etc. will be shortened to ICONST, etc., since ICONST_0 and the like
  188. * are not implemented (directly).
  189. */
  190. try {
  191. int len = name.length();
  192. char ch1 = name.charAt(len - 2), ch2 = name.charAt(len - 1);
  193. if((ch1 == '_') && (ch2 >= '0') && (ch2 <= '5'))
  194. name = name.substring(0, len - 2);
  195. if(name.equals("ICONST_M1")) // Special case
  196. name = "ICONST";
  197. } catch(StringIndexOutOfBoundsException e) { System.err.println(e); }
  198. return "com.sun.org.apache.bcel.internal.generic." + name;
  199. }
  200. /**
  201. * This method also gives right results for instructions whose
  202. * effect on the stack depends on the constant pool entry they
  203. * reference.
  204. * @return Number of words consumed from stack by this instruction,
  205. * or Constants.UNPREDICTABLE, if this can not be computed statically
  206. */
  207. public int consumeStack(ConstantPoolGen cpg) {
  208. return Constants.CONSUME_STACK[opcode];
  209. }
  210. /**
  211. * This method also gives right results for instructions whose
  212. * effect on the stack depends on the constant pool entry they
  213. * reference.
  214. * @return Number of words produced onto stack by this instruction,
  215. * or Constants.UNPREDICTABLE, if this can not be computed statically
  216. */
  217. public int produceStack(ConstantPoolGen cpg) {
  218. return Constants.PRODUCE_STACK[opcode];
  219. }
  220. /**
  221. * @return this instructions opcode
  222. */
  223. public short getOpcode() { return opcode; }
  224. /**
  225. * @return length (in bytes) of instruction
  226. */
  227. public int getLength() { return length; }
  228. /**
  229. * Needed in readInstruction.
  230. */
  231. private void setOpcode(short opcode) { this.opcode = opcode; }
  232. /** Some instructions may be reused, so don't do anything by default.
  233. */
  234. void dispose() { }
  235. /**
  236. * Call corresponding visitor method(s). The order is:
  237. * Call visitor methods of implemented interfaces first, then
  238. * call methods according to the class hierarchy in descending order,
  239. * i.e., the most specific visitXXX() call comes last.
  240. *
  241. * @param v Visitor object
  242. */
  243. public abstract void accept(Visitor v);
  244. }