com.sun.tools.classfile.ClassFile Java Examples

The following examples show how to use com.sun.tools.classfile.ClassFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: jdk8u60   Author: chenghanpeng   File: DuplicateConstantPoolEntry.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkReference() throws IOException, ConstantPoolException {
    File file = new File("A.class");
    ClassFile classFile = ClassFile.read(file);
    for (int i = 1;
            i < classFile.constant_pool.size() - 1;
            i += classFile.constant_pool.get(i).size()) {
        for (int j = i + classFile.constant_pool.get(i).size();
                j < classFile.constant_pool.size();
                j += classFile.constant_pool.get(j).size()) {
            if (classFile.constant_pool.get(i).toString().
                    equals(classFile.constant_pool.get(j).toString())) {
                throw new AssertionError(
                        "Duplicate entries in the constant pool at positions " +
                        i + " and " + j);
            }
        }
    }
}
 
Example #2
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: DetectMutableStaticFields.java    License: GNU General Public License v2.0 6 votes vote down vote up
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example #3
Source Project: dragonwell8_jdk   Author: alibaba   File: LambdaAsm.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void verifyASM() throws Exception {
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_8, ACC_PUBLIC, "X", null, "java/lang/Object", null);
    MethodVisitor mv = cw.visitMethod(ACC_STATIC, "foo",
            "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitMethodInsn(INVOKESTATIC,
            "java/util/function/Function.class",
            "identity", "()Ljava/util/function/Function;", true);
    mv.visitInsn(RETURN);
    cw.visitEnd();
    byte[] carray = cw.toByteArray();
    // for debugging
    // write((new File("X.class")).toPath(), carray, CREATE, TRUNCATE_EXISTING);

    // verify using javap/classfile reader
    ClassFile cf = ClassFile.read(new ByteArrayInputStream(carray));
    int mcount = checkMethod(cf, "foo");
    if (mcount < 1) {
        throw new RuntimeException("unexpected method count, expected 1" +
                "but got " + mcount);
    }
}
 
Example #4
Source Project: dragonwell8_jdk   Author: alibaba   File: ClassReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Element readFrom(InputStream in) throws IOException {
    try {
        this.in = in;
        ClassFile c = ClassFile.read(in);
        // read the file header
        if (c.magic != 0xCAFEBABE) {
            throw new RuntimeException("bad magic number " +
                    Integer.toHexString(c.magic));
        }
        cfile.setAttr("magic", "" + c.magic);
        int minver = c.minor_version;
        int majver = c.major_version;
        cfile.setAttr("minver", "" + minver);
        cfile.setAttr("majver", "" + majver);
        readCP(c);
        readClass(c);
        return result();
    } catch (InvalidDescriptor | ConstantPoolException ex) {
        throw new IOException("Fatal error", ex);
    }
}
 
Example #5
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: ClassReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Element readFrom(InputStream in) throws IOException {
    try {
        this.in = in;
        ClassFile c = ClassFile.read(in);
        // read the file header
        if (c.magic != 0xCAFEBABE) {
            throw new RuntimeException("bad magic number " +
                    Integer.toHexString(c.magic));
        }
        cfile.setAttr("magic", "" + c.magic);
        int minver = c.minor_version;
        int majver = c.major_version;
        cfile.setAttr("minver", "" + minver);
        cfile.setAttr("majver", "" + majver);
        readCP(c);
        readClass(c);
        return result();
    } catch (InvalidDescriptor | ConstantPoolException ex) {
        throw new IOException("Fatal error", ex);
    }
}
 
