Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HugeWordAssignBuf() memory corruption bug #42

Open
sztdevel opened this issue Jan 6, 2023 · 0 comments
Open

HugeWordAssignBuf() memory corruption bug #42

sztdevel opened this issue Jan 6, 2023 · 0 comments

Comments

@sztdevel
Copy link

sztdevel commented Jan 6, 2023

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant