FPC generates a word access when it should generate a byte access, occasionally causing an access violation
Original Reporter info from Mantis: 440bx @440bx
-
Reporter name:
Original Reporter info from Mantis: 440bx @440bx
- Reporter name:
Description:
For some expressions the compiler generates code that accesses a word instead of accessing a byte. When this occurs on the last accessible byte of a memory block, this causes an access violation. In the following code snippet:
procedure DumpHex(BaseAddress : pointer; BlockSize : DWORD);
const
HexDigits : packed array[0..$F] of char = '0123456789ABCDEF';
var
Buf : packed array[0..127] of char;
HexPtr : ^char;
p : pbyte;
i : dword;
begin
ZeroMemory(@Buf, sizeof(Buf));
HexPtr := @Buf;
if BlockSize > high(Buf) then BlockSize := high(Buf); // only dump 1 buffer's
// worth
i := 0;
while I < BlockSize do
begin
pchar(p) := pchar(BaseAddress) + I;
HexPtr^ := HexDigits[p^ shr 4]; // first nibble
inc(HexPtr);
// this instruction causes an access violation on the last byte because
// it tries to access a word instead of a byte.
HexPtr^ := HexDigits[p^ and $F]; // second nibble
inc(HexPtr);
writeln('I : ', i,
' address : ', IntToHex(ptruint(p), 0), ' dump : ', Buf);
inc(I);
end;
writeln(Buf); // won't get here
end;
the expression:
HexPtr^ := HexDigits[p^ and $F]; // second nibble
generates a word access instead of a byte access.
The attached program reliably reproduces the problem.
Steps to reproduce:
attempt to access the last accessible byte of a memory block.
Compile and run the attached program. Look at the code generated for the expression:
HexPtr^ := HexDigits[p^ and $F]; // second nibble
to see the cause of the access violation.