discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Swizzling Alloc


From: Richard Frith-Macdonald
Subject: Re: Swizzling Alloc
Date: Sun, 30 May 2021 19:17:30 +0100


> On 30 May 2021, at 17:59, Gustavo Tavares <mucholove@fastmail.com> wrote:
> 
> Hi All,
> 
> So—I am trying to use swizzling for my first ever and my goal is to swizzle 
> `alloc`. Why? I want to run a unqiued counter of where my objects are 
> allocated by analyzing the call stack symbols. Sort of like Valgrind so that 
> I can see where my program is leaking data—but I figured since I don't know 
> how to parse Valgrind Objective-C might be an easier way to get something 
> very similar.
> 
> Unfortunately when I follow this guide to swizzle the methods—I am getting a 
> segmentation fault. 
> https://newrelic.com/blog/best-practices/right-way-to-swizzle
> 
> He basically tell me to do: 
>> 
>>         id gtkDebugAlloc(id self, SEL cmd) { .... } 
>> 
>>         {
>>              Method nsObjectAllocMethod = class_getClassMethod([NSObject 
>> class], @selector(alloc));
>>              IMP orginalAlloc = 
>> method_setImplementation(nsObjectAllocMethod,(IMP)gtkDebugAlloc);
>>         }

That looks fine, and works for me.
So ... if you are getting a segmentation violation, it's probably 
occurring-in/caused-by your gtkDebugAlloc function (which must of course 
allocate and return suitable memory).

Try this:

static IMP originalAlloc;
static id gtkDebugAlloc(id self, SEL cmd)
{
  fprintf(stderr, "Here I am\n");
  return (*originalAlloc)(self, cmd);
}

// then later on 
{    
     Method nsObjectAllocMethod = class_getClassMethod([NSObject class], 
@selector(alloc));     
     originalAlloc = 
method_setImplementation(nsObjectAllocMethod,(IMP)gtkDebugAlloc);
}


You should see 'Here I am' printed whenever an object is allocated.

I suspect it's hard to beat valgrind at this (because parsing the stack and 
storing counts of allocations at particular locations is hard to do), but if 
you suceed in writing an efficient yool for that, it would be great.





reply via email to

[Prev in Thread] Current Thread [Next in Thread]