1 /* general.c -- Stuff that is used by all files. */
3 /* Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992
4 Free Software Foundation, Inc.
6 This file is part of GNU Bash, the Bourne Again SHell.
8 Bash is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
13 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 You should have received a copy of the GNU General Public License along
19 with Bash; see the file COPYING. If not, write to the Free Software
20 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
22 #include "config.h" /* includes unistd.h for us */
26 #include "bashtypes.h"
27 #include <sys/param.h>
28 #if defined (_POSIX_VERSION)
29 # if defined (amiga) && defined (USGr4)
30 # define _POSIX_SOURCE
33 # if defined (amiga) && defined (USGr4)
36 #endif /* _POSIX_VERSION */
40 #include <tilde/tilde.h>
42 #if !defined (USG) || defined (HAVE_RESOURCE)
43 # include <sys/time.h>
46 #include <sys/times.h>
53 /* Make the functions strchr and strrchr if they do not exist. */
54 #if !defined (HAVE_STRCHR)
62 for (i = 0; string && string[i]; i++)
64 return ((char *) (string + i));
66 return ((char *) NULL);
77 i = strlen (string) - 1;
81 for (; string && i > -1; i--)
83 return ((char *) (string + i));
85 return ((char *) NULL);
87 #endif /* !HAVE_STRCHR */
89 /* **************************************************************** */
91 /* Memory Allocation and Deallocation. */
93 /* **************************************************************** */
99 register char *temp = (char *)malloc (size);
102 fatal_error ("Out of virtual memory!");
108 xrealloc (pointer, size)
115 temp = xmalloc (size);
117 temp = (char *)realloc (pointer, size);
120 fatal_error ("Out of virtual memory!");
125 /* Use this as the function to call when adding unwind protects so we
126 don't need to know what free() returns. */
134 /* **************************************************************** */
136 /* Integer to String Conversion */
138 /* **************************************************************** */
140 /* Number of characters that can appear in a string representation
141 of an integer. 32 is larger than the string rep of 2^^31 - 1. */
142 #define MAX_INT_LEN 32
144 /* Integer to string conversion. This conses the string; the
145 caller should free it. */
154 buf = xmalloc (MAX_INT_LEN);
162 ui = (unsigned int) i;
164 buf[MAX_INT_LEN - 1] = '\0';
165 p = &buf[MAX_INT_LEN - 2];
168 *p-- = (ui % 10) + '0';
174 ret = savestring (p + 1);
179 /* Return non-zero if all of the characters in STRING are digits. */
186 if (!digit (*string))
194 /* atol(3) is not universal */
202 while (s && *s && whitespace (*s))
204 if (*s == '-' || *s == '+')
209 for ( ; s && *s && digit (*s); s++)
210 ret = (ret * 10) + digit_value (*s);
211 return (neg ? -ret : ret);
214 #if defined (RLIMTYPE)
216 string_to_rlimtype (s)
222 while (s && *s && whitespace (*s))
224 if (*s == '-' || *s == '+')
229 for ( ; s && *s && digit (*s); s++)
230 ret = (ret * 10) + digit_value (*s);
231 return (neg ? -ret : ret);
235 print_rlimtype (n, addnl)
239 char s[sizeof (RLIMTYPE) * 3 + 1];
240 int len = sizeof (RLIMTYPE) * 3 + 1;
244 printf ("0%s", addnl ? "\n" : "");
255 for ( ; n != 0; n /= 10)
256 s[--len] = n % 10 + '0';
257 printf ("%s%s", s + len, addnl ? "\n" : "");
259 #endif /* RLIMTYPE */
261 /* Return 1 if this token is a legal shell `identifier'; that is, it consists
262 solely of letters, digits, and underscores, and does not begin with a
265 legal_identifier (name)
270 if (!name || !*name || digit (*name))
273 for (s = name; s && *s; s++)
275 if (!isletter (*s) && !digit (*s) && (*s != '_'))
281 /* Make sure that WORD is a valid shell identifier, i.e.
282 does not contain a dollar sign, nor is quoted in any way. Nor
283 does it consist of all digits. If CHECK_WORD is non-zero,
284 the word is checked to ensure that it consists of only letters,
285 digits, and underscores. */
286 check_identifier (word, check_word)
290 if (word->dollar_present || word->quoted || all_digits (word->word))
292 report_error ("`%s' is not a valid identifier", word->word);
295 else if (check_word && legal_identifier (word->word) == 0)
297 report_error ("`%s' is not a valid identifier", word->word);
304 /* A function to unset no-delay mode on a file descriptor. Used in shell.c
305 to unset it on the fd passed as stdin. Should be called on stdin if
306 readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
308 #if !defined (O_NDELAY)
309 # if defined (FNDELAY)
310 # define O_NDELAY FNDELAY
312 #endif /* O_NDELAY */
314 /* Make sure no-delay mode is not set on file descriptor FD. */
316 unset_nodelay_mode (fd)
321 if ((flags = fcntl (fd, F_GETFL, 0)) < 0)
324 #if defined (O_NONBLOCK)
325 if (flags & O_NONBLOCK)
327 flags &= ~O_NONBLOCK;
330 #endif /* O_NONBLOCK */
332 #if defined (O_NDELAY)
333 if (flags & O_NDELAY)
338 #endif /* O_NDELAY */
341 fcntl (fd, F_SETFL, flags);
345 /* **************************************************************** */
347 /* Generic List Functions */
349 /* **************************************************************** */
351 /* Call FUNCTION on every member of LIST, a generic list. */
353 map_over_list (list, function)
364 /* Call FUNCTION on every string in WORDS. */
366 map_over_words (words, function)
372 (*function)(words->word->word);
377 /* Reverse the chain of structures in LIST. Output the new head
378 of the chain. You should always assign the output value of this
379 function to something, or you will lose the chain. */
384 register GENERIC_LIST *next, *prev = (GENERIC_LIST *)NULL;
396 /* Return the number of elements in LIST, a generic list. */
403 for (i = 0; list; list = list->next, i++);
407 /* A global variable which acts as a sentinel for an `error' list return. */
408 GENERIC_LIST global_error_list;
410 /* Delete the element of LIST which satisfies the predicate function COMPARER.
411 Returns the element that was deleted, so you can dispose of it, or -1 if
412 the element wasn't found. COMPARER is called with the list element and
413 then ARG. Note that LIST contains the address of a variable which points
414 to the list. You might call this function like this:
416 SHELL_VAR *elt = delete_element (&variable_list, check_var_has_name, "foo");
417 dispose_variable (elt);
420 delete_element (list, comparer, arg)
425 register GENERIC_LIST *prev = (GENERIC_LIST *)NULL;
426 register GENERIC_LIST *temp = *list;
430 if ((*comparer) (temp, arg))
433 prev->next = temp->next;
441 return ((GENERIC_LIST *)&global_error_list);
444 /* Find NAME in ARRAY. Return the index of NAME, or -1 if not present.
445 ARRAY should be NULL terminated. */
447 find_name_in_list (name, array)
452 for (i = 0; array[i]; i++)
453 if (strcmp (name, array[i]) == 0)
459 /* Return the length of ARRAY, a NULL terminated array of char *. */
465 for (i = 0; array[i]; i++);
469 /* Free the contents of ARRAY, a NULL terminated array of char *. */
483 /* Allocate and return a new copy of ARRAY and its contents. */
492 len = array_len (array);
494 new_array = (char **)xmalloc ((len + 1) * sizeof (char *));
495 for (i = 0; array[i]; i++)
496 new_array[i] = savestring (array[i]);
497 new_array[i] = (char *)NULL;
502 /* Comparison routine for use with qsort() on arrays of strings. */
504 qsort_string_compare (s1, s2)
505 register char **s1, **s2;
509 if ((result = **s1 - **s2) == 0)
510 result = strcmp (*s1, *s2);
515 /* Append LIST2 to LIST1. Return the header of the list. */
517 list_append (head, tail)
518 GENERIC_LIST *head, *tail;
520 register GENERIC_LIST *t_head = head;
526 t_head = t_head->next;
531 /* Some random string stuff. */
533 /* Remove all leading whitespace from STRING. This includes
534 newlines. STRING should be terminated with a zero. */
536 strip_leading (string)
539 char *start = string;
541 while (*string && (whitespace (*string) || *string == '\n'))
546 int len = strlen (string);
547 FASTCOPY (string, start, len);
552 /* Remove all trailing whitespace from STRING. This includes
553 newlines. If NEWLINES_ONLY is non-zero, only trailing newlines
554 are removed. STRING should be terminated with a zero. */
556 strip_trailing (string, newlines_only)
560 int len = strlen (string) - 1;
564 if ((newlines_only && string[len] == '\n') ||
565 (!newlines_only && whitespace (string[len])))
570 string[len + 1] = '\0';
573 /* Canonicalize PATH, and return a new path. The new path differs from PATH
575 Multple `/'s are collapsed to a single `/'.
576 Leading `./'s and trailing `/.'s are removed.
577 Trailing `/'s are removed.
578 Non-leading `../'s and trailing `..'s are handled by removing
579 portions of the path. */
581 canonicalize_pathname (path)
584 register int i, start;
588 /* The result cannot be larger than the input PATH. */
589 result = savestring (path);
591 stub_char = (*path == '/') ? '/' : '.';
593 /* Walk along RESULT looking for things to compact. */
600 while (result[i] && result[i] != '/')
605 /* If we didn't find any slashes, then there is nothing left to do. */
609 /* Handle multiple `/'s in a row. */
610 while (result[i] == '/')
613 #if !defined (apollo)
614 if ((start + 1) != i)
616 if ((start + 1) != i && (start != 0 || i != 2))
619 strcpy (result + start + 1, result + i);
624 /* Handle backslash-quoted `/'. */
625 if (start > 0 && result[start - 1] == '\\')
629 /* Check for trailing `/'. */
630 if (start && !result[i])
637 /* Check for `../', `./' or trailing `.' by itself. */
638 if (result[i] == '.')
640 /* Handle trailing `.' by itself. */
645 if (result[i + 1] == '/')
647 strcpy (result + i, result + i + 1);
648 i = (start < 0) ? 0 : start;
652 /* Handle `../' or trailing `..' by itself. */
653 if (result[i + 1] == '.' &&
654 (result[i + 2] == '/' || !result[i + 2]))
656 while (--start > -1 && result[start] != '/');
657 strcpy (result + start + 1, result + i + 2);
658 i = (start < 0) ? 0 : start;
672 /* Turn STRING (a pathname) into an absolute pathname, assuming that
673 DOT_PATH contains the symbolic location of `.'. This always
674 returns a new string, even if STRING was an absolute pathname to
677 make_absolute (string, dot_path)
678 char *string, *dot_path;
683 if (!dot_path || *string == '/')
684 result = savestring (string);
687 if (dot_path && dot_path[0])
689 result = xmalloc (2 + strlen (dot_path) + strlen (string));
690 strcpy (result, dot_path);
691 result_len = strlen (result);
692 if (result[result_len - 1] != '/')
694 result[result_len++] = '/';
695 result[result_len] = '\0';
700 result = xmalloc (3 + strlen (string));
701 result[0] = '.'; result[1] = '/'; result[2] = '\0';
705 strcpy (result + result_len, string);
711 /* Return 1 if STRING contains an absolute pathname, else 0. */
713 absolute_pathname (string)
716 if (!string || !*string)
722 if (*string++ == '.')
724 if (!*string || *string == '/')
727 if (*string == '.' && (string[1] == '\0' || string[1] == '/'))
733 /* Return 1 if STRING is an absolute program name; it is absolute if it
734 contains any slashes. This is used to decide whether or not to look
737 absolute_program (string)
740 return ((char *)strchr (string, '/') != (char *)NULL);
743 /* Return the `basename' of the pathname in STRING (the stuff after the
744 last '/'). If STRING is not a full pathname, simply return it. */
746 base_pathname (string)
751 if (!absolute_pathname (string))
754 p = (char *)strrchr (string, '/');
761 /* Return the full pathname of FILE. Easy. Filenames that begin
762 with a '/' are returned as themselves. Other filenames have
763 the current working directory prepended. A new string is
764 returned in either case. */
772 file = tilde_expand (file);
774 file = savestring (file);
776 if ((*file == '/') && absolute_pathname (file))
782 char *current_dir = xmalloc (2 + MAXPATHLEN + strlen (file));
784 if (getwd (current_dir) == 0)
786 report_error (current_dir);
788 return ((char *)NULL);
790 dlen = strlen (current_dir);
791 current_dir[dlen++] = '/';
793 /* Turn /foo/./bar into /foo/bar. */
794 if (file[0] == '.' && file[1] == '/')
797 strcpy (current_dir + dlen, file);
799 return (current_dir);
803 #if !defined (HAVE_STRCASECMP)
805 #if !defined (to_upper)
806 # define to_upper(c) (islower(c) ? toupper(c) : (c))
807 #endif /* to_upper */
809 /* Compare at most COUNT characters from string1 to string2. Case
812 strnicmp (string1, string2, count)
813 char *string1, *string2;
816 register char ch1, ch2;
822 if (to_upper(ch1) == to_upper(ch2))
830 /* strcmp (), but caseless. */
832 stricmp (string1, string2)
833 char *string1, *string2;
835 register char ch1, ch2;
837 while (*string1 && *string2)
841 if (to_upper(ch1) != to_upper(ch2))
844 return (*string1 - *string2);
846 #endif /* !HAVE_STRCASECMP */
848 /* Determine if s2 occurs in s1. If so, return a pointer to the
849 match in s1. The compare is case insensitive. */
854 register int i, l = strlen (s2);
855 register int len = strlen (s1);
857 for (i = 0; (len - i) >= l; i++)
858 if (strnicmp (s1 + i, s2, l) == 0)
860 return ((char *)NULL);
863 /* Set the environment variables $LINES and $COLUMNS in response to
864 a window size change. */
866 set_lines_and_columns (lines, cols)
872 bind_variable ("LINES", val);
876 bind_variable ("COLUMNS", val);
880 /* A wrapper for bcopy that can be prototyped in general.h */
889 /* Return a string corresponding to the error number E. From
891 #if defined (strerror)
895 #if !defined (HAVE_STRERROR)
901 extern char *sys_errlist[];
902 static char emsg[40];
904 if (e > 0 && e < sys_nerr)
905 return (sys_errlist[e]);
908 sprintf (emsg, "Unknown error %d", e);
912 #endif /* HAVE_STRERROR */
914 #if (defined (USG) && !defined (HAVE_TIMEVAL)) || defined (Minix)
915 # define TIMEVAL_MISSING
918 #if !defined (TIMEVAL_MISSING) || defined (HAVE_RESOURCE)
919 /* Print the contents of a struct timeval * in a standard way. */
924 int minutes, seconds_fraction;
927 seconds = tvp->tv_sec;
929 seconds_fraction = tvp->tv_usec % 1000000;
930 seconds_fraction = (seconds_fraction * 100) / 1000000;
932 minutes = seconds / 60;
935 printf ("%0dm%0ld.%02ds", minutes, seconds, seconds_fraction);
937 #endif /* !TIMEVAL_MISSING || HAVE_RESOURCE */
939 /* Print the time defined by a time_t (returned by the `times' and `time'
940 system calls) in a standard way. This is scaled in terms of HZ, which
941 is what is returned by the `times' call. */
943 #if !defined (BrainDeath)
946 # define HZ 100 /* From my Sys V.3.2 manual for times(2) */
948 # define HZ 60 /* HZ is always 60 on BSD systems */
956 int minutes, seconds_fraction;
959 seconds_fraction = t % HZ;
960 seconds_fraction = (seconds_fraction * 100) / HZ;
964 minutes = seconds / 60;
967 printf ("%0dm%0ld.%02ds", minutes, seconds, seconds_fraction);
969 #endif /* BrainDeath */
971 #if !defined (HAVE_DUP2)
972 /* Replacement for dup2 (), for those systems which either don't have it,
973 or supply one with broken behaviour. */
978 extern int getdtablesize ();
981 /* If FD1 is not a valid file descriptor, then return immediately with
983 if (fcntl (fd1, F_GETFL, 0) == -1)
986 if (fd2 < 0 || fd2 >= getdtablesize ())
998 r = fcntl (fd1, F_DUPFD, fd2);
1001 errno = saved_errno;
1003 if (errno == EINVAL)
1006 /* Force the new file descriptor to remain open across exec () calls. */
1007 SET_OPEN_ON_EXEC (fd2);
1010 #endif /* !HAVE_DUP2 */
1013 * Return the total number of available file descriptors.
1015 * On some systems, like 4.2BSD and its descendents, there is a system call
1016 * that returns the size of the descriptor table: getdtablesize(). There are
1017 * lots of ways to emulate this on non-BSD systems.
1019 * On System V.3, this can be obtained via a call to ulimit:
1020 * return (ulimit(4, 0L));
1022 * On other System V systems, NOFILE is defined in /usr/include/sys/param.h
1023 * (this is what we assume below), so we can simply use it:
1026 * On POSIX systems, there are specific functions for retrieving various
1027 * configuration parameters:
1028 * return (sysconf(_SC_OPEN_MAX));
1032 #if !defined (USG) && !defined (HPUX) && !defined (HAVE_GETDTABLESIZE)
1033 # define HAVE_GETDTABLESIZE
1034 #endif /* !USG && !HPUX && !HAVE_GETDTABLESIZE */
1036 #if defined (hppa) && (defined (hpux_8) || defined (hpux_9))
1037 # undef HAVE_GETDTABLESIZE
1038 #endif /* hppa && hpux_8 */
1040 #if !defined (HAVE_GETDTABLESIZE)
1044 # if defined (_POSIX_VERSION) && defined (_SC_OPEN_MAX)
1045 return (sysconf(_SC_OPEN_MAX)); /* Posix systems use sysconf */
1046 # else /* ! (_POSIX_VERSION && _SC_OPEN_MAX) */
1047 # if defined (USGr3)
1048 return (ulimit (4, 0L)); /* System V.3 systems use ulimit(4, 0L) */
1050 # if defined (NOFILE) /* Other systems use NOFILE */
1052 # else /* !NOFILE */
1053 return (20); /* XXX - traditional value is 20 */
1054 # endif /* !NOFILE */
1055 # endif /* !USGr3 */
1056 # endif /* ! (_POSIX_VERSION && _SC_OPEN_MAX) */
1058 #endif /* !HAVE_GETDTABLESIZE */
1062 #if !defined (HAVE_BCOPY)
1063 bcopy (s,d,n) char *d,*s; { FASTCOPY (s, d, n); }
1064 bzero (s,n) char *s; int n; { memset(s, '\0', n); }
1065 #endif /* !HAVE_BCOPY */
1067 #if !defined (HAVE_GETHOSTNAME)
1068 #include <sys/utsname.h>
1070 gethostname (name, namelen)
1080 i = strlen (ut.nodename) + 1;
1081 strncpy (name, ut.nodename, i < namelen ? i : namelen);
1082 name[namelen] = '\0';
1085 #endif /* !HAVE_GETHOSTNAME */
1088 #if !defined (HAVE_GETWD)
1093 extern char *getcwd ();
1096 result = getcwd (string, MAXPATHLEN);
1098 strcpy (string, "getwd: cannot access parent directories");
1101 #endif /* !HAVE_GETWD */
1103 /* A slightly related function. Get the prettiest name of this
1104 directory possible. */
1105 static char tdir[MAXPATHLEN];
1107 /* Return a pretty pathname. If the first part of the pathname is
1108 the same as $HOME, then replace that with `~'. */
1110 polite_directory_format (name)
1113 char *home = get_string_value ("HOME");
1114 int l = home ? strlen (home) : 0;
1116 if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
1118 strcpy (tdir + 1, name + l);
1126 #if defined (NO_READ_RESTART_ON_SIGNAL)
1127 static char localbuf[128];
1128 static int local_index = 0, local_bufused = 0;
1130 /* Posix and USG systems do not guarantee to restart read () if it is
1131 interrupted by a signal. We do the read ourselves, and restart it
1132 if it returns EINTR. */
1134 getc_with_restart (stream)
1137 /* Try local buffering to reduce the number of read(2) calls. */
1138 if (local_index == local_bufused || local_bufused == 0)
1142 local_bufused = read (fileno (stream), localbuf, sizeof(localbuf));
1143 if (local_bufused > 0)
1145 else if (local_bufused == 0 || errno != EINTR)
1153 return (localbuf[local_index++]);
1157 ungetc_with_restart (c, fp)
1161 if (local_index == 0 || local_bufused == 0 || c == EOF)
1163 return (localbuf[--local_index] = c);
1166 #endif /* NO_READ_RESTART_ON_SIGNAL */
1168 #if defined (USG) || defined (AIX) || (defined (_POSIX_VERSION) && defined (Ultrix))
1169 /* USG and strict POSIX systems do not have killpg (). But we use it in
1170 jobs.c, nojobs.c and some of the builtins. This can also be redefined
1171 as a macro if necessary. */
1172 #if !defined (_POSIX_VERSION)
1174 #endif /* _POSIX_VERSION */
1181 return (kill (-pgrp, sig));
1183 #endif /* USG || AIX || (_POSIX_VERSION && Ultrix) */
1185 /* **************************************************************** */
1187 /* Tilde Initialization and Expansion */
1189 /* **************************************************************** */
1191 /* If tilde_expand hasn't been able to expand the text, perhaps it
1192 is a special shell expansion. This function is installed as the
1193 tilde_expansion_failure_hook. It knows how to expand ~- and ~+. */
1195 bash_tilde_expand (text)
1198 char *result = (char *)NULL;
1203 result = get_string_value ("PWD");
1204 else if (*text == '-')
1205 result = get_string_value ("OLDPWD");
1209 result = savestring (result);
1214 /* Initialize the tilde expander. In Bash, we handle `~-' and `~+', as
1215 well as handling special tilde prefixes; `:~" and `=~' are indications
1216 that we should do tilde expansion. */
1220 static int times_called = 0;
1222 /* Tell the tilde expander that we want a crack if it fails. */
1223 tilde_expansion_failure_hook = (CPFunction *)bash_tilde_expand;
1225 /* Tell the tilde expander about special strings which start a tilde
1226 expansion, and the special strings that end one. Only do this once.
1227 tilde_initialize () is called from within bashline_reinitialize (). */
1228 if (times_called == 0)
1230 tilde_additional_prefixes = (char **)xmalloc (3 * sizeof (char *));
1231 tilde_additional_prefixes[0] = "=~";
1232 tilde_additional_prefixes[1] = ":~";
1233 tilde_additional_prefixes[2] = (char *)NULL;
1235 tilde_additional_suffixes = (char **)xmalloc (3 * sizeof (char *));
1236 tilde_additional_suffixes[0] = ":";
1237 tilde_additional_suffixes[1] = "=~";
1238 tilde_additional_suffixes[2] = (char *)NULL;
1243 #if defined (_POSIX_VERSION)
1245 #if !defined (SA_INTERRUPT)
1246 # define SA_INTERRUPT 0
1249 #if !defined (SA_RESTART)
1250 # define SA_RESTART 0
1254 set_signal_handler (sig, handler)
1256 SigHandler *handler;
1258 struct sigaction act, oact;
1260 act.sa_handler = handler;
1264 act.sa_flags |= SA_INTERRUPT; /* XXX */
1266 act.sa_flags |= SA_RESTART; /* XXX */
1268 sigemptyset (&act.sa_mask);
1269 sigemptyset (&oact.sa_mask);
1270 sigaction (sig, &act, &oact);
1271 return (oact.sa_handler);
1273 #endif /* _POSIX_VERSION */