├── .gitignore
├── LICENSE.txt
├── README.md
├── annotations
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── java
│ └── net
│ └── grandcentrix
│ └── gradle
│ └── logalot
│ └── annotations
│ └── LogALot.kt
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── debug
│ ├── AndroidManifest.xml
│ └── java
│ │ └── net
│ │ └── grandcentrix
│ │ └── logalot
│ │ └── DebugApp.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── net
│ │ │ └── grandcentrix
│ │ │ └── logalot
│ │ │ └── MainActivity.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── net
│ └── grandcentrix
│ └── logalot
│ └── MainActivityTest.kt
├── build.gradle
├── buildSrc
├── build.gradle.kts
└── src
│ ├── main
│ └── java
│ │ └── net
│ │ └── grandcentrix
│ │ └── gradle
│ │ └── logalot
│ │ ├── LogALotPlugin.kt
│ │ └── LogALotTransformer.kt
│ └── test
│ └── java
│ └── net
│ └── grandcentrix
│ └── gradle
│ └── logalot
│ ├── LogALotPluginTest.kt
│ └── LogALotTransformerTest.kt
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── runtime
├── .gitignore
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── net
│ └── grandcentrix
│ └── gradle
│ └── logalot
│ └── runtime
│ └── LogALotRuntime.kt
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches/build_file_checksums.ser
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | .DS_Store
9 | /build
10 | /captures
11 | .externalNativeBuild
12 | .idea
13 | build
14 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2018 grandcentrix GmbH
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Using the Transform API for byte code manipulation
2 |
3 | # Introduction
4 |
5 | The [Transform API](http://tools.android.com/tech-docs/new-build-system/transform-api) is part of the Android build system since version 1.5 and allows you to hook into the build to modify code and Java resources.
6 |
7 | Here I use it to emit logs for methods/functions and access to fields annotated with a custom annotation.
8 |
9 | # Resources
10 |
11 | - http://tools.android.com/tech-docs/new-build-system/transform-api
12 | - http://www.javassist.org
13 |
14 | # How the Transform API generally works
15 |
16 | First you need to register your transformation to have it executed during the build.
17 |
18 | The only problem I encountered was the fact that the examples I was able to find are written in Groovy and use older versions of the Transform API.
19 | It took me some time to realize that `project.android.registerTransform(..)` in Groovy needs to be `(project.extensions.findByName("android") as BaseExtension).registerTransform(..)` in Kotlin.
20 |
21 | The transform needs to be registered during the apply phase and the transform is executed for every build variant. (But you can access the currently building variant during transformation.)
22 |
23 | The transformation is a subclass of `com.android.build.api.transform.Transform`. You need to implement a couple of functions to make the build know about your transformation. e.g. `getName`, `getScopes` and so on.
24 |
25 | The heavy lifting happens in `transform`.
26 |
27 | You get an instance of `TransformInvocation` which offers everything you need for your actual transform.
28 |
29 | Besides a context (the variant, a LoggingManager etc.) you get the inputs to your transform and an output provider you need to use to know where to put your transformed files.
30 |
31 | It's worth to note that you might not only get directories containing class files but for some scopes you will likely get JARs - if you want to modify them you have to take that into account.
32 |
33 | If your transformation can handle incremental transforms you can query for the changed files that need to be re-processed.
34 |
35 | The important thing is that even if you don't want to modify a file in your requested scopes you need to copy it over - otherwise it won't make it into your final APK.
36 |
37 | How exactly you process the individual files is completely up to you. If you want to modify bytecode there are plenty of libraries to make your life easier.
38 | (e.g. ASM, BCEL, ByteBuddy are popular)
39 |
40 | But the most convenient library in my opinion is Javassist - it is quite high level and can even process a subset of Java source. The only downside is you need all the dependencies of the classes you want to process on Javassist's own classpath.
41 |
42 | # Things to note about this implementation
43 |
44 | First you can configure for which variants you want the transform to get applied. Because this check can only be done in the transform itself we need to copy the requested files even if we don't modify them.
45 |
46 | As said above there is a custom annotation. It lives in it's own module and you need a dependency to that in order to use it.
47 |
48 | Additionally there is a runtime which is called whenever an actual log happens. I could have used `android.util.Log` or anything else directly but a dedicated runtime gives more freedom for the implementation.
49 | The runtime needs to be added as a dependency for at least every variant you enable the transformation for.
50 |
51 | The actual byte code manipulation is pretty straight forward thanks to the high level Javassist API.
52 |
53 | While logging a method invocation is done by just adding a `before` block to the method itself it's a bit trickier to do that for field access:
54 | Since there is no code run when accessing a field I instrument every read and write of the annotated fields in the methods which actually perform that operation.
55 |
56 | The transform only touches files from the `PROJECT` scope. Not from external dependencies or sub modules. That's not a limitation of the Transform API but a design decision.
57 |
58 | Since Javassist needs all the referenced classes of a class you want to modify on it's own classpath we need the scopes EXTERNAL_LIBRARIES and SUB_PROJECTS.
59 | We could have added them to the requested scopes but in that case we need to copy them in order to get them into the final APK. That would certainly work.
60 |
61 | However I do it differently: I request the EXTERNAL_LIBRARIES and SUB_PROJECTS scopes as referenced scopes.
62 | This way we get them into the transform as referenced input but don't have to copy them.
63 |
64 | To make things easier for now the transform is not incremental.
65 | Enabling incremental transformation would be a bit tricky for this transform since in that case you could add the annotation to a public field and that means we have to process also the untouched classes since they could contain a field access to such a field.
66 |
67 | One important hint to safe you a lot of trouble: For some reasons Javassist often sees old versions of the runtime which is a problem if you add methods or change method signatures!
68 | The solution is: Kill the Gradle daemon (gradlew --stop) after changing the runtime. (Or don't built via IDE and always use --no-daemon command line switch).
69 |
70 | There are tests for the plugin and the transform itself. Since we are using buildSrc the tests consequently also live in buildSrc. Downside of this is that importing the project into the IDE will fail if there are failing tests.
71 |
72 | The tests are low level unit tests using MockK and Kluent but don't use TestKit. They are really unit tests not functional tests.
73 |
74 | Most challenging part in testing this is to test the actual byte code modifications.
75 |
76 | # License
77 |
78 | ```
79 | Copyright 2018 grandcentrix GmbH
80 |
81 | Licensed under the Apache License, Version 2.0 (the "License");
82 | you may not use this file except in compliance with the License.
83 | You may obtain a copy of the License at
84 |
85 | http://www.apache.org/licenses/LICENSE-2.0
86 |
87 | Unless required by applicable law or agreed to in writing, software
88 | distributed under the License is distributed on an "AS IS" BASIS,
89 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
90 | See the License for the specific language governing permissions and
91 | limitations under the License.
92 | ```
93 |
--------------------------------------------------------------------------------
/annotations/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/annotations/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'org.jetbrains.kotlin.jvm'
3 | id 'java-library'
4 | }
5 |
6 | dependencies {
7 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
8 | }
9 |
10 | sourceCompatibility = "7"
11 | targetCompatibility = "7"
12 |
--------------------------------------------------------------------------------
/annotations/src/main/java/net/grandcentrix/gradle/logalot/annotations/LogALot.kt:
--------------------------------------------------------------------------------
1 | package net.grandcentrix.gradle.logalot.annotations
2 |
3 | /**
4 | * Use this annotation to have the method or field logged.
5 | */
6 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
7 | @Retention(AnnotationRetention.BINARY)
8 | annotation class LogALot
9 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | apply plugin: 'net.grandcentrix.logalot'
5 |
6 | android {
7 | compileSdkVersion 28
8 | defaultConfig {
9 | applicationId "net.grandcentrix.logalot"
10 | minSdkVersion 26
11 | targetSdkVersion 28
12 | versionCode 1
13 | versionName "1.0"
14 | }
15 | buildTypes {
16 | release {
17 | signingConfig debug.signingConfig
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | flavorDimensions "version"
24 | productFlavors {
25 | internal {
26 | dimension "version"
27 | }
28 | playStore {
29 | dimension "version"
30 | }
31 | }
32 | }
33 |
34 | logALot {
35 | applyFor = ["debug"]
36 | }
37 |
38 | dependencies {
39 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
40 | implementation 'com.android.support:appcompat-v7:28.0.0'
41 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
42 |
43 | implementation project(":annotations")
44 | debugImplementation project(":runtime")
45 |
46 | testImplementation 'junit:junit:4.12'
47 | }
48 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/debug/java/net/grandcentrix/logalot/DebugApp.kt:
--------------------------------------------------------------------------------
1 | package net.grandcentrix.logalot
2 |
3 | import android.app.Application
4 | import android.util.Log
5 | import net.grandcentrix.gradle.logalot.runtime.logMethodInvocationDelegate
6 |
7 | class DebugApp : Application() {
8 |
9 | companion object {
10 | init {
11 | logMethodInvocationDelegate = { clazz, method, params ->
12 | Log.d("LogALot", "Delegated method invocation log: $clazz $method ${params.joinToString(",")}")
13 | }
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/java/net/grandcentrix/logalot/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package net.grandcentrix.logalot
2 |
3 | import android.annotation.SuppressLint
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import android.widget.Button
7 | import net.grandcentrix.gradle.logalot.annotations.LogALot
8 |
9 | /**
10 | * Just a test.
11 | */
12 | class MainActivity : AppCompatActivity() {
13 |
14 | @LogALot
15 | private var myField = 0
16 |
17 | @LogALot
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | noArgMethod()
21 |
22 | try {
23 | thrower()
24 | } catch (e: Throwable) {
25 | // nothing here
26 | }
27 |
28 | setContentView(R.layout.activity_main)
29 | findViewById