Example #6
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: InlinedFinallyConfuseDebuggersTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final File cfile, String methodToFind) throws Exception {
    ClassFile classFile = ClassFile.read(cfile);
    boolean methodFound = false;
    for (Method method : classFile.methods) {
        if (method.getName(classFile.constant_pool).equals(methodToFind)) {
            methodFound = true;
            Code_attribute code = (Code_attribute) method.attributes.get("Code");
            LineNumberTable_attribute lnt =
                    (LineNumberTable_attribute) code.attributes.get("LineNumberTable");
            Assert.check(lnt.line_number_table_length == expectedLNT.length,
                    "The LineNumberTable found has a length different to the expected one");
            int i = 0;
            for (LineNumberTable_attribute.Entry entry: lnt.line_number_table) {
                Assert.check(entry.line_number == expectedLNT[i][0] &&
                        entry.start_pc == expectedLNT[i][1],
                        "LNT entry at pos " + i + " differ from expected." +
                        "Found " + entry.line_number + ":" + entry.start_pc +
                        ". Expected " + expectedLNT[i][0] + ":" + expectedLNT[i][1]);
                i++;
            }
        }
    }
    Assert.check(methodFound, "The seek method was not found");
}
 
Example #7
Source Project: dragonwell8_jdk   Author: alibaba   File: ClassReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void readCP(ClassFile c) throws IOException {
    cpool = new Element("ConstantPool", c.constant_pool.size());
    ConstantPoolVisitor cpv = new ConstantPoolVisitor(cpool, c,
            c.constant_pool.size());
    for (int i = 1 ; i < c.constant_pool.size() ; i++) {
        try {
            cpv.visit(c.constant_pool.get(i), i);
        } catch (InvalidIndex ex) {
            // can happen periodically when accessing doubles etc. ignore it
            // ex.printStackTrace();
        }
    }
    thePool = cpv.getPoolList();
    if (verbose) {
        for (int i = 0; i < thePool.size(); i++) {
            System.out.println("[" + i + "]: " + thePool.get(i));
        }
    }
    if (keepCP) {
        cfile.add(cpool);
    }
}
 
Example #8
Source Project: hottub   Author: dsrg-uoft   File: DetectMutableStaticFields.java    License: GNU General Public License v2.0 6 votes vote down vote up
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example #9
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: DeadCodeGeneratedForEmptyTryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final Path path) throws Exception {
    ClassFile classFile = ClassFile.read(
            new BufferedInputStream(Files.newInputStream(path)));
    constantPool = classFile.constant_pool;
    utf8Index = constantPool.getUTF8Index("STR_TO_LOOK_FOR");
    for (Method method: classFile.methods) {
        if (method.getName(constantPool).equals("methodToLookFor")) {
            Code_attribute codeAtt = (Code_attribute)method.attributes.get(Attribute.Code);
            for (Instruction inst: codeAtt.getInstructions()) {
                inst.accept(codeVisitor, null);
            }
        }
    }
    Assert.check(numberOfRefToStr == 1,
            "There should only be one reference to a CONSTANT_String_info structure in the generated code");
}
 
Example #10
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: LVTHarness.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(File file)
        throws IOException, ConstantPoolException, InvalidDescriptor {
    ClassFile classFile = ClassFile.read(file);
    ConstantPool constantPool = classFile.constant_pool;

    //lets get all the methods in the class file.
    for (Method method : classFile.methods) {
        for (ElementKey elementKey: aliveRangeMap.keySet()) {
            String methodDesc = method.getName(constantPool) +
                    method.descriptor.getParameterTypes(constantPool).replace(" ", "");
            if (methodDesc.equals(elementKey.elem.toString())) {
                checkMethod(constantPool, method, aliveRangeMap.get(elementKey));
                seenAliveRanges.add(elementKey);
            }
        }
    }
}
 
Example #11
Source Project: openjdk-8   Author: bpupadhyaya   File: ReferenceInfoUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean compare(Map<String, TypeAnnotation.Position> expectedAnnos,
        List<TypeAnnotation> actualAnnos, ClassFile cf) throws InvalidIndex, UnexpectedEntry {
    if (actualAnnos.size() != expectedAnnos.size()) {
        throw new ComparisionException("Wrong number of annotations",
                expectedAnnos,
                actualAnnos);
    }

    for (Map.Entry<String, TypeAnnotation.Position> e : expectedAnnos.entrySet()) {
        String aName = e.getKey();
        TypeAnnotation.Position expected = e.getValue();
        TypeAnnotation actual = findAnnotation(aName, actualAnnos, cf);
        if (actual == null)
            throw new ComparisionException("Expected annotation not found: " + aName);

        // TODO: you currently get an exception if the test case does not use all necessary
        // annotation attributes, e.g. forgetting the offset for a local variable.
        // It would be nicer to give an understandable warning instead.
        if (!areEquals(expected, actual.position)) {
            throw new ComparisionException("Unexpected position for annotation : " + aName +
                    "\n  Expected: " + expected.toString() +
                    "\n  Found: " + actual.position.toString());
        }
    }
    return true;
}
 
