org.objectweb.asm.commons.ClassRemapper Java Examples

The following examples show how to use org.objectweb.asm.commons.ClassRemapper. 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: MappingProcessor.java    From zelixkiller with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Given a map of ClassNodes and mappings, returns a map of class names to
 * class bytes.
 * 
 * @param nodes
 * @param mappings
 * @return
 */
public static Map<String, byte[]> process(Map<String, ClassNode> nodes, Map<String, MappedClass> mappings, boolean useMaxs) {
	Map<String, byte[]> out = new HashMap<String, byte[]>();
	SkidRemapper mapper = new SkidRemapper(mappings);
	try {
		for (ClassNode cn : nodes.values()) {
			ClassWriter cw = new MappingClassWriter(mappings, useMaxs ? ClassWriter.COMPUTE_MAXS : ClassWriter.COMPUTE_FRAMES);
			ClassVisitor remapper = new ClassRemapper(cw, mapper);
			cn.accept(remapper);
			out.put(mappings.containsKey(cn.name) ? mappings.get(cn.name).getNewName() : cn.name, cw.toByteArray());
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return out;
}
 
Example #2
Source File: EntrypointPatchFML125.java    From fabric-loader with Apache License 2.0 6 votes vote down vote up
@Override
public void process(FabricLauncher launcher, Consumer<ClassNode> classEmitter) {
	if (classExists(launcher, TO)
		&& !classExists(launcher, "cpw.mods.fml.relauncher.FMLRelauncher")) {

		if (!(launcher instanceof Knot)) {
			throw new RuntimeException("1.2.5 FML patch only supported on Knot!");
		}

		debug("Detected 1.2.5 FML - Knotifying ModClassLoader...");
		try {
			ClassNode patchedClassLoader = loadClass(launcher, FROM);
			ClassNode remappedClassLoader = new ClassNode();

			patchedClassLoader.accept(new ClassRemapper(remappedClassLoader, new Remapper() {
				@Override
				public String map(String internalName) {
					return FROM_INTERNAL.equals(internalName) ? TO_INTERNAL : internalName;
				}
			}));

			classEmitter.accept(remappedClassLoader);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
 
Example #3
Source File: FaviconFactory.java    From thorntail with Apache License 2.0 6 votes vote down vote up
static byte[] createFaviconServletExtension(String name) throws IOException {
    ClassReader reader = new ClassReader(FaviconServletExtension.class.getClassLoader().getResourceAsStream(FaviconServletExtension.class.getName().replace('.', '/') + ".class"));

    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/undertow/internal/FaviconServletExtension")) {
                return slashName;
            }
            return super.map(typeName);
        }
    };

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

    writer.visitEnd();

    return writer.toByteArray();
}
 
Example #4
Source File: FaviconFactory.java    From thorntail with Apache License 2.0 6 votes vote down vote up
static byte[] createFaviconErrorHandler(String name) throws IOException {
    ClassReader reader = new ClassReader(FaviconErrorHandler.class.getClassLoader().getResourceAsStream(FaviconErrorHandler.class.getName().replace('.', '/') + ".class"));

    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/undertow/internal/FaviconErrorHandler")) {
                return slashName;
            }
            return super.map(typeName);
        }
    };

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

    writer.visitEnd();

    return writer.toByteArray();
}
 
Example #5
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 #6
Source File: CoreLibraryRewriter.java    From bazel with Apache License 2.0 6 votes vote down vote up
UnprefixingClassWriter(int flags) {
  super(Opcodes.ASM8);
  this.writer = new ClassWriter(flags);
  this.cv = this.writer;
  if (!prefix.isEmpty()) {
    this.cv =
        new ClassRemapper(
            this.writer,
            new Remapper() {
              @Override
              public String map(String typeName) {
                return unprefix(typeName);
              }
            });
  }
}
 
