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.pack200;
018
019import org.objectweb.asm.ClassReader;
020
021/**
022 * Wrapper for ClassReader that enables pack200 to obtain extra class file information
023 */
024public class Pack200ClassReader extends ClassReader {
025
026    private boolean lastConstantHadWideIndex;
027    private int lastUnsignedShort;
028    private boolean anySyntheticAttributes;
029    private String fileName;
030
031    /**
032     * @param b the contents of class file in the format of bytes
033     */
034    public Pack200ClassReader(final byte[] b) {
035        super(b);
036    }
037
038    public String getFileName() {
039        return fileName;
040    }
041
042    public boolean hasSyntheticAttributes() {
043        return anySyntheticAttributes;
044    }
045
046    public boolean lastConstantHadWideIndex() {
047        return lastConstantHadWideIndex;
048    }
049
050    @Override
051    public Object readConst(final int item, final char[] buf) {
052        lastConstantHadWideIndex = item == lastUnsignedShort;
053        return super.readConst(item, buf);
054    }
055
056    @Override
057    public int readUnsignedShort(final int index) {
058        // Doing this to check whether last load-constant instruction was ldc (18) or ldc_w (19)
059        // TODO: Assess whether this impacts on performance
060        final int unsignedShort = super.readUnsignedShort(index);
061        if (index > 0 && b[index - 1] == 19) {
062            lastUnsignedShort = unsignedShort;
063        } else {
064            lastUnsignedShort = Short.MIN_VALUE;
065        }
066        return unsignedShort;
067    }
068
069    @Override
070    public String readUTF8(final int arg0, final char[] arg1) {
071        final String utf8 = super.readUTF8(arg0, arg1);
072        if (!anySyntheticAttributes && "Synthetic".equals(utf8)) {
073            anySyntheticAttributes = true;
074        }
075        return utf8;
076    }
077
078    public void setFileName(final String name) {
079        this.fileName = name;
080    }
081
082}