1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
  
     | 
    
      unit FpImgReaderBase;
{$mode objfpc}{$H+}
{$IFDEF INLINE_OFF}{$INLINE OFF}{$ENDIF}
{$modeswitch advancedrecords}
interface
{$ifdef CD_Cocoa}{$DEFINE MacOS}{$ENDIF}
{$IFDEF Darwin}{$DEFINE MacOS}{$ENDIF}
uses
  {$ifdef windows}
  Windows, // After LCLType
  {$endif}
  fgl, LazFglHash, LazFileUtils, LazLoggerBase,
  fpDbgSymTable,
  Classes, SysUtils, DbgIntfBaseTypes, contnrs,
  FpDbgCommon, crc;
type
  TDbgImageSection = record
    RawData: Pointer;
    Size: QWord;
    VirtualAddress: QWord;
    // Use this flag to identify sections that should be uploaded via RSP
    // This is probably only relevant for uploads to low level targets (embedded, FreeRTOS...)
    IsLoadable: Boolean;
    Name: String;
  end;
  PDbgImageSection = ^TDbgImageSection;
  TDbgImageSectionEx = record
    Sect: TDbgImageSection;
    Offs: QWord;
    Loaded: Boolean;
  end;
  PDbgImageSectionEx = ^TDbgImageSectionEx;
