Example usage for org.objectweb.asm MethodVisitor MethodVisitor

List of usage examples for org.objectweb.asm MethodVisitor MethodVisitor

Introduction

In this page you can find the example usage for org.objectweb.asm MethodVisitor MethodVisitor.

Prototype

public MethodVisitor(final int api) 

Source Link

Document

Constructs a new MethodVisitor .

Usage

From source file:org.apache.commons.weaver.privilizer.BlueprintingVisitor.java

License:Apache License

private String importMethod(final Pair<Type, Method> key) {
    if (importedMethods.containsKey(key)) {
        return importedMethods.get(key);
    }/*from www  . jav  a  2s .  co m*/
    final String result = new StringBuilder(key.getLeft().getInternalName().replace('/', '_')).append("$$")
            .append(key.getRight().getName()).toString();
    importedMethods.put(key, result);
    privilizer().env.debug("importing %s#%s as %s", key.getLeft().getClassName(), key.getRight(), result);
    final int access = Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC;

    final MethodNode source = typeInfo(key.getLeft()).methods.get(key.getRight());

    final String[] exceptions = source.exceptions.toArray(ArrayUtils.EMPTY_STRING_ARRAY);

    // non-public fields accessed
    final Set<FieldAccess> fieldAccesses = new LinkedHashSet<>();

    source.accept(new MethodVisitor(Privilizer.ASM_VERSION) {
        @Override
        public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
            final FieldAccess fieldAccess = fieldAccess(Type.getObjectType(owner), name);

            super.visitFieldInsn(opcode, owner, name, desc);
            if (!Modifier.isPublic(fieldAccess.access)) {
                fieldAccesses.add(fieldAccess);
            }
        }
    });

    final MethodNode withAccessibleAdvice = new MethodNode(access, result, source.desc, source.signature,
            exceptions);

    // spider own methods:
    MethodVisitor mv = new NestedMethodInvocationHandler(withAccessibleAdvice, key); //NOPMD

    if (!fieldAccesses.isEmpty()) {
        mv = new AccessibleAdvisor(mv, access, result, source.desc, new ArrayList<>(fieldAccesses));
    }
    source.accept(mv);

    // private can only be called by other privileged methods, so no need to mark as privileged
    if (!Modifier.isPrivate(source.access)) {
        withAccessibleAdvice.visitAnnotation(Type.getType(Privileged.class).getDescriptor(), false).visitEnd();
    }
    withAccessibleAdvice.accept(this.cv);

    return result;
}

From source file:org.apache.flink.api.java.ClosureCleaner.java

License:Apache License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] exceptions) {
    return new MethodVisitor(Opcodes.ASM5) {

        @Override//from  w w  w .j  a  va2s  . com
        public void visitFieldInsn(int op, String owner, String name, String desc) {
            if (op == Opcodes.GETFIELD && name.equals(this0Name)) {
                isThis0Accessed = true;
            }
        }
    };
}

From source file:org.apache.ignite.internal.processors.hadoop.GridHadoopClassLoader.java

License:Apache License

/**
 * @param clsName Class name.//from   w w  w.  ja  v  a  2 s  . c o m
 * @return {@code true} If the class has external dependencies.
 */
