Skip to content

HugeWordAssignBuf() memory corruption bug #42

@sztdevel

Description

@sztdevel

I think, there is a bug in HugeWordAssignBuf() at the end of the procedure. Here is a modified version with some explanations:

procedure HugeWordAssignBuf(var A: HugeWord; const Buf; const BufSize{Bytes}: Integer; const ReverseByteOrder: Boolean);
//* The for cycle high value when filling the end of A.Data buffer with zeroes. -1 means no fill, 0 means 1 byte fill.
const FillCount: array[0..HugeWordElementSize-1] of Integer = (-1, 2, 1, 0); 
var {L}ElemCount, I : Integer;
    P, Q : PByte;
begin
  if BufSize <= 0 then
    HugeWordAssignZero(A)
  else
    begin
      {L}ElemCount := (BufSize{Bytes} + HugeWordElementSize{Bytes} - 1) div HugeWordElementSize{Bytes};
      HugeWordSetSize_NoZeroMem(A, {L}ElemCount);
      //* Copy number of BufSize bytes from Buf to A.Data
      P := @Buf;
      Q := A.Data;
      if ReverseByteOrder then
        Inc(P, BufSize{Bytes} - 1);
      //* For example BufSize = 3, ElemCount = 1, this is a 4 byte buffer. 
      //* It copies bytes at position 0, 1, 2 
      for I := 0 to BufSize{Bytes} - 1 do
        begin
          Q^ := P^;
          Inc(Q);
          if ReverseByteOrder then
            Dec(P)
          else
            Inc(P);
        end;
      //* Fill the remaining bytes with zeroes in A.Data
(* Original code
      //* In the above example, Q points to position 3, and the cycle should run once.
      //* But 3 mod 4 - 1 = 2, and the cycle will run 3 times, causing memory corruption above the allocated buffer.
      for I := 0 to BufSize{Bytes} mod 4{HugeWordElementSize} - 1 do
        begin
          Q^ := 0; 
          Inc(Q);
        end;
*)
      //*  Modified code
      for I := 0 to FillCount[BufSize{Bytes} mod HugeWordElementSize] do
        begin
          Q^ := 0; 
          Inc(Q);
        end;
    end;
end;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions