| 1 |
#include "binary/safe_dl.hpp" |
| 2 |
|
| 3 |
#include "utils/common.hpp" |
| 4 |
#include "utils/utils.hpp" |
| 5 |
#include "platform/program_name.hpp" |
| 6 |
|
| 7 |
#include <string> |
| 8 |
#include <vector> |
| 9 |
#include <unordered_map> |
| 10 |
#include <cstring> |
| 11 |
#include <iostream> |
| 12 |
|
| 13 |
#ifdef CPPTRACE_HAS_DL_FIND_OBJECT |
| 14 |
#if IS_LINUX || IS_APPLE |
| 15 |
#include <unistd.h> |
| 16 |
#include <dlfcn.h> |
| 17 |
#include <link.h> |
| 18 |
#endif |
| 19 |
|
| 20 |
CPPTRACE_BEGIN_NAMESPACE |
| 21 |
namespace detail { |
| 22 |
void get_safe_object_frame(frame_ptr address, safe_object_frame* out) { |
| 23 |
out->raw_address = address; |
| 24 |
dl_find_object result; |
| 25 |
if(_dl_find_object(reinterpret_cast<void*>(address), &result) == 0) { // thread-safe, signal-safe |
| 26 |
out->address_relative_to_object_start = address - to_frame_ptr(result.dlfo_link_map->l_addr); |
| 27 |
if(result.dlfo_link_map->l_name != nullptr && result.dlfo_link_map->l_name[0] != 0) { |
| 28 |
std::size_t path_length = std::strlen(result.dlfo_link_map->l_name); |
| 29 |
std::memcpy( |
| 30 |
out->object_path, |
| 31 |
result.dlfo_link_map->l_name, |
| 32 |
std::min(path_length + 1, std::size_t(CPPTRACE_PATH_MAX + 1)) |
| 33 |
); |
| 34 |
} else { |
| 35 |
// empty l_name, this means it's the currently running executable |
| 36 |
memset(out->object_path, 0, CPPTRACE_PATH_MAX + 1); |
| 37 |
// signal-safe |
| 38 |
auto res = readlink("/proc/self/exe", out->object_path, CPPTRACE_PATH_MAX); |
| 39 |
if(res == -1) { |
| 40 |
// error handling? |
| 41 |
} |
| 42 |
// TODO: Special handling for /proc/pid/exe unlink edge case |
| 43 |
} |
| 44 |
} else { |
| 45 |
out->address_relative_to_object_start = 0; |
| 46 |
out->object_path[0] = 0; |
| 47 |
} |
| 48 |
// TODO: Handle this part of the documentation? |
| 49 |
// The address can be a code address or data address. On architectures using function descriptors, no attempt is |
| 50 |
// made to decode the function descriptor. Depending on how these descriptors are implemented, _dl_find_object |
| 51 |
// may return the object that defines the function descriptor (and not the object that contains the code |
| 52 |
// implementing the function), or fail to find any object at all. |
| 53 |
} |
| 54 |
|
| 55 |
bool has_get_safe_object_frame() { |
| 56 |
return true; |
| 57 |
} |
| 58 |
} |
| 59 |
CPPTRACE_END_NAMESPACE |
| 60 |
#else |
| 61 |
CPPTRACE_BEGIN_NAMESPACE |
| 62 |
namespace detail { |
| 63 |
void get_safe_object_frame(frame_ptr address, safe_object_frame* out) { |
| 64 |
out->raw_address = address; |
| 65 |
out->address_relative_to_object_start = 0; |
| 66 |
out->object_path[0] = 0; |
| 67 |
} |
| 68 |
|
| 69 |
bool has_get_safe_object_frame() { |
| 70 |
return false; |
| 71 |
} |
| 72 |
} |
| 73 |
CPPTRACE_END_NAMESPACE |
| 74 |
#endif |