How to find an empty local variable in a method for instrumenting using asm library

喜夏-厌秋 提交于 2019-12-13 15:28:54

问题


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;");

回答1:


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.




回答2:


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.




回答3:


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

Peter Lawrey for helping out :)



来源:https://stackoverflow.com/questions/11669461/how-to-find-an-empty-local-variable-in-a-method-for-instrumenting-using-asm-libr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!