Debian Codegraph @

src/symbols/symbols_with_addr2line.cpp

raw
1 #ifdef CPPTRACE_GET_SYMBOLS_WITH_ADDR2LINE
2
3 #include <cpptrace/basic.hpp>
4 #include "symbols/symbols.hpp"
5 #include "utils/common.hpp"
6 #include "utils/microfmt.hpp"
7 #include "utils/utils.hpp"
8
9 #include <cstdint>
10 #include <cstdio>
11 #include <functional>
12 #include <mutex>
13 #include <string>
14 #include <unordered_map>
15 #include <utility>
16 #include <vector>
17
18 #if IS_LINUX || IS_APPLE
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22 #endif
23
24 #include "binary/object.hpp"
25 #include "options.hpp"
26
27 CPPTRACE_BEGIN_NAMESPACE
28 namespace detail {
29 namespace addr2line {
30 #if IS_LINUX || IS_APPLE
31 bool has_addr2line() {
32 static std::mutex mutex;
33 static bool has_addr2line = false;
34 static bool checked = false;
35 std::lock_guard<std::mutex> lock(mutex);
36 if(!checked) {
37 checked = true;
38 // Detects if addr2line exists by trying to invoke addr2line --help
39 constexpr int magic = 42;
40 const pid_t pid = fork();
41 if(pid == -1) { return false; }
42 if(pid == 0) { // child
43 close(STDOUT_FILENO);
44 close(STDERR_FILENO); // atos --help writes to stderr
45 #ifdef CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH
46 #if !IS_APPLE
47 execlp("addr2line", "addr2line", "--help", nullptr);
48 #else
49 execlp("atos", "atos", "--help", nullptr);
50 #endif
51 #else
52 #ifndef CPPTRACE_ADDR2LINE_PATH
53 #error "CPPTRACE_ADDR2LINE_PATH must be defined if CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH is not"
54 #endif
55 execl(CPPTRACE_ADDR2LINE_PATH, CPPTRACE_ADDR2LINE_PATH, "--help", nullptr);
56 #endif
57 _exit(magic);
58 }
59 int status;
60 waitpid(pid, &status, 0);
61 has_addr2line = WEXITSTATUS(status) == 0;
62 }
63 return has_addr2line;
64 }
65
66 struct pipe_ends {
67 int read;
68 int write;
69 };
70
71 struct pipe_t {
72 union {
73 pipe_ends end;
74 int data[2];
75 };
76 };
77 static_assert(sizeof(pipe_t) == 2 * sizeof(int), "Unexpected struct packing");
78
79 std::string resolve_addresses(const std::string& addresses, const std::string& executable) {
80 pipe_t output_pipe;
81 pipe_t input_pipe;
82 if(pipe(output_pipe.data) != 0 || pipe(input_pipe.data) != 0) {
83 throw internal_error("call to pipe failed: {}", errno);
84 }
85 const pid_t pid = fork();
86 if(pid == -1) { return ""; } // error? TODO: Diagnostic
87 if(pid == 0) { // child
88 dup2(output_pipe.end.write, STDOUT_FILENO);
89 dup2(input_pipe.end.read, STDIN_FILENO);
90 close(output_pipe.end.read);
91 close(output_pipe.end.write);
92 close(input_pipe.end.read);
93 close(input_pipe.end.write);
94 close(STDERR_FILENO); // TODO: Might be worth conditionally enabling or piping
95 #ifdef CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH
96 #if !IS_APPLE
97 execlp("addr2line", "addr2line", "-e", executable.c_str(), "-f", "-C", "-p", nullptr);
98 #else
99 execlp("atos", "atos", "-o", executable.c_str(), "-fullPath", nullptr);
100 #endif
101 #else
102 #ifndef CPPTRACE_ADDR2LINE_PATH
103 #error "CPPTRACE_ADDR2LINE_PATH must be defined if CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH is not"
104 #endif
105 #if !IS_APPLE
106 execl(
107 CPPTRACE_ADDR2LINE_PATH,
108 CPPTRACE_ADDR2LINE_PATH,
109 "-e",
110 executable.c_str(),
111 "-f",
112 "-C",
113 "-p",
114 nullptr
115 );
116 #else
117 execl(
118 CPPTRACE_ADDR2LINE_PATH,
119 CPPTRACE_ADDR2LINE_PATH,
120 "-o", executable.c_str(),
121 "-fullPath",
122 nullptr
123 );
124 #endif
125 #endif
126 _exit(1); // TODO: Diagnostic?
127 }
128 if(write(input_pipe.end.write, addresses.data(), addresses.size()) == -1) {
129 throw internal_error("call to write failed: {}", errno);
130 }
131 close(input_pipe.end.read);
132 close(input_pipe.end.write);
133 close(output_pipe.end.write);
134 std::string output;
135 constexpr int buffer_size = 4096;
136 char buffer[buffer_size];
137 std::size_t count = 0;
138 while((count = read(output_pipe.end.read, buffer, buffer_size)) > 0) {
139 output.insert(output.end(), buffer, buffer + count);
140 }
141 // TODO: check status from addr2line?
142 waitpid(pid, nullptr, 0);
143 return output;
144 }
145 #elif IS_WINDOWS
146 bool has_addr2line() {
147 static std::mutex mutex;
148 static bool has_addr2line = false;
149 static bool checked = false;
150 std::lock_guard<std::mutex> lock(mutex);
151 if(!checked) {
152 // TODO: Popen is a hack. Implement properly with CreateProcess and pipes later.
153 checked = true;
154 #ifdef CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH
155 std::FILE* p = popen("addr2line --version", "r");
156 #else
157 #ifndef CPPTRACE_ADDR2LINE_PATH
158 #error "CPPTRACE_ADDR2LINE_PATH must be defined if CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH is not"
159 #endif
160 std::FILE* p = popen(CPPTRACE_ADDR2LINE_PATH " --version", "r");
161 #endif
162 if(p) {
163 has_addr2line = pclose(p) == 0;
164 }
165 }
166 return has_addr2line;
167 }
168
169 std::string resolve_addresses(const std::string& addresses, const std::string& executable) {
170 // TODO: Popen is a hack. Implement properly with CreateProcess and pipes later.
171 ///fprintf(stderr, ("addr2line -e " + executable + " -fCp " + addresses + "\n").c_str());
172 #ifdef CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH
173 std::FILE* p = popen(("addr2line -e \"" + executable + "\" -fCp " + addresses).c_str(), "r");
174 #else
175 #ifndef CPPTRACE_ADDR2LINE_PATH
176 #error "CPPTRACE_ADDR2LINE_PATH must be defined if CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH is not"
177 #endif
178 std::FILE* p = popen(
179 (CPPTRACE_ADDR2LINE_PATH " -e \"" + executable + "\" -fCp " + addresses).c_str(),
180 "r"
181 );
182 #endif
183 std::string output;
184 constexpr int buffer_size = 4096;
185 char buffer[buffer_size];
186 std::size_t count = 0;
187 while((count = std::fread(buffer, 1, buffer_size, p)) > 0) {
188 output.insert(output.end(), buffer, buffer + count);
189 }
190 pclose(p);
191 ///fprintf(stderr, "%s\n", output.c_str());
192 return output;
193 }
194 #endif
195
196 void update_trace(const std::string& line, std::size_t entry_index, const collated_vec& entries_vec) {
197 #if !IS_APPLE
198 // Result will be of the form "<symbol> at path:line"
199 // The path may be ?? if addr2line cannot resolve, line may be ?
200 // Edge cases:
201 // ?? ??:0
202 // symbol :?
203 const std::size_t at_location = line.find(" at ");
204 std::size_t symbol_end;
205 std::size_t filename_start;
206 if(at_location != std::string::npos) {
207 symbol_end = at_location;
208 filename_start = at_location + 4;
209 } else {
210 VERIFY(line.find("?? ") == 0, "Unexpected edge case while processing addr2line output");
211 symbol_end = 2;
212 filename_start = 3;
213 }
214 auto symbol = line.substr(0, symbol_end);
215 auto colon = line.rfind(':');
216 VERIFY(colon != std::string::npos);
217 VERIFY(colon >= filename_start); // :? to deal with "symbol :?" edge case
218 auto filename = line.substr(filename_start, colon - filename_start);
219 auto line_number = line.substr(colon + 1);
220 if(line_number != "?") {
221 entries_vec[entry_index].second.get().line = std::stoi(line_number);
222 }
223 if(!filename.empty() && filename != "??") {
224 entries_vec[entry_index].second.get().filename = filename;
225 }
226 if(!symbol.empty()) {
227 entries_vec[entry_index].second.get().symbol = symbol;
228 }
229 #else
230 // Result will be of the form "<symbol> (in <object name>) (file:line)"
231 // The symbol may just be the given address if atos can't resolve it
232 // Examples:
233 // trace() (in demo) (demo.cpp:8)
234 // 0x100003b70 (in demo)
235 // 0xffffffffffffffff
236 // foo (in bar) + 14
237 // I'm making some assumptions here. Support may need to be improved later. This is tricky output to
238 // parse.
239 const std::size_t in_location = line.find(" (in ");
240 if(in_location == std::string::npos) {
241 // presumably the 0xffffffffffffffff case
242 return;
243 }
244 const std::size_t symbol_end = in_location;
245 entries_vec[entry_index].second.get().symbol = line.substr(0, symbol_end);
246 const std::size_t object_end = line.find(")", in_location);
247 VERIFY(
248 object_end != std::string::npos,
249 "Unexpected edge case while processing addr2line/atos output"
250 );
251 const std::size_t filename_start = line.find(") (", object_end);
252 if(filename_start == std::string::npos) {
253 // presumably something like 0x100003b70 (in demo) or foo (in bar) + 14
254 return;
255 }
256 const std::size_t filename_end = line.find(":", filename_start);
257 VERIFY(
258 filename_end != std::string::npos,
259 "Unexpected edge case while processing addr2line/atos output"
260 );
261 entries_vec[entry_index].second.get().filename = line.substr(
262 filename_start + 3,
263 filename_end - filename_start - 3
264 );
265 const std::size_t line_start = filename_end + 1;
266 const std::size_t line_end = line.find(")", filename_end);
267 VERIFY(
268 line_end == line.size() - 1,
269 "Unexpected edge case while processing addr2line/atos output"
270 );
271 entries_vec[entry_index].second.get().line = std::stoi(line.substr(line_start, line_end - line_start));
272 #endif
273 }
274
275 std::vector<stacktrace_frame> resolve_frames(const std::vector<object_frame>& frames) {
276 // TODO: Refactor better
277 std::vector<stacktrace_frame> trace(frames.size(), null_frame());
278 for(std::size_t i = 0; i < frames.size(); i++) {
279 trace[i].raw_address = frames[i].raw_address;
280 trace[i].object_address = frames[i].object_address;
281 // Set what is known for now, and resolutions from addr2line should overwrite
282 trace[i].filename = frames[i].object_path;
283 }
284 if(has_addr2line()) {
285 const auto entries = collate_frames(frames, trace);
286 for(const auto& entry : entries) {
287 try {
288 const auto& object_name = entry.first;
289 if(object_name.empty()) {
290 continue;
291 }
292 const auto& entries_vec = entry.second;
293 // You may ask why it'd ever happen that there could be an empty entries_vec array, if there're
294 // no addresses why would get_addr2line_targets do anything? The reason is because if things in
295 // get_addr2line_targets fail it will silently skip. This is partly an optimization but also an
296 // assertion below will fail if addr2line is given an empty input.
297 if(entries_vec.empty()) {
298 continue;
299 }
300 std::string address_input;
301 for(const auto& pair : entries_vec) {
302 address_input += microfmt::format(
303 "{:h}{}",
304 pair.first.get().object_address,
305 #if !IS_WINDOWS
306 '\n'
307 #else
308 ' '
309 #endif
310 );
311 }
312 auto output = split(trim(resolve_addresses(address_input, object_name)), "\n");
313 VERIFY(output.size() == entries_vec.size());
314 for(std::size_t i = 0; i < output.size(); i++) {
315 update_trace(output[i], i, entries_vec);
316 }
317 } catch(...) { // NOSONAR
318 detail::log_and_maybe_propagate_exception(std::current_exception());
319 }
320 }
321 }
322 return trace;
323 }
324 }
325 }
326 CPPTRACE_END_NAMESPACE
327
328 #endif