Link to home
Start Free TrialLog in
Avatar of circler
circlerFlag for Lebanon

asked on

Reading/Writing into PE section

Hey there,

I am trying to write something into a new section of an executable, let's say the name of the section is .bla, I need to a function write a string buffer there.. then using a different function I need to read a buffer from this section..
P.S: I only need to use WINAPI in the reading function
Can anyone help me in such a code?

Thanks
Avatar of circler
circler
Flag of Lebanon image

ASKER

bump, no ideas?
Avatar of circler

ASKER

Thanks, I've seen that but it's not what I need :)
which winapi function do you need ? Is this function in the links above ?
Use file mapping (WinAPI: CreateFileMapping) with SEC_IMAGE flag & PE structures from Windows.pas
<skipped>
var
  hPeFile, hPeFileMap: Cardinal;
  pBaseAddress: PByte;
  pDosHeader: PImageDosHeader;
  pNtHeaders: PImageNtHeaders;
  pSectionHeader: PImageSectionHeader;
  dwOffset: Cardinal;
  pSection: Pointer;
  SectName: String;
begin
  hPeFile := CreateFile(PChar(AFileName), GENERIC_READ, FILE_SHARE_READ,
    nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if (hPeFile = INVALID_HANDLE_VALUE) then
    Exit;
 
  hPeFileMap := CreateFileMapping(hPeFile, nil, PAGE_READONLY or SEC_IMAGE,
    0, 0, nil);
  if (hPeFileMap = 0) then
  begin
    CloseHandle(hPeFile);
    Exit;
  end;
 
  pBaseAddress := MapViewOfFile(hPeFileMap, FILE_MAP_READ, 0, 0, 0);
  if (pBaseAddress = nil) then
  begin
    CloseHandle(hPeFileMap);
    CloseHandle(hPeFile);
    Exit;
  end;
 
  dwOffset := Cardinal(pBaseAddress);
  pDosHeader := PImageDosHeader(pBaseAddress);
  pNtHeaders := PImageNtHeaders(dwOffset + pDosHeader._lfanew);
 
  // Get sections info
  pSectionHeader := pImageSectionHeader(Cardinal(pNtHeaders) + SizeOf(TImageNtHeaders));
  for i := 1 to pNtHeaders.FileHeader.NumberOfSections do
  begin
    SetString(SectName, PChar(@pSectionHeader.Name), SizeOf(pSectionHeader.Name));
    SectName := Trim(SectName);
 
    pSection := Pointer(dwOffset + pSectionHeader.VirtualAddress);
    if (AnsiLowerCase(SectName) = '.bla') then
    begin
      // ToDo: Get your buffer here!
    end;
  end;
 
  // Don't forget to free resources & close all handles
</skipped>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of cebasso
cebasso
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of aikimark
@circler

What is the context for this problem?
Why limit the reading of the file to Win API and not native Delphi I/O statements?
I think the cebasso comment, http:#26397197 should be accepted as the solution.