Celtoys / Remotery

Single C file, Realtime CPU/GPU Profiler with Remote Web Viewer
Apache License 2.0
3.1k stars 264 forks source link

BUG: Buffer overrun in MessageQueue_AllocMessage #108

Open shooshx opened 7 years ago

shooshx commented 7 years ago

The internal message queueing mechanism doesn't seem to handle correctly the case where a message is allocated across the ending of the cyclic buffer. This bug has the potential to crash the process with a segmentation fault.

code to reproduces the problem:

int main(int argc, const char * argv[])
{
    rmtError error;
    MessageQueue* queue = NULL;
    auto messageQueueSizeInBytes = 1024 * 64;
    New_1(MessageQueue, queue, messageQueueSizeInBytes);

    const char* t = "Hello1234567890123";
    int tsz = strlen(t);
    int written = 0;

    for(int i = 0; i < 100000; ++i)
    {
        bool threshCross = written + MessageQueue_SizeForPayload(tsz) > messageQueueSizeInBytes;
        if (threshCross)
        {
            Message* outmsg = MessageQueue_PeekNextMessage(queue);
            MessageQueue_ConsumeNextMessage(queue, outmsg);
            printf("Reading 1\n");
        }
        Message* message = MessageQueue_AllocMessage(queue, tsz, NULL);
        if (message == NULL)
            break;

        if (threshCross) {
            printf("Got %p inside buffer %p  which is  %d  bytes from the end with payload size %d\n",
                    (void*)message->payload, (void*)queue->data->ptr, ((char*)queue->data->ptr + queue->size - (char*)message->payload), tsz);
            break;
        }

        // Copy the text and commit the message
        memcpy(message->payload, t, tsz);
        MessageQueue_CommitMessage(message, MsgID_LogText);
        written += MessageQueue_SizeForPayload(tsz);
    }

    return 0;
}

prints:

Got 0x108d3cffc inside buffer 0x108d2d000  which is  4  bytes from the end with payload size 18
shooshx commented 7 years ago

no replay for almost a month... so this project is basically dead?

vinjn commented 7 years ago

Dude, this is the world of open-source project. The author could be busy with other projects / making money / having xmas holiday.

dwilliamson commented 7 years ago

@shooshx PRs are more than welcome.

shooshx commented 7 years ago

@dwilliamson I've came across this issue when I copied your code as a starting point for a lockless queue for my own purpose. In my code, solving this required some significant changes to the structures involved and the way the queue works. I'm not sure I know enough about the intricacies of your code base yet to do it properly.