Skip to content

Commit

Permalink
Fix calculation of base address for dylib
Browse files Browse the repository at this point in the history
  • Loading branch information
xoofx committed Dec 15, 2024
1 parent a826459 commit ce1b0e2
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions src/Ultra.Sampler/MacOS/MacOSUltraSampler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ private void AddModuleEvent(NativeModuleEventKind kind, nint loadAddress)
var path = MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)info.dli_fname);
evt.Path = path.ToArray();
evt.TimestampUtc = DateTime.UtcNow;
evt.Size = GetMaximumCodeAddress(loadAddress);
evt.Size = GetDyldCodeSize(loadAddress);

lock (_moduleEventLock)
{
Expand Down Expand Up @@ -197,9 +197,9 @@ private static bool TryGetUuidFromMacHeader(nint headerPtr, out Guid guid)
return false;
}

private static ulong GetMaximumCodeAddress(nint headerPtr)
private static ulong GetDyldCodeSize(nint headerPtr)
{
ulong startAddress = 0;
ulong startAddress = ulong.MaxValue;

ulong size = 0;
var header = (MacOSLibSystem.mach_header_64*)headerPtr;
Expand All @@ -213,22 +213,30 @@ private static ulong GetMaximumCodeAddress(nint headerPtr)
if (command.cmd == MacOSLibSystem.LC_SEGMENT_64)
{
ref var segment = ref Unsafe.As<MacOSLibSystem.load_command,MacOSLibSystem.segment_command_64>(ref command);
if (segment.vmaddr != 0)
if (segment.vmaddr < startAddress)
{
if (startAddress == 0)
{
startAddress = segment.vmaddr;
}

var newSize = (ulong)((long)segment.vmaddr + (long)segment.vmsize - (long)startAddress);
if (newSize > size)
{
size = newSize;
}
startAddress = segment.vmaddr;
}
}
}

if (startAddress == ulong.MaxValue) return 0;

for (uint i = 0; i < nbCommands; i++)
{
ref var command = ref commands[i];
if (command.cmd == MacOSLibSystem.LC_SEGMENT_64)
{
ref var segment = ref Unsafe.As<MacOSLibSystem.load_command, MacOSLibSystem.segment_command_64>(ref command);

var newSize = (ulong)((long)segment.vmaddr + (long)segment.vmsize - (long)startAddress);
if (newSize > size)
{
size = newSize;
}
}
}

return size;
}

Expand Down

0 comments on commit ce1b0e2

Please sign in to comment.