Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper demangle function for 3rd party tools #16295

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions druntime/src/core/demangle.d
Original file line number Diff line number Diff line change
Expand Up @@ -3273,3 +3273,68 @@ private struct BufSlice
auto getSlice() inout nothrow scope { return buf[from .. to]; }
size_t length() const scope { return to - from; }
}

ryuukk marked this conversation as resolved.
Show resolved Hide resolved


/**
* C API to demangle D mangled names.
*
* Params:
* mangled = The string to demangle.
* buffer = A destination buffer.
* bufferLength = The length of the destination buffer.
*
* Returns:
* 1 for success 0 for failure
*/
extern(C) int d_demangle(const(char*) mangled, char* buffer, size_t bufferLength)
{
import core.stdc.string: strlen, memcpy;
if (mangled == null)
return 0;

auto mangledSlice = mangled[0 .. strlen(mangled)];
auto demangled = demangle(mangledSlice);

if (demangled.ptr == null || demangled.ptr == mangled)
return 0;

if (demangled.length > bufferLength)
return 0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should return the length of the demangled name.
so the user can decide to allocate a bigger buffer if it does not fit.


memcpy(buffer, demangled.ptr, demangled.length);
buffer[demangled.length] = 0;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an out-of-bounds write if bufferLength == demangled.length


return 1;
ryuukk marked this conversation as resolved.
Show resolved Hide resolved
}


unittest {
import core.stdc.string: strncmp;
{
char[512] buffer;

int ok = d_demangle("_D6mangle2CC6memberMFNlZPi", buffer.ptr, buffer.length);

assert(ok == 1);
assert(strncmp(buffer.ptr, "scope int* mangle.CC.member()", buffer.length) == 0);
}

{
// test invalid mangled name
char[512] buffer;

int ok = d_demangle("", buffer.ptr, buffer.length);

assert(ok == 0);
}

{
// test failure for buffer too small
char[8] buffer;

int ok = d_demangle("_D6mangle2CC6memberMFNlZPi", buffer.ptr, buffer.length);

assert(ok == 0);
}
}
Loading