001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.bcel.classfile;
020
021import java.io.DataInput;
022import java.io.DataOutputStream;
023import java.io.IOException;
024import java.util.Arrays;
025
026import org.apache.bcel.Const;
027import org.apache.bcel.util.Args;
028
029/**
030 * This class represents a stack map attribute used for preverification of Java classes for the
031 * <a href="https://java.sun.com/j2me/"> Java 2 Micro Edition</a> (J2ME). This attribute is used by the
032 * <a href="https://java.sun.com/products/cldc/">KVM</a> and contained within the Code attribute of a method. See CLDC
033 * specification �5.3.1.2
034 *
035 * <pre>
036 * StackMapTable_attribute {
037 *   u2              attribute_name_index;
038 *   u4              attribute_length;
039 *   u2              number_of_entries;
040 *   stack_map_frame entries[number_of_entries];
041 * }
042 * </pre>
043 *
044 * @see Code
045 * @see StackMapEntry
046 * @see StackMapType
047 */
048public final class StackMap extends Attribute {
049
050    private StackMapEntry[] table; // Table of stack map entries
051
052    /**
053     * Constructs object from input stream.
054     *
055     * @param nameIndex Index of name.
056     * @param length Content length in bytes.
057     * @param dataInput Input stream.
058     * @param constantPool Array of constants.
059     * @throws IOException Thrown if an I/O error occurs.
060     */
061    StackMap(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException {
062        this(nameIndex, length, (StackMapEntry[]) null, constantPool);
063        final int mapLength = dataInput.readUnsignedShort();
064        table = new StackMapEntry[mapLength];
065        for (int i = 0; i < mapLength; i++) {
066            table[i] = new StackMapEntry(dataInput, constantPool);
067        }
068    }
069
070    /**
071     * Constructs a StackMap.
072     *
073     * @param nameIndex Index of name.
074     * @param length Content length in bytes.
075     * @param table Table of stack map entries.
076     * @param constantPool Array of constants.
077     */
078    public StackMap(final int nameIndex, final int length, final StackMapEntry[] table, final ConstantPool constantPool) {
079        super(Const.ATTR_STACK_MAP, nameIndex, length, constantPool);
080        this.table = table != null ? table : StackMapEntry.EMPTY_ARRAY;
081        Args.requireU2(this.table.length, "table.length");
082    }
083
084    /**
085     * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
086     * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
087     *
088     * @param v Visitor object.
089     */
090    @Override
091    public void accept(final Visitor v) {
092        v.visitStackMap(this);
093    }
094
095    /**
096     * @return deep copy of this attribute.
097     */
098    @Override
099    public Attribute copy(final ConstantPool constantPool) {
100        final StackMap c = (StackMap) clone();
101        c.table = new StackMapEntry[table.length];
102        Arrays.setAll(c.table, i -> table[i].copy());
103        c.setConstantPool(constantPool);
104        return c;
105    }
106
107    /**
108     * Dumps stack map table attribute to file stream in binary format.
109     *
110     * @param file Output file stream.
111     * @throws IOException Thrown if an I/O error occurs.
112     */
113    @Override
114    public void dump(final DataOutputStream file) throws IOException {
115        super.dump(file);
116        file.writeShort(Args.requireU2(table.length, "table.length"));
117        for (final StackMapEntry entry : table) {
118            entry.dump(file);
119        }
120    }
121
122    /**
123     * Gets the map length.
124     *
125     * @return The map length.
126     */
127    public int getMapLength() {
128        return table.length;
129    }
130
131    /**
132     * Gets the stack map.
133     *
134     * @return Array of stack map entries.
135     */
136    public StackMapEntry[] getStackMap() {
137        return table;
138    }
139
140    /**
141     * Sets the stack map.
142     *
143     * @param table Array of stack map entries.
144     */
145    public void setStackMap(final StackMapEntry[] table) {
146        this.table = table != null ? table : StackMapEntry.EMPTY_ARRAY;
147        int len = 2; // Length of 'number_of_entries' field prior to the array of stack maps
148        for (final StackMapEntry element : this.table) {
149            len += element.getMapEntrySize();
150        }
151        setLength(len);
152    }
153
154    /**
155     * @return String representation.
156     */
157    @Override
158    public String toString() {
159        final StringBuilder buf = new StringBuilder("StackMap(");
160        int runningOffset = -1; // no +1 on first entry
161        for (int i = 0; i < table.length; i++) {
162            runningOffset = table[i].getByteCodeOffset() + runningOffset + 1;
163            buf.append(String.format("%n@%03d %s", runningOffset, table[i]));
164            if (i < table.length - 1) {
165                buf.append(", ");
166            }
167        }
168        buf.append(')');
169        return buf.toString();
170    }
171}