Skip to content

Commit 1aacb04

Browse files
authored
Support special characters in coroutine names in JSON dumps (#3747)
1 parent c8b3e5e commit 1aacb04

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

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

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ internal object DebugProbesImpl {
182182
val coroutinesInfoAsJson = ArrayList<String>(size)
183183
for (info in coroutinesInfo) {
184184
val context = info.context
185-
val name = context[CoroutineName.Key]?.name?.toStringWithQuotes()
186-
val dispatcher = context[CoroutineDispatcher.Key]?.toStringWithQuotes()
185+
val name = context[CoroutineName.Key]?.name?.toStringRepr()
186+
val dispatcher = context[CoroutineDispatcher.Key]?.toStringRepr()
187187
coroutinesInfoAsJson.add(
188188
"""
189189
{
@@ -219,7 +219,7 @@ internal object DebugProbesImpl {
219219
{
220220
"declaringClass": "${element.className}",
221221
"methodName": "${element.methodName}",
222-
"fileName": ${element.fileName?.toStringWithQuotes()},
222+
"fileName": ${element.fileName?.toStringRepr()},
223223
"lineNumber": ${element.lineNumber}
224224
}
225225
""".trimIndent()
@@ -229,7 +229,7 @@ internal object DebugProbesImpl {
229229
return "[${stackTraceElementsInfoAsJson.joinToString()}]"
230230
}
231231

232-
private fun Any.toStringWithQuotes() = "\"$this\""
232+
private fun Any.toStringRepr() = toString().repr()
233233

234234
/*
235235
* Internal (JVM-public) method used by IDEA debugger as of 1.4-M3.
@@ -590,3 +590,19 @@ internal object DebugProbesImpl {
590590

591591
private val StackTraceElement.isInternalMethod: Boolean get() = className.startsWith("kotlinx.coroutines")
592592
}
593+
594+
private fun String.repr(): String = buildString {
595+
append('"')
596+
for (c in this@repr) {
597+
when (c) {
598+
'"' -> append("\\\"")
599+
'\\' -> append("\\\\")
600+
'\b' -> append("\\b")
601+
'\n' -> append("\\n")
602+
'\r' -> append("\\r")
603+
'\t' -> append("\\t")
604+
else -> append(c)
605+
}
606+
}
607+
append('"')
608+
}

kotlinx-coroutines-debug/test/DumpCoroutineInfoAsJsonAndReferencesTest.kt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ class DumpCoroutineInfoAsJsonAndReferencesTest : DebugTestBase() {
2929
fun testDumpOfNamedCoroutine() =
3030
runTestWithNamedDeferred("Name")
3131

32+
@Test
33+
fun testDumpOfNamedCoroutineWithSpecialCharacters() =
34+
runTestWithNamedDeferred("Name with\n \"special\" characters\\/\t\b")
35+
3236
@Test
3337
fun testDumpWithNoCoroutines() {
3438
val dumpResult = DebugProbesImpl.dumpCoroutinesInfoAsJsonAndReferences()

0 commit comments

Comments
 (0)