Delphi Assembler/RTTI-gurus: Can I obtain the memory address and type info of the implied Result variable in a function?

StackOverflow https://stackoverflow.com/questions/10819770

  •  11-06-2021
  •  | 
  •  

Question

Consider this typical code for method tracing (simplified for illustration):

type
  IMethodTracer = interface
  end;

  TMethodTracer = class(TInterfacedObject, IMethodTracer)
  private
    FName: String;
    FResultAddr: Pointer;
    FResultType: PTypeInfo;
  public
    constructor Create(
      const AName: String;
      const AResultAddr: Pointer = nil;
      const AResultType: PTypeInfo = nil);
    destructor Destroy; override;
  end;

constructor TMethodTracer.Create(
  const AName: String;
  const AResultAddr: Pointer;
  const AResultType: PTypeInfo);
begin
  inherited Create();
  FName := AName;
  FResultAddr := AResultAddr;
  FResultType := AResultType;
  Writeln('Entering ' + FName);
end;

destructor TMethodTracer.Destroy;
var
  lSuffix: String;
  lResVal: TValue;
begin
  lSuffix := '';
  if FResultAddr <> nil then
    begin
      //there's probably a more straight-forward to doing this, without involving TValue:
      TValue.Make(FResultAddr, FResultType, lResVal);
      lSuffix := ' - Result = ' + lResVal.AsString;
    end;
  Writeln('Leaving ' + FName + lSuffix);

  inherited Destroy;
end;

function TraceMethod(
  const AName: String;
  const AResultAddr: Pointer;
  const AResultType: PTypeInfo): IMethodTracer;
begin
  Result := TMethodTracer.Create(AName, AResultAddr, AResultType);
end;

//////

function F1: String;
begin
  TraceMethod('F1', @Result, TypeInfo(String));
  Writeln('Doing some stuff...');
  Result := 'Booyah!';
end;

F1();

This is working as intended. The output is:

Entering F1
Doing some stuff...
Leaving F1 - Result = Booyah!

I am now looking for a way to minimize the number of required parameters for the call to TraceMethod(), ideally allowing me to skip the Result-related arguments altogether. I have no experience with assembler or stack layout myself but If I am not mistaken, judging by the "magic" I have seen other people do, at least the memory address of the implied magic Result-variable should be obtainable somehow, shouldn't it? And possibly one can work from there to get at its type info, too?

Of course, if it were possible to even determine the name of the "surrounding" function itself that would eliminate the need for passing arguments to TraceMethod entirely...

I am using Delphi XE2, so all recently introduced language/framework features can be used.

And before anyone mentions it: My actual code already uses CodeSite.EnterMethod/ExitMethod instead of Writeln-calls. I am also aware that this simplified example cannot handle complex types and performs no error handling whatsoever.

Was it helpful?

Solution

Your best bet is truly to just pass in @Result. If you don't, then there's no guarantee that Result even has an address. Functions returning simple types like Integer and Boolean put the result in the EAX register. If there's no reason for the result to have an address, then the compiler won't allocate any memory for it. Using the expression @Result forces the compiler to give it an address.

Merely knowing the address won't get you the return type, though. There might be a way to discover it with RTTI. It would involve three steps:

  1. Extract the class name from the method name. Then you can get the RTTI for that type. This would require the method name to include an unambiguous name for the class (including unit name).

  2. Using the list of methods from that type, find the RTTI for the method. This will be complicated by the fact that the name doesn't necessarily uniquely identify a method. Overloads will all show the same name. (Rruz showed how to deal with RTTI of overloaded methods in the context of the Invoke method.) Also, the method name you get from the debug info won't necessarily match the RTTI name.

    Instead of trying to match the name, you could instead loop over all the class's methods, searching for the one whose CodeAddress property matches the address of the caller. Determining how to get the address of the start of the caller (instead of the return address) is proving more difficult to find than I expected, though.

  3. Get the method's return type and use the Handle property to finally get the PTypeInfo value you want.

OTHER TIPS

Some of this feature is already included in our TSynLog class, which works from Delphi 5 up to XE2.

It is full Open Source, and working with Delphi XE2, so you have all the needed source code at hand. And it features exception interception and stack trace.

It allows coding trace like this:

procedure TestPeopleProc;
var People: TSQLRecordPeople;
    Log: ISynLog;
begin
  Log := TSQLLog.Enter;
  People := TSQLRecordPeople.Create;
  try
    People.ID := 16;
    People.FirstName := 'Louis';
    People.LastName := 'Croivébaton';
    People.YearOfBirth := 1754;
    People.YearOfDeath := 1793;
    Log.Log(sllInfo,People);
  finally
    People.Free;
  end;
end;

It will be logged as such:

20120520 13172261  +    000E9F67 SynSelfTests.TestPeopleProc (784)
20120520 13172261 info      {"TSQLRecordPeople(00AB92E0)":{"ID":16,"FirstName":"Louis","LastName":"Croivébaton","Data":"","YearOfBirth":1754,"YearOfDeath":1793}}
20120520 13172261   -    000EA005 SynSelfTests.TestPeopleProc (794) 00.002.229

That is:

  • You have the line numbers and the method name;
  • You have the exact time consummed within the method (00.002.229);
  • It is very easy to display any result (here, the class is even serialized as JSON directly, and you can do the same with any kind of data, even records);
  • Methods can be nested, and there is also a profiling tool available in our log viewer - that is, you can retrieve in which methods the most time is spent, on the customer side, from the log file;
  • You can add a stack trace, or whatever information you want, very easily;
  • Our code is very optimized for speed: e.g. it uses an interface for the "auto-leave" function, just like you, but it won't make any memory allocation, since it uses a "fake reference count" trick;
  • Of course, defining a Log variable on the stack is optional: if you need only to trace the Enter/Leave of the method, just writing TSQLLog.Enter is enough. The Log local variable is used to easily nest additional information within the method (Log.Log(sllInfo,People)).

Note that the debugging information (i.e. the method name and line numbers) are retrieved from a proprietary very optimized binary conversion of the .map file generated at compile time. It will be much smaller than the .map itself (e.g. 900 KB .map -> 70 KB .mab which can be easily embedded within the exe), therefore smaller than the format used by JCL or MadExcept, and also smaller than the information embedded at compile time by Delphi.

I do not think that having the "result" hard-coded within the "Enter" method is worth it. It will add a lot of coding (e.g. the conversion to TValue is time consuming), for a negligible benefit - most of the time, you'll need to know much more than the result content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top