4

I have a server written in c++ that leaks Mach ports when run on osx. Specifically, when running top I noticed that it had around 50000 (under #PORTS) . Curiously, I left it running overnight and the next day the machine was basically dead (took 15min to respond to ctrl-c, wasn't accepting new ssh connections) so IT had to restart it. Could such a leak bring down the system like this? It wasn't running as root.

Anyway ,what are some good strategies for searching for the cause of this kind of leak? Are there any good tools?

I've found one test that when run reliably leaks 5 ports, but that's about it.

Edit: I've found that our thread class creates a mach port leak, but I don't understand why. In the constructor, we have the following code:

// Initialize the default attributes.
if (0 != pthread_attr_init(&m_threadAttributes))
{
    throw "blah";
}

// Set the thread to be joinable.
if (0 != pthread_attr_setdetachstate(&m_threadAttributes, PTHREAD_CREATE_JOINABLE))
{
    pthread_attr_destroy(&m_threadAttributes);
    throw "blah";
}

if (0 != pthread_create(
            &m_thread, 
            &m_threadAttributes, 
            &StartThreadFunction, 
            reinterpret_cast<void*>(this)))
{
    throw "blah";
}

And I notice the port count for the process goes up by one after the call to pthread_create, which is expected.

Then, later on I join the thread with the following code:

if (0 != pthread_join(m_thread, NULL))
{
    throw "blah";
}

And no exception is thrown, so I can only assume pthread_join returned 0 and thus succeeded, but the # of ports in top doesn't go down. Is there anything else I need to do to clean up a thread?

Bwmat
  • 4,314
  • 3
  • 27
  • 42

1 Answers1

2

You can use Dtrace to instrument the mach port usage on a running system. There are a number of mach_port related probes:

sudo dtrace -l | grep mach_port

You can write a Dtrace script that tracks wether each each port creation or retain call is balanced by a corresponding release. Dtrace scripts for tracking memory leaks would be a useful starting point.

Once you have a script that is working for your purposes you can use Instruments to control the trace session and graph the results.

quellish
  • 21,123
  • 4
  • 76
  • 83