boolean hasExternalDependencies(final String clsName, final Set<String> visited) {
    if (isHadoop(clsName)) // Hadoop must not be in classpath but Idea sucks, so filtering explicitly as external.
        return true;

    // Try to get from parent to check if the type accessible.
    InputStream in = loadClassBytes(getParent(), clsName);

    if (in == null) // The class is external itself, it must be loaded from this class loader.
        return true;

    if (!isIgfsOrGgHadoop(clsName)) // Other classes should not have external dependencies.
        return false;

    final ClassReader rdr;

    try {
        rdr = new ClassReader(in);
    } catch (IOException e) {
        throw new RuntimeException("Failed to read class: " + clsName, e);
    }

    visited.add(clsName);

    final AtomicBoolean hasDeps = new AtomicBoolean();

    rdr.accept(new ClassVisitor(Opcodes.ASM4) {
        AnnotationVisitor av = new AnnotationVisitor(Opcodes.ASM4) {
            // TODO
        };

        FieldVisitor fv = new FieldVisitor(Opcodes.ASM4) {
            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean b) {
                onType(desc);

                return av;
            }
        };

        MethodVisitor mv = new MethodVisitor(Opcodes.ASM4) {
            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean b) {
                onType(desc);

                return av;
            }

            @Override
            public AnnotationVisitor visitParameterAnnotation(int i, String desc, boolean b) {
                onType(desc);

                return av;
            }

            @Override
            public AnnotationVisitor visitAnnotationDefault() {
                return av;
            }

            @Override
            public void visitFieldInsn(int i, String owner, String name, String desc) {
                onType(owner);
                onType(desc);
            }

            @Override
            public void visitFrame(int i, int i2, Object[] locTypes, int i3, Object[] stackTypes) {
                for (Object o : locTypes) {
                    if (o instanceof String)
                        onType((String) o);
                }

                for (Object o : stackTypes) {
                    if (o instanceof String)
                        onType((String) o);
                }
            }

            @Override
            public void visitLocalVariable(String name, String desc, String signature, Label lb, Label lb2,
                    int i) {
                onType(desc);
            }

            @Override
            public void visitMethodInsn(int i, String owner, String name, String desc) {
                onType(owner);
            }

            @Override
            public void visitMultiANewArrayInsn(String desc, int dim) {
                onType(desc);
            }

            @Override
            public void visitTryCatchBlock(Label lb, Label lb2, Label lb3, String e) {
                onType(e);
            }
        };

        void onClass(String depCls) {
            assert validateClassName(depCls) : depCls;

            if (depCls.startsWith("java.")) // Filter out platform classes.
                return;

            if (visited.contains(depCls))
                return;

            Boolean res = cache.get(depCls);

            if (res == Boolean.TRUE || (res == null && hasExternalDependencies(depCls, visited)))
                hasDeps.set(true);
        }

        void onType(String type) {
            if (type == null)
                return;

            int off = 0;

            while (type.charAt(off) == '[')
                off++; // Handle arrays.

            if (off != 0)
                type = type.substring(off);

            if (type.length() == 1)
                return; // Get rid of primitives.

            if (type.charAt(type.length() - 1) == ';') {
                assert type.charAt(0) == 'L' : type;

                type = type.substring(1, type.length() - 1);
            }

            type = type.replace('/', '.');

            onClass(type);
        }

        @Override
        public void visit(int i, int i2, String name, String signature, String superName, String[] ifaces) {
            onType(superName);

            if (ifaces != null) {
                for (String iface : ifaces)
                    onType(iface);
            }
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            onType(desc);

            return av;
        }

        @Override
        public void visitInnerClass(String name, String outerName, String innerName, int i) {
            onType(name);
        }

        @Override
        public FieldVisitor visitField(int i, String name, String desc, String signature, Object val) {
            onType(desc);

            return fv;
        }

        @Override
        public MethodVisitor visitMethod(int i, String name, String desc, String signature,
                String[] exceptions) {
            if (exceptions != null) {
                for (String e : exceptions)
                    onType(e);
            }

            return mv;
        }
    }, 0);

    if (hasDeps.get()) // We already know that we have dependencies, no need to check parent.
        return true;

    // Here we are known to not have any dependencies but possibly we have a parent which have them.
    int idx = clsName.lastIndexOf('$');

    if (idx == -1) // No parent class.
        return false;

    String parentCls = clsName.substring(0, idx);

    if (visited.contains(parentCls))
        return false;

    Boolean res = cache.get(parentCls);

    if (res == null)
        res = hasExternalDependencies(parentCls, visited);

    return res;
}

From source file:org.apache.ignite.internal.processors.hadoop.HadoopClassLoader.java

License:Apache License

/**
 * @param clsName Class name./*from w  ww  .  jav  a2  s.c om*/
 * @return {@code true} If the class has external dependencies.
 */