type
  TDbgAddressMap = record
    OrgAddr: QWord;
    Length: QWord;
    NewAddr: QWord;
    class operator =(r1,r2: TDbgAddressMap) : boolean;
  end;
  PDbgAddressMap = ^TDbgAddressMap;
  TDbgAddressMapList = specialize TFPGList<TDbgAddressMap>;
  { TDbgAddressMapHashList }
  TDbgAddressMapHashList = class(specialize TLazFPGHashTable<TDbgAddressMap>)
  public
    function ItemFromNode(ANode: THTCustomNode): TDbgAddressMap;
    function ItemPointerFromNode(ANode: THTCustomNode): PDbgAddressMap;
  end;
  { TDbgAddressMapPointerHashList }
  TDbgAddressMapPointerHashList = class(specialize TLazFPGHashTable<PDbgAddressMap>)
  public
    function ItemPointerFromNode(ANode: THTCustomNode): PDbgAddressMap;
  end;
  { TDbgFileLoader }
  {$ifdef windows}
    {$define USE_WIN_FILE_MAPPING}
  {$endif}
  TDbgFileLoader = class(TObject)
  private
    {$ifdef USE_WIN_FILE_MAPPING}
    FFileHandle: THandle;
    FMapHandle: THandle;
    FModulePtr: Pointer;
    {$else}
    FStream: TStream;
    FList: TList;
    {$endif}
    FFileName: String;
    function GetFileName: String;
  public
    constructor Create(AFileName: String);
    {$ifdef USE_WIN_FILE_MAPPING}
    constructor Create(AFileHandle: THandle);
    {$endif}
    destructor Destroy; override;
    procedure Close;
    function  Read(AOffset, ASize: QWord; AMem: Pointer): QWord;
    function  LoadMemory(AOffset, ASize: QWord; out AMem: Pointer): QWord;
    procedure UnloadMemory({%H-}AMem: Pointer);
    property FileName: String read GetFileName;
  end;
  { TDbgImageReader }
  TDbgImageReader = class(TObject) // executable parser
  private
    FImageBase: QWord;
    FImageSize: QWord;
    FRelocationOffset: QWord;
    FLoadedTargetImageAddr: TDBGPtr;
    FReaderErrors: String;
    FUUID: TGuid;
  protected
    FTargetInfo: TTargetDescriptor;
    function GetSubFiles: TStrings; virtual;
    function GetAddressMapList: TDbgAddressMapList; virtual;
    function GetSection(const AName: String): PDbgImageSection; virtual; abstract;
    function GetSection(const ID: integer): PDbgImageSection; virtual; abstract;
    procedure SetUUID(AGuid: TGuid);
    procedure SetImageBase(ABase: QWord);
    procedure SetImageSize(ASize: QWord);
    procedure SetRelocationOffset(AnOffset: QWord);
    procedure AddReaderError(AnError: String);
    function  ReadGnuDebugLinkSection(out AFileName: String; out ACrc: Cardinal): Boolean;
    function  LoadGnuDebugLink(ASearchPath, AFileName: String; ACrc: Cardinal): TDbgFileLoader;
    property LoadedTargetImageAddr: TDBGPtr read FLoadedTargetImageAddr;
  public
    class function isValid(ASource: TDbgFileLoader): Boolean; virtual; abstract;
    class function UserName: AnsiString; virtual; abstract;
    procedure ParseSymbolTable(AFpSymbolInfo: TfpSymbolList); virtual;
    procedure ParseLibrarySymbolTable(AFpSymbolInfo: TfpSymbolList); virtual;
    // The LoadedTargetImageAddr is the start-address of the data of the binary
    // once loaded into memory.
    // On Linux it is 0 for executables, and had another value for libraries
    // which are relocated into another position.
    // On Windows it is the same as the ImageBase, except when the binary has
    // been relocated. This only happens if two libraries with the same ImageBase
    // are loaded. In that case, one of them is being relocated to another
    // LoadedTargetImageAddr.
    constructor Create({%H-}ASource: TDbgFileLoader; {%H-}ADebugMap: TObject; ALoadedTargetImageAddr: TDbgPtr; OwnSource: Boolean); virtual;
    procedure AddSubFilesToLoaderList(ALoaderList: TObject; PrimaryLoader: TObject); virtual;
    function EnclosesAddressRange(AStartAddress, AnEndAddress: TDBGPtr): Boolean; virtual;
    // The ImageBase is the address at which the linker assumed the binary will be
    // loaded at. So it is stored inside the binary itself and all addresses inside
    // the binary assume that once loaded into memory, it is loaded at this
    // address. (Which is not the case for relocated libraries, see the comments
    // for the LoadedTargetImageAddr)
    // On Linux it is always 0, on Windows it is set by the linker/compiler.
    property ImageBase: QWord read FImageBase;
    property ImageSize: QWord read FImageSize;
    // The RelocationOffset is the offset between the addresses as they are encoded
    // into the binary, and their real addresses once loaded in memory.
    // On linux it is equal to the LoadedTargetImageAddr.
    // On Windows it is 0, except for libraries which are re-located. In that
    // case the offset is LoadedTargetImageAddr-ImageBase.
    property RelocationOffset: QWord read FRelocationOffset;
    property TargetInfo: TTargetDescriptor read FTargetInfo;
    property UUID: TGuid read FUUID;
    property Section[const AName: String]: PDbgImageSection read GetSection;
    property SectionByID[const ID: integer]: PDbgImageSection read GetSection;
    property SubFiles: TStrings read GetSubFiles;
    property AddressMapList: TDbgAddressMapList read GetAddressMapList;
    property ReaderErrors: String read FReaderErrors;
  end;
  TDbgImageReaderClass = class of TDbgImageReader;
function GetImageReader(ASource: TDbgFileLoader; ADebugMap: TObject; ALoadedTargetImageAddr: TDbgPtr; OwnSource: Boolean): TDbgImageReader; overload;
procedure RegisterImageReaderClass(DataSource: TDbgImageReaderClass);
implementation
var
  DBG_WARNINGS: PLazLoggerLogGroup;
const
  // Symbol-map section name
  _gnu_dbg_link        = '.gnu_debuglink';
var
  RegisteredImageReaderClasses  : TFPList;
{ TDbgAddressMapPointerHashList }
function TDbgAddressMapPointerHashList.ItemPointerFromNode(ANode: THTCustomNode
  ): PDbgAddressMap;
begin
  Result := THTGNode(ANode).Data;
end;
{ TDbgAddressMapHashList }
function TDbgAddressMapHashList.ItemFromNode(ANode: THTCustomNode
 ): TDbgAddressMap;
begin
  Result := THTGNode(ANode).Data;
end;
function TDbgAddressMapHashList.ItemPointerFromNode(ANode: THTCustomNode
  ): PDbgAddressMap;
begin
  Result := @THTGNode(ANode).Data;
end;
 class operator TDbgAddressMap.=(r1,r2: TDbgAddressMap) : boolean;
 begin
   result := (r1.OrgAddr=r2.OrgAddr) and (r1.Length=r2.Length) and (r1.NewAddr=r2.NewAddr);
 end;
function GetImageReader(ASource: TDbgFileLoader; ADebugMap: TObject; ALoadedTargetImageAddr: TDbgPtr; OwnSource: Boolean): TDbgImageReader;
var
  i   : Integer;
  cls : TDbgImageReaderClass;
begin
  Result := nil;
  if not Assigned(ASource) then Exit;
  for i := 0 to RegisteredImageReaderClasses.Count - 1 do begin
    cls :=  TDbgImageReaderClass(RegisteredImageReaderClasses[i]);
    try
      if cls.isValid(ASource) then begin
        Result := cls.Create(ASource, ADebugMap, ALoadedTargetImageAddr, OwnSource);
        ASource.Close;
        Exit;
      end
      else
        ;
    except
      on e: exception do begin
        //writeln('exception! WHY? ', e.Message);
      end;
    end;
  end;
  ASource.Close;
  Result := nil;
end;
procedure RegisterImageReaderClass( DataSource: TDbgImageReaderClass);
begin
  if Assigned(DataSource) and (RegisteredImageReaderClasses.IndexOf(DataSource) < 0) then
    RegisteredImageReaderClasses.Add(DataSource)
end;
{$ifdef USE_WIN_FILE_MAPPING}
type
  TGetFinalPathNameByHandle = function(hFile: THandle; lpszFilePath: PWideChar; cchFilePath, dwFlags: DWORD): DWORD; stdcall;
var
  GetFinalPathNameByHandle: TGetFinalPathNameByHandle = nil;
function GetFinalPathNameByHandleDummy(hFile: THandle; lpszFilePath: PWideChar; cchFilePath, dwFlags: DWORD): DWORD; stdcall;
begin
  Result := 0;
end;
function FileHandleToFileName(Handle : THandle): string;
var
  U: WideString;
  hmod: HMODULE;
begin
  if not Assigned(GetFinalPathNameByHandle) then
  begin
    hmod := GetModuleHandle('kernel32');
    if hmod <> 0 then
      Pointer(GetFinalPathNameByHandle) := GetProcAddress(hmod,'GetFinalPathNameByHandleW');
    if not Assigned(GetFinalPathNameByHandle) then
      GetFinalPathNameByHandle := @GetFinalPathNameByHandleDummy;
  end;
  SetLength(U, MAX_PATH+1);
  SetLength(U, GetFinalPathNameByHandle(Handle, @U[1], Length(U), 0));
  if Copy(U, 1, 4)='\\?\' then
    Delete(U, 1, 4);
  Result := U;
end;
{$endif}
{ TDbgFileLoader }
{$ifdef USE_WIN_FILE_MAPPING}
function CreateFileW(lpFileName:LPCWSTR; dwDesiredAccess:DWORD; dwShareMode:DWORD; lpSecurityAttributes:LPSECURITY_ATTRIBUTES; dwCreationDisposition:DWORD;dwFlagsAndAttributes:DWORD; hTemplateFile:HANDLE):HANDLE; stdcall; external 'kernel32' name 'CreateFileW';
{$ENDIF}
function TDbgFileLoader.GetFileName: String;
begin
  {$ifdef USE_WIN_FILE_MAPPING}
  if (FFileName = '') and (FFileHandle <> 0) then begin
    FFileName := FileHandleToFileName(FFileHandle);
  end;
  {$endif}
  Result := FFileName;
end;
constructor TDbgFileLoader.Create(AFileName: String);
{$IFDEF MacOS}
var
  s: String;
{$ENDIF}
{$ifdef USE_WIN_FILE_MAPPING}
var
  s: UnicodeString;
{$ENDIF}
begin
  {$ifdef USE_WIN_FILE_MAPPING}
  FFileName := AFileName;
  s := UTF8Decode(AFileName);
  FFileHandle := CreateFileW(PWideChar(s), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  Create(FFileHandle);
  {$else}
  FList := TList.Create;
  {$IFDEF MacOS}
  if (RightStr(AFileName,4) = '.app') then begin
    s := ExtractFileName(AFileName);
    s := AFileName + PathDelim + 'Contents' + PathDelim + 'MacOS' + PathDelim + copy(s, 1, Length(s) - 4);
    if (FileExists(s)) then AFileName := s
  end;
  {$ENDIF}
  FFileName := AFileName;
  FStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone);
  inherited Create;
  {$endif}
end;
{$ifdef USE_WIN_FILE_MAPPING}
constructor TDbgFileLoader.Create(AFileHandle: THandle);
begin
  FFileHandle := AFileHandle;
  if FFileHandle = INVALID_HANDLE_VALUE
  then begin
    raise Exception.Create('Invalid file handle');
  end;
  FMapHandle := CreateFileMapping(FFileHandle, nil, PAGE_READONLY{ or SEC_IMAGE}, 0, 0, nil);
  if FMapHandle = 0
  then begin
    raise Exception.CreateFmt('Could not create module mapping, error %d', [GetLastError]);
    Exit;
  end;
  FModulePtr := MapViewOfFile(FMapHandle, FILE_MAP_READ, 0, 0, 0);
  if FModulePtr = nil
  then begin
    raise Exception.Create('Could not map view: ' + IntToStr(GetLastOSError));
    Exit;
  end;
  inherited Create;
end;
{$endif}
destructor TDbgFileLoader.Destroy;
begin
  {$ifdef USE_WIN_FILE_MAPPING}
  if FModulePtr <> nil
  then UnmapViewOfFile(FModulePtr);
  if FMapHandle <> 0
  then CloseHandle(FMapHandle);
  if FFileHandle <> INVALID_HANDLE_VALUE
  then CloseHandle(FFileHandle);
  {$else}
  while FList.Count > 0 do
    UnloadMemory(FList[0]);
  FreeAndNil(FList);
  FreeAndNil(FStream);
  inherited Destroy;
  {$endif}
end;
procedure TDbgFileLoader.Close;
begin
  {$ifNdef USE_WIN_FILE_MAPPING}
  FreeAndNil(FStream);
  {$endif}
end;
function TDbgFileLoader.Read(AOffset, ASize: QWord; AMem: Pointer): QWord;
begin
  {$ifdef USE_WIN_FILE_MAPPING}
  move((FModulePtr + AOffset)^, AMem^, ASize);
  Result := ASize;
  {$else}
  Result := 0;
  if AMem = nil then
    exit;
  if FStream = nil then
    FStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyNone);
  FStream.Position := AOffset;
  Result := FStream.Read(AMem^, ASize);
  {$endif}
end;
function TDbgFileLoader.LoadMemory(AOffset, ASize: QWord; out AMem: Pointer): QWord;
begin
  {$ifdef USE_WIN_FILE_MAPPING}
  AMem := FModulePtr + AOffset;
  Result := ASize;
  {$else}
  Result := 0;
  AMem := AllocMem(ASize);
  if AMem = nil then
    exit;
  if FStream = nil then
    FStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyNone);
  FList.Add(AMem);
  FStream.Position := AOffset;
  Result := FStream.Read(AMem^, ASize);
  {$endif}
end;
procedure TDbgFileLoader.UnloadMemory(AMem: Pointer);
begin
  {$ifdef USE_WIN_FILE_MAPPING}
  {$else}
  FList.Remove(AMem);
  Freemem(AMem);
  {$endif}
end;
{ TDbgImageReader }
function TDbgImageReader.GetAddressMapList: TDbgAddressMapList;
begin
  result := nil;
end;
function TDbgImageReader.GetSubFiles: TStrings;
begin
  result := nil;
end;
procedure TDbgImageReader.SetUUID(AGuid: TGuid);
begin
  FUUID := AGuid;
end;
procedure TDbgImageReader.SetImageBase(ABase: QWord);
begin
  FImageBase := ABase;
  if FLoadedTargetImageAddr = 0 then
    FLoadedTargetImageAddr := ABase;
end;
procedure TDbgImageReader.SetImageSize(ASize: QWord);
begin
  FImageSize := ASize;
