Imported from ../bash-2.05a.tar.gz.
[platform/upstream/bash.git] / builtins / common.c
1 /* Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
2
3    This file is part of GNU Bash, the Bourne Again SHell.
4
5    Bash is free software; you can redistribute it and/or modify it under
6    the terms of the GNU General Public License as published by the Free
7    Software Foundation; either version 2, or (at your option) any later
8    version.
9
10    Bash is distributed in the hope that it will be useful, but WITHOUT ANY
11    WARRANTY; without even the implied warranty of MERCHANTABILITY or
12    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13    for more details.
14    
15    You should have received a copy of the GNU General Public License along
16    with Bash; see the file COPYING.  If not, write to the Free Software
17    Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
18
19 #include <config.h>
20
21 #if defined (HAVE_UNISTD_H)
22 #  ifdef _MINIX
23 #    include <sys/types.h>
24 #  endif
25 #  include <unistd.h>
26 #endif
27
28 #include <stdio.h>
29 #include <chartypes.h>
30 #include "../bashtypes.h"
31 #include "posixstat.h"
32 #include <signal.h>
33
34 #include <errno.h>
35
36 #if defined (PREFER_STDARG)
37 #  include <stdarg.h>
38 #else
39 #  if defined (PREFER_VARARGS)
40 #    include <varargs.h>
41 #  endif
42 #endif
43
44 #include "../bashansi.h"
45
46 #include "../shell.h"
47 #include "maxpath.h"
48 #include "../flags.h"
49 #include "../jobs.h"
50 #include "../builtins.h"
51 #include "../input.h"
52 #include "../execute_cmd.h"
53 #include "../trap.h"
54 #include "bashgetopt.h"
55 #include "common.h"
56 #include "builtext.h"
57 #include <tilde/tilde.h>
58
59 #if defined (HISTORY)
60 #  include "../bashhist.h"
61 #endif
62
63 #if !defined (errno)
64 extern int errno;   
65 #endif /* !errno */
66
67 extern int no_symbolic_links;
68 extern int indirection_level, startup_state, subshell_environment;
69 extern int line_number;
70 extern int last_command_exit_value;
71 extern int running_trap;
72 extern int posixly_correct;
73 extern char *this_command_name, *shell_name;
74 extern char *bash_getcwd_errstr;
75
76 /* Used by some builtins and the mainline code. */
77 sh_builtin_func_t *last_shell_builtin = (sh_builtin_func_t *)NULL;
78 sh_builtin_func_t *this_shell_builtin = (sh_builtin_func_t *)NULL;
79
80 /* **************************************************************** */
81 /*                                                                  */
82 /*           Error reporting, usage, and option processing          */
83 /*                                                                  */
84 /* **************************************************************** */
85
86 /* This is a lot like report_error (), but it is for shell builtins
87    instead of shell control structures, and it won't ever exit the
88    shell. */
89 #if defined (USE_VARARGS)
90 void
91 #if defined (PREFER_STDARG)
92 builtin_error (const char *format, ...)
93 #else
94 builtin_error (format, va_alist)
95      const char *format;
96      va_dcl
97 #endif
98 {
99   va_list args;
100   char *name;
101
102   name = get_name_for_error ();
103   fprintf (stderr, "%s: ", name);
104
105   if (this_command_name && *this_command_name)
106     fprintf (stderr, "%s: ", this_command_name);
107
108 #if defined (PREFER_STDARG)
109   va_start (args, format);
110 #else
111   va_start (args);
112 #endif
113
114   vfprintf (stderr, format, args);
115   va_end (args);
116   fprintf (stderr, "\n");
117 }
118 #else /* !USE_VARARGS */
119 void
120 builtin_error (format, arg1, arg2, arg3, arg4, arg5)
121      char *format, *arg1, *arg2, *arg3, *arg4, *arg5;
122 {
123   if (this_command_name && *this_command_name)
124     fprintf (stderr, "%s: ", this_command_name);
125
126   fprintf (stderr, format, arg1, arg2, arg3, arg4, arg5);
127   fprintf (stderr, "\n");
128   fflush (stderr);
129 }
130 #endif /* !USE_VARARGS */
131
132 /* Print a usage summary for the currently-executing builtin command. */
133 void
134 builtin_usage ()
135 {
136   if (this_command_name && *this_command_name)
137     fprintf (stderr, "%s: usage: ", this_command_name);
138   fprintf (stderr, "%s\n", current_builtin->short_doc);
139   fflush (stderr);
140 }
141
142 /* Return if LIST is NULL else barf and jump to top_level.  Used by some
143    builtins that do not accept arguments. */
144 void
145 no_args (list)
146      WORD_LIST *list;
147 {
148   if (list)
149     {
150       builtin_error ("too many arguments");
151       jump_to_top_level (DISCARD);
152     }
153 }
154
155 /* Function called when one of the builtin commands detects a bad
156    option. */
157 void
158 bad_option (s)
159      char *s;
160 {
161   builtin_error ("unknown option: %s", s);
162 }
163
164 /* Check that no options were given to the currently-executing builtin,
165    and return 0 if there were options. */
166 int
167 no_options (list)
168      WORD_LIST *list;
169 {
170   reset_internal_getopt ();
171   if (internal_getopt (list, "") != -1)
172     {
173       builtin_usage ();
174       return (1);
175     }
176   return (0);
177 }
178
179 /* **************************************************************** */
180 /*                                                                  */
181 /*           Shell positional parameter manipulation                */
182 /*                                                                  */
183 /* **************************************************************** */
184
185 /* Convert a WORD_LIST into a C-style argv.  Return the number of elements
186    in the list in *IP, if IP is non-null.  A convenience function for
187    loadable builtins; also used by `test'. */
188 char **
189 make_builtin_argv (list, ip)
190      WORD_LIST *list;
191      int *ip;
192 {
193   char **argv;
194
195   argv = word_list_to_argv (list, 0, 1, ip);
196   argv[0] = this_command_name;
197   return argv;
198 }
199
200 /* Remember LIST in $0 ... $9, and REST_OF_ARGS.  If DESTRUCTIVE is
201    non-zero, then discard whatever the existing arguments are, else
202    only discard the ones that are to be replaced. */
203 void
204 remember_args (list, destructive)
205      WORD_LIST *list;
206      int destructive;
207 {
208   register int i;
209
210   for (i = 1; i < 10; i++)
211     {
212       if ((destructive || list) && dollar_vars[i])
213         {
214           free (dollar_vars[i]);
215           dollar_vars[i] = (char *)NULL;
216         }
217
218       if (list)
219         {
220           dollar_vars[i] = savestring (list->word->word);
221           list = list->next;
222         }
223     }
224
225   /* If arguments remain, assign them to REST_OF_ARGS.
226      Note that copy_word_list (NULL) returns NULL, and
227      that dispose_words (NULL) does nothing. */
228   if (destructive || list)
229     {
230       dispose_words (rest_of_args);
231       rest_of_args = copy_word_list (list);
232     }
233
234   if (destructive)
235     set_dollar_vars_changed ();
236 }
237
238 /* **************************************************************** */
239 /*                                                                  */
240 /*               Pushing and Popping variable contexts              */
241 /*                                                                  */
242 /* **************************************************************** */
243
244 static WORD_LIST **dollar_arg_stack = (WORD_LIST **)NULL;
245 static int dollar_arg_stack_slots;
246 static int dollar_arg_stack_index;
247
248 void
249 push_context ()
250 {
251   push_dollar_vars ();
252   variable_context++;
253 }
254
255 void
256 pop_context ()
257 {
258   pop_dollar_vars ();
259   kill_all_local_variables ();
260   variable_context--;
261 }
262
263 /* Save the existing positional parameters on a stack. */
264 void
265 push_dollar_vars ()
266 {
267   if (dollar_arg_stack_index + 2 > dollar_arg_stack_slots)
268     {
269       dollar_arg_stack = (WORD_LIST **)
270         xrealloc (dollar_arg_stack, (dollar_arg_stack_slots += 10)
271                   * sizeof (WORD_LIST **));
272     }
273   dollar_arg_stack[dollar_arg_stack_index++] = list_rest_of_args ();
274   dollar_arg_stack[dollar_arg_stack_index] = (WORD_LIST *)NULL;
275 }
276
277 /* Restore the positional parameters from our stack. */
278 void
279 pop_dollar_vars ()
280 {
281   if (!dollar_arg_stack || dollar_arg_stack_index == 0)
282     return;
283
284   remember_args (dollar_arg_stack[--dollar_arg_stack_index], 1);
285   dispose_words (dollar_arg_stack[dollar_arg_stack_index]);
286   dollar_arg_stack[dollar_arg_stack_index] = (WORD_LIST *)NULL;
287 }
288
289 void
290 dispose_saved_dollar_vars ()
291 {
292   if (!dollar_arg_stack || dollar_arg_stack_index == 0)
293     return;
294
295   dispose_words (dollar_arg_stack[dollar_arg_stack_index]);
296   dollar_arg_stack[dollar_arg_stack_index] = (WORD_LIST *)NULL;
297 }
298
299 static int changed_dollar_vars;
300
301 /* Have the dollar variables been reset to new values since we last
302    checked? */
303 int
304 dollar_vars_changed ()
305 {
306   return (changed_dollar_vars);
307 }
308
309 void
310 set_dollar_vars_unchanged ()
311 {
312   changed_dollar_vars = 0;
313 }
314
315 void
316 set_dollar_vars_changed ()
317 {
318   changed_dollar_vars = 1;
319 }
320
321 /* **************************************************************** */
322 /*                                                                  */
323 /*              Validating numeric input and arguments              */
324 /*                                                                  */
325 /* **************************************************************** */
326
327 /* Read a numeric arg for this_command_name, the name of the shell builtin
328    that wants it.  LIST is the word list that the arg is to come from.
329    Accept only the numeric argument; report an error if other arguments
330    follow.  If FATAL is true, call throw_to_top_level, which exits the
331    shell; if not, call jump_to_top_level (DISCARD), which aborts the
332    current command. */
333 long
334 get_numeric_arg (list, fatal)
335      WORD_LIST *list;
336      int fatal;
337 {
338   long count = 1;
339
340   if (list)
341     {
342       register char *arg;
343
344       arg = list->word->word;
345       if (!arg || (legal_number (arg, &count) == 0))
346         {
347           builtin_error ("bad non-numeric arg `%s'", list->word->word);
348           if (fatal)
349             throw_to_top_level ();
350           else
351             jump_to_top_level (DISCARD);
352         }
353       no_args (list->next);
354     }
355
356   return (count);
357 }
358
359 /* Get an eight-bit status value from LIST */
360 int
361 get_exitstat (list)
362      WORD_LIST *list;
363 {
364   int status;
365   long sval;
366   char *arg;
367
368   arg = list->word->word;
369   if (arg == 0 || legal_number (arg, &sval) == 0)
370     {
371       builtin_error ("bad non-numeric arg `%s'", list->word->word);
372       return 255;
373     }
374   no_args (list->next);
375
376   status = sval & 255;
377   return status;
378 }
379
380 /* Return the octal number parsed from STRING, or -1 to indicate
381    that the string contained a bad number. */
382 int
383 read_octal (string)
384      char *string;
385 {
386   int result, digits;
387
388   result = digits = 0;
389   while (*string && ISOCTAL (*string))
390     {
391       digits++;
392       result = (result * 8) + (*string++ - '0');
393       if (result > 0777)
394         return -1;
395     }
396
397   if (digits == 0 || *string)
398     result = -1;
399
400   return (result);
401 }
402
403 /* **************************************************************** */
404 /*                                                                  */
405 /*           Manipulating the current working directory             */
406 /*                                                                  */
407 /* **************************************************************** */
408
409 /* Return a consed string which is the current working directory.
410    FOR_WHOM is the name of the caller for error printing.  */
411 char *the_current_working_directory = (char *)NULL;
412
413 char *
414 get_working_directory (for_whom)
415      char *for_whom;
416 {
417   char *directory;
418
419   if (no_symbolic_links)
420     {
421       if (the_current_working_directory)
422         free (the_current_working_directory);
423
424       the_current_working_directory = (char *)NULL;
425     }
426
427   if (the_current_working_directory == 0)
428     {
429       the_current_working_directory = (char *)xmalloc (PATH_MAX);
430       the_current_working_directory[0] = '\0';
431       directory = getcwd (the_current_working_directory, PATH_MAX);
432       if (directory == 0)
433         {
434           fprintf (stderr, "%s: could not get current directory: %s: %s\n",
435                    (for_whom && *for_whom) ? for_whom : get_name_for_error (),
436                    bash_getcwd_errstr, strerror (errno));
437
438           free (the_current_working_directory);
439           the_current_working_directory = (char *)NULL;
440           return (char *)NULL;
441         }
442     }
443
444   return (savestring (the_current_working_directory));
445 }
446
447 /* Make NAME our internal idea of the current working directory. */
448 void
449 set_working_directory (name)
450      char *name;
451 {
452   FREE (the_current_working_directory);
453   the_current_working_directory = savestring (name);
454 }
455
456 /* **************************************************************** */
457 /*                                                                  */
458 /*              Job control support functions                       */
459 /*                                                                  */
460 /* **************************************************************** */
461
462 #if defined (JOB_CONTROL)
463 /* Return the job spec found in LIST. */
464 int
465 get_job_spec (list)
466      WORD_LIST *list;
467 {
468   register char *word;
469   int job, substring_search;
470
471   if (list == 0)
472     return (current_job);
473
474   word = list->word->word;
475
476   if (*word == '\0')
477     return (current_job);
478
479   if (*word == '%')
480     word++;
481
482   if (DIGIT (*word) && all_digits (word))
483     {
484       job = atoi (word);
485       return (job >= job_slots ? NO_JOB : job - 1);
486     }
487
488   substring_search = 0;
489   switch (*word)
490     {
491     case 0:
492     case '%':
493     case '+':
494       return (current_job);
495
496     case '-':
497       return (previous_job);
498
499     case '?':                   /* Substring search requested. */
500       substring_search++;
501       word++;
502       /* FALLTHROUGH */
503
504     default:
505       {
506         register int i, wl;
507
508         job = NO_JOB;
509         wl = strlen (word);
510         for (i = 0; i < job_slots; i++)
511           {
512             if (jobs[i])
513               {
514                 register PROCESS *p;
515                 p = jobs[i]->pipe;
516                 do
517                   {
518                     if ((substring_search && strindex (p->command, word)) ||
519                         (STREQN (p->command, word, wl)))
520                       {
521                         if (job != NO_JOB)
522                           {
523                             builtin_error ("ambigious job spec: %s", word);
524                             return (DUP_JOB);
525                           }
526                         else
527                           job = i;
528                       }
529
530                     p = p->next;
531                   }
532                 while (p != jobs[i]->pipe);
533               }
534           }
535         return (job);
536       }
537     }
538 }
539 #endif /* JOB_CONTROL */
540
541 int
542 display_signal_list (list, forcecols)
543      WORD_LIST *list;
544      int forcecols;
545 {
546   register int i, column;
547   char *name;
548   int result;
549   long signum;
550
551   result = EXECUTION_SUCCESS;
552   if (!list)
553     {
554       for (i = 1, column = 0; i < NSIG; i++)
555         {
556           name = signal_name (i);
557           if (STREQN (name, "SIGJUNK", 7) || STREQN (name, "Unknown", 7))
558             continue;
559
560           if (posixly_correct && !forcecols)
561             printf ("%s%s", name, (i == NSIG - 1) ? "" : " ");
562           else
563             {
564               printf ("%2d) %s", i, name);
565
566               if (++column < 4)
567                 printf ("\t");
568               else
569                 {
570                   printf ("\n");
571                   column = 0;
572                 }
573             }
574         }
575
576       if ((posixly_correct && !forcecols) || column != 0)
577         printf ("\n");
578       return result;
579     }
580
581   /* List individual signal names or numbers. */
582   while (list)
583     {
584       if (legal_number (list->word->word, &signum))
585         {
586           /* This is specified by Posix.2 so that exit statuses can be
587              mapped into signal numbers. */
588           if (signum > 128)
589             signum -= 128;
590           if (signum < 0 || signum >= NSIG)
591             {
592               builtin_error ("bad signal number: %s", list->word->word);
593               result = EXECUTION_FAILURE;
594               list = list->next;
595               continue;
596             }
597
598           name = signal_name (signum);
599           if (STREQN (name, "SIGJUNK", 7) || STREQN (name, "Unknown", 7))
600             {
601               list = list->next;
602               continue;
603             }
604 #if defined (JOB_CONTROL)
605           /* POSIX.2 says that `kill -l signum' prints the signal name without
606              the `SIG' prefix. */
607           printf ("%s\n", (this_shell_builtin == kill_builtin) ? name + 3 : name);
608 #else
609           printf ("%s\n", name);
610 #endif
611         }
612       else
613         {
614           signum = decode_signal (list->word->word);
615           if (signum == NO_SIG)
616             {
617               builtin_error ("%s: not a signal specification", list->word->word);
618               result = EXECUTION_FAILURE;
619               list = list->next;
620               continue;
621             }
622           printf ("%ld\n", signum);
623         }
624       list = list->next;
625     }
626   return (result);
627 }
628
629 /* **************************************************************** */
630 /*                                                                  */
631 /*          Finding builtin commands and their functions            */
632 /*                                                                  */
633 /* **************************************************************** */
634
635 /* Perform a binary search and return the address of the builtin function
636    whose name is NAME.  If the function couldn't be found, or the builtin
637    is disabled or has no function associated with it, return NULL.
638    Return the address of the builtin.
639    DISABLED_OKAY means find it even if the builtin is disabled. */
640 struct builtin *
641 builtin_address_internal (name, disabled_okay)
642      char *name;
643      int disabled_okay;
644 {
645   int hi, lo, mid, j;
646
647   hi = num_shell_builtins - 1;
648   lo = 0;
649
650   while (lo <= hi)
651     {
652       mid = (lo + hi) / 2;
653
654       j = shell_builtins[mid].name[0] - name[0];
655
656       if (j == 0)
657         j = strcmp (shell_builtins[mid].name, name);
658
659       if (j == 0)
660         {
661           /* It must have a function pointer.  It must be enabled, or we
662              must have explicitly allowed disabled functions to be found,
663              and it must not have been deleted. */
664           if (shell_builtins[mid].function &&
665               ((shell_builtins[mid].flags & BUILTIN_DELETED) == 0) &&
666               ((shell_builtins[mid].flags & BUILTIN_ENABLED) || disabled_okay))
667             return (&shell_builtins[mid]);
668           else
669             return ((struct builtin *)NULL);
670         }
671       if (j > 0)
672         hi = mid - 1;
673       else
674         lo = mid + 1;
675     }
676   return ((struct builtin *)NULL);
677 }
678
679 /* Return the pointer to the function implementing builtin command NAME. */
680 sh_builtin_func_t *
681 find_shell_builtin (name)
682      char *name;
683 {
684   current_builtin = builtin_address_internal (name, 0);
685   return (current_builtin ? current_builtin->function : (sh_builtin_func_t *)NULL);
686 }
687
688 /* Return the address of builtin with NAME, whether it is enabled or not. */
689 sh_builtin_func_t *
690 builtin_address (name)
691      char *name;
692 {
693   current_builtin = builtin_address_internal (name, 1);
694   return (current_builtin ? current_builtin->function : (sh_builtin_func_t *)NULL);
695 }
696
697 /* Return the function implementing the builtin NAME, but only if it is a
698    POSIX.2 special builtin. */
699 sh_builtin_func_t *
700 find_special_builtin (name)
701      char *name;
702 {
703   current_builtin = builtin_address_internal (name, 0);
704   return ((current_builtin && (current_builtin->flags & SPECIAL_BUILTIN)) ?
705                         current_builtin->function :
706                         (sh_builtin_func_t *)NULL);
707 }
708   
709 static int
710 shell_builtin_compare (sbp1, sbp2)
711      struct builtin *sbp1, *sbp2;
712 {
713   int result;
714
715   if ((result = sbp1->name[0] - sbp2->name[0]) == 0)
716     result = strcmp (sbp1->name, sbp2->name);
717
718   return (result);
719 }
720
721 /* Sort the table of shell builtins so that the binary search will work
722    in find_shell_builtin. */
723 void
724 initialize_shell_builtins ()
725 {
726   qsort (shell_builtins, num_shell_builtins, sizeof (struct builtin),
727     (QSFUNC *)shell_builtin_compare);
728 }