PhoenixDL  1.0.0
Library to manipulate symbols in dynamic libraries
Loading...
Searching...
No Matches
phoenix_dl.cpp
Go to the documentation of this file.
1/***************************************
2 Auteur : Pierre Aubert
3 Mail : pierre.aubert@lapp.in2p3.fr
4 Licence : CeCILL-C
5****************************************/
6
7#include <stdio.h>
8
9// DL includes
10#include <link.h>
11#include <stdlib.h>
12#include <dlfcn.h>
13#include <elf.h>
14
15#include <iostream>
16
17#include "phoenix_dl.h"
18
20
23void phoenix_listLibrarySymbol(std::vector<std::string> & vecFunction, const std::string & libFileName){
24 if(libFileName == ""){return;}
25 void* library = dlopen(libFileName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
26 if(library == NULL){
27 std::cerr << "phoenix_listLibrarySymbol : library '"<<libFileName<<"' not found" << std::endl;
28 return;
29 }
30 struct link_map * map = NULL;
31 dlinfo(library, RTLD_DI_LINKMAP, &map);
32
33 Elf64_Sym * symtab = nullptr;
34 char * strtab = nullptr;
35 int symentries = 0;
36 for(auto section = map->l_ld; section->d_tag != DT_NULL; ++section){
37 if(section->d_tag == DT_SYMTAB){
38 symtab = (Elf64_Sym *)section->d_un.d_ptr;
39 }
40 if(section->d_tag == DT_STRTAB){
41 strtab = (char*)section->d_un.d_ptr;
42 }
43 if(section->d_tag == DT_SYMENT){
44 symentries = section->d_un.d_val;
45 }
46 }
47 int size = strtab - (char *)symtab;
48 for(int k = 0; k < size / symentries; ++k){
49 auto sym = &symtab[k];
50 // If sym is function
51 if(ELF64_ST_TYPE(symtab[k].st_info) == STT_FUNC){
52 //str is name of each symbol
53 auto str = &strtab[sym->st_name];
54 vecFunction.push_back(std::string(str));
55// printf("%s\n", str);
56 }
57 }
58 dlclose(library);
59}
60
62
67std::string phoenix_mangleFunction(const std::string & functionPrototype, const std::string & extraInclude, const std::string & compiler){
68 std::string command("echo \"#include <new>\\n#include <string>\\n"+extraInclude+"\\n"+functionPrototype+" {} \" | "+compiler+" -x c++ -S - -o- | grep \"@function\" | cut -d ',' -f 1 | sed -e \"s/.type//g\" | sed -s \"s/ //g\" | sed -e \"s/\t//g\"");
69 FILE * fp = popen(command.c_str(), "r");
70 if(fp == NULL){
71 std::cerr << "phoenix_mangleFunction : cannot get result of command '"<<command<<"'" << std::endl;
72 return "";
73 }
74 std::string mangledFunction("");
75 int buffer;
76 while(!feof(fp)){
77 buffer = fgetc(fp);
78 if(buffer != EOF){
79 char ch = (char)buffer;
80 if(ch != ' ' && ch != '\t' && ch != '\n'){
81 mangledFunction += ch;
82 }
83 }
84 else break;
85 }
86 pclose(fp);
87 return mangledFunction;
88}
89
90
void phoenix_listLibrarySymbol(std::vector< std::string > &vecFunction, const std::string &libFileName)
List the symbols in the given library.
std::string phoenix_mangleFunction(const std::string &functionPrototype, const std::string &extraInclude, const std::string &compiler)
Mangle the given function prototype.