Fix invalid read in verilator_memutil
Fix invalid read in verilator_memutil

The simutil_verilator_set_mem function is an exported SystemVerilog
function with the following prototype:

  function int simutil_verilator_set_mem(input int         index,
                                         input bit [255:0] val);

The val input is only used as follows:

    mem[index] = val[Width-1:0];

(with Width = 32 in the memory I'm interested in). However, Verilator
translates the function to include the following statement:

    VL_SET_W_SVBV(256,val__Vcvt,val);

This is a function call to a function defined in verilator_dpi.h,
designed to convert between "val" (an svBitVecVal*, whose layout is
defined by the SystemVerilog DPI spec) and "val__Vcvt" (an internal
Verilator bit vector type).

That function reads the whole of val (all 256 bits of it). If val is
actually a pointer to the last few bytes of a malloc'd array, this
reads off the end of the array. The C++ code goes on to mask out the
upper bits (to do the [Width-1:0] select) but the damage is already
done: we've read data off the end of an array.

This causes an "Invalid read of size 4" error when run under Valgrind.

An alternative fix would be to allocate an extra 31 bytes of padding
as part of the malloc in ElfFileToBinary. Since I can't believe the
performance of this code matters, I've done it this way to make things
more explicit.

Signed-off-by: Rupert Swarbrick <290093e2ad2515ed2f14d749293c8cf8e02ca274@lowrisc.org>

lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan