1 /* common.c - utility functions for all builtins */
3 /* Copyright (C) 1987-2021 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #if defined (HAVE_UNISTD_H)
25 # include <sys/types.h>
31 #include <chartypes.h>
32 #include "../bashtypes.h"
33 #include "posixstat.h"
38 #if defined (PREFER_STDARG)
44 #include "../bashansi.h"
45 #include "../bashintl.h"
47 #define NEED_FPURGE_DECL
52 #include "../parser.h"
54 #include "../builtins.h"
56 #include "../execute_cmd.h"
58 #include "bashgetopt.h"
61 #include <tilde/tilde.h>
64 # include "../bashhist.h"
71 extern const char * const bash_getcwd_errstr
;
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
;
77 /* **************************************************************** */
79 /* Error reporting, usage, and option processing */
81 /* **************************************************************** */
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
88 builtin_error_prolog ()
92 name
= get_name_for_error ();
93 fprintf (stderr
, "%s: ", name
);
95 if (interactive_shell
== 0)
96 fprintf (stderr
, _("line %d: "), executing_line_number ());
98 if (this_command_name
&& *this_command_name
)
99 fprintf (stderr
, "%s: ", this_command_name
);
103 #if defined (PREFER_STDARG)
104 builtin_error (const char *format
, ...)
106 builtin_error (format
, va_alist
)
113 builtin_error_prolog ();
115 SH_VA_START (args
, format
);
117 vfprintf (stderr
, format
, args
);
119 fprintf (stderr
, "\n");
123 #if defined (PREFER_STDARG)
124 builtin_warning (const char *format
, ...)
126 builtin_warning (format
, va_alist
)
133 builtin_error_prolog ();
134 fprintf (stderr
, _("warning: "));
136 SH_VA_START (args
, format
);
138 vfprintf (stderr
, format
, args
);
140 fprintf (stderr
, "\n");
143 /* Print a usage summary for the currently-executing builtin command. */
147 if (this_command_name
&& *this_command_name
)
148 fprintf (stderr
, _("%s: usage: "), this_command_name
);
149 fprintf (stderr
, "%s\n", _(current_builtin
->short_doc
));
153 /* Return if LIST is NULL else barf and jump to top_level. Used by some
154 builtins that do not accept arguments. */
161 builtin_error (_("too many arguments"));
162 top_level_cleanup ();
163 jump_to_top_level (DISCARD
);
167 /* Check that no options were given to the currently-executing builtin,
168 and return 0 if there were options. */
175 reset_internal_getopt ();
176 if ((opt
= internal_getopt (list
, "")) != -1)
178 if (opt
== GETOPT_HELP
)
193 builtin_error (_("%s: option requires an argument"), s
);
200 builtin_error (_("%s: numeric argument required"), s
);
207 builtin_error (_("%s: not found"), s
);
210 /* Function called when one of the builtin commands detects an invalid
216 builtin_error (_("%s: invalid option"), s
);
220 sh_invalidoptname (s
)
223 builtin_error (_("%s: invalid option name"), s
);
230 builtin_error (_("`%s': not a valid identifier"), s
);
239 if (*s
== '0' && isdigit ((unsigned char)s
[1]))
240 msg
= _("invalid octal number");
241 else if (*s
== '0' && s
[1] == 'x')
242 msg
= _("invalid hex number");
244 msg
= _("invalid number");
245 builtin_error ("%s: %s", s
, msg
);
252 builtin_error (_("%s: invalid signal specification"), s
);
259 builtin_error (_("`%s': not a pid or valid job spec"), s
);
266 builtin_error (_("%s: readonly variable"), s
);
273 internal_error (_("%s: cannot assign"), s
); /* XXX */
281 builtin_error (_("%s: %s out of range"), s
, desc
? desc
: _("argument"));
283 builtin_error (_("%s out of range"), desc
? desc
: _("argument"));
286 #if defined (JOB_CONTROL)
291 builtin_error (_("%s: no such job"), s
);
299 builtin_error (_("%s: no job control"), s
);
301 builtin_error (_("no job control"));
305 #if defined (RESTRICTED_SHELL)
311 builtin_error (_("%s: restricted"), s
);
313 builtin_error (_("restricted"));
321 builtin_error (_("%s: not a shell builtin"), s
);
327 #if defined (DONT_REPORT_BROKEN_PIPE_WRITE_ERRORS) && defined (EPIPE)
329 #endif /* DONT_REPORT_BROKEN_PIPE_WRITE_ERRORS && EPIPE */
330 builtin_error (_("write error: %s"), strerror (errno
));
338 builtin_error (_("error setting terminal attributes: %s"), strerror (errno
));
340 builtin_error (_("error getting terminal attributes: %s"), strerror (errno
));
355 return (EXECUTION_FAILURE
);
360 /* **************************************************************** */
362 /* Shell positional parameter manipulation */
364 /* **************************************************************** */
366 /* Convert a WORD_LIST into a C-style argv. Return the number of elements
367 in the list in *IP, if IP is non-null. A convenience function for
368 loadable builtins; also used by `test'. */
370 make_builtin_argv (list
, ip
)
376 argv
= strvec_from_word_list (list
, 0, 1, ip
);
377 argv
[0] = this_command_name
;
381 /* Remember LIST in $1 ... $9, and REST_OF_ARGS. If DESTRUCTIVE is
382 non-zero, then discard whatever the existing arguments are, else
383 only discard the ones that are to be replaced. Set POSPARAM_COUNT
384 to the number of args assigned (length of LIST). */
386 remember_args (list
, destructive
)
394 for (i
= 1; i
< 10; i
++)
396 if ((destructive
|| list
) && dollar_vars
[i
])
398 free (dollar_vars
[i
]);
399 dollar_vars
[i
] = (char *)NULL
;
404 dollar_vars
[posparam_count
= i
] = savestring (list
->word
->word
);
409 /* If arguments remain, assign them to REST_OF_ARGS.
410 Note that copy_word_list (NULL) returns NULL, and
411 that dispose_words (NULL) does nothing. */
412 if (destructive
|| list
)
414 dispose_words (rest_of_args
);
415 rest_of_args
= copy_word_list (list
);
416 posparam_count
+= list_length (list
);
420 set_dollar_vars_changed ();
422 invalidate_cached_quoted_dollar_at ();
432 if (times
<= 0) /* caller should check */
438 free (dollar_vars
[1]);
440 for (count
= 1; count
< 9; count
++)
441 dollar_vars
[count
] = dollar_vars
[count
+ 1];
446 dollar_vars
[9] = savestring (temp
->word
->word
);
447 rest_of_args
= rest_of_args
->next
;
448 temp
->next
= (WORD_LIST
*)NULL
;
449 dispose_words (temp
);
452 dollar_vars
[9] = (char *)NULL
;
462 register WORD_LIST
*list
;
465 for (n
= 0; n
< 9 && dollar_vars
[n
+1]; n
++)
467 for (list
= rest_of_args
; list
; list
= list
->next
)
470 if (n
!= posparam_count
)
471 itrace("number_of_args: n (%d) != posparam_count (%d)", n
, posparam_count
);
473 return posparam_count
;
477 static int changed_dollar_vars
;
479 /* Have the dollar variables been reset to new values since we last
482 dollar_vars_changed ()
484 return (changed_dollar_vars
);
488 set_dollar_vars_unchanged ()
490 changed_dollar_vars
= 0;
494 set_dollar_vars_changed ()
496 if (variable_context
)
497 changed_dollar_vars
|= ARGS_FUNC
;
498 else if (this_shell_builtin
== set_builtin
)
499 changed_dollar_vars
|= ARGS_SETBLTIN
;
501 changed_dollar_vars
|= ARGS_INVOC
;
504 /* **************************************************************** */
506 /* Validating numeric input and arguments */
508 /* **************************************************************** */
510 /* Read a numeric arg for this_command_name, the name of the shell builtin
511 that wants it. LIST is the word list that the arg is to come from.
512 Accept only the numeric argument; report an error if other arguments
513 follow. If FATAL is 1, call throw_to_top_level, which exits the
514 shell; if it's 2, call jump_to_top_level (DISCARD), which aborts the
515 current command; if FATAL is 0, return an indication of an invalid
516 number by setting *NUMOK == 0 and return -1. */
518 get_numeric_arg (list
, fatal
, count
)
528 if (list
&& list
->word
&& ISOPTION (list
->word
->word
, '-'))
533 arg
= list
->word
->word
;
534 if (arg
== 0 || (legal_number (arg
, count
) == 0))
536 sh_neednumarg (list
->word
->word
? list
->word
->word
: "`'");
539 else if (fatal
== 1) /* fatal == 1; abort */
540 throw_to_top_level ();
541 else /* fatal == 2; discard current command */
543 top_level_cleanup ();
544 jump_to_top_level (DISCARD
);
547 no_args (list
->next
);
553 /* Get an eight-bit status value from LIST */
562 if (list
&& list
->word
&& ISOPTION (list
->word
->word
, '-'))
567 /* If we're not running the DEBUG trap, the return builtin, when not
568 given any arguments, uses the value of $? before the trap ran. If
569 given an argument, return uses it. This means that the trap can't
570 change $?. The DEBUG trap gets to change $?, though, since that is
571 part of its reason for existing, and because the extended debug mode
572 does things with the return value. */
573 if (this_shell_builtin
== return_builtin
&& running_trap
> 0 && running_trap
!= DEBUG_TRAP
+1)
574 return (trap_saved_exit_value
);
575 return (last_command_exit_value
);
578 arg
= list
->word
->word
;
579 if (arg
== 0 || legal_number (arg
, &sval
) == 0)
581 sh_neednumarg (list
->word
->word
? list
->word
->word
: "`'");
584 no_args (list
->next
);
590 /* Return the octal number parsed from STRING, or -1 to indicate
591 that the string contained a bad number. */
599 while (*string
&& ISOCTAL (*string
))
602 result
= (result
* 8) + (*string
++ - '0');
607 if (digits
== 0 || *string
)
613 /* **************************************************************** */
615 /* Manipulating the current working directory */
617 /* **************************************************************** */
619 /* Return a consed string which is the current working directory.
620 FOR_WHOM is the name of the caller for error printing. */
621 char *the_current_working_directory
= (char *)NULL
;
624 get_working_directory (for_whom
)
627 if (no_symbolic_links
)
629 FREE (the_current_working_directory
);
630 the_current_working_directory
= (char *)NULL
;
633 if (the_current_working_directory
== 0)
635 #if defined (GETCWD_BROKEN)
636 the_current_working_directory
= getcwd (0, PATH_MAX
);
638 the_current_working_directory
= getcwd (0, 0);
640 if (the_current_working_directory
== 0)
642 fprintf (stderr
, _("%s: error retrieving current directory: %s: %s\n"),
643 (for_whom
&& *for_whom
) ? for_whom
: get_name_for_error (),
644 _(bash_getcwd_errstr
), strerror (errno
));
649 return (savestring (the_current_working_directory
));
652 /* Make NAME our internal idea of the current working directory. */
654 set_working_directory (name
)
657 FREE (the_current_working_directory
);
658 the_current_working_directory
= savestring (name
);
661 /* **************************************************************** */
663 /* Job control support functions */
665 /* **************************************************************** */
667 #if defined (JOB_CONTROL)
669 get_job_by_name (name
, flags
)
673 register int i
, wl
, cl
, match
, job
;
679 for (i
= js
.j_jobslots
- 1; i
>= 0; i
--)
681 j
= get_job_by_jid (i
);
682 if (j
== 0 || ((flags
& JM_STOPPED
) && J_JOBSTATE(j
) != JSTOPPED
))
688 if (flags
& JM_EXACT
)
690 cl
= strlen (p
->command
);
691 match
= STREQN (p
->command
, name
, cl
);
693 else if (flags
& JM_SUBSTRING
)
694 match
= strcasestr (p
->command
, name
) != (char *)0;
696 match
= STREQN (p
->command
, name
, wl
);
703 else if (flags
& JM_FIRSTMATCH
)
704 return i
; /* return first match */
705 else if (job
!= NO_JOB
)
707 if (this_shell_builtin
)
708 builtin_error (_("%s: ambiguous job spec"), name
);
710 internal_error (_("%s: ambiguous job spec"), name
);
716 while (p
!= j
->pipe
);
722 /* Return the job spec found in LIST. */
731 return (js
.j_current
);
733 word
= list
->word
->word
;
741 if (DIGIT (*word
) && all_digits (word
))
744 return ((job
< 0 || job
> js
.j_jobslots
) ? NO_JOB
: job
- 1);
753 return (js
.j_current
);
756 return (js
.j_previous
);
758 case '?': /* Substring search requested. */
759 jflags
|= JM_SUBSTRING
;
764 return get_job_by_name (word
, jflags
);
767 #endif /* JOB_CONTROL */
770 * NOTE: `kill' calls this function with forcecols == 0
773 display_signal_list (list
, forcecols
)
777 register int i
, column
;
779 int result
, signum
, dflags
;
782 result
= EXECUTION_SUCCESS
;
785 for (i
= 1, column
= 0; i
< NSIG
; i
++)
787 name
= signal_name (i
);
788 if (STREQN (name
, "SIGJUNK", 7) || STREQN (name
, "Unknown", 7))
791 if (posixly_correct
&& !forcecols
)
793 /* This is for the kill builtin. POSIX.2 says the signal names
794 are displayed without the `SIG' prefix. */
795 if (STREQN (name
, "SIG", 3))
797 printf ("%s%s", name
, (i
== NSIG
- 1) ? "" : " ");
801 printf ("%2d) %s", i
, name
);
813 if ((posixly_correct
&& !forcecols
) || column
!= 0)
818 /* List individual signal names or numbers. */
821 if (legal_number (list
->word
->word
, &lsignum
))
823 /* This is specified by Posix.2 so that exit statuses can be
824 mapped into signal numbers. */
827 if (lsignum
< 0 || lsignum
>= NSIG
)
829 sh_invalidsig (list
->word
->word
);
830 result
= EXECUTION_FAILURE
;
836 name
= signal_name (signum
);
837 if (STREQN (name
, "SIGJUNK", 7) || STREQN (name
, "Unknown", 7))
842 /* POSIX.2 says that `kill -l signum' prints the signal name without
844 printf ("%s\n", (this_shell_builtin
== kill_builtin
&& signum
> 0) ? name
+ 3 : name
);
848 dflags
= DSIG_NOCASE
;
849 if (posixly_correct
== 0 || this_shell_builtin
!= kill_builtin
)
850 dflags
|= DSIG_SIGPREFIX
;
851 signum
= decode_signal (list
->word
->word
, dflags
);
852 if (signum
== NO_SIG
)
854 sh_invalidsig (list
->word
->word
);
855 result
= EXECUTION_FAILURE
;
859 printf ("%d\n", signum
);
866 /* **************************************************************** */
868 /* Finding builtin commands and their functions */
870 /* **************************************************************** */
872 /* Perform a binary search and return the address of the builtin function
873 whose name is NAME. If the function couldn't be found, or the builtin
874 is disabled or has no function associated with it, return NULL.
875 Return the address of the builtin.
876 DISABLED_OKAY means find it even if the builtin is disabled. */
878 builtin_address_internal (name
, disabled_okay
)
884 hi
= num_shell_builtins
- 1;
891 j
= shell_builtins
[mid
].name
[0] - name
[0];
894 j
= strcmp (shell_builtins
[mid
].name
, name
);
898 /* It must have a function pointer. It must be enabled, or we
899 must have explicitly allowed disabled functions to be found,
900 and it must not have been deleted. */
901 if (shell_builtins
[mid
].function
&&
902 ((shell_builtins
[mid
].flags
& BUILTIN_DELETED
) == 0) &&
903 ((shell_builtins
[mid
].flags
& BUILTIN_ENABLED
) || disabled_okay
))
904 return (&shell_builtins
[mid
]);
906 return ((struct builtin
*)NULL
);
913 return ((struct builtin
*)NULL
);
916 /* Return the pointer to the function implementing builtin command NAME. */
918 find_shell_builtin (name
)
921 current_builtin
= builtin_address_internal (name
, 0);
922 return (current_builtin
? current_builtin
->function
: (sh_builtin_func_t
*)NULL
);
925 /* Return the address of builtin with NAME, whether it is enabled or not. */
927 builtin_address (name
)
930 current_builtin
= builtin_address_internal (name
, 1);
931 return (current_builtin
? current_builtin
->function
: (sh_builtin_func_t
*)NULL
);
934 /* Return the function implementing the builtin NAME, but only if it is a
935 POSIX.2 special builtin. */
937 find_special_builtin (name
)
940 current_builtin
= builtin_address_internal (name
, 0);
941 return ((current_builtin
&& (current_builtin
->flags
& SPECIAL_BUILTIN
)) ?
942 current_builtin
->function
:
943 (sh_builtin_func_t
*)NULL
);
947 shell_builtin_compare (sbp1
, sbp2
)
948 struct builtin
*sbp1
, *sbp2
;
952 if ((result
= sbp1
->name
[0] - sbp2
->name
[0]) == 0)
953 result
= strcmp (sbp1
->name
, sbp2
->name
);
958 /* Sort the table of shell builtins so that the binary search will work
959 in find_shell_builtin. */
961 initialize_shell_builtins ()
963 qsort (shell_builtins
, num_shell_builtins
, sizeof (struct builtin
),
964 (QSFUNC
*)shell_builtin_compare
);
967 #if !defined (HELP_BUILTIN)
971 printf ("%s: %s\n", this_command_name
, _("help not available in this version"));
975 /* **************************************************************** */
977 /* Variable assignments during builtin commands */
979 /* **************************************************************** */
981 /* Assign NAME=VALUE, passing FLAGS to the assignment functions. */
983 builtin_bind_variable (name
, value
, flags
)
989 int vflags
, bindflags
;
991 #if defined (ARRAY_VARS)
992 /* Callers are responsible for calling this with array references that have
993 already undergone valid_array_reference checks (read, printf). */
994 vflags
= assoc_expand_once
? (VA_NOEXPAND
|VA_ONEWORD
) : 0;
995 bindflags
= flags
| (assoc_expand_once
? ASS_NOEXPAND
: 0) | ASS_ALLOWALLSUB
;
996 if (flags
& ASS_NOEXPAND
)
997 vflags
|= VA_NOEXPAND
;
998 if (flags
& ASS_ONEWORD
)
999 vflags
|= VA_ONEWORD
;
1001 if (valid_array_reference (name
, vflags
) == 0)
1002 v
= bind_variable (name
, value
, flags
);
1004 v
= assign_array_element (name
, value
, bindflags
, (array_eltstate_t
*)0);
1005 #else /* !ARRAY_VARS */
1006 v
= bind_variable (name
, value
, flags
);
1007 #endif /* !ARRAY_VARS */
1009 if (v
&& readonly_p (v
) == 0 && noassign_p (v
) == 0)
1010 VUNSETATTR (v
, att_invisible
);
1016 builtin_bind_var_to_int (name
, val
, flags
)
1023 v
= bind_var_to_int (name
, val
, flags
|ASS_ALLOWALLSUB
);
1027 #if defined (ARRAY_VARS)
1029 builtin_find_indexed_array (array_name
, flags
)
1035 if ((flags
& 2) && legal_identifier (array_name
) == 0)
1037 sh_invalidid (array_name
);
1038 return (SHELL_VAR
*)NULL
;
1041 entry
= find_or_make_array_variable (array_name
, 1);
1042 /* With flags argument & 1, find_or_make_array_variable checks for readonly
1043 and noassign variables and prints error messages. */
1046 else if (array_p (entry
) == 0)
1048 builtin_error (_("%s: not an indexed array"), array_name
);
1049 return (SHELL_VAR
*)NULL
;
1051 else if (invisible_p (entry
))
1052 VUNSETATTR (entry
, att_invisible
); /* no longer invisible */
1055 array_flush (array_cell (entry
));
1059 #endif /* ARRAY_VARS */
1061 /* Like check_unbind_variable, but for use by builtins (only matters for
1064 builtin_unbind_variable (vname
)
1069 v
= find_variable (vname
);
1070 if (v
&& readonly_p (v
))
1072 builtin_error (_("%s: cannot unset: readonly %s"), vname
, "variable");
1075 else if (v
&& non_unsettable_p (v
))
1077 builtin_error (_("%s: cannot unset"), vname
);
1080 return (unbind_variable (vname
));
1084 builtin_arrayref_flags (w
, baseflags
)
1093 /* Don't require assoc_expand_once if we have an argument that's already
1094 passed through valid_array_reference and been expanded once. That
1095 doesn't protect it from normal expansions like word splitting, so
1096 proper quoting is still required. */
1097 if (w
->flags
& W_ARRAYREF
)
1098 vflags
|= VA_ONEWORD
|VA_NOEXPAND
;
1101 /* This is a little sketchier but handles quoted arguments. */
1102 if (assoc_expand_once
&& (t
= strchr (w
->word
, '[')) && t
[strlen(t
) - 1] == ']')
1103 vflags
|= VA_ONEWORD
|VA_NOEXPAND
;
1109 /* **************************************************************** */
1111 /* External interface to manipulate shell options */
1113 /* **************************************************************** */
1115 #if defined (ARRAY_VARS)
1117 set_expand_once (nval
, uwp
)
1122 oa
= assoc_expand_once
;
1123 if (shell_compatibility_level
> 51) /* XXX - internal */
1126 unwind_protect_int (assoc_expand_once
);
1127 assoc_expand_once
= nval
;