I've developed this little C++ program for Linux
#include <iostream>
#include <vector>
#include <string>
#include <link.h>
#include <climits>
#include <dlfcn.h>
using namespace std;
template<typename Fn>
requires requires( Fn fn, dl_phdr_info *image, size_t n ) { { fn( image, n ) } -> same_as<int>; }
int dlIteratePhdr( Fn &&fn )
{
return dl_iterate_phdr(
[]( dl_phdr_info *image, size_t size, void *pFn ) -> int
{
return (*(Fn *)pFn)( image, size );
}, &fn );
};
int main()
{
size_t nImages = 0;
dlIteratePhdr( [&]( dl_phdr_info *, size_t ) -> int { ++nImages; return 0; } );
vector<string> images;
images.reserve( nImages );
if( dlIteratePhdr(
[&]( dl_phdr_info *image, size_t ) -> int
{
try
{
images.emplace_back( image->dlpi_name );
return 0;
}
catch( ... )
{
return 1;
}
} ) )
return EXIT_FAILURE;
for( string const &image : images )
cout << "\"" << image << "\"" << endl;
}
For my Ubuntu machine this prints:
""
"linux-vdso.so.1"
"/lib/x86_64-linux-gnu/libstdc++.so.6"
"/lib/x86_64-linux-gnu/libgcc_s.so.1"
"/lib/x86_64-linux-gnu/libc.so.6"
"/lib/x86_64-linux-gnu/libm.so.6"
"/lib64/ld-linux-x86-64.so.2"
Why is the name of the first image empty ?
Is this reserved for the executable itself ?
And is it really necessary to copy the information given to the callback or would this be alive after dl_iterate_phdr ?