Java Code Examples for com.sun.tools.classfile.ClassFile#read()

The following examples show how to use com.sun.tools.classfile.ClassFile#read() . 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 File: CheckACC_STRICTFlagOnclinitTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
void check(String dir, String... fileNames)
    throws
        IOException,
        ConstantPoolException,
        Descriptor.InvalidDescriptor {
    for (String fileName : fileNames) {
        ClassFile classFileToCheck = ClassFile.read(new File(dir, fileName));

        for (Method method : classFileToCheck.methods) {
            if ((method.access_flags.flags & ACC_STRICT) == 0) {
                errors.add(String.format(offendingMethodErrorMessage,
                        method.getName(classFileToCheck.constant_pool),
                        classFileToCheck.getName()));
            }
        }
    }
}
 
Example 2
Source File: ClassReader.java    From jdk8u60 with 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 3
Source File: WrongLNTForLambdaTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final File cfile, String methodToFind, int[][] expectedLNT) 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 4
Source File: ByteCodeTest.java    From openjdk-jdk9 with 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 5
Source File: FindNativeFiles.java    From TencentKona-8 with 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 6
Source File: NoDeadCodeGenerationOnTrySmtTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
void checkClassFile(final File cfile, String[] methodsToFind) throws Exception {
    ClassFile classFile = ClassFile.read(cfile);
    int numberOfmethodsFound = 0;
    for (String methodToFind : methodsToFind) {
        for (Method method : classFile.methods) {
            if (method.getName(classFile.constant_pool).equals(methodToFind)) {
                numberOfmethodsFound++;
                Code_attribute code = (Code_attribute) method.attributes.get("Code");
                Assert.check(code.exception_table_length == expectedExceptionTable.length,
                        "The ExceptionTable found has a length different to the expected one");
                int i = 0;
                for (Exception_data entry: code.exception_table) {
                    Assert.check(entry.start_pc == expectedExceptionTable[i][0] &&
                            entry.end_pc == expectedExceptionTable[i][1] &&
                            entry.handler_pc == expectedExceptionTable[i][2] &&
                            entry.catch_type == expectedExceptionTable[i][3],
                            "Exception table entry at pos " + i + " differ from expected.");
                    i++;
                }
            }
        }
    }
    Assert.check(numberOfmethodsFound == 2, "Some seek methods were not found");
}
 
Example 7
Source File: DeadCodeGeneratedForEmptyTryTest.java    From hottub with 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 8
Source File: ClassReader.java    From jdk8u_jdk with 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 9
Source File: InlinedFinallyConfuseDebuggersTest.java    From openjdk-jdk8u with 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 10
Source File: ConstDebugTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    ClassFile classFile = ClassFile.read(Paths.get(System.getProperty("test.classes"),
            ConstDebugTest.class.getSimpleName() + ".class"));
    for (Method method: classFile.methods) {
        if (method.getName(classFile.constant_pool).equals("<clinit>")) {
            throw new AssertionError(
                "javac should not create a <clinit> method for ConstDebugTest class");
        }
    }
}
 
Example 11
Source File: InnerClassAttrMustNotHaveStrictFPFlagTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void analyzeClassFile(File path) throws Exception {
    ClassFile classFile = ClassFile.read(path);
    InnerClasses_attribute innerClasses =
            (InnerClasses_attribute) classFile.attributes.get(Attribute.InnerClasses);
    for (Info classInfo : innerClasses.classes) {
        Assert.check(!classInfo.inner_class_access_flags.is(AccessFlags.ACC_STRICT),
                "Inner classes attribute must not have the ACC_STRICT flag set");
    }
}
 