Example #12
Source Project: hottub   Author: dsrg-uoft   File: CompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
boolean isNativeClass(JarFile jar, JarEntry entry) throws IOException, ConstantPoolException {
    String name = entry.getName();
    if (name.startsWith("META-INF") || !name.endsWith(".class"))
        return false;
    //String className = name.substring(0, name.length() - 6).replace("/", ".");
    //System.err.println("check " + className);
    InputStream in = jar.getInputStream(entry);
    ClassFile cf = ClassFile.read(in);
    for (int i = 0; i < cf.methods.length; i++) {
        Method m = cf.methods[i];
        if (m.access_flags.is(AccessFlags.ACC_NATIVE)) {
            // System.err.println(className);
            return true;
        }
    }
    return false;
}
 
Example #13
Source Project: openjdk-8   Author: bpupadhyaya   File: DeadCodeGeneratedForEmptyTryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final Path path) throws Exception {
    ClassFile classFile = ClassFile.read(
            new BufferedInputStream(Files.newInputStream(path)));
    constantPool = classFile.constant_pool;
    utf8Index = constantPool.getUTF8Index("STR_TO_LOOK_FOR");
    for (Method method: classFile.methods) {
        if (method.getName(constantPool).equals("methodToLookFor")) {
            Code_attribute codeAtt = (Code_attribute)method.attributes.get(Attribute.Code);
            for (Instruction inst: codeAtt.getInstructions()) {
                inst.accept(codeVisitor, null);
            }
        }
    }
    Assert.check(numberOfRefToStr == 1,
            "There should only be one reference to a CONSTANT_String_info structure in the generated code");
}
 
Example #14
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: DeadCodeGeneratedForEmptyTryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final Path path) throws Exception {
    ClassFile classFile = ClassFile.read(
            new BufferedInputStream(Files.newInputStream(path)));
    constantPool = classFile.constant_pool;
    utf8Index = constantPool.getUTF8Index("STR_TO_LOOK_FOR");
    for (Method method: classFile.methods) {
        if (method.getName(constantPool).equals("methodToLookFor")) {
            Code_attribute codeAtt = (Code_attribute)method.attributes.get(Attribute.Code);
            for (Instruction inst: codeAtt.getInstructions()) {
                inst.accept(codeVisitor, null);
            }
        }
    }
    Assert.check(numberOfRefToStr == 1,
            "There should only be one reference to a CONSTANT_String_info structure in the generated code");
}
 
Example #15
Source Project: openjdk-8-source   Author: keerath   File: ReferenceInfoUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean compare(Map<String, TypeAnnotation.Position> expectedAnnos,
        List<TypeAnnotation> actualAnnos, ClassFile cf) throws InvalidIndex, UnexpectedEntry {
    if (actualAnnos.size() != expectedAnnos.size()) {
        throw new ComparisionException("Wrong number of annotations",
                expectedAnnos,
                actualAnnos);
    }

    for (Map.Entry<String, TypeAnnotation.Position> e : expectedAnnos.entrySet()) {
        String aName = e.getKey();
        TypeAnnotation.Position expected = e.getValue();
        TypeAnnotation actual = findAnnotation(aName, actualAnnos, cf);
        if (actual == null)
            throw new ComparisionException("Expected annotation not found: " + aName);

        // TODO: you currently get an exception if the test case does not use all necessary
        // annotation attributes, e.g. forgetting the offset for a local variable.
        // It would be nicer to give an understandable warning instead.
        if (!areEquals(expected, actual.position)) {
            throw new ComparisionException("Unexpected position for annotation : " + aName +
                    "\n  Expected: " + expected.toString() +
                    "\n  Found: " + actual.position.toString());
        }
    }
    return true;
}
 
