More tweaks for CONSISTENCY CHECK readability
[freeradius.git] / src / lib / debug.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * @file debug.c
19  * @brief Various functions to aid in debugging
20  *
21  * @copyright 2013  The FreeRADIUS server project
22  * @copyright 2013  Arran Cudbard-Bell <a.cudbardb@freeradius.org>
23  */
24 #include <assert.h>
25 #include <freeradius-devel/libradius.h>
26 #include <sys/stat.h>
27
28 #if defined(HAVE_MALLOPT) && defined(HAVE_MALLOC_H)
29 #  include <malloc.h>
30 #endif
31
32 /*
33  *      runtime backtrace functions are not POSIX but are included in
34  *      glibc, OSX >= 10.5 and various BSDs
35  */
36 #ifdef HAVE_EXECINFO
37 #  include <execinfo.h>
38 #endif
39
40 #ifdef HAVE_SYS_PRCTL_H
41 #  include <sys/prctl.h>
42 #endif
43
44 #ifdef HAVE_SYS_RESOURCE_H
45 #  include <sys/resource.h>
46 #endif
47
48 #ifdef HAVE_PTHREAD_H
49 #  define PTHREAD_MUTEX_LOCK pthread_mutex_lock
50 #  define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
51 #else
52 #  define PTHREAD_MUTEX_LOCK(_x)
53 #  define PTHREAD_MUTEX_UNLOCK(_x)
54 #endif
55
56 #ifdef HAVE_EXECINFO
57 #  define MAX_BT_FRAMES 128
58 #  define MAX_BT_CBUFF  65536                           //!< Should be a power of 2
59
60 #  ifdef HAVE_PTHREAD_H
61 static pthread_mutex_t fr_debug_init = PTHREAD_MUTEX_INITIALIZER;
62 #  endif
63
64 typedef struct fr_bt_info {
65         void            *obj;                           //!< Memory address of the block of allocated memory.
66         void            *frames[MAX_BT_FRAMES];         //!< Backtrace frame data
67         int             count;                          //!< Number of frames stored
68 } fr_bt_info_t;
69
70 struct fr_bt_marker {
71         void            *obj;                           //!< Pointer to the parent object, this is our needle
72                                                         //!< when we iterate over the contents of the circular buffer.
73         fr_cbuff_t      *cbuff;                         //!< Where we temporarily store the backtraces
74 };
75 #endif
76
77 static char panic_action[512];                          //!< The command to execute when panicking.
78 static fr_fault_cb_t panic_cb = NULL;                   //!< Callback to execute whilst panicking, before the
79                                                         //!< panic_action.
80 static fr_fault_log_t fr_fault_log = NULL;              //!< Function to use to process logging output.
81 static int fr_fault_log_fd = STDERR_FILENO;             //!< Where to write debug output.
82
83 static int fr_debugger_present = -1;                    //!< Whether were attached to by a debugger.
84
85 #ifdef HAVE_SYS_RESOURCE_H
86 static struct rlimit core_limits;
87 #endif
88
89 #define FR_FAULT_LOG(fmt, ...) fr_fault_log(fmt "\n", ## __VA_ARGS__)
90
91 /** Stub callback to see if the SIGTRAP handler is overriden
92  *
93  * @param signum signal raised.
94  */
95 static void _sigtrap_handler(UNUSED int signum)
96 {
97         fr_debugger_present = 0;
98         signal(SIGTRAP, SIG_DFL);
99 }
100
101 /** Break in debugger (if were running under a debugger)
102  *
103  * If the server is running under a debugger this will raise a
104  * SIGTRAP which will pause the running process.
105  *
106  * If the server is not running under debugger then this will do nothing.
107  */
108 void fr_debug_break(void)
109 {
110         if (fr_debugger_present == -1) {
111                 fr_debugger_present = 0;
112                 signal(SIGTRAP, _sigtrap_handler);
113                 raise(SIGTRAP);
114         } else if (fr_debugger_present == 1) {
115                 raise(SIGTRAP);
116         }
117 }
118
119 #ifdef HAVE_EXECINFO
120 /** Generate a backtrace for an object during destruction
121  *
122  * If this is the first entry being inserted
123  */
124 static int _fr_do_bt(fr_bt_marker_t *marker)
125 {
126         fr_bt_info_t *bt;
127
128         if (!fr_assert(marker->obj) || !fr_assert(marker->cbuff)) {
129                 return -1;
130         }
131
132         bt = talloc_zero(marker->cbuff, fr_bt_info_t);
133         if (!bt) {
134                 return -1;
135         }
136         bt->count = backtrace(bt->frames, MAX_BT_FRAMES);
137         fr_cbuff_rp_insert(marker->cbuff, bt);
138
139         return 0;
140 }
141
142 /** Print backtrace entry for a given object
143  *
144  * @param cbuff to search in.
145  * @param obj pointer to original object
146  */
147 void backtrace_print(fr_cbuff_t *cbuff, void *obj)
148 {
149         fr_bt_info_t *p;
150         bool found = false;
151         int i = 0;
152         char **frames;
153
154         while ((p = fr_cbuff_rp_next(cbuff, NULL))) {
155                 if ((p == obj) || !obj) {
156                         found = true;
157                         frames = backtrace_symbols(p->frames, p->count);
158
159                         fprintf(stderr, "Stacktrace for: %p\n", p);
160                         for (i = 0; i < p->count; i++) {
161                                 fprintf(stderr, "%s\n", frames[i]);
162                         }
163
164                         /* We were only asked to look for one */
165                         if (obj) {
166                                 return;
167                         }
168                 }
169         };
170
171         if (!found) {
172                 fprintf(stderr, "No backtrace available for %p", obj);
173         }
174 }
175
176 /** Inserts a backtrace marker into the provided context
177  *
178  * Allows for maximum laziness and will initialise a circular buffer if one has not already been created.
179  *
180  * Code augmentation should look something like:
181 @verbatim
182         // Create a static cbuffer pointer, the first call to backtrace_attach will initialise it
183         static fr_cbuff *my_obj_bt;
184
185         my_obj_t *alloc_my_obj(TALLOC_CTX *ctx) {
186                 my_obj_t *this;
187
188                 this = talloc(ctx, my_obj_t);
189
190                 // Attach backtrace marker to object
191                 backtrace_attach(&my_obj_bt, this);
192
193                 return this;
194         }
195 @endverbatim
196  *
197  * Then, later when a double free occurs:
198 @verbatim
199         (gdb) call backtrace_print(&my_obj_bt, <pointer to double freed memory>)
200 @endverbatim
201  *
202  * which should print a limited backtrace to stderr. Note, this backtrace will not include any argument
203  * values, but should at least show the code path taken.
204  *
205  * @param cbuff this should be a pointer to a static *fr_cbuff.
206  * @param obj we want to generate a backtrace for.
207  */
208 fr_bt_marker_t *fr_backtrace_attach(fr_cbuff_t **cbuff, TALLOC_CTX *obj)
209 {
210         fr_bt_marker_t *marker;
211
212         if (*cbuff == NULL) {
213                 PTHREAD_MUTEX_LOCK(&fr_debug_init);
214                 /* Check again now we hold the mutex - eww*/
215                 if (*cbuff == NULL) {
216                         TALLOC_CTX *ctx;
217
218                         ctx = fr_autofree_ctx();
219                         *cbuff = fr_cbuff_alloc(ctx, MAX_BT_CBUFF, true);
220                 }
221                 PTHREAD_MUTEX_UNLOCK(&fr_debug_init);
222         }
223
224         marker = talloc(obj, fr_bt_marker_t);
225         if (!marker) {
226                 return NULL;
227         }
228
229         marker->obj = (void *) obj;
230         marker->cbuff = *cbuff;
231
232         talloc_set_destructor(marker, _fr_do_bt);
233
234         return marker;
235 }
236 #else
237 void backtrace_print(UNUSED fr_cbuff_t *cbuff, UNUSED void *obj)
238 {
239         fprintf(stderr, "Server built without fr_backtrace_* support, requires execinfo.h and possibly -lexecinfo\n");
240 }
241 fr_bt_marker_t *fr_backtrace_attach(UNUSED fr_cbuff_t **cbuff, UNUSED TALLOC_CTX *obj)
242 {
243         fprintf(stderr, "Server built without fr_backtrace_* support, requires execinfo.h and possibly -lexecinfo\n");
244         abort();
245 }
246 #endif /* ifdef HAVE_EXECINFO */
247
248 static int _panic_on_free(UNUSED char *foo)
249 {
250         fr_fault(SIGUSR1);
251         return -1;      /* this should make the free fail */
252 }
253
254 /** Insert memory into the context of another talloc memory chunk which
255  * causes a panic when freed.
256  *
257  * @param ctx TALLOC_CTX to monitor for frees.
258  */
259 void fr_panic_on_free(TALLOC_CTX *ctx)
260 {
261         char *ptr;
262
263         ptr = talloc(ctx, char);
264         talloc_set_destructor(ptr, _panic_on_free);
265 }
266
267 /** Set the dumpable flag, also controls whether processes can PATTACH
268  *
269  * @param dumpable whether we should allow core dumping
270  */
271 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
272 static int fr_set_dumpable_flag(bool dumpable)
273 {
274         if (prctl(PR_SET_DUMPABLE, dumpable ? 1 : 0) < 0) {
275                 fr_strerror_printf("Cannot re-enable core dumps: prctl(PR_SET_DUMPABLE) failed: %s",
276                                    fr_syserror(errno));
277                 return -1;
278         }
279
280         return 0;
281 }
282 #else
283 static int fr_set_dumpable_flag(UNUSED bool dumpable)
284 {
285         fr_strerror_printf("Changing value of PR_DUMPABLE not supported on this system");
286         return -2;
287 }
288 #endif
289
290 /** Get the processes dumpable flag
291  *
292  */
293 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_GET_DUMPABLE)
294 static int fr_get_dumpable_flag(void)
295 {
296         int ret;
297
298         ret = prctl(PR_GET_DUMPABLE);
299         if (ret < 0) {
300                 fr_strerror_printf("Cannot get dumpable flag: %s", fr_syserror(errno));
301                 return -1;
302         }
303
304         /*
305          *  Linux is crazy and prctl sometimes returns 2 for disabled
306          */
307         if (ret != 1) return 0;
308         return 1;
309 }
310 #else
311 static int fr_get_dumpable_flag(void)
312 {
313         fr_strerror_printf("Getting value of PR_DUMPABLE not supported on this system");
314         return -2;
315 }
316 #endif
317
318
319 /** Get the current maximum for core files
320  *
321  * Do this before anything else so as to ensure it's properly initialized.
322  */
323 int fr_set_dumpable_init(void)
324 {
325 #ifdef HAVE_SYS_RESOURCE_H
326         if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
327                 fr_strerror_printf("Failed to get current core limit:  %s", fr_syserror(errno));
328                 return -1;
329         }
330 #endif
331         return 0;
332 }
333
334 /** Enable or disable core dumps
335  *
336  * @param allow_core_dumps whether to enable or disable core dumps.
337  */
338 int fr_set_dumpable(bool allow_core_dumps)
339 {
340         /*
341          *      If configured, turn core dumps off.
342          */
343         if (!allow_core_dumps) {
344 #ifdef HAVE_SYS_RESOURCE_H
345                 struct rlimit no_core;
346
347                 no_core.rlim_cur = 0;
348                 no_core.rlim_max = 0;
349
350                 if (setrlimit(RLIMIT_CORE, &no_core) < 0) {
351                         fr_strerror_printf("Failed disabling core dumps: %s", fr_syserror(errno));
352
353                         return -1;
354                 }
355 #endif
356                 return 0;
357         }
358
359         if (fr_set_dumpable_flag(true) < 0) return -1;
360
361         /*
362          *      Reset the core dump limits to their original value.
363          */
364 #ifdef HAVE_SYS_RESOURCE_H
365         if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
366                 fr_strerror_printf("Cannot update core dump limit: %s", fr_syserror(errno));
367
368                 return -1;
369         }
370 #endif
371         return 0;
372 }
373
374 /** Check to see if panic_action file is world writeable
375  *
376  * @return 0 if file is OK, else -1.
377  */
378 static int fr_fault_check_permissions(void)
379 {
380         char const *p, *q;
381         size_t len;
382         char filename[256];
383         struct stat statbuf;
384
385         /*
386          *      Try and guess which part of the command is the binary, and check to see if
387          *      it's world writeable, to try and save the admin from their own stupidity.
388          *
389          *      @fixme we should do this properly and take into account single and double
390          *      quotes.
391          */
392         if ((q = strchr(panic_action, ' '))) {
393                 /*
394                  *      need to use a static buffer, because mallocing memory in a signal handler
395                  *      is a bad idea and can result in deadlock.
396                  */
397                 len = snprintf(filename, sizeof(filename), "%.*s", (int)(q - panic_action), panic_action);
398                 if (is_truncated(len, sizeof(filename))) {
399                         fr_strerror_printf("Failed writing panic_action to temporary buffer (truncated)");
400                         return -1;
401                 }
402                 p = filename;
403         } else {
404                 p = panic_action;
405         }
406
407         if (stat(p, &statbuf) == 0) {
408 #ifdef S_IWOTH
409                 if ((statbuf.st_mode & S_IWOTH) != 0) {
410                         fr_strerror_printf("panic_action file \"%s\" is globally writable", p);
411                         return -1;
412                 }
413 #endif
414         }
415
416         return 0;
417 }
418
419 /** Prints a simple backtrace (if execinfo is available) and calls panic_action if set.
420  *
421  * @param sig caught
422  */
423 void fr_fault(int sig)
424 {
425         char cmd[sizeof(panic_action) + 20];
426         char *out = cmd;
427         size_t left = sizeof(cmd), ret;
428
429         char const *p = panic_action;
430         char const *q;
431
432         int code;
433
434         /*
435          *      Makes the backtraces slightly cleaner
436          */
437         memset(cmd, 0, sizeof(cmd));
438
439         FR_FAULT_LOG("CAUGHT SIGNAL: %s", strsignal(sig));
440
441         /*
442          *      Check for administrator sanity.
443          */
444         if (fr_fault_check_permissions() < 0) {
445                 FR_FAULT_LOG("Refusing to execute panic action: %s", fr_strerror());
446                 goto finish;
447         }
448
449         /*
450          *      Run the callback if one was registered
451          */
452         if (panic_cb && (panic_cb(sig) < 0)) goto finish;
453
454         /*
455          *      Produce a simple backtrace - They've very basic but at least give us an
456          *      idea of the area of the code we hit the issue in.
457          *
458          *      See below in fr_fault_setup() and
459          *      https://sourceware.org/bugzilla/show_bug.cgi?id=16159
460          *      for why we only print backtraces in debug builds if we're using GLIBC.
461          */
462 #if defined(HAVE_EXECINFO) && (!defined(NDEBUG) || !defined(__GNUC__))
463         {
464                 size_t frame_count, i;
465                 void *stack[MAX_BT_FRAMES];
466                 char **strings;
467
468                 frame_count = backtrace(stack, MAX_BT_FRAMES);
469
470                 FR_FAULT_LOG("Backtrace of last %zu frames:", frame_count);
471
472                 /*
473                  *      Only use backtrace_symbols() if we don't have a logging fd.
474                  *      If the server has experienced memory corruption, there's
475                  *      a high probability that calling backtrace_symbols() which
476                  *      mallocs more memory, will fail.
477                  */
478                 if (fr_fault_log_fd < 0) {
479                         strings = backtrace_symbols(stack, frame_count);
480                         for (i = 0; i < frame_count; i++) {
481                                 FR_FAULT_LOG("%s", strings[i]);
482                         }
483                         free(strings);
484                 } else {
485                         backtrace_symbols_fd(stack, frame_count, fr_fault_log_fd);
486                 }
487         }
488 #endif
489
490         /* No panic action set... */
491         if (panic_action[0] == '\0') {
492                 FR_FAULT_LOG("No panic action set");
493                 goto finish;
494         }
495
496         /* Substitute %p for the current PID (useful for attaching a debugger) */
497         while ((q = strstr(p, "%p"))) {
498                 out += ret = snprintf(out, left, "%.*s%d", (int) (q - p), p, (int) getpid());
499                 if (left <= ret) {
500                 oob:
501                         FR_FAULT_LOG("Panic action too long");
502                         fr_exit_now(1);
503                 }
504                 left -= ret;
505                 p = q + 2;
506         }
507         if (strlen(p) >= left) goto oob;
508         strlcpy(out, p, left);
509
510         FR_FAULT_LOG("Calling: %s", cmd);
511
512         {
513                 bool disable = false;
514
515                 /*
516                  *      Here we temporarily enable the dumpable flag so if GBD or LLDB
517                  *      is called in the panic_action, they can pattach tot he running
518                  *      process.
519                  */
520                 if (fr_get_dumpable_flag() == 0) {
521                         if ((fr_set_dumpable_flag(true) < 0) || !fr_get_dumpable_flag()) {
522                                 FR_FAULT_LOG("Failed setting dumpable flag, pattach may not work: %s", fr_strerror());
523                         } else {
524                                 disable = true;
525                         }
526                         FR_FAULT_LOG("Temporarily setting PR_DUMPABLE to 1");
527                 }
528
529                 code = system(cmd);
530
531                 /*
532                  *      We only want to error out here, if dumpable was originally disabled
533                  *      and we managed to change the value to enabled, but failed
534                  *      setting it back to disabled.
535                  */
536                 if (disable) {
537                         FR_FAULT_LOG("Resetting PR_DUMPABLE to 0");
538                         if (fr_set_dumpable_flag(false) < 0) {
539                                 FR_FAULT_LOG("Failed reseting dumpable flag to off: %s", fr_strerror());
540                                 FR_FAULT_LOG("Exiting due to insecure process state");
541                                 fr_exit_now(1);
542                         }
543                 }
544         }
545
546         FR_FAULT_LOG("Panic action exited with %i", code);
547
548 finish:
549 #ifdef SIGUSR1
550         if (sig == SIGUSR1) {
551                 return;
552         }
553 #endif
554         fr_exit_now(1);
555 }
556
557 #ifdef SIGABRT
558 /** Work around debuggers which can't backtrace past the signal handler
559  *
560  * At least this provides us some information when we get talloc errors.
561  */
562 static void _fr_talloc_fault(char const *reason)
563 {
564         fr_fault_log("talloc abort: %s\n", reason);
565         fr_fault(SIGABRT);
566 }
567 #endif
568
569 /** Wrapper to pass talloc log output to our fr_fault_log function
570  *
571  */
572 static void _fr_talloc_log(char const *msg)
573 {
574         fr_fault_log("%s\n", msg);
575 }
576
577 /** Generate a talloc memory report for a context and print to stderr/stdout
578  *
579  * @param ctx to generate a report for, may be NULL in which case the root context is used.
580  */
581 int fr_log_talloc_report(TALLOC_CTX *ctx)
582 {
583         FILE *log;
584         int i = 0;
585         int fd;
586
587         fd = dup(fr_fault_log_fd);
588         if (fd < 0) {
589                 fr_strerror_printf("Couldn't write memory report, failed to dup log fd: %s", fr_syserror(errno));
590                 return -1;
591         }
592         log = fdopen(fd, "w");
593         if (!log) {
594                 close(fd);
595                 fr_strerror_printf("Couldn't write memory report, fdopen failed: %s", fr_syserror(errno));
596                 return -1;
597         }
598
599         fprintf(log, "Current state of talloced memory:\n");
600         if (!ctx) {
601                 talloc_report_full(NULL, log);
602         } else do {
603                 fprintf(log, "Context level %i", i++);
604
605                 talloc_report_full(ctx, log);
606         } while ((ctx = talloc_parent(ctx)) && talloc_parent(ctx));  /* Stop before we hit NULL ctx */
607
608         fclose(log);
609
610         return 0;
611 }
612
613 /** Signal handler to print out a talloc memory report
614  *
615  * @param sig caught
616  */
617 static void _fr_fault_mem_report(int sig)
618 {
619         fr_fault_log("CAUGHT SIGNAL: %s\n", strsignal(sig));
620
621         if (fr_log_talloc_report(NULL) < 0) fr_perror("memreport");
622 }
623
624 static int _fr_disable_null_tracking(UNUSED bool *p)
625 {
626         talloc_disable_null_tracking();
627         return 0;
628 }
629
630 /** Registers signal handlers to execute panic_action on fatal signal
631  *
632  * May be called multiple time to change the panic_action/program.
633  *
634  * @param cmd to execute on fault. If present %p will be substituted
635  *        for the parent PID before the command is executed, and %e
636  *        will be substituted for the currently running program.
637  * @param program Name of program currently executing (argv[0]).
638  * @return 0 on success -1 on failure.
639  */
640 int fr_fault_setup(char const *cmd, char const *program)
641 {
642         static bool setup = false;
643
644         char *out = panic_action;
645         size_t left = sizeof(panic_action), ret;
646
647         char const *p = cmd;
648         char const *q;
649
650         if (cmd) {
651                 /* Substitute %e for the current program */
652                 while ((q = strstr(p, "%e"))) {
653                         out += ret = snprintf(out, left, "%.*s%s", (int) (q - p), p, program ? program : "");
654                         if (left <= ret) {
655                         oob:
656                                 fr_strerror_printf("Panic action too long");
657                                 return -1;
658                         }
659                         left -= ret;
660                         p = q + 2;
661                 }
662                 if (strlen(p) >= left) goto oob;
663                 strlcpy(out, p, left);
664         } else {
665                 *panic_action = '\0';
666         }
667
668         /*
669          *      Check for administrator sanity.
670          */
671         if (fr_fault_check_permissions() < 0) return -1;
672
673         /* Unsure what the side effects of changing the signal handler mid execution might be */
674         if (!setup) {
675 #ifdef SIGSEGV
676                 if (fr_set_signal(SIGSEGV, fr_fault) < 0) return -1;
677 #endif
678 #ifdef SIGBUS
679                 if (fr_set_signal(SIGBUS, fr_fault) < 0) return -1;
680 #endif
681 #ifdef SIGABRT
682                 if (fr_set_signal(SIGABRT, fr_fault) < 0) return -1;
683                 /*
684                  *  Use this instead of abort so we get a
685                  *  full backtrace with broken versions of LLDB
686                  */
687                 talloc_set_abort_fn(_fr_talloc_fault);
688 #endif
689 #ifdef SIGFPE
690                 if (fr_set_signal(SIGFPE, fr_fault) < 0) return -1;
691 #endif
692
693 #ifdef SIGUSR1
694                 if (fr_set_signal(SIGUSR1, fr_fault) < 0) return -1;
695 #endif
696
697 #ifdef SIGUSR2
698                 if (fr_set_signal(SIGUSR2, _fr_fault_mem_report) < 0) return -1;
699 #endif
700
701                 /*
702                  *  Setup the default logger
703                  */
704                 if (!fr_fault_log) fr_fault_set_log_fn(NULL);
705                 talloc_set_log_fn(_fr_talloc_log);
706
707                 /*
708                  *  Needed for memory reports
709                  *
710                  *  Disable null tracking on exit, else valgrind complains
711                  */
712                 {
713                         TALLOC_CTX *autofree;
714                         bool *marker;
715
716                         talloc_enable_null_tracking();
717
718                         autofree = talloc_autofree_context();
719                         marker = talloc(autofree, bool);
720                         talloc_set_destructor(marker, _fr_disable_null_tracking);
721                 }
722
723                 /*
724                  *  If were using glibc malloc > 2.4 this scribbles over
725                  *  uninitialised and freed memory, to make memory issues easier
726                  *  to track down.
727                  */
728 #if defined(HAVE_MALLOPT) && !defined(NDEBUG)
729                 mallopt(M_PERTURB, 0x42);
730                 mallopt(M_CHECK_ACTION, 3);
731 #endif
732
733 #if defined(HAVE_EXECINFO) && defined(__GNUC__) && !defined(NDEBUG)
734                /*
735                 *  We need to pre-load lgcc_s, else we can get into a deadlock
736                 *  in fr_fault, as backtrace() attempts to dlopen it.
737                 *
738                 *  Apparently there's a performance impact of loading lgcc_s,
739                 *  so only do it if this is a debug build.
740                 *
741                 *  See: https://sourceware.org/bugzilla/show_bug.cgi?id=16159
742                 */
743                 {
744                         void *stack[10];
745
746                         backtrace(stack, 10);
747                 }
748 #endif
749         }
750         setup = true;
751
752         return 0;
753 }
754
755 /** Set a callback to be called before fr_fault()
756  *
757  * @param func to execute. If callback returns < 0
758  *      fr_fault will exit before running panic_action code.
759  */
760 void fr_fault_set_cb(fr_fault_cb_t func)
761 {
762         panic_cb = func;
763 };
764
765 /** Default logger, logs output to stderr
766  *
767  */
768 static void CC_HINT(format (printf, 1, 2)) _fr_fault_log(char const *msg, ...)
769 {
770         va_list ap;
771
772         va_start(ap, msg);
773         vfprintf(stderr, msg, ap);
774         va_end(ap);
775 }
776
777
778 /** Set a file descriptor to log panic_action output to.
779  *
780  * @param func to call to output log messages.
781  */
782 void fr_fault_set_log_fn(fr_fault_log_t func)
783 {
784         fr_fault_log = func ? func : _fr_fault_log;
785 }
786
787 /** Set a file descriptor to log memory reports to.
788  *
789  * @param fd to write output to.
790  */
791 void fr_fault_set_log_fd(int fd)
792 {
793         fr_fault_log_fd = fd;
794 }
795
796
797 #ifdef WITH_VERIFY_PTR
798
799 /*
800  *      Verify a VALUE_PAIR
801  */
802 inline void fr_verify_vp(char const *file, int line, VALUE_PAIR const *vp)
803 {
804         (void) talloc_get_type_abort(vp, VALUE_PAIR);
805
806         if (vp->data.ptr) switch (vp->da->type) {
807         case PW_TYPE_OCTETS:
808         case PW_TYPE_TLV:
809         {
810                 size_t len;
811                 TALLOC_CTX *parent;
812
813                 if (!talloc_get_type(vp->data.ptr, uint8_t)) {
814                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" data buffer type should be "
815                                 "uint8_t but is %s\n", file, line, vp->da->name, talloc_get_name(vp->data.ptr));
816                         (void) talloc_get_type_abort(vp->data.ptr, uint8_t);
817                 }
818
819                 len = talloc_array_length(vp->vp_octets);
820                 if (vp->length > len) {
821                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" length %zu is greater than "
822                                 "uint8_t data buffer length %zu\n", file, line, vp->da->name, vp->length, len);
823                         fr_assert(0);
824                         fr_exit_now(1);
825                 }
826
827                 parent = talloc_parent(vp->data.ptr);
828                 if (parent != vp) {
829                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" char buffer is not "
830                                 "parented by VALUE_PAIR %p, instead parented by %p (%s)\n",
831                                 file, line, vp->da->name,
832                                 vp, parent, parent ? talloc_get_name(parent) : "NULL");
833                         fr_assert(0);
834                         fr_exit_now(1);
835                 }
836         }
837                 break;
838
839         case PW_TYPE_STRING:
840         {
841                 size_t len;
842                 TALLOC_CTX *parent;
843
844                 if (!talloc_get_type(vp->data.ptr, char)) {
845                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" data buffer type should be "
846                                 "char but is %s\n", file, line, vp->da->name, talloc_get_name(vp->data.ptr));
847                         (void) talloc_get_type_abort(vp->data.ptr, char);
848                 }
849
850                 len = (talloc_array_length(vp->vp_strvalue) - 1);
851                 if (vp->length > len) {
852                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" length %zu is greater than "
853                                 "char buffer length %zu\n", file, line, vp->da->name, vp->length, len);
854                         fr_assert(0);
855                         fr_exit_now(1);
856                 }
857
858                 if (vp->vp_strvalue[vp->length] != '\0') {
859                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" char buffer not \\0 "
860                                 "terminated\n", file, line, vp->da->name);
861                         fr_assert(0);
862                         fr_exit_now(1);
863                 }
864
865                 parent = talloc_parent(vp->data.ptr);
866                 if (parent != vp) {
867                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: VALUE_PAIR \"%s\" uint8_t buffer is not "
868                                 "parented by VALUE_PAIR %p, instead parented by %p (%s)\n",
869                                 file, line, vp->da->name,
870                                 vp, parent, parent ? talloc_get_name(parent) : "NULL");
871                         fr_assert(0);
872                         fr_exit_now(1);
873                 }
874         }
875                 break;
876
877         default:
878                 break;
879         }
880 }
881
882 /*
883  *      Verify a pair list
884  */
885 void fr_verify_list(char const *file, int line, TALLOC_CTX *expected, VALUE_PAIR *vps)
886 {
887         vp_cursor_t cursor;
888         VALUE_PAIR *vp;
889         TALLOC_CTX *parent;
890
891         for (vp = fr_cursor_init(&cursor, &vps);
892              vp;
893              vp = fr_cursor_next(&cursor)) {
894                 VERIFY_VP(vp);
895
896                 parent = talloc_parent(vp);
897                 if (expected && (parent != expected)) {
898                         fprintf(stderr, "CONSISTENCY CHECK FAILED %s[%u]: Expected VALUE_PAIR (%s) to be parented "
899                                 "by %p (%s), instead parented by %p (%s)\n",
900                                 file, line, vp->da->name,
901                                 expected, talloc_get_name(expected),
902                                 parent, parent ? talloc_get_name(parent) : "NULL");
903
904                         fr_log_talloc_report(expected);
905                         if (parent) fr_log_talloc_report(parent);
906
907                         assert(0);
908                 }
909
910         }
911 }
912 #endif