net.bytebuddy.jar.asm.ClassReader Java Examples

The following examples show how to use net.bytebuddy.jar.asm.ClassReader. 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: InstrumentationUtils.java    From BlockHound with Apache License 2.0 6 votes vote down vote up
static void injectBootstrapClasses(Instrumentation instrumentation, String... classNames) throws IOException {
    File tempJarFile = File.createTempFile("BlockHound", ".jar");
    tempJarFile.deleteOnExit();

    ClassLoader classLoader = BlockHound.class.getClassLoader();
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempJarFile))) {
        for (String className : classNames) {
            String classFile = className.replace(".", "/") + ".class";
            try (InputStream inputStream = classLoader.getResourceAsStream(classFile)) {
                ZipEntry entry = new ZipEntry(classFile);
                zipOutputStream.putNextEntry(entry);

                ClassReader cr = new ClassReader(inputStream);
                ClassWriter cw = new ClassWriter(cr, 0);

                cr.accept(new MakePublicClassVisitor(cw), 0);

                zipOutputStream.write(cw.toByteArray());
            }

            zipOutputStream.closeEntry();
        }
    }
    instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(tempJarFile));
}
 
Example #2
Source File: ClassFileExtraction.java    From garmadon with Apache License 2.0 5 votes vote down vote up
public static byte[] extract(Class<?> type, AsmVisitorWrapper asmVisitorWrapper) throws IOException {
    ClassReader classReader = new ClassReader(type.getName());
    ClassWriter classWriter = new ClassWriter(classReader, AsmVisitorWrapper.NO_FLAGS);
    classReader.accept(asmVisitorWrapper.wrap(new TypeDescription.ForLoadedType(type),
            classWriter,
            new IllegalContext(),
            TypePool.Empty.INSTANCE,
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            AsmVisitorWrapper.NO_FLAGS,
            AsmVisitorWrapper.NO_FLAGS), AsmVisitorWrapper.NO_FLAGS);
    return classWriter.toByteArray();
}
 
Example #3
Source File: MixinClassVisitor.java    From kanela with Apache License 2.0 5 votes vote down vote up
@Override
public void visitEnd() {
    Try.run(() -> {
        // By default, ClassReader will try to use the System ClassLoader to load the classes but we need to make sure
        // that all classes are loaded with Kanela's Instrumentation ClassLoader (which some times might be the
        // System ClassLoader and some others will be an Attach ClassLoader).
        val classLoader = InstrumentationClassPath.last()
                .map(InstrumentationClassPath::getClassLoader)
                .getOrElse(() -> Thread.currentThread().getContextClassLoader());

        val mixinClassFileName = mixin.getMixinClass().getName().replace('.', '/') + ".class";

        try (val classStream = classLoader.getResourceAsStream(mixinClassFileName)) {
            val cr = new ClassReader(classStream);
            val cn = new ClassNode();
            cr.accept(cn, ClassReader.EXPAND_FRAMES);

            cn.fields.forEach(fieldNode -> fieldNode.accept(this));
            cn.methods.stream().filter(isConstructor()).forEach(mn -> {
                String[] exceptions = new String[mn.exceptions.size()];
                MethodVisitor mv = cv.visitMethod(mn.access, mn.name, mn.desc, mn.signature, exceptions);
                mn.accept(new MethodRemapper(mv, new SimpleRemapper(cn.name, type.getInternalName())));
            });
        }
        super.visitEnd();
    });
}
 
Example #4
Source File: FrontendDependencies.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Recursive method for visiting class names using bytecode inspection.
 *
 * @param className
 * @param endPoint
 * @return
 * @throws IOException
 */
private EndPointData visitClass(String className, EndPointData endPoint,
        boolean themeScope) throws IOException {

    // In theme scope, we want to revisit already visited classes to have
    // theme modules collected separately (in turn required for module
    // sorting, #5729)
    if (!isVisitable(className)
            || (!themeScope && endPoint.getClasses().contains(className))) {
        return endPoint;
    }
    endPoint.getClasses().add(className);

    URL url = getUrl(className);
    if (url == null) {
        return endPoint;
    }

    FrontendClassVisitor visitor = new FrontendClassVisitor(className,
            endPoint, themeScope);
    ClassReader cr = new ClassReader(url.openStream());
    cr.accept(visitor, ClassReader.EXPAND_FRAMES);

    // all classes visited by the scanner, used for performance (#5933)
    visited.add(className);

    for (String clazz : visitor.getChildren()) {
        // Since we only have an entry point for the app, it is all right to
        // skip the visit to the the same class in other end-points, because
        // we output all dependencies at once. When we implement
        // chunks, this will need to be considered.
        if (!visited.contains(clazz)) {
            visitClass(clazz, endPoint, themeScope);
        }
    }

    return endPoint;
}
 
Example #5
Source File: BridgeClassVisitorWrapper.java    From kanela with Apache License 2.0 4 votes vote down vote up
@Override
public int mergeReader(int flags) {
    return flags | ClassReader.EXPAND_FRAMES;
}
 
Example #6
Source File: MixinClassVisitorWrapper.java    From kanela with Apache License 2.0 4 votes vote down vote up
@Override
public int mergeReader(int flags) {
    return flags | ClassReader.EXPAND_FRAMES;
}
 
Example #7
Source File: AnalyzedClass.java    From kanela with Apache License 2.0 4 votes vote down vote up
private static ClassNode convertToClassNode(InputStream classBytes) throws IOException {
    val result = new ClassNode(OpenedClassReader.ASM_API);
    val reader =  new ClassReader(classBytes);
    reader.accept(result, ClassReader.SKIP_FRAMES);
    return result;
}
 
Example #8
Source File: ReactorDebugAgent.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
private static void instrument(Instrumentation instrumentation) {
	ClassFileTransformer transformer = new ClassFileTransformer() {
		@Override
		public byte[] transform(
				ClassLoader loader,
				String className,
				Class<?> clazz,
				ProtectionDomain protectionDomain,
				byte[] bytes
		) {
			if (loader == null) {
				return null;
			}

			if (
					className == null ||
							className.startsWith("java/") ||
							className.startsWith("jdk/") ||
							className.startsWith("sun/") ||
							className.startsWith("com/sun/") ||
							className.startsWith("reactor/core/")
			) {
				return null;
			}

			if (
					clazz != null && (
							clazz.isPrimitive() ||
									clazz.isArray() ||
									clazz.isAnnotation() ||
									clazz.isSynthetic()
					)
			) {
				return null;
			}

			ClassReader cr = new ClassReader(bytes);
			ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);

			AtomicBoolean changed = new AtomicBoolean();
			ClassVisitor classVisitor = new ReactorDebugClassVisitor(cw, changed);

			try {
				cr.accept(classVisitor, 0);
			}
			catch (Throwable e) {
				e.printStackTrace();
				throw e;
			}

			if (!changed.get()) {
				return null;
			}

			return cw.toByteArray();
		}
	};

	instrumentation.addTransformer(transformer, true);
}