Example #16
Source Project: jdk8u60   Author: chenghanpeng   File: LVTHarness.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(File file)
        throws IOException, ConstantPoolException, InvalidDescriptor {
    ClassFile classFile = ClassFile.read(file);
    ConstantPool constantPool = classFile.constant_pool;

    //lets get all the methods in the class file.
    for (Method method : classFile.methods) {
        for (ElementKey elementKey: aliveRangeMap.keySet()) {
            String methodDesc = method.getName(constantPool) +
                    method.descriptor.getParameterTypes(constantPool).replace(" ", "");
            if (methodDesc.equals(elementKey.elem.toString())) {
                checkMethod(constantPool, method, aliveRangeMap.get(elementKey));
                seenAliveRanges.add(elementKey);
            }
        }
    }
}
 
Example #17
Source Project: TencentKona-8   Author: Tencent   File: CompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
boolean isNativeClass(JarFile jar, JarEntry entry) throws IOException, ConstantPoolException {
    String name = entry.getName();
    if (name.startsWith("META-INF") || !name.endsWith(".class"))
        return false;
    //String className = name.substring(0, name.length() - 6).replace("/", ".");
    //System.err.println("check " + className);
    InputStream in = jar.getInputStream(entry);
    ClassFile cf = ClassFile.read(in);
    for (int i = 0; i < cf.methods.length; i++) {
        Method m = cf.methods[i];
        if (m.access_flags.is(AccessFlags.ACC_NATIVE)) {
            // System.err.println(className);
            return true;
        }
    }
    return false;
}
 
Example #18
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: LambdaAsm.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void verifyInvokerBytecodeGenerator() throws Exception {
    int count = 0;
    int mcount = 0;
    try (DirectoryStream<Path> ds = newDirectoryStream(new File(".").toPath(),
            // filter in lambda proxy classes
            "A$I$$Lambda$?.class")) {
        for (Path p : ds) {
            System.out.println(p.toFile());
            ClassFile cf = ClassFile.read(p.toFile());
            // Check those methods implementing Supplier.get
            mcount += checkMethod(cf, "get");
            count++;
        }
    }
    if (count < 3) {
        throw new RuntimeException("unexpected number of files, "
                + "expected atleast 3 files, but got only " + count);
    }
    if (mcount < 3) {
        throw new RuntimeException("unexpected number of methods, "
                + "expected atleast 3 methods, but got only " + mcount);
    }
}
 
Example #19
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: LVTHarness.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(File file)
        throws IOException, ConstantPoolException, InvalidDescriptor {
    ClassFile classFile = ClassFile.read(file);
    ConstantPool constantPool = classFile.constant_pool;

    //lets get all the methods in the class file.
    for (Method method : classFile.methods) {
        for (ElementKey elementKey: aliveRangeMap.keySet()) {
            String methodDesc = method.getName(constantPool) +
                    method.descriptor.getParameterTypes(constantPool).replace(" ", "");
            if (methodDesc.equals(elementKey.elem.toString())) {
                checkMethod(constantPool, method, aliveRangeMap.get(elementKey));
                seenAliveRanges.add(elementKey);
            }
        }
    }
}
 
Example #20
Source Project: hottub   Author: dsrg-uoft   File: ClassReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Element readFrom(InputStream in) throws IOException {
    try {
        this.in = in;
        ClassFile c = ClassFile.read(in);
        // read the file header
        if (c.magic != 0xCAFEBABE) {
            throw new RuntimeException("bad magic number " +
                    Integer.toHexString(c.magic));
        }
        cfile.setAttr("magic", "" + c.magic);
        int minver = c.minor_version;
        int majver = c.major_version;
        cfile.setAttr("minver", "" + minver);
        cfile.setAttr("majver", "" + majver);
        readCP(c);
        readClass(c);
        return result();
    } catch (InvalidDescriptor | ConstantPoolException ex) {
        throw new IOException("Fatal error", ex);
    }
}
 
