使用Asm注入一个类all方法
这是我的代码:
转换api获取所有类
def cacheFile = new File(file.parent, file.name + ".cache");
fis = new FileInputStream(file)
fos = new FileOutputStream(cacheFile)
println "injectFile: ${file.path}"
byte[] bytes = hackClass(file, null, false, fis);
fos.write(bytes)
if (file.exists()) {
file.delete()
}
cacheFile.renameTo(file)
Asm方法访问者
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = null;
if(name.equals("onCreate") || name.equals("onPause")){
System.out.println(file.getName() + "Method name : " + name);
mv = cv.visitMethod(access, name, desc, signature, exceptions);
return new TraceMethodVisitor(name, mv);
}
if (cv != null){
mv = cv.visitMethod(access, name, desc, signature, exceptions);
}
return mv;
}
MethodVisitor代码:
@Override
public void visitCode() {
//add start
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mv.visitLdcInsn("========start=========");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
mv.visitLdcInsn("Hi");
mv.visitLdcInsn("hello world");
mv.visitMethodInsn(INVOKEVIRTUAL, "android/util/Log", "v", "(Ljava/lang/String;Ljava/lang/String;)I", false);
super.visitCode();
}
如果MethodVisitor只修改一个方法,则成功
修改两个或多个方法,失败,上面的代码修改了两个方法
以下是控制台的输出:
:app:transformClassesWithDexForDebug
Uncaught translation error: com.android.dx.cf.code.SimException:stack: overflow
Uncaught translation error: com.android.dx.cf.code.SimException:stack: overflow
2 errors; aborting
:app:transformClassesWithDexForDebug FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
com.android.build.api.transform.TransformException:com.android.ide.common.process.ProcessException:java.util.concurrent.ExecutionException:com.android.ide.common.process.ProcessException:返回码1用于dex进程
如何解决此问题? :(
答案 0 :(得分:0)
创建类com / bigocto / hacksourcecode / JavaInjectTest
public class JavaInjectTest {
public static void test1(){
//Do something what you want
}
public void test2(){
System.out.println("I am test 2");
}
}
修改MethodVisitor代码
@Override
public void visitCode() {
//add start
this.visitMethodInsn(INVOKESTATIC, "com/bigocto/hacksourcecode/JavaInjectTest", "test1", "()V", false);
super.visitCode();
}
问题得到了解决!!
答案 1 :(得分:0)
我遇到类似错误的类似问题:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: Return code 1 for dex process
在我的情况下,错误包括依赖Java 1.8字节码会导致构建失败,因为我的应用程序使用的是Java 1.7。
我提出了与库维护者相同的内容,并明确将以下行添加到库的模块级build.gradle修复了问题:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
希望它有所帮助。