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