Home | History | Annotate | Line # | Download | only in isc
backtrace.c revision 1.1.1.6
      1 /*	$NetBSD: backtrace.c,v 1.1.1.6 2024/02/21 21:54:49 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      5  *
      6  * SPDX-License-Identifier: MPL-2.0
      7  *
      8  * This Source Code Form is subject to the terms of the Mozilla Public
      9  * License, v. 2.0. If a copy of the MPL was not distributed with this
     10  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
     11  *
     12  * See the COPYRIGHT file distributed with this work for additional
     13  * information regarding copyright ownership.
     14  */
     15 
     16 /*! \file */
     17 
     18 #include <stdlib.h>
     19 #include <string.h>
     20 #ifdef HAVE_BACKTRACE_SYMBOLS
     21 #include <execinfo.h>
     22 #endif /* HAVE_BACKTRACE_SYMBOLS */
     23 
     24 #include <isc/backtrace.h>
     25 #include <isc/print.h>
     26 #include <isc/result.h>
     27 #include <isc/util.h>
     28 
     29 #if HAVE_BACKTRACE_SYMBOLS
     30 int
     31 isc_backtrace(void **addrs, int maxaddrs) {
     32 	int n;
     33 
     34 	/*
     35 	 * Validate the arguments: intentionally avoid using REQUIRE().
     36 	 * See notes in backtrace.h.
     37 	 */
     38 	if (addrs == NULL || maxaddrs <= 0) {
     39 		return (-1);
     40 	}
     41 
     42 	/*
     43 	 * backtrace(3) includes this function itself in the address array,
     44 	 * which should be eliminated from the returned sequence.
     45 	 */
     46 	n = backtrace(addrs, maxaddrs);
     47 	if (n < 2) {
     48 		return (-1);
     49 	}
     50 	n--;
     51 	memmove(addrs, &addrs[1], sizeof(addrs[0]) * n);
     52 
     53 	return (n);
     54 }
     55 
     56 char **
     57 isc_backtrace_symbols(void *const *buffer, int size) {
     58 	return (backtrace_symbols(buffer, size));
     59 }
     60 
     61 void
     62 isc_backtrace_symbols_fd(void *const *buffer, int size, int fd) {
     63 	backtrace_symbols_fd(buffer, size, fd);
     64 }
     65 
     66 #else /* HAVE_BACKTRACE_SYMBOLS */
     67 
     68 int
     69 isc_backtrace(void **addrs, int maxaddrs) {
     70 	UNUSED(addrs);
     71 	UNUSED(maxaddrs);
     72 
     73 	return (-1);
     74 }
     75 
     76 char **
     77 isc_backtrace_symbols(void *const *buffer, int size) {
     78 	UNUSED(buffer);
     79 	UNUSED(size);
     80 
     81 	return (NULL);
     82 }
     83 
     84 void
     85 isc_backtrace_symbols_fd(void *const *buffer, int size, int fd) {
     86 	UNUSED(buffer);
     87 	UNUSED(size);
     88 	UNUSED(fd);
     89 }
     90 
     91 #endif /* HAVE_BACKTRACE_SYMBOLS */
     92