|
| 1 | +/* SPDX-License-Identifier: Apache-2.0 OR MIT |
| 2 | + * |
| 3 | + * SPDX-FileCopyrightText: Copyright 2023 Micron Technology, Inc. |
| 4 | + */ |
| 5 | + |
| 6 | +#include <assert.h> |
| 7 | +#include <stdarg.h> |
| 8 | +#include <stddef.h> |
| 9 | +#include <stdio.h> |
| 10 | +#include <stdlib.h> |
| 11 | +#include <sysexits.h> |
| 12 | + |
| 13 | +#include <hse/hse.h> |
| 14 | + |
| 15 | +#include <hse/cli/output.h> |
| 16 | +#include <hse/cli/program.h> |
| 17 | +#include <hse/util/compiler.h> |
| 18 | + |
| 19 | +static thread_local char error_buffer_tls[1024]; |
| 20 | + |
| 21 | +static void |
| 22 | +eprint(const hse_err_t err, const char *fmt, va_list ap) |
| 23 | +{ |
| 24 | + int rc HSE_MAYBE_UNUSED; |
| 25 | + |
| 26 | + /* We take progname from argv[0]. argv[0] may contain % symbols which could |
| 27 | + * cause an escape in the vfprintf() below, so just print it plainly for |
| 28 | + * safety. |
| 29 | + */ |
| 30 | + fputs(progname, stderr); |
| 31 | + if (err) { |
| 32 | + char buf[256]; |
| 33 | + size_t needed_sz HSE_MAYBE_UNUSED; |
| 34 | + |
| 35 | + needed_sz = hse_strerror(err, buf, sizeof(buf)); |
| 36 | + assert(needed_sz < sizeof(buf)); |
| 37 | + |
| 38 | + rc = snprintf(error_buffer_tls, sizeof(error_buffer_tls), ": %s: %s\n", fmt, buf); |
| 39 | + } else { |
| 40 | + rc = snprintf(error_buffer_tls, sizeof(error_buffer_tls), ": %s\n", fmt); |
| 41 | + } |
| 42 | + assert(rc >= 0 && rc < sizeof(error_buffer_tls)); |
| 43 | + |
| 44 | + vfprintf(stderr, error_buffer_tls, ap); |
| 45 | +} |
| 46 | + |
| 47 | +void |
| 48 | +error(const hse_err_t err, const char * const fmt, ...) |
| 49 | +{ |
| 50 | + va_list ap; |
| 51 | + |
| 52 | + va_start(ap, fmt); |
| 53 | + eprint(err, fmt, ap); |
| 54 | + va_end(ap); |
| 55 | +} |
| 56 | + |
| 57 | +void |
| 58 | +fatal(const hse_err_t err, const char * const fmt, ...) |
| 59 | +{ |
| 60 | + va_list ap; |
| 61 | + |
| 62 | + va_start(ap, fmt); |
| 63 | + eprint(err, fmt, ap); |
| 64 | + va_end(ap); |
| 65 | + |
| 66 | + exit(1); |
| 67 | +} |
| 68 | + |
| 69 | +void |
| 70 | +syntax(const char * const fmt, ...) |
| 71 | +{ |
| 72 | + va_list ap; |
| 73 | + char msg[256]; |
| 74 | + |
| 75 | + va_start(ap, fmt); |
| 76 | + vsnprintf(msg, sizeof(msg), fmt, ap); |
| 77 | + va_end(ap); |
| 78 | + |
| 79 | + error(0, "%s, use -h for help", msg); |
| 80 | + exit(EX_USAGE); |
| 81 | +} |
0 commit comments