Search in sources :

Example 6 with Remapper

use of org.objectweb.asm.commons.Remapper in project FoamFix by asiekierka.

the class FoamFixTransformer method spliceClasses.

public static ClassNode spliceClasses(final ClassNode nodeData, final byte[] dataSplice, final String className, final boolean addMethods, final String... methods) {
    // System.out.println("Splicing from " + className + " to " + targetClassName)
    if (dataSplice == null) {
        throw new RuntimeException("Class " + className + " not found! This is a FoamFix bug!");
    }
    final Set<String> methodSet = Sets.newHashSet(methods);
    final List<String> methodList = Lists.newArrayList(methods);
    final ClassReader readerSplice = new ClassReader(dataSplice);
    final String className2 = className.replace('.', '/');
    final String targetClassName2 = nodeData.name;
    final String targetClassName = targetClassName2.replace('/', '.');
    final Remapper remapper = new Remapper() {

        public String map(final String name) {
            return className2.equals(name) ? targetClassName2 : name;
        }
    };
    ClassNode nodeSplice = new ClassNode();
    readerSplice.accept(new ClassRemapper(nodeSplice, remapper), ClassReader.EXPAND_FRAMES);
    for (String s : nodeSplice.interfaces) {
        System.out.println(s);
        if (s.contains("IFoamFix")) {
            nodeData.interfaces.add(s);
            System.out.println("Added INTERFACE: " + s);
        }
    }
    for (int i = 0; i < nodeSplice.methods.size(); i++) {
        if (methodSet.contains(nodeSplice.methods.get(i).name)) {
            MethodNode mn = nodeSplice.methods.get(i);
            boolean added = false;
            for (int j = 0; j < nodeData.methods.size(); j++) {
                if (nodeData.methods.get(j).name.equals(mn.name) && nodeData.methods.get(j).desc.equals(mn.desc)) {
                    MethodNode oldMn = nodeData.methods.get(j);
                    System.out.println("Spliced in METHOD: " + targetClassName + "." + mn.name);
                    nodeData.methods.set(j, mn);
                    if (nodeData.superName != null && nodeData.name.equals(nodeSplice.superName)) {
                        ListIterator<AbstractInsnNode> nodeListIterator = mn.instructions.iterator();
                        while (nodeListIterator.hasNext()) {
                            AbstractInsnNode node = nodeListIterator.next();
                            if (node instanceof MethodInsnNode && node.getOpcode() == Opcodes.INVOKESPECIAL) {
                                MethodInsnNode methodNode = (MethodInsnNode) node;
                                if (targetClassName2.equals(methodNode.owner)) {
                                    methodNode.owner = nodeData.superName;
                                }
                            }
                        }
                    }
                    oldMn.name = methodList.get((methodList.indexOf(oldMn.name)) & (~1)) + "_foamfix_old";
                    nodeData.methods.add(oldMn);
                    added = true;
                    break;
                }
            }
            if (!added && addMethods) {
                System.out.println("Added METHOD: " + targetClassName + "." + mn.name);
                nodeData.methods.add(mn);
                added = true;
            }
        }
    }
    for (int i = 0; i < nodeSplice.fields.size(); i++) {
        if (methodSet.contains(nodeSplice.fields.get(i).name)) {
            FieldNode mn = nodeSplice.fields.get(i);
            boolean added = false;
            for (int j = 0; j < nodeData.fields.size(); j++) {
                if (nodeData.fields.get(j).name.equals(mn.name) && nodeData.fields.get(j).desc.equals(mn.desc)) {
                    System.out.println("Spliced in FIELD: " + targetClassName + "." + mn.name);
                    nodeData.fields.set(j, mn);
                    added = true;
                    break;
                }
            }
            if (!added) {
                System.out.println("Added FIELD: " + targetClassName + "." + mn.name);
                nodeData.fields.add(mn);
                added = true;
            }
        }
    }
    return nodeData;
}
Also used : ClassRemapper(org.objectweb.asm.commons.ClassRemapper) Remapper(org.objectweb.asm.commons.Remapper) ClassRemapper(org.objectweb.asm.commons.ClassRemapper) ClassReader(org.objectweb.asm.ClassReader)

