Branch data Line data Source code
1 : : /* Print the source files of a given ELF file.
2 : : Copyright (C) 2023 Red Hat, Inc.
3 : : This file is part of elfutils.
4 : : Written by Housam Alamour <alamourh@redhat.com>.
5 : :
6 : : This file is free software; you can redistribute it and/or modify
7 : : it under the terms of the GNU General Public License as published by
8 : : the Free Software Foundation; either version 3 of the License, or
9 : : (at your option) any later version.
10 : :
11 : : elfutils is distributed in the hope that it will be useful, but
12 : : WITHOUT ANY WARRANTY; without even the implied warranty of
13 : : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : : GNU General Public License for more details.
15 : :
16 : : You should have received a copy of the GNU General Public License
17 : : along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 : :
19 : :
20 : : /* In case we have a bad fts we include this before config.h because it
21 : : can't handle _FILE_OFFSET_BITS.
22 : : Everything we need here is fine if its declarations just come first.
23 : : Also, include sys/types.h before fts. On some systems fts.h is not self
24 : : contained. */
25 : : #ifdef BAD_FTS
26 : : #include <sys/types.h>
27 : : #include <fts.h>
28 : : #endif
29 : :
30 : : #ifdef HAVE_CONFIG_H
31 : : # include <config.h>
32 : : #endif
33 : :
34 : : #include "printversion.h"
35 : : #include <dwarf.h>
36 : : #include <argp.h>
37 : : #include <cstring>
38 : : #include <set>
39 : : #include <string>
40 : : #include <cassert>
41 : : #include <gelf.h>
42 : : #include <memory>
43 : :
44 : : #ifdef ENABLE_LIBDEBUGINFOD
45 : : #include "debuginfod.h"
46 : : #endif
47 : :
48 : : #include <libdwfl.h>
49 : : #include <fcntl.h>
50 : : #include <iostream>
51 : : #include <libdw.h>
52 : : #include <sstream>
53 : : #include <vector>
54 : :
55 : : /* Libraries for use by the --zip option */
56 : : #ifdef HAVE_LIBARCHIVE
57 : : #include <archive.h>
58 : : #include <archive_entry.h>
59 : : #endif
60 : :
61 : : /* If fts.h is included before config.h, its indirect inclusions may not
62 : : give us the right LFS aliases of these functions, so map them manually. */
63 : : #ifdef BAD_FTS
64 : : #ifdef _FILE_OFFSET_BITS
65 : : #define open open64
66 : : #define fopen fopen64
67 : : #endif
68 : : #else
69 : : #include <sys/types.h>
70 : : #include <fts.h>
71 : : #endif
72 : :
73 : : using namespace std;
74 : :
75 : : /* Name and version of program. */
76 : : ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
77 : :
78 : : /* Bug report address. */
79 : : ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
80 : :
81 : : #ifdef HAVE_LIBARCHIVE
82 : : constexpr size_t BUFFER_SIZE = 8192;
83 : : #endif
84 : :
85 : : /* Definitions of arguments for argp functions. */
86 : : static const struct argp_option options[] =
87 : : {
88 : : { NULL, 0, NULL, OPTION_DOC, N_("Output options:"), 1 },
89 : : { "null", '0', NULL, 0,
90 : : N_ ("Separate items by a null instead of a newline."), 0 },
91 : : { "verbose", 'v', NULL, 0,
92 : : N_ ("Increase verbosity of logging messages."), 0 },
93 : : { "cu-only", 'c', NULL, 0, N_("Only list the CU names."), 0 },
94 : : #ifdef HAVE_LIBARCHIVE
95 : : { "zip", 'z', NULL, 0, N_("Zip all the source files and send to stdout. "
96 : : "Cannot be used with the null option"), 0 },
97 : : #ifdef ENABLE_LIBDEBUGINFOD
98 : : { "no-backup", 'b', NULL, 0, N_("Disables local source file search when "
99 : : "debuginfod fails to fetch files. This option is only applicable "
100 : : "when fetching and zipping files."), 0 },
101 : : #endif
102 : : #endif
103 : : { NULL, 0, NULL, 0, NULL, 0 }
104 : : };
105 : :
106 : : /* Short description of program. */
107 : : static const char doc[] = N_("Lists the source files of a DWARF/ELF file. The default input is the file 'a.out'.");
108 : :
109 : : /* Strings for arguments in help texts. */
110 : : static const char args_doc[] = N_("INPUT");
111 : :
112 : : /* Prototype for option handler. */
113 : : static error_t parse_opt (int key, char *arg, struct argp_state *state);
114 : :
115 : : static struct argp_child argp_children[2]; /* [0] is set in main. */
116 : :
117 : : /* Data structure to communicate with argp functions. */
118 : : static const struct argp argp =
119 : : {
120 : : options, parse_opt, args_doc, doc, argp_children, NULL, NULL
121 : : };
122 : :
123 : : /* Verbose message printing. */
124 : : static bool verbose;
125 : : /* Delimit the output with nulls. */
126 : : static bool null_arg;
127 : : /* Only print compilation unit names. */
128 : : static bool CU_only;
129 : : #ifdef HAVE_LIBARCHIVE
130 : : /* Zip all the source files and send to stdout. */
131 : : static bool zip;
132 : :
133 : : #ifdef ENABLE_LIBDEBUGINFOD
134 : : /* Disables local source file search when debuginfod fails to fetch them.
135 : : This option is only applicable when fetching and zipping files.*/
136 : : static bool no_backup;
137 : : #endif
138 : : #endif
139 : :
140 : : /* Handle program arguments. Note null arg and zip
141 : : cannot be combined due to warnings raised when unzipping. */
142 : : static error_t
143 : 230 : parse_opt (int key, char *arg, struct argp_state *state)
144 : : {
145 : : /* Suppress "unused parameter" warning. */
146 : 230 : (void)arg;
147 [ + + + + : 230 : switch (key)
+ + + ]
148 : : {
149 : 38 : case ARGP_KEY_INIT:
150 : 38 : state->child_inputs[0] = state->input;
151 : 38 : break;
152 : :
153 : 12 : case '0':
154 : 12 : null_arg = true;
155 : 12 : break;
156 : :
157 : 16 : case 'v':
158 : 16 : verbose = true;
159 : 16 : break;
160 : :
161 : 8 : case 'c':
162 : 8 : CU_only = true;
163 : 8 : break;
164 : :
165 : : #ifdef HAVE_LIBARCHIVE
166 : 10 : case 'z':
167 : 10 : zip = true;
168 : 10 : break;
169 : :
170 : : #ifdef ENABLE_LIBDEBUGINFOD
171 : 2 : case 'b':
172 : 2 : no_backup = true;
173 : 2 : break;
174 : : #endif
175 : : #endif
176 : :
177 : : default:
178 : : return ARGP_ERR_UNKNOWN;
179 : : }
180 : : return 0;
181 : : }
182 : :
183 : : /* Remove the "/./" , "../" and the preceding directory
184 : : that some paths include which raise errors during unzip. */
185 : 995780 : string canonicalize_path(string path)
186 : : {
187 : 995780 : stringstream ss(path);
188 : 995780 : string token;
189 : 995780 : vector<string> tokens;
190 : : /* Extract each directory of the path and place into a vector. */
191 [ + - + + ]: 7801516 : while (getline(ss, token, '/')) {
192 : : /* Ignore any empty //, or /./ dirs. */
193 [ + + + + ]: 5809956 : if (token == "" || token == ".")
194 : 1025252 : continue;
195 : : /* When /.. is encountered, remove the most recent directory from the vector. */
196 [ + + ]: 4784704 : else if (token == "..") {
197 [ + - ]: 154792 : if (!tokens.empty())
198 : 154792 : tokens.pop_back();
199 : : } else
200 [ + - ]: 4629912 : tokens.push_back(token);
201 : : }
202 [ + - ]: 995780 : stringstream result;
203 [ - + ]: 995780 : if (tokens.empty())
204 [ # # ]: 0 : return "/";
205 : : /* Reconstruct the path from the extracted directories. */
206 [ + + ]: 5470900 : for (const string &t : tokens) {
207 [ + - + - ]: 4475120 : result << '/' << t;
208 : : }
209 [ + - ]: 995780 : return result.str();
210 : 995780 : }
211 : :
212 : : /* Global list of collected source files and their respective module.
213 : : Normally, it'll contain the sources of just one named binary, but
214 : : the '-K' option can cause multiple dwfl modules to be loaded, thus
215 : : listed. */
216 : : set<pair<string, Dwfl_Module*>> debug_sourcefiles;
217 : :
218 : : static int
219 : 68 : collect_sourcefiles (Dwfl_Module *dwflmod,
220 : : void **userdata __attribute__ ((unused)),
221 : : const char *name __attribute__ ((unused)),
222 : : Dwarf_Addr base __attribute__ ((unused)),
223 : : void *arg __attribute__ ((unused)))
224 : : {
225 : 68 : Dwarf *dbg;
226 : 68 : Dwarf_Addr bias; /* ignored - for addressing purposes only. */
227 : :
228 : 68 : dbg = dwfl_module_getdwarf (dwflmod, &bias);
229 : :
230 : 68 : Dwarf_CU *cu = NULL;
231 : 68 : Dwarf_Die cudie_mem;
232 : 68 : Dwarf_Die subdie_mem;
233 : : /* Traverse all CUs of this module. */
234 : 68 : while (dwarf_get_units (dbg, cu, &cu, NULL, NULL,
235 [ + + ]: 12256 : &cudie_mem, &subdie_mem) == 0)
236 : : {
237 : 12188 : Dwarf_Die *cudie = &cudie_mem;
238 : 12188 : Dwarf_Die *subdie = (dwarf_tag (&subdie_mem) != DW_TAG_invalid
239 [ + - ]: 12188 : ? &subdie_mem : NULL);
240 : :
241 : : /* For split dwarf (dwo) the name might not be in the skeleton
242 : : CU DIE, try the split compile unit DIE, if there is one. */
243 : 12188 : const char *cuname = (dwarf_diename (cudie)
244 [ + + + - ]: 12188 : ?: (dwarf_diename (subdie) ?: "<unknown>"));
245 : 12188 : Dwarf_Files *files;
246 : 12188 : size_t nfiles;
247 : : /* The stmt list is usually in the skeleton_unit, but might also
248 : : be found in a split type unit. */
249 : 12188 : if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0
250 [ + + + - ]: 12188 : && dwarf_getsrcfiles (subdie, &files, &nfiles) != 0)
251 : 512 : continue;
252 : :
253 : : /* extract DW_AT_comp_dir to resolve relative file names. */
254 : 11676 : const char *comp_dir = "";
255 : 11676 : const char *const *dirs;
256 : 11676 : size_t ndirs;
257 : :
258 [ + - + - ]: 11676 : if (dwarf_getsrcdirs (files, &dirs, &ndirs) == 0 && dirs[0] != NULL)
259 : 11676 : comp_dir = dirs[0];
260 : 11676 : if (comp_dir == NULL)
261 : : comp_dir = "";
262 : :
263 [ + + ]: 11676 : if (verbose)
264 : 5192 : clog << "searching for sources for cu=" << cuname
265 : 5192 : << " comp_dir=" << comp_dir << " #files=" << nfiles
266 : 5192 : << " #dirs=" << ndirs << endl;
267 : :
268 [ - + - - ]: 11676 : if (comp_dir[0] == '\0' && cuname[0] != '/')
269 : : {
270 : : /* This is a common symptom for dwz-compressed debug files,
271 : : where the altdebug file cannot be resolved. */
272 [ # # ]: 0 : if (verbose)
273 : 0 : clog << "skipping cu=" << cuname << " due to empty comp_dir" << endl;
274 : 0 : continue;
275 : : }
276 [ + + ]: 1011256 : for (size_t f = 0; f < nfiles; ++f)
277 : : {
278 : : /* For --cu-only we are only interested in the "zero" entry. */
279 [ + + + + ]: 1002164 : if (CU_only && f != 0)
280 : : break;
281 : :
282 : 996996 : const char *hat;
283 [ + + ]: 996996 : if (f == 0)
284 : : {
285 [ + + - + ]: 11676 : if (strcmp(cuname, "<unknown>") == 0 || strcmp(cuname, "<artificial>") == 0 )
286 : 3800 : continue;
287 : : hat = cuname;
288 : : }
289 : : else
290 : 987904 : hat = dwarf_filesrc (files, f, NULL, NULL);
291 : :
292 [ - + ]: 987904 : if (hat == NULL)
293 : 0 : continue;
294 : :
295 [ + + ]: 997900 : if (string(hat).find("<built-in>")
296 : : != string::npos) /* gcc intrinsics, don't bother recording */
297 : 2120 : continue;
298 : :
299 : 995780 : string waldo;
300 [ + + ]: 995780 : if (hat[0] == '/') /* absolute */
301 [ + - ]: 823320 : waldo = (string (hat));
302 [ + - ]: 172460 : else if (comp_dir[0] != '\0') /* comp_dir relative */
303 [ + - + - : 172460 : waldo = (string (comp_dir) + string ("/") + string (hat));
+ - + - +
- ]
304 : : else
305 : : {
306 [ # # ]: 0 : if (verbose)
307 [ # # # # : 0 : clog << "skipping file=" << hat << " due to empty comp_dir" << endl;
# # # # ]
308 : 0 : continue;
309 : : }
310 [ + - + - ]: 995780 : waldo = canonicalize_path (waldo);
311 [ + - + - ]: 995780 : debug_sourcefiles.insert (make_pair(waldo, dwflmod));
312 : 995780 : }
313 : : }
314 : 68 : return DWARF_CB_OK;
315 : : }
316 : :
317 : : #ifdef HAVE_LIBARCHIVE
318 : 10 : void zip_files()
319 : : {
320 : 10 : struct archive *a = archive_write_new();
321 : 10 : struct stat st;
322 : 10 : char buff[BUFFER_SIZE];
323 : 10 : int len;
324 : : #ifdef ENABLE_LIBDEBUGINFOD
325 : : /* Initialize a debuginfod client. */
326 : 10 : static unique_ptr <debuginfod_client, void (*)(debuginfod_client*)>
327 [ + - + - : 10 : client (debuginfod_begin(), &debuginfod_end);
+ - ]
328 : : #endif
329 : :
330 : 10 : archive_write_set_format_zip(a);
331 : 10 : archive_write_open_fd(a, STDOUT_FILENO);
332 : :
333 : 10 : int missing_files = 0;
334 [ + + ]: 8920 : for (const auto &pair : debug_sourcefiles)
335 : : {
336 : 8910 : int fd = -1;
337 : 8910 : const std::string &file_path = pair.first;
338 : 8910 : struct archive_entry *entry = NULL;
339 : 8910 : string entry_name;
340 : :
341 : : /* Attempt to query debuginfod client to fetch source files. */
342 : : #ifdef ENABLE_LIBDEBUGINFOD
343 : 8910 : Dwfl_Module* dwflmod = pair.second;
344 : : /* Obtain source file's build ID. */
345 : 8910 : const unsigned char *bits;
346 : 8910 : GElf_Addr vaddr;
347 [ + - ]: 8910 : int bits_length = dwfl_module_build_id(dwflmod, &bits, &vaddr);
348 : : /* Ensure successful client and build ID acquisition. */
349 [ + - + - ]: 8910 : if (client.get() != NULL && bits_length > 0)
350 : : {
351 [ + - ]: 8910 : fd = debuginfod_find_source(client.get(),
352 : : bits, bits_length,
353 : : file_path.c_str(), NULL);
354 : : }
355 : : else
356 : : {
357 [ # # ]: 0 : if (client.get() == NULL)
358 [ # # # # ]: 0 : cerr << "Error: Failed to initialize debuginfod client." << endl;
359 : : else
360 [ # # # # : 0 : cerr << "Error: Invalid build ID length (" << bits_length << ")." << endl;
# # # # ]
361 : : }
362 : :
363 [ + + ]: 8910 : if (!no_backup)
364 : : #endif /* ENABLE_LIBDEBUGINFOD */
365 : : /* Files could not be located using debuginfod, search locally */
366 [ + - ]: 7128 : if (fd < 0)
367 [ + - ]: 7128 : fd = open(file_path.c_str(), O_RDONLY);
368 [ - + ]: 8910 : if (fd < 0)
369 : : {
370 [ # # ]: 0 : if (verbose)
371 [ # # # # ]: 0 : cerr << file_path << endl;
372 : 0 : missing_files++;
373 : 0 : continue;
374 : : }
375 : :
376 : : /* Create an entry for each file including file information to be placed in the zip. */
377 [ - + ]: 8910 : if (fstat(fd, &st) == -1)
378 : : {
379 [ # # ]: 0 : if (verbose)
380 [ # # # # ]: 0 : cerr << file_path << endl;
381 : 0 : missing_files++;
382 [ # # ]: 0 : if (verbose)
383 [ # # # # : 0 : cerr << "Error: Failed to get file status for " << file_path << ": " << strerror(errno) << endl;
# # # # #
# ]
384 : 0 : goto next;
385 : : }
386 [ + - ]: 8910 : entry = archive_entry_new();
387 : : /* Removing first "/"" to make the path "relative" before zipping, otherwise warnings are raised when unzipping. */
388 [ + - ]: 8910 : entry_name = file_path.substr(file_path.find_first_of('/') + 1);
389 [ + - ]: 8910 : archive_entry_set_pathname(entry, entry_name.c_str());
390 [ + - ]: 8910 : archive_entry_copy_stat(entry, &st);
391 [ + - - + ]: 8910 : if (archive_write_header(a, entry) != ARCHIVE_OK)
392 : : {
393 [ # # ]: 0 : if (verbose)
394 [ # # # # ]: 0 : cerr << file_path << endl;
395 : 0 : missing_files++;
396 [ # # ]: 0 : if (verbose)
397 [ # # # # : 0 : cerr << "Error: failed to write header for " << file_path << ": " << archive_error_string(a) << endl;
# # # # #
# # # ]
398 : 0 : goto next;
399 : : }
400 : :
401 : : /* Write the file to the zip. */
402 [ + - ]: 8910 : len = read(fd, buff, sizeof(buff));
403 [ - + ]: 8910 : if (len == -1)
404 : : {
405 [ # # ]: 0 : if (verbose)
406 [ # # # # ]: 0 : cerr << file_path << endl;
407 : 0 : missing_files++;
408 [ # # ]: 0 : if (verbose)
409 [ # # # # : 0 : cerr << "Error: Failed to open file: " << file_path << ": " << strerror(errno) <<endl;
# # # # #
# ]
410 : 0 : goto next;
411 : : }
412 [ + + ]: 25540 : while (len > 0)
413 : : {
414 [ + - - + ]: 16630 : if (archive_write_data(a, buff, len) < ARCHIVE_OK)
415 : : {
416 [ # # ]: 0 : if (verbose)
417 [ # # # # : 0 : cerr << "Error: Failed to read from the file: " << file_path << ": " << strerror(errno) << endl;
# # # # #
# ]
418 : : break;
419 : : }
420 [ + - ]: 16630 : len = read(fd, buff, sizeof(buff));
421 : : }
422 : :
423 : 8910 : next:
424 [ + - ]: 8910 : if (fd >= 0)
425 [ + - ]: 8910 : close(fd);
426 [ + - ]: 8910 : if (entry != NULL)
427 [ + - ]: 8910 : archive_entry_free(entry);
428 : 8910 : }
429 [ + + - + ]: 10 : if (verbose && missing_files > 0 )
430 : 0 : cerr << missing_files << " file(s) listed above could not be found. " << endl;
431 : :
432 : 10 : archive_write_close(a);
433 : 10 : archive_write_free(a);
434 : 10 : }
435 : : #endif
436 : :
437 : : int
438 : 38 : main (int argc, char *argv[])
439 : : {
440 : 38 : int remaining;
441 : :
442 : : /* Parse and process arguments. This includes opening the modules. */
443 : 38 : argp_children[0].argp = dwfl_standard_argp ();
444 : 38 : argp_children[0].group = 1;
445 : :
446 : 38 : Dwfl *dwfl = NULL;
447 : 38 : (void) argp_parse (&argp, argc, argv, 0, &remaining, &dwfl);
448 [ - + ]: 36 : assert (dwfl != NULL);
449 : : /* Process all loaded modules - probably just one, except if -K or -p is used. */
450 : 36 : (void) dwfl_getmodules (dwfl, &collect_sourcefiles, NULL, 0);
451 : :
452 [ + - ]: 36 : if (!debug_sourcefiles.empty ())
453 : : {
454 : : #ifdef HAVE_LIBARCHIVE
455 [ + + ]: 36 : if (zip)
456 : 10 : zip_files();
457 : : else
458 : : #endif
459 : : {
460 [ + + ]: 13960 : for (const auto &pair : debug_sourcefiles)
461 : : {
462 : 13934 : cout << pair.first;
463 [ + + ]: 13934 : if (null_arg)
464 : 6076 : cout << '\0';
465 : : else
466 : 7858 : cout << '\n';
467 : : }
468 : : }
469 : : }
470 : :
471 : 36 : dwfl_end (dwfl);
472 : 36 : return 0;
473 : : }
|