org.objectweb.asm.ClassWriter Java Examples

The following examples show how to use org.objectweb.asm.ClassWriter. 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: DefaultApplicationFactory.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public static byte[] create(String name, String path) throws IOException {
    ClassReader reader = new ClassReader(basicClassBytes());

    String slashName = name.replace('.', '/');

    ClassWriter writer = new ClassWriter(0);
    Remapper remapper = new Remapper() {
        @Override
        public String map(String typeName) {
            if (typeName.equals("org/wildfly/swarm/jaxrs/runtime/DefaultApplication")) {
                return slashName;
            }
            return super.map(typeName);
        }
    };

    ClassRemapper adapter = new ClassRemapper(writer, remapper);
    reader.accept(adapter, 0);

    AnnotationVisitor ann = writer.visitAnnotation("Ljavax/ws/rs/ApplicationPath;", true);
    ann.visit("value", path);
    ann.visitEnd();
    writer.visitEnd();

    return writer.toByteArray();
}
 
Example #2
Source File: MonitorClassFileTransformer.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] transform(final String className,
                           final Class<?> classBeingRedefined,
                           final ProtectionDomain protectionDomain,
                           final byte[] classBytes) throws IllegalClassFormatException {
    if (!Objects.equal(className, monitorClassName)) {
        return null;
    }
    LOG.info("monitor class: {}", className);
    Lock lock = classFileBuffer.getLock();
    lock.lock();
    try {
        final ClassReader classReader = new ClassReader(classFileBuffer.getClassBuffer(classBeingRedefined, classBytes));
        final ClassWriter classWriter = new ClassWriter(computeFlag(classReader));
        final ClassVisitor classVisitor = new MonitorClassVisitor(new CheckClassAdapter(classWriter), methodName, methodDesc);
        classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
        byte[] bytes = classWriter.toByteArray();
        classFileBuffer.setClassBuffer(classBeingRedefined, bytes);
        return bytes;
    } finally {
        lock.unlock();
    }
}
 
Example #3
Source File: ContinuableClassTransformer.java    From tascalate-javaflow with Apache License 2.0 6 votes vote down vote up
public byte[] transform(byte[] original, Collection<String> retransformClasses) {
    ClassReader reader = new ClassReader(original);
    ClassWriter writer = new OfflineClassWriter(classHierarchy, reader, ClassWriter.COMPUTE_FRAMES);
    ContinuableClassVisitor visitor = new ContinuableClassVisitor(
        writer, /* BytecodeDebugUtils.decorateClassVisitor(cw, true, * System.err) -- DUMP*/ 
        classHierarchy,
        cciResolver,
        original
    );
    cciResolver.reset(retransformClasses);
    try {
        reader.accept(visitor, ClassReader.SKIP_FRAMES);
    } catch (StopException ex) {
        // Preliminary stop visiting non-continuable class
        return null;
    }

    if (visitor.skipEnchancing()) {
        return null;
    }

    byte[] bytecode = writer.toByteArray();
    // BytecodeDebugUtils.dumpClass(bytecode);
    return bytecode;
}
 
Example #4
Source File: Bug62456849TestDataGenerator.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static byte[] convertClass(ZipFile file, ZipEntry entry) throws IOException {
  try (InputStream content = file.getInputStream(entry)) {
    ClassReader reader = new ClassReader(content);
    ClassWriter writer = new ClassWriter(0);
    ClassVisitor converter =
        new ClassVisitor(Opcodes.ASM5, writer) {
          @Override
          public MethodVisitor visitMethod(
              int access, String name, String desc, String signature, String[] exceptions) {
            if (name.startsWith("lambda$") && (access & Opcodes.ACC_SYNTHETIC) == 0) {
              access |= Opcodes.ACC_SYNTHETIC;
            }
            return super.visitMethod(access, name, desc, signature, exceptions);
          }
        };
    reader.accept(converter, 0);
    return writer.toByteArray();
  }
}
 
Example #5
Source File: ClassTransformer.java    From TcpNoDelayMod with MIT License 6 votes vote down vote up
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
    if (bytes == null) {
        return null;
    }
    // check for any inner classes of NetworkManager. It differes between mc versions
    if (transformedName.startsWith("net.minecraft.network.NetworkManager$")) {
        try {
            ClassReader classReader = new ClassReader(bytes);
            ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES);
            ClassVisitor classVisitor = new NetworkManagerInnerVisitor(classWriter);
            classReader.accept(classVisitor, ClassReader.SKIP_FRAMES);
            return classWriter.toByteArray();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    return bytes;
}
 
