xref: /original-bsd/usr.bin/sed/misc.c (revision 49a3a6ff)
1 /*-
2  * Copyright (c) 1992 Diomidis Spinellis.
3  * Copyright (c) 1992 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Diomidis Spinellis of Imperial College, University of London.
8  *
9  * %sccs.include.redist.c%
10  */
11 
12 #ifndef lint
13 static char sccsid[] = "@(#)misc.c	5.4 (Berkeley) 04/14/93";
14 #endif /* not lint */
15 
16 #include <sys/types.h>
17 
18 #include <errno.h>
19 #include <regex.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include "defs.h"
25 #include "extern.h"
26 
27 /*
28  * malloc with result test
29  */
30 void *
31 xmalloc(size)
32 	u_int size;
33 {
34 	void *p;
35 
36 	if ((p = malloc(size)) == NULL)
37 		err(FATAL, "%s", strerror(errno));
38 	return (p);
39 }
40 
41 /*
42  * realloc with result test
43  */
44 void *
45 xrealloc(p, size)
46 	void *p;
47 	u_int size;
48 {
49 	if (p == NULL)			/* Compatibility hack. */
50 		return (xmalloc(size));
51 
52 	if ((p = realloc(p, size)) == NULL)
53 		err(FATAL, "%s", strerror(errno));
54 	return (p);
55 }
56 
57 char *
58 strnchr(buf, c, len)
59 	const char *buf;
60 	int c;
61 	size_t len;
62 {
63 	const char *cp;
64 
65 	for (cp = buf; cp - buf < len; cp++)
66 		if (*cp == c)
67 			return ((char *)cp);
68 	return (NULL);
69 }
70 
71 /*
72  * Return a string for a regular expression error passed.  This is a overkill,
73  * because of the silly semantics of regerror (we can never know the size of
74  * the buffer).
75  */
76 char *
77 strregerror(errcode, preg)
78 	int errcode;
79 	regex_t *preg;
80 {
81 	static char *oe;
82 	size_t s;
83 
84 	if (oe != NULL)
85 		free(oe);
86 	s = regerror(errcode, preg, "", 0);
87 	oe = xmalloc(s);
88 	(void)regerror(errcode, preg, oe, s);
89 	return (oe);
90 }
91 
92 #if __STDC__
93 #include <stdarg.h>
94 #else
95 #include <varargs.h>
96 #endif
97 /*
98  * Error reporting function
99  */
100 void
101 #if __STDC__
102 err(int severity, const char *fmt, ...)
103 #else
104 err(severity, fmt, va_alist)
105 	int severity;
106 	char *fmt;
107         va_dcl
108 #endif
109 {
110 	va_list ap;
111 #if __STDC__
112 	va_start(ap, fmt);
113 #else
114 	va_start(ap);
115 #endif
116 	(void)fprintf(stderr, "sed: ");
117 	switch (severity) {
118 	case WARNING:
119 	case COMPILE:
120 		(void)fprintf(stderr, "%lu: %s: ", linenum, fname);
121 	}
122 	(void)vfprintf(stderr, fmt, ap);
123 	va_end(ap);
124 	(void)fprintf(stderr, "\n");
125 	if (severity == WARNING)
126 		return;
127 	exit(1);
128 	/* NOTREACHED */
129 }
130