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