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

Utf8 strings are not null-terminated #502

Open
VerySmallRoach opened this issue Dec 11, 2024 · 0 comments
Open

Utf8 strings are not null-terminated #502

VerySmallRoach opened this issue Dec 11, 2024 · 0 comments

Comments

@VerySmallRoach
Copy link

Tested on 1.91.0.1, but it looks like master have the same issue.

Here's the code:

if (ImGui.Begin("test", ImGuiWindowFlags.AlwaysHorizontalScrollbar)) {
    var label = new string('1', 5000);
    var data = "";
    ImGui.InputText(label, ref data, 10);
}
ImGui.End();

It creates a string with a very long label (to force ImGui.Net code to allocate instead of stackalloc). Sometimes if I launch program and scroll all the way to the right label ends up with random junk changing at runtime:

image

It does not always happen, sometimes program renders only 1111 as it should, sometimes junk appears for a few seconds and then disappears.

I believe the problem is in these lines (code from decompiled 1.91.0.1):

public unsafe static bool InputText(string label, ref string input, uint maxLength, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, nint user_data) {
        int byteCount = Encoding.UTF8.GetByteCount(label);
        byte* ptr = ((byteCount <= 2048) ? stackalloc byte[(int)(uint)(byteCount + 1)] : Util.Allocate(byteCount + 1));
        Util.GetUtf8(label, ptr, byteCount);

For long labels this code allocates memory, but is does not seem that Marshal.AllocHGlobal zeroes memory, and Encoding.UTF8.GetBytes does not write null-terminating zero.

Looking at other places in decompiled ImGui.NET code, there's explicit zero after Util.GetUtf8:

public unsafe static bool InputFloat(string label, ref float v, float step) {
        int num = 0;
        byte* ptr;
        if (label != null) {
            num = Encoding.UTF8.GetByteCount(label);
            ptr = ((num <= 2048) ? stackalloc byte[(int)(uint)(num + 1)] : Util.Allocate(num + 1));
            int utf = Util.GetUtf8(label, ptr, num);
            ptr[utf] = 0;
        } else {
            ptr = null;
        }

But InputText and some other methods do not have it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant