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;
026import org.apache.bcel.util.Args;
027import org.apache.commons.lang3.ArrayUtils;
028
029/**
030 * This class represents the table of exceptions that are thrown by a method. This attribute may be used once per
031 * method. The name of this class is <em>ExceptionTable</em> for historical reasons; The Java Virtual Machine
032 * Specification, Second Edition defines this attribute using the name <em>Exceptions</em> (which is inconsistent with
033 * the other classes).
034 *
035 * <pre>
036 * Exceptions_attribute {
037 *   u2 attribute_name_index;
038 *   u4 attribute_length;
039 *   u2 number_of_exceptions;
040 *   u2 exception_index_table[number_of_exceptions];
041 * }
042 * </pre>
043 * @see Code
044 */
045public final class ExceptionTable extends Attribute {
046
047    private int[] exceptionIndexTable; // constant pool
048
049    /**
050     * Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a
051     * physical copy.
052     *
053     * @param c Source to copy.
054     */
055    public ExceptionTable(final ExceptionTable c) {
056        this(c.getNameIndex(), c.getLength(), c.getExceptionIndexTable(), c.getConstantPool());
057    }
058
059    /**
060     * Constructs object from input stream.
061     *
062     * @param nameIndex Index in constant pool
063     * @param length Content length in bytes
064     * @param input Input stream
065     * @param constantPool Array of constants
066     * @throws IOException if an I/O error occurs.
067     */
068    ExceptionTable(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException {
069        this(nameIndex, length, (int[]) null, constantPool);
070        final int exceptionCount = input.readUnsignedShort();
071        exceptionIndexTable = new int[exceptionCount];
072        for (int i = 0; i < exceptionCount; i++) {
073            exceptionIndexTable[i] = input.readUnsignedShort();
074        }
075    }
076
077    /**
078     * @param nameIndex Index in constant pool
079     * @param length Content length in bytes
080     * @param exceptionIndexTable Table of indices in constant pool
081     * @param constantPool Array of constants
082     */
083    public ExceptionTable(final int nameIndex, final int length, final int[] exceptionIndexTable, final ConstantPool constantPool) {
084        super(Const.ATTR_EXCEPTIONS, nameIndex, length, constantPool);
085        this.exceptionIndexTable = ArrayUtils.nullToEmpty(exceptionIndexTable);
086        Args.requireU2(this.exceptionIndexTable.length, "exceptionIndexTable.length");
087    }
088
089    /**
090     * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
091     * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
092     *
093     * @param v Visitor object
094     */
095    @Override
096    public void accept(final Visitor v) {
097        v.visitExceptionTable(this);
098    }
099
100    /**
101     * @return deep copy of this attribute
102     */
103    @Override
104    public Attribute copy(final ConstantPool constantPool) {
105        final ExceptionTable c = (ExceptionTable) clone();
106        if (exceptionIndexTable != null) {
107            c.exceptionIndexTable = exceptionIndexTable.clone();
108        }
109        c.setConstantPool(constantPool);
110        return c;
111    }
112
113    /**
114     * Dump exceptions attribute to file stream in binary format.
115     *
116     * @param file Output file stream
117     * @throws IOException if an I/O error occurs.
118     */
119    @Override
120    public void dump(final DataOutputStream file) throws IOException {
121        super.dump(file);
122        file.writeShort(exceptionIndexTable.length);
123        for (final int index : exceptionIndexTable) {
124            file.writeShort(index);
125        }
126    }
127
128    /**
129     * @return Array of indices into constant pool of thrown exceptions.
130     */
131    public int[] getExceptionIndexTable() {
132        return exceptionIndexTable;
133    }
134
135    /**
136     * @return class names of thrown exceptions
137     */
138    public String[] getExceptionNames() {
139        final String[] names = new String[exceptionIndexTable.length];
140        Arrays.setAll(names, i -> Utility.pathToPackage(super.getConstantPool().getConstantString(exceptionIndexTable[i], Const.CONSTANT_Class)));
141        return names;
142    }
143
144    /**
145     * @return Length of exception table.
146     */
147    public int getNumberOfExceptions() {
148        return exceptionIndexTable == null ? 0 : exceptionIndexTable.length;
149    }
150
151    /**
152     * @param exceptionIndexTable the list of exception indexes Also redefines number_of_exceptions according to table
153     *        length.
154     */
155    public void setExceptionIndexTable(final int[] exceptionIndexTable) {
156        this.exceptionIndexTable = ArrayUtils.nullToEmpty(exceptionIndexTable);
157    }
158
159    /**
160     * @return String representation, i.e., a list of thrown exceptions.
161     */
162    @Override
163    public String toString() {
164        final StringBuilder buf = new StringBuilder();
165        String str;
166        buf.append("Exceptions: ");
167        for (int i = 0; i < exceptionIndexTable.length; i++) {
168            str = super.getConstantPool().getConstantString(exceptionIndexTable[i], Const.CONSTANT_Class);
169            buf.append(Utility.compactClassName(str, false));
170            if (i < exceptionIndexTable.length - 1) {
171                buf.append(", ");
172            }
173        }
174        return buf.toString();
175    }
176}