Example #7
Source File: Renamer.java    From AVM with MIT License 5 votes vote down vote up
private static Map<String, ClassNode> applyMapping(Map<String, ClassNode> classMap, Map<String, String> classNameMap) {
    SimpleRemapper remapper = new SimpleRemapper(classNameMap);
    Map<String, ClassNode> newClassMap = new HashMap<>();
    for (ClassNode node : classMap.values()) {
        ClassNode copy = new ClassNode();
        ClassRemapper adapter = new ClassRemapper(copy, remapper);
        node.accept(adapter);
        newClassMap.put(copy.name, copy);
    }
    return newClassMap;
}
 
Example #8
Source File: Mappings.java    From Recaf with MIT License 5 votes vote down vote up
private void accept(Map<String, byte[]> updated, ClassReader cr, int readFlags, int writeFlags) {
	String name = cr.getClassName();
	// Apply with mapper
	SimpleRecordingRemapper mapper = new SimpleRecordingRemapper(getMappings(),
			checkFieldHierarchy, checkMethodHierarchy, workspace);
	WorkspaceClassWriter cw = workspace.createWriter(writeFlags);
	cw.setMappings(getMappings(), reverseClassMappings);
	ClassRemapper adapter = new ClassRemapper(cw, mapper);
	if (clearDebugInfo)
		readFlags |= ClassReader.SKIP_DEBUG;
	cr.accept(adapter, readFlags);
	// Only return the modified class if any references to the mappings were found.
	if (mapper.isDirty())
		updated.put(name, cw.toByteArray());
}
 
Example #9
Source File: AbstractNormalizer.java    From deobfuscator with Apache License 2.0 5 votes vote down vote up
@Override
public final boolean transform() throws Throwable {
    CustomRemapper remapper = new CustomRemapper();

    remap(remapper);

    Map<String, ClassNode> updated = new HashMap<>();
    Set<String> removed = new HashSet<>();

    classNodes().forEach(wr -> {
        removed.add(wr.name);

        ClassNode newNode = new ClassNode();
        ClassRemapper classRemapper = new ClassRemapper(newNode, remapper);
        wr.accept(classRemapper);
        updated.put(newNode.name, newNode);

        getDeobfuscator().setConstantPool(newNode, getDeobfuscator().getConstantPool(wr));
    });

    removed.forEach(classes::remove);
    removed.forEach(classpath::remove);
    classes.putAll(updated);
    classpath.putAll(updated);
    getDeobfuscator().resetHierachy();
    return true;
}
 
Example #10
Source File: FrozerPlugin.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] rewriteBytecode(Map<String, String> internalPackageNameMap, byte[] bytecode) {
  ClassReader classReader = new ClassReader(bytecode);
  ClassWriter classWriter = new ClassWriter(0);
  classReader.accept(new ClassRemapper(classWriter, new Remapper() {
    @Override
    public String map(String internalName) {
      return interpolateInternalName(internalPackageNameMap, internalName);
    }
    @Override
    public String mapPackageName(String internalPackageName) {
      return matchInternalPackagePrefix(internalPackageNameMap, internalPackageName)
          .orElse(internalPackageName);
    }
    @Override
    public Object mapValue(Object value) {
      if (!(value instanceof String)) {  
        return super.mapValue(value);
      }

      // try to patch if it's like a class name (dot form and slash form)
      var string = (String)value;
      
      if (lookLikeAClassName(string)) {
        var index = string.lastIndexOf('.');
        return matchInternalPackagePrefix(internalPackageNameMap, string.substring(0, index).replace('.', '/'))
            .map(packageName -> packageName.replace('/', '.') + '.' + string.substring(index + 1))
            .map(result -> { System.out.println("literal constant string " + string +" as " + result); return result;})
            .orElse(string);
      }
      return string;
    }
  }), 0);
  return classWriter.toByteArray();
}
 
