[fpc-devel] Valgrind strscan

petr.kristan at epos.cz petr.kristan at epos.cz
Thu Apr 10 14:50:07 CEST 2008


Hi.

In the morning I was hunting valgrind "Invalid read of size 4" in my
code and finally I found it. Example:

program str;
uses
  SysUtils;
var
  p: PChar;
begin
  GetMem(p, 1);
  p^ := #0;
  StrScan(p, 'x');
  FreeMem(p);
end.

==14379== Invalid read of size 4
==14379==    at 0x80708F0: SYSUTILS_STRSCAN$PCHAR$CHAR$$PCHAR (strings.inc:439)
==14379==    by 0x804828A: main (str.pas:9)
==14379==  Address 0x416A494 is 4 bytes inside a block of size 5 alloc'd
==14379==    at 0x401D38B: malloc (vg_replace_malloc.c:149)
==14379==    by 0x8063398: CMEM_CGETMEM$LONGWORD$$POINTER (cmem.pp:50)
==14379==    by 0x805AFA6: SYSTEM_GETMEM$POINTER$LONGWORD (heap.inc:235)
==14379==    by 0x8048276: main (str.pas:7)

Problem is in assembler code for i386. rtl/i386/strings.inc.
This routine reads always 4 bytes alligned by 4 regardless string length.

function strscan(p : pchar;c : char) : pchar;assembler;
...
// load new 4 bytes
        movl     (%edi),%edx   <-here valgrind report Invalid read 
...

Problem was discovered aleady here http://bugs.freepascal.org/view.php?id=6314

My assembler knowledge is unfortunately not so good yet to effectively repair it.
Besides routine is very sophisticated. :)
But I think that solving this cosmetic error will save many developers
hours during valgrind code checking. And preparing testcases fo fpc
developers.

Petr

-- 
Ing. Petr Kristan
.
EPOS PRO s.r.o., Bozeny Nemcove 2625, 530 02 Pardubice
tel: +420 466335223    Czech Republic (Eastern Europe) 
fax: +420 466510709



More information about the fpc-devel mailing list