Skip to content

Commit 9f070ed

Browse files
authored
Merge pull request #25308 from Azoy/demangle-bug-thing
[Runtime] swift_demangle: Update buffer size after copying
2 parents f9324d8 + 9bbb853 commit 9f070ed

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

stdlib/public/runtime/Demangle.cpp

+5-4
Original file line numberDiff line numberDiff line change
@@ -666,13 +666,14 @@ char *swift_demangle(const char *mangledName,
666666
return strdup(result.c_str());
667667
}
668668

669-
// Indicate a failure if the result does not fit and will be truncated
670-
// and set the required outputBufferSize.
669+
// Copy into the provided buffer.
670+
_swift_strlcpy(outputBuffer, result.c_str(), *outputBufferSize);
671+
672+
// Indicate a failure if the result did not fit and was truncated
673+
// by setting the required outputBufferSize.
671674
if (*outputBufferSize < result.length() + 1) {
672675
*outputBufferSize = result.length() + 1;
673676
}
674677

675-
// Copy into the provided buffer.
676-
_swift_strlcpy(outputBuffer, result.c_str(), *outputBufferSize);
677678
return outputBuffer;
678679
}

test/stdlib/Runtime.swift.gyb

+31
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,37 @@ Runtime.test("demangleName") {
375375
expectEqual("Foobar", _stdlib_demangleName("$s13__lldb_expr_46FoobarCD"))
376376
}
377377

378+
Runtime.test("demangleTruncate") {
379+
// Swift.Int requires 10 bytes to be fully demangled.
380+
let buffer = UnsafeMutableBufferPointer<Int8>.allocate(capacity: 10)
381+
382+
defer { buffer.deallocate() }
383+
384+
// Set last byte to a custom number, that way when we call swift_demangle
385+
// the last byte should be unchanged rather than it being set to 0.
386+
buffer[buffer.count - 1] = 16
387+
388+
// Only give 9 bytes though to exercise that swift_demangle doesn't write past
389+
// the buffer.
390+
var bufferSize = UInt(buffer.count - 1)
391+
392+
let mangled = "$sSi"
393+
394+
mangled.utf8CString.withUnsafeBufferPointer {
395+
_ = _stdlib_demangleImpl(
396+
mangledName: $0.baseAddress,
397+
mangledNameLength: UInt($0.count - 1),
398+
outputBuffer: buffer.baseAddress,
399+
outputBufferSize: &bufferSize,
400+
flags: 0
401+
)
402+
}
403+
404+
expectEqual(String(cString: buffer.baseAddress!), "Swift.In")
405+
expectEqual(bufferSize, 10)
406+
expectEqual(buffer[buffer.count - 1], 16)
407+
}
408+
378409
% for optionality in ['', '?']:
379410
Runtime.test("_stdlib_atomicCompareExchangeStrongPtr") {
380411
typealias IntPtr = UnsafeMutablePointer<Int>

0 commit comments

Comments
 (0)