blob: 2f3eee1be0667aa8bab4086fa8357530c9e68745 [file] [log] [blame]
Elliott Hughes7887e0e2025-08-13 08:04:13 -07001/*
2 * Copyright (C) 2025 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <err.h>
30
31#include <errno.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35
36static void report_err(bool show_errno, const char* fmt, va_list args) {
37 int error = errno;
38 fflush(stdout);
39
40 fprintf(stderr, "%s: ", getprogname());
41 if (fmt) {
42 vfprintf(stderr, fmt, args);
43 if (show_errno) fprintf(stderr, ": ");
44 }
45 if (show_errno) fprintf(stderr, "%s", strerror(error));
46 putc('\n', stderr);
47 fflush(stderr);
48}
49
50void err(int status, const char* _Nullable fmt, ...) {
51 va_list va;
52 va_start(va, fmt);
53 verr(status, fmt, va);
54}
55
56void verr(int status, const char* _Nullable fmt, va_list args) {
57 report_err(true, fmt, args);
58 exit(status);
59}
60
61void errx(int status, const char* _Nullable fmt, ...) {
62 va_list va;
63 va_start(va, fmt);
64 verrx(status, fmt, va);
65}
66
67void verrx(int status, const char* _Nullable fmt, va_list args) {
68 report_err(false, fmt, args);
69 exit(status);
70}
71
72void warn(const char* _Nullable fmt, ...) {
73 va_list va;
74 va_start(va, fmt);
75 vwarn(fmt, va);
76 va_end(va);
77}
78
79void vwarn(const char* _Nullable fmt, va_list args) {
80 report_err(true, fmt, args);
81}
82
83void warnx(const char* _Nullable fmt, ...) {
84 va_list va;
85 va_start(va, fmt);
86 vwarnx(fmt, va);
87 va_end(va);
88}
89
90void vwarnx(const char* _Nullable fmt, va_list args) {
91 report_err(false, fmt, args);
92}