Example #21
Source Project: openjdk-8-source   Author: keerath   File: CompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
boolean isNativeClass(JarFile jar, JarEntry entry) throws IOException, ConstantPoolException {
    String name = entry.getName();
    if (name.startsWith("META-INF") || !name.endsWith(".class"))
        return false;
    //String className = name.substring(0, name.length() - 6).replace("/", ".");
    //System.err.println("check " + className);
    InputStream in = jar.getInputStream(entry);
    ClassFile cf = ClassFile.read(in);
    for (int i = 0; i < cf.methods.length; i++) {
        Method m = cf.methods[i];
        if (m.access_flags.is(AccessFlags.ACC_NATIVE)) {
            // System.err.println(className);
            return true;
        }
    }
    return false;
}
 
Example #22
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: DeprecatedTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void test(String src) {
    addTestCase(src);
    printf("Testing test case :\n%s\n", src);
    try {
        Map<String, ? extends JavaFileObject> classes = compile(src).getClasses();
        String outerClassName = classes.containsKey("deprecated")
                ? "deprecated"
                : "notDeprecated";
        echo("Testing outer class : " + outerClassName);
        ClassFile cf = readClassFile(classes.get(outerClassName));
        Deprecated_attribute attr = (Deprecated_attribute)
                cf.getAttribute(Attribute.Deprecated);
        testAttribute(outerClassName, attr, cf);
        testInnerClasses(cf, classes);
        testMethods(cf);
        testFields(cf);
    } catch (Exception e) {
        addFailure(e);
    }
}
 
Example #23
Source Project: openjdk-8-source   Author: keerath   File: DuplicateConstantPoolEntry.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkReference() throws IOException, ConstantPoolException {
    File file = new File("A.class");
    ClassFile classFile = ClassFile.read(file);
    for (int i = 1;
            i < classFile.constant_pool.size() - 1;
            i += classFile.constant_pool.get(i).size()) {
        for (int j = i + classFile.constant_pool.get(i).size();
                j < classFile.constant_pool.size();
                j += classFile.constant_pool.get(j).size()) {
            if (classFile.constant_pool.get(i).toString().
                    equals(classFile.constant_pool.get(j).toString())) {
                throw new AssertionError(
                        "Duplicate entries in the constant pool at positions " +
                        i + " and " + j);
            }
        }
    }
}
 
Example #24
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ByteCodeTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean verifyClassFileAttributes(File classFile, TestCases tc) {
    ClassFile c = null;
    try {
        c = ClassFile.read(classFile);
    } catch (IOException | ConstantPoolException e) {
        e.printStackTrace();
    }
    ConstantPoolVisitor cpv = new ConstantPoolVisitor(c, c.constant_pool.size());
    Map<Integer, String> hm = cpv.getBSMMap();

    List<String> expectedValList = tc.getExpectedArgValues();
    expectedValList.add(tc.bsmSpecifier.specifier);
    if(!(hm.values().containsAll(new HashSet<String>(expectedValList)))) {
        System.out.println("Values do not match");
        return false;
    }
    return true;
}
 
Example #25
Source Project: openjdk-8   Author: bpupadhyaya   File: ClassFileReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public ClassFile next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }

    ClassFile cf;
    try {
        cf = readClassFile(nextEntry);
    } catch (IOException ex) {
        throw new ClassFileError(ex);
    }
    JarEntry entry = nextEntry;
    nextEntry = null;
    while (entries.hasMoreElements()) {
        JarEntry e = entries.nextElement();
        String name = e.getName();
        if (name.endsWith(".class")) {
            nextEntry = e;
            break;
        }
    }
    return cf;
}
 
Example #26
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ByteCodeTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean verifyClassFileAttributes(File classFile, TestCases tc) {
    ClassFile c = null;
    try {
        c = ClassFile.read(classFile);
    } catch (IOException | ConstantPoolException e) {
        e.printStackTrace();
    }
    ConstantPoolVisitor cpv = new ConstantPoolVisitor(c, c.constant_pool.size());
    Map<Integer, String> hm = cpv.getBSMMap();

    List<String> expectedValList = tc.getExpectedArgValues();
    expectedValList.add(tc.bsmSpecifier.specifier);
    if(!(hm.values().containsAll(new HashSet<String>(expectedValList)))) {
        System.out.println("Values do not match");
        return false;
    }
    return true;
}
 
