blob: 9f4d0eef80cc0ea0d0caf500da9b13c8284e08ee [file] [log] [blame]
Elliott Hughesb8a8cf02015-01-24 18:36:29 -08001/*
2 * Copyright (C) 2015 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 <error.h>
30
31#include <errno.h>
32#include <stdio.h>
33#include <stdlib.h>
34
35unsigned int error_message_count = 0;
36void (*error_print_progname)(void) = NULL;
37int error_one_per_line = 0;
38
39static void __error_head() {
40 ++error_message_count;
41
42 if (error_print_progname != NULL) {
43 error_print_progname();
44 } else {
45 fflush(stdout);
46 fprintf(stderr, "%s:", getprogname());
47 }
48}
49
50static void __error_tail(int status, int error) {
51 if (error != 0) {
52 fprintf(stderr, ": %s", strerror(error));
53 }
54
55 putc('\n', stderr);
56 fflush(stderr);
57
58 if (status != 0) {
59 exit(status);
60 }
61}
62
63void error(int status, int error, const char* fmt, ...) {
64 __error_head();
65 putc(' ', stderr);
66
67 va_list ap;
68 va_start(ap, fmt);
69 vfprintf(stderr, fmt, ap);
70 va_end(ap);
71
72 __error_tail(status, error);
73}
74
75void error_at_line(int status, int error, const char* file, unsigned int line, const char* fmt, ...) {
76 if (error_one_per_line) {
77 static const char* last_file;
78 static unsigned int last_line;
79 if (last_line == line && last_file != NULL && strcmp(last_file, file) == 0) {
80 return;
81 }
82 last_file = file;
83 last_line = line;
84 }
85
86 __error_head();
87 fprintf(stderr, "%s:%d: ", file, line);
88
89 va_list ap;
90 va_start(ap, fmt);
91 vfprintf(stderr, fmt, ap);
92 va_end(ap);
93
94 __error_tail(status, error);
95}