Example 7 with Remapper

use of org.objectweb.asm.commons.Remapper in project gradle by gradle.

the class ShadedJar method analyse.

private void analyse(FileCollection sourceFiles, final ClassGraph classes, final PrintWriter writer) {
    final PackagePatterns ignored = new PackagePatterns(Collections.singleton("java"));
    sourceFiles.getAsFileTree().visit(new FileVisitor() {

        boolean seenManifest;

        public void visitDir(FileVisitDetails dirDetails) {
        }

        public void visitFile(FileVisitDetails fileDetails) {
            writer.print(fileDetails.getPath() + ": ");
            if (fileDetails.getPath().endsWith(".class")) {
                try {
                    ClassReader reader;
                    try (InputStream inputStream = new BufferedInputStream(fileDetails.open())) {
                        reader = new ClassReader(inputStream);
                    }
                    final ClassDetails details = classes.get(reader.getClassName());
                    details.visited = true;
                    ClassWriter classWriter = new ClassWriter(0);
                    reader.accept(new ClassRemapper(classWriter, new Remapper() {

                        public String map(String name) {
                            if (ignored.matches(name)) {
                                return name;
                            }
                            ClassDetails dependencyDetails = classes.get(name);
                            if (dependencyDetails != details) {
                                details.dependencies.add(dependencyDetails);
                            }
                            return dependencyDetails.outputClassName;
                        }
                    }), ClassReader.EXPAND_FRAMES);
                    writer.println("mapped class name: " + details.outputClassName);
                    File outputFile = new File(classesDir, details.outputClassName.concat(".class"));
                    outputFile.getParentFile().mkdirs();
                    try (OutputStream outputStream = new FileOutputStream(outputFile)) {
                        outputStream.write(classWriter.toByteArray());
                    }
                } catch (Exception exception) {
                    throw new ClassAnalysisException("Could not transform class from " + fileDetails.getFile(), exception);
                }
            } else if (fileDetails.getPath().endsWith(".properties") && classes.unshadedPackages.matches(fileDetails.getPath())) {
                writer.println("include");
                classes.addResource(new ResourceDetails(fileDetails.getPath(), fileDetails.getFile()));
            } else if (fileDetails.getPath().equals(JarFile.MANIFEST_NAME) && !seenManifest) {
                seenManifest = true;
                classes.manifest = new ResourceDetails(fileDetails.getPath(), fileDetails.getFile());
            } else {
                writer.println("skipped");
            }
        }
    });
}
Also used : JarOutputStream(java.util.jar.JarOutputStream) ClassRemapper(org.objectweb.asm.commons.ClassRemapper) ClassWriter(org.objectweb.asm.ClassWriter) FileVisitDetails(org.gradle.api.file.FileVisitDetails) Remapper(org.objectweb.asm.commons.Remapper) ClassRemapper(org.objectweb.asm.commons.ClassRemapper) ClassReader(org.objectweb.asm.ClassReader) FileVisitor(org.gradle.api.file.FileVisitor) JarFile(java.util.jar.JarFile)

Example 8 with Remapper

use of org.objectweb.asm.commons.Remapper in project cdap by caskdata.

the class LogPipelineCheckTest method renameClass.

/**
 * Generates the bytecode of a new class with the given name using the given class as the skeleton.
 */
private byte[] renameClass(final Class<?> cls, final String newClassName) throws IOException {
    ClassReader cr = new ClassReader(cls.getName());
    ClassWriter cw = new ClassWriter(0);
    final String oldTypeName = Type.getInternalName(cls);
    cr.accept(new RemappingClassAdapter(cw, new Remapper() {

        @Override
        public String mapType(String type) {
            return oldTypeName.equals(type) ? newClassName : type;
        }
    }), 0);
    return cw.toByteArray();
}
Also used : RemappingClassAdapter(org.objectweb.asm.commons.RemappingClassAdapter) Remapper(org.objectweb.asm.commons.Remapper) ClassReader(org.objectweb.asm.ClassReader) ClassWriter(org.objectweb.asm.ClassWriter)