end;
procedure TDbgImageReader.SetRelocationOffset(AnOffset: QWord);
begin
  FRelocationOffset := AnOffset;
end;
procedure TDbgImageReader.AddReaderError(AnError: String);
begin
  if FReaderErrors <> '' then
    FReaderErrors := FReaderErrors + LineEnding;
  FReaderErrors := FReaderErrors + AnError;
end;
function TDbgImageReader.ReadGnuDebugLinkSection(out AFileName: String; out
  ACrc: Cardinal): Boolean;
var
  p: PDbgImageSectionEx;
  i: Integer;
begin
  p := PDbgImageSectionEx(Section[_gnu_dbg_link]);
  Result := p <> nil;
  if Result then
  begin
    i := IndexByte(p^.Sect.RawData^, p^.Sect.Size-4, 0);
    Result := i > 0;
    if Result then
    begin
      SetLength(AFileName, i);
      move(PDbgImageSectionEx(p)^.Sect.RawData^, AFileName[1], i);
      i := align(i+1, 4);
      Result := (i+4) <= p^.Sect.Size;
      if Result then
        move((p^.Sect.RawData+i)^, ACrc, 4);
    end;
  end;
end;
function TDbgImageReader.LoadGnuDebugLink(ASearchPath, AFileName: String;
  ACrc: Cardinal): TDbgFileLoader;
  function LoadFile(AFullName: String): TDbgFileLoader;
  var
    i, j: Int64;
    c: Cardinal;
    mem: Pointer;
  begin
    Result := TDbgFileLoader.Create(AFullName);
    i := FileSizeUtf8(AFullName) - 4096;
    j := 0;
    c:=0;
    while j < i do begin
      Result.LoadMemory(j, 4096, mem);
      c:=Crc32(c, mem, 4096);
      Result.UnloadMemory(mem);
      inc(j, 4096)
    end;
    i := i - j + 4096;
    Result.LoadMemory(j, i, mem);
    c:=Crc32(c, mem, i);
    Result.UnloadMemory(mem);
    DebugLn(DBG_WARNINGS and (c <> ACrc), ['Invalid CRC for ext debug info: ', AFullName]);
    if c <> ACrc then
      FreeAndNil(Result);
  end;
begin
  Result := nil;
  if FileExists(AppendPathDelim(ASearchPath) + AFileName) then
    Result := LoadFile(AppendPathDelim(ASearchPath) + AFileName);
  if (Result = nil) and
     FileExists(AppendPathDelim(ASearchPath) + AppendPathDelim('.debug') + AFileName)
  then
    Result := LoadFile(AppendPathDelim(ASearchPath) + AppendPathDelim('.debug') + AFileName);
end;
procedure TDbgImageReader.ParseSymbolTable(AFpSymbolInfo: TfpSymbolList);
begin
  // The format of the symbol-table-section(s) can be different on each
  // platform. That's why parsing the data is done in TDbgImageReader.
end;
procedure TDbgImageReader.ParseLibrarySymbolTable(AFpSymbolInfo: TfpSymbolList);
begin
  //
end;
constructor TDbgImageReader.Create(ASource: TDbgFileLoader; ADebugMap: TObject; ALoadedTargetImageAddr: TDbgPtr; OwnSource: Boolean);
begin
  inherited Create;
  FLoadedTargetImageAddr := ALoadedTargetImageAddr;
end;
procedure TDbgImageReader.AddSubFilesToLoaderList(ALoaderList: TObject;
  PrimaryLoader: TObject);
begin
  //
end;
function TDbgImageReader.EnclosesAddressRange(AStartAddress, AnEndAddress: TDBGPtr): Boolean;
begin
  Result := False;
end;
procedure InitDebugInfoLists;
begin
  RegisteredImageReaderClasses := TFPList.Create;
end;
procedure ReleaseDebugInfoLists;
begin
  FreeAndNil(RegisteredImageReaderClasses);
end;
initialization
  DBG_WARNINGS := DebugLogger.FindOrRegisterLogGroup('DBG_WARNINGS' {$IFDEF DBG_WARNINGS} , True {$ENDIF} );
  InitDebugInfoLists;
finalization
  ReleaseDebugInfoLists;
end.
 
     |