xref: /dragonfly/contrib/bmake/util.c (revision e95199c5)
1 /*	$NetBSD: util.c,v 1.76 2021/02/03 08:00:36 rillig Exp $	*/
2 
3 /*
4  * Missing stuff from OS's
5  *
6  *	$Id: util.c,v 1.46 2021/02/05 20:02:29 sjg Exp $
7  */
8 
9 #include <sys/param.h>
10 #include <errno.h>
11 #include <time.h>
12 #include <signal.h>
13 
14 #include "make.h"
15 
16 MAKE_RCSID("$NetBSD: util.c,v 1.76 2021/02/03 08:00:36 rillig Exp $");
17 
18 #if !defined(MAKE_NATIVE) && !defined(HAVE_STRERROR)
19 extern int errno, sys_nerr;
20 extern char *sys_errlist[];
21 
22 char *
23 strerror(int e)
24 {
25     static char buf[100];
26     if (e < 0 || e >= sys_nerr) {
27 	snprintf(buf, sizeof buf, "Unknown error %d", e);
28 	return buf;
29     } else
30 	return sys_errlist[e];
31 }
32 #endif
33 
34 #if !defined(HAVE_GETENV) || !defined(HAVE_SETENV) || !defined(HAVE_UNSETENV)
35 extern char **environ;
36 
37 static char *
38 findenv(const char *name, int *offset)
39 {
40 	size_t i, len;
41 	char *p, *q;
42 
43 	len = strlen(name);
44 	for (i = 0; (q = environ[i]); i++) {
45 		p = strchr(q, '=');
46 		if (p == NULL || p - q != len)
47 			continue;
48 		if (strncmp(name, q, len) == 0) {
49 			*offset = i;
50 			return q + len + 1;
51 		}
52 	}
53 	*offset = i;
54 	return NULL;
55 }
56 
57 char *
58 getenv(const char *name)
59 {
60     int offset;
61 
62     return findenv(name, &offset);
63 }
64 
65 int
66 unsetenv(const char *name)
67 {
68 	char **p;
69 	int offset;
70 
71 	if (name == NULL || *name == '\0' || strchr(name, '=') != NULL) {
72 		errno = EINVAL;
73 		return -1;
74 	}
75 
76 	while (findenv(name, &offset))	{ /* if set multiple times */
77 		for (p = &environ[offset];; p++)
78 			if (!(*p = *(p + 1)))
79 				break;
80 	}
81 	return 0;
82 }
83 
84 int
85 setenv(const char *name, const char *value, int rewrite)
86 {
87 	char *c, **newenv;
88 	const char *cc;
89 	size_t l_value, size;
90 	int offset;
91 
92 	if (name == NULL || value == NULL) {
93 		errno = EINVAL;
94 		return -1;
95 	}
96 
97 	if (*value == '=')			/* no `=' in value */
98 		value++;
99 	l_value = strlen(value);
100 
101 	/* find if already exists */
102 	if ((c = findenv(name, &offset))) {
103 		if (!rewrite)
104 			return 0;
105 		if (strlen(c) >= l_value)	/* old larger; copy over */
106 			goto copy;
107 	} else {					/* create new slot */
108 		size = sizeof(char *) * (offset + 2);
109 		if (savedEnv == environ) {		/* just increase size */
110 			if ((newenv = realloc(savedEnv, size)) == NULL)
111 				return -1;
112 			savedEnv = newenv;
113 		} else {				/* get new space */
114 			/*
115 			 * We don't free here because we don't know if
116 			 * the first allocation is valid on all OS's
117 			 */
118 			if ((savedEnv = malloc(size)) == NULL)
119 				return -1;
120 			(void)memcpy(savedEnv, environ, size - sizeof(char *));
121 		}
122 		environ = savedEnv;
123 		environ[offset + 1] = NULL;
124 	}
125 	for (cc = name; *cc && *cc != '='; cc++)	/* no `=' in name */
126 		continue;
127 	size = cc - name;
128 	/* name + `=' + value */
129 	if ((environ[offset] = malloc(size + l_value + 2)) == NULL)
130 		return -1;
131 	c = environ[offset];
132 	(void)memcpy(c, name, size);
133 	c += size;
134 	*c++ = '=';
135 copy:
136 	(void)memcpy(c, value, l_value + 1);
137 	return 0;
138 }
139 
140 #ifdef TEST
141 int
142 main(int argc, char *argv[])
143 {
144 	setenv(argv[1], argv[2], 0);
145 	printf("%s\n", getenv(argv[1]));
146 	unsetenv(argv[1]);
147 	printf("%s\n", getenv(argv[1]));
148 	return 0;
149 }
150 #endif
151 
152 #endif
153 
154 
155 #if defined(__hpux__) || defined(__hpux)
156 /*
157  * strrcpy():
158  *	Like strcpy, going backwards and returning the new pointer
159  */
160 static char *
161 strrcpy(char *ptr, char *str)
162 {
163     int len = strlen(str);
164 
165     while (len != 0)
166 	*--ptr = str[--len];
167 
168     return ptr;
169 } /* end strrcpy */
170 
171 
172 char    *sys_siglist[] = {
173 	"Signal 0",
174 	"Hangup",			/* SIGHUP    */
175 	"Interrupt",			/* SIGINT    */
176 	"Quit",				/* SIGQUIT   */
177 	"Illegal instruction",		/* SIGILL    */
178 	"Trace/BPT trap",		/* SIGTRAP   */
179 	"IOT trap",			/* SIGIOT    */
180 	"EMT trap",			/* SIGEMT    */
181 	"Floating point exception",	/* SIGFPE    */
182 	"Killed",			/* SIGKILL   */
183 	"Bus error",			/* SIGBUS    */
184 	"Segmentation fault",		/* SIGSEGV   */
185 	"Bad system call",		/* SIGSYS    */
186 	"Broken pipe",			/* SIGPIPE   */
187 	"Alarm clock",			/* SIGALRM   */
188 	"Terminated",			/* SIGTERM   */
189 	"User defined signal 1",	/* SIGUSR1   */
190 	"User defined signal 2",	/* SIGUSR2   */
191 	"Child exited",			/* SIGCLD    */
192 	"Power-fail restart",		/* SIGPWR    */
193 	"Virtual timer expired",	/* SIGVTALRM */
194 	"Profiling timer expired",	/* SIGPROF   */
195 	"I/O possible",			/* SIGIO     */
196 	"Window size changes",		/* SIGWINDOW */
197 	"Stopped (signal)",		/* SIGSTOP   */
198 	"Stopped",			/* SIGTSTP   */
199 	"Continued",			/* SIGCONT   */
200 	"Stopped (tty input)",		/* SIGTTIN   */
201 	"Stopped (tty output)",		/* SIGTTOU   */
202 	"Urgent I/O condition",		/* SIGURG    */
203 	"Remote lock lost (NFS)",	/* SIGLOST   */
204 	"Signal 31",			/* reserved  */
205 	"DIL signal"			/* SIGDIL    */
206 };
207 #endif /* __hpux__ || __hpux */
208 
209 #if defined(__hpux__) || defined(__hpux)
210 #include <sys/types.h>
211 #include <sys/syscall.h>
212 #include <sys/signal.h>
213 #include <sys/stat.h>
214 #include <dirent.h>
215 #include <sys/time.h>
216 #include <unistd.h>
217 
218 int
219 killpg(int pid, int sig)
220 {
221     return kill(-pid, sig);
222 }
223 
224 #if !defined(BSD) && !defined(d_fileno)
225 # define d_fileno d_ino
226 #endif
227 
228 #ifndef DEV_DEV_COMPARE
229 # define DEV_DEV_COMPARE(a, b) ((a) == (b))
230 #endif
231 #define ISDOT(c) ((c)[0] == '.' && (((c)[1] == '\0') || ((c)[1] == '/')))
232 #define ISDOTDOT(c) ((c)[0] == '.' && ISDOT(&((c)[1])))
233 
234 char *
235 getwd(char *pathname)
236 {
237     DIR    *dp;
238     struct dirent *d;
239     extern int errno;
240 
241     struct stat st_root, st_cur, st_next, st_dotdot;
242     char    pathbuf[MAXPATHLEN], nextpathbuf[MAXPATHLEN * 2];
243     char   *pathptr, *nextpathptr, *cur_name_add;
244 
245     /* find the inode of root */
246     if (stat("/", &st_root) == -1) {
247 	(void)sprintf(pathname,
248 			"getwd: Cannot stat \"/\" (%s)", strerror(errno));
249 	return NULL;
250     }
251     pathbuf[MAXPATHLEN - 1] = '\0';
252     pathptr = &pathbuf[MAXPATHLEN - 1];
253     nextpathbuf[MAXPATHLEN - 1] = '\0';
254     cur_name_add = nextpathptr = &nextpathbuf[MAXPATHLEN - 1];
255 
256     /* find the inode of the current directory */
257     if (lstat(".", &st_cur) == -1) {
258 	(void)sprintf(pathname,
259 			"getwd: Cannot stat \".\" (%s)", strerror(errno));
260 	return NULL;
261     }
262     nextpathptr = strrcpy(nextpathptr, "../");
263 
264     /* Descend to root */
265     for (;;) {
266 
267 	/* look if we found root yet */
268 	if (st_cur.st_ino == st_root.st_ino &&
269 	    DEV_DEV_COMPARE(st_cur.st_dev, st_root.st_dev)) {
270 	    (void)strcpy(pathname, *pathptr != '/' ? "/" : pathptr);
271 	    return pathname;
272 	}
273 
274 	/* open the parent directory */
275 	if (stat(nextpathptr, &st_dotdot) == -1) {
276 	    (void)sprintf(pathname,
277 			    "getwd: Cannot stat directory \"%s\" (%s)",
278 			    nextpathptr, strerror(errno));
279 	    return NULL;
280 	}
281 	if ((dp = opendir(nextpathptr)) == NULL) {
282 	    (void)sprintf(pathname,
283 			    "getwd: Cannot open directory \"%s\" (%s)",
284 			    nextpathptr, strerror(errno));
285 	    return NULL;
286 	}
287 
288 	/* look in the parent for the entry with the same inode */
289 	if (DEV_DEV_COMPARE(st_dotdot.st_dev, st_cur.st_dev)) {
290 	    /* Parent has same device. No need to stat every member */
291 	    for (d = readdir(dp); d != NULL; d = readdir(dp))
292 		if (d->d_fileno == st_cur.st_ino)
293 		    break;
294 	} else {
295 	    /*
296 	     * Parent has a different device. This is a mount point so we
297 	     * need to stat every member
298 	     */
299 	    for (d = readdir(dp); d != NULL; d = readdir(dp)) {
300 		if (ISDOT(d->d_name) || ISDOTDOT(d->d_name))
301 		    continue;
302 		(void)strcpy(cur_name_add, d->d_name);
303 		if (lstat(nextpathptr, &st_next) == -1) {
304 		    (void)sprintf(pathname,
305 			"getwd: Cannot stat \"%s\" (%s)",
306 			d->d_name, strerror(errno));
307 		    (void)closedir(dp);
308 		    return NULL;
309 		}
310 		/* check if we found it yet */
311 		if (st_next.st_ino == st_cur.st_ino &&
312 		    DEV_DEV_COMPARE(st_next.st_dev, st_cur.st_dev))
313 		    break;
314 	    }
315 	}
316 	if (d == NULL) {
317 	    (void)sprintf(pathname,
318 		"getwd: Cannot find \".\" in \"..\"");
319 	    (void)closedir(dp);
320 	    return NULL;
321 	}
322 	st_cur = st_dotdot;
323 	pathptr = strrcpy(pathptr, d->d_name);
324 	pathptr = strrcpy(pathptr, "/");
325 	nextpathptr = strrcpy(nextpathptr, "../");
326 	(void)closedir(dp);
327 	*cur_name_add = '\0';
328     }
329 } /* end getwd */
330 
331 #endif /* __hpux */
332 
333 #if !defined(HAVE_GETCWD)
334 char *
335 getcwd(path, sz)
336      char *path;
337      int sz;
338 {
339 	return getwd(path);
340 }
341 #endif
342 
343 /* force posix signals */
344 SignalProc
345 bmake_signal(int s, SignalProc a)
346 {
347 	struct sigaction sa, osa;
348 
349 	sa.sa_handler = a;
350 	sigemptyset(&sa.sa_mask);
351 	sa.sa_flags = SA_RESTART;
352 
353 	if (sigaction(s, &sa, &osa) == -1)
354 		return SIG_ERR;
355 	else
356 		return osa.sa_handler;
357 }
358 
359 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_VASPRINTF)
360 #include <stdarg.h>
361 #endif
362 
363 #if !defined(HAVE_VSNPRINTF)
364 #if !defined(__osf__)
365 #ifdef _IOSTRG
366 #define STRFLAG	(_IOSTRG|_IOWRT)	/* no _IOWRT: avoid stdio bug */
367 #else
368 #if 0
369 #define STRFLAG	(_IOREAD)		/* XXX: Assume svr4 stdio */
370 #endif
371 #endif /* _IOSTRG */
372 #endif /* __osf__ */
373 
374 int
375 vsnprintf(char *s, size_t n, const char *fmt, va_list args)
376 {
377 #ifdef STRFLAG
378 	FILE fakebuf;
379 
380 	fakebuf._flag = STRFLAG;
381 	/*
382 	 * Some os's are char * _ptr, others are unsigned char *_ptr...
383 	 * We cast to void * to make everyone happy.
384 	 */
385 	fakebuf._ptr = (void *)s;
386 	fakebuf._cnt = n - 1;
387 	fakebuf._file = -1;
388 	_doprnt(fmt, args, &fakebuf);
389 	fakebuf._cnt++;
390 	putc('\0', &fakebuf);
391 	if (fakebuf._cnt < 0)
392 	    fakebuf._cnt = 0;
393 	return n - fakebuf._cnt - 1;
394 #else
395 #ifndef _PATH_DEVNULL
396 # define _PATH_DEVNULL "/dev/null"
397 #endif
398 	/*
399 	 * Rats... we don't want to clobber anything...
400 	 * do a printf to /dev/null to see how much space we need.
401 	 */
402 	static FILE *nullfp;
403 	int need = 0;			/* XXX what's a useful error return? */
404 
405 	if (!nullfp)
406 		nullfp = fopen(_PATH_DEVNULL, "w");
407 	if (nullfp) {
408 		need = vfprintf(nullfp, fmt, args);
409 		if (need < n)
410 			(void)vsprintf(s, fmt, args);
411 	}
412 	return need;
413 #endif
414 }
415 #endif
416 
417 #if !defined(HAVE_SNPRINTF)
418 int
419 snprintf(char *s, size_t n, const char *fmt, ...)
420 {
421 	va_list ap;
422 	int rv;
423 
424 	va_start(ap, fmt);
425 	rv = vsnprintf(s, n, fmt, ap);
426 	va_end(ap);
427 	return rv;
428 }
429 #endif
430 
431 #if !defined(HAVE_STRFTIME)
432 size_t
433 strftime(char *buf, size_t len, const char *fmt, const struct tm *tm)
434 {
435 	static char months[][4] = {
436 		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
437 		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
438 	};
439 
440 	size_t s;
441 	char *b = buf;
442 
443 	while (*fmt) {
444 		if (len == 0)
445 			return buf - b;
446 		if (*fmt != '%') {
447 			*buf++ = *fmt++;
448 			len--;
449 			continue;
450 		}
451 		switch (*fmt++) {
452 		case '%':
453 			*buf++ = '%';
454 			len--;
455 			if (len == 0) return buf - b;
456 			/*FALLTHROUGH*/
457 		case '\0':
458 			*buf = '%';
459 			s = 1;
460 			break;
461 		case 'k':
462 			s = snprintf(buf, len, "%d", tm->tm_hour);
463 			break;
464 		case 'M':
465 			s = snprintf(buf, len, "%02d", tm->tm_min);
466 			break;
467 		case 'S':
468 			s = snprintf(buf, len, "%02d", tm->tm_sec);
469 			break;
470 		case 'b':
471 			if (tm->tm_mon >= 12)
472 				return buf - b;
473 			s = snprintf(buf, len, "%s", months[tm->tm_mon]);
474 			break;
475 		case 'd':
476 			s = snprintf(buf, len, "%02d", tm->tm_mday);
477 			break;
478 		case 'Y':
479 			s = snprintf(buf, len, "%d", 1900 + tm->tm_year);
480 			break;
481 		default:
482 			s = snprintf(buf, len, "Unsupported format %c",
483 			    fmt[-1]);
484 			break;
485 		}
486 		buf += s;
487 		len -= s;
488 	}
489 	return buf - b;
490 }
491 #endif
492 
493 #if !defined(HAVE_KILLPG)
494 #if !defined(__hpux__) && !defined(__hpux)
495 int
496 killpg(int pid, int sig)
497 {
498     return kill(-pid, sig);
499 }
500 #endif
501 #endif
502 
503 #if !defined(HAVE_WARNX)
504 static void
505 vwarnx(const char *fmt, va_list args)
506 {
507 	fprintf(stderr, "%s: ", progname);
508 	if ((fmt)) {
509 		vfprintf(stderr, fmt, args);
510 		fprintf(stderr, ": ");
511 	}
512 }
513 #endif
514 
515 #if !defined(HAVE_WARN)
516 static void
517 vwarn(const char *fmt, va_list args)
518 {
519 	vwarnx(fmt, args);
520 	fprintf(stderr, "%s\n", strerror(errno));
521 }
522 #endif
523 
524 #if !defined(HAVE_ERR)
525 static void
526 verr(int eval, const char *fmt, va_list args)
527 {
528 	vwarn(fmt, args);
529 	exit(eval);
530 }
531 #endif
532 
533 #if !defined(HAVE_ERRX)
534 static void
535 verrx(int eval, const char *fmt, va_list args)
536 {
537 	vwarnx(fmt, args);
538 	exit(eval);
539 }
540 #endif
541 
542 #if !defined(HAVE_ERR)
543 void
544 err(int eval, const char *fmt, ...)
545 {
546         va_list ap;
547 
548         va_start(ap, fmt);
549         verr(eval, fmt, ap);
550         va_end(ap);
551 }
552 #endif
553 
554 #if !defined(HAVE_ERRX)
555 void
556 errx(int eval, const char *fmt, ...)
557 {
558         va_list ap;
559 
560         va_start(ap, fmt);
561         verrx(eval, fmt, ap);
562         va_end(ap);
563 }
564 #endif
565 
566 #if !defined(HAVE_WARN)
567 void
568 warn(const char *fmt, ...)
569 {
570         va_list ap;
571 
572         va_start(ap, fmt);
573         vwarn(fmt, ap);
574         va_end(ap);
575 }
576 #endif
577 
578 #if !defined(HAVE_WARNX)
579 void
580 warnx(const char *fmt, ...)
581 {
582         va_list ap;
583 
584         va_start(ap, fmt);
585         vwarnx(fmt, ap);
586         va_end(ap);
587 }
588 #endif
589