Example 12
Source File: TestNonSerializableLambdaNameStability.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void run() throws Exception {
    List<JavaFileObject> sources = new ArrayList<>();

    for (int i = 0; i < 3; i++) {
        sources.add(new SourceJavaFileObject("L" + i, String.format(lambdaSource, i)));
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    try (MemoryFileManager fm = new MemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
        if (!compiler.getTask(null, fm, null, null, null, sources).call()) {
            throw new AssertionError("Compilation failed!");
        }

        for (String file : fm.name2Content.keySet()) {
            byte[] fileBytes = fm.name2Content.get(file);
            try (InputStream in = new ByteArrayInputStream(fileBytes)) {
                boolean foundLambdaMethod = false;
                ClassFile cf = ClassFile.read(in);
                StringBuilder seenMethods = new StringBuilder();
                String sep = "";
                for (Method m : cf.methods) {
                    String methodName = m.getName(cf.constant_pool);
                    if (expectedLambdaMethodName.equals(methodName)) {
                        foundLambdaMethod = true;
                        break;
                    }
                    seenMethods.append(sep);
                    seenMethods.append(methodName);
                    sep = ", ";
                }

                if (!foundLambdaMethod) {
                    throw new AbstractMethodError("Did not find the lambda method, " +
                                                  "found methods: " + seenMethods.toString());
                }
            }
        }
    }
}
 
Example 13
Source File: ClassFileReader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected Set<String> scan() {
    try {
        ClassFile cf = ClassFile.read(path);
        String name = cf.access_flags.is(AccessFlags.ACC_MODULE)
            ? "module-info" : cf.getName();
        return Collections.singleton(name);
    } catch (ConstantPoolException|IOException e) {
        throw new ClassFileError(e);
    }
}
 
Example 14
Source File: ClassFileReader.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
protected ClassFile readClassFile(JarFile jarfile, JarEntry e) throws IOException {
    InputStream is = null;
    try {
        is = jarfile.getInputStream(e);
        return ClassFile.read(is);
    } catch (ConstantPoolException ex) {
        throw new ClassFileError(ex);
    } finally {
        if (is != null)
            is.close();
    }
}
 
Example 15
Source File: InnerClassCannotBeVerified.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void check() throws IOException, ConstantPoolException {
    File file = new File("Test$1.class");
    ClassFile classFile = ClassFile.read(file);
    boolean inheritsFromObject =
            classFile.getSuperclassName().equals("java/lang/Object");
    boolean implementsNoInterface = classFile.interfaces.length == 0;
    boolean noMethods = classFile.methods.length == 0;
    if (!(inheritsFromObject &&
          implementsNoInterface &&
          noMethods)) {
        throw new AssertionError("The inner classes reused as " +
                "access constructor tag for this code must be empty");
    }
}
 
Example 16
Source File: AnnotationsAreNotCopiedToBridgeMethodsTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void checkClassFile(final Path cfilePath) throws Exception {
    ClassFile classFile = ClassFile.read(
            new BufferedInputStream(Files.newInputStream(cfilePath)));
    for (Method method : classFile.methods) {
        if (method.access_flags.is(AccessFlags.ACC_BRIDGE)) {
            checkForAttr(method.attributes,
                    "Annotations hasn't been copied to bridge method",
                    Attribute.RuntimeVisibleAnnotations,
                    Attribute.RuntimeVisibleParameterAnnotations);
        }
    }
}
 
Example 17
Source File: TestNoBridgeOnDefaults.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void checkNoBridgeOnDefaults(File f) {
    System.err.println("check: " + f);
    try {
        ClassFile cf = ClassFile.read(f);
        for (Method m : cf.methods) {
            String mname = m.getName(cf.constant_pool);
            if (mname.equals(TEST_METHOD_NAME)) {
                throw new Error("unexpected bridge method found " + m);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error("error reading " + f +": " + e);
    }
}
 
Example 18
Source File: Driver.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private ClassFile compileAndReturn(String fullFile, String testClass, String... extraParams) throws Exception {
    File source = writeTestFile(fullFile);
    File clazzFile = compileTestFile(source, testClass);
    return ClassFile.read(clazzFile);
}
 
Example 19
Source File: TestCP.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
void verifyMethodHandleInvocationDescriptors(File f) {
    System.err.println("verify: " + f);
    try {
        int count = 0;
        ClassFile cf = ClassFile.read(f);
        Method testMethod = null;
        for (Method m : cf.methods) {
            if (m.getName(cf.constant_pool).equals(TEST_METHOD_NAME)) {
                testMethod = m;
                break;
            }
        }
        if (testMethod == null) {
            throw new Error("Test method not found");
        }
        Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code);
        if (testMethod == null) {
            throw new Error("Code attribute for test() method not found");
        }
        int instr_count = 0;
        int cp_entry = -1;

        for (Instruction i : ea.getInstructions()) {
            if (i.getMnemonic().equals("invokevirtual")) {
                instr_count++;
                if (cp_entry == -1) {
                    cp_entry = i.getUnsignedShort(1);
                } else if (cp_entry != i.getUnsignedShort(1)) {
                    throw new Error("Unexpected CP entry in polymorphic signature call");
                }
                CONSTANT_Methodref_info methRef =
                        (CONSTANT_Methodref_info)cf.constant_pool.get(cp_entry);
                String type = methRef.getNameAndTypeInfo().getType();
                if (!type.equals(PS_TYPE)) {
                    throw new Error("Unexpected type in polymorphic signature call: " + type);
                }
            }
        }
        if (instr_count != PS_CALLS_COUNT) {
            throw new Error("Wrong number of polymorphic signature call found: " + instr_count);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error("error reading " + f +": " + e);
    }
}
 
Example 20
Source File: T7093325.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
void verifyBytecode(JavaSource source, int id) {
    boolean lastInlined = false;
    boolean hasCode = false;
    int gapsCount = 0;
    for (int i = 0; i < stmts.length ; i++) {
        lastInlined = stmts[i].canInline;
        hasCode = hasCode || !stmts[i].empty;
        if (lastInlined && hasCode) {
            hasCode = false;
            gapsCount++;
        }
    }
    if (!lastInlined) {
        gapsCount++;
    }

    File compiledTest = new File(String.format("Test%s.class", id));
    try {
        ClassFile cf = ClassFile.read(compiledTest);
        if (cf == null) {
            throw new Error("Classfile not found: " +
                            compiledTest.getName());
        }

        Method test_method = null;
        for (Method m : cf.methods) {
            if (m.getName(cf.constant_pool).equals("test")) {
                test_method = m;
                break;
            }
        }

        if (test_method == null) {
            throw new Error("Method test() not found in class Test");
        }

        Code_attribute code = null;
        for (Attribute a : test_method.attributes) {
            if (a.getName(cf.constant_pool).equals(Attribute.Code)) {
                code = (Code_attribute)a;
                break;
            }
        }

        if (code == null) {
            throw new Error("Code attribute not found in method test()");
        }

        int actualGapsCount = 0;
        for (int i = 0; i < code.exception_table_length ; i++) {
            int catchType = code.exception_table[i].catch_type;
            if (catchType == 0) { //any
                actualGapsCount++;
            }
        }

        if (actualGapsCount != gapsCount) {
            throw new Error("Bad exception table for test()\n" +
                        "expected gaps: " + gapsCount + "\n" +
                        "found gaps: " + actualGapsCount + "\n" +
                        source);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error("error reading " + compiledTest +": " + e);
    }

}