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.classfile;
019
020import java.io.DataInput;
021import java.io.DataOutputStream;
022import java.io.IOException;
023import java.util.Arrays;
024
025import org.apache.bcel.Const;
026
027/**
028 * This class represents a stack map entry recording the types of local variables and the of stack items at a given
029 * byte code offset. See CLDC specification 5.3.1.2
030 *
031 * @see StackMap
032 * @see StackMapType
033 */
034public final class StackMapEntry implements Node, Cloneable {
035
036    /**
037     * Empty array.
038     */
039    private static final StackMapType[] EMPTY_STACK_MAP_TYPE_ARRAY = {};
040
041    private int frameType;
042    private int byteCodeOffset;
043    private StackMapType[] typesOfLocals;
044    private StackMapType[] typesOfStackItems;
045    private ConstantPool constantPool;
046
047    /**
048     * Construct object from input stream.
049     *
050     * @param input Input stream
051     * @throws IOException if an I/O error occurs.
052     */
053    StackMapEntry(final DataInput input, final ConstantPool constantPool) throws IOException {
054        this(input.readByte() & 0xFF, -1, null, null, constantPool);
055
056        if (frameType >= Const.SAME_FRAME && frameType <= Const.SAME_FRAME_MAX) {
057            byteCodeOffset = frameType - Const.SAME_FRAME;
058        } else if (frameType >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frameType <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
059            byteCodeOffset = frameType - Const.SAME_LOCALS_1_STACK_ITEM_FRAME;
060            typesOfStackItems = new StackMapType[1];
061            typesOfStackItems[0] = new StackMapType(input, constantPool);
062        } else if (frameType == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {
063            byteCodeOffset = input.readShort();
064            typesOfStackItems = new StackMapType[1];
065            typesOfStackItems[0] = new StackMapType(input, constantPool);
066        } else if (frameType >= Const.CHOP_FRAME && frameType <= Const.CHOP_FRAME_MAX) {
067            byteCodeOffset = input.readShort();
068        } else if (frameType == Const.SAME_FRAME_EXTENDED) {
069            byteCodeOffset = input.readShort();
070        } else if (frameType >= Const.APPEND_FRAME && frameType <= Const.APPEND_FRAME_MAX) {
071            byteCodeOffset = input.readShort();
072            final int number_of_locals = frameType - 251;
073            typesOfLocals = new StackMapType[number_of_locals];
074            for (int i = 0; i < number_of_locals; i++) {
075                typesOfLocals[i] = new StackMapType(input, constantPool);
076            }
077        } else if (frameType == Const.FULL_FRAME) {
078            byteCodeOffset = input.readShort();
079            final int number_of_locals = input.readShort();
080            typesOfLocals = new StackMapType[number_of_locals];
081            for (int i = 0; i < number_of_locals; i++) {
082                typesOfLocals[i] = new StackMapType(input, constantPool);
083            }
084            final int number_of_stack_items = input.readShort();
085            typesOfStackItems = new StackMapType[number_of_stack_items];
086            for (int i = 0; i < number_of_stack_items; i++) {
087                typesOfStackItems[i] = new StackMapType(input, constantPool);
088            }
089        } else {
090            /* Can't happen */
091            throw new ClassFormatException("Invalid frame type found while parsing stack map table: " + frameType);
092        }
093    }
094
095    /**
096     * DO NOT USE
097     *
098     * @param byteCodeOffset
099     * @param numberOfLocals NOT USED
100     * @param typesOfLocals array of {@link StackMapType}s of locals
101     * @param numberOfStackItems NOT USED
102     * @param typesOfStackItems array ot {@link StackMapType}s of stack items
103     * @param constantPool the constant pool
104     * @deprecated Since 6.0, use {@link #StackMapEntry(int, int, StackMapType[], StackMapType[], ConstantPool)} instead
105     */
106    @java.lang.Deprecated
107    public StackMapEntry(final int byteCodeOffset, final int numberOfLocals, final StackMapType[] typesOfLocals, final int numberOfStackItems,
108        final StackMapType[] typesOfStackItems, final ConstantPool constantPool) {
109        this.byteCodeOffset = byteCodeOffset;
110        this.typesOfLocals = typesOfLocals != null ? typesOfLocals : EMPTY_STACK_MAP_TYPE_ARRAY;
111        this.typesOfStackItems = typesOfStackItems != null ? typesOfStackItems : EMPTY_STACK_MAP_TYPE_ARRAY;
112        this.constantPool = constantPool;
113    }
114
115    /**
116     * Create an instance
117     *
118     * @param tag the frameType to use
119     * @param byteCodeOffset
120     * @param typesOfLocals array of {@link StackMapType}s of locals
121     * @param typesOfStackItems array ot {@link StackMapType}s of stack items
122     * @param constantPool the constant pool
123     */
124    public StackMapEntry(final int tag, final int byteCodeOffset, final StackMapType[] typesOfLocals, final StackMapType[] typesOfStackItems,
125        final ConstantPool constantPool) {
126        this.frameType = tag;
127        this.byteCodeOffset = byteCodeOffset;
128        this.typesOfLocals = typesOfLocals != null ? typesOfLocals : EMPTY_STACK_MAP_TYPE_ARRAY;
129        this.typesOfStackItems = typesOfStackItems != null ? typesOfStackItems : EMPTY_STACK_MAP_TYPE_ARRAY;
130        this.constantPool = constantPool;
131    }
132
133    /**
134     * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
135     * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
136     *
137     * @param v Visitor object
138     */
139    @Override
140    public void accept(final Visitor v) {
141        v.visitStackMapEntry(this);
142    }
143
144    /**
145     * @return deep copy of this object
146     */
147    public StackMapEntry copy() {
148        StackMapEntry e;
149        try {
150            e = (StackMapEntry) clone();
151        } catch (final CloneNotSupportedException ex) {
152            throw new Error("Clone Not Supported");
153        }
154
155        e.typesOfLocals = new StackMapType[typesOfLocals.length];
156        Arrays.setAll(e.typesOfLocals, i -> typesOfLocals[i].copy());
157        e.typesOfStackItems = new StackMapType[typesOfStackItems.length];
158        Arrays.setAll(e.typesOfStackItems, i -> typesOfStackItems[i].copy());
159        return e;
160    }
161
162    /**
163     * Dump stack map entry
164     *
165     * @param file Output file stream
166     * @throws IOException if an I/O error occurs.
167     */
168    public void dump(final DataOutputStream file) throws IOException {
169        file.write(frameType);
170        if (frameType >= Const.SAME_FRAME && frameType <= Const.SAME_FRAME_MAX) {
171            // nothing to be done
172        } else if (frameType >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frameType <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
173            typesOfStackItems[0].dump(file);
174        } else if (frameType == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {
175            file.writeShort(byteCodeOffset);
176            typesOfStackItems[0].dump(file);
177        } else if (frameType >= Const.CHOP_FRAME && frameType <= Const.CHOP_FRAME_MAX) {
178            file.writeShort(byteCodeOffset);
179        } else if (frameType == Const.SAME_FRAME_EXTENDED) {
180            file.writeShort(byteCodeOffset);
181        } else if (frameType >= Const.APPEND_FRAME && frameType <= Const.APPEND_FRAME_MAX) {
182            file.writeShort(byteCodeOffset);
183            for (final StackMapType type : typesOfLocals) {
184                type.dump(file);
185            }
186        } else if (frameType == Const.FULL_FRAME) {
187            file.writeShort(byteCodeOffset);
188            file.writeShort(typesOfLocals.length);
189            for (final StackMapType type : typesOfLocals) {
190                type.dump(file);
191            }
192            file.writeShort(typesOfStackItems.length);
193            for (final StackMapType type : typesOfStackItems) {
194                type.dump(file);
195            }
196        } else {
197            /* Can't happen */
198            throw new ClassFormatException("Invalid Stack map table tag: " + frameType);
199        }
200    }
201
202    public int getByteCodeOffset() {
203        return byteCodeOffset;
204    }
205
206    /**
207     * @return Constant pool used by this object.
208     */
209    public ConstantPool getConstantPool() {
210        return constantPool;
211    }
212
213    public int getFrameType() {
214        return frameType;
215    }
216
217    /**
218     * Calculate stack map entry size
219     *
220     */
221    int getMapEntrySize() {
222        if (frameType >= Const.SAME_FRAME && frameType <= Const.SAME_FRAME_MAX) {
223            return 1;
224        }
225        if (frameType >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frameType <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
226            return 1 + (typesOfStackItems[0].hasIndex() ? 3 : 1);
227        }
228        if (frameType == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {
229            return 3 + (typesOfStackItems[0].hasIndex() ? 3 : 1);
230        }
231        if (frameType >= Const.CHOP_FRAME && frameType <= Const.CHOP_FRAME_MAX || frameType == Const.SAME_FRAME_EXTENDED) {
232            return 3;
233        }
234        if (frameType >= Const.APPEND_FRAME && frameType <= Const.APPEND_FRAME_MAX) {
235            int len = 3;
236            for (final StackMapType types_of_local : typesOfLocals) {
237                len += types_of_local.hasIndex() ? 3 : 1;
238            }
239            return len;
240        }
241        if (frameType != Const.FULL_FRAME) {
242            throw new IllegalStateException("Invalid StackMap frameType: " + frameType);
243        }
244        int len = 7;
245        for (final StackMapType types_of_local : typesOfLocals) {
246            len += types_of_local.hasIndex() ? 3 : 1;
247        }
248        for (final StackMapType types_of_stack_item : typesOfStackItems) {
249            len += types_of_stack_item.hasIndex() ? 3 : 1;
250        }
251        return len;
252    }
253
254    public int getNumberOfLocals() {
255        return typesOfLocals.length;
256    }
257
258    public int getNumberOfStackItems() {
259        return typesOfStackItems.length;
260    }
261
262    public StackMapType[] getTypesOfLocals() {
263        return typesOfLocals;
264    }
265
266    public StackMapType[] getTypesOfStackItems() {
267        return typesOfStackItems;
268    }
269
270    public void setByteCodeOffset(final int new_offset) {
271        if (new_offset < 0 || new_offset > 32767) {
272            throw new IllegalArgumentException("Invalid StackMap offset: " + new_offset);
273        }
274
275        if (frameType >= Const.SAME_FRAME && frameType <= Const.SAME_FRAME_MAX) {
276            if (new_offset > Const.SAME_FRAME_MAX) {
277                frameType = Const.SAME_FRAME_EXTENDED;
278            } else {
279                frameType = new_offset;
280            }
281        } else if (frameType >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frameType <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
282            if (new_offset > Const.SAME_FRAME_MAX) {
283                frameType = Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;
284            } else {
285                frameType = Const.SAME_LOCALS_1_STACK_ITEM_FRAME + new_offset;
286            }
287        } else if (frameType == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { // CHECKSTYLE IGNORE EmptyBlock
288        } else if (frameType >= Const.CHOP_FRAME && frameType <= Const.CHOP_FRAME_MAX) { // CHECKSTYLE IGNORE EmptyBlock
289        } else if (frameType == Const.SAME_FRAME_EXTENDED) { // CHECKSTYLE IGNORE EmptyBlock
290        } else if (frameType >= Const.APPEND_FRAME && frameType <= Const.APPEND_FRAME_MAX) { // CHECKSTYLE IGNORE EmptyBlock
291        } else if (frameType == Const.FULL_FRAME) { // CHECKSTYLE IGNORE EmptyBlock
292        } else {
293            throw new IllegalStateException("Invalid StackMap frameType: " + frameType);
294        }
295        byteCodeOffset = new_offset;
296    }
297
298    /**
299     * @param constantPool Constant pool to be used for this object.
300     */
301    public void setConstantPool(final ConstantPool constantPool) {
302        this.constantPool = constantPool;
303    }
304
305    public void setFrameType(final int f) {
306        if (f >= Const.SAME_FRAME && f <= Const.SAME_FRAME_MAX) {
307            byteCodeOffset = f - Const.SAME_FRAME;
308        } else if (f >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && f <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
309            byteCodeOffset = f - Const.SAME_LOCALS_1_STACK_ITEM_FRAME;
310        } else if (f == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { // CHECKSTYLE IGNORE EmptyBlock
311        } else if (f >= Const.CHOP_FRAME && f <= Const.CHOP_FRAME_MAX) { // CHECKSTYLE IGNORE EmptyBlock
312        } else if (f == Const.SAME_FRAME_EXTENDED) { // CHECKSTYLE IGNORE EmptyBlock
313        } else if (f >= Const.APPEND_FRAME && f <= Const.APPEND_FRAME_MAX) { // CHECKSTYLE IGNORE EmptyBlock
314        } else if (f == Const.FULL_FRAME) { // CHECKSTYLE IGNORE EmptyBlock
315        } else {
316            throw new IllegalArgumentException("Invalid StackMap frameType");
317        }
318        frameType = f;
319    }
320
321    /**
322     *
323     * @deprecated since 6.0
324     */
325    @java.lang.Deprecated
326    public void setNumberOfLocals(final int n) { // TODO unused
327    }
328
329    /**
330     *
331     * @deprecated since 6.0
332     */
333    @java.lang.Deprecated
334    public void setNumberOfStackItems(final int n) { // TODO unused
335    }
336
337    public void setTypesOfLocals(final StackMapType[] types) {
338        typesOfLocals = types != null ? types : EMPTY_STACK_MAP_TYPE_ARRAY;
339    }
340
341    public void setTypesOfStackItems(final StackMapType[] types) {
342        typesOfStackItems = types != null ? types : EMPTY_STACK_MAP_TYPE_ARRAY;
343    }
344
345    /**
346     * @return String representation.
347     */
348    @Override
349    public String toString() {
350        final StringBuilder buf = new StringBuilder(64);
351        buf.append("(");
352        if (frameType >= Const.SAME_FRAME && frameType <= Const.SAME_FRAME_MAX) {
353            buf.append("SAME");
354        } else if (frameType >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frameType <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
355            buf.append("SAME_LOCALS_1_STACK");
356        } else if (frameType == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {
357            buf.append("SAME_LOCALS_1_STACK_EXTENDED");
358        } else if (frameType >= Const.CHOP_FRAME && frameType <= Const.CHOP_FRAME_MAX) {
359            buf.append("CHOP ").append(String.valueOf(251 - frameType));
360        } else if (frameType == Const.SAME_FRAME_EXTENDED) {
361            buf.append("SAME_EXTENDED");
362        } else if (frameType >= Const.APPEND_FRAME && frameType <= Const.APPEND_FRAME_MAX) {
363            buf.append("APPEND ").append(String.valueOf(frameType - 251));
364        } else if (frameType == Const.FULL_FRAME) {
365            buf.append("FULL");
366        } else {
367            buf.append("UNKNOWN (").append(frameType).append(")");
368        }
369        buf.append(", offset delta=").append(byteCodeOffset);
370        if (typesOfLocals.length > 0) {
371            buf.append(", locals={");
372            for (int i = 0; i < typesOfLocals.length; i++) {
373                buf.append(typesOfLocals[i]);
374                if (i < typesOfLocals.length - 1) {
375                    buf.append(", ");
376                }
377            }
378            buf.append("}");
379        }
380        if (typesOfStackItems.length > 0) {
381            buf.append(", stack items={");
382            for (int i = 0; i < typesOfStackItems.length; i++) {
383                buf.append(typesOfStackItems[i]);
384                if (i < typesOfStackItems.length - 1) {
385                    buf.append(", ");
386                }
387            }
388            buf.append("}");
389        }
390        buf.append(")");
391        return buf.toString();
392    }
393
394    /**
395     * Update the distance (as an offset delta) from this StackMap entry to the next. Note that this might cause the
396     * frame type to change. Note also that delta may be negative.
397     *
398     * @param delta offset delta
399     */
400    public void updateByteCodeOffset(final int delta) {
401        setByteCodeOffset(byteCodeOffset + delta);
402    }
403}