Memory corruption in DB on platforms with FPC_REQUIRES_PROPER_ALIGNMENT
Original Reporter info from Mantis: kluug.net @onpok
-
Reporter name: Ondrej Pokorny
Original Reporter info from Mantis: kluug.net @onpok
- Reporter name: Ondrej Pokorny
Description:
Memory is being overwritten in DB / BufDataset. I debugged into it and found out that the compiler define FPC_REQUIRES_PROPER_ALIGNMENT is causing it.
The problem is the difference between DataSize returned in TStringField:
function TStringField.GetDataSize: Integer;
begin
case FCodePage of
CP_UTF8: Result := 4*Size+1;
else Result := Size+1;
end;
end;
and the DataSize returned in TCustomBufDataset.GetFieldSize:
function TCustomBufDataset.GetFieldSize(FieldDef : TFieldDef) : longint;
begin
// ...
{$IFDEF FPC_REQUIRES_PROPER_ALIGNMENT}
result:=Align(result,4);
{$ENDIF}
end;
As you can see the result from TCustomBufDataset.GetFieldSize is aligned and thus it can be bigger than the result from TStringField.GetDataSize.
The problem is that the buffer is allocated with TStringField.GetDataSize and it is filled with TCustomBufDataset.GetFieldSize that causes memory corruption.
See the attached patch where I commented the places where the buffer is allocated and where it is filled. The patch also includes a (temporary) solution for TStringField.GetDataSize. I don't know if it is a correct solution. Maybe more places have to be fixed or the fix should be different. A solution could also be to disable alignment for strings in TCustomBufDataset.GetFieldSize.
Steps to reproduce:
See DBMemCorr.lpr
Mantis conversion info:
- Mantis ID: 36747
- OS: Raspbian
- Platform: linux-arm Raspberry Pi 4
- Version: 3.3.1
- Fixed in version: 3.3.1
- Fixed in revision: 44280 (#c49dbb9d)
- Target version: 3.2.0