Question

While instrumenting a class for its different methods In order to make a method do a write operation in a text file. I first stored the string in a local variable 3160 explicitly defined. How to choose these variables to prevent conflicts with already existing variables.

Like in this snippet The code does the work of writing the class name to a text file every time it enters any method. In order to do so the string s had to be loaded on stack using variable 3160 ( value kept large so that the already defined variable names do not conflict with variable s (3160). My Question is how to define a local variables in a method during instrumentation with ASM Library. This question may seem kind of premature to many but that is because I am a beginner.

    String s= className;
    mv.visitLdcInsn(s);
    mv.visitVarInsn(Opcodes.ASTORE, 3160);
    mv.visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder");
    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ALOAD, 3160);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;");
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V");
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/me/database/dataCollectionFile/Info", "callMeAnyTime", "()Ljava/lang/String;");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;");
Was it helpful?

Solution

You should use LocalVariablesSorter adapter (either extend your own visitor from it, or add it to the visitors chain before MethodWriter). Then when you'll need a new variable you can call LocalVariablesSorter.newLocal() method to get new variable slot allocated. Also see ASM guide for more details.

OTHER TIPS

I would look at the local variables debug table and I would use the next available id which is more likely to be 2 or 10 rather than 3160.

If you don't have debugging information, you may need to scan the code more than once, first to see how many ids have been used.

Note: double and long require two ids for historical reasons.

newLocal(Type.type) is what I found is going to help in my case thank you Eugene Kuleshov and

Peter Lawrey for helping out :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top