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