9348584c46f870b8e131fcd575d3ebdb4a1b91fc
[pkgsrcv2.git] / devel / bmake / files / util.c
1 /*      $NetBSD: util.c,v 1.6 2010/04/20 13:37:49 joerg Exp $   */
2
3 /*
4  * Missing stuff from OS's
5  *
6  *      $Id: util.c,v 1.7 2010/05/13 18:43:08 joerg Exp $
7  */
8
9 #include "make.h"
10
11 #ifndef MAKE_NATIVE
12 static char rcsid[] = "$NetBSD: util.c,v 1.6 2010/04/20 13:37:49 joerg Exp $";
13 #else
14 #ifndef lint
15 __RCSID("$NetBSD: util.c,v 1.6 2010/04/20 13:37:49 joerg Exp $");
16 #endif
17 #endif
18
19 #include <errno.h>
20 #include <time.h>
21
22 #if !defined(HAVE_STRERROR)
23 extern int errno, sys_nerr;
24 extern char *sys_errlist[];
25
26 char *
27 strerror(int e)
28 {
29     static char buf[100];
30     if (e < 0 || e >= sys_nerr) {
31         snprintf(buf, sizeof(buf), "Unknown error %d", e);
32         return buf;
33     }
34     else
35         return sys_errlist[e];
36 }
37 #endif
38
39 #if !defined(HAVE_SETENV) || !defined(HAVE_UNSETENV)
40 extern char **environ;
41
42 static char *
43 findenv(const char *name, int *offset)
44 {
45         size_t i, len;
46         char *p, *q;
47
48         for (i = 0; (q = environ[i]); i++) {
49                 char *p = strchr(q, '=');
50                 if (p == NULL)
51                         continue;
52                 if (strncmp(name, q, len = p - q) == 0) {
53                         *offset = i;
54                         return q + len + 1;
55                 }
56         }
57         *offset = i;
58         return NULL;
59 }
60 #endif
61
62 #if !defined(HAVE_UNSETENV)
63 int
64 unsetenv(const char *name)
65 {
66         char **p;
67         int offset;
68
69         if (name == NULL || *name == '\0' || strchr(name, '=') != NULL) {
70                 errno = EINVAL;
71                 return -1;
72         }
73
74         while (findenv(name, &offset))  { /* if set multiple times */
75                 for (p = &environ[offset];; ++p)
76                         if (!(*p = *(p + 1)))
77                                 break;
78         }
79         return 0;
80 }
81 #endif
82
83 #if !defined(HAVE_SETENV)
84 int
85 setenv(const char *name, const char *value, int rewrite)
86 {
87         static char **saveenv;  /* copy of previously allocated space */
88         char *c, **newenv;
89         const char *cc;
90         size_t l_value, size;
91         int offset;
92
93         if (name == NULL || value == NULL) {
94                 errno = EINVAL;
95                 return -1;
96         }
97
98         if (*value == '=')                      /* no `=' in value */
99                 ++value;
100         l_value = strlen(value);
101
102         /* find if already exists */
103         if ((c = findenv(name, &offset))) {
104                 if (!rewrite)
105                         return 0;
106                 if (strlen(c) >= l_value)       /* old larger; copy over */
107                         goto copy;
108         } else {                                        /* create new slot */
109                 size = sizeof(char *) * (offset + 2);
110                 if (saveenv == environ) {               /* just increase size */
111                         if ((newenv = realloc(saveenv, size)) == NULL)
112                                 return -1;
113                         saveenv = newenv;
114                 } else {                                /* get new space */
115                         /*
116                          * We don't free here because we don't know if
117                          * the first allocation is valid on all OS's
118                          */
119                         if ((saveenv = malloc(size)) == NULL)
120                                 return -1;
121                         (void)memcpy(saveenv, environ, size - sizeof(char *));
122                 }
123                 environ = saveenv;
124                 environ[offset + 1] = NULL;
125         }
126         for (cc = name; *cc && *cc != '='; ++cc)        /* no `=' in name */
127                 continue;
128         size = cc - name;
129         /* name + `=' + value */
130         if ((environ[offset] = malloc(size + l_value + 2)) == NULL)
131                 return -1;
132         c = environ[offset];
133         (void)memcpy(c, name, size);
134         c += size;
135         *c++ = '=';
136 copy:
137         (void)memcpy(c, value, l_value + 1);
138         return 0;
139 }
140
141 #ifdef TEST
142 int
143 main(int argc, char *argv[])
144 {
145         setenv(argv[1], argv[2], 0);
146         printf("%s\n", getenv(argv[1]));
147         unsetenv(argv[1]);
148         printf("%s\n", getenv(argv[1]));
149         return 0;
150 }
151 #endif
152
153 #endif
154
155
156 #if defined(__hpux__) || defined(__hpux)
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)
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(__hpux__) && !defined(__hpux)
225 void
226 srandom(long seed)
227 {
228     srand48(seed);
229 }
230
231 long
232 random(void)
233 {
234     return lrand48();
235 }
236 #endif
237
238 /* turn into bsd signals */
239 void (*
240 signal(int s, void (*a)(int)))(int)
241 {
242     struct sigvec osv, sv;
243
244     (void)sigvector(s, NULL, &osv);
245     sv = osv;
246     sv.sv_handler = a;
247 #ifdef SV_BSDSIG
248     sv.sv_flags = SV_BSDSIG;
249 #endif
250
251     if (sigvector(s, &sv, NULL) == -1)
252         return (BADSIG);
253     return (osv.sv_handler);
254 }
255
256 #if !defined(__hpux__) && !defined(__hpux)
257 int
258 utimes(char *file, struct timeval tvp[2])
259 {
260     struct utimbuf t;
261
262     t.actime  = tvp[0].tv_sec;
263     t.modtime = tvp[1].tv_sec;
264     return(utime(file, &t));
265 }
266 #endif
267
268 #if !defined(BSD) && !defined(d_fileno)
269 # define d_fileno d_ino
270 #endif
271
272 #ifndef DEV_DEV_COMPARE
273 # define DEV_DEV_COMPARE(a, b) ((a) == (b))
274 #endif
275 #define ISDOT(c) ((c)[0] == '.' && (((c)[1] == '\0') || ((c)[1] == '/')))
276 #define ISDOTDOT(c) ((c)[0] == '.' && ISDOT(&((c)[1])))
277
278 char *
279 getwd(char *pathname)
280 {
281     DIR    *dp;
282     struct dirent *d;
283     extern int errno;
284
285     struct stat st_root, st_cur, st_next, st_dotdot;
286     char    pathbuf[MAXPATHLEN], nextpathbuf[MAXPATHLEN * 2];
287     char   *pathptr, *nextpathptr, *cur_name_add;
288
289     /* find the inode of root */
290     if (stat("/", &st_root) == -1) {
291         (void)sprintf(pathname,
292                         "getwd: Cannot stat \"/\" (%s)", strerror(errno));
293         return NULL;
294     }
295     pathbuf[MAXPATHLEN - 1] = '\0';
296     pathptr = &pathbuf[MAXPATHLEN - 1];
297     nextpathbuf[MAXPATHLEN - 1] = '\0';
298     cur_name_add = nextpathptr = &nextpathbuf[MAXPATHLEN - 1];
299
300     /* find the inode of the current directory */
301     if (lstat(".", &st_cur) == -1) {
302         (void)sprintf(pathname,
303                         "getwd: Cannot stat \".\" (%s)", strerror(errno));
304         return NULL;
305     }
306     nextpathptr = strrcpy(nextpathptr, "../");
307
308     /* Descend to root */
309     for (;;) {
310
311         /* look if we found root yet */
312         if (st_cur.st_ino == st_root.st_ino &&
313             DEV_DEV_COMPARE(st_cur.st_dev, st_root.st_dev)) {
314             (void)strcpy(pathname, *pathptr != '/' ? "/" : pathptr);
315             return (pathname);
316         }
317
318         /* open the parent directory */
319         if (stat(nextpathptr, &st_dotdot) == -1) {
320             (void)sprintf(pathname,
321                             "getwd: Cannot stat directory \"%s\" (%s)",
322                             nextpathptr, strerror(errno));
323             return NULL;
324         }
325         if ((dp = opendir(nextpathptr)) == NULL) {
326             (void)sprintf(pathname,
327                             "getwd: Cannot open directory \"%s\" (%s)",
328                             nextpathptr, strerror(errno));
329             return NULL;
330         }
331
332         /* look in the parent for the entry with the same inode */
333         if (DEV_DEV_COMPARE(st_dotdot.st_dev, st_cur.st_dev)) {
334             /* Parent has same device. No need to stat every member */
335             for (d = readdir(dp); d != NULL; d = readdir(dp))
336                 if (d->d_fileno == st_cur.st_ino)
337                     break;
338         }
339         else {
340             /*
341              * Parent has a different device. This is a mount point so we
342              * need to stat every member
343              */
344             for (d = readdir(dp); d != NULL; d = readdir(dp)) {
345                 if (ISDOT(d->d_name) || ISDOTDOT(d->d_name))
346                     continue;
347                 (void)strcpy(cur_name_add, d->d_name);
348                 if (lstat(nextpathptr, &st_next) == -1) {
349                     (void)sprintf(pathname,
350                         "getwd: Cannot stat \"%s\" (%s)",
351                         d->d_name, strerror(errno));
352                     (void)closedir(dp);
353                     return NULL;
354                 }
355                 /* check if we found it yet */
356                 if (st_next.st_ino == st_cur.st_ino &&
357                     DEV_DEV_COMPARE(st_next.st_dev, st_cur.st_dev))
358                     break;
359             }
360         }
361         if (d == NULL) {
362             (void)sprintf(pathname,
363                 "getwd: Cannot find \".\" in \"..\"");
364             (void)closedir(dp);
365             return NULL;
366         }
367         st_cur = st_dotdot;
368         pathptr = strrcpy(pathptr, d->d_name);
369         pathptr = strrcpy(pathptr, "/");
370         nextpathptr = strrcpy(nextpathptr, "../");
371         (void)closedir(dp);
372         *cur_name_add = '\0';
373     }
374 } /* end getwd */
375
376 #endif /* __hpux */
377
378 #if !defined(HAVE_GETCWD)
379 char *
380 getcwd(path, sz)
381      char *path;
382      int sz;
383 {
384         return getwd(path);
385 }
386 #endif
387
388 #if !defined(FORCE_POSIX_SIGNALS)
389 /*
390  * If FORCE_POSIX_SIGNALS is defined
391  * then sigcompat will have done this.
392  */
393 #if defined(sun) && (defined(__svr4__) || defined(__SVR4))
394 #include <signal.h>
395
396 /* turn into bsd signals */
397 void (*
398 signal(int s, void (*a)(int)))(int)
399 {
400     struct sigaction sa, osa;
401
402     sa.sa_handler = a;
403     sigemptyset(&sa.sa_mask);
404     sa.sa_flags = SA_RESTART;
405
406     if (sigaction(s, &sa, &osa) == -1)
407         return SIG_ERR;
408     else
409         return osa.sa_handler;
410 }
411 #endif
412 #endif
413
414 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_VASPRINTF)
415 #include <stdarg.h>
416 #endif
417
418 #if !defined(HAVE_VSNPRINTF)
419 #if !defined(__osf__)
420 #ifdef _IOSTRG
421 #define STRFLAG (_IOSTRG|_IOWRT)        /* no _IOWRT: avoid stdio bug */
422 #else
423 #if 0
424 #define STRFLAG (_IOREAD)               /* XXX: Assume svr4 stdio */
425 #endif
426 #endif /* _IOSTRG */
427 #endif /* __osf__ */
428
429 int
430 vsnprintf(char *s, size_t n, const char *fmt, va_list args)
431 {
432 #ifdef STRFLAG
433         FILE fakebuf;
434
435         fakebuf._flag = STRFLAG;
436         /*
437          * Some os's are char * _ptr, others are unsigned char *_ptr...
438          * We cast to void * to make everyone happy.
439          */
440         fakebuf._ptr = (void *)s;
441         fakebuf._cnt = n-1;
442         fakebuf._file = -1;
443         _doprnt(fmt, args, &fakebuf);
444         fakebuf._cnt++;
445         putc('\0', &fakebuf);
446         if (fakebuf._cnt<0)
447             fakebuf._cnt = 0;
448         return (n-fakebuf._cnt-1);
449 #else
450 #ifndef _PATH_DEVNULL
451 # define _PATH_DEVNULL "/dev/null"
452 #endif
453         /*
454          * Rats... we don't want to clobber anything...
455          * do a printf to /dev/null to see how much space we need.
456          */
457         static FILE *nullfp;
458         int need = 0;                   /* XXX what's a useful error return? */
459
460         if (!nullfp)
461                 nullfp = fopen(_PATH_DEVNULL, "w");
462         if (nullfp) {
463                 need = vfprintf(nullfp, fmt, args);
464                 if (need < n)
465                         (void)vsprintf(s, fmt, args);
466         }
467         return need;
468 #endif
469 }
470 #endif
471
472 #if !defined(HAVE_SNPRINTF)
473 int
474 snprintf(char *s, size_t n, const char *fmt, ...)
475 {
476         va_list ap;
477         int rv;
478
479         va_start(ap, fmt);
480         rv = vsnprintf(s, n, fmt, ap);
481         va_end(ap);
482         return rv;
483 }
484 #endif
485                 
486 #if !defined(HAVE_STRFTIME)
487 size_t
488 strftime(char *buf, size_t len, const char *fmt, const struct tm *tm)
489 {
490         static char months[][4] = {
491                 "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
492                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
493         };
494
495         size_t s;
496         char *b = buf;
497
498         while (*fmt) {
499                 if (len == 0)
500                         return buf - b;
501                 if (*fmt != '%') {
502                         *buf++ = *fmt++;
503                         len--;
504                         continue;
505                 }
506                 switch (*fmt++) {
507                 case '%':
508                         *buf++ = '%';
509                         len--;
510                         if (len == 0) return buf - b;
511                         /*FALLTHROUGH*/
512                 case '\0':
513                         *buf = '%';
514                         s = 1;
515                         break;
516                 case 'k':
517                         s = snprintf(buf, len, "%d", tm->tm_hour);
518                         break;
519                 case 'M':
520                         s = snprintf(buf, len, "%02d", tm->tm_min);
521                         break;
522                 case 'S':
523                         s = snprintf(buf, len, "%02d", tm->tm_sec);
524                         break;
525                 case 'b':
526                         if (tm->tm_mon >= 12)
527                                 return buf - b;
528                         s = snprintf(buf, len, "%s", months[tm->tm_mon]);
529                         break;
530                 case 'd':
531                         s = snprintf(buf, len, "%02d", tm->tm_mday);
532                         break;
533                 case 'Y':
534                         s = snprintf(buf, len, "%d", 1900 + tm->tm_year);
535                         break;
536                 default:
537                         s = snprintf(buf, len, "Unsupported format %c",
538                             fmt[-1]);
539                         break;
540                 }
541                 buf += s;
542                 len -= s;
543         }
544 }
545 #endif
546
547 #if !defined(HAVE_KILLPG)
548 #if !defined(__hpux__) && !defined(__hpux)
549 int
550 killpg(int pid, int sig)
551 {
552     return kill(-pid, sig);
553 }
554 #endif
555 #endif