Can I use dl_iterate_phdr to monitor an exec process?

Issue

I would like to get the base address of a process that I am calling with execl such as in the following code.

Does the approach make any sense?

#include <stdio.h>
#define __USE_GNU
#include <link.h>

int callback(struct dl_phdr_info *info, size_t size, void *data)
{
    printf("name: '%s'  base:'%lu'\n", info->dlpi_name, info->dlpi_addr);
    return 0;
}
int main()
{
    dl_iterate_phdr(callback, NULL);
    execl("/usr/bin/ls", "ls", NULL);
}

My worry is that since its a callback it will get erased when execl is called. Hence a race condition as to how many callbacks will be called.

Solution

I would like to get the base address of a process that I am calling with excel such as in the following code.

The following code will not work — dl_iterate_phdr() can only examine the process it is running in. By the time execl() starts running the new binary, all traces of the current process are gone and replaced with the new binary.

My worry is that since its a callback it will get erased when execl is called. Hence a race condition as to how many callbacks will be called.

Your worry is misplaced: the dl_iterate_ohdr() is a synchronous function. It completes (and executes all the calls to callback) before you reach the execl.

The only way you can monitor execld process is by using ptrace on it (as debuggers and strace do).

Answered By – Employed Russian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published