boolean hasExternalDependencies(final String clsName, final Set<String> visited) {
    if (isHadoop(clsName)) // Hadoop must not be in classpath but Idea sucks, so filtering explicitly as external.
        return true;

    // Try to get from parent to check if the type accessible.
    InputStream in = loadClassBytes(getParent(), clsName);

    if (in == null) // The class is external itself, it must be loaded from this class loader.
        return true;

    if (!isHadoopIgfs(clsName)) // Other classes should not have external dependencies.
        return false;

    final ClassReader rdr;

    try {
        rdr = new ClassReader(in);
    } catch (IOException e) {
        throw new RuntimeException("Failed to read class: " + clsName, e);
    }

    visited.add(clsName);

    final AtomicBoolean hasDeps = new AtomicBoolean();

    rdr.accept(new ClassVisitor(Opcodes.ASM4) {
        AnnotationVisitor av = new AnnotationVisitor(Opcodes.ASM4) {
            // TODO
        };

        FieldVisitor fv = new FieldVisitor(Opcodes.ASM4) {
            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean b) {
                onType(desc);

                return av;
            }
        };

        MethodVisitor mv = new MethodVisitor(Opcodes.ASM4) {
            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean b) {
                onType(desc);

                return av;
            }

            @Override
            public AnnotationVisitor visitParameterAnnotation(int i, String desc, boolean b) {
                onType(desc);

                return av;
            }

            @Override
            public AnnotationVisitor visitAnnotationDefault() {
                return av;
            }

            @Override
            public void visitFieldInsn(int i, String owner, String name, String desc) {
                onType(owner);
                onType(desc);
            }

            @Override
            public void visitFrame(int i, int i2, Object[] locTypes, int i3, Object[] stackTypes) {
                for (Object o : locTypes) {
                    if (o instanceof String)
                        onType((String) o);
                }

                for (Object o : stackTypes) {
                    if (o instanceof String)
                        onType((String) o);
                }
            }

            @Override
            public void visitLocalVariable(String name, String desc, String signature, Label lb, Label lb2,
                    int i) {
                onType(desc);
            }

            @Override
            public void visitMethodInsn(int i, String owner, String name, String desc) {
                onType(owner);
            }

            @Override
            public void visitMultiANewArrayInsn(String desc, int dim) {
                onType(desc);
            }

            @Override
            public void visitTryCatchBlock(Label lb, Label lb2, Label lb3, String e) {
                onType(e);
            }
        };

        void onClass(String depCls) {
            assert validateClassName(depCls) : depCls;

            if (depCls.startsWith("java.")) // Filter out platform classes.
                return;

            if (visited.contains(depCls))
                return;

            Boolean res = cache.get(depCls);

            if (res == Boolean.TRUE || (res == null && hasExternalDependencies(depCls, visited)))
                hasDeps.set(true);
        }

        void onType(String type) {
            if (type == null)
                return;

            int off = 0;

            while (type.charAt(off) == '[')
                off++; // Handle arrays.

            if (off != 0)
                type = type.substring(off);

            if (type.length() == 1)
                return; // Get rid of primitives.

            if (type.charAt(type.length() - 1) == ';') {
                assert type.charAt(0) == 'L' : type;

                type = type.substring(1, type.length() - 1);
            }

            type = type.replace('/', '.');

            onClass(type);
        }

        @Override
        public void visit(int i, int i2, String name, String signature, String superName, String[] ifaces) {
            onType(superName);

            if (ifaces != null) {
                for (String iface : ifaces)
                    onType(iface);
            }
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            onType(desc);

            return av;
        }

        @Override
        public void visitInnerClass(String name, String outerName, String innerName, int i) {
            onType(name);
        }

        @Override
        public FieldVisitor visitField(int i, String name, String desc, String signature, Object val) {
            onType(desc);

            return fv;
        }

        @Override
        public MethodVisitor visitMethod(int i, String name, String desc, String signature,
                String[] exceptions) {
            if (exceptions != null) {
                for (String e : exceptions)
                    onType(e);
            }

            return mv;
        }
    }, 0);

    if (hasDeps.get()) // We already know that we have dependencies, no need to check parent.
        return true;

    // Here we are known to not have any dependencies but possibly we have a parent which have them.
    int idx = clsName.lastIndexOf('$');

    if (idx == -1) // No parent class.
        return false;

    String parentCls = clsName.substring(0, idx);

    if (visited.contains(parentCls))
        return false;

    Boolean res = cache.get(parentCls);

    if (res == null)
        res = hasExternalDependencies(parentCls, visited);

    return res;
}

From source file:org.apache.lucene.validation.ForbiddenApisCheckTask.java

License:Apache License

