Peter-van-Tol/LiteX-CNC

Buffer overflow

Closed this issue · 0 comments

Describe the bug
The communication to the card fails with the following message:

Unexpected read length: -1, expected 88
Unexpected read length: -1, expected 88
Unexpected read length: -1, expected 88
Unexpected read length: -1, expected 88
Unexpected read length: -1, expected 88

The card itself is still responsive, as the card is successfully reset at start up and shut down of LinuxCNC.

Cause
The buffer containing the addresses to be read is partly over-written. The magic byte is erased and therefore the FPGA does not recognize the packet as a read command.

Solution
The culprit in this essence is the clearing the read and write buffers:

    // Clear buffer (except for the header)
    memset(
        litexcnc->fpga->read_buffer + litexcnc->fpga->read_header_size, 
        0, 
        litexcnc->fpga->read_buffer_size
    ); 

This code will cause a write outside of the buffer, because the offset is not applied to the length.

Correct way is:

    // Clear buffer (except for the header)
    memset(
        litexcnc->fpga->read_buffer + litexcnc->fpga->read_header_size, 
        0, 
        litexcnc->fpga->read_buffer_size - litexcnc->fpga->read_header_size
    );