-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
WrappingVisitor.kt
195 lines (178 loc) · 7.89 KB
/
WrappingVisitor.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
@file:Suppress("UnstableApiUsage")
package io.sentry.android.gradle.instrumentation.wrap.visitor
import com.android.build.api.instrumentation.ClassData
import io.sentry.android.gradle.SentryPlugin
import io.sentry.android.gradle.instrumentation.MethodContext
import io.sentry.android.gradle.instrumentation.wrap.Replacement
import io.sentry.android.gradle.util.info
import java.util.LinkedList
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.commons.GeneratorAdapter
import org.objectweb.asm.commons.Method
import org.objectweb.asm.tree.InsnNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.TypeInsnNode
import org.objectweb.asm.tree.VarInsnNode
import org.slf4j.Logger
class WrappingVisitor(
api: Int,
originalVisitor: MethodVisitor,
private val firstPassVisitor: MethodNode,
private val classContext: ClassData,
private val context: MethodContext,
private val replacements: Map<Replacement, Replacement>,
private val logger: Logger = SentryPlugin.logger
) : GeneratorAdapter(
api,
originalVisitor,
context.access,
context.name,
context.descriptor
) {
private val targetTypes = replacements.keys
.toSet()
.map { it.owner }
private val newInsnsForTargets by lazy {
// filter all NEW insns for the target types that we are going to wrap
val insns = firstPassVisitor.instructions
.toArray()
.filter { it is TypeInsnNode && it.opcode == Opcodes.NEW && it.desc in targetTypes }
LinkedList(insns)
}
private val className = classContext.className.replace('.', '/')
private var manuallyDuped = false
private var varIndex = -1
override fun visitTypeInsn(opcode: Int, type: String?) {
super.visitTypeInsn(opcode, type)
if (opcode == Opcodes.NEW && type in targetTypes) {
val nextInsn = newInsnsForTargets.poll()?.next ?: return
// in case the next insn after NEW is not a DUP, we inject our own DUP and flip a flag
// to later store our wrapping instance with the same index as the original instance
val isNextInsnDup = (nextInsn as? InsnNode)?.opcode == Opcodes.DUP
// in case the next insn after NEW is DUP, but is followed by ASTORE, we do the same
// thing as above. This case cannot be written by a developer, but rather is produced
// by a code obfuscator/compiler, because the usage of uninitialized instance
// is prohibited by the java verifier (NEW should be followed by INVOKESPECIAL before
// using it, which is not the case with ASTORE)
val isDupFollowedByStore =
isNextInsnDup && (nextInsn.next as? VarInsnNode)?.opcode == Opcodes.ASTORE
if (!isNextInsnDup || isDupFollowedByStore) {
dup()
manuallyDuped = true
}
}
}
override fun visitVarInsn(opcode: Int, `var`: Int) {
super.visitVarInsn(opcode, `var`)
// capture the variable index of the instrumented type to later store our wrapped type
// with the same index
if (opcode == Opcodes.ASTORE && manuallyDuped && varIndex == -1) {
varIndex = `var`
}
}
override fun visitMethodInsn(
opcode: Int,
owner: String,
name: String,
descriptor: String,
isInterface: Boolean
) {
val methodSig = Replacement(owner, name, descriptor)
val replacement = if (methodSig in replacements) {
replacements[methodSig]
} else {
// try to look up for a replacement without owner (as the owner sometimes can differ)
replacements[methodSig.copy(owner = "")]
}
when {
opcode == Opcodes.INVOKEDYNAMIC -> {
// we don't instrument invokedynamic, because it's just forwarding to a synthetic method
// which will be instrumented thanks to condition below
logger.info {
"INVOKEDYNAMIC skipped from instrumentation for" +
" ${className.prettyPrintClassName()}.${context.name}"
}
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface)
}
replacement != null -> {
val isSuperCallInOverride = opcode == Opcodes.INVOKESPECIAL &&
owner != className &&
name == context.name &&
descriptor == context.descriptor
val isSuperCallInCtor = opcode == Opcodes.INVOKESPECIAL &&
name == "<init>" &&
classContext.superClasses.firstOrNull()?.fqName() == owner
when {
isSuperCallInOverride -> {
// this will be instrumented on the calling side of the overriding class
logger.info {
"${className.prettyPrintClassName()} skipped from instrumentation " +
"in overridden method $name.$descriptor"
}
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface)
}
isSuperCallInCtor -> {
// this has to be manually instrumented (e.g. by inheriting our runtime classes)
logger.info {
"${className.prettyPrintClassName()} skipped from instrumentation " +
"in constructor $name.$descriptor"
}
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface)
}
else -> {
logger.info {
"Wrapping $owner.$name with ${replacement.owner}.${replacement.name} " +
"in ${className.prettyPrintClassName()}.${context.name}"
}
visitWrapping(replacement, opcode, owner, name, descriptor, isInterface)
}
}
}
else -> super.visitMethodInsn(opcode, owner, name, descriptor, isInterface)
}
}
private fun String.prettyPrintClassName() = replace('/', '.')
private fun String.fqName() = replace('.', '/')
private fun GeneratorAdapter.visitWrapping(
replacement: Replacement,
opcode: Int,
owner: String,
name: String,
descriptor: String,
isInterface: Boolean
) {
// create a new method to figure out the number of arguments
val originalMethod = Method(name, descriptor)
// replicate arguments on stack, so we can later re-use them for our wrapping
val locals = IntArray(originalMethod.argumentTypes.size)
for (i in locals.size - 1 downTo 0) {
locals[i] = newLocal(originalMethod.argumentTypes[i])
storeLocal(locals[i])
}
// load arguments from stack for the original method call
locals.forEach {
loadLocal(it)
}
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface)
// load arguments from stack for the wrapping method call
// only load as many as the new method requires (replacement method may have less arguments)
val newMethod = Method(replacement.name, replacement.descriptor)
for (i in 0 until newMethod.argumentTypes.size - 1) {
loadLocal(locals[i])
}
// call wrapping (it's always a static method)
super.visitMethodInsn(
Opcodes.INVOKESTATIC,
replacement.owner,
replacement.name,
replacement.descriptor,
false
)
if (manuallyDuped && varIndex >= 0) {
mv.visitVarInsn(Opcodes.ASTORE, varIndex)
varIndex = -1
manuallyDuped = false
}
}
}