]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bmake/util.c
sysctl(9): Fix a few mandoc related issues
[FreeBSD/FreeBSD.git] / contrib / bmake / util.c
1 /*      $NetBSD: util.c,v 1.68 2020/11/16 18:29:49 rillig Exp $ */
2
3 /*
4  * Missing stuff from OS's
5  *
6  *      $Id: util.c,v 1.41 2020/11/18 03:58:32 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.68 2020/11/16 18:29:49 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 /* strrcpy():
157  *      Like strcpy, going backwards and returning the new pointer
158  */
159 static char *
160 strrcpy(char *ptr, char *str)
161 {
162     int len = strlen(str);
163
164     while (len)
165         *--ptr = str[--len];
166
167     return ptr;
168 } /* end strrcpy */
169
170
171 char    *sys_siglist[] = {
172         "Signal 0",
173         "Hangup",                       /* SIGHUP    */
174         "Interrupt",                    /* SIGINT    */
175         "Quit",                         /* SIGQUIT   */
176         "Illegal instruction",          /* SIGILL    */
177         "Trace/BPT trap",               /* SIGTRAP   */
178         "IOT trap",                     /* SIGIOT    */
179         "EMT trap",                     /* SIGEMT    */
180         "Floating point exception",     /* SIGFPE    */
181         "Killed",                       /* SIGKILL   */
182         "Bus error",                    /* SIGBUS    */
183         "Segmentation fault",           /* SIGSEGV   */
184         "Bad system call",              /* SIGSYS    */
185         "Broken pipe",                  /* SIGPIPE   */
186         "Alarm clock",                  /* SIGALRM   */
187         "Terminated",                   /* SIGTERM   */
188         "User defined signal 1",        /* SIGUSR1   */
189         "User defined signal 2",        /* SIGUSR2   */
190         "Child exited",                 /* SIGCLD    */
191         "Power-fail restart",           /* SIGPWR    */
192         "Virtual timer expired",        /* SIGVTALRM */
193         "Profiling timer expired",      /* SIGPROF   */
194         "I/O possible",                 /* SIGIO     */
195         "Window size changes",          /* SIGWINDOW */
196         "Stopped (signal)",             /* SIGSTOP   */
197         "Stopped",                      /* SIGTSTP   */
198         "Continued",                    /* SIGCONT   */
199         "Stopped (tty input)",          /* SIGTTIN   */
200         "Stopped (tty output)",         /* SIGTTOU   */
201         "Urgent I/O condition",         /* SIGURG    */
202         "Remote lock lost (NFS)",       /* SIGLOST   */
203         "Signal 31",                    /* reserved  */
204         "DIL signal"                    /* SIGDIL    */
205 };
206 #endif /* __hpux__ || __hpux */
207
208 #if defined(__hpux__) || defined(__hpux)
209 #include <sys/types.h>
210 #include <sys/syscall.h>
211 #include <sys/signal.h>
212 #include <sys/stat.h>
213 #include <dirent.h>
214 #include <sys/time.h>
215 #include <unistd.h>
216
217 int
218 killpg(int pid, int sig)
219 {
220     return kill(-pid, sig);
221 }
222
223 #if !defined(BSD) && !defined(d_fileno)
224 # define d_fileno d_ino
225 #endif
226
227 #ifndef DEV_DEV_COMPARE
228 # define DEV_DEV_COMPARE(a, b) ((a) == (b))
229 #endif
230 #define ISDOT(c) ((c)[0] == '.' && (((c)[1] == '\0') || ((c)[1] == '/')))
231 #define ISDOTDOT(c) ((c)[0] == '.' && ISDOT(&((c)[1])))
232
233 char *
234 getwd(char *pathname)
235 {
236     DIR    *dp;
237     struct dirent *d;
238     extern int errno;
239
240     struct stat st_root, st_cur, st_next, st_dotdot;
241     char    pathbuf[MAXPATHLEN], nextpathbuf[MAXPATHLEN * 2];
242     char   *pathptr, *nextpathptr, *cur_name_add;
243
244     /* find the inode of root */
245     if (stat("/", &st_root) == -1) {
246         (void)sprintf(pathname,
247                         "getwd: Cannot stat \"/\" (%s)", strerror(errno));
248         return NULL;
249     }
250     pathbuf[MAXPATHLEN - 1] = '\0';
251     pathptr = &pathbuf[MAXPATHLEN - 1];
252     nextpathbuf[MAXPATHLEN - 1] = '\0';
253     cur_name_add = nextpathptr = &nextpathbuf[MAXPATHLEN - 1];
254
255     /* find the inode of the current directory */
256     if (lstat(".", &st_cur) == -1) {
257         (void)sprintf(pathname,
258                         "getwd: Cannot stat \".\" (%s)", strerror(errno));
259         return NULL;
260     }
261     nextpathptr = strrcpy(nextpathptr, "../");
262
263     /* Descend to root */
264     for (;;) {
265
266         /* look if we found root yet */
267         if (st_cur.st_ino == st_root.st_ino &&
268             DEV_DEV_COMPARE(st_cur.st_dev, st_root.st_dev)) {
269             (void)strcpy(pathname, *pathptr != '/' ? "/" : pathptr);
270             return pathname;
271         }
272
273         /* open the parent directory */
274         if (stat(nextpathptr, &st_dotdot) == -1) {
275             (void)sprintf(pathname,
276                             "getwd: Cannot stat directory \"%s\" (%s)",
277                             nextpathptr, strerror(errno));
278             return NULL;
279         }
280         if ((dp = opendir(nextpathptr)) == NULL) {
281             (void)sprintf(pathname,
282                             "getwd: Cannot open directory \"%s\" (%s)",
283                             nextpathptr, strerror(errno));
284             return NULL;
285         }
286
287         /* look in the parent for the entry with the same inode */
288         if (DEV_DEV_COMPARE(st_dotdot.st_dev, st_cur.st_dev)) {
289             /* Parent has same device. No need to stat every member */
290             for (d = readdir(dp); d != NULL; d = readdir(dp))
291                 if (d->d_fileno == st_cur.st_ino)
292                     break;
293         } else {
294             /*
295              * Parent has a different device. This is a mount point so we
296              * need to stat every member
297              */
298             for (d = readdir(dp); d != NULL; d = readdir(dp)) {
299                 if (ISDOT(d->d_name) || ISDOTDOT(d->d_name))
300                     continue;
301                 (void)strcpy(cur_name_add, d->d_name);
302                 if (lstat(nextpathptr, &st_next) == -1) {
303                     (void)sprintf(pathname,
304                         "getwd: Cannot stat \"%s\" (%s)",
305                         d->d_name, strerror(errno));
306                     (void)closedir(dp);
307                     return NULL;
308                 }
309                 /* check if we found it yet */
310                 if (st_next.st_ino == st_cur.st_ino &&
311                     DEV_DEV_COMPARE(st_next.st_dev, st_cur.st_dev))
312                     break;
313             }
314         }
315         if (d == NULL) {
316             (void)sprintf(pathname,
317                 "getwd: Cannot find \".\" in \"..\"");
318             (void)closedir(dp);
319             return NULL;
320         }
321         st_cur = st_dotdot;
322         pathptr = strrcpy(pathptr, d->d_name);
323         pathptr = strrcpy(pathptr, "/");
324         nextpathptr = strrcpy(nextpathptr, "../");
325         (void)closedir(dp);
326         *cur_name_add = '\0';
327     }
328 } /* end getwd */
329
330 #endif /* __hpux */
331
332 #if !defined(HAVE_GETCWD)
333 char *
334 getcwd(path, sz)
335      char *path;
336      int sz;
337 {
338         return getwd(path);
339 }
340 #endif
341
342 /* force posix signals */
343 SignalProc
344 bmake_signal(int s, SignalProc a)
345 {
346     struct sigaction sa, osa;
347
348     sa.sa_handler = a;
349     sigemptyset(&sa.sa_mask);
350     sa.sa_flags = SA_RESTART;
351
352     if (sigaction(s, &sa, &osa) == -1)
353         return SIG_ERR;
354     else
355         return osa.sa_handler;
356 }
357
358 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_VASPRINTF)
359 #include <stdarg.h>
360 #endif
361
362 #if !defined(HAVE_VSNPRINTF)
363 #if !defined(__osf__)
364 #ifdef _IOSTRG
365 #define STRFLAG (_IOSTRG|_IOWRT)        /* no _IOWRT: avoid stdio bug */
366 #else
367 #if 0
368 #define STRFLAG (_IOREAD)               /* XXX: Assume svr4 stdio */
369 #endif
370 #endif /* _IOSTRG */
371 #endif /* __osf__ */
372
373 int
374 vsnprintf(char *s, size_t n, const char *fmt, va_list args)
375 {
376 #ifdef STRFLAG
377         FILE fakebuf;
378
379         fakebuf._flag = STRFLAG;
380         /*
381          * Some os's are char * _ptr, others are unsigned char *_ptr...
382          * We cast to void * to make everyone happy.
383          */
384         fakebuf._ptr = (void *)s;
385         fakebuf._cnt = n - 1;
386         fakebuf._file = -1;
387         _doprnt(fmt, args, &fakebuf);
388         fakebuf._cnt++;
389         putc('\0', &fakebuf);
390         if (fakebuf._cnt < 0)
391             fakebuf._cnt = 0;
392         return n - fakebuf._cnt - 1;
393 #else
394 #ifndef _PATH_DEVNULL
395 # define _PATH_DEVNULL "/dev/null"
396 #endif
397         /*
398          * Rats... we don't want to clobber anything...
399          * do a printf to /dev/null to see how much space we need.
400          */
401         static FILE *nullfp;
402         int need = 0;                   /* XXX what's a useful error return? */
403
404         if (!nullfp)
405                 nullfp = fopen(_PATH_DEVNULL, "w");
406         if (nullfp) {
407                 need = vfprintf(nullfp, fmt, args);
408                 if (need < n)
409                         (void)vsprintf(s, fmt, args);
410         }
411         return need;
412 #endif
413 }
414 #endif
415
416 #if !defined(HAVE_SNPRINTF)
417 int
418 snprintf(char *s, size_t n, const char *fmt, ...)
419 {
420         va_list ap;
421         int rv;
422
423         va_start(ap, fmt);
424         rv = vsnprintf(s, n, fmt, ap);
425         va_end(ap);
426         return rv;
427 }
428 #endif
429                 
430 #if !defined(HAVE_STRFTIME)
431 size_t
432 strftime(char *buf, size_t len, const char *fmt, const struct tm *tm)
433 {
434         static char months[][4] = {
435                 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
436                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
437         };
438
439         size_t s;
440         char *b = buf;
441
442         while (*fmt) {
443                 if (len == 0)
444                         return buf - b;
445                 if (*fmt != '%') {
446                         *buf++ = *fmt++;
447                         len--;
448                         continue;
449                 }
450                 switch (*fmt++) {
451                 case '%':
452                         *buf++ = '%';
453                         len--;
454                         if (len == 0) return buf - b;
455                         /*FALLTHROUGH*/
456                 case '\0':
457                         *buf = '%';
458                         s = 1;
459                         break;
460                 case 'k':
461                         s = snprintf(buf, len, "%d", tm->tm_hour);
462                         break;
463                 case 'M':
464                         s = snprintf(buf, len, "%02d", tm->tm_min);
465                         break;
466                 case 'S':
467                         s = snprintf(buf, len, "%02d", tm->tm_sec);
468                         break;
469                 case 'b':
470                         if (tm->tm_mon >= 12)
471                                 return buf - b;
472                         s = snprintf(buf, len, "%s", months[tm->tm_mon]);
473                         break;
474                 case 'd':
475                         s = snprintf(buf, len, "%02d", tm->tm_mday);
476                         break;
477                 case 'Y':
478                         s = snprintf(buf, len, "%d", 1900 + tm->tm_year);
479                         break;
480                 default:
481                         s = snprintf(buf, len, "Unsupported format %c",
482                             fmt[-1]);
483                         break;
484                 }
485                 buf += s;
486                 len -= s;
487         }
488         return buf - b;
489 }
490 #endif
491
492 #if !defined(HAVE_KILLPG)
493 #if !defined(__hpux__) && !defined(__hpux)
494 int
495 killpg(int pid, int sig)
496 {
497     return kill(-pid, sig);
498 }
499 #endif
500 #endif
501
502 #if !defined(HAVE_WARNX)
503 static void
504 vwarnx(const char *fmt, va_list args)
505 {
506         fprintf(stderr, "%s: ", progname);
507         if ((fmt)) {
508                 vfprintf(stderr, fmt, args);
509                 fprintf(stderr, ": ");
510         }
511 }
512 #endif
513
514 #if !defined(HAVE_WARN)
515 static void
516 vwarn(const char *fmt, va_list args)
517 {
518         vwarnx(fmt, args);
519         fprintf(stderr, "%s\n", strerror(errno));
520 }
521 #endif
522
523 #if !defined(HAVE_ERR)
524 static void
525 verr(int eval, const char *fmt, va_list args)
526 {
527         vwarn(fmt, args);
528         exit(eval);
529 }
530 #endif
531
532 #if !defined(HAVE_ERRX)
533 static void
534 verrx(int eval, const char *fmt, va_list args)
535 {
536         vwarnx(fmt, args);
537         exit(eval);
538 }
539 #endif
540
541 #if !defined(HAVE_ERR)
542 void
543 err(int eval, const char *fmt, ...)
544 {
545         va_list ap;
546
547         va_start(ap, fmt);
548         verr(eval, fmt, ap);
549         va_end(ap);
550 }
551 #endif
552
553 #if !defined(HAVE_ERRX)
554 void
555 errx(int eval, const char *fmt, ...)
556 {
557         va_list ap;
558
559         va_start(ap, fmt);
560         verrx(eval, fmt, ap);
561         va_end(ap);
562 }
563 #endif
564
565 #if !defined(HAVE_WARN)
566 void
567 warn(const char *fmt, ...)
568 {
569         va_list ap;
570
571         va_start(ap, fmt);
572         vwarn(fmt, ap);
573         va_end(ap);
574 }
575 #endif
576
577 #if !defined(HAVE_WARNX)
578 void
579 warnx(const char *fmt, ...)
580 {
581         va_list ap;
582
583         va_start(ap, fmt);
584         vwarnx(fmt, ap);
585         va_end(ap);
586 }
587 #endif