Imported Upstream version 4.0
[platform/upstream/make.git] / misc.c
1 /* Miscellaneous generic support functions for GNU Make.
2 Copyright (C) 1988-2013 Free Software Foundation, Inc.
3 This file is part of GNU Make.
4
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
9
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along with
15 this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include "makeint.h"
18 #include "filedef.h"
19 #include "dep.h"
20 #include "debug.h"
21
22 /* GNU make no longer supports pre-ANSI89 environments.  */
23
24 #include <stdarg.h>
25
26 #ifdef HAVE_FCNTL_H
27 # include <fcntl.h>
28 #else
29 # include <sys/file.h>
30 #endif
31
32 /* Compare strings *S1 and *S2.
33    Return negative if the first is less, positive if it is greater,
34    zero if they are equal.  */
35
36 int
37 alpha_compare (const void *v1, const void *v2)
38 {
39   const char *s1 = *((char **)v1);
40   const char *s2 = *((char **)v2);
41
42   if (*s1 != *s2)
43     return *s1 - *s2;
44   return strcmp (s1, s2);
45 }
46 \f
47 /* Discard each backslash-newline combination from LINE.
48    Backslash-backslash-newline combinations become backslash-newlines.
49    This is done by copying the text at LINE into itself.  */
50
51 void
52 collapse_continuations (char *line)
53 {
54   char *in, *out, *p;
55
56   in = strchr (line, '\n');
57   if (in == 0)
58     return;
59
60   out = in;
61   while (out > line && out[-1] == '\\')
62     --out;
63
64   while (*in != '\0')
65     {
66       /* BS_WRITE gets the number of quoted backslashes at
67          the end just before IN, and BACKSLASH gets nonzero
68          if the next character is quoted.  */
69       unsigned int backslash = 0;
70       unsigned int bs_write = 0;
71       for (p = in - 1; p >= line && *p == '\\'; --p)
72         {
73           if (backslash)
74             ++bs_write;
75           backslash = !backslash;
76
77           /* It should be impossible to go back this far without exiting,
78              but if we do, we can't get the right answer.  */
79           if (in == out - 1)
80             abort ();
81         }
82
83       /* Output the appropriate number of backslashes.  */
84       while (bs_write-- > 0)
85         *out++ = '\\';
86
87       /* Skip the newline.  */
88       ++in;
89
90       if (backslash)
91         {
92           /* Backslash/newline handling:
93              In traditional GNU make all trailing whitespace, consecutive
94              backslash/newlines, and any leading whitespace on the next line
95              is reduced to a single space.
96              In POSIX, each backslash/newline and is replaced by a space.  */
97           in = next_token (in);
98           if (! posix_pedantic)
99             while (out > line && isblank ((unsigned char)out[-1]))
100               --out;
101           *out++ = ' ';
102         }
103       else
104         /* If the newline isn't quoted, put it in the output.  */
105         *out++ = '\n';
106
107       /* Now copy the following line to the output.
108          Stop when we find backslashes followed by a newline.  */
109       while (*in != '\0')
110         if (*in == '\\')
111           {
112             p = in + 1;
113             while (*p == '\\')
114               ++p;
115             if (*p == '\n')
116               {
117                 in = p;
118                 break;
119               }
120             while (in < p)
121               *out++ = *in++;
122           }
123         else
124           *out++ = *in++;
125     }
126
127   *out = '\0';
128 }
129 \f
130 /* Print N spaces (used in debug for target-depth).  */
131
132 void
133 print_spaces (unsigned int n)
134 {
135   while (n-- > 0)
136     putchar (' ');
137 }
138
139 \f
140 /* Return a string whose contents concatenate the NUM strings provided
141    This string lives in static, re-used memory.  */
142
143 const char *
144 concat (unsigned int num, ...)
145 {
146   static unsigned int rlen = 0;
147   static char *result = NULL;
148   unsigned int ri = 0;
149   va_list args;
150
151   va_start (args, num);
152
153   while (num-- > 0)
154     {
155       const char *s = va_arg (args, const char *);
156       unsigned int l = xstrlen (s);
157
158       if (l == 0)
159         continue;
160
161       if (ri + l > rlen)
162         {
163           rlen = ((rlen ? rlen : 60) + l) * 2;
164           result = xrealloc (result, rlen);
165         }
166
167       memcpy (result + ri, s, l);
168       ri += l;
169     }
170
171   va_end (args);
172
173   /* Get some more memory if we don't have enough space for the
174      terminating '\0'.   */
175   if (ri == rlen)
176     {
177       rlen = (rlen ? rlen : 60) * 2;
178       result = xrealloc (result, rlen);
179     }
180
181   result[ri] = '\0';
182
183   return result;
184 }
185 \f
186
187 #ifndef HAVE_STRERROR
188 #undef  strerror
189 char *
190 strerror (int errnum)
191 {
192   extern int errno, sys_nerr;
193 #ifndef __DECC
194   extern char *sys_errlist[];
195 #endif
196   static char buf[] = "Unknown error 12345678901234567890";
197
198   if (errno < sys_nerr)
199     return sys_errlist[errnum];
200
201   sprintf (buf, _("Unknown error %d"), errnum);
202   return buf;
203 }
204 #endif
205 \f
206 /* Like malloc but get fatal error if memory is exhausted.  */
207 /* Don't bother if we're using dmalloc; it provides these for us.  */
208
209 #ifndef HAVE_DMALLOC_H
210
211 #undef xmalloc
212 #undef xcalloc
213 #undef xrealloc
214 #undef xstrdup
215
216 void *
217 xmalloc (unsigned int size)
218 {
219   /* Make sure we don't allocate 0, for pre-ISO implementations.  */
220   void *result = malloc (size ? size : 1);
221   if (result == 0)
222     fatal (NILF, _("virtual memory exhausted"));
223   return result;
224 }
225
226
227 void *
228 xcalloc (unsigned int size)
229 {
230   /* Make sure we don't allocate 0, for pre-ISO implementations.  */
231   void *result = calloc (size ? size : 1, 1);
232   if (result == 0)
233     fatal (NILF, _("virtual memory exhausted"));
234   return result;
235 }
236
237
238 void *
239 xrealloc (void *ptr, unsigned int size)
240 {
241   void *result;
242
243   /* Some older implementations of realloc() don't conform to ISO.  */
244   if (! size)
245     size = 1;
246   result = ptr ? realloc (ptr, size) : malloc (size);
247   if (result == 0)
248     fatal (NILF, _("virtual memory exhausted"));
249   return result;
250 }
251
252
253 char *
254 xstrdup (const char *ptr)
255 {
256   char *result;
257
258 #ifdef HAVE_STRDUP
259   result = strdup (ptr);
260 #else
261   result = malloc (strlen (ptr) + 1);
262 #endif
263
264   if (result == 0)
265     fatal (NILF, _("virtual memory exhausted"));
266
267 #ifdef HAVE_STRDUP
268   return result;
269 #else
270   return strcpy (result, ptr);
271 #endif
272 }
273
274 #endif  /* HAVE_DMALLOC_H */
275
276 char *
277 xstrndup (const char *str, unsigned int length)
278 {
279   char *result;
280
281 #ifdef HAVE_STRNDUP
282   result = strndup (str, length);
283   if (result == 0)
284     fatal (NILF, _("virtual memory exhausted"));
285 #else
286   result = xmalloc (length + 1);
287   if (length > 0)
288     strncpy (result, str, length);
289   result[length] = '\0';
290 #endif
291
292   return result;
293 }
294 \f
295
296 /* Limited INDEX:
297    Search through the string STRING, which ends at LIMIT, for the character C.
298    Returns a pointer to the first occurrence, or nil if none is found.
299    Like INDEX except that the string searched ends where specified
300    instead of at the first null.  */
301
302 char *
303 lindex (const char *s, const char *limit, int c)
304 {
305   while (s < limit)
306     if (*s++ == c)
307       return (char *)(s - 1);
308
309   return 0;
310 }
311 \f
312 /* Return the address of the first whitespace or null in the string S.  */
313
314 char *
315 end_of_token (const char *s)
316 {
317   while (! STOP_SET (*s, MAP_BLANK|MAP_NUL))
318     ++s;
319   return (char *)s;
320 }
321
322 /* Return the address of the first nonwhitespace or null in the string S.  */
323
324 char *
325 next_token (const char *s)
326 {
327   while (isblank ((unsigned char)*s))
328     ++s;
329   return (char *)s;
330 }
331
332 /* Find the next token in PTR; return the address of it, and store the length
333    of the token into *LENGTHPTR if LENGTHPTR is not nil.  Set *PTR to the end
334    of the token, so this function can be called repeatedly in a loop.  */
335
336 char *
337 find_next_token (const char **ptr, unsigned int *lengthptr)
338 {
339   const char *p = next_token (*ptr);
340
341   if (*p == '\0')
342     return 0;
343
344   *ptr = end_of_token (p);
345   if (lengthptr != 0)
346     *lengthptr = *ptr - p;
347
348   return (char *)p;
349 }
350 \f
351
352 /* Copy a chain of 'struct dep'.  For 2nd expansion deps, dup the name.  */
353
354 struct dep *
355 copy_dep_chain (const struct dep *d)
356 {
357   struct dep *firstnew = 0;
358   struct dep *lastnew = 0;
359
360   while (d != 0)
361     {
362       struct dep *c = xmalloc (sizeof (struct dep));
363       memcpy (c, d, sizeof (struct dep));
364
365       if (c->need_2nd_expansion)
366         c->name = xstrdup (c->name);
367
368       c->next = 0;
369       if (firstnew == 0)
370         firstnew = lastnew = c;
371       else
372         lastnew = lastnew->next = c;
373
374       d = d->next;
375     }
376
377   return firstnew;
378 }
379
380 /* Free a chain of 'struct dep'.  */
381
382 void
383 free_dep_chain (struct dep *d)
384 {
385   while (d != 0)
386     {
387       struct dep *df = d;
388       d = d->next;
389       free_dep (df);
390     }
391 }
392
393 /* Free a chain of struct nameseq.
394    For struct dep chains use free_dep_chain.  */
395
396 void
397 free_ns_chain (struct nameseq *ns)
398 {
399   while (ns != 0)
400     {
401       struct nameseq *t = ns;
402       ns = ns->next;
403       free (t);
404     }
405 }
406 \f
407
408 #if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
409 /* If we don't have strcasecmp() (from POSIX), or anything that can substitute
410    for it, define our own version.  */
411
412 int
413 strcasecmp (const char *s1, const char *s2)
414 {
415   while (1)
416     {
417       int c1 = (int) *(s1++);
418       int c2 = (int) *(s2++);
419
420       if (isalpha (c1))
421         c1 = tolower (c1);
422       if (isalpha (c2))
423         c2 = tolower (c2);
424
425       if (c1 != '\0' && c1 == c2)
426         continue;
427
428       return (c1 - c2);
429     }
430 }
431 #endif
432
433 #if !HAVE_STRNCASECMP && !HAVE_STRNICMP && !HAVE_STRNCMPI
434 /* If we don't have strncasecmp() (from POSIX), or anything that can
435    substitute for it, define our own version.  */
436
437 int
438 strncasecmp (const char *s1, const char *s2, int n)
439 {
440   while (n-- > 0)
441     {
442       int c1 = (int) *(s1++);
443       int c2 = (int) *(s2++);
444
445       if (isalpha (c1))
446         c1 = tolower (c1);
447       if (isalpha (c2))
448         c2 = tolower (c2);
449
450       if (c1 != '\0' && c1 == c2)
451         continue;
452
453       return (c1 - c2);
454     }
455
456   return 0;
457 }
458 #endif
459 \f
460 #ifdef  GETLOADAVG_PRIVILEGED
461
462 #ifdef POSIX
463
464 /* Hopefully if a system says it's POSIX.1 and has the setuid and setgid
465    functions, they work as POSIX.1 says.  Some systems (Alpha OSF/1 1.2,
466    for example) which claim to be POSIX.1 also have the BSD setreuid and
467    setregid functions, but they don't work as in BSD and only the POSIX.1
468    way works.  */
469
470 #undef HAVE_SETREUID
471 #undef HAVE_SETREGID
472
473 #else   /* Not POSIX.  */
474
475 /* Some POSIX.1 systems have the seteuid and setegid functions.  In a
476    POSIX-like system, they are the best thing to use.  However, some
477    non-POSIX systems have them too but they do not work in the POSIX style
478    and we must use setreuid and setregid instead.  */
479
480 #undef HAVE_SETEUID
481 #undef HAVE_SETEGID
482
483 #endif  /* POSIX.  */
484
485 #ifndef HAVE_UNISTD_H
486 extern int getuid (), getgid (), geteuid (), getegid ();
487 extern int setuid (), setgid ();
488 #ifdef HAVE_SETEUID
489 extern int seteuid ();
490 #else
491 #ifdef  HAVE_SETREUID
492 extern int setreuid ();
493 #endif  /* Have setreuid.  */
494 #endif  /* Have seteuid.  */
495 #ifdef HAVE_SETEGID
496 extern int setegid ();
497 #else
498 #ifdef  HAVE_SETREGID
499 extern int setregid ();
500 #endif  /* Have setregid.  */
501 #endif  /* Have setegid.  */
502 #endif  /* No <unistd.h>.  */
503
504 /* Keep track of the user and group IDs for user- and make- access.  */
505 static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
506 #define access_inited   (user_uid != -1)
507 static enum { make, user } current_access;
508
509
510 /* Under -d, write a message describing the current IDs.  */
511
512 static void
513 log_access (const char *flavor)
514 {
515   if (! ISDB (DB_JOBS))
516     return;
517
518   /* All the other debugging messages go to stdout,
519      but we write this one to stderr because it might be
520      run in a child fork whose stdout is piped.  */
521
522   fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
523            flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
524            (unsigned long) getegid (), (unsigned long) getgid ());
525   fflush (stderr);
526 }
527
528
529 static void
530 init_access (void)
531 {
532 #ifndef VMS
533   user_uid = getuid ();
534   user_gid = getgid ();
535
536   make_uid = geteuid ();
537   make_gid = getegid ();
538
539   /* Do these ever fail?  */
540   if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
541     pfatal_with_name ("get{e}[gu]id");
542
543   log_access (_("Initialized access"));
544
545   current_access = make;
546 #endif
547 }
548
549 #endif  /* GETLOADAVG_PRIVILEGED */
550
551 /* Give the process appropriate permissions for access to
552    user data (i.e., to stat files, or to spawn a child process).  */
553 void
554 user_access (void)
555 {
556 #ifdef  GETLOADAVG_PRIVILEGED
557
558   if (!access_inited)
559     init_access ();
560
561   if (current_access == user)
562     return;
563
564   /* We are in "make access" mode.  This means that the effective user and
565      group IDs are those of make (if it was installed setuid or setgid).
566      We now want to set the effective user and group IDs to the real IDs,
567      which are the IDs of the process that exec'd make.  */
568
569 #ifdef  HAVE_SETEUID
570
571   /* Modern systems have the seteuid/setegid calls which set only the
572      effective IDs, which is ideal.  */
573
574   if (seteuid (user_uid) < 0)
575     pfatal_with_name ("user_access: seteuid");
576
577 #else   /* Not HAVE_SETEUID.  */
578
579 #ifndef HAVE_SETREUID
580
581   /* System V has only the setuid/setgid calls to set user/group IDs.
582      There is an effective ID, which can be set by setuid/setgid.
583      It can be set (unless you are root) only to either what it already is
584      (returned by geteuid/getegid, now in make_uid/make_gid),
585      the real ID (return by getuid/getgid, now in user_uid/user_gid),
586      or the saved set ID (what the effective ID was before this set-ID
587      executable (make) was exec'd).  */
588
589   if (setuid (user_uid) < 0)
590     pfatal_with_name ("user_access: setuid");
591
592 #else   /* HAVE_SETREUID.  */
593
594   /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
595      They may be set to themselves or each other.  So you have two alternatives
596      at any one time.  If you use setuid/setgid, the effective will be set to
597      the real, leaving only one alternative.  Using setreuid/setregid, however,
598      you can toggle between your two alternatives by swapping the values in a
599      single setreuid or setregid call.  */
600
601   if (setreuid (make_uid, user_uid) < 0)
602     pfatal_with_name ("user_access: setreuid");
603
604 #endif  /* Not HAVE_SETREUID.  */
605 #endif  /* HAVE_SETEUID.  */
606
607 #ifdef  HAVE_SETEGID
608   if (setegid (user_gid) < 0)
609     pfatal_with_name ("user_access: setegid");
610 #else
611 #ifndef HAVE_SETREGID
612   if (setgid (user_gid) < 0)
613     pfatal_with_name ("user_access: setgid");
614 #else
615   if (setregid (make_gid, user_gid) < 0)
616     pfatal_with_name ("user_access: setregid");
617 #endif
618 #endif
619
620   current_access = user;
621
622   log_access (_("User access"));
623
624 #endif  /* GETLOADAVG_PRIVILEGED */
625 }
626
627 /* Give the process appropriate permissions for access to
628    make data (i.e., the load average).  */
629 void
630 make_access (void)
631 {
632 #ifdef  GETLOADAVG_PRIVILEGED
633
634   if (!access_inited)
635     init_access ();
636
637   if (current_access == make)
638     return;
639
640   /* See comments in user_access, above.  */
641
642 #ifdef  HAVE_SETEUID
643   if (seteuid (make_uid) < 0)
644     pfatal_with_name ("make_access: seteuid");
645 #else
646 #ifndef HAVE_SETREUID
647   if (setuid (make_uid) < 0)
648     pfatal_with_name ("make_access: setuid");
649 #else
650   if (setreuid (user_uid, make_uid) < 0)
651     pfatal_with_name ("make_access: setreuid");
652 #endif
653 #endif
654
655 #ifdef  HAVE_SETEGID
656   if (setegid (make_gid) < 0)
657     pfatal_with_name ("make_access: setegid");
658 #else
659 #ifndef HAVE_SETREGID
660   if (setgid (make_gid) < 0)
661     pfatal_with_name ("make_access: setgid");
662 #else
663   if (setregid (user_gid, make_gid) < 0)
664     pfatal_with_name ("make_access: setregid");
665 #endif
666 #endif
667
668   current_access = make;
669
670   log_access (_("Make access"));
671
672 #endif  /* GETLOADAVG_PRIVILEGED */
673 }
674
675 /* Give the process appropriate permissions for a child process.
676    This is like user_access, but you can't get back to make_access.  */
677 void
678 child_access (void)
679 {
680 #ifdef  GETLOADAVG_PRIVILEGED
681
682   if (!access_inited)
683     abort ();
684
685   /* Set both the real and effective UID and GID to the user's.
686      They cannot be changed back to make's.  */
687
688 #ifndef HAVE_SETREUID
689   if (setuid (user_uid) < 0)
690     pfatal_with_name ("child_access: setuid");
691 #else
692   if (setreuid (user_uid, user_uid) < 0)
693     pfatal_with_name ("child_access: setreuid");
694 #endif
695
696 #ifndef HAVE_SETREGID
697   if (setgid (user_gid) < 0)
698     pfatal_with_name ("child_access: setgid");
699 #else
700   if (setregid (user_gid, user_gid) < 0)
701     pfatal_with_name ("child_access: setregid");
702 #endif
703
704   log_access (_("Child access"));
705
706 #endif  /* GETLOADAVG_PRIVILEGED */
707 }
708
709 #ifdef NEED_GET_PATH_MAX
710 unsigned int
711 get_path_max (void)
712 {
713   static unsigned int value;
714
715   if (value == 0)
716     {
717       long int x = pathconf ("/", _PC_PATH_MAX);
718       if (x > 0)
719         value = x;
720       else
721         return MAXPATHLEN;
722     }
723
724   return value;
725 }
726 #endif