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 */
017package org.apache.commons.compress.harmony.unpack200.bytecode;
018
019import java.io.DataOutputStream;
020import java.io.IOException;
021import java.util.List;
022
023import org.apache.commons.compress.harmony.pack200.Pack200Exception;
024
025/**
026 * Abstract superclass for attributes that have some part encoded with a BCI renumbering
027 */
028public abstract class BCIRenumberedAttribute extends Attribute {
029
030    protected boolean renumbered;
031
032    /*
033     * (non-Javadoc)
034     *
035     * @see org.apache.commons.compress.harmony.unpack200.bytecode.Attribute#hasBCIRenumbering()
036     */
037    @Override
038    public boolean hasBCIRenumbering() {
039        return true;
040    }
041
042    public BCIRenumberedAttribute(final CPUTF8 attributeName) {
043        super(attributeName);
044    }
045
046    @Override
047    protected abstract int getLength();
048
049    @Override
050    protected abstract void writeBody(DataOutputStream dos) throws IOException;
051
052    @Override
053    public abstract String toString();
054
055    protected abstract int[] getStartPCs();
056
057    /**
058     * In Pack200, line number tables are BCI renumbered. This method takes the byteCodeOffsets (which is a List of
059     * Integers specifying the offset in the byte code array of each instruction) and updates the start_pcs so that it
060     * points to the instruction index itself, not the BCI renumbering of the instruction.
061     *
062     * @param byteCodeOffsets List of Integer offsets of the bytecode array
063     * @throws Pack200Exception TODO
064     */
065    public void renumber(final List byteCodeOffsets) throws Pack200Exception {
066        if (renumbered) {
067            throw new Error("Trying to renumber a line number table that has already been renumbered");
068        }
069        renumbered = true;
070        final int[] startPCs = getStartPCs();
071        for (int index = 0; index < startPCs.length; index++) {
072            startPCs[index] = ((Integer) byteCodeOffsets.get(startPCs[index])).intValue();
073        }
074    }
075
076}