Example #6
Source File: MarkerClassGenerator.java    From OpenModsLib with MIT License 6 votes vote down vote up
private <T> Class<? extends T> createMarkerCls(Class<T> superClass, int key) {
	final ClassWriter writer = new ClassWriter(0);

	final String superCls = Type.getInternalName(superClass);
	writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, superCls + "$marker_" + key, null, superCls, interfaces);

	final MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, "getMarkerValue", "()I", null, null);
	mv.visitCode();
	mv.visitLdcInsn(key);
	mv.visitInsn(Opcodes.IRETURN);
	mv.visitMaxs(1, 1);
	mv.visitEnd();

	writer.visitEnd();

	@SuppressWarnings("unchecked")
	final Class<? extends T> cls = (Class<? extends T>)loader.define(writer.toByteArray());
	return cls;
}
 
Example #7
Source File: UnbalancedMonitorsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void visitConstructor(ClassWriter cw) {
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitInsn(RETURN);
    Label l2 = new Label();
    mv.visitLabel(l2);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
}
 
Example #8
Source File: AtlasFixStackFramesTransform.java    From atlas with Apache License 2.0 6 votes vote down vote up
@NonNull
private static byte[] getFixedClass(
        @NonNull InputStream originalFile, @NonNull URLClassLoader classLoader)
        throws IOException {
    byte[] bytes = ByteStreams.toByteArray(originalFile);
    try {
        ClassReader classReader = new ClassReader(bytes);
        ClassWriter classWriter = new AtlasFixStackFramesTransform.FixFramesVisitor(ClassWriter.COMPUTE_FRAMES, classLoader);
        classReader.accept(classWriter, ClassReader.SKIP_FRAMES);
        return classWriter.toByteArray();
    } catch (Throwable t) {
        // we could not fix it, just copy the original and log the exception
        logger.verbose(t.getMessage());
        return bytes;
    }
}
 
Example #9
Source File: ClassRenameVisitorTest.java    From AVM with MIT License 6 votes vote down vote up
@Test
public void testSmallTarget() throws Exception {
    String targetTestName = ClassRenameVisitorTestTarget.class.getName();
    byte[] targetTestBytes = Utilities.loadRequiredResourceAsBytes(Utilities.fulllyQualifiedNameToInternalName(targetTestName) + ".class");
    
    String newName = "THE_NEW_CLASS";
    byte[] renamedBytes = new ClassToolchain.Builder(targetTestBytes, PARSING_OPTIONS)
                    .addNextVisitor(new ClassRenameVisitor(newName))
                    .addWriter(new ClassWriter(WRITING_OPTIONS))
                    .build()
                    .runAndGetBytecode();
    Class<?> original = SingleLoader.loadClass(targetTestName, targetTestBytes);
    runOnClass(original);
    Class<?> rename = SingleLoader.loadClass(newName, renamedBytes);
    runOnClass(rename);
}
 
Example #10
Source File: ClazzReplacer.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) {

    //            logger.log(pathName);
    if (reMapping.containsKey(pathName.substring(0, pathName.length() - 6))) {
        logger.info("[ClazzReplacer] remove class  " + pathName + " form " + jarFile);
        return;
    }

    try {
        InputStream in = jarFile.getInputStream(ze);
        ClassReader cr = new ClassReader(in);
        ClassWriter cw = new ClassWriter(0);
        RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw, new SimpleRemapper(reMapping));
        cr.accept(remappingClassAdapter, ClassReader.EXPAND_FRAMES);

        InputStream inputStream = new ByteArrayInputStream(cw.toByteArray());
        copyStreamToJar(inputStream, jos, pathName, ze.getTime());

    } catch (Throwable e) {

        System.err.println("[ClazzReplacer] rewrite error > " + pathName);
        justCopy(jarFile, jos, ze, pathName);
    }

}
 
Example #11
Source File: ExampleTransformer.java    From java-svc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
		ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
	if (probes.containsKey(className)) {
		try {
			ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
			TimingVisitor visitor = new TimingVisitor(classWriter, probes.get(className));
			ClassReader reader = new ClassReader(classfileBuffer);
			reader.accept(visitor, 0);
			return classWriter.toByteArray();
		} catch (Throwable t) {
			Logger.getLogger(getClass().getName()).log(Level.SEVERE,
					"Failed to instrument " + probes.get(className), t);
			return classfileBuffer;
		}
	} else {
		// Use the byte code as is...
		return null;
	}
}
 
