github.com/anonymouse64/snapd@v0.0.0-20210824153203-04c4c42d842d/cmd/libsnap-confine-private/panic.c (about)

     1  /*
     2   * Copyright (C) 2019 Canonical Ltd
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License version 3 as
     6   * published by the Free Software Foundation.
     7   *
     8   * This program is distributed in the hope that it will be useful,
     9   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    10   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11   * GNU General Public License for more details.
    12   *
    13   * You should have received a copy of the GNU General Public License
    14   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15   *
    16   */
    17  
    18  #include "panic.h"
    19  
    20  #include <errno.h>
    21  #include <stdarg.h>
    22  #include <stdio.h>
    23  #include <stdlib.h>
    24  #include <string.h>
    25  #include <unistd.h>
    26  
    27  static sc_panic_exit_fn panic_exit_fn = NULL;
    28  static sc_panic_msg_fn panic_msg_fn = NULL;
    29  
    30  void sc_panic(const char *fmt, ...) {
    31      va_list ap;
    32      va_start(ap, fmt);
    33      sc_panicv(fmt, ap);
    34      va_end(ap);
    35  }
    36  
    37  void sc_panicv(const char *fmt, va_list ap) {
    38      int errno_copy = errno;
    39  
    40      if (panic_msg_fn != NULL) {
    41          panic_msg_fn(fmt, ap, errno_copy);
    42      } else {
    43          vfprintf(stderr, fmt, ap);
    44          if (errno != 0) {
    45              fprintf(stderr, ": %s\n", strerror(errno_copy));
    46          } else {
    47              fprintf(stderr, "\n");
    48          }
    49      }
    50  
    51      if (panic_exit_fn != NULL) {
    52          panic_exit_fn();
    53      }
    54      exit(1);
    55  }
    56  
    57  sc_panic_exit_fn sc_set_panic_exit_fn(sc_panic_exit_fn fn) {
    58      sc_panic_exit_fn old = panic_exit_fn;
    59      panic_exit_fn = fn;
    60      return old;
    61  }
    62  
    63  sc_panic_msg_fn sc_set_panic_msg_fn(sc_panic_msg_fn fn) {
    64      sc_panic_msg_fn old = panic_msg_fn;
    65      panic_msg_fn = fn;
    66      return old;
    67  }