001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018package org.apache.bcel.generic;
019
020import java.io.DataOutputStream;
021import java.io.IOException;
022
023import org.apache.bcel.util.ByteSequence;
024
025/**
026 * Abstract super class for branching instructions like GOTO, IFEQ, etc..
027 * Branch instructions may have a variable length, namely GOTO, JSR,
028 * LOOKUPSWITCH and TABLESWITCH.
029 *
030 * @see InstructionList
031 */
032public abstract class BranchInstruction extends Instruction implements InstructionTargeter {
033
034    /**
035     * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
036     */
037    @Deprecated
038    protected int index; // Branch target relative to this instruction
039
040    /**
041     * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
042     */
043    @Deprecated
044    protected InstructionHandle target; // Target object in instruction list
045
046    /**
047     * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
048     */
049    @Deprecated
050    protected int position; // Byte code offset
051
052
053    /**
054     * Empty constructor needed for Instruction.readInstruction.
055     * Not to be used otherwise.
056     */
057    BranchInstruction() {
058    }
059
060
061    /** Common super constructor
062     * @param opcode Instruction opcode
063     * @param target instruction to branch to
064     */
065    protected BranchInstruction(final short opcode, final InstructionHandle target) {
066        super(opcode, (short) 3);
067        setTarget(target);
068    }
069
070
071    /**
072     * Dump instruction as byte code to stream out.
073     * @param out Output stream
074     */
075    @Override
076    public void dump( final DataOutputStream out ) throws IOException {
077        out.writeByte(super.getOpcode());
078        index = getTargetOffset();
079        if (!isValidShort(index)) {
080            throw new ClassGenException("Branch target offset too large for short: " + index);
081        }
082        out.writeShort(index); // May be negative, i.e., point backwards
083    }
084
085
086    /**
087     * @param _target branch target
088     * @return the offset to  `target' relative to this instruction
089     */
090    protected int getTargetOffset( final InstructionHandle _target ) {
091        if (_target == null) {
092            throw new ClassGenException("Target of " + super.toString(true)
093                    + " is invalid null handle");
094        }
095        final int t = _target.getPosition();
096        if (t < 0) {
097            throw new ClassGenException("Invalid branch target position offset for "
098                    + super.toString(true) + ":" + t + ":" + _target);
099        }
100        return t - position;
101    }
102
103
104    /**
105     * @return the offset to this instruction's target
106     */
107    protected int getTargetOffset() {
108        return getTargetOffset(target);
109    }
110
111
112    /**
113     * Called by InstructionList.setPositions when setting the position for every
114     * instruction. In the presence of variable length instructions `setPositions'
115     * performs multiple passes over the instruction list to calculate the
116     * correct (byte) positions and offsets by calling this function.
117     *
118     * @param offset additional offset caused by preceding (variable length) instructions
119     * @param max_offset the maximum offset that may be caused by these instructions
120     * @return additional offset caused by possible change of this instruction's length
121     */
122    protected int updatePosition( final int offset, final int max_offset ) {
123        position += offset;
124        return 0;
125    }
126
127
128    /**
129     * Long output format:
130     *
131     * &lt;position in byte code&gt;
132     * &lt;name of opcode&gt; "["&lt;opcode number&gt;"]"
133     * "("&lt;length of instruction&gt;")"
134     * "&lt;"&lt;target instruction&gt;"&gt;" "@"&lt;branch target offset&gt;
135     *
136     * @param verbose long/short format switch
137     * @return mnemonic for instruction
138     */
139    @Override
140    public String toString( final boolean verbose ) {
141        final String s = super.toString(verbose);
142        String t = "null";
143        if (verbose) {
144            if (target != null) {
145                if (target.getInstruction() == this) {
146                    t = "<points to itself>";
147                } else if (target.getInstruction() == null) {
148                    t = "<null instruction!!!?>";
149                } else {
150                    // I'm more interested in the address of the target then
151                    // the instruction located there.
152                    //t = target.getInstruction().toString(false); // Avoid circles
153                    t = "" + target.getPosition();
154                }
155            }
156        } else {
157            if (target != null) {
158                index = target.getPosition();
159                // index = getTargetOffset();  crashes if positions haven't been set
160                // t = "" + (index + position);
161                t = "" + index;
162            }
163        }
164        return s + " -> " + t;
165    }
166
167
168    /**
169     * Read needed data (e.g. index) from file. Conversion to a InstructionHandle
170     * is done in InstructionList(byte[]).
171     *
172     * @param bytes input stream
173     * @param wide wide prefix?
174     * @see InstructionList
175     */
176    @Override
177    protected void initFromFile( final ByteSequence bytes, final boolean wide ) throws IOException {
178        super.setLength(3);
179        index = bytes.readShort();
180    }
181
182
183    /**
184     * @return target offset in byte code
185     */
186    public final int getIndex() {
187        return index;
188    }
189
190
191    /**
192     * @return target of branch instruction
193     */
194    public InstructionHandle getTarget() {
195        return target;
196    }
197
198
199    /**
200     * Set branch target
201     * @param target branch target
202     */
203    public void setTarget( final InstructionHandle target ) {
204        notifyTarget(this.target, target, this);
205        this.target = target;
206    }
207
208
209    /**
210     * Used by BranchInstruction, LocalVariableGen, CodeExceptionGen, LineNumberGen
211     */
212    static void notifyTarget( final InstructionHandle old_ih, final InstructionHandle new_ih,
213            final InstructionTargeter t ) {
214        if (old_ih != null) {
215            old_ih.removeTargeter(t);
216        }
217        if (new_ih != null) {
218            new_ih.addTargeter(t);
219        }
220    }
221
222
223    /**
224     * @param old_ih old target
225     * @param new_ih new target
226     */
227    @Override
228    public void updateTarget( final InstructionHandle old_ih, final InstructionHandle new_ih ) {
229        if (target == old_ih) {
230            setTarget(new_ih);
231        } else {
232            throw new ClassGenException("Not targeting " + old_ih + ", but " + target);
233        }
234    }
235
236
237    /**
238     * @return true, if ih is target of this instruction
239     */
240    @Override
241    public boolean containsTarget( final InstructionHandle ih ) {
242        return target == ih;
243    }
244
245
246    /**
247     * Inform target that it's not targeted anymore.
248     */
249    @Override
250    void dispose() {
251        setTarget(null);
252        index = -1;
253        position = -1;
254    }
255
256
257    /**
258     * @return the position
259     * @since 6.0
260     */
261    protected int getPosition() {
262        return position;
263    }
264
265
266    /**
267     * @param position the position to set
268     * @since 6.0
269     */
270    protected void setPosition(final int position) {
271        this.position = position;
272    }
273
274
275    /**
276     * @param index the index to set
277     * @since 6.0
278     */
279    protected void setIndex(final int index) {
280        this.index = index;
281    }
282
283}