Example #12
Source File: FeatureStructureClassGen.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Not called for built-in types
 * @param type the type to generate
 * @return the bytecode for that type
 */
byte[] createJCas_TypeCoverClass(TypeImpl type) {
  this.type = type;
  typeJavaDescriptor = type.getJavaDescriptor();
  typeJavaClassName = type.getName().replace('.', '/') + "_Type";
  cn = new ClassNode(ASM5); // java 8
  cn.version = JAVA_CLASS_VERSION;
  cn.access = ACC_PUBLIC + ACC_SUPER;
  cn.name = typeJavaClassName;   
  cn.superName = type.getSuperType().getName().replace('.', '/') + "_Type";

  // TODO
  
  ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  cn.accept(cw);
  return cw.toByteArray();
}
 
Example #13
Source File: ClassNameRenamer.java    From atlas with Apache License 2.0 6 votes vote down vote up
public static void rewriteDataBinderMapper(File dir, String fromName, String toName,
                                           File Clazz) throws IOException {
    FileInputStream fileInputStream = new FileInputStream(Clazz);
    ClassReader in1 = new ClassReader(fileInputStream);
    ClassWriter cw = new ClassWriter(0);

    Set<String> renames = new HashSet<String>();
    renames.add(fromName);
    in1.accept(new ClassRenamer(cw, renames, toName), 8);

    File destClass = new File(dir, toName + ".class");
    destClass.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(destClass);
    fileOutputStream.write(cw.toByteArray());
    IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(fileInputStream);

}
 
Example #14
Source File: ObfuscatorImpl.java    From obfuscator with MIT License 6 votes vote down vote up
private void saveJar(JarOutputStream jarOutputStream) throws IOException {
    for (ClassNode classNode : this.classMap.values()) {
        final JarEntry jarEntry = new JarEntry(classNode.name + ".class");
        final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);

        jarOutputStream.putNextEntry(jarEntry);

        classNode.accept(classWriter);
        jarOutputStream.write(classWriter.toByteArray());
        jarOutputStream.closeEntry();
    }

    for (Map.Entry<String, byte[]> entry : this.fileMap.entrySet()) {
        jarOutputStream.putNextEntry(new JarEntry(entry.getKey()));
        jarOutputStream.write(entry.getValue());
        jarOutputStream.closeEntry();
    }
}
 
Example #15
Source File: UserlibCollisionTest.java    From AVM with MIT License 6 votes vote down vote up
private static byte[] getAvmPackageClassBytes() {

        ClassWriter classWriter = new ClassWriter(0);
        MethodVisitor methodVisitor;

        classWriter.visit(V10, ACC_PUBLIC | ACC_SUPER, "avm/Main", null, "java/lang/Object", null);

        classWriter.visitSource("Main.java", null);
        {
            methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            methodVisitor.visitCode();
            Label label0 = new Label();
            methodVisitor.visitLabel(label0);
            methodVisitor.visitLineNumber(3, label0);
            methodVisitor.visitVarInsn(ALOAD, 0);
            methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            methodVisitor.visitInsn(RETURN);
            methodVisitor.visitMaxs(1, 1);
            methodVisitor.visitEnd();
        }
        classWriter.visitEnd();

        return classWriter.toByteArray();
    }
 
Example #16
Source File: ClassNameRemapper.java    From Concurnas with MIT License 6 votes vote down vote up
public static byte[] remapClass(byte[] resource, String nameFrom, String nameTo) {
	ClassReader reader = new ClassReader(resource);

	ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
	ClassVisitor visitor = new RemappingClassAdapter(writer, new Remapper() {
		@Override
		public String map(String from) {
			if (from.equals(nameFrom)) {
				return nameTo;
			}
			return from;
		}
	});

	reader.accept(visitor, ClassReader.EXPAND_FRAMES);
	return writer.toByteArray();
}
 
Example #17
Source File: CoverageTransformer.java    From QuickTheories with Apache License 2.0 5 votes vote down vote up
private byte[] transformBytes(final ClassLoader loader,
    final String className, final byte[] classfileBuffer) {
  final ClassReader reader = new ClassReader(classfileBuffer);
  final ClassWriter writer = new ComputeClassWriter(
      new ClassloaderByteArraySource(pickLoader(loader)), this.computeCache,
      FrameOptions.pickFlags(classfileBuffer));
  
  final int id = CodeCoverageStore.registerClass(className);
  reader.accept(new CoverageClassVisitor(id, writer),
      ClassReader.EXPAND_FRAMES);
  
  return writer.toByteArray();
}
 
