blob: f42f2b5384a2d5e5032bc85aadadf9989e35cc28 [file] [log] [blame]
Rob Pike69b74c32008-06-12 13:26:16 -07001/*
2Plan 9 from User Space src/lib9/errstr.c
3http://code.swtch.com/plan9port/src/tip/src/lib9/errstr.c
4
5Copyright 2001-2007 Russ Cox. All Rights Reserved.
6
7Permission is hereby granted, free of charge, to any person obtaining a copy
8of this software and associated documentation files (the "Software"), to deal
9in the Software without restriction, including without limitation the rights
10to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11copies of the Software, and to permit persons to whom the Software is
12furnished to do so, subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in
15all copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23THE SOFTWARE.
24*/
25
26/*
27 * We assume there's only one error buffer for the whole system.
28 * If you use ffork, you need to provide a _syserrstr. Since most
29 * people will use libthread (which provides a _syserrstr), this is
30 * okay.
31 */
32
33#include <u.h>
34#include <errno.h>
35#include <string.h>
36#include <libc.h>
37
38enum
39{
40 EPLAN9 = 0x19283745
41};
42
43char *(*_syserrstr)(void);
44static char xsyserr[ERRMAX];
45static char*
46getsyserr(void)
47{
48 char *s;
49
50 s = nil;
51 if(_syserrstr)
52 s = (*_syserrstr)();
53 if(s == nil)
54 s = xsyserr;
55 return s;
56}
57
58int
59errstr(char *err, uint n)
60{
61 char tmp[ERRMAX];
62 char *syserr;
63
64 strecpy(tmp, tmp+ERRMAX, err);
65 rerrstr(err, n);
66 syserr = getsyserr();
67 strecpy(syserr, syserr+ERRMAX, tmp);
68 errno = EPLAN9;
69 return 0;
70}
71
72void
73rerrstr(char *err, uint n)
74{
75 char *syserr;
76
77 syserr = getsyserr();
78 if(errno == EINTR)
79 strcpy(syserr, "interrupted");
80 else if(errno != EPLAN9)
81 strcpy(syserr, strerror(errno));
82 strecpy(err, err+n, syserr);
83}
84
85/* replaces __errfmt in libfmt */
86
87int
88__errfmt(Fmt *f)
89{
90 if(errno == EPLAN9)
91 return fmtstrcpy(f, getsyserr());
92 return fmtstrcpy(f, strerror(errno));
93}
94
95void
96werrstr(char *fmt, ...)
97{
98 va_list arg;
99 char buf[ERRMAX];
100
101 va_start(arg, fmt);
102 vseprint(buf, buf+ERRMAX, fmt, arg);
103 va_end(arg);
104 errstr(buf, ERRMAX);
105}
106