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