2011-02-11

Valgrind checking of iOS programs

Well, this is awesome news. First, valgrind has been available for OS X for some time now. And second, you can use it to check your iOS programs on the simulator with it.

The idea here is to let your program spawn valgrind itself. Because you cannot tell the simulator to run the program through valgrind. Well, maybe you could build a funky bundle, but I think this works just fine. So here is the  code, taken from the above link:

#define VALGRIND "/usr/local/valgrind/bin/valgrind"
 
int main(int argc, char *argv[]) {
#ifdef VALGRIND_REXEC
    /* Using the valgrind build config, rexec ourself
     * in valgrind */
    if (argc < 2 || (argc >= 2 && strcmp(argv[1], "-valgrind") != 0)) {
        execl(VALGRIND, VALGRIND, "--leak-check=full", "--dsymutil=yes", argv[0], "-valgrind",
              NULL);
    }
#endif
  
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, @"PeepsAppDelegate");
    [pool release];
    return retVal;
}

You will obviously want to define the VALGRIND_REXEC macro, if you need valgrind output. You can also pass different command line arguments to valgrind. E.g. you can switch to different valgrind tools this way, or pipe everything to a log-file.
Update: I finally got around to trying out this method. One problem here is that valgrind will fail to run, since it tries to open /dev/random, which I guess is not allowed for sandboxed applications. But one can fix this by patching and recompiling valgrind, which is not too hard. Especially when using MacPorts. Furthermore, I needed to add --dsymutil=yes to the valgrind options, or else the program would just crash.

6 comments:

  1. Does this still work with Xcode 4.x ?

    ReplyDelete
  2. I don't know why it shouldn't. Only one way to find out!

    I didn't need this since when I posted this. The Apple Instruments may also have gotten better and more useful.

    ReplyDelete
  3. error: address doesn't contain a section that points to a section in a object file

    ReplyDelete
  4. I'm having the exact same problem as @aiks. Anyone solved this already?

    ReplyDelete
  5. Since Apple Instruments got a lot better in the last two years, I suggest trying it first, before attempting to use Valgrind... It seems much to cumbersome these days...

    ReplyDelete
  6. The idea is very cool.

    ReplyDelete