xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-debug/src/internal/Attach.kt (revision 7a7160fed73afa6648ef8aa100d4a336fe921d9a)
1 @file:Suppress("unused")
2 package kotlinx.coroutines.debug.internal
3 
4 import net.bytebuddy.*
5 import net.bytebuddy.agent.*
6 import net.bytebuddy.dynamic.loading.*
7 
8 /*
9  * This class is used reflectively from kotlinx-coroutines-core when this module is present in the classpath.
10  * It is a substitute for service loading.
11  */
12 internal class ByteBuddyDynamicAttach : Function1<Boolean, Unit> {
invokenull13     override fun invoke(value: Boolean) {
14         if (value) attach() else detach()
15     }
16 
attachnull17     private fun attach() {
18         ByteBuddyAgent.install(ByteBuddyAgent.AttachmentProvider.ForEmulatedAttachment.INSTANCE)
19         val cl = Class.forName("kotlin.coroutines.jvm.internal.DebugProbesKt")
20         val cl2 = Class.forName("kotlinx.coroutines.debug.internal.DebugProbesKt")
21 
22         ByteBuddy()
23             .redefine(cl2)
24             .name(cl.name)
25             .make()
26             .load(cl.classLoader, ClassReloadingStrategy.fromInstalledAgent())
27     }
28 
detachnull29     private fun detach() {
30         val cl = Class.forName("kotlin.coroutines.jvm.internal.DebugProbesKt")
31         val cl2 = Class.forName("kotlinx.coroutines.debug.internal.NoOpProbesKt")
32         ByteBuddy()
33             .redefine(cl2)
34             .name(cl.name)
35             .make()
36             .load(cl.classLoader, ClassReloadingStrategy.fromInstalledAgent())
37     }
38 }
39