xref: /aosp_15_r20/external/elfutils/tests/backtrace.c (revision 7304104da70ce23c86437a01be71edd1a2d7f37e)
1 /* Test program for unwinding of frames.
2    Copyright (C) 2013, 2014, 2016 Red Hat, Inc.
3    This file is part of elfutils.
4 
5    This file is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9 
10    elfutils is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17 
18 #include <config.h>
19 #include <assert.h>
20 #include <inttypes.h>
21 #include <stdio.h>
22 #include <stdio_ext.h>
23 #include <locale.h>
24 #include <dirent.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <dwarf.h>
29 #ifdef __linux__
30 #include <sys/resource.h>
31 #include <sys/ptrace.h>
32 #include <signal.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <sys/user.h>
36 #include <fcntl.h>
37 #include <string.h>
38 #include <argp.h>
39 #include ELFUTILS_HEADER(dwfl)
40 #endif
41 #include "system.h"
42 
43 #ifndef __linux__
44 
45 int
main(int argc,char ** argv)46 main (int argc __attribute__ ((unused)), char **argv)
47 {
48   fprintf (stderr, "%s: Unwinding not supported for this architecture\n",
49 	   argv[0]);
50   return 77;
51 }
52 
53 #else /* __linux__ */
54 
55 static int
dump_modules(Dwfl_Module * mod,void ** userdata,const char * name,Dwarf_Addr start,void * arg)56 dump_modules (Dwfl_Module *mod, void **userdata __attribute__ ((unused)),
57 	      const char *name, Dwarf_Addr start,
58 	      void *arg __attribute__ ((unused)))
59 {
60   Dwarf_Addr end;
61   dwfl_module_info (mod, NULL, NULL, &end, NULL, NULL, NULL, NULL);
62   printf ("%#" PRIx64 "\t%#" PRIx64 "\t%s\n", (uint64_t) start, (uint64_t) end,
63 	  name);
64   return DWARF_CB_OK;
65 }
66 
67 static bool use_raise_jmp_patching;
68 static pid_t check_tid;
69 
70 static void
callback_verify(pid_t tid,unsigned frameno,Dwarf_Addr pc,const char * symname,Dwfl * dwfl)71 callback_verify (pid_t tid, unsigned frameno, Dwarf_Addr pc,
72 		 const char *symname, Dwfl *dwfl)
73 {
74   static bool seen_main = false;
75   if (symname && *symname == '.')
76     symname++;
77   if (symname && strcmp (symname, "main") == 0)
78     seen_main = true;
79   if (pc == 0)
80     {
81       assert (seen_main);
82       return;
83     }
84   if (check_tid == 0)
85     check_tid = tid;
86   if (tid != check_tid)
87     {
88       // For the main thread we are only interested if we can unwind till
89       // we see the "main" symbol.
90       return;
91     }
92   Dwfl_Module *mod;
93   /* Skip frames for which there isn't a function name.  */
94   static int nulls_seen = 0;
95   if (symname == NULL)
96     {
97       nulls_seen++;
98       return;
99     }
100   frameno -= nulls_seen;
101   /* See case 4. Special case to help out simple frame pointer unwinders. */
102   static bool duplicate_sigusr2 = false;
103   if (duplicate_sigusr2)
104     frameno--;
105   static bool reduce_frameno = false;
106   if (reduce_frameno)
107     frameno--;
108   static bool pthread_kill_seen = false;
109   if (pthread_kill_seen)
110     frameno--;
111   if (! use_raise_jmp_patching && frameno >= 2)
112     frameno += 2;
113   const char *symname2 = NULL;
114   switch (frameno)
115   {
116     case 0:
117       if (! reduce_frameno && symname
118 	       && (strcmp (symname, "__kernel_vsyscall") == 0
119 		   || strcmp (symname, "__libc_do_syscall") == 0))
120 	reduce_frameno = true;
121       else if (! pthread_kill_seen && symname
122 	       && strstr (symname, "pthread_kill") != NULL)
123 	pthread_kill_seen = true;
124       else
125 	{
126 	  if (!symname || strcmp (symname, "raise") != 0)
127 	    {
128 	      fprintf (stderr,
129 		       "case 0: expected symname 'raise' got '%s'\n", symname);
130 	      abort ();
131 	    }
132 	}
133       break;
134     case 1:
135       if (symname == NULL || strcmp (symname, "sigusr2") != 0)
136 	{
137 	  fprintf (stderr,
138 		   "case 1: expected symname 'sigusr2' got '%s'\n", symname);
139 	  abort ();
140 	}
141       break;
142     case 2: // x86_64 only
143       /* __restore_rt - glibc maybe does not have to have this symbol.  */
144       break;
145     case 3: // use_raise_jmp_patching
146       if (use_raise_jmp_patching)
147 	{
148 	  /* Verify we trapped on the very first instruction of jmp.  */
149 	  if (symname == NULL || strcmp (symname, "jmp") != 0)
150 	    {
151 	      fprintf (stderr,
152 		       "case 3: expected symname 'raise' got '%s'\n", symname);
153 	      abort ();
154 	    }
155 	  mod = dwfl_addrmodule (dwfl, pc - 1);
156 	  if (mod)
157 	    symname2 = dwfl_module_addrname (mod, pc - 1);
158 	  if (symname2 == NULL || strcmp (symname2, "jmp") != 0)
159 	    {
160 	      fprintf (stderr,
161 		       "case 3: expected symname2 'jmp' got '%s'\n", symname2);
162 	      abort ();
163 	    }
164 	  break;
165 	}
166       FALLTHROUGH;
167     case 4:
168       /* Some simple frame unwinders get this wrong and think sigusr2
169 	 is calling itself again. Allow it and just pretend there is
170 	 an extra sigusr2 frame. */
171       if (symname != NULL && strcmp (symname, "sigusr2") == 0)
172 	{
173 	  duplicate_sigusr2 = true;
174 	  break;
175 	}
176       if (symname == NULL || strcmp (symname, "stdarg") != 0)
177 	{
178 	  fprintf (stderr,
179 		   "case 4: expected symname 'stdarg' got '%s'\n", symname);
180 	  abort ();
181 	}
182       break;
183     case 5:
184       /* Verify we trapped on the very last instruction of child.  */
185       if (symname == NULL || strcmp (symname, "backtracegen") != 0)
186 	{
187 	  fprintf (stderr,
188 		   "case 5: expected symname 'backtracegen' got '%s'\n",
189 		   symname);
190 	  abort ();
191 	}
192       mod = dwfl_addrmodule (dwfl, pc);
193       if (mod)
194 	symname2 = dwfl_module_addrname (mod, pc);
195 
196       // Note that the following assert might in theory even fail on x86_64,
197       // there is no guarantee that the compiler doesn't reorder the
198       // instructions or even inserts some padding instructions at the end
199       // (which apparently happens on ppc64).
200       if (use_raise_jmp_patching)
201 	{
202           if (symname2 != NULL && strcmp (symname2, "backtracegen") == 0)
203 	    {
204 	      fprintf (stderr,
205 		       "use_raise_jmp_patching didn't expect symname2 "
206 		       "'backtracegen'\n");
207 	      abort ();
208 	    }
209 	}
210       break;
211   }
212 }
213 
214 static int
frame_callback(Dwfl_Frame * state,void * frame_arg)215 frame_callback (Dwfl_Frame *state, void *frame_arg)
216 {
217   int *framenop = frame_arg;
218   Dwarf_Addr pc;
219   bool isactivation;
220 
221   if (*framenop > 16)
222     {
223       error (0, 0, "Too many frames: %d\n", *framenop);
224       return DWARF_CB_ABORT;
225     }
226 
227   if (! dwfl_frame_pc (state, &pc, &isactivation))
228     {
229       error (0, 0, "%s", dwfl_errmsg (-1));
230       return DWARF_CB_ABORT;
231     }
232   Dwarf_Addr pc_adjusted = pc - (isactivation ? 0 : 1);
233 
234   /* Get PC->SYMNAME.  */
235   Dwfl_Thread *thread = dwfl_frame_thread (state);
236   Dwfl *dwfl = dwfl_thread_dwfl (thread);
237   Dwfl_Module *mod = dwfl_addrmodule (dwfl, pc_adjusted);
238   const char *symname = NULL;
239   if (mod)
240     symname = dwfl_module_addrname (mod, pc_adjusted);
241 
242   printf ("#%2d %#" PRIx64 "%4s\t%s\n", *framenop, (uint64_t) pc,
243 	  ! isactivation ? "- 1" : "", symname ?: "<null>");
244   pid_t tid = dwfl_thread_tid (thread);
245   callback_verify (tid, *framenop, pc, symname, dwfl);
246   (*framenop)++;
247 
248   return DWARF_CB_OK;
249 }
250 
251 static int
thread_callback(Dwfl_Thread * thread,void * thread_arg)252 thread_callback (Dwfl_Thread *thread, void *thread_arg __attribute__((unused)))
253 {
254   printf ("TID %ld:\n", (long) dwfl_thread_tid (thread));
255   int frameno = 0;
256   switch (dwfl_thread_getframes (thread, frame_callback, &frameno))
257     {
258     case 0:
259       break;
260     case DWARF_CB_ABORT:
261       return DWARF_CB_ABORT;
262     case -1:
263       error (0, 0, "dwfl_thread_getframes: %s", dwfl_errmsg (-1));
264       /* All platforms do not have yet proper unwind termination.  */
265       break;
266     default:
267       abort ();
268     }
269   return DWARF_CB_OK;
270 }
271 
272 static void
dump(Dwfl * dwfl)273 dump (Dwfl *dwfl)
274 {
275   ptrdiff_t ptrdiff = dwfl_getmodules (dwfl, dump_modules, NULL, 0);
276   assert (ptrdiff == 0);
277   bool err = false;
278   switch (dwfl_getthreads (dwfl, thread_callback, NULL))
279     {
280     case 0:
281       break;
282     case DWARF_CB_ABORT:
283       err = true;
284       break;
285     case -1:
286       error (0, 0, "dwfl_getthreads: %s", dwfl_errmsg (-1));
287       err = true;
288       break;
289     default:
290       abort ();
291     }
292   callback_verify (0, 0, 0, NULL, dwfl);
293   if (err)
294     exit (EXIT_FAILURE);
295 }
296 
297 struct see_exec_module
298 {
299   Dwfl_Module *mod;
300   char selfpath[PATH_MAX + 1];
301 };
302 
303 static int
see_exec_module(Dwfl_Module * mod,void ** userdata,const char * name,Dwarf_Addr start,void * arg)304 see_exec_module (Dwfl_Module *mod, void **userdata __attribute__ ((unused)),
305 		 const char *name __attribute__ ((unused)),
306 		 Dwarf_Addr start __attribute__ ((unused)), void *arg)
307 {
308   struct see_exec_module *data = arg;
309   if (strcmp (name, data->selfpath) != 0)
310     return DWARF_CB_OK;
311   assert (data->mod == NULL);
312   data->mod = mod;
313   return DWARF_CB_ABORT;
314 }
315 
316 /* We used to do this on x86_64 only (see backtrace-child why we now don't):
317      PC will get changed to function 'jmp' by backtrace.c function
318      prepare_thread.  Then SIGUSR2 will be signalled to backtrace-child
319      which will invoke function sigusr2.
320      This is all done so that signal interrupts execution of the very first
321      instruction of a function.  Properly handled unwind should not slip into
322      the previous unrelated function.  */
323 
324 #ifdef __x86_64__
325 /* #define RAISE_JMP_PATCHING 1 */
326 #endif
327 
328 static void
prepare_thread(pid_t pid2,void (* jmp)(void))329 prepare_thread (pid_t pid2 __attribute__ ((unused)),
330 		void (*jmp) (void) __attribute__ ((unused)))
331 {
332 #ifndef RAISE_JMP_PATCHING
333   abort ();
334 #else /* RAISE_JMP_PATCHING */
335   long l;
336   struct user_regs_struct user_regs;
337   errno = 0;
338   l = ptrace (PTRACE_GETREGS, pid2, 0, (intptr_t) &user_regs);
339   assert (l == 0);
340   user_regs.rip = (intptr_t) jmp;
341   l = ptrace (PTRACE_SETREGS, pid2, 0, (intptr_t) &user_regs);
342   assert (l == 0);
343   l = ptrace (PTRACE_CONT, pid2, NULL, (void *) (intptr_t) SIGUSR2);
344   int status;
345   pid_t got = waitpid (pid2, &status, __WALL);
346   assert (got == pid2);
347   assert (WIFSTOPPED (status));
348   assert (WSTOPSIG (status) == SIGUSR1);
349 #endif /* RAISE_JMP_PATCHING */
350 }
351 
352 #include <asm/unistd.h>
353 #include <unistd.h>
354 
355 static void
report_pid(Dwfl * dwfl,pid_t pid)356 report_pid (Dwfl *dwfl, pid_t pid)
357 {
358   int result = dwfl_linux_proc_report (dwfl, pid);
359   if (result < 0)
360     error (2, 0, "dwfl_linux_proc_report: %s", dwfl_errmsg (-1));
361   else if (result > 0)
362     error (2, result, "dwfl_linux_proc_report");
363 
364   if (dwfl_report_end (dwfl, NULL, NULL) != 0)
365     error (2, 0, "dwfl_report_end: %s", dwfl_errmsg (-1));
366 
367   result = dwfl_linux_proc_attach (dwfl, pid, true);
368   if (result < 0)
369     error (2, 0, "dwfl_linux_proc_attach: %s", dwfl_errmsg (-1));
370   else if (result > 0)
371     error (2, result, "dwfl_linux_proc_attach");
372 }
373 
374 static Dwfl *
pid_to_dwfl(pid_t pid)375 pid_to_dwfl (pid_t pid)
376 {
377   static char *debuginfo_path;
378   static const Dwfl_Callbacks proc_callbacks =
379     {
380       .find_debuginfo = dwfl_standard_find_debuginfo,
381       .debuginfo_path = &debuginfo_path,
382 
383       .find_elf = dwfl_linux_proc_find_elf,
384     };
385   Dwfl *dwfl = dwfl_begin (&proc_callbacks);
386   if (dwfl == NULL)
387     error (2, 0, "dwfl_begin: %s", dwfl_errmsg (-1));
388   report_pid (dwfl, pid);
389   return dwfl;
390 }
391 
392 static void
exec_dump(const char * exec)393 exec_dump (const char *exec)
394 {
395   pid_t pid = fork ();
396   switch (pid)
397   {
398     case -1:
399       abort ();
400     case 0:
401       execl (exec, exec, "--ptraceme", NULL);
402       abort ();
403     default:
404       break;
405   }
406 
407   /* Catch the main thread.  Catch it first otherwise the /proc evaluation of
408      PID may have caught still ourselves before executing execl above.  */
409   errno = 0;
410   int status;
411   pid_t got = waitpid (pid, &status, 0);
412   assert (got == pid);
413   assert (WIFSTOPPED (status));
414   // Main thread will signal SIGUSR2.  Other thread will signal SIGUSR1.
415   assert (WSTOPSIG (status) == SIGUSR2);
416 
417   /* Catch the spawned thread.  Do not use __WCLONE as we could get racy
418      __WCLONE, probably despite pthread_create already had to be called the new
419      task is not yet alive enough for waitpid.  */
420   pid_t pid2 = waitpid (-1, &status, __WALL);
421   assert (pid2 > 0);
422   assert (pid2 != pid);
423   assert (WIFSTOPPED (status));
424   // Main thread will signal SIGUSR2.  Other thread will signal SIGUSR1.
425   assert (WSTOPSIG (status) == SIGUSR1);
426 
427   Dwfl *dwfl = pid_to_dwfl (pid);
428   char *selfpathname;
429   int i = asprintf (&selfpathname, "/proc/%ld/exe", (long) pid);
430   assert (i > 0);
431   struct see_exec_module data;
432   ssize_t ssize = readlink (selfpathname, data.selfpath,
433 			    sizeof (data.selfpath));
434   free (selfpathname);
435   assert (ssize > 0 && ssize < (ssize_t) sizeof (data.selfpath));
436   data.selfpath[ssize] = '\0';
437   data.mod = NULL;
438   dwfl_getmodules (dwfl, see_exec_module, &data, 0);
439   assert (data.mod != NULL);
440   GElf_Addr loadbase;
441   Elf *elf = dwfl_module_getelf (data.mod, &loadbase);
442   GElf_Ehdr ehdr_mem, *ehdr = gelf_getehdr (elf, &ehdr_mem);
443   assert (ehdr != NULL);
444   /* It is false also on x86_64 with i386 inferior.  */
445 #ifndef RAISE_JMP_PATCHING
446   use_raise_jmp_patching = false;
447 #else /* RAISE_JMP_PATCHING_ */
448   use_raise_jmp_patching = ehdr->e_machine == EM_X86_64;
449 #endif /* __x86_64__ */
450   void (*jmp) (void) = 0;
451   if (use_raise_jmp_patching)
452     {
453       // Find inferior symbol named "jmp".
454       int nsym = dwfl_module_getsymtab (data.mod);
455       int symi;
456       for (symi = 1; symi < nsym; ++symi)
457 	{
458 	  GElf_Sym symbol;
459 	  const char *symbol_name = dwfl_module_getsym (data.mod, symi, &symbol, NULL);
460 	  if (symbol_name == NULL)
461 	    continue;
462 	  switch (GELF_ST_TYPE (symbol.st_info))
463 	    {
464 	    case STT_SECTION:
465 	    case STT_FILE:
466 	    case STT_TLS:
467 	      continue;
468 	    default:
469 	      if (strcmp (symbol_name, "jmp") != 0)
470 		continue;
471 	      break;
472 	    }
473 	  /* LOADBASE is already applied here.  */
474 	  jmp = (void (*) (void)) (uintptr_t) symbol.st_value;
475 	  break;
476 	}
477       assert (symi < nsym);
478       prepare_thread (pid2, jmp);
479     }
480   dwfl_end (dwfl);
481   check_tid = pid2;
482   dwfl = pid_to_dwfl (pid);
483   dump (dwfl);
484   dwfl_end (dwfl);
485 }
486 
487 #define OPT_BACKTRACE_EXEC 0x100
488 
489 static const struct argp_option options[] =
490   {
491     { "backtrace-exec", OPT_BACKTRACE_EXEC, "EXEC", 0, N_("Run executable"), 0 },
492     { NULL, 0, NULL, 0, NULL, 0 }
493   };
494 
495 
496 static error_t
parse_opt(int key,char * arg,struct argp_state * state)497 parse_opt (int key, char *arg, struct argp_state *state)
498 {
499   switch (key)
500     {
501     case ARGP_KEY_INIT:
502       state->child_inputs[0] = state->input;
503       break;
504 
505     case OPT_BACKTRACE_EXEC:
506       exec_dump (arg);
507       exit (0);
508 
509     default:
510       return ARGP_ERR_UNKNOWN;
511     }
512   return 0;
513 }
514 
515 int
main(int argc,char ** argv)516 main (int argc __attribute__ ((unused)), char **argv)
517 {
518   /* We use no threads here which can interfere with handling a stream.  */
519   __fsetlocking (stdin, FSETLOCKING_BYCALLER);
520   __fsetlocking (stdout, FSETLOCKING_BYCALLER);
521   __fsetlocking (stderr, FSETLOCKING_BYCALLER);
522 
523   /* Set locale.  */
524   (void) setlocale (LC_ALL, "");
525 
526   elf_version (EV_CURRENT);
527 
528   Dwfl *dwfl = NULL;
529   const struct argp_child argp_children[] =
530     {
531       { .argp = dwfl_standard_argp () },
532       { .argp = NULL }
533     };
534   const struct argp argp =
535     {
536       options, parse_opt, NULL, NULL, argp_children, NULL, NULL
537     };
538   (void) argp_parse (&argp, argc, argv, 0, NULL, &dwfl);
539   assert (dwfl != NULL);
540   /* We want to make sure the dwfl was properly attached.  */
541   if (dwfl_pid (dwfl) < 0)
542     error (2, 0, "dwfl_pid: %s", dwfl_errmsg (-1));
543   dump (dwfl);
544   dwfl_end (dwfl);
545   return 0;
546 }
547 
548 #endif /* ! __linux__ */
549 
550