Example 9 with Remapper

use of org.objectweb.asm.commons.Remapper in project SpecialSource by md-5.

the class JarMapping method loadMappings.

/**
 * Load a mapping given a .csrg file
 *
 * @param reader Mapping file reader
 * @param inputTransformer Transformation to apply on input
 * @param outputTransformer Transformation to apply on output
 * @param reverse Swap input and output mappings (after applying any
 * input/output transformations)
 * @throws IOException
 */
public void loadMappings(BufferedReader reader, MappingTransformer inputTransformer, MappingTransformer outputTransformer, boolean reverse) throws IOException {
    if (inputTransformer == null) {
        inputTransformer = MavenShade.IDENTITY;
    }
    if (outputTransformer == null) {
        outputTransformer = MavenShade.IDENTITY;
    }
    List<String> lines = new ArrayList<>();
    String line;
    while ((line = reader.readLine()) != null) {
        int commentIndex = line.indexOf('#');
        if (commentIndex != -1) {
            line = line.substring(0, commentIndex);
        }
        if (line.isEmpty()) {
            continue;
        }
        lines.add(line);
    }
    // Gather class mappings here so that we can support reversing csrg/tsrg.
    final Map<String, String> clsMap = new HashMap<>();
    for (String l : lines) {
        if (l.contains(":")) {
            if (!l.startsWith("CL:")) {
                continue;
            }
            String[] tokens = l.split(" ");
            clsMap.put(tokens[1], tokens[1]);
        } else {
            if (l.startsWith("\t")) {
                continue;
            }
            String[] tokens = l.split(" ");
            clsMap.put(tokens[0], tokens[1]);
        }
    }
    // We use a Remapper so that we don't have to duplicate the logic of remapping method descriptors.
    Remapper reverseMapper = new Remapper() {

        @Override
        public String map(String cls) {
            return clsMap.getOrDefault(cls, cls);
        }
    };
    for (String l : lines) {
        if (l.contains(":")) {
            // standard srg
            parseSrgLine(l, inputTransformer, outputTransformer, reverse);
        } else {
            // better 'compact' srg format
            parseCsrgLine(l, inputTransformer, outputTransformer, reverse, reverseMapper);
        }
    }
    currentClass = null;
}
Also used : Remapper(org.objectweb.asm.commons.Remapper)

Example 10 with Remapper

use of org.objectweb.asm.commons.Remapper in project wildfly-swarm by wildfly-swarm.

the class FaviconFactory method createFaviconErrorHandler.

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();
}
Also used : Remapper(org.objectweb.asm.commons.Remapper) ClassRemapper(org.objectweb.asm.commons.ClassRemapper) ClassReader(org.objectweb.asm.ClassReader) ClassRemapper(org.objectweb.asm.commons.ClassRemapper) ClassWriter(org.objectweb.asm.ClassWriter)

Aggregations

Remapper (org.objectweb.asm.commons.Remapper)12 ClassReader (org.objectweb.asm.ClassReader)9 ClassRemapper (org.objectweb.asm.commons.ClassRemapper)8 ClassWriter (org.objectweb.asm.ClassWriter)7 RemappingClassAdapter (org.objectweb.asm.commons.RemappingClassAdapter)3 IOException (java.io.IOException)1 JarFile (java.util.jar.JarFile)1 JarOutputStream (java.util.jar.JarOutputStream)1 FileVisitDetails (org.gradle.api.file.FileVisitDetails)1 FileVisitor (org.gradle.api.file.FileVisitor)1 AnnotationVisitor (org.objectweb.asm.AnnotationVisitor)1 ClassVisitor (org.objectweb.asm.ClassVisitor)1 SimpleRemapper (org.objectweb.asm.commons.SimpleRemapper)1 ClassNode (org.objectweb.asm.tree.ClassNode)1