Read Java Socket connect values using bytecode instrumentation

177 views Asked by At

I am trying to read the java.net.Socket connect method arguments in an interpreter using ASM. I am not sure how to read the value of method parameters using byte code instrumentation. Please help me with this.

public class SocketClassVisitor extends ClassVisitor {

    public SocketClassVisitor(ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

        return new SocketConnectSiteVisitor(mv, name, desc);
    }

    public static void sleep() {
        System.out.println("SLEEP IS CALLED!!!!!!!!!");
    }

    public static void onSocketConnect(SocketAddress endpoint, int timeout) {
        System.out.println("onSocketConnect IS CALLED!!!!!!!!!");
    }

    /**
     *   * bootstrap method for invokeDynamic support   
     */
    public static CallSite bootstrap(MethodHandles.Lookup caller, String name, MethodType type)
    throws NoSuchMethodException, IllegalAccessException {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class thisClass = lookup.lookupClass();
        MethodHandle methodHandle = lookup.findStatic(thisClass, name, type);
        return new ConstantCallSite(methodHandle.asType(type));
    }

    private class SocketConnectSiteVisitor extends MethodVisitor {
        private String methodName;
        private String desc;

        public SocketConnectSiteVisitor(MethodVisitor mv, String methodName, String desc) {
            super(Opcodes.ASM5, mv);
            this.methodName = methodName;
            this.desc = desc;
        }

        @Override
        public void visitCode() {
            if ("connect".equals(methodName) && "(Ljava/net/SocketAddress;I)V".equals(desc)) {

                mv.visitVarInsn(Opcodes.ILOAD, 2);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);

                mv.visitInsn(Opcodes.AASTORE);

                mv.visitVarInsn(Opcodes.ALOAD, 1);
                mv.visitInsn(Opcodes.AASTORE);

                this.visitLdcInsn("java/net/Socket");
                this.visitLdcInsn(this.methodName);

                mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getType(SocketClassVisitor.class).getInternalName(),
                    "onSocketConnect", "(Ljava/net/SocketAddress;I)V", false);
                System.out.println("VisitCode visitMethodInsn with args");

                super.visitCode();
            }
        }
    }
}

When ever I try to call Socket.connect from test program, the JVM crashes with error Problematic frame: j java.net.Socket.connect(Ljava/net/SocketAddress;I)V+1

0

There are 0 answers