diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..84c0c5c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,23 @@ +#Change Log + +## Version 1.0.4 +*2018-01-25 +* Fix: in rare case, lancet generate illegal bytecode because of multi-thread. + +## Version 1.0.3 +*2018-01-24* +* Fix: in rare case, lancet generate illegal bytecode because of multi-thread. +* Add an option to open/close incremental build. + +## Version 1.0.2 +*2017-9-11* +* Fix: fall back when runtime exception occurs during process class bytes. + +## Version 1.0.0 +*2017-07-14* +* Remove guava and android plugin dependency. +* Fix: when multiple proxy appear in one method, only one works. + +## Version 1.0.0-beta1 +*2017-05-31* +* Initial release. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..6723610 --- /dev/null +++ b/README.md @@ -0,0 +1,383 @@ +# Lancet + +[Chinese README](README_zh.md) + +Lancet is a lightweight AOP framework for Android. + +It's fast and just take up a little time during compiling. Also, it supports incremental compiling. + +But it provides great api to help you coding in Android. + +It takes no runtime jar. + +In addition, not only App developers but also SDK developers can use Lancet. + +## Usage +### Installation + +Firstly, add following code in root **build.gradle** of your project. + +```groovy +dependencies{ + classpath 'me.ele:lancet-plugin:1.0.4' +} +``` +And then, add following code in your **application module's build.gradle** + +```groovy +apply plugin: 'me.ele.lancet' + +dependencies { + provided 'me.ele:lancet-base:1.0.4' +} +``` + +That's OK.Now you can follow our tutorial to learn how to use it. + +### Tutorial + +Lancet use annotation to indicate where to cut the code and focus on interacting with origin class's methods and fields; + +Firstly, let's see a example. +Look at the following code: + +```java +@Proxy("i") +@TargetClass("android.util.Log") +public static int anyName(String tag, String msg){ + msg = msg + "lancet"; + return (int) Origin.call(); +} +``` + +There are some key points: + +* ```@TargetClass``` directly locate the target ```android.util.Log``` +* ```@Proxy```locate the method name```i``` +* ```Origin.call()``` will be replaced by```Log.i()``` as we explained above +* so the influence is every ```Log.i```'s second parameter```msg``` will has a trailing **"lancet"** + + +### Choose target class + +```java +public @interface TargetClass { + String value(); + + Scope scope() default Scope.SELF; +} + +public @interface ImplementedInterface { + + String[] value(); + + Scope scope() default Scope.SELF; +} + +public enum Scope { + + SELF, + DIRECT, + ALL, + LEAF +} +``` +We use the three classes above to locate our targets. + +#### @TargetClass + + 1. **value** in ```@TargetClass``` should be a full class name. + 2. Scope.SELF means the target is the class named by **value** + 3. Scope.DIRECT locate the direct subclasses of **value** + 4. Scope.All indicates the all subclasses of **value** + 5. The Scope.LEAF is a little bit special, it means all leaf subclasses of **value**.For example: ```A <- B <- C, B <- D```, the leaf children of A are C and D. + +#### @ImplementedInterface + +1. **value** in ```@ImplementedInterface``` is a string array filled with full interface names and classes that satisfied all conditions will be chosen. +2. Scope.SELF : all classes implements interfaces **literally** +3. Scope.DIRECT : all classes implements interfaces or their children interfaces **literally** +4. Scope.ALL: all classes included in *Scope.DIRECT* and their childrens +5. Scope.LEAF: all classes in *Scope.ALL* with no children. + +Let's see a illustration. + +![scope](media/14948409810841/scope.png) + +When we use```@ImplementedInterface(value = "I", scope = ...)```, the targets are: + +* Scope.SELF -> A +* Scope.DIRECT -> A C +* Scope.ALL -> A B C D +* Scope.LEAF -> B D + + +### Choose target method + +#### Choose method name + +```java +public @interface Insert { + String value(); + boolean mayCreateSuper() default false; +} + +public @interface Proxy { + String value(); +} + +public @interface TryCatchHandler { +} + +public @interface NameRegex { + String value(); +} + +``` + +##### @TryCatchHandler + +This annotation is easy. + +```java +@TryCatchHandler +@NameRegex("(?!me/ele/).*") + public static Throwable catches(Throwable t){ + return t; + } +``` + +As the code above, it hook every try catch handle, you can deal with and return. And the control flow will jump to it's origin space. + +But with the ```@NameRegex```, something is different. + +##### @NameRegex + +@NameRegex is used to restrict hook method by match the class name.Be caution, the *dot* in class name will be replaced by *slash*. + +String value in @NameRegex will be compiled to pattern. the hook method only works if the pattern matches the class name where appear the cut point. + +Such as the above example, every class will be ignored if it's package name start with "me.ele."; + +@NameRegex can only be used with @Proxy or @TryCatchHandler. + +##### @Proxy and @Insert + +1. **Value** in ```@Proxy``` and ```@Insert``` is the target method name. +2. ```@Proxy``` means to hook every invoke point of the target method. + +3. ```@Insert``` means to hook the code inside the method. +4. In another word, if you use @Insert to hook a method, the running code in the target method will be changed.But ```@Proxy``` can control the scope by using it combined with ```@NameRegex```. +5. Another different is, classes in Android's ROM can't be touched as compiling time.So we can't use @Insert if we want to change the behavior of ROM's classes, but @Proxy can do it. + +@Insert has a special boolean parameter is ```mayCreateSuper```.Let's see a example. + +```java + +@TargetClass(value = "android.support.v7.app.AppCompatActivity", scope = Scope.LEAF) +@Insert(value = "onStop", mayCreateSuper = true) +protected void onStop(){ + System.out.println("hello world"); + Origin.callVoid(); +} +``` + +The goal method of the hook method is +every leaf child of AppcompatActivity ```void onStop()```. + +If a class ```MyActivity extends AppcompatActivity```do not override the onStop method, we will create a method for ```MyActivity``` like this: + +```java +protected void onStop() { + super.onStop(); +} +``` + +And then hook the method. + +If you open the flag, it will always create the method if target class has no matched method no matter it has the super method or doesn't. + +And the public/protected/private flag is inherited from above hook method.This is the flag's only use. + +Also be care that + +#### Choose method descriptor + +The example shown at first also indicates a important rule which is the strict match.The ```Log.i``` 's full descriptor is **"int Log.i(String, String)"**, more precisely "**"(Ljava/lang/String;Ljava/lang/String;)I"**". + +It means our hook method should have the same method descriptor and static flag with target method. + +It doesn't matter if you don't known method descriptor. You can have a look at [JVM Specification Chapter 4.3](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3) if interested. + +We doesn't care if parameters' generic type are the same or not.In another word, we don't care signature of method, only descriptor. + +Also, exceptions declaration is also ignorable.You can write them for convenience. + +Any other access flag will be ignored except private/protected/public/static that we said above. + +##### @ClassOf + +Sometimes, we can't directly declare a class that we can't touch as parameter of our hook method. + +we can use ```@ClassOf``` to do this job. + +Take a look at the following example: + +```java +public class A { + protected int execute(B b){ + return b.call(); + } + + private class B { + + int call() { + return 0; + } + } +} + +@TargetClass("com.dieyidezui.demo.A") +@Insert("execute") +public int hookExecute(@ClassOf("com.dieyidezui.demo.A$B") Object o) { + System.out.println(o); + return (int) Origin.call(); +} +``` + +We use ```@ClassOf```to locate the parameter's actual type. + +And the parameter declared in method should be it's super class, such as ```java.lang.Object```; + +value in @ClassOf should be in the form of **"(package_name.)(outer_class_name$)class_name([]...)"**, such as: +* java.lang.Object +* java.lang.Integer[][] +* A[] +* A$B + +if no ```@ClassOf```, the hook method's descriptor is **"(Ljava/lang/Object;)I"**. But now it is **"(Lcom/dieyidezui/demo/A$B;)I"**. + +So the ```hookExecute``` method can match ```A.execute```. + +### API + +Till now, we have two classes to use, they are ```Origin``` and ```This```. + +#### Origin + +```Origin``` is used to call original method. +You can invoke its method zero or one more times if you like. + +##### Origin.call/callThrowOne/callThrowTwo/callThrowThree() +This group API is used for call the original method which has return value. +You should cast it to original type that the same with hook method descriptor's return type. + +##### Origin.callVoid/callVoidThrowOne/callVoidThrowTwo/callVoidThrowThree() + +Similar with above three methods, these methods are used for method without return value. + +By the way, the ```ThrowOne/ThrowTwo/ThrowThree``` are for deceiving the compiler if you want to catch some exceptions for some convenience. + +For example: + +```java +@TargetClass("java.io.InputStream") +@Proxy("read") +public int read(byte[] bytes) throws IOException { + try { + return (int) Origin.callThrowOne(); + } catch (IOException e) { + e.printStackTrace(); + throw e; + } +} +``` + +So that on every invoke point of ```int InputStream.read(byte[])```, if ```IOException``` happens, we will see its stacktrace. + +#### This + +##### get() + +This method is used for none static method to find this object. +You can cast it to its actual type. + +###### putField(Object, String) / getField(String) + +You can directly get or put a field in the target class even if the field is protected or private! + +What's more! If the field name is not exists, we will create it for you! + +Auto box and unbox are also supported. + +Also, we have some restricts: + +* These two methods only are only allowed to use with ```@Insert``` till now. +* You can't retrieve it's field of super class. When you try to get or put a field that it's super class has. We still will create the field for you. If the field of super class is private, it's OK. Otherwise, you will get a error at runtime. + +For example: + +```java +package me.ele; +public class Main { + private int a = 1; + + public void nothing(){ + + } + + public int getA(){ + return a; + } +} + +@TargetClass("me.ele.Main") +@Insert("nothing") +public void testThis() { + Log.e("debug", This.get().getClass().getName()); + This.putField(3, "a"); + Origin.callVoid(); +} + +``` + +Then we run the following codes: + +```java +Main main = new Main(); +main.nothing(); +Log.e("debug", "a = " + main.getA()); +``` + +We will see: + +``` +E/debug: me.ele.Main +E/debug: a = 3 +``` + +## Tips +1. Inner classes should be named like ```package.outer_class$inner_class``` +2. SDK developer needn't to apply plugin, just ```provided me.ele:lancet-base:x.y.z``` +3. Although we support incremental compilation. But when you use ```Scope.LEAF、Scope.ALL``` or edit the hook class, the incremental judgement will be a little special. It may cause full compilation. + +## License + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + + + + + + diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000..a247707 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,292 @@ +# Lancet + +Lancet 是一个轻量级Android AOP框架。 + ++ 编译速度快, 并且支持增量编译. ++ 简洁的 API, 几行 Java 代码完成注入需求. ++ 没有任何多余代码插入 apk. ++ 支持用于 SDK, 可以在SDK编写注入代码来修改依赖SDK的App. + +## 开始使用 +### 安装 + +在根目录的 `build.gradle` 添加: +```groovy +dependencies{ + classpath 'me.ele:lancet-plugin:1.0.4' +} +``` +在 app 目录的'build.gradle' 添加: +```groovy +apply plugin: 'me.ele.lancet' + +dependencies { + provided 'me.ele:lancet-base:1.0.4' +} +``` + + +### 示例 + +Lancet 使用注解来指定代码织入的规则与位置。 + +首先看看基础API使用: + +```java +@Proxy("i") +@TargetClass("android.util.Log") +public static int anyName(String tag, String msg){ + msg = msg + "lancet"; + return (int) Origin.call(); +} +``` + +这里有几个关键点: + +* ```@TargetClass``` 指定了将要被织入代码目标类 ```android.util.Log```. +* ```@Proxy``` 指定了将要被织入代码目标方法 ```i```. +* 织入方式为`Proxy`(将在后面介绍). +* ```Origin.call()``` 代表了 ```Log.i()``` 这个目标方法. + +所以这个示例Hook方法的作用就是 将代码里出现的所有 ```Log.i(tag,msg)``` 代码替换为```Log.i(tag,msg + "lancet")``` + +### 代码织入方式 + +#### @Proxy +```java +public @interface Proxy { + String value(); +} +``` + +`@Proxy` 将使用新的方法**替换**代码里存在的原有的目标方法. +比如代码里有10个地方调用了 `Dog.bark()`, 代理这个方法后,所有的10个地方的代码会变为`_Lancet.xxxx.bark()`. 而在这个新方法中会执行你在Hook方法中所写的代码. +`@Proxy` 通常用与对系统 API 的劫持。因为虽然我们不能注入代码到系统提供的库之中,但我们可以劫持掉所有调用系统API的地方。 + +##### @NameRegex +@NameRegex 用来限制范围操作的作用域. 仅用于`Proxy`模式中, 比如你只想代理掉某一个包名下所有的目标操作. 或者你在代理所有的网络请求时,不想代理掉自己发起的请求. 使用`NameRegex`对 `TargetClass` , `ImplementedInterface` 筛选出的class再进行一次匹配. + + + +#### @Insert +``` java +public @interface Insert { + String value(); + boolean mayCreateSuper() default false; +} +``` + +`@Insert` 将新代码插入到目标方法原有代码前后。 +`@Insert` 常用于操作App与library的类,并且可以通过`This`操作目标类的私有属性与方法(下文将会介绍)。 +`@Insert` 当目标方法不存在时,还可以使用`mayCreateSuper`参数来创建目标方法。 +比如下面将代码注入每一个Activity的`onStop`生命周期 + +```java + +@TargetClass(value = "android.support.v7.app.AppCompatActivity", scope = Scope.LEAF) +@Insert(value = "onStop", mayCreateSuper = true) +protected void onStop(){ + System.out.println("hello world"); + Origin.callVoid(); +} +``` + +`Scope` 将在后文介绍,这里的意为目标是 `AppCompatActivity` 的所有最终子类。 +如果一个类 `MyActivity extends AppcompatActivity` 没有重写 `onStop` 会自动创建`onStop`方法,而`Origin`在这里就代表了`super.onStop()`, 最后就是这样的效果: + +```java +protected void onStop() { + System.out.println("hello world"); + super.onStop(); +} +``` + +Note:public/protected/private 修饰符会完全照搬 Hook 方法的修饰符。 + + +### 匹配目标类 + +```java +public @interface TargetClass { + String value(); + + Scope scope() default Scope.SELF; +} + +public @interface ImplementedInterface { + + String[] value(); + + Scope scope() default Scope.SELF; +} + +public enum Scope { + + SELF, + DIRECT, + ALL, + LEAF +} +``` + +很多情况,我们不会仅匹配一个类,会有注入某各类所有子类,或者实现某个接口的所有类等需求。所以通过 `TargetClass` , `ImplementedInterface` 2个注解及 `Scope` 进行目标类匹配。 + +#### @TargetClass +通过类查找. + 1. `@TargetClass` 的 `value` 是一个类的全称. + 2. Scope.SELF 代表仅匹配 `value` 指定的目标类. + 3. Scope.DIRECT 代表匹配 `value` 指定类的直接子类. + 4. Scope.All 代表匹配 `value` 指定类的所有子类. + 5. Scope.LEAF 代表匹配 `value` 指定类的最终子类.众所周知java是单继承,所以继承关系是树形结构,所以这里代表了指定类为顶点的继承树的所有叶子节点. + +#### @ImplementedInterface +通过接口查找. 情况比通过类查找稍复杂一些. +1. `@ImplementedInterface` 的 `value` 可以填写多个接口的全名. +2. Scope.SELF : 代表直接实现所有指定接口的类. +3. Scope.DIRECT : 代表直接实现所有指定接口,以及指定接口的子接口的类. +4. Scope.ALL: 代表 `Scope.DIRECT` 指定的所有类及他们的所有子类. +5. Scope.LEAF: 代表 `Scope.ALL` 指定的森林结构中的所有叶节点. + +如下图: +![scope](media/14948409810841/scope.png) + +当我们使用`@ImplementedInterface(value = "I", scope = ...)`时, 目标类如下: + +* Scope.SELF -> A +* Scope.DIRECT -> A C +* Scope.ALL -> A B C D +* Scope.LEAF -> B D + + +### 匹配目标方法 +虽然在 `Proxy` , `Insert` 中我们指定了方法名, 但识别方法必须要更细致的信息. 我们会直接使用 Hook 方法的修饰符,参数类型来匹配方法. +所以一定要保持 Hook 方法的 `public/protected/private` `static` 信息与目标方法一致,参数类型,返回类型与目标方法一致. +返回类型可以用 Object 代替. +方法名不限. 异常声明也不限. + +但有时候我们并没有权限声明目标类. 这时候怎么办? +##### @ClassOf +可以使用 `ClassOf` 注解来替代对类的直接 import. +比如下面这个例子: +```java +public class A { + protected int execute(B b){ + return b.call(); + } + + private class B { + + int call() { + return 0; + } + } +} + +@TargetClass("com.dieyidezui.demo.A") +@Insert("execute") +public int hookExecute(@ClassOf("com.dieyidezui.demo.A$B") Object o) { + System.out.println(o); + return (int) Origin.call(); +} +``` + +`ClassOf` 的 value 一定要按照 **`(package_name.)(outer_class_name$)inner_class_name([]...)`**的模板. +比如: +* java.lang.Object +* java.lang.Integer[][] +* A[] +* A$B + +### API +我们可以通过 `Origin` 与 `This` 与目标类进行一些交互. + +#### Origin +`Origin` 用来调用原目标方法. 可以被多次调用. +`Origin.call()` 用来调用有返回值的方法. +`Origin.callVoid()` 用来调用没有返回值的方法. +另外,如果你有捕捉异常的需求.可以使用 +`Origin.call/callThrowOne/callThrowTwo/callThrowThree()` +`Origin.callVoid/callVoidThrowOne/callVoidThrowTwo/callVoidThrowThree()` + +For example: + +```java +@TargetClass("java.io.InputStream") +@Proxy("read") +public int read(byte[] bytes) throws IOException { + try { + return (int) Origin.callThrowOne(); + } catch (IOException e) { + e.printStackTrace(); + throw e; + } +} +``` + + +#### This +仅用于`Insert` 方式的非静态方法的Hook中.(暂时) + +##### get() +返回目标方法被调用的实例化对象. + +###### putField & getField +你可以直接存取目标类的所有属性,无论是 `protected` or `private`. +另外,如果这个属性不存在,我们还会自动创建这个属性. Exciting! +自动装箱拆箱肯定也支持了. + +一些已知的缺陷: ++ `Proxy` 不能使用 `This` ++ 你不能存取你父类的属性. 当你尝试存取父类属性时,我们还是会创建新的属性. + +For example: + +```java +package me.ele; +public class Main { + private int a = 1; + + public void nothing(){ + + } + + public int getA(){ + return a; + } +} + +@TargetClass("me.ele.Main") +@Insert("nothing") +public void testThis() { + Log.e("debug", This.get().getClass().getName()); + This.putField(3, "a"); + Origin.callVoid(); +} + +``` + +## Tips +1. 内部类应该命名为 ```package.outer_class$inner_class``` +2. SDK 开发者不需要 `apply` 插件, 只需要 ```provided me.ele:lancet-base:x.y.z``` +3. 尽管我们支持增量编译. 但当我们使用 ```Scope.LEAF、Scope.ALL``` 覆盖的类有变动 或者修改 Hook 类时, 本次编译将会变成全量编译. + +## License + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + + + + + + diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..41449e2 --- /dev/null +++ b/TODO.md @@ -0,0 +1,7 @@ +# TODOList ++ meta.json in parser use json format and support version compatible ++ split PlaceHolder's function ++ support private field and method invoke. ++ support dynamically create field and method. ++ auto compile base and processor module ++ write unit test diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..fd14310 --- /dev/null +++ b/build.gradle @@ -0,0 +1,156 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +apply plugin: 'base' +buildscript { + ext { + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + + ele = true + ele = "true" == properties.getProperty("ele") + + if (!ele) { + bintrayUser = properties.getProperty('bintrayUser') + bintrayKey = properties.getProperty('bintrayKey') + } + lancet_group = 'me.ele' + lancet_version = '1.0.4' + //lancet_version = '0.0.1.8-SNAPSHOT' + + asm_version = '7.0' + //android_tools_version = '2.4.0-alpha6' + android_tools_version = '3.2.1' + guava_version = '20.0' + } + repositories { + jcenter() + mavenCentral() + maven { + if (ele) { + url "http://maven.dev.elenet.me/nexus/content/groups/public" + } else { + url "https://dl.bintray.com/eleme-mt-arch/maven" + } + } + } + dependencies { + if (ele) { + classpath 'me.ele:eradle:1.7.0' + } else { + classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' + } + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +subprojects { pro -> + + repositories { + jcenter() + mavenCentral() + maven { + url 'https://maven.google.com' + } + } + + if (pro.name == 'sample-test')return + + version = lancet_version + group = lancet_group + + if (ele) { + apply plugin: 'eradle' + modifyPom { + project { + groupId lancet_group + artifactId pro.name + version lancet_version + packaging 'jar' + } + } + extraArchive { + sources = true + } + } else { + apply plugin: 'maven' + apply plugin: 'com.jfrog.bintray' + afterEvaluate { + task sourcesJar(type: Jar) { + from sourceSets.main.java.srcDirs + classifier = 'sources' + } + + task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir + } + + artifacts { + archives sourcesJar + archives javadocJar + } + tasks.install { + repositories.mavenInstaller { + pom { + project { + packaging 'jar' + licenses { + license { + name 'The Apache Software License, Version 2.0' + url 'http://www.apache.org/licenses/LICENSE-2.0.txt' + } + } + developers { + developer { + id 'dieyidezui' + name '耿万鹏' + email 'dieyidezui@gmail.com' + } + developer { + id 'jude95' + name '朱晨曦' + email '973829691@qq.com' + } + } + } + } + } + } + } + bintray { + user = bintrayUser + key = bintrayKey + configurations = ['archives'] + pkg { + userOrg = "eleme-mt-arch" + repo = "maven" + userOrg = "eleme-mt-arch" + name = pro.name //发布到JCenter上的项目名字 + websiteUrl = "https://github.com/eleme/lancet" + vcsUrl = "git@github.com:eleme/lancet.git" + licenses = ["Apache-2.0"] + publish = true + } + } + } + +} + +task uploadAll { task -> + + task.group = 'upload' + gradle.projectsEvaluated { + task.dependsOn project.tasks.clean + task.dependsOn project.tasks.build + + project.tasks.build.mustRunAfter project.tasks.clean + + project.subprojects { + if (it.name != 'sample-test') { + Task upload = !ele ? it.tasks.bintrayUpload : it.tasks.uploadArchives; + task.dependsOn upload + upload.mustRunAfter project.tasks.build + } + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..89196d1 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..86a9f99 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +#Mon Apr 10 15:23:45 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.10-all.zip + diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lancet-base/.gitignore b/lancet-base/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/lancet-base/.gitignore @@ -0,0 +1 @@ +/build diff --git a/lancet-base/build.gradle b/lancet-base/build.gradle new file mode 100644 index 0000000..608c002 --- /dev/null +++ b/lancet-base/build.gradle @@ -0,0 +1,10 @@ +apply plugin: 'java' + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'org.aspectj:aspectjrt:1.9.2' + compileOnly "com.google.code.findbugs:jsr305:3.0.2" +} + +sourceCompatibility = "1.7" +targetCompatibility = "1.7" diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/AroundContext.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/AroundContext.java new file mode 100644 index 0000000..dac042b --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/AroundContext.java @@ -0,0 +1,36 @@ +package com.dieyidezui.lancet.rt; + +import com.sun.istack.internal.Nullable; + +public interface AroundContext { + + /** + * @return The Arguments of the methods, changes to it will affect {@link AroundContext#proceed()}'s arguments on Lancet.getGlobalInterceptor. + * But it doesn't works on hook method, because {@link AroundContext#proceed()} will collect your hook method's actual arguments as parameters. + */ + Object[] getArgs(); + + /** + * @return The context where your target method called. + * If static, return the class of method. + */ + Object getTarget(); + + /** + * @return The object when your target method executed. + * If static, return the class of method. + */ + Object getThis(); + + @Nullable + Object proceed(); + + @Nullable + Object proceedThrow1() throws T1; + + @Nullable + Object proceedThrow2() throws T1, T2; + + @Nullable + Object proceedThrow3() throws T1, T2, T3; +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/AutoReplaced.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/AutoReplaced.java new file mode 100644 index 0000000..0c39403 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/AutoReplaced.java @@ -0,0 +1,13 @@ +package com.dieyidezui.lancet.rt; + +import java.lang.annotation.*; + +/** + * Indicates that annotations will replace / move / transform their annotated methods' bytecode. + */ +@Documented +@Retention(RetentionPolicy.SOURCE) +@AutoReplaced +@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +public @interface AutoReplaced { +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Interceptor.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Interceptor.java new file mode 100644 index 0000000..3192f84 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Interceptor.java @@ -0,0 +1,6 @@ +package com.dieyidezui.lancet.rt; + +public interface Interceptor { + + Object intercept(AroundContext context); +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Lancet.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Lancet.java new file mode 100644 index 0000000..f2b7520 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Lancet.java @@ -0,0 +1,31 @@ +package com.dieyidezui.lancet.rt; + +import javax.annotation.Nullable; + +public class Lancet { + + private static Lancet instance = new Lancet(); + + public static Lancet instance() { + return instance; + } + + private Interceptor global; + + /** + * Add Method Interceptor at runtime, use it carefully! + */ + public void setGlobalInterceptor(@Nullable Interceptor interceptor) { + this.global = interceptor; + } + + @Nullable + public Interceptor getGlobalInterceptor() { + return global; + } + + @AutoReplaced + public static AroundContext getContext() { + throw new AssertionError("Don't invoke it outside hook method!"); + } +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Scope.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Scope.java new file mode 100644 index 0000000..5c0a102 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/Scope.java @@ -0,0 +1,12 @@ +package com.dieyidezui.lancet.rt; + +/** + * Created by gengwanpeng on 17/5/3. + */ +public enum Scope { + + SELF, + DIRECT, + ALL, + LEAF +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/ClassOf.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/ClassOf.java new file mode 100644 index 0000000..4ebad36 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/ClassOf.java @@ -0,0 +1,20 @@ +package com.dieyidezui.lancet.rt.annotations; + +import java.lang.annotation.*; + +/** + * Annotates a parameter that its actual desc is the value(). + * The parameter should be instance of the desc of class. + * For example: + * void foo(@ClassOf("java.util.HashMap") HashMap map); // useless for @ClassOf + * void foo(@ClassOf("java.util.HashMap") Map map); // work + * void foo(@ClassOf("java.util.HashMap[]") Object obj); // work + * void foo(@ClassOf("java.util.HashMap[]") Map[] maps); // work + * void foo(@ClassOf("java.util.HashMap[]") Map map); // doesn't work + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface ClassOf { + String value(); +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/ImplementedInterface.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/ImplementedInterface.java new file mode 100644 index 0000000..116bcc1 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/ImplementedInterface.java @@ -0,0 +1,27 @@ +package com.dieyidezui.lancet.rt.annotations; + +import com.dieyidezui.lancet.rt.Scope; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Limit the target classes. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface ImplementedInterface { + + /** + * Interface array, java type name, $ for inner class. + * For example : a.b.c$d; + */ + String[] value(); + + /** + * The scope of interface array. + */ + Scope scope() default Scope.SELF; +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Insert.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Insert.java new file mode 100644 index 0000000..ba2349e --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Insert.java @@ -0,0 +1,30 @@ +package com.dieyidezui.lancet.rt.annotations; + +import com.dieyidezui.lancet.rt.AutoReplaced; + +import java.lang.annotation.*; + +/** + * Indicate the hook method. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@AutoReplaced +public @interface Insert { + + /** + * The target method name. + */ + String value(); + + /** + * if true, create empty method which only invoke super if not exits + */ + boolean mayCreateSuper() default false; + + /** + * Priority to sort hook methods, the smaller, the higher. + */ + int priority() default 0; +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Interceptable.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Interceptable.java new file mode 100644 index 0000000..b376bb8 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Interceptable.java @@ -0,0 +1,16 @@ +package com.dieyidezui.lancet.rt.annotations; + +import com.dieyidezui.lancet.rt.AutoReplaced; +import com.dieyidezui.lancet.rt.Lancet; + +import java.lang.annotation.*; + +/** + * Annotate a method to make it interceptable by {@link Lancet#getGlobalInterceptor()}. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +@AutoReplaced +public @interface Interceptable { +} \ No newline at end of file diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/NameRegex.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/NameRegex.java new file mode 100644 index 0000000..01f3911 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/NameRegex.java @@ -0,0 +1,18 @@ +package com.dieyidezui.lancet.rt.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Restrict {@link Proxy} and {@link TryCatchHandler}'s scope, only classes which matched the regex will add the hook code. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface NameRegex { + /** + * The regex to match the class name, use the internal name, dot to slash + */ + String value(); +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Proxy.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Proxy.java new file mode 100644 index 0000000..0a899d6 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/Proxy.java @@ -0,0 +1,24 @@ +package com.dieyidezui.lancet.rt.annotations; + +import com.dieyidezui.lancet.rt.AutoReplaced; + +import java.lang.annotation.*; + +/** + * Indicate the hook method. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@AutoReplaced +public @interface Proxy { + /** + * The target method name. + */ + String value(); + + /** + * Priority to sort hook methods, the smaller, the higher. + */ + int priority() default 0; +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/TargetClass.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/TargetClass.java new file mode 100644 index 0000000..4417daf --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/TargetClass.java @@ -0,0 +1,17 @@ +package com.dieyidezui.lancet.rt.annotations; + +import com.dieyidezui.lancet.rt.Scope; + +import java.lang.annotation.*; + +/** + * Limit the target classes. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface TargetClass { + String value(); + + Scope scope() default Scope.SELF; +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/TryCatchHandler.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/TryCatchHandler.java new file mode 100644 index 0000000..58abbf9 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/annotations/TryCatchHandler.java @@ -0,0 +1,17 @@ +package com.dieyidezui.lancet.rt.annotations; + +import com.dieyidezui.lancet.rt.AutoReplaced; + +import java.lang.annotation.*; + +/** + * Pre process the classes who extends {@link Throwable}. + * The method desc should like (A)A (A is a class that extends Throwable). + * Combine with {@link NameRegex} to restrict the scope. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@AutoReplaced +public @interface TryCatchHandler { +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/AroundMethodChain.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/AroundMethodChain.java new file mode 100644 index 0000000..4688e9a --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/AroundMethodChain.java @@ -0,0 +1,81 @@ +package com.dieyidezui.lancet.rt.internal; + + +import com.dieyidezui.lancet.rt.AroundContext; +import com.dieyidezui.lancet.rt.Interceptor; + +import javax.annotation.Nullable; +import java.util.List; + +public class AroundMethodChain implements AroundContext { + + private final Object target; + private final Object thiz; + private final int index; + private final List interceptors; + private final Object[] args; + + public AroundMethodChain(Object target, Object thiz, int index, List interceptors, Object[] args) { + this.target = target; + this.thiz = thiz; + this.index = index; + this.interceptors = interceptors; + this.args = args; + } + + @Nullable + @Override + public Object getTarget() { + return target; + } + + @Nullable + @Override + public Object getThis() { + return thiz; + } + + @Override + public Object[] getArgs() { + return args; + } + + @Nullable + @Override + public Object proceedThrow1() throws T1 { + return proceed(); + } + + @Nullable + @Override + public Object proceedThrow2() throws T1, T2 { + return proceed(); + } + + @Nullable + @Override + public Object proceedThrow3() throws T1, T2, T3 { + return proceed(); + } + + @Nullable + @Override + public Object proceed() { + return proceed(args.clone()); + } + + /** + * public for generated code! + * + * @param args don't clone args + */ + @Nullable + public Object proceed(Object[] args) { + if (this.index > interceptors.size()) { + throw new AssertionError(); + } + // Clone args when pass to next! + AroundMethodChain next = new AroundMethodChain(target, thiz, index + 1, interceptors, args); + return interceptors.get(index).intercept(next); + } +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/Util.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/Util.java new file mode 100644 index 0000000..2eebf48 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/Util.java @@ -0,0 +1,4 @@ +package com.dieyidezui.lancet.rt.internal; + +public class Util { +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/codegen/CodegenHelper.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/codegen/CodegenHelper.java new file mode 100644 index 0000000..e5c7cfd --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/codegen/CodegenHelper.java @@ -0,0 +1,46 @@ +package com.dieyidezui.lancet.rt.internal.codegen; + +import com.dieyidezui.lancet.rt.Interceptor; +import com.dieyidezui.lancet.rt.Lancet; +import com.dieyidezui.lancet.rt.AroundContext; +import com.dieyidezui.lancet.rt.annotations.TryCatchHandler; +import com.dieyidezui.lancet.rt.internal.AroundMethodChain; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CodegenHelper { + + /** + * Invoked by generated code at hook point. + * @param interceptorArray sorted by priority + */ + public static void doAround(@Nullable Object target, @Nullable Object thiz, Object[] args, GeneratedInterceptor[] interceptorArray) { + + List interceptors = new ArrayList<>(interceptorArray.length + 1); + + Interceptor global = Lancet.instance().getGlobalInterceptor(); + if (global != null) { + interceptors.add(global); + } + interceptors.addAll(Arrays.asList(interceptorArray)); + // Optimize for first invoke, reduce clone args once + new AroundMethodChain(target, thiz, 0, interceptors, null).proceed(args); + } + + /** + * For {@link TryCatchHandler} + */ + public static Object onThrow(@Nullable Object target, Object[] args, GeneratedInterceptor[] interceptors) { + return new AroundMethodChain(target, null, 0, Arrays.asList(interceptors), null).proceed(args); + } + + /** + * Lancet.getContext() will redirect to this method + */ + public static AroundContext getContext(GeneratedInterceptor interceptor) { + return interceptor.getContext(); + } +} diff --git a/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/codegen/GeneratedInterceptor.java b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/codegen/GeneratedInterceptor.java new file mode 100644 index 0000000..97285b7 --- /dev/null +++ b/lancet-base/src/main/java/com/dieyidezui/lancet/rt/internal/codegen/GeneratedInterceptor.java @@ -0,0 +1,24 @@ +package com.dieyidezui.lancet.rt.internal.codegen; + +import com.dieyidezui.lancet.rt.Interceptor; +import com.dieyidezui.lancet.rt.AroundContext; + +import javax.annotation.Nullable; + +public abstract class GeneratedInterceptor implements Interceptor { + + private AroundContext context; + + @Override + public final Object intercept(AroundContext context) { + this.context = context; + return intercept(context.getArgs()); + } + + final public AroundContext getContext() { + return context; + } + + @Nullable + protected abstract Object intercept(Object[] args); +} diff --git a/lancet-plugin/.gitignore b/lancet-plugin/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/lancet-plugin/.gitignore @@ -0,0 +1 @@ +/build diff --git a/lancet-plugin/build.gradle b/lancet-plugin/build.gradle new file mode 100644 index 0000000..1c7d763 --- /dev/null +++ b/lancet-plugin/build.gradle @@ -0,0 +1,30 @@ +apply plugin: 'java' + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile gradleApi() + compileOnly "com.android.tools.build:gradle:$android_tools_version" + compile "com.google.code.gson:gson:2.8.0" + compile project(':lancet-weaver') + testCompile gradleTestKit() + testCompile 'junit:junit:4.12' +} + +sourceCompatibility = "1.8" +targetCompatibility = "1.8" + +task createClasspathManifest { + def outputDir = file("$buildDir/$name") + + inputs.files sourceSets.main.runtimeClasspath + outputs.dir outputDir + + doLast { + outputDir.mkdirs() + file("$outputDir/plugin-classpath.txt").text = sourceSets.main.runtimeClasspath.join("\n") + } +} + +dependencies { + testRuntime files(createClasspathManifest) +} \ No newline at end of file diff --git a/lancet-plugin/src/main/java/com/dieyidezui/lancet/plugin/LancetTransform.java b/lancet-plugin/src/main/java/com/dieyidezui/lancet/plugin/LancetTransform.java new file mode 100644 index 0000000..8686ff1 --- /dev/null +++ b/lancet-plugin/src/main/java/com/dieyidezui/lancet/plugin/LancetTransform.java @@ -0,0 +1,39 @@ +package com.dieyidezui.lancet.plugin; + +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.Transform; +import com.android.build.api.transform.TransformException; +import com.android.build.api.transform.TransformInvocation; +import com.android.build.gradle.internal.pipeline.TransformManager; + +import java.io.IOException; +import java.util.Set; + +public class LancetTransform extends Transform { + + + @Override + public String getName() { + return "lancet"; + } + + @Override + public Set getInputTypes() { + return TransformManager.CONTENT_CLASS; + } + + @Override + public Set getScopes() { + return TransformManager.SCOPE_FULL_PROJECT; + } + + @Override + public boolean isIncremental() { + return true; + } + + @Override + public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException { + + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetExtension.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetExtension.java new file mode 100644 index 0000000..35f848a --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetExtension.java @@ -0,0 +1,73 @@ + +package me.ele.lancet.plugin; + +import com.google.common.base.Strings; +import me.ele.lancet.weaver.internal.log.Log; + +import java.io.File; +import java.util.Objects; + +public class LancetExtension { + private Log.Level level = Log.Level.INFO; + private String fileName = null; + private boolean incremental = true; + + public void logLevel(Log.Level level) { + this.level = Objects.requireNonNull(level, "Log.Level is null"); + } + + public void logLevel(int level) { + this.level = Log.Level.values()[level]; + } + + public void logLevel(String logStr) { + logLevel(strToLog(logStr)); + } + + private static Log.Level strToLog(String logStr) { + logStr = logStr.toLowerCase(); + switch (logStr) { + case "d": + case "debug": + return Log.Level.DEBUG; + case "i": + case "info": + return Log.Level.INFO; + case "w": + case "warn": + return Log.Level.WARN; + case "e": + case "error": + return Log.Level.ERROR; + default: + throw new IllegalArgumentException("wrong log string: " + logStr); + } + } + + public void useFileLog(String fileName) { + if (Strings.isNullOrEmpty(fileName) || fileName.contains(File.separator)) { + throw new IllegalArgumentException("File name is illegal: " + fileName); + } + this.fileName = fileName; + } + + public void setIncremental(boolean incremental) { + this.incremental = incremental; + } + + public boolean getIncremental() { + return this.incremental; + } + + public void incremental(boolean incremental) { + this.incremental = incremental; + } + + public Log.Level getLogLevel() { + return level; + } + + public String getFileName() { + return fileName; + } +} \ No newline at end of file diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetPlugin.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetPlugin.java new file mode 100644 index 0000000..b70a145 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetPlugin.java @@ -0,0 +1,22 @@ +package me.ele.lancet.plugin; + + +import com.android.build.gradle.BaseExtension; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.ProjectConfigurationException; + +public class LancetPlugin implements Plugin { + + @Override + public void apply(Project project) { + if (project.getPlugins().findPlugin("com.android.application") == null + && project.getPlugins().findPlugin("com.android.library") == null) { + throw new ProjectConfigurationException("Need android application/library plugin to be applied first", null); + } + + BaseExtension baseExtension = (BaseExtension) project.getExtensions().getByName("android"); + LancetExtension lancetExtension = project.getExtensions().create("lancet", LancetExtension.class); + baseExtension.registerTransform(new LancetTransform(project, lancetExtension)); + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetTransform.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetTransform.java new file mode 100644 index 0000000..f6da027 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/LancetTransform.java @@ -0,0 +1,165 @@ +package me.ele.lancet.plugin; + +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.SecondaryFile; +import com.android.build.api.transform.Transform; +import com.android.build.api.transform.TransformException; +import com.android.build.api.transform.TransformInvocation; +import com.android.build.gradle.internal.pipeline.TransformManager; +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.common.io.Files; + +import org.gradle.api.Project; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import me.ele.lancet.plugin.internal.GlobalContext; +import me.ele.lancet.plugin.internal.LocalCache; +import me.ele.lancet.plugin.internal.preprocess.PreClassAnalysis; +import me.ele.lancet.plugin.internal.TransformContext; +import me.ele.lancet.plugin.internal.TransformProcessor; +import me.ele.lancet.plugin.internal.context.ContextReader; +import me.ele.lancet.weaver.MetaParser; +import me.ele.lancet.weaver.Weaver; +import me.ele.lancet.weaver.internal.AsmWeaver; +import me.ele.lancet.weaver.internal.entity.TransformInfo; +import me.ele.lancet.weaver.internal.log.Impl.FileLoggerImpl; +import me.ele.lancet.weaver.internal.log.Log; +import me.ele.lancet.weaver.internal.parser.AsmMetaParser; + +class LancetTransform extends Transform { + + private final LancetExtension lancetExtension; + private final GlobalContext global; + private LocalCache cache; + + + public LancetTransform(Project project, LancetExtension lancetExtension) { + this.lancetExtension = lancetExtension; + this.global = new GlobalContext(project); + // load the LocalCache from disk + this.cache = new LocalCache(global.getLancetDir()); + } + + @Override + public String getName() { + return "lancet"; + } + + + @Override + public Set getInputTypes() { + return TransformManager.CONTENT_CLASS; + } + + + @Override + public Set getScopes() { + return TransformManager.SCOPE_FULL_PROJECT; + } + + @Override + public boolean isIncremental() { + return true; + } + + + /** + * @return Hook classes we found in last compilation. If they has been changed,gradle will auto go full compile. + */ + @Override + public Collection getSecondaryFiles() { + return cache.hookClassesInDir() + .stream() + .map(File::new) + .map(SecondaryFile::nonIncremental) + .collect(Collectors.toList()); + } + + @Override + public Collection getSecondaryDirectoryOutputs() { + return Collections.singletonList(global.getLancetDir()); + } + + @Override + public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException { + initLog(); + + Log.i("start time: " + System.currentTimeMillis()); + + // collect the information this compile need + TransformContext context = new TransformContext(transformInvocation, global); + + Log.i("after android plugin, incremental: " + context.isIncremental()); + Log.i("now: " + System.currentTimeMillis()); + + boolean incremental = lancetExtension.getIncremental() && context.isIncremental(); + + PreClassAnalysis preClassAnalysis = new PreClassAnalysis(cache); + + incremental = preClassAnalysis.execute(incremental, context); + + Log.i("after pre analysis, incremental: " + incremental); + Log.i("now: " + System.currentTimeMillis()); + + MetaParser parser = createParser(context); + if (incremental && !context.getGraph().checkFlow()) { + incremental = false; + context.clear(); + } + Log.i("after check flow, incremental: " + incremental); + Log.i("now: " + System.currentTimeMillis()); + + context.getGraph().flow().clear(); + TransformInfo transformInfo = parser.parse(context.getHookClasses(), context.getGraph()); + + Weaver weaver = AsmWeaver.newInstance(transformInfo, context.getGraph()); + new ContextReader(context).accept(incremental, new TransformProcessor(context, weaver)); + Log.i("build successfully done"); + Log.i("now: " + System.currentTimeMillis()); + + cache.saveToLocal(); + Log.i("cache saved"); + Log.i("now: " + System.currentTimeMillis()); + } + + private AsmMetaParser createParser(TransformContext context) { + URL[] urls = Stream.concat(context.getAllJars().stream(), context.getAllDirs().stream()).map(QualifiedContent::getFile) + .map(File::toURI) + .map(u -> { + try { + return u.toURL(); + } catch (MalformedURLException e) { + throw new AssertionError(e); + } + }) + .toArray(URL[]::new); + Log.d("urls:\n" + Joiner.on("\n ").join(urls)); + ClassLoader cl = URLClassLoader.newInstance(urls, null); + return new AsmMetaParser(cl); + } + + private void initLog() throws IOException { + Log.setLevel(lancetExtension.getLogLevel()); + if (!Strings.isNullOrEmpty(lancetExtension.getFileName())) { + String name = lancetExtension.getFileName(); + if (name.contains(File.separator)) { + throw new IllegalArgumentException("Log file name can't contains file separator"); + } + File logFile = new File(global.getLancetDir(), "log_" + lancetExtension.getFileName()); + Files.createParentDirs(logFile); + Log.setImpl(FileLoggerImpl.of(logFile.getAbsolutePath())); + } + } +} + diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/Util.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/Util.java new file mode 100644 index 0000000..537b9e3 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/Util.java @@ -0,0 +1,21 @@ +package me.ele.lancet.plugin; + +import com.android.utils.FileUtils; +import me.ele.lancet.weaver.internal.asm.ClassTransform; + +import java.io.File; + +/** + * Created by gengwanpeng on 17/5/4. + */ +public class Util { + + public static File toSystemDependentFile(File parent, String relativePath) { + return new File(parent, relativePath.replace('/', File.separatorChar)); + } + + public static File toSystemDependentHookFile(File relativeRoot, String relativePath) { + int index = relativePath.lastIndexOf('.'); + return toSystemDependentFile(relativeRoot, relativePath.substring(0, index) + ClassTransform.AID_INNER_CLASS_NAME + relativePath.substring(index)); + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/GlobalContext.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/GlobalContext.java new file mode 100644 index 0000000..e3fc881 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/GlobalContext.java @@ -0,0 +1,22 @@ +package me.ele.lancet.plugin.internal; + +import org.gradle.api.Project; + +import java.io.File; + +/** + * Created by gengwanpeng on 17/4/26. + */ +public class GlobalContext { + + private Project project; + + public GlobalContext(Project project) { + this.project = project; + } + + + public File getLancetDir() { + return new File(project.getBuildDir(), "lancet"); + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/LocalCache.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/LocalCache.java new file mode 100644 index 0000000..846f7cb --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/LocalCache.java @@ -0,0 +1,111 @@ +package me.ele.lancet.plugin.internal; + +import com.android.build.api.transform.Status; +import com.google.common.io.Files; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +import org.apache.commons.io.Charsets; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.List; +import java.util.stream.Stream; + +import me.ele.lancet.plugin.internal.preprocess.MetaGraphGeneratorImpl; +import me.ele.lancet.weaver.internal.graph.CheckFlow; +import me.ele.lancet.weaver.internal.graph.ClassEntity; + +/** + * Created by gengwanpeng on 17/4/26. + */ +public class LocalCache { + + // Persistent storage for metas + private File localCache; + private final Metas metas; + private Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + public LocalCache(File dir) { + localCache = new File(dir, "buildCache.json"); + metas = loadCache(); + } + + private Metas loadCache() { + if (localCache.exists() && localCache.isFile()) { + try { + Reader reader = Files.newReader(localCache, Charsets.UTF_8); + return gson.fromJson(reader, Metas.class).withoutNull(); + } catch (IOException e) { + throw new RuntimeException(e); + } catch (JsonParseException e) { + if (!localCache.delete()) { + throw new RuntimeException("cache file has been modified, but can't delete.", e); + } + } + } + return new Metas(); + } + + + public List hookClasses() { + return metas.hookClasses; + } + + public List hookClassesInDir() { + return metas.hookClassesInDir; + } + + public CheckFlow hookFlow() { + return metas.flow; + } + + + /** + * if hook class has modified. + * @param context TransformContext for this compile + * @return true if hook class hasn't modified. + */ + public boolean isHookClassModified(TransformContext context) { + List hookClasses = metas.jarsWithHookClasses; + return Stream.concat(context.getRemovedJars().stream(), context.getChangedJars().stream()) + .anyMatch(jarInput -> hookClasses.contains(jarInput.getFile().getAbsolutePath())); + } + + public void accept(MetaGraphGeneratorImpl graph) { + metas.classMetas.forEach(m -> graph.add(m, Status.NOTCHANGED)); + } + + public void saveToLocal() { + try { + Files.createParentDirs(localCache); + Writer writer = Files.newWriter(localCache, Charsets.UTF_8); + gson.toJson(metas.withoutNull(), Metas.class, writer); + writer.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void clear() throws IOException { + if (localCache.exists() && localCache.isFile() && !localCache.delete()) { + throw new IOException("can't delete cache file"); + } + } + + public void savePartially(List classMetas) { + metas.classMetas = classMetas; + saveToLocal(); + } + + public void saveFully(List classMetas, List hookClasses, List hookClassesInDir, List jarWithHookClasses) { + metas.classMetas = classMetas; + metas.hookClasses = hookClasses; + metas.hookClassesInDir = hookClassesInDir; + metas.jarsWithHookClasses = jarWithHookClasses; + saveToLocal(); + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/Metas.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/Metas.java new file mode 100644 index 0000000..b54236b --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/Metas.java @@ -0,0 +1,45 @@ +package me.ele.lancet.plugin.internal; + + +import java.util.Collections; +import java.util.List; + +import me.ele.lancet.weaver.internal.graph.CheckFlow; +import me.ele.lancet.weaver.internal.graph.ClassEntity; + +/** + * Created by gengwanpeng on 17/4/26. + */ +class Metas { + + public List hookClasses = Collections.emptyList(); + + public List hookClassesInDir = Collections.emptyList(); + + public List jarsWithHookClasses = Collections.emptyList(); + + public CheckFlow flow = new CheckFlow(); + + public List classMetas = Collections.emptyList(); + + + public Metas withoutNull() { + Metas shallowClone = new Metas(); + if (hookClasses != null) { + shallowClone.hookClasses = hookClasses; + } + if (hookClassesInDir != null) { + shallowClone.hookClassesInDir = hookClassesInDir; + } + if (jarsWithHookClasses != null) { + shallowClone.jarsWithHookClasses = jarsWithHookClasses; + } + if (classMetas != null) { + shallowClone.classMetas = classMetas; + } + if (flow != null) { + shallowClone.flow = flow; + } + return shallowClone; + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/TransformContext.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/TransformContext.java new file mode 100644 index 0000000..9480a85 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/TransformContext.java @@ -0,0 +1,139 @@ +package me.ele.lancet.plugin.internal; + +import com.android.build.api.transform.DirectoryInput; +import com.android.build.api.transform.Format; +import com.android.build.api.transform.JarInput; +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.TransformInvocation; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import me.ele.lancet.weaver.internal.graph.Graph; +import me.ele.lancet.weaver.internal.log.Log; + +/** + * Created by gengwanpeng on 17/4/26. + * + * A data sets collect all jar info and pre-analysis result. + * + */ +public class TransformContext { + + private TransformInvocation invocation; + + private Collection allJars; + private Collection addedJars; + private Collection removedJars; + private Collection changedJars; + private Collection allDirs; + + private GlobalContext global; + private List hookClasses; + private Graph graph; + + public TransformContext(TransformInvocation invocation, GlobalContext global) { + this.global = global; + this.invocation = invocation; + init(); + } + + /** + * start collect. + */ + private void init() { + allJars = new ArrayList<>(invocation.getInputs().size()); + addedJars = new ArrayList<>(invocation.getInputs().size()); + changedJars = new ArrayList<>(invocation.getInputs().size()); + removedJars = new ArrayList<>(invocation.getInputs().size()); + allDirs = new ArrayList<>(invocation.getInputs().size()); + invocation.getInputs().forEach(it -> { + Log.d(it.toString()); + it.getJarInputs().forEach(j -> { + allJars.add(j); + if (invocation.isIncremental()) { + switch (j.getStatus()) { + case ADDED: + addedJars.add(j); + break; + case REMOVED: + removedJars.add(j); + break; + case CHANGED: + changedJars.add(j); + } + } + }); + allDirs.addAll(it.getDirectoryInputs()); + }); + } + + + public boolean isIncremental() { + return invocation.isIncremental(); + } + + public Collection getAllJars() { + return Collections.unmodifiableCollection(allJars); + } + + public Collection getAllDirs() { + return Collections.unmodifiableCollection(allDirs); + } + + public Collection getAddedJars() { + return Collections.unmodifiableCollection(addedJars); + } + + public Collection getChangedJars() { + return Collections.unmodifiableCollection(changedJars); + } + + public Collection getRemovedJars() { + return Collections.unmodifiableCollection(removedJars); + } + + public File getRelativeFile(QualifiedContent content) { + return invocation.getOutputProvider().getContentLocation(content.getName(), content.getContentTypes(), content.getScopes(), + (content instanceof JarInput ? Format.JAR : Format.DIRECTORY)); + } + + public void clear() throws IOException { + invocation.getOutputProvider().deleteAll(); + } + + public GlobalContext getGlobal() { + return global; + } + + public void setHookClasses(List hookClasses) { + this.hookClasses = hookClasses; + } + + public List getHookClasses() { + return hookClasses; + } + + public Graph getGraph() { + return graph; + } + + public void setGraph(Graph graph) { + this.graph = graph; + } + + @Override + public String toString() { + return "TransformContext{" + + "allJars=" + allJars + + ", addedJars=" + addedJars + + ", removedJars=" + removedJars + + ", changedJars=" + changedJars + + ", allDirs=" + allDirs + + '}'; + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/TransformProcessor.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/TransformProcessor.java new file mode 100644 index 0000000..dc263be --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/TransformProcessor.java @@ -0,0 +1,129 @@ +package me.ele.lancet.plugin.internal; + +import com.android.build.api.transform.JarInput; +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.Status; +import com.android.utils.FileUtils; +import com.google.common.io.Files; + +import java.io.BufferedOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.jar.JarOutputStream; +import java.util.zip.ZipEntry; + +import me.ele.lancet.plugin.Util; +import me.ele.lancet.plugin.internal.context.ClassFetcher; +import me.ele.lancet.weaver.ClassData; +import me.ele.lancet.weaver.Weaver; +import me.ele.lancet.weaver.internal.log.Log; + +/** + * Created by gengwanpeng on 17/5/4. + */ +public class TransformProcessor implements ClassFetcher { + + private final TransformContext context; + private final Weaver weaver; + private final DirectoryRunner dirRunner = new DirectoryRunner(); + private Map map = new ConcurrentHashMap<>(); + + public TransformProcessor(TransformContext context, Weaver weaver) { + this.context = context; + this.weaver = weaver; + } + + @Override + public boolean onStart(QualifiedContent content) throws IOException { + if (content instanceof JarInput) { + JarInput jarInput = (JarInput) content; + File targetFile = context.getRelativeFile(content); + switch (jarInput.getStatus()) { + case REMOVED: + FileUtils.deleteIfExists(targetFile); + return false; + case CHANGED: + FileUtils.deleteIfExists(targetFile); + default: + Files.createParentDirs(targetFile); + map.put(content, new JarRunner(content, targetFile)); + } + } + return true; + } + + @Override + public void onClassFetch(QualifiedContent content, Status status, String relativePath, byte[] bytes) throws IOException { + if (content instanceof JarInput) { + JarRunner jarRunner = map.get(content); + jarRunner.run(relativePath, bytes); + } else { // directory, so must be class + File relativeRoot = context.getRelativeFile(content); + File target = Util.toSystemDependentFile(relativeRoot, relativePath); + File hookWithTarget = Util.toSystemDependentHookFile(relativeRoot, relativePath); + switch (status) { + case REMOVED: + FileUtils.deleteIfExists(target); + FileUtils.deleteIfExists(hookWithTarget); + break; + case CHANGED: + FileUtils.deleteIfExists(target); + FileUtils.deleteIfExists(hookWithTarget); + default: + dirRunner.run(relativeRoot, relativePath, bytes); + } + } + } + + @Override + public void onComplete(QualifiedContent content) throws IOException { + if (content instanceof JarInput && ((JarInput) content).getStatus() != Status.REMOVED) { + map.get(content).close(); + } + } + + class JarRunner implements Closeable { + + private final JarOutputStream jos; + private final QualifiedContent content; + + JarRunner(QualifiedContent content, File targetFile) throws IOException { + this.content = content; + this.jos = new JarOutputStream( + new BufferedOutputStream(new FileOutputStream(targetFile))); + } + + void run(String relativePath, byte[] bytes) throws IOException { + if (!relativePath.endsWith(".class")) { + ZipEntry entry = new ZipEntry(relativePath); + jos.putNextEntry(entry); + jos.write(bytes); + } else { + for (ClassData classData : weaver.weave(bytes, relativePath)) { + ZipEntry entry = new ZipEntry(classData.getClassName() + ".class"); + jos.putNextEntry(entry); + jos.write(classData.getClassBytes()); + } + } + } + + public void close() throws IOException { + jos.close(); + } + } + + class DirectoryRunner { + + void run(File relativeRoot, String relativePath, byte[] bytes) throws IOException { + for (ClassData data : weaver.weave(bytes, relativePath)) { + File target = Util.toSystemDependentFile(relativeRoot, data.getClassName() + ".class"); + Files.createParentDirs(target); + Files.write(data.getClassBytes(), target); + } + } + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ClassFetcher.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ClassFetcher.java new file mode 100644 index 0000000..52e729c --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ClassFetcher.java @@ -0,0 +1,37 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.Status; + +import java.io.IOException; + +/** + * The Fetcher to fetch each class in QualifiedContent + */ +public interface ClassFetcher { + + /** + * begin unzip a QualifiedContent. + * @param content the Jar or Dir QualifiedContent. + * @return whether the Fetcher can accept this QualifiedContent. + * @throws IOException + */ + boolean onStart(QualifiedContent content) throws IOException; + + /** + * fetch each class in QualifiedContent. each invoke will in one thread. + * @param content + * @param status + * @param relativePath + * @param bytes + * @throws IOException + */ + void onClassFetch(QualifiedContent content, Status status, String relativePath, byte[] bytes) throws IOException; + + /** + * has finished fetch class in this QualifiedContent + * @param content + * @throws IOException + */ + void onComplete(QualifiedContent content) throws IOException; +} \ No newline at end of file diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ClassifiedContentProvider.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ClassifiedContentProvider.java new file mode 100644 index 0000000..183c4c5 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ClassifiedContentProvider.java @@ -0,0 +1,33 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.QualifiedContent; + +import java.io.IOException; + +/** + * Created by gengwanpeng on 17/4/28. + * + * A QualifiedContentProvider proxy multiple ContentProviders. + * + */ +public class ClassifiedContentProvider implements QualifiedContentProvider { + + public static ClassifiedContentProvider newInstance(TargetedQualifiedContentProvider... providers) { + return new ClassifiedContentProvider(providers); + } + + private TargetedQualifiedContentProvider[] providers; + + private ClassifiedContentProvider(TargetedQualifiedContentProvider... providers) { + this.providers = providers; + } + + @Override + public void forEach(QualifiedContent content, ClassFetcher processor) throws IOException { + for (TargetedQualifiedContentProvider provider : providers) { + if(provider.accepted(content)){ + provider.forEach(content,processor); + } + } + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ContextReader.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ContextReader.java new file mode 100644 index 0000000..8d81574 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/ContextReader.java @@ -0,0 +1,135 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.JarInput; +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.Status; +import com.google.common.collect.ImmutableList; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import me.ele.lancet.plugin.internal.TransformContext; +import me.ele.lancet.plugin.internal.preprocess.ParseFailureException; +import me.ele.lancet.weaver.internal.log.Log; + +/** + * Created by gengwanpeng on 17/5/2. + * + * This class will unzip all jars,and accept all class with input ClassFetcher in thread pool. + * Used in pre-analysis and formal analysis. + * + */ +public class ContextReader { + + private AtomicBoolean lock = new AtomicBoolean(false); + private TransformContext context; + private ClassifiedContentProvider provider; + private ExecutorService service = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(), + 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(), (r, executor) -> { + Log.i("partial parse failed, executor has been shutdown"); + }); + + public ContextReader(TransformContext context) { + this.context = context; + } + + /** + * read the classes in thread pool and send class to fetcher. + * @param incremental is incremental compile + * @param fetcher the fetcher to visit classes + * @throws IOException + * @throws InterruptedException + */ + public void accept(boolean incremental, ClassFetcher fetcher) throws IOException, InterruptedException { + + provider = ClassifiedContentProvider.newInstance(new JarContentProvider(), new DirectoryContentProvider(incremental)); + // get all jars + Collection jars = !incremental ? context.getAllJars() : + ImmutableList.builder() + .addAll(context.getAddedJars()) + .addAll(context.getRemovedJars()) + .addAll(changedToDeleteAndAdd()) + .build(); + // accept the jar in thread pool + List> tasks = Stream.concat(jars.stream(), context.getAllDirs().stream()) + .map(q -> new QualifiedContentTask(q, fetcher)) + .map(t -> service.submit(t)) + .collect(Collectors.toList()); + + // block until all task has finish. + for (Future future : tasks) { + try { + future.get(); + } catch (ExecutionException e) { + if (incremental && e.getCause() instanceof ParseFailureException) { + shutDownAndRestart(); + continue; + } + Throwable cause = e.getCause(); + if (cause instanceof IOException) { + throw (IOException) cause; + } else if (cause instanceof InterruptedException) { + throw (InterruptedException) cause; + } else { + throw new RuntimeException(e.getCause()); + } + } + } + + } + + /** + * Transform the change operation to delete & add. + * @return + */ + private Collection changedToDeleteAndAdd(){ + List jarInputs = new ArrayList<>(); + context.getChangedJars().stream() + .peek(c -> jarInputs.add(new StatusOverrideJarInput(context,c, Status.REMOVED))) + .peek(c -> jarInputs.add(new StatusOverrideJarInput(context,c, Status.ADDED))); + return jarInputs; + } + + + + private void shutDownAndRestart() { + if (lock.compareAndSet(false, true)) { + service.shutdown(); + service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + } + } + + /** + * Task to accept target QualifiedContent + */ + private class QualifiedContentTask implements Callable { + + private QualifiedContent content; + private ClassFetcher fetcher; + + QualifiedContentTask(QualifiedContent content, ClassFetcher fetcher) { + this.content = content; + this.fetcher = fetcher; + } + + @Override + public Void call() throws Exception { + provider.forEach(content, fetcher); + return null; + } + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/DirectoryContentProvider.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/DirectoryContentProvider.java new file mode 100644 index 0000000..c5a21b4 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/DirectoryContentProvider.java @@ -0,0 +1,64 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.DirectoryInput; +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.Status; +import com.google.common.io.Files; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.Map; + +import me.ele.lancet.weaver.internal.log.Log; + +/** + * Created by gengwanpeng on 17/4/28. + */ +public class DirectoryContentProvider extends TargetedQualifiedContentProvider { + + private final boolean incremental; + + public DirectoryContentProvider(boolean incremental) { + this.incremental = incremental; + } + + @Override + public void forEach(QualifiedContent content, ClassFetcher processor) throws IOException { + if (processor.onStart(content)) { + File root = content.getFile(); + URI base = root.toURI(); + if (!incremental) { + /** + * if this compile is full compilation. we traverse all classes as newly added classes + */ + for (File f : Files.fileTreeTraverser().preOrderTraversal(root)) { + if (f.isFile() && f.getName().endsWith(".class")) { + byte[] data = Files.toByteArray(f); + String relativePath = base.relativize(f.toURI()).toString(); + processor.onClassFetch(content, Status.ADDED, relativePath, data); + } + } + } else { + /** + * if this compile is incremental compilation. we traverse all changed classes. + */ + for (Map.Entry entry : ((DirectoryInput) content).getChangedFiles().entrySet()) { + Log.d(entry.getKey() + " " + entry.getValue()); + File f = entry.getKey(); + if (f.isFile() && f.getName().endsWith(".class")) { + byte[] data = Files.toByteArray(f); + String relativePath = base.relativize(f.toURI()).toString(); + processor.onClassFetch(content, entry.getValue(), relativePath, data); + } + } + } + } + processor.onComplete(content); + } + + @Override + public boolean accepted(QualifiedContent qualifiedContent) { + return qualifiedContent instanceof DirectoryInput; + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/JarContentProvider.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/JarContentProvider.java new file mode 100644 index 0000000..ce82179 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/JarContentProvider.java @@ -0,0 +1,45 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.JarInput; +import com.android.build.api.transform.QualifiedContent; +import com.google.common.io.ByteStreams; + +import org.apache.commons.io.IOUtils; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * Created by gengwanpeng on 17/4/28. + */ +public class JarContentProvider extends TargetedQualifiedContentProvider { + + @Override + public void forEach(QualifiedContent content, ClassFetcher processor) throws IOException { + forActualInput((JarInput) content, processor); + } + + private void forActualInput(JarInput jarInput, ClassFetcher processor) throws IOException { + if (processor.onStart(jarInput)) { + ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(jarInput.getFile()))); + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.isDirectory()) { + continue; + } + byte[] data = ByteStreams.toByteArray(zis); + processor.onClassFetch(jarInput, jarInput.getStatus(), entry.getName(), data); + } + IOUtils.closeQuietly(zis); + } + processor.onComplete(jarInput); + } + + @Override + public boolean accepted(QualifiedContent qualifiedContent) { + return qualifiedContent instanceof JarInput; + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/QualifiedContentProvider.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/QualifiedContentProvider.java new file mode 100644 index 0000000..39d3795 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/QualifiedContentProvider.java @@ -0,0 +1,27 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.QualifiedContent; + +import java.io.IOException; + +/** + * Created by gengwanpeng on 17/4/28. + * + * Unzip QualifiedContent and provide single class for inout ClassFetcher. + * QualifiedContent may be one of {@link com.android.build.api.transform.JarInput} and {@link com.android.build.api.transform.DirectoryInput}. + * So there are tow child of QualifiedContentProvider {@link JarContentProvider} and {@link DirectoryContentProvider} + * + */ +public interface QualifiedContentProvider { + + /** + * start accept the classes + * @param content + * @param processor + * @throws IOException + */ + void forEach(QualifiedContent content, ClassFetcher processor) throws IOException; + + + +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/StatusOverrideJarInput.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/StatusOverrideJarInput.java new file mode 100644 index 0000000..845687e --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/StatusOverrideJarInput.java @@ -0,0 +1,53 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.JarInput; +import com.android.build.api.transform.Status; +import com.google.common.base.Charsets; +import com.google.common.hash.Hashing; + +import java.io.File; +import java.util.Set; + +import me.ele.lancet.plugin.internal.TransformContext; + +/** + * Created by Jude on 2017/7/14. + */ + +public class StatusOverrideJarInput implements JarInput { + private JarInput jarInput; + private File jar ; + private Status status; + + + public StatusOverrideJarInput(TransformContext context, JarInput jarInput,Status status) { + this.jarInput = jarInput; + this.jar = context.getRelativeFile(jarInput); + this.status = status; + } + + @Override + public Status getStatus() { + return status; + } + + @Override + public String getName() { + return Hashing.sha1().hashString(jar.getPath()+status, Charsets.UTF_16LE).toString(); + } + + @Override + public File getFile() { + return jar; + } + + @Override + public Set getContentTypes() { + return jarInput.getContentTypes(); + } + + @Override + public Set getScopes() { + return jarInput.getScopes(); + } +} \ No newline at end of file diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/TargetedQualifiedContentProvider.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/TargetedQualifiedContentProvider.java new file mode 100644 index 0000000..e5228b3 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/context/TargetedQualifiedContentProvider.java @@ -0,0 +1,18 @@ +package me.ele.lancet.plugin.internal.context; + +import com.android.build.api.transform.QualifiedContent; + +/** + * Created by gengwanpeng on 17/4/28. + * {@inheritDoc} + */ +public abstract class TargetedQualifiedContentProvider implements QualifiedContentProvider { + + /** + * Judge the QualifiedContent type + * @param qualifiedContent {@link com.android.build.api.transform.JarInput} or {@link com.android.build.api.transform.DirectoryInput} + * @return can this provider accept this QualifiedContent. + */ + public abstract boolean accepted(QualifiedContent qualifiedContent); + +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/AsmClassProcessorImpl.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/AsmClassProcessorImpl.java new file mode 100644 index 0000000..2d58383 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/AsmClassProcessorImpl.java @@ -0,0 +1,20 @@ +package me.ele.lancet.plugin.internal.preprocess; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.Opcodes; + +import java.io.IOException; + +/** + * Created by gengwanpeng on 17/4/27. + */ +public class AsmClassProcessorImpl implements PreClassProcessor { + + @Override + public PreClassProcessor.ProcessResult process(byte[] classBytes) { + ClassReader cr = new ClassReader(classBytes); + PreProcessClassVisitor cv = new PreProcessClassVisitor(Opcodes.ASM5); + cr.accept(cv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + return cv.getProcessResult(); + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/MetaGraphGeneratorImpl.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/MetaGraphGeneratorImpl.java new file mode 100644 index 0000000..f93f4c7 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/MetaGraphGeneratorImpl.java @@ -0,0 +1,78 @@ +package me.ele.lancet.plugin.internal.preprocess; + +import com.android.build.api.transform.Status; + +import org.objectweb.asm.Opcodes; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import me.ele.lancet.weaver.internal.graph.CheckFlow; +import me.ele.lancet.weaver.internal.graph.ClassEntity; +import me.ele.lancet.weaver.internal.graph.ClassNode; +import me.ele.lancet.weaver.internal.graph.Graph; +import me.ele.lancet.weaver.internal.graph.InterfaceNode; +import me.ele.lancet.weaver.internal.graph.MetaGraphGenerator; +import me.ele.lancet.weaver.internal.graph.Node; + +/** + * Created by gengwanpeng on 17/4/26. + */ +public class MetaGraphGeneratorImpl implements MetaGraphGenerator { + + private final CheckFlow checkFlow; + // Key is class name. value is class node. + private Map nodeMap = new ConcurrentHashMap<>(512); + private Graph graph; + + public MetaGraphGeneratorImpl(CheckFlow checkFlow) { + this.checkFlow = checkFlow; + } + + // thread safe + public void add(ClassEntity entity, Status status) { + Node current = getOrPutEmpty((entity.access & Opcodes.ACC_INTERFACE) != 0, entity.name); + + ClassNode superNode = null; + List interfaceNodes = Collections.emptyList(); + if (entity.superName != null) { + superNode = (ClassNode) getOrPutEmpty(false, entity.superName); + } + if (entity.interfaces.size() > 0) { + interfaceNodes = entity.interfaces.stream().map(i -> (InterfaceNode) getOrPutEmpty(true, i)).collect(Collectors.toList()); + } + + current.entity = entity; + current.parent = superNode; + current.status = status; + current.interfaces = interfaceNodes; + } + + public void remove(String className) { + nodeMap.remove(className); + } + + // find node by name, if node is not exist then create and add it. + private Node getOrPutEmpty(boolean isInterface, String className) { + return nodeMap.computeIfAbsent(className, n -> isInterface ? + new InterfaceNode(n) : + new ClassNode(n)); + } + + + List toLocalNodes() { + return nodeMap.values().stream().filter(it -> it.parent != null).map(it -> it.entity).collect(Collectors.toList()); + } + + @Override + public Graph generate() { + if (graph == null) { + graph = new Graph(nodeMap, checkFlow); + graph.prepare(); + } + return graph; + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/ParseFailureException.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/ParseFailureException.java new file mode 100644 index 0000000..c7aecd1 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/ParseFailureException.java @@ -0,0 +1,21 @@ +package me.ele.lancet.plugin.internal.preprocess; + +/** + * Created by gengwanpeng on 17/5/4. + */ +public class ParseFailureException extends RuntimeException { + public ParseFailureException() { + } + + public ParseFailureException(String message) { + super(message); + } + + public ParseFailureException(String message, Throwable cause) { + super(message, cause); + } + + public ParseFailureException(Throwable cause) { + super(cause); + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreClassAnalysis.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreClassAnalysis.java new file mode 100644 index 0000000..dba6436 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreClassAnalysis.java @@ -0,0 +1,160 @@ +package me.ele.lancet.plugin.internal.preprocess; + +import com.android.build.api.transform.JarInput; +import com.android.build.api.transform.QualifiedContent; +import com.android.build.api.transform.Status; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import me.ele.lancet.plugin.Util; +import me.ele.lancet.plugin.internal.LocalCache; +import me.ele.lancet.plugin.internal.TransformContext; +import me.ele.lancet.plugin.internal.context.ClassFetcher; +import me.ele.lancet.plugin.internal.context.ContextReader; +import me.ele.lancet.weaver.internal.log.Log; + +/** + * Created by gengwanpeng on 17/4/26. + * + * When you see this class you may be as happy as me like this: + * + * + * PreClassAnalysis mainly records the dependency graph of all classes, + * and record the hook classes to judge if incremental compile available in next time. + * + */ +public class PreClassAnalysis { + + private LocalCache cache; + private MetaGraphGeneratorImpl graph; + private PreClassProcessor classProcessor = new AsmClassProcessorImpl(); + + + private ContextReader contextReader; + + + private volatile boolean partial = true; + + public PreClassAnalysis(LocalCache cache) { + this.cache = cache; + this.graph = new MetaGraphGeneratorImpl(cache.hookFlow()); + } + + /** + * start pre-analysis, the only API for pre-analysis. + * this method will block until pre-analysis finish. + * + * @param incremental + * @param context + * @return is incremental compile mode + * @throws IOException + * @throws InterruptedException + */ + public boolean execute(boolean incremental, TransformContext context) throws IOException, InterruptedException { + Log.d(context.toString()); + long duration = System.currentTimeMillis(); + + contextReader = new ContextReader(context); + + if (incremental && context.isIncremental() && !cache.isHookClassModified(context)){ + // can use incremental + partial = true; + + saveData(partialParse(context), context); + } else { + // must full compile + partial = false; + + // clear LocalCache and TransformContext + cache.clear(); + context.clear(); + + saveData(fullyParse(context), context); + + duration = System.currentTimeMillis() - duration; + Log.tag("Timer").i("pre parse cost: " + duration); + } + return partial; + } + + private PreAnalysisClassFetcher partialParse(TransformContext context) throws IOException, InterruptedException { + PreAnalysisClassFetcher preAnalysisClassFetcher = new PreAnalysisClassFetcher(); + // load cached full data into graph. + cache.accept(graph); + contextReader.accept(true, preAnalysisClassFetcher); + return preAnalysisClassFetcher; + } + + private PreAnalysisClassFetcher fullyParse(TransformContext context) throws IOException, InterruptedException { + PreAnalysisClassFetcher preAnalysisClassFetcher = new PreAnalysisClassFetcher(); + contextReader.accept(false, preAnalysisClassFetcher); + return preAnalysisClassFetcher; + } + + private void saveData(PreAnalysisClassFetcher preAnalysisClassFetcher, TransformContext context) { + if (partial) { + cache.savePartially(graph.toLocalNodes()); + } else { + cache.saveFully(graph.toLocalNodes(), preAnalysisClassFetcher.hookClasses, preAnalysisClassFetcher.hookClassesInDir, new ArrayList<>(preAnalysisClassFetcher.jarPathOfHookClasses)); + } + + context.setGraph(graph.generate()); + context.setHookClasses(cache.hookClasses()); + } + + + /** + * ClassFetcher to fetch all changed classed in this compilation. + */ + private class PreAnalysisClassFetcher implements ClassFetcher { + + List hookClasses = new ArrayList<>(4); + List hookClassesInDir = new ArrayList<>(4); + Set jarPathOfHookClasses = new HashSet<>(); + + @Override + public boolean onStart(QualifiedContent content) { + return true; + } + + @Override + public void onClassFetch(QualifiedContent content, Status status, String relativePath, byte[] bytes) { + if (relativePath.endsWith(".class")) { + PreClassProcessor.ProcessResult result = classProcessor.process(bytes); + + // if this time is incremental, the hook class won't be fetched. + if (partial && result.isHookClass) { + partial = false; + throw new ParseFailureException(result.toString()); + } + + // store hook classes for next compile + if (result.isHookClass) { + synchronized (this) { + hookClasses.add(result.entity.name); + if (content instanceof JarInput) { + jarPathOfHookClasses.add(content.getFile().getAbsolutePath()); + } else { + hookClassesInDir.add(Util.toSystemDependentFile(content.getFile(), relativePath).getAbsolutePath()); + } + } + } + + // update the graph + if (status != Status.REMOVED) { + graph.add(result.entity, status); + } else { + graph.remove(result.entity.name); + } + } + } + + @Override + public void onComplete(QualifiedContent content) { + } + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreClassProcessor.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreClassProcessor.java new file mode 100644 index 0000000..0b8d794 --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreClassProcessor.java @@ -0,0 +1,32 @@ +package me.ele.lancet.plugin.internal.preprocess; + + +import me.ele.lancet.weaver.internal.graph.ClassEntity; + +/** + * Created by gengwanpeng on 17/4/27. + */ +public interface PreClassProcessor { + + ProcessResult process(byte[] classBytes); + + class ProcessResult { + + + public ProcessResult(boolean isHookClass, ClassEntity entity) { + this.isHookClass = isHookClass; + this.entity = entity; + } + + public boolean isHookClass; + public ClassEntity entity; + + @Override + public String toString() { + return "ProcessResult{" + + "isHookClass=" + isHookClass + + ", entity=" + entity + + '}'; + } + } +} diff --git a/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreProcessClassVisitor.java b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreProcessClassVisitor.java new file mode 100644 index 0000000..6c6f65b --- /dev/null +++ b/lancet-plugin/src/main/java/me/ele/lancet/plugin/internal/preprocess/PreProcessClassVisitor.java @@ -0,0 +1,65 @@ +package me.ele.lancet.plugin.internal.preprocess; + +import com.dieyidezui.lancet.rt.annotations.Insert; +import com.dieyidezui.lancet.rt.annotations.Proxy; +import com.dieyidezui.lancet.rt.annotations.TryCatchHandler; +import me.ele.lancet.weaver.internal.graph.ClassEntity; +import me.ele.lancet.weaver.internal.graph.FieldEntity; +import me.ele.lancet.weaver.internal.graph.MethodEntity; +import org.objectweb.asm.*; + +import java.util.Arrays; +import java.util.Collections; + +/** + * Created by gengwanpeng on 17/4/27. + */ +public class PreProcessClassVisitor extends ClassVisitor { + + private static final String PROXY = Type.getDescriptor(Proxy.class); + private static final String INSERT = Type.getDescriptor(Insert.class); + private static final String TRY_CATCH = Type.getDescriptor(TryCatchHandler.class); + + private boolean isHookClass; + private ClassEntity entity; + + PreProcessClassVisitor(int api) { + super(api, null); + } + + public PreClassProcessor.ProcessResult getProcessResult() { + return new PreClassProcessor.ProcessResult(isHookClass, entity); + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + entity = new ClassEntity(access, name, superName, interfaces == null ? Collections.emptyList() : Arrays.asList(interfaces)); + } + + @Override + public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { + entity.fields.add(new FieldEntity(access, name, desc)); + return null; + } + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + entity.methods.add(new MethodEntity(access, name, desc)); + if (!isHookClass) { + return new MethodVisitor(Opcodes.ASM5) { + @Override + public AnnotationVisitor visitAnnotation(String annoDesc, boolean visible) { + judge(annoDesc); + return null; + } + }; + } + return null; + } + + private void judge(String desc) { + if (!isHookClass && (INSERT.equals(desc) || PROXY.equals(desc) || TRY_CATCH.equals(desc))) { + isHookClass = true; + } + } +} diff --git a/lancet-plugin/src/main/resources/META-INF/gradle-plugins/me.ele.lancet.properties b/lancet-plugin/src/main/resources/META-INF/gradle-plugins/me.ele.lancet.properties new file mode 100644 index 0000000..a1e14d4 --- /dev/null +++ b/lancet-plugin/src/main/resources/META-INF/gradle-plugins/me.ele.lancet.properties @@ -0,0 +1 @@ +implementation-class=me.ele.lancet.plugin.LancetPlugin \ No newline at end of file diff --git a/lancet-weaver/.gitignore b/lancet-weaver/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/lancet-weaver/.gitignore @@ -0,0 +1 @@ +/build diff --git a/lancet-weaver/build.gradle b/lancet-weaver/build.gradle new file mode 100644 index 0000000..3697028 --- /dev/null +++ b/lancet-weaver/build.gradle @@ -0,0 +1,23 @@ +apply plugin: 'java' + +dependencies { + testCompile "junit:junit:4.12" + testCompile 'com.squareup.okio:okio:1.11.0' + testCompile 'org.assertj:assertj-core:3.6.2' + + compileClasspath "com.android.tools.build:gradle:$android_tools_version" + compile "me.ele:lancet-base:1.0.4" + compile gradleApi() + compileClasspath "com.google.guava:guava:$guava_version" + compile "org.ow2.asm:asm:$asm_version" + compile 'org.ow2.asm:asm-tree:7.0' + compile 'org.ow2.asm:asm-util:7.0' + compile 'org.ow2.asm:asm-commons:7.0' + compile 'org.ow2.asm:asm-analysis:7.0' + compile 'org.ow2.asm:asm-test:7.0' +} + +sourceCompatibility = "1.8" +targetCompatibility = "1.8" + + diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/ClassData.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/ClassData.java new file mode 100644 index 0000000..79ed2e0 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/ClassData.java @@ -0,0 +1,31 @@ +package me.ele.lancet.weaver; + +/** + * Created by Jude on 2017/4/25. + */ + +public class ClassData { + byte[] classBytes; + String className; + + public ClassData(byte[] classBytes, String className) { + this.classBytes = classBytes; + this.className = className; + } + + public byte[] getClassBytes() { + return classBytes; + } + + public void setClassBytes(byte[] classBytes) { + this.classBytes = classBytes; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/MetaParser.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/MetaParser.java new file mode 100644 index 0000000..f5f39c1 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/MetaParser.java @@ -0,0 +1,16 @@ +package me.ele.lancet.weaver; + +import java.util.List; + +import me.ele.lancet.weaver.internal.entity.TransformInfo; +import me.ele.lancet.weaver.internal.graph.Graph; + + +/** + * + * Created by gengwanpeng on 17/3/21. + */ +public interface MetaParser { + + TransformInfo parse(List classes, Graph graph); +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/Weaver.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/Weaver.java new file mode 100644 index 0000000..dacb93a --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/Weaver.java @@ -0,0 +1,18 @@ +package me.ele.lancet.weaver; + +/** + * Created by gengwanpeng on 17/3/21. + */ +public interface Weaver{ + + /** + * Transform input class with specified rules. + * Input one class may return two classes, because weaver may create multiple inner classes. + * this method will be invoke in multi-threaded and multi-process + * + * @param input the bytecode of the class want to transform. + * @param relativePath the file path of the class, end with .class, the new classes will output into the same path. + * @return the bytecode of transformed classes. + */ + ClassData[] weave(byte[] input, String relativePath); +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/AsmWeaver.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/AsmWeaver.java new file mode 100644 index 0000000..69409f6 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/AsmWeaver.java @@ -0,0 +1,53 @@ +package me.ele.lancet.weaver.internal; + +import me.ele.lancet.weaver.ClassData; +import me.ele.lancet.weaver.Weaver; +import me.ele.lancet.weaver.internal.asm.ClassTransform; +import me.ele.lancet.weaver.internal.entity.TransformInfo; +import me.ele.lancet.weaver.internal.graph.Graph; +import me.ele.lancet.weaver.internal.log.Log; + + +/** + * Created by gengwanpeng on 17/3/21. + */ +public class AsmWeaver implements Weaver { + + /** + * Create a AsmWeaver instance. In a compilation process, the AsmWeaver instance will only be created once. + * + * @param transformInfo the transformInfo for this compilation process. + * @param graph + * @return + */ + public static Weaver newInstance(TransformInfo transformInfo, Graph graph) { + return new AsmWeaver(transformInfo, graph); + } + + private final TransformInfo transformInfo; + private final Graph graph; + + private AsmWeaver(TransformInfo transformInfo, Graph graph) { + Log.d(transformInfo.toString()); + this.graph = graph; + this.transformInfo = transformInfo; + } + + /** + * {@inheritDoc} + */ + @Override + public ClassData[] weave(byte[] input, String relativePath) { + if(!relativePath.endsWith(".class")){ + throw new IllegalArgumentException("relativePath is not a class: " + relativePath); + } + String internalName = relativePath.substring(0, relativePath.lastIndexOf('.')); + try { + return ClassTransform.weave(transformInfo, graph, input, internalName); + }catch (RuntimeException e){ + Log.e("error in transform: " + relativePath, e); + return new ClassData[]{new ClassData(input, internalName)}; + } + } + +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassCollector.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassCollector.java new file mode 100644 index 0000000..ac03d22 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassCollector.java @@ -0,0 +1,83 @@ +package me.ele.lancet.weaver.internal.asm; + + +import me.ele.lancet.weaver.internal.graph.Graph; +import org.objectweb.asm.*; +import org.objectweb.asm.util.CheckClassAdapter; + +import java.util.HashMap; +import java.util.Map; + +import me.ele.lancet.weaver.ClassData; + +/** + * Created by Jude on 2017/4/25. + */ + +public class ClassCollector { + + // canonical name + String originClassName; + ClassWriter originClassWriter; + + ClassReader mClassReader; + Graph graph; + + // simple name of innerClass + Map mClassWriters = new HashMap<>(); + + public ClassCollector(ClassReader mClassReader, Graph graph) { + this.mClassReader = mClassReader; + this.graph = graph; + } + + void setOriginClassName(String originClassName) { + this.originClassName = originClassName; + } + + public ClassVisitor getOriginClassVisitor() { + if(originClassWriter ==null){ + originClassWriter = new ClassWriter(mClassReader, 0); + } + return originClassWriter; + } + + public ClassVisitor getInnerClassVisitor(String classSimpleName) { + ClassWriter writer = mClassWriters.get(classSimpleName); + if (writer == null) { + writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + initForWriter(writer, classSimpleName); + mClassWriters.put(classSimpleName, writer); + } + return writer; + } + + private void initForWriter(ClassVisitor visitor, String classSimpleName) { + visitor.visit(Opcodes.V1_7, Opcodes.ACC_SUPER, getCanonicalName(classSimpleName), null, "java/lang/Object", null); + MethodVisitor mv = visitor.visitMethod(Opcodes.ACC_PRIVATE, "", "()V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + } + + public ClassData[] generateClassBytes() { + for (String className : mClassWriters.keySet()) { + originClassWriter.visitInnerClass(getCanonicalName(className), originClassName, className, Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC); + } + ClassData[] classDataArray = new ClassData[mClassWriters.size() + 1]; + int index = 0; + for (Map.Entry entry : mClassWriters.entrySet()) { + classDataArray[index] = new ClassData(entry.getValue().toByteArray(), getCanonicalName(entry.getKey())); + index++; + } + classDataArray[index] = new ClassData(originClassWriter.toByteArray(), originClassName); + return classDataArray; + } + + public String getCanonicalName(String simpleName) { + return originClassName + "$" + simpleName; + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassContext.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassContext.java new file mode 100644 index 0000000..fd7f20f --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassContext.java @@ -0,0 +1,38 @@ +package me.ele.lancet.weaver.internal.asm; + +import me.ele.lancet.weaver.internal.graph.Graph; +import org.objectweb.asm.ClassVisitor; + +import java.util.BitSet; + +/** + * Created by gengwanpeng on 17/5/12. + */ +public class ClassContext { + + private final Graph graph; + private final MethodChain chain; + private final ClassVisitor tail; + + public String name; + public String superName; + + public ClassContext(Graph graph, MethodChain chain, ClassVisitor tail) { + this.graph = graph; + this.chain = chain; + this.tail = tail; + } + + public ClassVisitor getTail() { + return tail; + } + + public Graph getGraph() { + return graph; + } + + public MethodChain getChain() { + return chain; + } + +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassTransform.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassTransform.java new file mode 100644 index 0000000..6c12929 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/ClassTransform.java @@ -0,0 +1,63 @@ +package me.ele.lancet.weaver.internal.asm; + +import org.objectweb.asm.ClassReader; + +import me.ele.lancet.weaver.ClassData; +import me.ele.lancet.weaver.internal.asm.classvisitor.HookClassVisitor; +import me.ele.lancet.weaver.internal.asm.classvisitor.InsertClassVisitor; +import me.ele.lancet.weaver.internal.asm.classvisitor.ProxyClassVisitor; +import me.ele.lancet.weaver.internal.asm.classvisitor.TryCatchInfoClassVisitor; +import me.ele.lancet.weaver.internal.entity.TransformInfo; +import me.ele.lancet.weaver.internal.graph.Graph; + +/** + * Created by Jude on 2017/4/25. + */ + +public class ClassTransform { + + public static final String AID_INNER_CLASS_NAME = "_lancet"; + + public static ClassData[] weave(TransformInfo transformInfo, Graph graph, byte[] classByte, String internalName) { + ClassCollector classCollector = new ClassCollector(new ClassReader(classByte), graph); + + classCollector.setOriginClassName(internalName); + + MethodChain chain = new MethodChain(internalName, classCollector.getOriginClassVisitor(), graph); + ClassContext context = new ClassContext(graph, chain, classCollector.getOriginClassVisitor()); + + ClassTransform transform = new ClassTransform(classCollector, context); + transform.connect(new HookClassVisitor(transformInfo.hookClasses)); + transform.connect(new ProxyClassVisitor(transformInfo.proxyInfo)); + transform.connect(new InsertClassVisitor(transformInfo.executeInfo)); + transform.connect(new TryCatchInfoClassVisitor(transformInfo.tryCatchInfo)); + transform.startTransform(); + return classCollector.generateClassBytes(); + } + + private LinkedClassVisitor mHeadVisitor; + private LinkedClassVisitor mTailVisitor; + private ClassCollector mClassCollector; + private final ClassContext context; + + public ClassTransform(ClassCollector mClassCollector, ClassContext context) { + this.mClassCollector = mClassCollector; + this.context = context; + } + + void connect(LinkedClassVisitor visitor) { + if (mHeadVisitor == null) { + mHeadVisitor = visitor; + } else { + mTailVisitor.setNextClassVisitor(visitor); + } + mTailVisitor = visitor; + visitor.setClassCollector(mClassCollector); + visitor.setContext(context); + } + + void startTransform() { + mTailVisitor.setNextClassVisitor(mClassCollector.getOriginClassVisitor()); + mClassCollector.mClassReader.accept(mHeadVisitor, 0); + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/LinkedClassVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/LinkedClassVisitor.java new file mode 100644 index 0000000..55553f1 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/LinkedClassVisitor.java @@ -0,0 +1,45 @@ +package me.ele.lancet.weaver.internal.asm; + +import me.ele.lancet.weaver.internal.graph.Graph; +import me.ele.lancet.weaver.internal.util.Bitset; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Created by Jude on 2017/4/25. + */ + +public class LinkedClassVisitor extends ClassVisitor { + + + private ClassContext context; + private ClassCollector mClassCollector; + + + public LinkedClassVisitor() { + super(Opcodes.ASM5); + } + + public void setContext(ClassContext context) { + this.context = context; + } + + void setClassCollector(ClassCollector classCollector) { + this.mClassCollector = classCollector; + } + + public ClassContext getContext() { + return context; + } + + protected ClassCollector getClassCollector() { + return mClassCollector; + } + + public void setNextClassVisitor(ClassVisitor classVisitor) { + cv = classVisitor; + } + + +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/MethodChain.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/MethodChain.java new file mode 100644 index 0000000..d5c80c0 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/MethodChain.java @@ -0,0 +1,296 @@ +package me.ele.lancet.weaver.internal.asm; + +import com.google.common.base.Preconditions; +import com.dieyidezui.lancet.rt.annotations.ClassOf; +import me.ele.lancet.weaver.internal.asm.classvisitor.methodvisitor.AutoUnboxMethodVisitor; +import me.ele.lancet.weaver.internal.graph.ClassEntity; +import me.ele.lancet.weaver.internal.graph.FieldEntity; +import me.ele.lancet.weaver.internal.graph.Graph; +import me.ele.lancet.weaver.internal.log.Log; +import me.ele.lancet.weaver.internal.parser.AopMethodAdjuster; +import me.ele.lancet.weaver.internal.util.Bitset; +import me.ele.lancet.weaver.internal.util.PrimitiveUtil; +import me.ele.lancet.weaver.internal.util.TypeUtil; +import org.objectweb.asm.*; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Collectors; + + +/** + * Created by gengwanpeng on 17/5/9. + */ +public class MethodChain { + + private static final String ACCESS = "access$"; + private static final String FORMAT = "access$%03d"; + private static final String CLASS_OF = Type.getDescriptor(ClassOf.class); + + private final String className; + private final ClassVisitor base; + private final Graph graph; + private Bitset bitset; + + private Invoker head; + + private Map fieldMap; + private Map invokerMap = new HashMap<>(); + + + public MethodChain(String className, ClassVisitor base, Graph graph) { + this.className = className; + this.base = base; + this.graph = graph; + this.bitset = new Bitset(); + this.bitset.setInitializer(b -> { + int len = ACCESS.length(); + ClassEntity entity = graph.get(className).entity; + entity.methods.forEach(m -> { + if (TypeUtil.isStatic(m.access) && m.name.startsWith(ACCESS)) { + bitset.tryAdd(m.name, len); + } + }); + }); + } + + private void head(int access, int opcode, String owner, String name, String desc) { + this.head = Invoker.forMethod( + new MethodInsnNode(opcode, owner, name, desc, opcode == Opcodes.INVOKEINTERFACE) + , !hasPermission(access, owner), className); + } + + private boolean hasPermission(int access, String owner) { + return TypeUtil.isPublic(access) || !TypeUtil.isPrivate(access) && owner.equals(className); + } + + public void headFromProxy(int opcode, String owner, String name, String desc) { + int access = Opcodes.ACC_PRIVATE; + if (opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) { + access = Opcodes.ACC_PUBLIC; + } + head(access, opcode, owner, name, desc); + } + + public void headFromInsert(int access, String owner, String name, String desc) { + head(access, TypeUtil.isStatic(access) ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, owner, name, desc); + } + + + public void next(String className, int access, String name, String desc, MethodNode node, ClassVisitor cv) { + String[] exs = (String[]) node.exceptions.toArray(new String[0]); + head.createIfNeed(base, bitset, exs); + + MethodVisitor mv = cv.visitMethod(access, name, desc, null, exs); + node.accept(new MethodVisitor(Opcodes.ASM5, new AutoUnboxMethodVisitor(mv)) { + + @Override + public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { + if (opcode == AopMethodAdjuster.OP_CALL) { + head.loadArgsAndInvoke(mv); + } else if (opcode == AopMethodAdjuster.OP_THIS_GET_FIELD) { + dealField(Opcodes.GETFIELD, name, mv); + } else if (opcode == AopMethodAdjuster.OP_THIS_PUT_FIELD) { + dealField(Opcodes.PUTFIELD, name, mv); + } else { + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + } + + @Override + public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { + if (CLASS_OF.equals(desc)) { + return null; + } + return super.visitParameterAnnotation(parameter, desc, visible); + } + + }); + + headFromInsert(access, className, name, desc); + } + + private void dealField(int opcode, String name, MethodVisitor mv) { + initFields(); + + // always store in object, auto box and unbox. + final String obj = "Ljava/lang/Object;"; + + FieldEntity entity = fieldMap.get(name); + if (entity == null) { + base.visitField(Opcodes.ACC_PRIVATE, name, obj, null, null); + fieldMap.put(name, entity = new FieldEntity(Opcodes.ACC_PRIVATE, name, obj)); + } + + boolean needCreate = TypeUtil.isPrivate(entity.access); + String desc = entity.desc; + + invokerMap.computeIfAbsent(opcode + " " + name, + k -> { + Invoker invoker = Invoker.forField(new FieldInsnNode(opcode, className, name, desc), needCreate, className); + invoker.createIfNeed(base, bitset, null); + return invoker; + }) + .loadArgsAndInvoke(mv); + + } + + private void initFields() { + if (fieldMap == null) { + this.fieldMap = graph.get(className).entity.fields.stream() + .collect(Collectors.toMap(f -> f.name, f -> f)); + } + } + + public void fakePreMethod(String className, int access, String name, String desc, String signature, String[] exceptions) { + MethodVisitor mv = base.visitMethod(access, name, desc, null, exceptions); + + createMethod(access, desc, head.action()).accept(mv); + + headFromInsert(access, className, name, desc); + } + + public Invoker getHead(){ + return head; + } + + public void visitHead(MethodVisitor mv) { + head.invoke(mv); + } + + public static class Invoker implements Opcodes { + + public static Invoker forField(FieldInsnNode fn, boolean needCreate, String className) { + String staticDesc = staticDesc(className, null, Preconditions.checkNotNull(fn)); + return new Invoker(null, fn, needCreate, staticDesc, className); + } + + public static Invoker forMethod(MethodInsnNode mn, boolean needCreate, String className) { + String staticDesc = staticDesc(mn.owner, Preconditions.checkNotNull(mn), null); + return new Invoker(mn, null, needCreate, staticDesc, className); + } + + private static String staticDesc(String className, MethodInsnNode mn, FieldInsnNode fn) { + String desc = mn != null ? + mn.desc : + (fn.getOpcode() == PUTFIELD ? + '(' + fn.desc + ")V" : "()" + fn.desc); + int access = mn != null && mn.getOpcode() == INVOKESTATIC ? ACC_STATIC : 0; + return TypeUtil.descToStatic(access, desc, className); + } + + final MethodInsnNode mn; + final FieldInsnNode fn; + + final String staticDesc; + final String owner; + final boolean needCreate; + + MethodInsnNode syntheticNode; + + Invoker(MethodInsnNode mn, FieldInsnNode fn, boolean needCreate, String staticDesc, String owner) { + this.mn = mn; + this.fn = fn; + this.needCreate = needCreate; + this.staticDesc = staticDesc; + this.owner = owner; + } + + public void createIfNeed(ClassVisitor cv, Bitset bitset, String[] exceptions) { + if (syntheticNode != null) { + throw new IllegalStateException("can't create more than once"); + } + if (needCreate) { + String name = String.format(FORMAT, bitset.consume()); + + syntheticNode = new MethodInsnNode(INVOKESTATIC, owner, name, staticDesc, false); + Log.tag("transform").i("create synthetic node :" + owner + " " + name + " " + staticDesc); + + MethodVisitor mv = cv.visitMethod(ACC_STATIC | ACC_SYNTHETIC, name, staticDesc, null, exceptions); + + createMethod(ACC_STATIC, staticDesc, mn == null ? fn : mn) + .accept(mv); + } + } + + public void invoke(MethodVisitor mv) { + action().accept(mv); + } + + public void loadArgsAndInvoke(MethodVisitor mv) { + //load args + if (mn != null) { + Type[] params = Type.getArgumentTypes(staticDesc); + int index = 0; + for (Type t : params) { + mv.visitVarInsn(t.getOpcode(ILOAD), index); + index += t.getSize(); + } + invoke(mv); + } else { + if (fn.getOpcode() == PUTFIELD) { // unbox + mv.visitVarInsn(ALOAD, 0); + mv.visitInsn(SWAP); + if (PrimitiveUtil.isPrimitive(fn.desc)) { + String owner = PrimitiveUtil.box(fn.desc); + mv.visitMethodInsn(INVOKEVIRTUAL, PrimitiveUtil.virtualType(owner), + PrimitiveUtil.unboxMethod(owner), "()" + fn.desc, false); + } + invoke(mv); + } else { // box + mv.visitVarInsn(ALOAD, 0); + invoke(mv); + if (PrimitiveUtil.isPrimitive(fn.desc)) { + String owner = PrimitiveUtil.box(fn.desc); + mv.visitMethodInsn(INVOKESTATIC, owner, + "valueOf", "(" + fn.desc + ")L" + owner + ";", false); + ((AutoUnboxMethodVisitor) mv).markBoxed(); + } + } + } + } + + public AbstractInsnNode action() { + if (syntheticNode != null) { + return syntheticNode; + } else if (mn != null) { + return mn; + } else { + return fn; + } + } + } + + private static Consumer createMethod(int access, String desc, AbstractInsnNode action) { + return mv -> { + mv.visitCode(); + + //load args + Type[] params = Type.getArgumentTypes(desc); + int index = 0; + if (!TypeUtil.isStatic(access)) { + index++; + mv.visitVarInsn(Opcodes.ALOAD, 0); + } + + for (Type t : params) { + mv.visitVarInsn(t.getOpcode(Opcodes.ILOAD), index); + index += t.getSize(); + } + // action + action.accept(mv); + + // ret + Type ret = Type.getReturnType(desc); + mv.visitInsn(ret.getOpcode(Opcodes.IRETURN)); + + mv.visitMaxs(Math.max(index, ret.getSize()), index); + mv.visitEnd(); + }; + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/HookClassVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/HookClassVisitor.java new file mode 100644 index 0000000..209ce2a --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/HookClassVisitor.java @@ -0,0 +1,42 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor; + +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.Set; + +import me.ele.lancet.weaver.internal.asm.LinkedClassVisitor; +import me.ele.lancet.weaver.internal.util.TypeUtil; + +/** + * Created by gengwanpeng on 17/5/15. + */ +public class HookClassVisitor extends LinkedClassVisitor { + + private final Set excludes; + private boolean matched; + + public HookClassVisitor(Set excludes) { + this.excludes = excludes; + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + getContext().name = name; + getContext().superName = superName; + if (excludes.contains(name)) { + matched = true; + this.cv = getContext().getTail(); // make delegate point to the tail, ignore middle transform + } + super.visit(version, access, name, signature, superName, interfaces); + } + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + if (matched){ + return super.visitMethod(TypeUtil.resetAccessScope(access,Opcodes.ACC_PUBLIC), name, desc, signature, exceptions); + }else { + return super.visitMethod(access, name, desc, signature, exceptions); + } + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/InsertClassVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/InsertClassVisitor.java new file mode 100644 index 0000000..ac6f095 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/InsertClassVisitor.java @@ -0,0 +1,102 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor; + +import me.ele.lancet.weaver.internal.asm.MethodChain; +import org.objectweb.asm.*; +import org.objectweb.asm.commons.GeneratorAdapter; + +import java.util.*; +import java.util.stream.Collectors; + +import me.ele.lancet.weaver.internal.asm.ClassTransform; +import me.ele.lancet.weaver.internal.asm.LinkedClassVisitor; +import me.ele.lancet.weaver.internal.entity.InsertInfo; +import me.ele.lancet.weaver.internal.log.Log; +import me.ele.lancet.weaver.internal.util.TypeUtil; + +/** + * Created by gengwanpeng on 17/3/27. + */ +public class InsertClassVisitor extends LinkedClassVisitor { + + private Map> executeInfos; + private List matched; + + + public InsertClassVisitor(Map> executeInfos) { + this.executeInfos = executeInfos; + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + super.visit(version, access, name, signature, superName, interfaces); + matched = executeInfos.get(getContext().name); + } + + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + if (matched != null) { + List methodsMatched = new ArrayList<>(matched.size() >> 1); + matched.removeIf(e -> { + if (e.targetMethod.equals(name) && e.targetDesc.equals(desc)) { + if (((e.sourceMethod.access ^ access) & Opcodes.ACC_STATIC) != 0) { + throw new IllegalStateException(e.sourceClass + "." + e.sourceMethod.name + " should have the same static flag with " + + getContext().name + "." + name); + } + methodsMatched.add(e); + return true; + } + return false; + }); + + if (methodsMatched.size() > 0 && (access & (Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT)) == 0) { + Log.tag("transform").i("visit Insert method: " + getContext().name + "." + name + " " + desc); + + String staticDesc = TypeUtil.descToStatic(access, desc, getContext().name); + ClassVisitor cv = getClassCollector().getInnerClassVisitor(ClassTransform.AID_INNER_CLASS_NAME); + String owner = getClassCollector().getCanonicalName(ClassTransform.AID_INNER_CLASS_NAME); + String newName = name + "$___twin___"; + int newAccess = (access & ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC)) | Opcodes.ACC_PRIVATE; + + MethodChain chain = getContext().getChain(); + chain.headFromInsert(newAccess, getContext().name, newName, desc); + + methodsMatched.forEach(e -> { + Log.tag("transform").i( + " from " + e.sourceClass + "." + e.sourceMethod.name); + String methodName = e.sourceClass.replace("/", "_") + "_" + e.sourceMethod.name; + chain.next(owner, Opcodes.ACC_STATIC, methodName, staticDesc, e.threadLocalNode(), cv); + }); + chain.fakePreMethod(getContext().name, access, name, desc, signature, exceptions); + + return super.visitMethod(newAccess, newName, desc, signature, exceptions); + } + } + return super.visitMethod(access, name, desc, signature, exceptions); + } + + @Override + public void visitEnd() { + if (matched != null && matched.size() > 0) { + new ArrayList<>(matched).stream() + .collect(Collectors.groupingBy(e -> e.targetMethod)).forEach((k, v) -> { + if (v.stream().anyMatch(e -> e.createSuper)) { + InsertInfo e = v.get(0); + MethodVisitor mv = visitMethod(e.sourceMethod.access, e.targetMethod, e.targetDesc, e.sourceMethod.signature, + (String[]) e.sourceMethod.exceptions.toArray(new String[0])); + GeneratorAdapter adapter = new GeneratorAdapter(mv, e.sourceMethod.access, e.targetMethod, e.targetDesc); + adapter.visitCode(); + adapter.loadThis(); + adapter.loadArgs(); + adapter.visitMethodInsn(Opcodes.INVOKESPECIAL, getContext().superName, e.targetMethod, e.targetDesc, false); + adapter.returnValue(); + int sz = Type.getArgumentsAndReturnSizes(e.targetDesc); + adapter.visitMaxs(Math.max(sz >> 2, sz & 3), sz >> 2); + adapter.visitEnd(); + } + }); + + } + super.visitEnd(); + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/ProxyClassVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/ProxyClassVisitor.java new file mode 100644 index 0000000..d44a44c --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/ProxyClassVisitor.java @@ -0,0 +1,44 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor; + +import me.ele.lancet.weaver.internal.asm.MethodChain; +import org.objectweb.asm.MethodVisitor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import me.ele.lancet.weaver.internal.asm.LinkedClassVisitor; +import me.ele.lancet.weaver.internal.asm.classvisitor.methodvisitor.ProxyMethodVisitor; +import me.ele.lancet.weaver.internal.entity.ProxyInfo; + +/** + * Created by Jude on 17/4/26. + */ +public class ProxyClassVisitor extends LinkedClassVisitor { + + private List infos; + private Map> matches; + private Map maps = new HashMap<>(); + public ProxyClassVisitor(List infos) { + this.infos = infos; + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + matches = infos.stream() + .filter(t -> t.match(name)) + .collect(Collectors.groupingBy(t -> t.targetClass + " " + t.targetMethod + " " + t.targetDesc)); + + super.visit(version, access, name, signature, superName, interfaces); + } + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + if (matches.size() > 0) { + mv = new ProxyMethodVisitor(getContext().getChain(), mv, maps, matches, getContext().name, name, getClassCollector()); + } + return mv; + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/TryCatchInfoClassVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/TryCatchInfoClassVisitor.java new file mode 100644 index 0000000..9c51a39 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/TryCatchInfoClassVisitor.java @@ -0,0 +1,47 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor; + +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.List; +import java.util.stream.Collectors; + +import me.ele.lancet.weaver.internal.asm.LinkedClassVisitor; +import me.ele.lancet.weaver.internal.asm.classvisitor.methodvisitor.TryCatchMethodVisitor; +import me.ele.lancet.weaver.internal.entity.TryCatchInfo; +import me.ele.lancet.weaver.internal.log.Log; + + +/** + * Created by gengwanpeng on 17/3/27. + */ +public class TryCatchInfoClassVisitor extends LinkedClassVisitor { + + private String className; + private List infos; + private List matches = null; + + + public TryCatchInfoClassVisitor(List infos) { + this.infos = infos; + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + className = name; + if (infos != null){ + matches = infos.stream().filter(t -> t.match(name)).collect(Collectors.toList()); + } + super.visit(version, access, name, signature, superName, interfaces); + } + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + if (matches != null && matches.size() > 0) { + Log.tag("transform").i("visit TryCatch method: "+className+"."+name+" "+desc); + mv = new TryCatchMethodVisitor(Opcodes.ASM5, mv, matches); + } + return mv; + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/AutoUnboxMethodVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/AutoUnboxMethodVisitor.java new file mode 100644 index 0000000..d7f60fa --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/AutoUnboxMethodVisitor.java @@ -0,0 +1,128 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor.methodvisitor; + + +import me.ele.lancet.weaver.internal.util.PrimitiveUtil; +import org.objectweb.asm.*; + +/** + * Created by gengwanpeng on 17/5/31. + */ +public class AutoUnboxMethodVisitor extends MethodVisitor { + + private boolean flag = false; + private String lastOwner; + + public AutoUnboxMethodVisitor(MethodVisitor methodVisitor) { + super(Opcodes.ASM5, methodVisitor); + } + + public void markBoxed() { + flag = true; + } + + @Override + public void visitInsn(int opcode) { + clearFlag(); + super.visitInsn(opcode); + } + + private void clearFlag() { + flag = false; + } + + @Override + public void visitIntInsn(int opcode, int operand) { + clearFlag(); + super.visitIntInsn(opcode, operand); + } + + @Override + public void visitVarInsn(int opcode, int var) { + clearFlag(); + super.visitVarInsn(opcode, var); + } + + @Override + public void visitTypeInsn(int opcode, String type) { + if (flag) { + if (opcode == Opcodes.CHECKCAST && !type.equals(lastOwner) && PrimitiveUtil.boxedNumberTypes().contains(type)) { + if (lastOwner == null || !PrimitiveUtil.boxedNumberTypes().contains(lastOwner)) { + throw new IllegalStateException("can't cast bool or char to number"); + } + String method = PrimitiveUtil.unboxMethod(type); + String primitive = PrimitiveUtil.unbox(type); + super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Number", method, "()" + primitive, false); + super.visitMethodInsn(Opcodes.INVOKESTATIC, type, "valueOf", "(" + primitive + ")L" + type + ";", false); + } + } + clearFlag(); + super.visitTypeInsn(opcode, type); + } + + @Override + public void visitFieldInsn(int opcode, String owner, String name, String desc) { + clearFlag(); + super.visitFieldInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(int opcode, String owner, String name, String desc) { + clearFlag(); + super.visitMethodInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { + this.lastOwner = owner; + clearFlag(); + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + + @Override + public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { + clearFlag(); + super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); + } + + @Override + public void visitJumpInsn(int opcode, Label label) { + clearFlag(); + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitLdcInsn(Object cst) { + clearFlag(); + super.visitLdcInsn(cst); + } + + @Override + public void visitIincInsn(int var, int increment) { + clearFlag(); + super.visitIincInsn(var, increment); + } + + @Override + public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { + clearFlag(); + super.visitTableSwitchInsn(min, max, dflt, labels); + } + + @Override + public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { + clearFlag(); + super.visitLookupSwitchInsn(dflt, keys, labels); + } + + @Override + public void visitMultiANewArrayInsn(String desc, int dims) { + clearFlag(); + super.visitMultiANewArrayInsn(desc, dims); + } + + @Override + public void visitEnd() { + clearFlag(); + super.visitEnd(); + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/ProxyMethodVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/ProxyMethodVisitor.java new file mode 100644 index 0000000..d64e4b7 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/ProxyMethodVisitor.java @@ -0,0 +1,76 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor.methodvisitor; + +import me.ele.lancet.weaver.internal.asm.MethodChain; +import me.ele.lancet.weaver.internal.util.TypeUtil; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.List; +import java.util.Map; + +import me.ele.lancet.weaver.internal.asm.ClassCollector; +import me.ele.lancet.weaver.internal.asm.ClassTransform; +import me.ele.lancet.weaver.internal.entity.ProxyInfo; +import me.ele.lancet.weaver.internal.log.Log; + +/** + * Created by Jude on 17/4/26. + */ +public class ProxyMethodVisitor extends MethodVisitor { + + private final Map invokerMap; + private final Map> matchMap; + private final String className; + private final String name; + private final ClassCollector classCollector; + private final MethodChain chain; + + public ProxyMethodVisitor(MethodChain chain, MethodVisitor mv, Map invokerMap, Map> matchMap, String className, String name, ClassCollector classCollector) { + super(Opcodes.ASM5, mv); + this.chain = chain; + this.invokerMap = invokerMap; + this.matchMap = matchMap; + this.className = className; + this.name = name; + this.classCollector = classCollector; + } + + @Override + public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { + String key = owner + " " + name + " " + desc; + List infos = matchMap.get(key); + MethodChain.Invoker invoker = invokerMap.get(key); + if (invoker != null) { + invoker.invoke(mv); + } else if (infos != null && infos.size() > 0) { + + String staticDesc = TypeUtil.descToStatic(opcode == Opcodes.INVOKESTATIC ? Opcodes.ACC_STATIC : 0, desc, owner); + // begin hook this code. + chain.headFromProxy(opcode, owner, name, desc); + + String artificialClassname = classCollector.getCanonicalName(ClassTransform.AID_INNER_CLASS_NAME); + ClassVisitor cv = classCollector.getInnerClassVisitor(ClassTransform.AID_INNER_CLASS_NAME); + + Log.tag("transform").i("start weave Call method " + " for " + owner + "." + name + desc + + " in " + className + "." + this.name); + + infos.forEach(c -> { + if (TypeUtil.isStatic(c.sourceMethod.access) != (opcode == Opcodes.INVOKESTATIC)) { + throw new IllegalStateException(c.sourceClass + "." + c.sourceMethod.name + " should have the same " + + "static flag with " + owner + "." + name); + } + Log.tag("transform").i( + " from " + c.sourceClass + "." + c.sourceMethod.name); + + String methodName = c.sourceClass.replace("/", "_") + "_" + c.sourceMethod.name; + chain.next(artificialClassname, Opcodes.ACC_STATIC, methodName, staticDesc, c.threadLocalNode(), cv); + }); + + invokerMap.put(key, chain.getHead()); + chain.getHead().invoke(mv); + } else { + super.visitMethodInsn(opcode, owner, name, desc, itf); + } + } +} diff --git a/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/TryCatchMethodVisitor.java b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/TryCatchMethodVisitor.java new file mode 100644 index 0000000..71a1641 --- /dev/null +++ b/lancet-weaver/src/main/java/me/ele/lancet/weaver/internal/asm/classvisitor/methodvisitor/TryCatchMethodVisitor.java @@ -0,0 +1,42 @@ +package me.ele.lancet.weaver.internal.asm.classvisitor.methodvisitor; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import me.ele.lancet.weaver.internal.entity.TryCatchInfo; + + +/** + * Created by gengwanpeng on 17/3/31. + */ +public class TryCatchMethodVisitor extends MethodVisitor { + + private Set