/** Parses a class given as Resource and checks for valid method invocations */
private int checkClass(final ClassReader reader) {
    final int[] violations = new int[1];
    reader.accept(new ClassVisitor(Opcodes.ASM4) {
        final String className = Type.getObjectType(reader.getClassName()).getClassName();
        String source = null;//from w  w w  . j  a  v  a2 s  . co  m

        @Override
        public void visitSource(String source, String debug) {
            this.source = source;
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            return new MethodVisitor(Opcodes.ASM4) {
                private int lineNo = -1;

                private ClassSignatureLookup lookupRelatedClass(String internalName) {
                    ClassSignatureLookup c = classesToCheck.get(internalName);
                    if (c == null)
                        try {
                            c = getClassFromClassLoader(internalName);
                        } catch (BuildException be) {
                            // we ignore lookup errors and simply ignore this related class
                            c = null;
                        }
                    return c;
                }

                private boolean checkClassUse(String owner) {
                    final String printout = forbiddenClasses.get(owner);
                    if (printout != null) {
                        log("Forbidden class use: " + printout, Project.MSG_ERR);
                        return true;
                    }
                    return false;
                }

                private boolean checkMethodAccess(String owner, Method method) {
                    if (checkClassUse(owner)) {
                        return true;
                    }
                    final String printout = forbiddenMethods.get(owner + '\000' + method);
                    if (printout != null) {
                        log("Forbidden method invocation: " + printout, Project.MSG_ERR);
                        return true;
                    }
                    final ClassSignatureLookup c = lookupRelatedClass(owner);
                    if (c != null && !c.methods.contains(method)) {
                        final String superName = c.reader.getSuperName();
                        if (superName != null && checkMethodAccess(superName, method)) {
                            return true;
                        }
                        final String[] interfaces = c.reader.getInterfaces();
                        if (interfaces != null) {
                            for (String intf : interfaces) {
                                if (intf != null && checkMethodAccess(intf, method)) {
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                }

                private boolean checkFieldAccess(String owner, String field) {
                    if (checkClassUse(owner)) {
                        return true;
                    }
                    final String printout = forbiddenFields.get(owner + '\000' + field);
                    if (printout != null) {
                        log("Forbidden field access: " + printout, Project.MSG_ERR);
                        return true;
                    }
                    final ClassSignatureLookup c = lookupRelatedClass(owner);
                    if (c != null && !c.fields.contains(field)) {
                        final String superName = c.reader.getSuperName();
                        if (superName != null && checkFieldAccess(superName, field)) {
                            return true;
                        }
                        final String[] interfaces = c.reader.getInterfaces();
                        if (interfaces != null) {
                            for (String intf : interfaces) {
                                if (intf != null && checkFieldAccess(intf, field)) {
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                }

                @Override
                public void visitMethodInsn(int opcode, String owner, String name, String desc) {
                    if (checkMethodAccess(owner, new Method(name, desc))) {
                        violations[0]++;
                        reportSourceAndLine();
                    }
                }

                @Override
                public void visitFieldInsn(int opcode, String owner, String name, String desc) {
                    if (checkFieldAccess(owner, name)) {
                        violations[0]++;
                        reportSourceAndLine();
                    }
                }

                private void reportSourceAndLine() {
                    final StringBuilder sb = new StringBuilder("  in ").append(className);
                    if (source != null && lineNo >= 0) {
                        new Formatter(sb, Locale.ROOT).format(" (%s:%d)", source, lineNo).flush();
                    }
                    log(sb.toString(), Project.MSG_ERR);
                }

                @Override
                public void visitLineNumber(int lineNo, Label start) {
                    this.lineNo = lineNo;
                }
            };
        }
    }, ClassReader.SKIP_FRAMES);
    return violations[0];
}

From source file:org.blockartistry.mod.DynSurround.world.WorldProviderWeatherHandle.java

License:MIT License

public WorldProviderWeatherHandle(final World world, final WorldProvider provider) {
    super(world, provider);

    if (provider.getClass() == WorldProviderSurface.class)
        return;//from   w  w w .  j a v  a  2  s  .c  o  m

    ModLog.info("Processing inspection on world provider class %s for compat", provider.getClass().getName());

    try {
        ModClassLoader modClassLoader = Loader.instance().getModClassLoader();
        Field mainLoaderField = modClassLoader.getClass().getDeclaredField("mainClassLoader");
        mainLoaderField.setAccessible(true);
        LaunchClassLoader classLoader = (LaunchClassLoader) mainLoaderField.get(modClassLoader);

        new ClassReader(classLoader.getClassBytes(provider.getClass().getName()))
                .accept(new ClassVisitor(Opcodes.ASM5) {
                    @Override
                    public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                            String[] exceptions) {
                        if (name.equals("updateWeather")) {
                            ModLog.info(
                                    "Visiting method %s with description %s named updateWeather() on WorldProvider",
                                    name, desc);

                            patchWeather = false;

                            return new MethodVisitor(Opcodes.ASM5) {
                                boolean isTheMethod = true;

                                @Override
                                public void visitParameter(String name, int access) {
                                    this.isTheMethod = false;
                                }

                                @Override
                                public void visitMethodInsn(int opcode, String owner, String name, String desc,
                                        boolean itf) {
                                    if (!this.isTheMethod)
                                        return;

                                    ModLog.info(
                                            "Visiting method call %s with description %s during inspection on WorldProvider#updateWeather(), for compat",
                                            name, desc);

                                    try {
                                        if (name.equals("updateWeatherBody")
                                                && desc.equals(Type.getMethodDescriptor(
                                                        World.class.getMethod("updateWeatherBody")))) {
                                            patchWeather = true;
                                            ModLog.info(
                                                    "Found World#updateWeatherBody() from WorldProvider#updateWeather()");
                                        } else if (name.equals("updateWeather")
                                                && desc.equals(Type.getMethodDescriptor(
                                                        WorldProvider.class.getMethod("updateWeather")))) {
                                            patchWeather = true;
                                            ModLog.info(
                                                    "Found WorldProvider#updateWeather() from WorldProvider#updateWeather()");
                                        }
                                    } catch (NoSuchMethodException exc) {
                                        Throwables.propagate(exc);
                                    }
                                }
                            };
                        }
                        return null;
                    }
                }, 0);
    } catch (IOException exc) {
        Throwables.propagate(exc);
    } catch (ReflectiveOperationException exc) {
        Throwables.propagate(exc);
    }
}

From source file:org.coldswap.asm.field.PrivateStaticFieldReplacer.java

License:Open Source License

/**
 * Removes any initializing reference of the field.
 *
 * @param classNode containing the old class.
 * @param fieldNode containing the old field.
 * @return the initializing list of instructions.
 *///from   www.j a  v  a 2 s . c om
@SuppressWarnings("unchecked")
private InsnList cleanClInit(ClassNode classNode, FieldNode fieldNode) {
    List<MethodNode> methodNodes = classNode.methods;
    AbstractInsnNode firstInst = null;
    int counter = 0;
    for (MethodNode methodNode : methodNodes) {
        if (methodNode.name.equals("<clinit>")) {
            // search for PUTSTATIC
            InsnList insnList = methodNode.instructions;
            Iterator iterator1 = insnList.iterator();
            while (iterator1.hasNext()) {
                AbstractInsnNode ins2 = (AbstractInsnNode) iterator1.next();
                // if a initializing has been found, then copy everything from
                // the corresponding label to the PUTSTATIC
                if (ins2.getOpcode() == Opcodes.PUTSTATIC) {
                    final Boolean[] fieldFound = { false };
                    final FieldNode fNode = fieldNode;
                    ins2.accept(new MethodVisitor(Opcodes.ASM5) {
                        @Override
                        public void visitFieldInsn(int i, String s, String s2, String s3) {
                            if (s2.equals(fNode.name)) {
                                fieldFound[0] = true;
                            }
                            super.visitFieldInsn(i, s, s2, s3);
                        }
                    });
                    if (fieldFound[0]) {
                        // find the first PUTSTATIC before this one.
                        boolean staticFound = false;
                        while (!staticFound) {
                            AbstractInsnNode tmpInst = ins2.getPrevious();
                            if (tmpInst != null) {
                                if (tmpInst.getOpcode() != Opcodes.F_NEW) {
                                    if (tmpInst.getOpcode() == Opcodes.PUTSTATIC) {
                                        staticFound = true;
                                    } else {
                                        firstInst = tmpInst;
                                        counter++;
                                    }
                                }
                            } else {
                                staticFound = true;
                            }
                            ins2 = tmpInst;
                        }

                        break;
                    }
                }
            }

            if (firstInst != null) {
                InsnList iList = new InsnList();
                iList.add(firstInst.clone(null));
                counter--;
                while (counter > 0) {
                    AbstractInsnNode ain = firstInst.getNext();
                    iList.add(ain.clone(null));
                    counter--;
                    insnList.remove(firstInst);
                    firstInst = ain;
                }
                // remove last instruction and the putstatic instruction
                AbstractInsnNode putStatic = firstInst.getNext();
                insnList.remove(firstInst);
                insnList.remove(putStatic);
                return iList;
            }
        }
    }
    return null;
}

From source file:org.coldswap.asm.field.PrivateStaticFieldReplacer.java

License:Open Source License

/**
 * Replaces any GETSTATIC/PUTSTATIC call of the field in the old class with the field
 * introduced in the new class./*  ww w  . jav a 2 s. com*/
 *
 * @param classNode containing the old class.
 * @param fieldNode containing the old field.
 */
@SuppressWarnings("unchecked")
private void replaceReferences(ClassNode classNode, FieldNode fieldNode) {
    List<MethodNode> methodNodes = classNode.methods;
    String contClass = classNode.name.substring(classNode.name.lastIndexOf("/") + 1);
    final String className = classPackage
            + TransformerNameGenerator.getPrivateStaticFieldClassName(contClass, fieldNode.name);
    for (MethodNode method : methodNodes) {
        InsnList inst = method.instructions;
        Iterator iter = inst.iterator();
        while (iter.hasNext()) {
            AbstractInsnNode absIns = (AbstractInsnNode) iter.next();
            int opcode = absIns.getOpcode();
            // check if instruction is GETSTATIC or PUTSTATIC
            if (opcode == Opcodes.GETSTATIC) {
                // get type
                if (absIns.getType() == AbstractInsnNode.FIELD_INSN) {
                    final Boolean[] foundField = { false };
                    final ClassNode cNode = classNode;
                    final FieldNode fNode = fieldNode;
                    absIns.accept(new MethodVisitor(Opcodes.ASM5) {
                        @Override
                        public void visitFieldInsn(int i, String s, String s2, String s3) {
                            if (cNode.name.equals(s) && fNode.name.equals(s2)) {
                                foundField[0] = true;
                            }
                            super.visitFieldInsn(i, s, s2, s3);
                        }
                    });
                    if (foundField[0]) {
                        inst.set(absIns, new FieldInsnNode(Opcodes.GETSTATIC, className, fieldNode.name,
                                fieldNode.desc));
                    }
                }
            } else if (opcode == Opcodes.PUTSTATIC) {
                if (absIns.getType() == AbstractInsnNode.FIELD_INSN) {
                    final Boolean[] foundField = { false };
                    final ClassNode cNode = classNode;
                    final FieldNode fNode = fieldNode;
                    absIns.accept(new MethodVisitor(Opcodes.ASM5) {
                        @Override
                        public void visitFieldInsn(int i, String s, String s2, String s3) {
                            if (cNode.name.equals(s) && fNode.name.equals(s2)) {
                                foundField[0] = true;
                            }
                            super.visitFieldInsn(i, s, s2, s3);
                        }
                    });
                    if (foundField[0]) {
                        inst.set(absIns, new FieldInsnNode(Opcodes.PUTSTATIC, className, fieldNode.name,
                                fieldNode.desc));
                    }
                }
            }
        }
    }
}

From source file:org.coldswap.asm.field.ProtectedStaticFieldReferenceReplacer.java

License:Open Source License

@SuppressWarnings("uncheked")
@Override//  ww  w . j ava 2s.co  m
public int findAndReplace(ClassNode classNode) {
    int counter = 0;
    if (classNode.superName.equals(supperClass)) {
        List<MethodNode> methodNodes = classNode.methods;
        for (MethodNode method : methodNodes) {
            InsnList inst = method.instructions;
            Iterator iter = inst.iterator();
            while (iter.hasNext()) {
                AbstractInsnNode absIns = (AbstractInsnNode) iter.next();
                int opcode = absIns.getOpcode();
                // check if instruction is GETSTATIC or PUTSTATIC
                if (opcode == Opcodes.GETSTATIC) {
                    // get type
                    if (absIns.getType() == AbstractInsnNode.FIELD_INSN) {
                        final Boolean[] foundField = { false };
                        absIns.accept(new MethodVisitor(Opcodes.ASM5) {
                            @Override
                            public void visitFieldInsn(int i, String s, String s2, String s3) {
                                if (oldClass.equals(s) && fieldToReplace.name.equals(s2)) {
                                    foundField[0] = true;
                                }
                                super.visitFieldInsn(i, s, s2, s3);
                            }
                        });
                        if (foundField[0]) {
                            inst.set(absIns, new FieldInsnNode(Opcodes.GETSTATIC, newClass, fieldToReplace.name,
                                    fieldToReplace.desc));
                            counter++;
                        }
                    }
                } else if (opcode == Opcodes.PUTSTATIC) {
                    if (absIns.getType() == AbstractInsnNode.FIELD_INSN) {
                        final Boolean[] foundField = { false };
                        absIns.accept(new MethodVisitor(Opcodes.ASM5) {
                            @Override
                            public void visitFieldInsn(int i, String s, String s2, String s3) {
                                if (oldClass.equals(s) && fieldToReplace.name.equals(s2)) {
                                    foundField[0] = true;
                                }
                                super.visitFieldInsn(i, s, s2, s3);
                            }
                        });
                        if (foundField[0]) {
                            inst.set(absIns, new FieldInsnNode(Opcodes.PUTSTATIC, newClass, fieldToReplace.name,
                                    fieldToReplace.desc));
                            counter++;
                        }
                    }
                }
            }
        }
    }
    return counter;
}

From source file:org.coldswap.asm.field.ProtectedStaticFieldReplacer.java

License:Open Source License

/**
 * Removes any initializing reference of the field.
 *
 * @param classNode containing the old class.
 * @param fieldNode containing the old field.
 * @param canRemove <code>true</code> if this method should remove the initializing code and return it
 *                  or <code>false</code> if you only want to return the init code.
 * @return the initializing list of instructions.
 *//*from  w  w w  .ja  v a  2 s  .  co m*/
@SuppressWarnings("unchecked")
private InsnList cleanClInit(ClassNode classNode, FieldNode fieldNode, boolean canRemove) {
    List<MethodNode> methodNodes = classNode.methods;
    AbstractInsnNode firstInst = null;
    int counter = 0;
    for (MethodNode methodNode : methodNodes) {
        if (methodNode.name.equals("<clinit>")) {
            // search for PUTSTATIC
            InsnList insnList = methodNode.instructions;
            Iterator iterator1 = insnList.iterator();
            while (iterator1.hasNext()) {
                AbstractInsnNode ins2 = (AbstractInsnNode) iterator1.next();
                // if a initializing has been found, then copy everything from
                // the coresponding label to the PUTSTATIC
                if (ins2.getOpcode() == Opcodes.PUTSTATIC) {
                    final Boolean[] fieldFound = { false };
                    final FieldNode fNode = fieldNode;
                    ins2.accept(new MethodVisitor(Opcodes.ASM5) {
                        @Override
                        public void visitFieldInsn(int i, String s, String s2, String s3) {
                            if (s2.equals(fNode.name)) {
                                fieldFound[0] = true;
                            }
                            super.visitFieldInsn(i, s, s2, s3);
                        }
                    });
                    if (fieldFound[0]) {
                        // find the first PUTSTATIC before this one.
                        boolean staticFound = false;
                        while (!staticFound) {
                            AbstractInsnNode tmpInst = ins2.getPrevious();
                            if (tmpInst != null) {
                                if (tmpInst.getOpcode() != Opcodes.F_NEW) {
                                    if (tmpInst.getOpcode() == Opcodes.PUTSTATIC) {
                                        staticFound = true;
                                    } else {
                                        firstInst = tmpInst;
                                        counter++;
                                    }
                                }
                            } else {
                                staticFound = true;
                            }
                            ins2 = tmpInst;
                        }

                        break;
                    }
                }
            }

            if (firstInst != null) {
                InsnList iList = new InsnList();
                iList.add(firstInst.clone(null));
                counter--;
                while (counter > 0) {
                    AbstractInsnNode ain = firstInst.getNext();
                    iList.add(ain.clone(null));
                    counter--;
                    if (canRemove) {
                        insnList.remove(firstInst);
                    }
                    firstInst = ain;
                }
                if (canRemove) {
                    // remove last instruction and the putstatic instruction
                    AbstractInsnNode putStatic = firstInst.getNext();
                    insnList.remove(firstInst);
                    insnList.remove(putStatic);
                }
                return iList;
            }
        }
    }
    return null;
}