Example #11
Source File: SerializablePortabilityTestUtilities.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
  for (Entry<String, String> mapping : remappings.entrySet()) {
    if (name.equals(mapping.getValue())) {
      String path = mapping.getKey().replace('.', '/').concat(".class");
      try {
        try (InputStream resource = getResourceAsStream(path)) {
          ClassReader reader = new ClassReader(resource);

          ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
          ClassVisitor visitor = new ClassRemapper(writer, new Remapper() {

            @Override
            public String map(String from) {
              String to = remappings.get(from.replace('/', '.'));
              if (to == null) {
                return from;
              } else {
                return to.replace('.', '/');
              }
            }
          });

          reader.accept(visitor, ClassReader.EXPAND_FRAMES);
          byte[] classBytes = writer.toByteArray();

          return defineClass(name, classBytes, 0, classBytes.length);
        }
      } catch (IOException e) {
        throw new ClassNotFoundException("IOException while loading", e);
      }
    }
  }
  return super.findClass(name);
}
 
Example #12
Source File: SerializerTestUtilities.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
  String key = findKeyFromValue(name).orElseGet(() -> null);
  if(key == null) {
    return super.findClass(name);
  }

  String path = key.replace('.', '/').concat(".class");
  try (InputStream resource = getResourceAsStream(path)) {
    ClassReader reader = new ClassReader(resource);
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);

    Remapper remapper = new Remapper() {
      @Override
      public String map(String from) {
        String to = remappings.get(from.replace('/', '.'));
        if (to == null) {
          return from;
        }
        return to.replace('.', '/');
      }
    };

    reader.accept(new ClassRemapper(writer, remapper), ClassReader.EXPAND_FRAMES);

    byte[] classBytes = writer.toByteArray();

    return defineClass(name, classBytes, 0, classBytes.length);
  } catch (IOException e) {
    throw new ClassNotFoundException("IOException while loading", e);
  }
}
 
Example #13
Source File: PluginClassRenamer.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private LazyDefinedClass build(String internalName, byte[] origBytes) throws IOException {
    processed.add(internalName);
    PluginClassRemapper remapper = new PluginClassRemapper();
    ImmutableLazyDefinedClass.Builder builder = ImmutableLazyDefinedClass.builder()
            .type(Type.getObjectType(remapper.mapType(internalName)));
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = new ClassRemapper(cw, remapper);
    ClassReader cr = new ClassReader(origBytes);
    cr.accept(cv, 0);
    builder.bytes(cw.toByteArray());
    for (String unprocessed : remapper.unprocessed) {
        builder.addDependencies(build(unprocessed));
    }
    return builder.build();
}
 
Example #14
Source File: FileContentProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
public final ImmutableSetMultimap<Predicate<ClassName>, ClassName> findReferencedTypes(
    ImmutableSet<Predicate<ClassName>> typeFilters) {
  ImmutableSetMultimap.Builder<ClassName, Predicate<ClassName>> collectedTypes =
      ImmutableSetMultimap.builder();
  // Takes an advantage of hit-all-referenced-types ASM Remapper to perform type collection.
  try (S inputStream = get()) {
    ClassReader cr = new ClassReader(inputStream);
    cr.accept(
        new ClassRemapper(
            new ClassWriter(ClassWriter.COMPUTE_FRAMES),
            new Remapper() {
              @Override
              public String map(String internalName) {
                ClassName className = ClassName.create(internalName);
                collectedTypes.putAll(
                    className,
                    typeFilters.stream()
                        .filter(className::acceptTypeFilter)
                        .collect(Collectors.toList()));
                return super.map(internalName);
              }
            }),
        /* parsingOptions= */ 0);
  } catch (IOException e) {
    throw new IOError(e);
  }
  return collectedTypes.build().inverse();
}
 
Example #15
Source File: ByteArrayClassLoaderChildFirstTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    return new ClassRemapper(OpenedClassReader.ASM_API, classVisitor, new SimpleRemapper(oldName, newName)) {
        /* only anonymous to define usage of Byte Buddy specific API version */
    };
}
 
Example #16
Source File: LambdaFactoryTest.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private void renameClass(ClassReader reader, ClassVisitor classVisitor) {
    String className = "com/navercorp/pinpoint/profiler/instrument/lambda/mock/UnsafeClassMock";
    Remapper remapper = new SimpleRemapper(className,className + "2");
    ClassRemapper classRemapper = new ClassRemapper(classVisitor, remapper);
    reader.accept(classRemapper, 0);
}