radareorg / radare2-r2pipe

Access radare2 via pipe from any programming language!
389 stars 99 forks source link

DotNet: Fix incorrect end of stream check in RunCommand #150

Closed ncatlin closed 2 years ago

ncatlin commented 2 years ago

Checklist

Description

Hello - not sure if anyone uses the DotNet bindings, but on closing it never terminates (until a memory leak becomes too fatal).

To reproduce

using r2pipe;

using (IR2Pipe pipe = new R2Pipe(@"C:\Windows\notepad.exe", @"C:\radare2\radare2.exe"))
{
    Task<string> async = pipe.RunCommandAsync("?V");
    Console.WriteLine("Hello async r2!" + async.Result);
}

#### Output

The expected message, but the program never terminates and memory usage constantly increases

image

Root cause

        public string RunCommand(string command)
        {
            var sb = new StringBuilder();
            r2Process.StandardInput.WriteLine(command);
            r2Process.StandardInput.Flush();

            while (true)
            {
                char buffer = (char)r2Process.StandardOutput.Read();

                if (buffer == 0x00)
                    break;

                sb.Append(buffer);
            }
            return sb.ToString();
        }

When the Dispose operation calls the q command, RunCommand waits for the end of the stream by checking for a 0 result. StreamReader.Read() doesn't return 0 when there is nothing left though, it returns -1.

This PR just changes the check to look for -1, so it now exits as expected.

trufae commented 2 years ago

Awesome! Good finding! Thanks for the fix