Skip to content

Commit 3a8fb3f

Browse files
committed
[debug] Introduce SafeAgentPremain class to avoid errors during debug if initialization of AgentPremain failed.
1 parent 0ea765f commit 3a8fb3f

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

kotlinx-coroutines-core/build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ fun setupManifest(jar: Jar) {
167167
jar.manifest {
168168
attributes(
169169
mapOf(
170-
"Premain-Class" to "kotlinx.coroutines.debug.internal.AgentPremain",
170+
"Premain-Class" to "kotlinx.coroutines.debug.internal.SafeAgentPremain",
171171
"Can-Retransform-Classes" to "true",
172172
)
173173
)

kotlinx-coroutines-core/jvm/src/debug/internal/AgentPremain.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,28 @@ internal object AgentPremain {
6969
}
7070
}
7171
}
72+
73+
/**
74+
* This class is loaded if and only if kotlinx-coroutines-core was used as a javaagent argument.
75+
* It serves as a "safe" wrapper around [AgentPremain] that does not require any kotlin-stdlib classes to be loaded for its initialization.
76+
*
77+
* Initialization of [AgentPremain] may fail, e.g., because it started before the required kotlin-stdlib classes were loaded.
78+
* If `kotlinx.coroutines.apply.debug.agent` is set to `false`, the coroutine debug agent will not be applied.
79+
*/
80+
@Suppress("unused")
81+
internal object SafeAgentPremain {
82+
@JvmStatic
83+
fun premain(args: String?, instrumentation: Instrumentation) {
84+
// If this property is disabled, the debug agent will not be applied at all
85+
val applyDebugAgent = System.getProperty("kotlinx.coroutines.apply.debug.agent", "true").toBoolean()
86+
if (!applyDebugAgent) return
87+
try {
88+
AgentPremain.premain(args, instrumentation)
89+
} catch (t: Throwable) {
90+
error("Something went wrong while loading kotlinx.coroutines debug agent.\n" +
91+
"Please ensure that kotlin-stdlib is present in the classpath.\n" +
92+
"Alternatively, you can disable kotlinx.coroutines debug agent with this system property: `kotlinx.coroutines.apply.debug.agent=false`\n" +
93+
t.cause)
94+
}
95+
}
96+
}

0 commit comments

Comments
 (0)