Example #27
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TypeAnnotationPropagationTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void run() throws Exception {
    ClassFile cf = getClassFile("TypeAnnotationPropagationTest$Test.class");

    Method f = null;
    for (Method m : cf.methods) {
        if (m.getName(cf.constant_pool).contains("f")) {
            f = m;
            break;
        }
    }

    int idx = f.attributes.getIndex(cf.constant_pool, Attribute.Code);
    Code_attribute cattr = (Code_attribute) f.attributes.get(idx);
    idx = cattr.attributes.getIndex(cf.constant_pool, Attribute.RuntimeVisibleTypeAnnotations);
    RuntimeVisibleTypeAnnotations_attribute attr =
            (RuntimeVisibleTypeAnnotations_attribute) cattr.attributes.get(idx);

    TypeAnnotation anno = attr.annotations[0];
    assertEquals(anno.position.lvarOffset, new int[] {3}, "start_pc");
    assertEquals(anno.position.lvarLength, new int[] {8}, "length");
    assertEquals(anno.position.lvarIndex, new int[] {1}, "index");
}
 
Example #28
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: FindNativeFiles.java    License: GNU General Public License v2.0 6 votes vote down vote up
boolean isNativeClass(JarFile jar, JarEntry entry) throws IOException, ConstantPoolException {
    String name = entry.getName();
    if (name.startsWith("META-INF") || !name.endsWith(".class"))
        return false;
    //String className = name.substring(0, name.length() - 6).replace("/", ".");
    //System.err.println("check " + className);
    InputStream in = jar.getInputStream(entry);
    ClassFile cf = ClassFile.read(in);
    in.close();
    for (int i = 0; i < cf.methods.length; i++) {
        Method m = cf.methods[i];
        if (m.access_flags.is(AccessFlags.ACC_NATIVE)) {
            // System.err.println(className);
            return true;
        }
    }
    return false;
}
 
Example #29
Source Project: openjdk-8   Author: bpupadhyaya   File: InlinedFinallyConfuseDebuggersTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final File cfile, String methodToFind) throws Exception {
    ClassFile classFile = ClassFile.read(cfile);
    boolean methodFound = false;
    for (Method method : classFile.methods) {
        if (method.getName(classFile.constant_pool).equals(methodToFind)) {
            methodFound = true;
            Code_attribute code = (Code_attribute) method.attributes.get("Code");
            LineNumberTable_attribute lnt =
                    (LineNumberTable_attribute) code.attributes.get("LineNumberTable");
            Assert.check(lnt.line_number_table_length == expectedLNT.length,
                    "The LineNumberTable found has a length different to the expected one");
            int i = 0;
            for (LineNumberTable_attribute.Entry entry: lnt.line_number_table) {
                Assert.check(entry.line_number == expectedLNT[i][0] &&
                        entry.start_pc == expectedLNT[i][1],
                        "LNT entry at pos " + i + " differ from expected." +
                        "Found " + entry.line_number + ":" + entry.start_pc +
                        ". Expected " + expectedLNT[i][0] + ":" + expectedLNT[i][1]);
                i++;
            }
        }
    }
    Assert.check(methodFound, "The seek method was not found");
}
 
Example #30
Source Project: openjdk-8   Author: bpupadhyaya   File: TestDirectSuperInterfaceInvoke.java    License: GNU General Public License v2.0 6 votes vote down vote up
void verifyDefaultBody(String classFile) {
    String workDir = System.getProperty("test.classes");
    File file = new File(workDir, classFile);
    try {
        final ClassFile cf = ClassFile.read(file);
        for (Method m : cf.methods) {
            Code_attribute codeAttr = (Code_attribute)m.attributes.get(Attribute.Code);
            for (Instruction instr : codeAttr.getInstructions()) {
                if (instr.getOpcode() == Opcode.INVOKESPECIAL) {
                    int pc_index = instr.getShort(1);
                    CPRefInfo ref = (CPRefInfo)cf.constant_pool.get(pc_index);
                    String className = ref.getClassName();
                    if (className.equals("BaseInterface"))
                        throw new IllegalStateException("Must not directly refer to TestedInterface");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error("error reading " + file +": " + e);
    }
}