Add tests that backtrace and backtrace_symbols produce correct results.
[platform/upstream/glibc.git] / debug / tst-backtrace3.c
1 /* Test backtrace and backtrace_symbols for recursive calls.
2    Copyright (C) 2010-2013 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, see
17    <http://www.gnu.org/licenses/>.  */
18
19 #include <execinfo.h>
20 #include <search.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 static int do_test (void);
26 #define TEST_FUNCTION do_test ()
27 #include "../test-skeleton.c"
28
29 /* Set to a non-zero value if the test fails.  */
30 int ret;
31
32 /* Accesses to X are used to prevent optimization.  */
33 volatile int x;
34
35 /* Called if the test fails.  */
36 #define FAIL() \
37   do { printf ("Failure on line %d\n", __LINE__); ret = 1; } while (0)
38
39 /* The backtrace should include at least 3 * fn, and do_test.  */
40 #define NUM_FUNCTIONS 4
41
42 /* Use this attribute to prevent inlining, so that all expected frames
43    are present.  */
44 #define NO_INLINE __attribute__ ((noinline))
45
46 NO_INLINE int
47 fn (int c)
48 {
49   void *addresses[NUM_FUNCTIONS];
50   char **symbols;
51   int n;
52   int i;
53
54   if (c > 0)
55     {
56       fn (c - 1);
57       return x;
58     }
59   /* Get the backtrace addresses.  */
60   n = backtrace (addresses, sizeof (addresses) / sizeof (addresses[0]));
61   printf ("Obtained backtrace with %d functions\n", n);
62   /*  Check that there are at least four functions.  */
63   if (n < NUM_FUNCTIONS)
64     {
65       FAIL ();
66       return 1;
67     }
68   /* Convert them to symbols.  */
69   symbols = backtrace_symbols (addresses, n);
70   /* Check that symbols were obtained.  */
71   if (symbols == NULL)
72     {
73       FAIL ();
74       return 1;
75     }
76   for (i = 0; i < n; ++i)
77     printf ("Function %d: %s\n", i, symbols[i]);
78   /* Check that the function names obtained are accurate.  */
79   for (i = 0; i < n - 1; ++i)
80     if (strstr (symbols[i], "fn") == NULL)
81       {
82         FAIL ();
83         return 1;
84       }
85   /* Symbol names are not available for static functions, so we do not
86      check do_test.  */
87   return x;
88 }
89
90 NO_INLINE static int
91 do_test (void)
92 {
93   fn (2);
94   return ret;
95 }