Example #18
Source File: ClinitStrippingVisitorTest.java    From AVM with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    String targetTestName = ClinitStrippingVisitorTestTarget.class.getName();
    byte[] targetTestBytes = Utilities.loadRequiredResourceAsBytes(targetTestName.replaceAll("\\.", "/") + ".class");
    
    byte[] strippedBytes = new ClassToolchain.Builder(targetTestBytes, ClassReader.SKIP_DEBUG)
                    .addNextVisitor(new ClinitStrippingVisitor())
                    .addWriter(new ClassWriter(0))
                    .build()
                    .runAndGetBytecode();
    this.originalClass = SingleLoader.loadClass(targetTestName, targetTestBytes);
    this.strippedClass = SingleLoader.loadClass(targetTestName, strippedBytes);
}
 
Example #19
Source File: Decompiler.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
protected String decompile(ClassNode cn, MethodNode mn) {
	if (last != null && cn.equals(last)
			&& ((lastMn == null && mn == null) || (mn != null && lastMn != null && mn.equals(lastMn)))) {
		// same node, same output
		return lastOutput;
	}
	last = cn;
	lastMn = mn;
	// do not regenerate anything here
	ClassWriter cw = new ClassWriter(0);
	cn.accept(cw);
	return decompile(cw.toByteArray(), mn);
}
 
Example #20
Source File: PatchEntityPlayerSP.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("EntityPlayerSP (%s)", Names.abstractClientPlayer.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #21
Source File: ApiTest.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
private static void inject2ApiUtils(Map<String, ApiInfo> apiImpls) throws IOException {
    ClassReader cr = new ClassReader(ApiUtils.class.getName());
    ClassWriter cw = new ClassWriter(cr, 0);
    ClassVisitor cv = new ApiUtilsClassVisitor(cw, apiImpls, ApiUtils.class.getCanonicalName());
    cr.accept(cv, ClassReader.SKIP_FRAMES);

    FileUtils.writeByteArrayToFile(new File("ApiUtils2333.class"), cw.toByteArray());
}
 
Example #22
Source File: PatchGuiTextfield.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiTextfield (%s)", Names.guiTextfield.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #23
Source File: PatchNetworkManager.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #24
Source File: ModuleInfoGenerator.java    From JOML with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    File dest = new File(args[0]);
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V9, Opcodes.ACC_MODULE, "module-info", null, null, null);
    ModuleVisitor mv = cw.visitModule("org.joml", 0, args[1]);
    mv.visitRequire("java.base", ACC_MANDATED, "9");
    mv.visitRequire("jdk.unsupported", ACC_STATIC_PHASE, null);
    mv.visitExport("org/joml", 0, (String[]) null);
    mv.visitExport("org/joml/sampling", 0, (String[]) null);
    mv.visitEnd();
    cw.visitEnd();
    FileOutputStream fos = new FileOutputStream(new File(dest, "module-info.class"));
    fos.write(cw.toByteArray());
    fos.close();
}
 
Example #25
Source File: PatchGuiIngameForge.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiIngameForge (%s)", Names.guiIngameForge.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #26
Source File: PatchGuiConnecting.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiConnecting (%s)", Names.guiConnecting.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #27
Source File: CallSiteGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static Constructor compilePogoMethod(CachedMethod cachedMethod) {
    ClassWriter cw = makeClassWriter();

    final CachedClass declClass = cachedMethod.getDeclaringClass();
    final CallSiteClassLoader callSiteLoader = declClass.getCallSiteLoader();
    final String name = callSiteLoader.createClassName(cachedMethod.getName());

    final byte[] bytes = genPogoMetaMethodSite(cachedMethod, cw, name);

    return callSiteLoader.defineClassAndGetConstructor(name, bytes);
}
 
Example #28
Source File: PatchMinecraft.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("Minecraft (%s)", Names.minecraft.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #29
Source File: PatchGuiTextfield.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiTextfield (%s)", Names.guiTextfield.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example #30
Source File: PatchGuiGameOver.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiGameOver (%s)", Names.guiGameOver.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}