The FreeRADIUS server  $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
debug.c
Go to the documentation of this file.
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 /** Functions to help with debugging
18  *
19  * @file src/lib/util/debug.c
20  *
21  * @copyright 2013 The FreeRADIUS server project
22  * @copyright 2013 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
23  */
24 #include <freeradius-devel/util/debug.h>
25 #include <freeradius-devel/util/hash.h>
26 #include <freeradius-devel/util/strerror.h>
27 #include <freeradius-devel/util/syserror.h>
28 
29 #include <pthread.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <sys/stat.h>
33 #include <sys/wait.h>
34 
35 #if defined(HAVE_MALLOPT) && defined(HAVE_MALLOC_H)
36 # include <malloc.h>
37 #endif
38 
39 /*
40  * runtime backtrace functions are not POSIX but are included in
41  * glibc, OSX >= 10.5 and various BSDs
42  */
43 #ifdef HAVE_EXECINFO
44 # include <execinfo.h>
45 #endif
46 
47 #ifdef HAVE_SYS_PRCTL_H
48 # include <sys/prctl.h>
49 #endif
50 
51 #ifdef HAVE_SYS_PROCCTL_H
52 # include <sys/procctl.h>
53 #endif
54 
55 #ifdef HAVE_SYS_PTRACE_H
56 # include <sys/ptrace.h>
57 # if !defined(PT_ATTACH) && defined(PTRACE_ATTACH)
58 # define PT_ATTACH PTRACE_ATTACH
59 # endif
60 # if !defined(PT_DETACH) && defined(PTRACE_DETACH)
61 # define PT_DETACH PTRACE_DETACH
62 # endif
63 #endif
64 
65 #ifdef HAVE_SYS_RESOURCE_H
66 # include <sys/resource.h>
67 #endif
68 
69 #ifdef __APPLE__
70 #include <sys/sysctl.h>
71 #endif
72 
73 #ifdef HAVE_EXECINFO
74 # ifndef MAX_BT_FRAMES
75 # define MAX_BT_FRAMES 128
76 # endif
77 # ifndef MAX_BT_CBUFF
78 # define MAX_BT_CBUFF 1048576 //!< Should be a power of 2
79 # endif
80 
81 static pthread_mutex_t fr_debug_init = PTHREAD_MUTEX_INITIALIZER;
82 
83 typedef struct {
84  void *obj; //!< Memory address of the block of allocated memory.
85  void *frames[MAX_BT_FRAMES]; //!< Backtrace frame data
86  int count; //!< Number of frames stored
87 } fr_bt_info_t;
88 
89 struct fr_bt_marker {
90  void *obj; //!< Pointer to the parent object, this is our needle
91  //!< when we iterate over the contents of the circular buffer.
92  fr_fring_t *fring; //!< Where we temporarily store the backtraces
93 };
94 #endif
95 
96 static char panic_action[512]; //!< The command to execute when panicking.
97 static fr_fault_cb_t panic_cb = NULL; //!< Callback to execute whilst panicking, before the
98  //!< panic_action.
99 
100 static bool dump_core; //!< Whether we should drop a core on fatal signals.
101 
102 static int fr_fault_log_fd = STDERR_FILENO; //!< Where to write debug output.
103 
104 fr_debug_state_t fr_debug_state = DEBUGGER_STATE_UNKNOWN; //!< Whether we're attached to by a debugger.
105 
106 #ifdef HAVE_SYS_RESOURCE_H
107 static struct rlimit init_core_limit;
108 #endif
109 
110 static TALLOC_CTX *talloc_autofree_ctx;
111 
112 /*
113  * On BSD systems, ptrace(PT_DETACH) uses a third argument for
114  * resume address, with the magic value (void *)1 to resume where
115  * process stopped. Specifying NULL there leads to a crash because
116  * process resumes at address 0.
117  */
118 #if defined(HAVE_SYS_PTRACE_H)
119 # ifdef __linux__
120 # define _PTRACE(_x, _y) ptrace(_x, _y, NULL, NULL)
121 # define _PTRACE_DETACH(_x) ptrace(PT_DETACH, _x, NULL, NULL)
122 # elif !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && !defined(HAVE_SYS_PROCCTL_H)
123 # define _PTRACE(_x, _y) ptrace(_x, _y, NULL, 0)
124 # define _PTRACE_DETACH(_x) ptrace(PT_DETACH, _x, (void *)1, 0)
125 #endif
126 
127 # ifdef HAVE_CAPABILITY_H
128 # include <sys/capability.h>
129 # endif
130 #endif
131 
132 #ifdef HAVE_SANITIZER_LSAN_INTERFACE_H
133 # include <sanitizer/lsan_interface.h>
134 #endif
135 
136 #ifdef HAVE_SANITIZER_LSAN_INTERFACE_H
137 static int lsan_test_pipe[2] = {-1, -1};
138 static int lsan_test_pid = -1;
139 static int lsan_state = INT_MAX;
140 static bool lsan_disable = false; //!< Explicitly disable LSAN
141 
142 /*
143  * Some versions of lsan_interface.h are broken and don't declare
144  * the prototypes of the functions properly, omitting the zero argument
145  * specifier (void), so we need to disable the warning.
146  *
147  * Observed with clang 5.
148  */
149 DIAG_OFF(missing-prototypes)
150 /** Callback for LSAN - do not rename
151  *
152  */
153 char const CC_HINT(used) *__lsan_default_suppressions(void)
154 {
155  return
156  "leak:CRYPTO_THREAD_lock_new\n" /* OpenSSL init leak - reported by heaptrack */
157 #if defined(__APPLE__)
158  "leak:*gmtsub*\n"
159  "leak:ImageLoaderMachO::doImageInit\n"
160  "leak:_st_tzset_basic\n"
161  "leak:attachCategories\n"
162  "leak:fork\n"
163  "leak:getaddrinfo\n"
164  "leak:getpwuid_r\n"
165  "leak:libSystem_atfork_child\n"
166  "leak:libsystem_notify\n"
167  "leak:load_images\n"
168  "leak:newlocale\n"
169  /* Perl >= 5.32.0 - Upstream bug, tracked by https://github.com/Perl/perl5/issues/18108 */
170  "leak:perl_construct\n"
171  "leak:realizeClassWithoutSwift\n"
172  "leak:tzset\n"
173  "leak:tzsetwall_basic\n"
174 #elif defined(__linux__)
175  "leak:*getpwnam_r*\n" /* libc startup leak - reported by heaptrack */
176  "leak:_dl_init\n" /* dl startup leak - reported by heaptrack */
177  "leak:initgroups\n" /* libc startup leak - reported by heaptrack */
178  "leak:kqueue\n"
179 #endif
180  ;
181 }
182 
183 /** Callback for LSAN - do not rename
184  *
185  * Turn off suppressions by default as it interferes with interpreting
186  * output from some of the test utilities.
187  */
188 char const CC_HINT(used) *__lsan_default_options(void)
189 {
190  return "print_suppressions=0";
191 }
192 
193 /** Callback for LSAN - do not rename
194  *
195  */
196 int CC_HINT(used) __lsan_is_turned_off(void)
197 {
198  uint8_t ret = 1;
199 
200  /* Disable LSAN explicitly - Used for tests involving fork() */
201  if (lsan_disable) return 1;
202 
203  /* Parent */
204  if (lsan_test_pid != 0) return 0;
205 
206  /* Child */
207  if (write(lsan_test_pipe[1], &ret, sizeof(ret)) < 0) {
208  fprintf(stderr, "Writing LSAN status failed: %s", fr_syserror(errno));
209  }
210  close(lsan_test_pipe[1]);
211  return 0;
212 }
213 DIAG_ON(missing-prototypes)
214 
215 /** Determine if we're running under LSAN (Leak Sanitizer)
216  *
217  * @return
218  * - 0 if we're not.
219  * - 1 if we are.
220  * - -1 if we can't tell because of an error.
221  * - -2 if we can't tell because we were compiled with support for the LSAN interface.
222  */
223 int fr_get_lsan_state(void)
224 {
225  uint8_t ret = 0;
226 
227  if (lsan_state != INT_MAX) return lsan_state;/* Use cached result */
228 
229  if (pipe(lsan_test_pipe) < 0) {
230  fr_strerror_printf("Failed opening internal pipe: %s", fr_syserror(errno));
231  return -1;
232  }
233 
234  lsan_test_pid = fork();
235  if (lsan_test_pid == -1) {
236  fr_strerror_printf("Error forking: %s", fr_syserror(errno));
237  return -1;
238  }
239 
240  /* Child */
241  if (lsan_test_pid == 0) {
242  close(lsan_test_pipe[0]); /* Close parent's side */
243  exit(EXIT_SUCCESS); /* Results in LSAN calling __lsan_is_turned_off via onexit handler */
244  }
245 
246  /* Parent */
247  close(lsan_test_pipe[1]); /* Close child's side */
248 
249  while ((read(lsan_test_pipe[0], &ret, sizeof(ret)) < 0) && (errno == EINTR));
250 
251  close(lsan_test_pipe[0]); /* Close our side (so we don't leak FDs) */
252 
253  /* Collect child */
254  waitpid(lsan_test_pid, NULL, 0);
255 
256  lsan_state = ret; /* Cache test results */
257 
258  return ret;
259 }
260 #else
262 {
263  fr_strerror_const("Not built with support for LSAN interface");
264  return -2;
265 }
266 #endif
267 
268 #if defined(HAVE_SYS_PROCCTL_H)
269 int fr_get_debug_state(void)
270 {
271  int status;
272 
273  if (procctl(P_PID, getpid(), PROC_TRACE_STATUS, &status) == -1) {
274  fr_strerror_printf("Cannot get dumpable flag: procctl(PROC_TRACE_STATUS) failed: %s", fr_syserror(errno));
275  return DEBUGGER_STATE_UNKNOWN;
276  }
277 
278  /*
279  * As FreeBSD docs say about "PROC_TRACE_STATUS":
280  *
281  * Returns the current tracing status for the specified process in the
282  * integer variable pointed to by data. If tracing is disabled, data
283  * is set to -1. If tracing is enabled, but no debugger is attached by
284  * the ptrace(2) syscall, data is set to 0. If a debugger is attached,
285  * data is set to the pid of the debugger process.
286  */
287  if (status <= 0) return DEBUGGER_STATE_NOT_ATTACHED;
288 
290 }
291 #elif defined(__APPLE__)
292 /** The ptrace_attach() method no longer works as of macOS 11.4 (we always get eperm)
293  *
294  * Apple published this helpful article here which provides the
295  * magical invocation: https://developer.apple.com/library/archive/qa/qa1361/_index.html
296  *
297  * @return
298  * - 0 if we're not.
299  * - 1 if we are.
300  * - -1
301  */
302 int fr_get_debug_state(void)
303 {
304  int ret;
305  int mib[4];
306  struct kinfo_proc info;
307  size_t size;
308 
309  /*
310  * Initialize the flags so that, if sysctl fails for some
311  * reason, we get a predictable result.
312  */
313  info.kp_proc.p_flag = 0;
314 
315  /*
316  * Initialize mib, which tells sysctl the info we want, in this case
317  * we're looking for information about a specific process ID.
318  */
319  mib[0] = CTL_KERN;
320  mib[1] = KERN_PROC;
321  mib[2] = KERN_PROC_PID;
322  mib[3] = getpid();
323 
324  /* Call sysctl */
325  size = sizeof(info);
326  ret = sysctl(mib, NUM_ELEMENTS(mib), &info, &size, NULL, 0);
327  if (ret != 0) return -1;
328 
329  /* We're being debugged if the P_TRACED flag is set */
330  return ((info.kp_proc.p_flag & P_TRACED) != 0);
331 }
332 #elif defined(HAVE_SYS_PTRACE_H) && !defined(__EMSCRIPTEN__)
333 /** Determine if we're running under a debugger by attempting to attach using pattach
334  *
335  * @return
336  * - 0 if we're not.
337  * - 1 if we are.
338  * - -1 if we can't tell because of an error.
339  * - -2 if we can't tell because we don't have the CAP_SYS_PTRACE capability.
340  */
341 int fr_get_debug_state(void)
342 {
343  int pid;
344 
345  int from_child[2] = {-1, -1};
346 
347 #ifdef HAVE_CAPABILITY_H
348  cap_flag_value_t state;
349  cap_t caps;
350 
351  /*
352  * If we're running under linux, we first need to check if we have
353  * permission to to ptrace. We do that using the capabilities
354  * functions.
355  */
356  caps = cap_get_proc();
357  if (!caps) {
358  fr_strerror_printf("Failed getting process capabilities: %s", fr_syserror(errno));
359  return DEBUGGER_STATE_UNKNOWN;
360  }
361 
362  if (cap_get_flag(caps, CAP_SYS_PTRACE, CAP_PERMITTED, &state) < 0) {
363  fr_strerror_printf("Failed getting CAP_SYS_PTRACE permitted state: %s",
364  fr_syserror(errno));
365  cap_free(caps);
366  return DEBUGGER_STATE_UNKNOWN;
367  }
368 
369  if ((state == CAP_SET) && (cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &state) < 0)) {
370  fr_strerror_printf("Failed getting CAP_SYS_PTRACE effective state: %s",
371  fr_syserror(errno));
372  cap_free(caps);
373  return DEBUGGER_STATE_UNKNOWN;
374  }
375 
376  /*
377  * We don't have permission to ptrace, so this test will always fail.
378  */
379  if (state == CAP_CLEAR) {
380  fr_strerror_printf("ptrace capability not set. If debugger detection is required run as root or: "
381  "setcap cap_sys_ptrace+ep <path_to_binary>");
382  cap_free(caps);
384  }
385  cap_free(caps);
386 #endif
387 
388  if (pipe(from_child) < 0) {
389  fr_strerror_printf("Error opening internal pipe: %s", fr_syserror(errno));
390  return DEBUGGER_STATE_UNKNOWN;
391  }
392 
393  pid = fork();
394  if (pid == -1) {
395  fr_strerror_printf("Error forking: %s", fr_syserror(errno));
396  return DEBUGGER_STATE_UNKNOWN;
397  }
398 
399  /* Child */
400  if (pid == 0) {
401  int8_t ret = DEBUGGER_STATE_NOT_ATTACHED;
402  int ppid = getppid();
403  int flags;
404 
405  /*
406  * Disable the leak checker for this forked process
407  * so we don't get spurious leaks reported.
408  */
409 #ifdef HAVE_SANITIZER_LSAN_INTERFACE_H
410  lsan_disable = true;
411 #endif
412 
413 DIAG_OFF(deprecated-declarations)
414  flags = PT_ATTACH;
415 DIAG_ON(deprecated-declarations)
416 
417  /* Close parent's side */
418  close(from_child[0]);
419 
420  /*
421  * FreeBSD is extremely picky about the order of operations here
422  * we need to attach, wait *then* write whilst the parent is still
423  * suspended, then detach, continuing the process.
424  *
425  * If we don't do it in that order the read in the parent triggers
426  * a SIGKILL.
427  */
428  errno = 0;
429  _PTRACE(flags, ppid);
430  if (errno == 0) {
431  /* Wait for the parent to stop */
432  waitpid(ppid, NULL, 0);
433 
434  /* Tell the parent what happened */
435  send_status:
436  if (write(from_child[1], &ret, sizeof(ret)) < 0) {
437  fprintf(stderr, "Writing ptrace status to parent failed: %s", fr_syserror(errno));
438  }
439 
440  /* Detach */
441  _PTRACE_DETACH(ppid);
442  _exit(0); /* don't run the atexit() handlers. */
443  /*
444  * We could attach because of a permissions issue, we don't know
445  * whether we're being traced or not.
446  */
447  } else if (errno == EPERM) {
449  goto send_status;
450  }
451 
453  /* Tell the parent what happened */
454  if (write(from_child[1], &ret, sizeof(ret)) < 0) {
455  fprintf(stderr, "Writing ptrace status to parent failed: %s", fr_syserror(errno));
456  }
457 
458  /*
459  * We call _exit() instead of exit(). This means that we skip the atexit() handlers,
460  * which don't need to run in a temporary child process. Skipping them means that we
461  * avoid dirtying those pages to "clean things up", which is then immediately followed by
462  * exiting.
463  *
464  * Skipping the atexit() handlers also means that we're not worried about memory leaks
465  * because things "aren't cleaned up correctly". We're not exiting cleanly here (and
466  * don't care to exit cleanly). So just exiting with no cleanups is fine.
467  */
468  _exit(0);
469  /* Parent */
470  } else {
471  int8_t ret = DEBUGGER_STATE_UNKNOWN;
472 
473  /*
474  * The child writes errno (reason) if pattach failed else 0.
475  *
476  * This read may be interrupted by pattach,
477  * which is why we need the loop.
478  */
479  while ((read(from_child[0], &ret, sizeof(ret)) < 0) && (errno == EINTR));
480 
481  /* Close the pipes here (if we did it above, it might race with pattach) */
482  close(from_child[1]);
483  close(from_child[0]);
484 
485  /* Collect the status of the child */
486  waitpid(pid, NULL, 0);
487 
488  return ret;
489  }
490 }
491 #else
493 {
494  fr_strerror_const("PTRACE not available");
495 
497 }
498 #endif
499 
500 /** Should be run before using setuid or setgid to get useful results
501  *
502  * @note sets the fr_debug_state global.
503  */
505 {
507 
508 #ifndef NDEBUG
509  /*
510  * There are many reasons why this might happen with
511  * a vanilla install, so we don't want to spam users
512  * with messages they won't understand and may not
513  * want to resolve.
514  */
515  if (fr_debug_state < 0) fprintf(stderr, "Getting debug state failed: %s\n", fr_strerror());
516 #endif
517 }
518 
519 /** Return current value of debug_state
520  *
521  * @param state to translate into a humanly readable value.
522  * @return humanly readable version of debug state.
523  */
525 {
526  switch (state) {
528  return "Debug state unknown (ptrace functionality not available)";
529 
531  return "Debug state unknown (cap_sys_ptrace capability not set)";
532 
534  return "Debug state unknown";
535 
537  return "Found debugger attached";
538 
540  return "Debugger not attached";
541  }
542 
543  return "<INVALID>";
544 }
545 
546 /** Break in debugger (if were running under a debugger)
547  *
548  * If the server is running under a debugger this will raise a
549  * SIGTRAP which will pause the running process.
550  *
551  * If the server is not running under debugger then this will do nothing.
552  */
553 void fr_debug_break(bool always)
554 {
555  if (always) raise(SIGTRAP);
556 
559  fprintf(stderr, "Debugger detected, raising SIGTRAP\n");
560  fflush(stderr);
561 
562  raise(SIGTRAP);
563  }
564 }
565 
566 #ifdef HAVE_EXECINFO
567 /** Print backtrace entry for a given object
568  *
569  * @param fring to search in.
570  * @param obj pointer to original object
571  */
572 void backtrace_print(fr_fring_t *fring, void *obj)
573 {
574  fr_bt_info_t *p;
575  bool found = false;
576 
577  while ((p = fr_fring_next(fring))) {
578  if ((p->obj == obj) || !obj) {
579  found = true;
580 
581  fprintf(stderr, "Stacktrace for: %p\n", p->obj);
582  backtrace_symbols_fd(p->frames, p->count, STDERR_FILENO);
583  }
584  }
585 
586  if (!found) {
587  fprintf(stderr, "No backtrace available for %p", obj);
588  }
589 }
590 
591 /** Generate a backtrace for an object
592  *
593  * If this is the first entry being inserted
594  */
595 int fr_backtrace_do(fr_bt_marker_t *marker)
596 {
597  fr_bt_info_t *bt;
598 
599  if (!fr_cond_assert(marker->obj) || !fr_cond_assert(marker->fring)) return -1;
600 
601  bt = talloc_zero(NULL, fr_bt_info_t);
602  if (!bt) return -1;
603 
604  bt->obj = marker->obj;
605  bt->count = backtrace(bt->frames, MAX_BT_FRAMES);
606 
607  fr_fring_overwrite(marker->fring, bt);
608 
609  return 0;
610 }
611 
612 /** Inserts a backtrace marker into the provided context
613  *
614  * Allows for maximum laziness and will initialise a circular buffer if one has not already been created.
615  *
616  * Code augmentation should look something like:
617 @verbatim
618  // Create a static fringer pointer, the first call to backtrace_attach will initialise it
619  static fr_fring_t *my_obj_bt;
620 
621  my_obj_t *alloc_my_obj(TALLOC_CTX *ctx) {
622  my_obj_t *this;
623 
624  this = talloc(ctx, my_obj_t);
625 
626  // Attach backtrace marker to object
627  backtrace_attach(&my_obj_bt, this);
628 
629  return this;
630  }
631 @endverbatim
632  *
633  * Then, later when a double free occurs:
634 @verbatim
635  (gdb) call backtrace_print(&my_obj_bt, <pointer to double freed memory>)
636 @endverbatim
637  *
638  * which should print a limited backtrace to stderr. Note, this backtrace will not include any argument
639  * values, but should at least show the code path taken.
640  *
641  * @param fring this should be a pointer to a static *fr_fring_buffer.
642  * @param obj we want to generate a backtrace for.
643  */
644 fr_bt_marker_t *fr_backtrace_attach(fr_fring_t **fring, TALLOC_CTX *obj)
645 {
646  fr_bt_marker_t *marker;
647 
648  if (*fring == NULL) {
649  pthread_mutex_lock(&fr_debug_init);
650  /* Check again now we hold the mutex - eww*/
651  if (*fring == NULL) *fring = fr_fring_alloc(NULL, MAX_BT_CBUFF, true);
652  pthread_mutex_unlock(&fr_debug_init);
653  }
654 
655  marker = talloc(obj, fr_bt_marker_t);
656  if (!marker) {
657  return NULL;
658  }
659 
660  marker->obj = (void *) obj;
661  marker->fring = *fring;
662 
663  fprintf(stderr, "Backtrace attached to %s %p\n", talloc_get_name(obj), obj);
664  /*
665  * Generate the backtrace for memory allocation
666  */
667  fr_backtrace_do(marker);
668  talloc_set_destructor(marker, fr_backtrace_do);
669 
670  return marker;
671 }
672 #else
673 void backtrace_print(UNUSED fr_fring_t *fring, UNUSED void *obj)
674 {
675  fprintf(stderr, "Server built without fr_backtrace_* support, requires execinfo.h and possibly -lexecinfo\n");
676 }
678 {
679  fprintf(stderr, "Server built without fr_backtrace_* support, requires execinfo.h and possibly -lexecinfo\n");
680  abort();
681 }
682 #endif /* ifdef HAVE_EXECINFO */
683 
684 static int _panic_on_free(UNUSED char *foo)
685 {
686  fr_fault(SIGABRT);
687  return -1; /* this should make the free fail */
688 }
689 
690 /** Insert memory into the context of another talloc memory chunk which
691  * causes a panic when freed.
692  *
693  * @param ctx TALLOC_CTX to monitor for frees.
694  */
695 void fr_panic_on_free(TALLOC_CTX *ctx)
696 {
697  char *ptr;
698 
699  ptr = talloc(ctx, char);
700  talloc_set_destructor(ptr, _panic_on_free);
701 }
702 
703 /** Set the dumpable flag, also controls whether processes can PATTACH
704  *
705  * @param dumpable whether we should allow core dumping
706  */
707 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE) && !defined(__EMSCRIPTEN__)
708 static int fr_set_pr_dumpable_flag(bool dumpable)
709 {
710  if (prctl(PR_SET_DUMPABLE, dumpable ? 1 : 0) < 0) {
711  fr_strerror_printf("Cannot re-enable core dumps: prctl(PR_SET_DUMPABLE) failed: %s",
712  fr_syserror(errno));
713  return -1;
714  }
715 
716  return 0;
717 }
718 #elif defined(HAVE_SYS_PROCCTL_H)
719 static int fr_set_pr_dumpable_flag(bool dumpable)
720 {
721  int mode = dumpable ? PROC_TRACE_CTL_ENABLE : PROC_TRACE_CTL_DISABLE;
722 
723  if (procctl(P_PID, getpid(), PROC_TRACE_CTL, &mode) == -1) {
724  fr_strerror_printf("Cannot re-enable core dumps: procctl(PROC_TRACE_CTL) failed: %s",
725  fr_syserror(errno));
726  return -1;
727  }
728 
729  return 0;
730 }
731 #else
732 static int fr_set_pr_dumpable_flag(UNUSED bool dumpable)
733 {
734  fr_strerror_const("Changing value of PR_DUMPABLE not supported on this system");
735  return -2;
736 }
737 #endif
738 
739 /** Get the processes dumpable flag
740  *
741  */
742 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_GET_DUMPABLE) && !defined(__EMSCRIPTEN__)
743 static int fr_get_pr_dumpable_flag(void)
744 {
745  int ret;
746 
747  ret = prctl(PR_GET_DUMPABLE);
748  if (ret < 0) {
749  fr_strerror_printf("Cannot get dumpable flag: %s", fr_syserror(errno));
750  return -1;
751  }
752 
753  /*
754  * Linux is crazy and prctl sometimes returns 2 for disabled
755  */
756  if (ret != 1) return 0;
757  return 1;
758 }
759 #elif defined(HAVE_SYS_PROCCTL_H)
760 static int fr_get_pr_dumpable_flag(void)
761 {
762  int status;
763 
764  if (procctl(P_PID, getpid(), PROC_TRACE_CTL, &status) == -1) {
765  fr_strerror_printf("Cannot get dumpable flag: procctl(PROC_TRACE_CTL) failed: %s", fr_syserror(errno));
766  return -1;
767  }
768 
769  /*
770  * There are a few different kinds of disabled, but only
771  * one ENABLE.
772  */
773  if (status != PROC_TRACE_CTL_ENABLE) return 0;
774 
775  return 1;
776 }
777 #else
778 static int fr_get_pr_dumpable_flag(void)
779 {
780  fr_strerror_const("Getting value of PR_DUMPABLE not supported on this system");
781  return -2;
782 }
783 #endif
784 
785 
786 /** Get the current maximum for core files
787  *
788  * Do this before anything else so as to ensure it's properly initialized.
789  */
791 {
792 #ifdef HAVE_SYS_RESOURCE_H
793  if (getrlimit(RLIMIT_CORE, &init_core_limit) < 0) {
794  fr_strerror_printf("Failed to get current core limit: %s", fr_syserror(errno));
795  return -1;
796  }
797 #endif
798  return 0;
799 }
800 
801 /** Enable or disable core dumps
802  *
803  * @param allow_core_dumps whether to enable or disable core dumps.
804  */
805 int fr_set_dumpable(bool allow_core_dumps)
806 {
807  dump_core = allow_core_dumps;
808 
809 #ifdef HAVE_SYS_RESOURCE_H
810  {
811  struct rlimit current;
812 
813  /*
814  * Reset the core limits (or disable them)
815  */
816  if (getrlimit(RLIMIT_CORE, &current) < 0) {
817  fr_strerror_printf("Failed to get current core limit: %s", fr_syserror(errno));
818  return -1;
819  }
820 
821  if (allow_core_dumps) {
822  if ((current.rlim_cur != init_core_limit.rlim_cur) ||
823  (current.rlim_max != init_core_limit.rlim_max)) {
824  if (setrlimit(RLIMIT_CORE, &init_core_limit) < 0) {
825  fr_strerror_printf("Cannot update core dump limit: %s", fr_syserror(errno));
826 
827  return -1;
828  }
829  }
830  /*
831  * We've been told to disable core dumping,
832  * rlim_cur is not set to zero.
833  *
834  * Set rlim_cur to zero, but leave rlim_max
835  * set to whatever the current value is.
836  *
837  * This is because, later, we may need to
838  * re-enable core dumps to allow the debugger
839  * to attach *sigh*.
840  */
841  } else if (current.rlim_cur != 0) {
842  struct rlimit no_core;
843 
844  no_core.rlim_cur = 0;
845  no_core.rlim_max = current.rlim_max;
846 
847  if (setrlimit(RLIMIT_CORE, &no_core) < 0) {
848  fr_strerror_printf("Failed disabling core dumps: %s", fr_syserror(errno));
849 
850  return -1;
851  }
852  }
853  }
854 #endif
855  /*
856  * Macro needed so we don't emit spurious errors
857  */
858 #if defined(HAVE_SYS_PROCCTL_H) || (defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE))
859  if (fr_set_pr_dumpable_flag(allow_core_dumps) < 0) return -1;
860 #endif
861 
862  return 0;
863 }
864 
865 /** Reset dumpable state to previously configured value
866  *
867  * Needed after suid up/down
868  *
869  * @return
870  * - 0 on success.
871  * - -1 on failure.
872  */
874 {
875  return fr_set_dumpable(dump_core);
876 }
877 
878 /** Check to see if panic_action file is world writable
879  *
880  * @return
881  * - 0 if file is OK.
882  * - -1 if the file is world writable.
883  */
885 {
886  char const *p, *q;
887  size_t len;
888  char filename[256];
889  struct stat statbuf;
890 
891  /*
892  * Try and guess which part of the command is the binary, and check to see if
893  * it's world writable, to try and save the admin from their own stupidity.
894  *
895  * @fixme we should do this properly and take into account single and double
896  * quotes.
897  */
898  if ((q = strchr(panic_action, ' '))) {
899  /*
900  * need to use a static buffer, because allocing memory in a signal handler
901  * is a bad idea and can result in deadlock.
902  */
903  len = snprintf(filename, sizeof(filename), "%.*s", (int)(q - panic_action), panic_action);
904  if (is_truncated(len, sizeof(filename))) {
905  fr_strerror_const("Failed writing panic_action to temporary buffer (truncated)");
906  return -1;
907  }
908  p = filename;
909  } else {
910  p = panic_action;
911  }
912 
913  if (stat(p, &statbuf) == 0) {
914 #ifdef S_IWOTH
915  if ((statbuf.st_mode & S_IWOTH) != 0) {
916  fr_strerror_printf("panic_action file \"%s\" is globally writable", p);
917  return -1;
918  }
919 #endif
920  }
921 
922  return 0;
923 }
924 
925 /** Prints a simple backtrace (if execinfo is available) and calls panic_action if set.
926  *
927  * @param sig caught
928  */
929 NEVER_RETURNS void fr_fault(int sig)
930 {
931  char cmd[sizeof(panic_action) + 20];
932  char *out = cmd;
933  size_t left = sizeof(cmd), ret;
934 
935  char const *p = panic_action;
936  char const *q;
937 
938  int code;
939 
940  /*
941  * If a debugger is attached, we don't want to run the panic action,
942  * as it may interfere with the operation of the debugger.
943  * If something calls us directly we just raise the signal and let
944  * the debugger handle it how it wants.
945  */
947  FR_FAULT_LOG("RAISING SIGNAL: %s", strsignal(sig));
948  raise(sig);
949  }
950 
951  /*
952  * Makes the backtraces slightly cleaner
953  */
954  memset(cmd, 0, sizeof(cmd));
955 
956  FR_FAULT_LOG("CAUGHT SIGNAL: %s", strsignal(sig));
957 
958  /*
959  * Run the callback if one was registered
960  */
961  if (panic_cb && (panic_cb(sig) < 0)) goto finish;
962 
963  /*
964  * Produce a simple backtrace - They're very basic but at least give us an
965  * idea of the area of the code we hit the issue in.
966  *
967  * See below in fr_fault_setup() and
968  * https://sourceware.org/bugzilla/show_bug.cgi?id=16159
969  * for why we only print backtraces in debug builds if we're using GLIBC.
970  */
971 #if defined(HAVE_EXECINFO) && (!defined(NDEBUG) || !defined(__GNUC__))
972  if (fr_fault_log_fd >= 0) {
973  size_t frame_count;
974  void *stack[MAX_BT_FRAMES];
975 
976  frame_count = backtrace(stack, MAX_BT_FRAMES);
977 
978  FR_FAULT_LOG("Backtrace of last %zu frames:", frame_count);
979 
980  backtrace_symbols_fd(stack, frame_count, fr_fault_log_fd);
981  }
982 #endif
983 
984  /* No panic action set... */
985  if (panic_action[0] == '\0') {
986  FR_FAULT_LOG("No panic action set");
987  goto finish;
988  }
989 
990  /*
991  * Check for administrator sanity.
992  */
993  if (fr_fault_check_permissions() < 0) {
994  FR_FAULT_LOG("Refusing to execute panic action: %s", fr_strerror());
995  goto finish;
996  }
997 
998  /* Substitute %p for the current PID (useful for attaching a debugger) */
999  while ((q = strstr(p, "%p"))) {
1000  out += ret = snprintf(out, left, "%.*s%d", (int) (q - p), p, (int) getpid());
1001  if (left <= ret) {
1002  oob:
1003  FR_FAULT_LOG("Panic action too long");
1004  fr_exit_now(128 + sig);
1005  }
1006  left -= ret;
1007  p = q + 2;
1008  }
1009  if (strlen(p) >= left) goto oob;
1010  strlcpy(out, p, left);
1011 
1012  {
1013  bool disable = false;
1014 
1015  FR_FAULT_LOG("Calling: %s", cmd);
1016 
1017  /*
1018  * Here we temporarily enable the dumpable flag so if GBD or LLDB
1019  * is called in the panic_action, they can pattach to the running
1020  * process.
1021  */
1022  if (fr_get_pr_dumpable_flag() == 0) {
1023  if ((fr_set_pr_dumpable_flag(true) < 0) || !fr_get_pr_dumpable_flag()) {
1024  FR_FAULT_LOG("Failed setting dumpable flag, pattach may not work: %s", fr_strerror());
1025  } else {
1026  disable = true;
1027  }
1028  FR_FAULT_LOG("Temporarily setting PR_DUMPABLE to 1");
1029  }
1030 
1031  code = system(cmd);
1032 
1033  /*
1034  * We only want to error out here, if dumpable was originally disabled
1035  * and we managed to change the value to enabled, but failed
1036  * setting it back to disabled.
1037  */
1038  if (disable) {
1039  FR_FAULT_LOG("Resetting PR_DUMPABLE to 0");
1040  if (fr_set_pr_dumpable_flag(false) < 0) {
1041  FR_FAULT_LOG("Failed resetting dumpable flag to off: %s", fr_strerror());
1042  FR_FAULT_LOG("Exiting due to insecure process state");
1043  fr_exit_now(EXIT_FAILURE);
1044  }
1045  }
1046 
1047  FR_FAULT_LOG("Panic action exited with %i", code);
1048 
1049  fr_exit_now(128 + sig);
1050  }
1051 
1052 finish:
1053  /*
1054  * (Re-)Raise the signal, so that if we're running under
1055  * a debugger.
1056  *
1057  * This allows debuggers to function normally and catch
1058  * fatal signals.
1059  */
1060  fr_unset_signal(sig); /* Make sure we don't get into a loop */
1061  raise(sig);
1062  fr_exit_now(128 + sig); /* Function marked as noreturn */
1063 }
1064 
1065 /** Callback executed on fatal talloc error
1066  *
1067  * This is the simple version which mostly behaves the same way as the default
1068  * one, and will not call panic_action.
1069  *
1070  * @param reason string provided by talloc.
1071  */
1072 static void _fr_talloc_fault_simple(char const *reason) CC_HINT(noreturn);
1073 static void _fr_talloc_fault_simple(char const *reason)
1074 {
1075  FR_FAULT_LOG("talloc abort: %s\n", reason);
1076 
1077 #if defined(HAVE_EXECINFO) && (!defined(NDEBUG) || !defined(__GNUC__))
1078  if (fr_fault_log_fd >= 0) {
1079  size_t frame_count;
1080  void *stack[MAX_BT_FRAMES];
1081 
1082  frame_count = backtrace(stack, MAX_BT_FRAMES);
1083  FR_FAULT_LOG("Backtrace of last %zu frames:", frame_count);
1084  backtrace_symbols_fd(stack, frame_count, fr_fault_log_fd);
1085  }
1086 #endif
1087  abort();
1088 }
1089 
1090 /** Callback executed on fatal talloc error
1091  *
1092  * Translates a talloc abort into a fr_fault call.
1093  * Mostly to work around issues with some debuggers not being able to
1094  * attach after a SIGABRT has been raised.
1095  *
1096  * @param reason string provided by talloc.
1097  */
1098 static void _fr_talloc_fault(char const *reason) CC_HINT(noreturn);
1099 static void _fr_talloc_fault(char const *reason)
1100 {
1101  FR_FAULT_LOG("talloc abort: %s", reason);
1102 #ifdef SIGABRT
1103  fr_fault(SIGABRT);
1104 #endif
1105  fr_exit_now(128 + SIGABRT);
1106 }
1107 
1108 /** Wrapper to pass talloc log output to our fr_fault_log function
1109  *
1110  */
1111 static void _fr_talloc_log(char const *msg)
1112 {
1113  fr_fault_log("%s\n", msg);
1114 }
1115 
1116 /** Generate a talloc memory report for a context and print to stderr/stdout
1117  *
1118  * @param ctx to generate a report for, may be NULL in which case the root context is used.
1119  */
1120 int fr_log_talloc_report(TALLOC_CTX const *ctx)
1121 {
1122 #define TALLOC_REPORT_MAX_DEPTH 20
1123 
1124  FILE *log;
1125  int fd;
1126 
1127  fd = dup(fr_fault_log_fd);
1128  if (fd < 0) {
1129  fr_strerror_printf("Couldn't write memory report, failed to dup log fd: %s", fr_syserror(errno));
1130  return -1;
1131  }
1132  log = fdopen(fd, "w");
1133  if (!log) {
1134  close(fd);
1135  fr_strerror_printf("Couldn't write memory report, fdopen failed: %s", fr_syserror(errno));
1136  return -1;
1137  }
1138 
1139  if (!ctx) {
1140  fprintf(log, "Current state of talloced memory:\n");
1141  talloc_report_full(talloc_null_ctx(), log);
1142  } else {
1143  int i;
1144 
1145  fprintf(log, "Talloc chunk lineage:\n");
1146  fprintf(log, "%p (%s)", ctx, talloc_get_name(ctx));
1147 
1148  i = 0;
1149  while ((i < TALLOC_REPORT_MAX_DEPTH) && (ctx = talloc_parent(ctx))) {
1150  fprintf(log, " < %p (%s)", ctx, talloc_get_name(ctx));
1151  i++;
1152  }
1153  fprintf(log, "\n");
1154 
1155  i = 0;
1156  do {
1157  fprintf(log, "Talloc context level %i:\n", i++);
1158  talloc_report_full(ctx, log);
1159  } while ((ctx = talloc_parent(ctx)) &&
1160  (i < TALLOC_REPORT_MAX_DEPTH) &&
1161  (talloc_parent(ctx) != talloc_autofree_ctx) && /* Stop before we hit the autofree ctx */
1162  (talloc_parent(ctx) != talloc_null_ctx())); /* Stop before we hit NULL ctx */
1163  }
1164 
1165  fclose(log);
1166 
1167  return 0;
1168 }
1169 
1170 
1171 static int _disable_null_tracking(UNUSED bool *p)
1172 {
1173  talloc_disable_null_tracking();
1174  return 0;
1175 }
1176 
1177 /** Disable the null tracking context when a talloc chunk is freed
1178  *
1179  */
1181 {
1182  bool *marker;
1183 
1184  /*
1185  * Disable null tracking on exit, else valgrind complains
1186  */
1187  marker = talloc(ctx, bool);
1188  talloc_set_destructor(marker, _disable_null_tracking);
1189 }
1190 
1191 /** Register talloc fault handlers
1192  *
1193  * Just register the fault handlers we need to make talloc
1194  * produce useful debugging output.
1195  */
1197 {
1198  talloc_set_log_fn(_fr_talloc_log);
1199  talloc_set_abort_fn(_fr_talloc_fault_simple);
1200 }
1201 
1202 /** Registers signal handlers to execute panic_action on fatal signal
1203  *
1204  * May be called multiple time to change the panic_action/program.
1205  *
1206  * @param[in] ctx to allocate autofreeable resources in.
1207  * @param[in] cmd to execute on fault. If present %p will be substituted
1208  * for the parent PID before the command is executed, and %e
1209  * will be substituted for the currently running program.
1210  * @param program Name of program currently executing (argv[0]).
1211  * @return
1212  * - 0 on success.
1213  * - -1 on failure.
1214  */
1215 int fr_fault_setup(TALLOC_CTX *ctx, char const *cmd, char const *program)
1216 {
1217  static bool setup = false;
1218 
1219  char *out = panic_action;
1220  size_t left = sizeof(panic_action);
1221 
1222  char const *p = cmd;
1223  char const *q;
1224 
1225  if (cmd) {
1226  size_t ret;
1227 
1228  /* Substitute %e for the current program */
1229  while ((q = strstr(p, "%e"))) {
1230  out += ret = snprintf(out, left, "%.*s%s", (int) (q - p), p, program ? program : "");
1231  if (left <= ret) {
1232  oob:
1233  fr_strerror_const("Panic action too long");
1234  return -1;
1235  }
1236  left -= ret;
1237  p = q + 2;
1238  }
1239  if (strlen(p) >= left) goto oob;
1240  strlcpy(out, p, left);
1241  } else {
1242  *panic_action = '\0';
1243  }
1244 
1245  /*
1246  * Check for administrator sanity.
1247  */
1248  if (fr_fault_check_permissions() < 0) return -1;
1249 
1250  /* Unsure what the side effects of changing the signal handler mid execution might be */
1251  if (!setup) {
1252  char *env;
1253 
1254  /*
1255  * Installing signal handlers interferes with some debugging
1256  * operations. Give the developer control over whether the
1257  * signal handlers are installed or not.
1258  */
1259  env = getenv("DEBUGGER_ATTACHED");
1260  if (env && (strcmp(env, "yes") == 0)) {
1261  fr_debug_state = DEBUGGER_STATE_ATTACHED; /* i.e. disable signal handlers */
1262 
1263  } else if (env && (strcmp(env, "no") == 0)) {
1264  fr_debug_state = DEBUGGER_STATE_NOT_ATTACHED; /* i.e. enable signal handlers */
1265 
1266  /*
1267  * Figure out if we were started under a debugger
1268  */
1269  } else {
1271  }
1272 
1273  talloc_set_log_fn(_fr_talloc_log);
1274 
1275  /*
1276  * These signals can't be properly dealt with in the debugger
1277  * if we set our own signal handlers.
1278  */
1279  switch (fr_debug_state) {
1280  default:
1282 #ifdef SIGABRT
1283  if (fr_set_signal(SIGABRT, fr_fault) < 0) return -1;
1284 
1285  /*
1286  * Use this instead of abort so we get a
1287  * full backtrace with broken versions of LLDB
1288  */
1289  talloc_set_abort_fn(_fr_talloc_fault);
1290 #endif
1291 #ifdef SIGILL
1292  if (fr_set_signal(SIGILL, fr_fault) < 0) return -1;
1293 #endif
1294 #ifdef SIGFPE
1295  if (fr_set_signal(SIGFPE, fr_fault) < 0) return -1;
1296 #endif
1297 #ifdef SIGSEGV
1298  if (fr_set_signal(SIGSEGV, fr_fault) < 0) return -1;
1299 #endif
1300 #ifdef SIGALRM
1301  /*
1302  * This is used be jlibtool to terminate
1303  * processes which have been running too
1304  * long.
1305  */
1306  if (fr_set_signal(SIGALRM, fr_fault) < 0) return -1;
1307 #endif
1308  break;
1309 
1311  break;
1312  }
1313 
1314  /*
1315  * Needed for memory reports
1316  */
1318 
1319 #if defined(HAVE_MALLOPT) && !defined(NDEBUG)
1320  /*
1321  * If were using glibc malloc > 2.4 this scribbles over
1322  * uninitialised and freed memory, to make memory issues easier
1323  * to track down.
1324  */
1325 # ifdef M_PERTURB
1326  if (!getenv("TALLOC_FREE_FILL")) mallopt(M_PERTURB, 0x42);
1327 # endif
1328 # ifdef M_CHECK_ACTION
1329  mallopt(M_CHECK_ACTION, 3);
1330 # endif
1331 #endif
1332 
1333 #if defined(HAVE_EXECINFO) && defined(__GNUC__) && !defined(NDEBUG)
1334  /*
1335  * We need to pre-load lgcc_s, else we can get into a deadlock
1336  * in fr_fault, as backtrace() attempts to dlopen it.
1337  *
1338  * Apparently there's a performance impact of loading lgcc_s,
1339  * so only do it if this is a debug build.
1340  *
1341  * See: https://sourceware.org/bugzilla/show_bug.cgi?id=16159
1342  */
1343  {
1344  void *stack[10];
1345 
1346  backtrace(stack, 10);
1347  }
1348 #endif
1349  }
1350  setup = true;
1351 
1352  return 0;
1353 }
1354 
1355 /** Set a callback to be called before fr_fault()
1356  *
1357  * @param func to execute. If callback returns < 0
1358  * fr_fault will exit before running panic_action code.
1359  */
1361 {
1362  panic_cb = func;
1363 }
1364 
1365 /** Log output to the fr_fault_log_fd
1366  *
1367  * We used to support a user defined callback, which was set to a radlog
1368  * function. Unfortunately, when logging to syslog, syslog would alloc memory
1369  * which would result in a deadlock if fr_fault was triggered from within
1370  * a allocation call.
1371  *
1372  * Now we just write directly to the FD.
1373  */
1374 void fr_fault_log(char const *msg, ...)
1375 {
1376  va_list ap;
1377 
1378  if (fr_fault_log_fd < 0) return;
1379 
1380  va_start(ap, msg);
1382  va_end(ap);
1383 }
1384 
1385 /** Print data as a hex block
1386  *
1387  */
1388 void fr_fault_log_hex(uint8_t const *data, size_t data_len)
1389 {
1390  size_t i, j, len;
1391  char buffer[(0x10 * 3) + 1];
1392  char *p, *end = buffer + sizeof(buffer);
1393 
1394  for (i = 0; i < data_len; i += 0x10) {
1395  len = 0x10;
1396  if ((i + len) > data_len) len = data_len - i;
1397 
1398  for (p = buffer, j = 0; j < len; j++, p += 3) snprintf(p, end - p, "%02x ", data[i + j]);
1399 
1400  dprintf(fr_fault_log_fd, "%04x: %s\n", (int)i, buffer);
1401  }
1402 }
1403 
1404 /** Set a file descriptor to log memory reports to.
1405  *
1406  * @param fd to write output to.
1407  */
1409 {
1410  fr_fault_log_fd = fd;
1411 }
1412 
1413 /** A soft assertion which triggers the fault handler in debug builds
1414  *
1415  * @param[in] file the assertion failed in.
1416  * @param[in] line of the assertion in the file.
1417  * @param[in] expr that was evaluated.
1418  * @param[in] msg Message to print (may be NULL).
1419  * @param[in] ... Arguments for msg string.
1420  * @return the value of cond.
1421  */
1422 bool _fr_assert_fail(char const *file, int line, char const *expr, char const *msg, ...)
1423 {
1424  if (msg) {
1425  char str[256]; /* Decent compilers won't allocate this unless fmt is !NULL... */
1426  va_list ap;
1427 
1428  va_start(ap, msg);
1429  (void)vsnprintf(str, sizeof(str), msg, ap);
1430  va_end(ap);
1431 
1432 #ifndef NDEBUG
1433  FR_FAULT_LOG("ASSERT FAILED %s[%u]: %s: %s", file, line, expr, str);
1434  fr_fault(SIGABRT);
1435 #else
1436  FR_FAULT_LOG("ASSERT WOULD FAIL %s[%u]: %s: %s", file, line, expr, str);
1437  return false;
1438 #endif
1439  }
1440 
1441 #ifndef NDEBUG
1442  FR_FAULT_LOG("ASSERT FAILED %s[%u]: %s", file, line, expr);
1443  fr_fault(SIGABRT);
1444 #else
1445  FR_FAULT_LOG("ASSERT WOULD FAIL %s[%u]: %s", file, line, expr);
1446  return false;
1447 #endif
1448 }
1449 
1450 /** A fatal assertion which triggers the fault handler in debug builds or exits
1451  *
1452  * @param[in] file the assertion failed in.
1453  * @param[in] line of the assertion in the file.
1454  * @param[in] expr that was evaluated.
1455  * @param[in] msg Message to print (may be NULL).
1456  * @param[in] ... Arguments for msg string.
1457  */
1458 void _fr_assert_fatal(char const *file, int line, char const *expr, char const *msg, ...)
1459 {
1460  if (msg) {
1461  char str[256]; /* Decent compilers won't allocate this unless fmt is !NULL... */
1462  va_list ap;
1463 
1464  va_start(ap, msg);
1465  (void)vsnprintf(str, sizeof(str), msg, ap);
1466  va_end(ap);
1467 
1468  FR_FAULT_LOG("FATAL ASSERT %s[%u]: %s: %s", file, line, expr, str);
1469  } else {
1470  FR_FAULT_LOG("FATAL ASSERT %s[%u]: %s", file, line, expr);
1471  }
1472 
1473 #ifdef NDEBUG
1474  _fr_exit(file, line, 128 + SIGABRT, true);
1475 #else
1476  fr_fault(SIGABRT);
1477 #endif
1478 }
1479 
1480 /** Exit possibly printing a message about why we're exiting.
1481  *
1482  * @note Use the fr_exit(status) macro instead of calling this function directly.
1483  *
1484  * @param[in] file where fr_exit() was called.
1485  * @param[in] line where fr_exit() was called.
1486  * @param[in] status we're exiting with.
1487  * @param[in] now Exit immediately.
1488  */
1489 #ifndef NDEBUG
1490 NEVER_RETURNS void _fr_exit(char const *file, int line, int status, bool now)
1491 {
1492  if (status != EXIT_SUCCESS) {
1493  char const *error = fr_strerror();
1494 
1495  if (error && *error && (status != 0)) {
1496  FR_FAULT_LOG("%sEXIT(%i) CALLED %s[%u]. Last error was: %s", now ? "_" : "",
1497  status, file, line, error);
1498  } else {
1499  FR_FAULT_LOG("%sEXIT(%i) CALLED %s[%u]", now ? "_" : "", status, file, line);
1500  }
1501 
1502  fr_debug_break(false); /* If running under GDB we'll break here */
1503  }
1504 
1505  if (now) _Exit(status);
1506  exit(status);
1507 }
1508 #else
1509 NEVER_RETURNS void _fr_exit(UNUSED char const *file, UNUSED int line, int status, bool now)
1510 {
1511  if (status != EXIT_SUCCESS) fr_debug_break(false); /* If running under GDB we'll break here */
1512 
1513  if (now) _Exit(status);
1514  exit(status);
1515 }
1516 #endif
1517 
1518 /*
1519  * Sign a structure, but skip _signature at "offset".
1520  */
1521 static uint32_t fr_hash_struct(void const *ptr, size_t size, size_t offset)
1522 {
1523  uint32_t hash;
1524 
1525  /*
1526  * Hash entry is at the end of the structure, that's
1527  * best...
1528  */
1529  if ((size + 4) == offset) {
1530  return fr_hash(ptr, size);
1531  }
1532 
1533  hash = fr_hash(ptr, offset);
1534  return fr_hash_update(((uint8_t const *) ptr) + offset + 4, size - (offset + 4), hash);
1535 }
1536 
1537 void fr_sign_struct(void *ptr, size_t size, size_t offset)
1538 {
1539  *(uint32_t *) (((uint8_t *) ptr) + offset) = fr_hash_struct(ptr, size, offset);
1540 }
1541 
1542 void fr_verify_struct(void const *ptr, size_t size, size_t offset)
1543 {
1544  uint32_t hash;
1545 
1546  hash = fr_hash_struct(ptr, size, offset);
1547 
1548  (void) fr_cond_assert(hash == *(uint32_t const *) (((uint8_t const *) ptr) + offset));
1549 }
1550 
1551 void fr_verify_struct_member(void const *ptr, size_t len, uint32_t *signature)
1552 {
1553  uint32_t hash;
1554 
1555  hash = fr_hash(ptr, len);
1556  (void) fr_cond_assert(hash == *signature);
1557 }
vsnprintf(buffer, sizeof(buffer), fmt, args)
static int const char char buffer[256]
Definition: acutest.h:574
int const char * file
Definition: acutest.h:702
va_end(args)
log_entry msg
Definition: acutest.h:794
int const char int line
Definition: acutest.h:702
va_start(args, fmt)
#define NEVER_RETURNS
Should be placed before the function return type.
Definition: build.h:311
#define DIAG_ON(_x)
Definition: build.h:419
#define UNUSED
Definition: build.h:313
#define NUM_ELEMENTS(_t)
Definition: build.h:335
#define DIAG_OFF(_x)
Definition: build.h:418
static int fr_fault_check_permissions(void)
Check to see if panic_action file is world writable.
Definition: debug.c:884
static char panic_action[512]
The command to execute when panicking.
Definition: debug.c:96
fr_bt_marker_t * fr_backtrace_attach(UNUSED fr_fring_t **fring, UNUSED TALLOC_CTX *obj)
Definition: debug.c:677
static int _disable_null_tracking(UNUSED bool *p)
Definition: debug.c:1171
static int _panic_on_free(UNUSED char *foo)
Definition: debug.c:684
char const * fr_debug_state_to_msg(fr_debug_state_t state)
Return current value of debug_state.
Definition: debug.c:524
void fr_disable_null_tracking_on_free(TALLOC_CTX *ctx)
Disable the null tracking context when a talloc chunk is freed.
Definition: debug.c:1180
bool _fr_assert_fail(char const *file, int line, char const *expr, char const *msg,...)
A soft assertion which triggers the fault handler in debug builds.
Definition: debug.c:1422
void fr_fault_set_log_fd(int fd)
Set a file descriptor to log memory reports to.
Definition: debug.c:1408
static bool dump_core
Whether we should drop a core on fatal signals.
Definition: debug.c:100
int fr_log_talloc_report(TALLOC_CTX const *ctx)
Generate a talloc memory report for a context and print to stderr/stdout.
Definition: debug.c:1120
int fr_set_dumpable(bool allow_core_dumps)
Enable or disable core dumps.
Definition: debug.c:805
static void _fr_talloc_fault_simple(char const *reason)
Callback executed on fatal talloc error.
Definition: debug.c:1073
void fr_verify_struct(void const *ptr, size_t size, size_t offset)
Definition: debug.c:1542
static int fr_set_pr_dumpable_flag(UNUSED bool dumpable)
Set the dumpable flag, also controls whether processes can PATTACH.
Definition: debug.c:732
static fr_fault_cb_t panic_cb
Callback to execute whilst panicking, before the panic_action.
Definition: debug.c:97
static TALLOC_CTX * talloc_autofree_ctx
Definition: debug.c:110
static uint32_t fr_hash_struct(void const *ptr, size_t size, size_t offset)
Definition: debug.c:1521
static int fr_fault_log_fd
Where to write debug output.
Definition: debug.c:102
int fr_reset_dumpable(void)
Reset dumpable state to previously configured value.
Definition: debug.c:873
int fr_fault_setup(TALLOC_CTX *ctx, char const *cmd, char const *program)
Registers signal handlers to execute panic_action on fatal signal.
Definition: debug.c:1215
void fr_verify_struct_member(void const *ptr, size_t len, uint32_t *signature)
Definition: debug.c:1551
#define TALLOC_REPORT_MAX_DEPTH
NEVER_RETURNS void fr_fault(int sig)
Prints a simple backtrace (if execinfo is available) and calls panic_action if set.
Definition: debug.c:929
void fr_sign_struct(void *ptr, size_t size, size_t offset)
Definition: debug.c:1537
int fr_get_lsan_state(void)
Definition: debug.c:261
void fr_debug_state_store(void)
Should be run before using setuid or setgid to get useful results.
Definition: debug.c:504
NEVER_RETURNS void _fr_exit(char const *file, int line, int status, bool now)
Exit possibly printing a message about why we're exiting.
Definition: debug.c:1490
void fr_talloc_fault_setup(void)
Register talloc fault handlers.
Definition: debug.c:1196
void fr_debug_break(bool always)
Break in debugger (if were running under a debugger)
Definition: debug.c:553
void fr_fault_set_cb(fr_fault_cb_t func)
Set a callback to be called before fr_fault()
Definition: debug.c:1360
void _fr_assert_fatal(char const *file, int line, char const *expr, char const *msg,...)
A fatal assertion which triggers the fault handler in debug builds or exits.
Definition: debug.c:1458
void fr_fault_log_hex(uint8_t const *data, size_t data_len)
Print data as a hex block.
Definition: debug.c:1388
int fr_set_dumpable_init(void)
Get the current maximum for core files.
Definition: debug.c:790
void fr_panic_on_free(TALLOC_CTX *ctx)
Insert memory into the context of another talloc memory chunk which causes a panic when freed.
Definition: debug.c:695
static void _fr_talloc_fault(char const *reason)
Callback executed on fatal talloc error.
Definition: debug.c:1099
static void _fr_talloc_log(char const *msg)
Wrapper to pass talloc log output to our fr_fault_log function.
Definition: debug.c:1111
static int fr_get_pr_dumpable_flag(void)
Get the processes dumpable flag.
Definition: debug.c:778
fr_debug_state_t fr_debug_state
Whether we're attached to by a debugger.
Definition: debug.c:104
void backtrace_print(UNUSED fr_fring_t *fring, UNUSED void *obj)
Definition: debug.c:673
int fr_get_debug_state(void)
Definition: debug.c:492
void fr_fault_log(char const *msg,...)
Log output to the fr_fault_log_fd.
Definition: debug.c:1374
fr_debug_state_t
Definition: debug.h:39
@ DEBUGGER_STATE_NOT_ATTACHED
We can attach, so a debugger must not be.
Definition: debug.h:43
@ DEBUGGER_STATE_UNKNOWN_NO_PTRACE
We don't have ptrace so can't check.
Definition: debug.h:40
@ DEBUGGER_STATE_UNKNOWN_NO_PTRACE_CAP
CAP_SYS_PTRACE not set for the process.
Definition: debug.h:41
@ DEBUGGER_STATE_UNKNOWN
Unknown, likely fr_get_debug_state() not called yet.
Definition: debug.h:42
@ DEBUGGER_STATE_ATTACHED
We can't attach, it's likely a debugger is already tracing.
Definition: debug.h:44
struct fr_bt_marker fr_bt_marker_t
Definition: debug.h:64
#define fr_cond_assert(_x)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition: debug.h:137
int(* fr_fault_cb_t)(int signum)
Optional callback passed to fr_fault_setup.
Definition: debug.h:63
#define FR_FAULT_LOG(_fmt,...)
Definition: debug.h:49
int fr_backtrace_do(fr_bt_marker_t *marker)
#define fr_exit_now(_x)
Exit without calling atexit() handlers, producing a log message in debug builds.
Definition: debug.h:232
void * fr_fring_next(fr_fring_t *fring)
Remove an item from the buffer.
Definition: fring.c:177
fr_fring_t * fr_fring_alloc(TALLOC_CTX *ctx, uint32_t size, bool lock)
Initialise a ring buffer with fixed element size.
Definition: fring.c:78
int fr_fring_overwrite(fr_fring_t *fring, void *in)
Insert a new item into the circular buffer, freeing the tail if we hit it.
Definition: fring.c:120
Standard thread safe circular buffer.
Definition: fring.c:36
uint32_t fr_hash_update(void const *data, size_t size, uint32_t hash)
Definition: hash.c:840
uint32_t fr_hash(void const *data, size_t size)
Definition: hash.c:806
waitpid(reap->pid_ev->pid, &status, 0)
static char * stack[MAX_STACK]
Definition: radmin.c:158
unsigned int uint32_t
Definition: merged_model.c:33
unsigned char uint8_t
Definition: merged_model.c:30
static size_t used
int fr_unset_signal(int sig)
Uninstall a signal for a specific handler.
Definition: misc.c:76
int fr_set_signal(int sig, sig_t func)
Sets a signal handler using sigaction if available, else signal.
Definition: misc.c:47
int vdprintf(int fd, char const *format, va_list args)
Definition: missing.c:210
#define is_truncated(_ret, _max)
Definition: print.h:48
static rc_request_t * current
Definition: radclient-ng.c:97
static unsigned int hash(char const *username, unsigned int tablesize)
Definition: rlm_passwd.c:132
PUBLIC int snprintf(char *string, size_t length, char *format, va_alist)
Definition: snprintf.c:689
return count
Definition: module.c:175
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition: strlcpy.c:34
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition: syserror.c:243
void * talloc_null_ctx(void)
Retrieve the current talloc NULL ctx.
Definition: talloc.c:49
close(uq->fd)
char const * fr_strerror(void)
Get the last library error.
Definition: strerror.c:554
#define fr_strerror_printf(_fmt,...)
Log to thread local error buffer.
Definition: strerror.h:64
#define fr_strerror_const(_msg)
Definition: strerror.h:223
static fr_slen_t data
Definition: value.h:1259
static size_t char ** out
Definition: value.h:984