1 /* Miscellaneous generic support functions for GNU Make.
2 Copyright (C) 1988-2022 Free Software Foundation, Inc.
3 This file is part of GNU Make.
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
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.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <https://www.gnu.org/licenses/>. */
23 /* GNU make no longer supports pre-ANSI89 environments. */
35 # include <sys/file.h>
39 make_toui (const char *str, const char **error)
42 unsigned long val = strtoul (str, &end, 10);
47 *error = "Missing value";
48 else if (*end != '\0')
49 *error = "Invalid value";
57 /* Convert val into a string, written to buf. buf must be large enough
58 to hold the largest possible value, plus a nul byte. Returns buf.
59 We can't use standard PRI* here: those are based on intNN_t types. */
62 make_lltoa (long long val, char *buf)
64 sprintf (buf, "%" MK_PRI64_PREFIX "d", val);
69 make_ulltoa (unsigned long long val, char *buf)
71 sprintf (buf, "%" MK_PRI64_PREFIX "u", val);
75 /* Simple random number generator, for use with shuffle.
76 This doesn't need to be truly random, just pretty random. Use our own
77 implementation rather than relying on the C runtime's rand() so we always
78 get the same results for a given seed, regardless of C runtime. */
80 static unsigned int mk_state = 0;
83 make_seed (unsigned int seed)
91 /* mk_state must never be 0. */
93 mk_state = (unsigned int)(time (NULL) ^ make_pid ()) + 1;
95 /* A simple xorshift RNG. */
96 mk_state ^= mk_state << 13;
97 mk_state ^= mk_state >> 17;
98 mk_state ^= mk_state << 5;
103 /* Compare strings *S1 and *S2.
104 Return negative if the first is less, positive if it is greater,
105 zero if they are equal. */
108 alpha_compare (const void *v1, const void *v2)
110 const char *s1 = *((char **)v1);
111 const char *s2 = *((char **)v2);
115 return strcmp (s1, s2);
118 /* Discard each backslash-newline combination from LINE.
119 Backslash-backslash-newline combinations become backslash-newlines.
120 This is done by copying the text at LINE into itself. */
123 collapse_continuations (char *line)
129 q = strchr(in, '\n');
137 size_t out_line_length;
139 if (q > line && q[-1] == '\\')
141 /* Search for more backslashes. */
143 while (&p[i] >= line && p[i] == '\\')
150 /* The number of backslashes is now -I, keep half of them. */
151 out_line_length = (p - in) + i - i/2;
153 memmove (out, in, out_line_length);
154 out += out_line_length;
156 /* When advancing IN, skip the newline too. */
161 /* Backslash/newline handling:
162 In traditional GNU make all trailing whitespace, consecutive
163 backslash/newlines, and any leading non-newline whitespace on the
164 next line is reduced to a single space.
165 In POSIX, each backslash/newline and is replaced by a space. */
166 while (ISBLANK (*in))
168 if (! posix_pedantic)
169 while (out > line && ISBLANK (out[-1]))
175 /* If the newline isn't quoted, put it in the output. */
179 q = strchr(in, '\n');
183 memmove(out, in, strlen(in) + 1);
186 /* Print N spaces (used in debug for target-depth). */
189 print_spaces (unsigned int n)
196 /* Return a string whose contents concatenate the NUM strings provided
197 This string lives in static, re-used memory. */
200 concat (unsigned int num, ...)
202 static size_t rlen = 0;
203 static char *result = NULL;
207 va_start (args, num);
211 const char *s = va_arg (args, const char *);
212 size_t l = xstrlen (s);
219 rlen = ((rlen ? rlen : 60) + l) * 2;
220 result = xrealloc (result, rlen);
223 memcpy (result + ri, s, l);
229 /* Get some more memory if we don't have enough space for the
233 rlen = (rlen ? rlen : 60) * 2;
234 result = xrealloc (result, rlen);
243 #ifndef HAVE_UNISTD_H
252 /* Like malloc but get fatal error if memory is exhausted. */
253 /* Don't bother if we're using dmalloc; it provides these for us. */
255 #ifndef HAVE_DMALLOC_H
263 xmalloc (size_t size)
265 /* Make sure we don't allocate 0, for pre-ISO implementations. */
266 void *result = malloc (size ? size : 1);
274 xcalloc (size_t size)
276 /* Make sure we don't allocate 0, for pre-ISO implementations. */
277 void *result = calloc (size ? size : 1, 1);
285 xrealloc (void *ptr, size_t size)
289 /* Some older implementations of realloc() don't conform to ISO. */
292 result = ptr ? realloc (ptr, size) : malloc (size);
300 xstrdup (const char *ptr)
305 result = strdup (ptr);
307 result = malloc (strlen (ptr) + 1);
316 return strcpy (result, ptr);
320 #endif /* HAVE_DMALLOC_H */
323 xstrndup (const char *str, size_t length)
328 result = strndup (str, length);
332 result = xmalloc (length + 1);
334 strncpy (result, str, length);
335 result[length] = '\0';
343 memrchr(const void* str, int ch, size_t len)
345 const char* sp = str;
367 Search through the string STRING, which ends at LIMIT, for the character C.
368 Returns a pointer to the first occurrence, or nil if none is found.
369 Like INDEX except that the string searched ends where specified
370 instead of at the first null. */
373 lindex (const char *s, const char *limit, int c)
377 return (char *)(s - 1);
382 /* Return the address of the first whitespace or null in the string S. */
385 end_of_token (const char *s)
387 while (! END_OF_TOKEN (*s))
392 /* Return the address of the first nonwhitespace or null in the string S. */
395 next_token (const char *s)
401 /* Find the next token in PTR; return the address of it, and store the length
402 of the token into *LENGTHPTR if LENGTHPTR is not nil. Set *PTR to the end
403 of the token, so this function can be called repeatedly in a loop. */
406 find_next_token (const char **ptr, size_t *lengthptr)
408 const char *p = next_token (*ptr);
413 *ptr = end_of_token (p);
415 *lengthptr = *ptr - p;
420 /* Write a BUFFER of size LEN to file descriptor FD.
421 Retry short writes from EINTR. Return LEN, or -1 on error. */
423 writebuf (int fd, const void *buffer, size_t len)
425 const char *msg = buffer;
431 EINTRLOOP (r, write (fd, msg, l));
442 /* Read until we get LEN bytes from file descriptor FD, into BUFFER.
443 Retry short reads on EINTR. If we get an error, return it.
446 readbuf (int fd, void *buffer, size_t len)
453 EINTRLOOP (r, read (fd, msg, len));
463 return (ssize_t)(msg - (char*)buffer);
467 /* Copy a chain of 'struct dep'. For 2nd expansion deps, dup the name. */
470 copy_dep_chain (const struct dep *d)
472 struct dep *firstnew = 0;
473 struct dep *lastnew = 0;
477 struct dep *c = xmalloc (sizeof (struct dep));
478 memcpy (c, d, sizeof (struct dep));
480 if (c->need_2nd_expansion)
481 c->name = xstrdup (c->name);
485 firstnew = lastnew = c;
487 lastnew = lastnew->next = c;
495 /* Free a chain of struct nameseq.
496 For struct dep chains use free_dep_chain. */
499 free_ns_chain (struct nameseq *ns)
503 struct nameseq *t = ns;
510 #ifdef MAKE_MAINTAINER_MODE
513 spin (const char* type)
518 sprintf (filenm, ".make-spin-%s", type);
520 if (stat (filenm, &dummy) == 0)
522 fprintf (stderr, "SPIN on %s\n", filenm);
529 while (stat (filenm, &dummy) == 0);
534 dbg (const char *fmt, ...)
536 FILE *fp = fopen ("/tmp/gmkdebug.log", "a+");
540 va_start (args, fmt);
541 vsprintf (buf, fmt, args);
544 fprintf(fp, "%u: %s\n", (unsigned) make_pid (), buf);
553 /* Provide support for temporary files. */
555 #ifndef HAVE_STDLIB_H
557 int mkstemp (char *template);
559 char *mktemp (char *template);
572 # define DEFAULT_TMPFILE "sys$scratch:gnv$make_cmdXXXXXX.com"
574 # define DEFAULT_TMPFILE "GmXXXXXX"
580 static const char *tmpdir = NULL;
584 #if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
585 # define TMP_EXTRAS "TMP", "TEMP",
589 const char *tlist[] = { "MAKE_TMPDIR", "TMPDIR", TMP_EXTRAS NULL };
591 unsigned int found = 0;
593 for (tp = tlist; *tp; ++tp)
594 if ((tmpdir = getenv (*tp)) && *tmpdir != '\0')
599 EINTRLOOP(r, stat (tmpdir, &st));
602 _("%s value %s: %s"), *tp, tmpdir, strerror (errno));
603 else if (! S_ISDIR (st.st_mode))
605 _("%s value %s: not a directory"), *tp, tmpdir);
610 tmpdir = DEFAULT_TMPDIR;
613 OS (error, NILF, _("using default temporary directory '%s'"), tmpdir);
622 const char *tmpdir = get_tmpdir ();
626 template = xmalloc (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
627 cp = stpcpy (template, tmpdir);
630 /* It's not possible for tmpdir to be empty. */
631 if (! ISDIRSEP (cp[-1]))
635 strcpy (cp, DEFAULT_TMPFILE);
640 #if !HAVE_MKSTEMP || !HAVE_FDOPEN
641 /* Generate a temporary filename. This is not safe as another program could
642 snipe our filename after we've generated it: use this only on systems
643 without more secure alternatives. */
651 path = get_tmptemplate ();
652 if (*mktemp (path) == '\0')
653 pfatal_with_name ("mktemp");
655 path = xmalloc (L_tmpnam + 1);
656 if (tmpnam (path) == NULL)
657 pfatal_with_name ("tmpnam");
664 /* Generate a temporary file and return an fd for it. If name is NULL then
665 the temp file is anonymous and will be deleted when the process exits. */
667 get_tmpfd (char **name)
673 /* If there's an os-specific way to get an anoymous temp file use it. */
681 /* Preserve the current umask, and set a restrictive one for temp files.
682 Only really needed for mkstemp() but won't hurt for the open method. */
685 #if defined(HAVE_MKSTEMP)
686 tmpnm = get_tmptemplate ();
688 /* It's safest to use mkstemp(), if we can. */
689 EINTRLOOP (fd, mkstemp (tmpnm));
691 tmpnm = get_tmppath ();
693 /* Can't use mkstemp(), but try to guard against a race condition. */
694 EINTRLOOP (fd, open (tmpnm, O_CREAT|O_EXCL|O_RDWR, 0600));
698 _("create temporary file %s: %s"), tmpnm, strerror (errno));
705 EINTRLOOP (r, unlink (tmpnm));
708 _("unlink temporary file %s: %s"), tmpnm, strerror (errno));
717 /* Return a FILE* for a temporary file, opened in the safest way possible.
718 Set name to point to an allocated buffer containing the name of the file.
719 Note, this cannot be NULL! */
721 get_tmpfile (char **name)
723 /* Be consistent with tmpfile, which opens as if by "wb+". */
724 const char *tmpfile_mode = "wb+";
727 #if defined(HAVE_FDOPEN)
728 int fd = get_tmpfd (name);
730 ENULLLOOP (file, fdopen (fd, tmpfile_mode));
733 _("fdopen: temporary file %s: %s"), *name, strerror (errno));
735 /* Preserve the current umask, and set a restrictive one for temp files. */
736 mode_t mask = umask (0077);
739 *name = get_tmppath ();
741 /* Although this fopen is insecure, it is executed only on non-fdopen
742 platforms, which should be a rarity nowadays. */
744 ENULLLOOP (file, fopen (*name, tmpfile_mode));
747 _("fopen: temporary file %s: %s"), *name, strerror (errno));
756 #if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
757 /* If we don't have strcasecmp() (from POSIX), or anything that can substitute
758 for it, define our own version. */
761 strcasecmp (const char *s1, const char *s2)
765 int c1 = (unsigned char) *(s1++);
766 int c2 = (unsigned char) *(s2++);
773 if (c1 != '\0' && c1 == c2)
781 #if !HAVE_STRNCASECMP && !HAVE_STRNICMP && !HAVE_STRNCMPI
782 /* If we don't have strncasecmp() (from POSIX), or anything that can
783 substitute for it, define our own version. */
786 strncasecmp (const char *s1, const char *s2, size_t n)
790 int c1 = (unsigned char) *(s1++);
791 int c2 = (unsigned char) *(s2++);
798 if (c1 != '\0' && c1 == c2)
809 #ifdef NEED_GET_PATH_MAX
813 static unsigned int value;
817 long x = pathconf ("/", _PC_PATH_MAX);
819 value = (unsigned int) x;
830 mempcpy (void *dest, const void *src, size_t n)
832 return (char *) memcpy (dest, src, n) + n;
838 stpcpy (char *dest, const char *src)
845 while (*s++ != '\0');
853 # undef USE_NUMBER_GROUPING
854 # undef USE_WIDE_CHAR
861 strerror (int errnum)
863 static char msg[256];
865 #define SETMSG(_e, _m) case _e: strcpy(msg, _m); break
870 SETMSG (EPERM , "Operation not permitted");
873 SETMSG (ENOENT , "No such file or directory");
876 SETMSG (ESRCH , "No such process");
879 SETMSG (EINTR , "Interrupted system call");
882 SETMSG (EIO , "I/O error");
885 SETMSG (ENXIO , "No such device or address");
888 SETMSG (E2BIG , "Argument list too long");
891 SETMSG (ENOEXEC, "Exec format error");
894 SETMSG (EBADF , "Bad file number");
897 SETMSG (ECHILD , "No child processes");
900 SETMSG (EAGAIN , "Try again");
903 SETMSG (ENOMEM , "Out of memory");
906 SETMSG (EACCES , "Permission denied");
909 SETMSG (EFAULT , "Bad address");
912 SETMSG (ENOTBLK, "Block device required");
915 SETMSG (EBUSY , "Device or resource busy");
918 SETMSG (EEXIST , "File exists");
921 SETMSG (EXDEV , "Cross-device link");
924 SETMSG (ENODEV , "No such device");
927 SETMSG (ENOTDIR, "Not a directory");
930 SETMSG (EISDIR , "Is a directory");
933 SETMSG (EINVAL , "Invalid argument");
936 SETMSG (ENFILE , "File table overflow");
939 SETMSG (EMFILE , "Too many open files");
942 SETMSG (ENOTTY , "Not a typewriter");
945 SETMSG (ETXTBSY, "Text file busy");
948 SETMSG (EFBIG , "File too large");
951 SETMSG (ENOSPC , "No space left on device");
954 SETMSG (ESPIPE , "Illegal seek");
957 SETMSG (EROFS , "Read-only file system");
960 SETMSG (EMLINK , "Too many links");
963 SETMSG (EPIPE , "Broken pipe");
966 SETMSG (EDOM , "Math argument out of domain of func");
969 SETMSG (ERANGE , "Math result not representable");
971 default: sprintf (msg, "Unknown error %d", errnum); break;