aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/code_intelligence/jazzer/agent/RuntimeInstrumentor.kt
blob: 57410f3063da3332682083489687b8b4933f1735 (plain)
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2021 Code Intelligence GmbH
//
// 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.

package com.code_intelligence.jazzer.agent

import com.code_intelligence.jazzer.driver.Opt
import com.code_intelligence.jazzer.instrumentor.ClassInstrumentor
import com.code_intelligence.jazzer.instrumentor.CoverageRecorder
import com.code_intelligence.jazzer.instrumentor.Hook
import com.code_intelligence.jazzer.instrumentor.InstrumentationType
import com.code_intelligence.jazzer.utils.ClassNameGlobber
import com.code_intelligence.jazzer.utils.Log
import io.github.classgraph.ClassGraph
import java.io.File
import java.lang.instrument.ClassFileTransformer
import java.lang.instrument.Instrumentation
import java.nio.file.Path
import java.security.ProtectionDomain
import kotlin.math.roundToInt
import kotlin.system.exitProcess
import kotlin.time.measureTimedValue

class RuntimeInstrumentor(
    private val instrumentation: Instrumentation,
    private val classesToFullyInstrument: ClassNameGlobber,
    private val classesToHookInstrument: ClassNameGlobber,
    private val instrumentationTypes: Set<InstrumentationType>,
    private val includedHooks: List<Hook>,
    private val customHooks: List<Hook>,
    // Dedicated name globber for additional classes to hook stated in hook annotations is needed due to
    // existing include and exclude pattern of classesToHookInstrument. All classes are included in hook
    // instrumentation except the ones from default excludes, like JDK and Kotlin classes. But additional
    // classes to hook, based on annotations, are allowed to reference normally ignored ones, like JDK
    // and Kotlin internals.
    // FIXME: Adding an additional class to hook will apply _all_ hooks to it and not only the one it's
    // defined in. At some point we might want to track the list of classes per custom hook rather than globally.
    private val additionalClassesToHookInstrument: ClassNameGlobber,
    private val coverageIdSynchronizer: CoverageIdStrategy,
    private val dumpClassesDir: Path?,
) : ClassFileTransformer {

    @kotlin.time.ExperimentalTime
    override fun transform(
        loader: ClassLoader?,
        internalClassName: String,
        classBeingRedefined: Class<*>?,
        protectionDomain: ProtectionDomain?,
        classfileBuffer: ByteArray,
    ): ByteArray? {
        var pathPrefix = ""
        if (!Opt.instrumentOnly.isEmpty() && protectionDomain != null) {
            var outputPathPrefix = protectionDomain.getCodeSource().getLocation().getFile().toString()
            if (outputPathPrefix.isNotEmpty()) {
                if (outputPathPrefix.contains(File.separator)) {
                    outputPathPrefix = outputPathPrefix.substring(outputPathPrefix.lastIndexOf(File.separator) + 1, outputPathPrefix.length)
                }

                if (outputPathPrefix.endsWith(".jar")) {
                    outputPathPrefix = outputPathPrefix.substring(0, outputPathPrefix.lastIndexOf(".jar"))
                }

                if (outputPathPrefix.isNotEmpty()) {
                    pathPrefix = outputPathPrefix + File.separator
                }
            }
        }

        return try {
            // Bail out early if we would instrument ourselves. This prevents ClassCircularityErrors as we might need to
            // load additional Jazzer classes until we reach the full exclusion logic.
            if (internalClassName.startsWith("com/code_intelligence/jazzer/")) {
                return null
            }
            // Workaround for a JDK bug (http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8299798):
            // When retransforming a class in the Java standard library, the provided classfileBuffer does not contain
            // any StackMapTable attributes. Our transformations require stack map frames to calculate the number of
            // local variables and stack slots as well as when adding control flow.
            //
            // We work around this by reloading the class file contents if we are retransforming (classBeingRedefined
            // is also non-null in this situation) and the class is provided by the bootstrap loader.
            //
            // Alternatives considered:
            // Using ClassWriter.COMPUTE_FRAMES as an escape hatch isn't possible in the context of an agent as the
            // computation may itself need to load classes, which leads to circular loads and incompatible class
            // redefinitions.
            transformInternal(internalClassName, classfileBuffer.takeUnless { loader == null && classBeingRedefined != null })
        } catch (t: Throwable) {
            // Throwables raised from transform are silently dropped, making it extremely hard to detect instrumentation
            // failures. The docs advise to use a top-level try-catch.
            // https://docs.oracle.com/javase/9/docs/api/java/lang/instrument/ClassFileTransformer.html
            if (dumpClassesDir != null) {
                dumpToClassFile(internalClassName, classfileBuffer, basenameSuffix = ".failed", pathPrefix = pathPrefix)
            }
            Log.warn("Failed to instrument $internalClassName:", t)
            throw t
        }.also { instrumentedByteCode ->
            // Only dump classes that were instrumented.
            if (instrumentedByteCode != null && dumpClassesDir != null) {
                dumpToClassFile(internalClassName, instrumentedByteCode, pathPrefix = pathPrefix)
                dumpToClassFile(internalClassName, classfileBuffer, basenameSuffix = ".original", pathPrefix = pathPrefix)
            }
        }
    }

    private fun dumpToClassFile(internalClassName: String, bytecode: ByteArray, basenameSuffix: String = "", pathPrefix: String = "") {
        val relativePath = "$pathPrefix$internalClassName$basenameSuffix.class"
        val absolutePath = dumpClassesDir!!.resolve(relativePath)
        val dumpFile = absolutePath.toFile()
        dumpFile.parentFile.mkdirs()
        dumpFile.writeBytes(bytecode)
    }

    @kotlin.time.ExperimentalTime
    override fun transform(
        module: Module?,
        loader: ClassLoader?,
        internalClassName: String,
        classBeingRedefined: Class<*>?,
        protectionDomain: ProtectionDomain?,
        classfileBuffer: ByteArray,
    ): ByteArray? {
        try {
            if (module != null && !module.canRead(RuntimeInstrumentor::class.java.module)) {
                // Make all other modules read our (unnamed) module, which allows them to access the classes needed by the
                // instrumentations, e.g. CoverageMap. If a module can't be modified, it should not be instrumented as the
                // injected bytecode might throw NoClassDefFoundError.
                // https://mail.openjdk.java.net/pipermail/jigsaw-dev/2021-May/014663.html
                if (!instrumentation.isModifiableModule(module)) {
                    val prettyClassName = internalClassName.replace('/', '.')
                    Log.warn("Failed to instrument $prettyClassName in unmodifiable module ${module.name}, skipping")
                    return null
                }
                instrumentation.redefineModule(
                    module,
                    setOf(RuntimeInstrumentor::class.java.module), // extraReads
                    emptyMap(),
                    emptyMap(),
                    emptySet(),
                    emptyMap(),
                )
            }
        } catch (t: Throwable) {
            // Throwables raised from transform are silently dropped, making it extremely hard to detect instrumentation
            // failures. The docs advise to use a top-level try-catch.
            // https://docs.oracle.com/javase/9/docs/api/java/lang/instrument/ClassFileTransformer.html
            if (dumpClassesDir != null) {
                dumpToClassFile(internalClassName, classfileBuffer, basenameSuffix = ".failed")
            }
            Log.warn("Failed to instrument $internalClassName:", t)
            throw t
        }
        return transform(loader, internalClassName, classBeingRedefined, protectionDomain, classfileBuffer)
    }

    @kotlin.time.ExperimentalTime
    fun transformInternal(internalClassName: String, maybeClassfileBuffer: ByteArray?): ByteArray? {
        val (fullInstrumentation, printInfo) = when {
            classesToFullyInstrument.includes(internalClassName) -> Pair(true, true)
            classesToHookInstrument.includes(internalClassName) -> Pair(false, true)
            // The classes to hook specified by hooks are more of an implementation detail of the hook. The list is
            // always the same unless the set of hooks changes and doesn't help the user judge whether their classes are
            // being instrumented, so we don't print info for them.
            additionalClassesToHookInstrument.includes(internalClassName) -> Pair(false, false)
            else -> return null
        }
        val className = internalClassName.replace('/', '.')
        val classfileBuffer = maybeClassfileBuffer ?: ClassGraph()
            .enableSystemJarsAndModules()
            .ignoreClassVisibility()
            .acceptClasses(className)
            .scan()
            .use {
                it.getClassInfo(className)?.resource?.load() ?: run {
                    Log.warn("Failed to load bytecode of class $className")
                    return null
                }
            }
        val (instrumentedBytecode, duration) = measureTimedValue {
            try {
                instrument(internalClassName, classfileBuffer, fullInstrumentation)
            } catch (e: CoverageIdException) {
                Log.error("Coverage IDs are out of sync")
                e.printStackTrace()
                exitProcess(1)
            }
        }
        val durationInMs = duration.inWholeMilliseconds
        val sizeIncrease = ((100.0 * (instrumentedBytecode.size - classfileBuffer.size)) / classfileBuffer.size).roundToInt()
        if (printInfo) {
            if (fullInstrumentation) {
                Log.info("Instrumented $className (took $durationInMs ms, size +$sizeIncrease%)")
            } else {
                Log.info("Instrumented $className with custom hooks only (took $durationInMs ms, size +$sizeIncrease%)")
            }
        }
        return instrumentedBytecode
    }

    private fun instrument(internalClassName: String, bytecode: ByteArray, fullInstrumentation: Boolean): ByteArray {
        val classWithHooksEnabledField = if (Opt.conditionalHooks) {
            // Let the hook instrumentation emit additional logic that checks the value of the
            // hooksEnabled field on this class and skips the hook if it is false.
            "com/code_intelligence/jazzer/runtime/JazzerInternal"
        } else {
            null
        }
        return ClassInstrumentor(internalClassName, bytecode).run {
            if (fullInstrumentation) {
                // Coverage instrumentation must be performed before any other code updates
                // or there will be additional coverage points injected if any calls are inserted
                // and JaCoCo will produce a broken coverage report.
                coverageIdSynchronizer.withIdForClass(internalClassName) { firstId ->
                    coverage(firstId).also { actualNumEdgeIds ->
                        CoverageRecorder.recordInstrumentedClass(
                            internalClassName,
                            bytecode,
                            firstId,
                            actualNumEdgeIds,
                        )
                    }
                }
                // Hook instrumentation must be performed after data flow tracing as the injected
                // bytecode would trigger the GEP callbacks for byte[].
                traceDataFlow(instrumentationTypes)
                hooks(includedHooks + customHooks, classWithHooksEnabledField)
            } else {
                hooks(customHooks, classWithHooksEnabledField)
            }
            instrumentedBytecode
        }
    }
}