1 /* variables.c -- Functions for hacking shell variables. */
3 /* Copyright (C) 1987-2016 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 #include "bashtypes.h"
24 #include "posixstat.h"
25 #include "posixtime.h"
28 # if defined (__QNXNTO__)
29 # include <sys/netmgr.h>
32 # endif /* !__QNXNTO__ */
35 #if defined (HAVE_UNISTD_H)
40 #include "chartypes.h"
41 #if defined (HAVE_PWD_H)
47 #define NEED_XTRACE_SET_DECL
51 #include "execute_cmd.h"
53 #include "mailcheck.h"
62 #include "builtins/getopt.h"
63 #include "builtins/common.h"
64 #include "builtins/builtext.h"
66 #if defined (READLINE)
67 # include "bashline.h"
68 # include <readline/readline.h>
70 # include <tilde/tilde.h>
74 # include "bashhist.h"
75 # include <readline/history.h>
78 #if defined (PROGRAMMABLE_COMPLETION)
79 # include "pcomplete.h"
82 #define VARIABLES_HASH_BUCKETS 1024 /* must be power of two */
83 #define FUNCTIONS_HASH_BUCKETS 512
84 #define TEMPENV_HASH_BUCKETS 4 /* must be power of two */
86 #define BASHFUNC_PREFIX "BASH_FUNC_"
87 #define BASHFUNC_PREFLEN 10 /* == strlen(BASHFUNC_PREFIX */
88 #define BASHFUNC_SUFFIX "%%"
89 #define BASHFUNC_SUFFLEN 2 /* == strlen(BASHFUNC_SUFFIX) */
91 /* flags for find_variable_internal */
93 #define FV_FORCETEMPENV 0x01
94 #define FV_SKIPINVISIBLE 0x02
96 extern char **environ
;
98 /* Variables used here and defined in other files. */
99 extern int posixly_correct
;
100 extern int line_number
, line_number_base
;
101 extern int subshell_environment
, indirection_level
, subshell_level
;
102 extern int build_version
, patch_level
;
103 extern int expanding_redir
;
104 extern int last_command_exit_value
;
105 extern char *dist_version
, *release_status
;
106 extern char *shell_name
;
107 extern char *primary_prompt
, *secondary_prompt
;
108 extern char *current_host_name
;
109 extern sh_builtin_func_t
*this_shell_builtin
;
110 extern SHELL_VAR
*this_shell_function
;
111 extern char *the_printed_command_except_trap
;
112 extern char *this_command_name
;
113 extern char *command_execution_string
;
114 extern time_t shell_start_time
;
115 extern int assigning_in_environment
;
116 extern int executing_builtin
;
117 extern int funcnest_max
;
119 #if defined (READLINE)
120 extern int no_line_editing
;
121 extern int perform_hostname_completion
;
124 /* The list of shell variables that the user has created at the global
125 scope, or that came from the environment. */
126 VAR_CONTEXT
*global_variables
= (VAR_CONTEXT
*)NULL
;
128 /* The current list of shell variables, including function scopes */
129 VAR_CONTEXT
*shell_variables
= (VAR_CONTEXT
*)NULL
;
131 /* The list of shell functions that the user has created, or that came from
133 HASH_TABLE
*shell_functions
= (HASH_TABLE
*)NULL
;
135 #if defined (DEBUGGER)
136 /* The table of shell function definitions that the user defined or that
137 came from the environment. */
138 HASH_TABLE
*shell_function_defs
= (HASH_TABLE
*)NULL
;
141 /* The current variable context. This is really a count of how deep into
142 executing functions we are. */
143 int variable_context
= 0;
145 /* The set of shell assignments which are made only in the environment
146 for a single command. */
147 HASH_TABLE
*temporary_env
= (HASH_TABLE
*)NULL
;
149 /* Set to non-zero if an assignment error occurs while putting variables
150 into the temporary environment. */
151 int tempenv_assign_error
;
153 /* Some funky variables which are known about specially. Here is where
154 "$*", "$1", and all the cruft is kept. */
155 char *dollar_vars
[10];
156 WORD_LIST
*rest_of_args
= (WORD_LIST
*)NULL
;
158 /* The value of $$. */
159 pid_t dollar_dollar_pid
;
161 /* Non-zero means that we have to remake EXPORT_ENV. */
162 int array_needs_making
= 1;
164 /* The number of times BASH has been executed. This is set
165 by initialize_variables (). */
168 /* An array which is passed to commands as their environment. It is
169 manufactured from the union of the initial environment and the
170 shell variables that are marked for export. */
171 char **export_env
= (char **)NULL
;
172 static int export_env_index
;
173 static int export_env_size
;
175 #if defined (READLINE)
176 static int winsize_assignment
; /* currently assigning to LINES or COLUMNS */
179 SHELL_VAR nameref_invalid_value
;
180 static SHELL_VAR nameref_maxloop_value
;
182 static HASH_TABLE
*last_table_searched
; /* hash_lookup sets this */
184 /* Some forward declarations. */
185 static void create_variable_tables
__P((void));
187 static void set_machine_vars
__P((void));
188 static void set_home_var
__P((void));
189 static void set_shell_var
__P((void));
190 static char *get_bash_name
__P((void));
191 static void initialize_shell_level
__P((void));
192 static void uidset
__P((void));
193 #if defined (ARRAY_VARS)
194 static void make_vers_array
__P((void));
197 static SHELL_VAR
*null_assign
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
198 #if defined (ARRAY_VARS)
199 static SHELL_VAR
*null_array_assign
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
201 static SHELL_VAR
*get_self
__P((SHELL_VAR
*));
203 #if defined (ARRAY_VARS)
204 static SHELL_VAR
*init_dynamic_array_var
__P((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
205 static SHELL_VAR
*init_dynamic_assoc_var
__P((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
208 static SHELL_VAR
*assign_seconds
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
209 static SHELL_VAR
*get_seconds
__P((SHELL_VAR
*));
210 static SHELL_VAR
*init_seconds_var
__P((void));
212 static int brand
__P((void));
213 static void sbrand
__P((unsigned long)); /* set bash random number generator. */
214 static void seedrand
__P((void)); /* seed generator randomly */
215 static SHELL_VAR
*assign_random
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
216 static SHELL_VAR
*get_random
__P((SHELL_VAR
*));
218 static SHELL_VAR
*assign_lineno
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
219 static SHELL_VAR
*get_lineno
__P((SHELL_VAR
*));
221 static SHELL_VAR
*assign_subshell
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
222 static SHELL_VAR
*get_subshell
__P((SHELL_VAR
*));
224 static SHELL_VAR
*get_bashpid
__P((SHELL_VAR
*));
226 #if defined (HISTORY)
227 static SHELL_VAR
*get_histcmd
__P((SHELL_VAR
*));
230 #if defined (READLINE)
231 static SHELL_VAR
*get_comp_wordbreaks
__P((SHELL_VAR
*));
232 static SHELL_VAR
*assign_comp_wordbreaks
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
235 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
236 static SHELL_VAR
*assign_dirstack
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
237 static SHELL_VAR
*get_dirstack
__P((SHELL_VAR
*));
240 #if defined (ARRAY_VARS)
241 static SHELL_VAR
*get_groupset
__P((SHELL_VAR
*));
243 static SHELL_VAR
*build_hashcmd
__P((SHELL_VAR
*));
244 static SHELL_VAR
*get_hashcmd
__P((SHELL_VAR
*));
245 static SHELL_VAR
*assign_hashcmd
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
247 static SHELL_VAR
*build_aliasvar
__P((SHELL_VAR
*));
248 static SHELL_VAR
*get_aliasvar
__P((SHELL_VAR
*));
249 static SHELL_VAR
*assign_aliasvar
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
253 static SHELL_VAR
*get_funcname
__P((SHELL_VAR
*));
254 static SHELL_VAR
*init_funcname_var
__P((void));
256 static void initialize_dynamic_variables
__P((void));
258 static SHELL_VAR
*hash_lookup
__P((const char *, HASH_TABLE
*));
259 static SHELL_VAR
*new_shell_variable
__P((const char *));
260 static SHELL_VAR
*make_new_variable
__P((const char *, HASH_TABLE
*));
261 static SHELL_VAR
*bind_variable_internal
__P((const char *, char *, HASH_TABLE
*, int, int));
263 static void dispose_variable_value
__P((SHELL_VAR
*));
264 static void free_variable_hash_data
__P((PTR_T
));
266 static VARLIST
*vlist_alloc
__P((int));
267 static VARLIST
*vlist_realloc
__P((VARLIST
*, int));
268 static void vlist_add
__P((VARLIST
*, SHELL_VAR
*, int));
270 static void flatten
__P((HASH_TABLE
*, sh_var_map_func_t
*, VARLIST
*, int));
272 static int qsort_var_comp
__P((SHELL_VAR
**, SHELL_VAR
**));
274 static SHELL_VAR
**vapply
__P((sh_var_map_func_t
*));
275 static SHELL_VAR
**fapply
__P((sh_var_map_func_t
*));
277 static int visible_var
__P((SHELL_VAR
*));
278 static int visible_and_exported
__P((SHELL_VAR
*));
279 static int export_environment_candidate
__P((SHELL_VAR
*));
280 static int local_and_exported
__P((SHELL_VAR
*));
281 static int variable_in_context
__P((SHELL_VAR
*));
282 #if defined (ARRAY_VARS)
283 static int visible_array_vars
__P((SHELL_VAR
*));
286 static SHELL_VAR
*find_variable_internal
__P((const char *, int));
288 static SHELL_VAR
*find_nameref_at_context
__P((SHELL_VAR
*, VAR_CONTEXT
*));
289 static SHELL_VAR
*find_variable_nameref_context
__P((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
290 static SHELL_VAR
*find_variable_last_nameref_context
__P((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
292 static SHELL_VAR
*bind_tempenv_variable
__P((const char *, char *));
293 static void push_temp_var
__P((PTR_T
));
294 static void propagate_temp_var
__P((PTR_T
));
295 static void dispose_temporary_env
__P((sh_free_func_t
*));
297 static inline char *mk_env_string
__P((const char *, const char *, int));
298 static char **make_env_array_from_var_list
__P((SHELL_VAR
**));
299 static char **make_var_export_array
__P((VAR_CONTEXT
*));
300 static char **make_func_export_array
__P((void));
301 static void add_temp_array_to_env
__P((char **, int, int));
303 static int n_shell_variables
__P((void));
304 static int set_context
__P((SHELL_VAR
*));
306 static void push_func_var
__P((PTR_T
));
307 static void push_exported_var
__P((PTR_T
));
309 static inline int find_special_var
__P((const char *));
312 create_variable_tables ()
314 if (shell_variables
== 0)
316 shell_variables
= global_variables
= new_var_context ((char *)NULL
, 0);
317 shell_variables
->scope
= 0;
318 shell_variables
->table
= hash_create (VARIABLES_HASH_BUCKETS
);
321 if (shell_functions
== 0)
322 shell_functions
= hash_create (FUNCTIONS_HASH_BUCKETS
);
324 #if defined (DEBUGGER)
325 if (shell_function_defs
== 0)
326 shell_function_defs
= hash_create (FUNCTIONS_HASH_BUCKETS
);
330 /* Initialize the shell variables from the current environment.
331 If PRIVMODE is nonzero, don't import functions from ENV or
334 initialize_shell_variables (env
, privmode
)
338 char *name
, *string
, *temp_string
;
339 int c
, char_index
, string_index
, string_length
, ro
;
342 create_variable_tables ();
344 for (string_index
= 0; env
&& (string
= env
[string_index
++]); )
348 while ((c
= *string
++) && c
!= '=')
350 if (string
[-1] == '=')
351 char_index
= string
- name
- 1;
353 /* If there are weird things in the environment, like `=xxx' or a
354 string without an `=', just skip them. */
358 /* ASSERT(name[char_index] == '=') */
359 name
[char_index
] = '\0';
360 /* Now, name = env variable name, string = env variable value, and
361 char_index == strlen (name) */
363 temp_var
= (SHELL_VAR
*)NULL
;
365 #if defined (FUNCTION_IMPORT)
366 /* If exported function, define it now. Don't import functions from
367 the environment in privileged mode. */
368 if (privmode
== 0 && read_but_dont_execute
== 0 &&
369 STREQN (BASHFUNC_PREFIX
, name
, BASHFUNC_PREFLEN
) &&
370 STREQ (BASHFUNC_SUFFIX
, name
+ char_index
- BASHFUNC_SUFFLEN
) &&
371 STREQN ("() {", string
, 4))
374 char *tname
; /* desired imported function name */
376 namelen
= char_index
- BASHFUNC_PREFLEN
- BASHFUNC_SUFFLEN
;
378 tname
= name
+ BASHFUNC_PREFLEN
; /* start of func name */
379 tname
[namelen
] = '\0'; /* now tname == func name */
381 string_length
= strlen (string
);
382 temp_string
= (char *)xmalloc (namelen
+ string_length
+ 2);
384 memcpy (temp_string
, tname
, namelen
);
385 temp_string
[namelen
] = ' ';
386 memcpy (temp_string
+ namelen
+ 1, string
, string_length
+ 1);
388 /* Don't import function names that are invalid identifiers from the
389 environment in posix mode, though we still allow them to be defined as
391 if (absolute_program (tname
) == 0 && (posixly_correct
== 0 || legal_identifier (tname
)))
392 parse_and_execute (temp_string
, tname
, SEVAL_NONINT
|SEVAL_NOHIST
|SEVAL_FUNCDEF
|SEVAL_ONECMD
);
394 free (temp_string
); /* parse_and_execute does this */
396 if (temp_var
= find_function (tname
))
398 VSETATTR (temp_var
, (att_exported
|att_imported
));
399 array_needs_making
= 1;
403 if (temp_var
= bind_variable (name
, string
, 0))
405 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
406 array_needs_making
= 1;
408 last_command_exit_value
= 1;
409 report_error (_("error importing function definition for `%s'"), tname
);
412 /* Restore original suffix */
413 tname
[namelen
] = BASHFUNC_SUFFIX
[0];
416 #endif /* FUNCTION_IMPORT */
417 #if defined (ARRAY_VARS)
419 /* Array variables may not yet be exported. */
420 if (*string
== '(' && string
[1] == '[' && string
[strlen (string
) - 1] == ')')
423 temp_string
= extract_array_assignment_list (string
, &string_length
);
424 temp_var
= assign_array_from_string (name
, temp_string
, 0);
426 VSETATTR (temp_var
, (att_exported
| att_imported
));
427 array_needs_making
= 1;
430 # endif /* ARRAY_EXPORT */
434 if (posixly_correct
&& STREQ (name
, "SHELLOPTS"))
436 temp_var
= find_variable ("SHELLOPTS");
437 ro
= temp_var
&& readonly_p (temp_var
);
439 VUNSETATTR (temp_var
, att_readonly
);
441 temp_var
= bind_variable (name
, string
, 0);
444 if (legal_identifier (name
))
445 VSETATTR (temp_var
, (att_exported
| att_imported
));
447 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
449 VSETATTR (temp_var
, att_readonly
);
450 array_needs_making
= 1;
454 name
[char_index
] = '=';
455 /* temp_var can be NULL if it was an exported function with a syntax
456 error (a different bug, but it still shouldn't dump core). */
457 if (temp_var
&& function_p (temp_var
) == 0) /* XXX not yet */
459 CACHE_IMPORTSTR (temp_var
, name
);
465 /* Set up initial value of $_ */
466 temp_var
= set_if_not ("_", dollar_vars
[0]);
468 /* Remember this pid. */
469 dollar_dollar_pid
= getpid ();
471 /* Now make our own defaults in case the vars that we think are
472 important are missing. */
473 temp_var
= set_if_not ("PATH", DEFAULT_PATH_VALUE
);
475 set_auto_export (temp_var
); /* XXX */
478 temp_var
= set_if_not ("TERM", "dumb");
480 set_auto_export (temp_var
); /* XXX */
483 #if defined (__QNX__)
484 /* set node id -- don't import it from the environment */
487 # if defined (__QNXNTO__)
488 netmgr_ndtostr(ND2S_LOCAL_STR
, ND_LOCAL_NODE
, node_name
, sizeof(node_name
));
490 qnx_nidtostr (getnid (), node_name
, sizeof (node_name
));
492 temp_var
= bind_variable ("NODE", node_name
, 0);
494 set_auto_export (temp_var
);
498 /* set up the prompts. */
499 if (interactive_shell
)
501 #if defined (PROMPT_STRING_DECODE)
502 set_if_not ("PS1", primary_prompt
);
504 if (current_user
.uid
== -1)
505 get_current_user_info ();
506 set_if_not ("PS1", current_user
.euid
== 0 ? "# " : primary_prompt
);
508 set_if_not ("PS2", secondary_prompt
);
511 if (current_user
.euid
== 0)
512 bind_variable ("PS4", "+ ", 0);
514 set_if_not ("PS4", "+ ");
516 /* Don't allow IFS to be imported from the environment. */
517 temp_var
= bind_variable ("IFS", " \t\n", 0);
520 /* Magic machine types. Pretty convenient. */
523 /* Default MAILCHECK for interactive shells. Defer the creation of a
524 default MAILPATH until the startup files are read, because MAIL
525 names a mail file if MAILPATH is not set, and we should provide a
526 default only if neither is set. */
527 if (interactive_shell
)
529 temp_var
= set_if_not ("MAILCHECK", posixly_correct
? "600" : "60");
530 VSETATTR (temp_var
, att_integer
);
533 /* Do some things with shell level. */
534 initialize_shell_level ();
538 /* Initialize the `getopts' stuff. */
539 temp_var
= bind_variable ("OPTIND", "1", 0);
540 VSETATTR (temp_var
, att_integer
);
542 bind_variable ("OPTERR", "1", 0);
545 if (login_shell
== 1 && posixly_correct
== 0)
548 /* Get the full pathname to THIS shell, and set the BASH variable
550 name
= get_bash_name ();
551 temp_var
= bind_variable ("BASH", name
, 0);
554 /* Make the exported environment variable SHELL be the user's login
555 shell. Note that the `tset' command looks at this variable
556 to determine what style of commands to output; if it ends in "csh",
557 then C-shell commands are output, else Bourne shell commands. */
560 /* Make a variable called BASH_VERSION which contains the version info. */
561 bind_variable ("BASH_VERSION", shell_version_string (), 0);
562 #if defined (ARRAY_VARS)
566 if (command_execution_string
)
567 bind_variable ("BASH_EXECUTION_STRING", command_execution_string
, 0);
569 /* Find out if we're supposed to be in Posix.2 mode via an
570 environment variable. */
571 temp_var
= find_variable ("POSIXLY_CORRECT");
573 temp_var
= find_variable ("POSIX_PEDANTIC");
574 if (temp_var
&& imported_p (temp_var
))
575 sv_strict_posix (temp_var
->name
);
577 #if defined (HISTORY)
578 /* Set history variables to defaults, and then do whatever we would
579 do if the variable had just been set. Do this only in the case
580 that we are remembering commands on the history list. */
581 if (remember_on_history
)
583 name
= bash_tilde_expand (posixly_correct
? "~/.sh_history" : "~/.bash_history", 0);
585 set_if_not ("HISTFILE", name
);
590 /* Seed the random number generator. */
593 /* Handle some "special" variables that we may have inherited from a
595 if (interactive_shell
)
597 temp_var
= find_variable ("IGNOREEOF");
599 temp_var
= find_variable ("ignoreeof");
600 if (temp_var
&& imported_p (temp_var
))
601 sv_ignoreeof (temp_var
->name
);
604 #if defined (HISTORY)
605 if (interactive_shell
&& remember_on_history
)
607 sv_history_control ("HISTCONTROL");
608 sv_histignore ("HISTIGNORE");
609 sv_histtimefmt ("HISTTIMEFORMAT");
613 #if defined (READLINE) && defined (STRICT_POSIX)
614 /* POSIXLY_CORRECT will only be 1 here if the shell was compiled
616 if (interactive_shell
&& posixly_correct
&& no_line_editing
== 0)
617 rl_prefer_env_winsize
= 1;
618 #endif /* READLINE && STRICT_POSIX */
623 * I'm tired of the arguing and bug reports. Bash now leaves SSH_CLIENT
624 * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in
625 * isnetconn() to avoid running the startup files more often than wanted.
626 * That will, of course, only work if the user's login shell is bash, so
627 * I've made that behavior conditional on SSH_SOURCE_BASHRC being defined
631 temp_var
= find_variable ("SSH_CLIENT");
632 if (temp_var
&& imported_p (temp_var
))
634 VUNSETATTR (temp_var
, att_exported
);
635 array_needs_making
= 1;
637 temp_var
= find_variable ("SSH2_CLIENT");
638 if (temp_var
&& imported_p (temp_var
))
640 VUNSETATTR (temp_var
, att_exported
);
641 array_needs_making
= 1;
645 /* Get the user's real and effective user ids. */
648 temp_var
= find_variable ("BASH_XTRACEFD");
649 if (temp_var
&& imported_p (temp_var
))
650 sv_xtracefd (temp_var
->name
);
652 sv_shcompat ("BASH_COMPAT");
654 /* Allow FUNCNEST to be inherited from the environment. */
655 sv_funcnest ("FUNCNEST");
657 /* Initialize the dynamic variables, and seed their values. */
658 initialize_dynamic_variables ();
661 /* **************************************************************** */
663 /* Setting values for special shell variables */
665 /* **************************************************************** */
672 temp_var
= set_if_not ("HOSTTYPE", HOSTTYPE
);
673 temp_var
= set_if_not ("OSTYPE", OSTYPE
);
674 temp_var
= set_if_not ("MACHTYPE", MACHTYPE
);
676 temp_var
= set_if_not ("HOSTNAME", current_host_name
);
679 /* Set $HOME to the information in the password file if we didn't get
680 it from the environment. */
682 /* This function is not static so the tilde and readline libraries can
687 if (current_user
.home_dir
== 0)
688 get_current_user_info ();
689 return current_user
.home_dir
;
697 temp_var
= find_variable ("HOME");
699 temp_var
= bind_variable ("HOME", sh_get_home_dir (), 0);
701 VSETATTR (temp_var
, att_exported
);
705 /* Set $SHELL to the user's login shell if it is not already set. Call
706 get_current_user_info if we haven't already fetched the shell. */
712 temp_var
= find_variable ("SHELL");
715 if (current_user
.shell
== 0)
716 get_current_user_info ();
717 temp_var
= bind_variable ("SHELL", current_user
.shell
, 0);
720 VSETATTR (temp_var
, att_exported
);
729 if ((login_shell
== 1) && RELPATH(shell_name
))
731 if (current_user
.shell
== 0)
732 get_current_user_info ();
733 name
= savestring (current_user
.shell
);
735 else if (ABSPATH(shell_name
))
736 name
= savestring (shell_name
);
737 else if (shell_name
[0] == '.' && shell_name
[1] == '/')
739 /* Fast path for common case. */
743 cdir
= get_string_value ("PWD");
747 name
= (char *)xmalloc (len
+ strlen (shell_name
) + 1);
749 strcpy (name
+ len
, shell_name
+ 1);
752 name
= savestring (shell_name
);
759 tname
= find_user_command (shell_name
);
763 /* Try the current directory. If there is not an executable
764 there, just punt and use the login shell. */
765 s
= file_status (shell_name
);
768 tname
= make_absolute (shell_name
, get_string_value ("PWD"));
769 if (*shell_name
== '.')
771 name
= sh_canonpath (tname
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
782 if (current_user
.shell
== 0)
783 get_current_user_info ();
784 name
= savestring (current_user
.shell
);
789 name
= full_pathname (tname
);
798 adjust_shell_level (change
)
801 char new_level
[5], *old_SHLVL
;
805 old_SHLVL
= get_string_value ("SHLVL");
806 if (old_SHLVL
== 0 || *old_SHLVL
== '\0' || legal_number (old_SHLVL
, &old_level
) == 0)
809 shell_level
= old_level
+ change
;
812 else if (shell_level
>= 1000)
814 internal_warning (_("shell level (%d) too high, resetting to 1"), shell_level
);
818 /* We don't need the full generality of itos here. */
819 if (shell_level
< 10)
821 new_level
[0] = shell_level
+ '0';
824 else if (shell_level
< 100)
826 new_level
[0] = (shell_level
/ 10) + '0';
827 new_level
[1] = (shell_level
% 10) + '0';
830 else if (shell_level
< 1000)
832 new_level
[0] = (shell_level
/ 100) + '0';
833 old_level
= shell_level
% 100;
834 new_level
[1] = (old_level
/ 10) + '0';
835 new_level
[2] = (old_level
% 10) + '0';
839 temp_var
= bind_variable ("SHLVL", new_level
, 0);
840 set_auto_export (temp_var
);
844 initialize_shell_level ()
846 adjust_shell_level (1);
849 /* If we got PWD from the environment, update our idea of the current
850 working directory. In any case, make sure that PWD exists before
851 checking it. It is possible for getcwd () to fail on shell startup,
852 and in that case, PWD would be undefined. If this is an interactive
853 login shell, see if $HOME is the current working directory, and if
854 that's not the same string as $PWD, set PWD=$HOME. */
859 SHELL_VAR
*temp_var
, *home_var
;
860 char *temp_string
, *home_string
, *current_dir
;
862 home_var
= find_variable ("HOME");
863 home_string
= home_var
? value_cell (home_var
) : (char *)NULL
;
865 temp_var
= find_variable ("PWD");
866 /* Follow posix rules for importing PWD */
867 if (temp_var
&& imported_p (temp_var
) &&
868 (temp_string
= value_cell (temp_var
)) &&
869 temp_string
[0] == '/' &&
870 same_file (temp_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
872 current_dir
= sh_canonpath (temp_string
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
873 if (current_dir
== 0)
874 current_dir
= get_working_directory ("shell_init");
876 set_working_directory (current_dir
);
879 else if (home_string
&& interactive_shell
&& login_shell
&&
880 same_file (home_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
882 set_working_directory (home_string
);
883 temp_var
= bind_variable ("PWD", home_string
, 0);
884 set_auto_export (temp_var
);
888 temp_string
= get_working_directory ("shell-init");
891 temp_var
= bind_variable ("PWD", temp_string
, 0);
892 set_auto_export (temp_var
);
897 /* According to the Single Unix Specification, v2, $OLDPWD is an
898 `environment variable' and therefore should be auto-exported. If we
899 don't find OLDPWD in the environment, or it doesn't name a directory,
900 make a dummy invisible variable for OLDPWD, and mark it as exported. */
901 temp_var
= find_variable ("OLDPWD");
902 if (temp_var
== 0 || value_cell (temp_var
) == 0 || file_isdir (value_cell (temp_var
)) == 0)
904 temp_var
= bind_variable ("OLDPWD", (char *)NULL
, 0);
905 VSETATTR (temp_var
, (att_exported
| att_invisible
));
909 /* Make a variable $PPID, which holds the pid of the shell's parent. */
913 char namebuf
[INT_STRLEN_BOUND(pid_t
) + 1], *name
;
916 name
= inttostr (getppid (), namebuf
, sizeof(namebuf
));
917 temp_var
= find_variable ("PPID");
919 VUNSETATTR (temp_var
, (att_readonly
| att_exported
));
920 temp_var
= bind_variable ("PPID", name
, 0);
921 VSETATTR (temp_var
, (att_readonly
| att_integer
));
927 char buff
[INT_STRLEN_BOUND(uid_t
) + 1], *b
;
928 register SHELL_VAR
*v
;
930 b
= inttostr (current_user
.uid
, buff
, sizeof (buff
));
931 v
= find_variable ("UID");
934 v
= bind_variable ("UID", b
, 0);
935 VSETATTR (v
, (att_readonly
| att_integer
));
938 if (current_user
.euid
!= current_user
.uid
)
939 b
= inttostr (current_user
.euid
, buff
, sizeof (buff
));
941 v
= find_variable ("EUID");
944 v
= bind_variable ("EUID", b
, 0);
945 VSETATTR (v
, (att_readonly
| att_integer
));
949 #if defined (ARRAY_VARS)
955 char *s
, d
[32], b
[INT_STRLEN_BOUND(int) + 1];
957 unbind_variable_noref ("BASH_VERSINFO");
959 vv
= make_new_array_variable ("BASH_VERSINFO");
960 av
= array_cell (vv
);
961 strcpy (d
, dist_version
);
965 array_insert (av
, 0, d
);
966 array_insert (av
, 1, s
);
967 s
= inttostr (patch_level
, b
, sizeof (b
));
968 array_insert (av
, 2, s
);
969 s
= inttostr (build_version
, b
, sizeof (b
));
970 array_insert (av
, 3, s
);
971 array_insert (av
, 4, release_status
);
972 array_insert (av
, 5, MACHTYPE
);
974 VSETATTR (vv
, att_readonly
);
976 #endif /* ARRAY_VARS */
978 /* Set the environment variables $LINES and $COLUMNS in response to
979 a window size change. */
981 sh_set_lines_and_columns (lines
, cols
)
984 char val
[INT_STRLEN_BOUND(int) + 1], *v
;
986 #if defined (READLINE)
987 /* If we are currently assigning to LINES or COLUMNS, don't do anything. */
988 if (winsize_assignment
)
992 v
= inttostr (lines
, val
, sizeof (val
));
993 bind_variable ("LINES", v
, 0);
995 v
= inttostr (cols
, val
, sizeof (val
));
996 bind_variable ("COLUMNS", v
, 0);
999 /* **************************************************************** */
1001 /* Printing variables and values */
1003 /* **************************************************************** */
1005 /* Print LIST (a list of shell variables) to stdout in such a way that
1006 they can be read back in. */
1008 print_var_list (list
)
1009 register SHELL_VAR
**list
;
1012 register SHELL_VAR
*var
;
1014 for (i
= 0; list
&& (var
= list
[i
]); i
++)
1015 if (invisible_p (var
) == 0)
1016 print_assignment (var
);
1019 /* Print LIST (a list of shell functions) to stdout in such a way that
1020 they can be read back in. */
1022 print_func_list (list
)
1023 register SHELL_VAR
**list
;
1026 register SHELL_VAR
*var
;
1028 for (i
= 0; list
&& (var
= list
[i
]); i
++)
1030 printf ("%s ", var
->name
);
1031 print_var_function (var
);
1036 /* Print the value of a single SHELL_VAR. No newline is
1037 output, but the variable is printed in such a way that
1038 it can be read back in. */
1040 print_assignment (var
)
1043 if (var_isset (var
) == 0)
1046 if (function_p (var
))
1048 printf ("%s", var
->name
);
1049 print_var_function (var
);
1052 #if defined (ARRAY_VARS)
1053 else if (array_p (var
))
1054 print_array_assignment (var
, 0);
1055 else if (assoc_p (var
))
1056 print_assoc_assignment (var
, 0);
1057 #endif /* ARRAY_VARS */
1060 printf ("%s=", var
->name
);
1061 print_var_value (var
, 1);
1066 /* Print the value cell of VAR, a shell variable. Do not print
1067 the name, nor leading/trailing newline. If QUOTE is non-zero,
1068 and the value contains shell metacharacters, quote the value
1069 in such a way that it can be read back in. */
1071 print_var_value (var
, quote
)
1077 if (var_isset (var
) == 0)
1080 if (quote
&& posixly_correct
== 0 && ansic_shouldquote (value_cell (var
)))
1082 t
= ansic_quote (value_cell (var
), 0, (int *)0);
1086 else if (quote
&& sh_contains_shell_metas (value_cell (var
)))
1088 t
= sh_single_quote (value_cell (var
));
1093 printf ("%s", value_cell (var
));
1096 /* Print the function cell of VAR, a shell variable. Do not
1097 print the name, nor leading/trailing newline. */
1099 print_var_function (var
)
1104 if (function_p (var
) && var_isset (var
))
1106 x
= named_function_string ((char *)NULL
, function_cell(var
), FUNC_MULTILINE
|FUNC_EXTERNAL
);
1111 /* **************************************************************** */
1113 /* Dynamic Variables */
1115 /* **************************************************************** */
1117 /* DYNAMIC VARIABLES
1119 These are variables whose values are generated anew each time they are
1120 referenced. These are implemented using a pair of function pointers
1121 in the struct variable: assign_func, which is called from bind_variable
1122 and, if arrays are compiled into the shell, some of the functions in
1123 arrayfunc.c, and dynamic_value, which is called from find_variable.
1125 assign_func is called from bind_variable_internal, if
1126 bind_variable_internal discovers that the variable being assigned to
1127 has such a function. The function is called as
1128 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value, ind)
1129 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
1130 is usually ENTRY (self). IND is an index for an array variable, and
1133 dynamic_value is called from find_variable_internal to return a `new'
1134 value for the specified dynamic varible. If this function is NULL,
1135 the variable is treated as a `normal' shell variable. If it is not,
1136 however, then this function is called like this:
1137 tempvar = (*(var->dynamic_value)) (var);
1139 Sometimes `tempvar' will replace the value of `var'. Other times, the
1140 shell will simply use the string value. Pretty object-oriented, huh?
1142 Be warned, though: if you `unset' a special variable, it loses its
1143 special meaning, even if you subsequently set it.
1145 The special assignment code would probably have been better put in
1146 subst.c: do_assignment_internal, in the same style as
1147 stupidly_hack_special_variables, but I wanted the changes as
1148 localized as possible. */
1150 #define INIT_DYNAMIC_VAR(var, val, gfunc, afunc) \
1153 v = bind_variable (var, (val), 0); \
1154 v->dynamic_value = gfunc; \
1155 v->assign_func = afunc; \
1159 #define INIT_DYNAMIC_ARRAY_VAR(var, gfunc, afunc) \
1162 v = make_new_array_variable (var); \
1163 v->dynamic_value = gfunc; \
1164 v->assign_func = afunc; \
1168 #define INIT_DYNAMIC_ASSOC_VAR(var, gfunc, afunc) \
1171 v = make_new_assoc_variable (var); \
1172 v->dynamic_value = gfunc; \
1173 v->assign_func = afunc; \
1178 null_assign (self
, value
, unused
, key
)
1187 #if defined (ARRAY_VARS)
1189 null_array_assign (self
, value
, ind
, key
)
1199 /* Degenerate `dynamic_value' function; just returns what's passed without
1208 #if defined (ARRAY_VARS)
1209 /* A generic dynamic array variable initializer. Initialize array variable
1210 NAME with dynamic value function GETFUNC and assignment function SETFUNC. */
1212 init_dynamic_array_var (name
, getfunc
, setfunc
, attrs
)
1214 sh_var_value_func_t
*getfunc
;
1215 sh_var_assign_func_t
*setfunc
;
1220 v
= find_variable (name
);
1223 INIT_DYNAMIC_ARRAY_VAR (name
, getfunc
, setfunc
);
1225 VSETATTR (v
, attrs
);
1230 init_dynamic_assoc_var (name
, getfunc
, setfunc
, attrs
)
1232 sh_var_value_func_t
*getfunc
;
1233 sh_var_assign_func_t
*setfunc
;
1238 v
= find_variable (name
);
1241 INIT_DYNAMIC_ASSOC_VAR (name
, getfunc
, setfunc
);
1243 VSETATTR (v
, attrs
);
1248 /* The value of $SECONDS. This is the number of seconds since shell
1249 invocation, or, the number of seconds since the last assignment + the
1250 value of the last assignment. */
1251 static intmax_t seconds_value_assigned
;
1254 assign_seconds (self
, value
, unused
, key
)
1260 if (legal_number (value
, &seconds_value_assigned
) == 0)
1261 seconds_value_assigned
= 0;
1262 shell_start_time
= NOW
;
1270 time_t time_since_start
;
1273 time_since_start
= NOW
- shell_start_time
;
1274 p
= itos(seconds_value_assigned
+ time_since_start
);
1276 FREE (value_cell (var
));
1278 VSETATTR (var
, att_integer
);
1279 var_setvalue (var
, p
);
1288 v
= find_variable ("SECONDS");
1291 if (legal_number (value_cell(v
), &seconds_value_assigned
) == 0)
1292 seconds_value_assigned
= 0;
1294 INIT_DYNAMIC_VAR ("SECONDS", (v
? value_cell (v
) : (char *)NULL
), get_seconds
, assign_seconds
);
1298 /* The random number seed. You can change this by setting RANDOM. */
1299 static unsigned long rseed
= 1;
1300 static int last_random_value
;
1301 static int seeded_subshell
= 0;
1303 /* A linear congruential random number generator based on the example
1304 one in the ANSI C standard. This one isn't very good, but a more
1305 complicated one is overkill. */
1307 /* Returns a pseudo-random number between 0 and 32767. */
1311 /* From "Random number generators: good ones are hard to find",
1312 Park and Miller, Communications of the ACM, vol. 31, no. 10,
1313 October 1988, p. 1195. filtered through FreeBSD */
1316 /* Can't seed with 0. */
1321 rseed
= 16807 * l
- 2836 * h
;
1324 rseed
+= 0x7fffffff;
1326 return ((unsigned int)(rseed
& 32767)); /* was % 32768 */
1329 /* Set the random number generator seed to SEED. */
1335 last_random_value
= 0;
1343 gettimeofday (&tv
, NULL
);
1344 sbrand (tv
.tv_sec
^ tv
.tv_usec
^ getpid ());
1348 assign_random (self
, value
, unused
, key
)
1354 sbrand (strtoul (value
, (char **)NULL
, 10));
1355 if (subshell_environment
)
1356 seeded_subshell
= getpid ();
1361 get_random_number ()
1365 /* Reset for command and process substitution. */
1367 if (subshell_environment
&& seeded_subshell
!= pid
)
1370 seeded_subshell
= pid
;
1375 while (rv
== last_random_value
);
1386 rv
= get_random_number ();
1387 last_random_value
= rv
;
1390 FREE (value_cell (var
));
1392 VSETATTR (var
, att_integer
);
1393 var_setvalue (var
, p
);
1398 assign_lineno (var
, value
, unused
, key
)
1406 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1408 line_number
= line_number_base
= new_value
;
1412 /* Function which returns the current line number. */
1420 ln
= executing_line_number ();
1422 FREE (value_cell (var
));
1423 var_setvalue (var
, p
);
1428 assign_subshell (var
, value
, unused
, key
)
1436 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1438 subshell_level
= new_value
;
1448 p
= itos (subshell_level
);
1449 FREE (value_cell (var
));
1450 var_setvalue (var
, p
);
1464 FREE (value_cell (var
));
1465 VSETATTR (var
, att_integer
|att_readonly
);
1466 var_setvalue (var
, p
);
1471 get_bash_command (var
)
1476 if (the_printed_command_except_trap
)
1477 p
= savestring (the_printed_command_except_trap
);
1480 p
= (char *)xmalloc (1);
1483 FREE (value_cell (var
));
1484 var_setvalue (var
, p
);
1488 #if defined (HISTORY)
1495 p
= itos (history_number ());
1496 FREE (value_cell (var
));
1497 var_setvalue (var
, p
);
1502 #if defined (READLINE)
1503 /* When this function returns, VAR->value points to malloced memory. */
1505 get_comp_wordbreaks (var
)
1508 /* If we don't have anything yet, assign a default value. */
1509 if (rl_completer_word_break_characters
== 0 && bash_readline_initialized
== 0)
1510 enable_hostname_completion (perform_hostname_completion
);
1512 FREE (value_cell (var
));
1513 var_setvalue (var
, savestring (rl_completer_word_break_characters
));
1518 /* When this function returns, rl_completer_word_break_characters points to
1521 assign_comp_wordbreaks (self
, value
, unused
, key
)
1527 if (rl_completer_word_break_characters
&&
1528 rl_completer_word_break_characters
!= rl_basic_word_break_characters
)
1529 free (rl_completer_word_break_characters
);
1531 rl_completer_word_break_characters
= savestring (value
);
1534 #endif /* READLINE */
1536 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1538 assign_dirstack (self
, value
, ind
, key
)
1544 set_dirstack_element (ind
, 1, value
);
1555 l
= get_directory_stack (0);
1556 a
= array_from_word_list (l
);
1557 array_dispose (array_cell (self
));
1559 var_setarray (self
, a
);
1562 #endif /* PUSHD AND POPD && ARRAY_VARS */
1564 #if defined (ARRAY_VARS)
1565 /* We don't want to initialize the group set with a call to getgroups()
1566 unless we're asked to, but we only want to do it once. */
1574 static char **group_set
= (char **)NULL
;
1578 group_set
= get_group_list (&ng
);
1579 a
= array_cell (self
);
1580 for (i
= 0; i
< ng
; i
++)
1581 array_insert (a
, i
, group_set
[i
]);
1587 build_hashcmd (self
)
1593 BUCKET_CONTENTS
*item
;
1595 h
= assoc_cell (self
);
1599 if (hashed_filenames
== 0 || HASH_ENTRIES (hashed_filenames
) == 0)
1601 var_setvalue (self
, (char *)NULL
);
1605 h
= assoc_create (hashed_filenames
->nbuckets
);
1606 for (i
= 0; i
< hashed_filenames
->nbuckets
; i
++)
1608 for (item
= hash_items (i
, hashed_filenames
); item
; item
= item
->next
)
1610 k
= savestring (item
->key
);
1611 v
= pathdata(item
)->path
;
1612 assoc_insert (h
, k
, v
);
1616 var_setvalue (self
, (char *)h
);
1624 build_hashcmd (self
);
1629 assign_hashcmd (self
, value
, ind
, key
)
1635 #if defined (RESTRICTED_SHELL)
1636 if (restricted
&& strchr (value
, '/'))
1638 sh_restricted (value
);
1639 return (SHELL_VAR
*)NULL
;
1642 phash_insert (key
, value
, 0, 0);
1643 return (build_hashcmd (self
));
1648 build_aliasvar (self
)
1654 BUCKET_CONTENTS
*item
;
1656 h
= assoc_cell (self
);
1660 if (aliases
== 0 || HASH_ENTRIES (aliases
) == 0)
1662 var_setvalue (self
, (char *)NULL
);
1666 h
= assoc_create (aliases
->nbuckets
);
1667 for (i
= 0; i
< aliases
->nbuckets
; i
++)
1669 for (item
= hash_items (i
, aliases
); item
; item
= item
->next
)
1671 k
= savestring (item
->key
);
1672 v
= ((alias_t
*)(item
->data
))->value
;
1673 assoc_insert (h
, k
, v
);
1677 var_setvalue (self
, (char *)h
);
1685 build_aliasvar (self
);
1690 assign_aliasvar (self
, value
, ind
, key
)
1696 add_alias (key
, value
);
1697 return (build_aliasvar (self
));
1701 #endif /* ARRAY_VARS */
1703 /* If ARRAY_VARS is not defined, this just returns the name of any
1704 currently-executing function. If we have arrays, it's a call stack. */
1709 #if ! defined (ARRAY_VARS)
1711 if (variable_context
&& this_shell_function
)
1713 FREE (value_cell (self
));
1714 t
= savestring (this_shell_function
->name
);
1715 var_setvalue (self
, t
);
1722 make_funcname_visible (on_or_off
)
1727 v
= find_variable ("FUNCNAME");
1728 if (v
== 0 || v
->dynamic_value
== 0)
1732 VUNSETATTR (v
, att_invisible
);
1734 VSETATTR (v
, att_invisible
);
1738 init_funcname_var ()
1742 v
= find_variable ("FUNCNAME");
1745 #if defined (ARRAY_VARS)
1746 INIT_DYNAMIC_ARRAY_VAR ("FUNCNAME", get_funcname
, null_array_assign
);
1748 INIT_DYNAMIC_VAR ("FUNCNAME", (char *)NULL
, get_funcname
, null_assign
);
1750 VSETATTR (v
, att_invisible
|att_noassign
);
1755 initialize_dynamic_variables ()
1759 v
= init_seconds_var ();
1761 INIT_DYNAMIC_VAR ("BASH_COMMAND", (char *)NULL
, get_bash_command
, (sh_var_assign_func_t
*)NULL
);
1762 INIT_DYNAMIC_VAR ("BASH_SUBSHELL", (char *)NULL
, get_subshell
, assign_subshell
);
1764 INIT_DYNAMIC_VAR ("RANDOM", (char *)NULL
, get_random
, assign_random
);
1765 VSETATTR (v
, att_integer
);
1766 INIT_DYNAMIC_VAR ("LINENO", (char *)NULL
, get_lineno
, assign_lineno
);
1767 VSETATTR (v
, att_integer
);
1769 INIT_DYNAMIC_VAR ("BASHPID", (char *)NULL
, get_bashpid
, null_assign
);
1770 VSETATTR (v
, att_integer
|att_readonly
);
1772 #if defined (HISTORY)
1773 INIT_DYNAMIC_VAR ("HISTCMD", (char *)NULL
, get_histcmd
, (sh_var_assign_func_t
*)NULL
);
1774 VSETATTR (v
, att_integer
);
1777 #if defined (READLINE)
1778 INIT_DYNAMIC_VAR ("COMP_WORDBREAKS", (char *)NULL
, get_comp_wordbreaks
, assign_comp_wordbreaks
);
1781 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1782 v
= init_dynamic_array_var ("DIRSTACK", get_dirstack
, assign_dirstack
, 0);
1783 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1785 #if defined (ARRAY_VARS)
1786 v
= init_dynamic_array_var ("GROUPS", get_groupset
, null_array_assign
, att_noassign
);
1788 # if defined (DEBUGGER)
1789 v
= init_dynamic_array_var ("BASH_ARGC", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1790 v
= init_dynamic_array_var ("BASH_ARGV", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1791 # endif /* DEBUGGER */
1792 v
= init_dynamic_array_var ("BASH_SOURCE", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1793 v
= init_dynamic_array_var ("BASH_LINENO", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1795 v
= init_dynamic_assoc_var ("BASH_CMDS", get_hashcmd
, assign_hashcmd
, att_nofree
);
1796 # if defined (ALIAS)
1797 v
= init_dynamic_assoc_var ("BASH_ALIASES", get_aliasvar
, assign_aliasvar
, att_nofree
);
1801 v
= init_funcname_var ();
1804 /* **************************************************************** */
1806 /* Retrieving variables and values */
1808 /* **************************************************************** */
1810 /* How to get a pointer to the shell variable or function named NAME.
1811 HASHED_VARS is a pointer to the hash table containing the list
1812 of interest (either variables or functions). */
1815 hash_lookup (name
, hashed_vars
)
1817 HASH_TABLE
*hashed_vars
;
1819 BUCKET_CONTENTS
*bucket
;
1821 bucket
= hash_search (name
, hashed_vars
, 0);
1822 /* If we find the name in HASHED_VARS, set LAST_TABLE_SEARCHED to that
1825 last_table_searched
= hashed_vars
;
1826 return (bucket
? (SHELL_VAR
*)bucket
->data
: (SHELL_VAR
*)NULL
);
1830 var_lookup (name
, vcontext
)
1832 VAR_CONTEXT
*vcontext
;
1837 v
= (SHELL_VAR
*)NULL
;
1838 for (vc
= vcontext
; vc
; vc
= vc
->down
)
1839 if (v
= hash_lookup (name
, vc
->table
))
1845 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
1846 then also search the temporarily built list of exported variables.
1847 The lookup order is:
1849 shell_variables list
1853 find_variable_internal (name
, flags
)
1858 int search_tempenv
, force_tempenv
;
1861 var
= (SHELL_VAR
*)NULL
;
1863 force_tempenv
= (flags
& FV_FORCETEMPENV
);
1865 /* If explicitly requested, first look in the temporary environment for
1866 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
1867 to get the `exported' value of $foo. This happens if we are executing
1868 a function or builtin, or if we are looking up a variable in a
1869 "subshell environment". */
1870 search_tempenv
= force_tempenv
|| (expanding_redir
== 0 && subshell_environment
);
1872 if (search_tempenv
&& temporary_env
)
1873 var
= hash_lookup (name
, temporary_env
);
1877 if ((flags
& FV_SKIPINVISIBLE
) == 0)
1878 var
= var_lookup (name
, shell_variables
);
1881 /* essentially var_lookup expanded inline so we can check for
1883 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
1885 var
= hash_lookup (name
, vc
->table
);
1886 if (var
&& invisible_p (var
))
1895 return ((SHELL_VAR
*)NULL
);
1897 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
1900 /* Look up and resolve the chain of nameref variables starting at V all the
1901 way to NULL or non-nameref. */
1903 find_variable_nameref (v
)
1908 SHELL_VAR
*orig
, *oldv
;
1912 while (v
&& nameref_p (v
))
1915 if (level
> NAMEREF_MAX
)
1916 return ((SHELL_VAR
*)0); /* error message here? */
1917 newname
= nameref_cell (v
);
1918 if (newname
== 0 || *newname
== '\0')
1919 return ((SHELL_VAR
*)0);
1922 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
1923 flags
|= FV_FORCETEMPENV
;
1924 /* We don't handle array subscripts here. */
1925 v
= find_variable_internal (newname
, flags
);
1926 if (v
== orig
|| v
== oldv
)
1928 internal_warning (_("%s: circular name reference"), orig
->name
);
1929 return ((SHELL_VAR
*)0);
1935 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
1937 find_variable_last_nameref (name
, vflags
)
1945 nv
= v
= find_variable_noref (name
);
1947 while (v
&& nameref_p (v
))
1950 if (level
> NAMEREF_MAX
)
1951 return ((SHELL_VAR
*)0); /* error message here? */
1952 newname
= nameref_cell (v
);
1953 if (newname
== 0 || *newname
== '\0')
1954 return ((vflags
&& invisible_p (v
)) ? v
: (SHELL_VAR
*)0);
1957 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
1958 flags
|= FV_FORCETEMPENV
;
1959 /* We don't accommodate array subscripts here. */
1960 v
= find_variable_internal (newname
, flags
);
1965 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
1967 find_global_variable_last_nameref (name
, vflags
)
1975 nv
= v
= find_global_variable_noref (name
);
1977 while (v
&& nameref_p (v
))
1980 if (level
> NAMEREF_MAX
)
1981 return ((SHELL_VAR
*)0); /* error message here? */
1982 newname
= nameref_cell (v
);
1983 if (newname
== 0 || *newname
== '\0')
1984 return ((vflags
&& invisible_p (v
)) ? v
: (SHELL_VAR
*)0);
1986 /* We don't accommodate array subscripts here. */
1987 v
= find_global_variable_noref (newname
);
1993 find_nameref_at_context (v
, vc
)
1997 SHELL_VAR
*nv
, *nv2
;
2004 while (nv
&& nameref_p (nv
))
2007 if (level
> NAMEREF_MAX
)
2008 return (&nameref_maxloop_value
);
2009 newname
= nameref_cell (nv
);
2010 if (newname
== 0 || *newname
== '\0')
2011 return ((SHELL_VAR
*)NULL
);
2012 nv2
= hash_lookup (newname
, vc
->table
);
2020 /* Do nameref resolution from the VC, which is the local context for some
2021 function or builtin, `up' the chain to the global variables context. If
2022 NVCP is not NULL, return the variable context where we finally ended the
2023 nameref resolution (so the bind_variable_internal can use the correct
2024 variable context and hash table). */
2026 find_variable_nameref_context (v
, vc
, nvcp
)
2031 SHELL_VAR
*nv
, *nv2
;
2034 /* Look starting at the current context all the way `up' */
2035 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
2037 nv2
= find_nameref_at_context (nv
, nvc
);
2038 if (nv2
== &nameref_maxloop_value
)
2039 return (nv2
); /* XXX */
2045 if (nameref_p (nv
) == 0)
2048 return (nameref_p (nv
) ? (SHELL_VAR
*)NULL
: nv
);
2051 /* Do nameref resolution from the VC, which is the local context for some
2052 function or builtin, `up' the chain to the global variables context. If
2053 NVCP is not NULL, return the variable context where we finally ended the
2054 nameref resolution (so the bind_variable_internal can use the correct
2055 variable context and hash table). */
2057 find_variable_last_nameref_context (v
, vc
, nvcp
)
2062 SHELL_VAR
*nv
, *nv2
;
2065 /* Look starting at the current context all the way `up' */
2066 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
2068 nv2
= find_nameref_at_context (nv
, nvc
);
2069 if (nv2
== &nameref_maxloop_value
)
2070 return (nv2
); /* XXX */
2077 return (nameref_p (nv
) ? nv
: (SHELL_VAR
*)NULL
);
2081 find_variable_nameref_for_create (name
, flags
)
2087 /* See if we have a nameref pointing to a variable that hasn't been
2089 var
= find_variable_last_nameref (name
, 1);
2090 if ((flags
&1) && var
&& nameref_p (var
) && invisible_p (var
))
2092 internal_warning (_("%s: removing nameref attribute"), name
);
2093 VUNSETATTR (var
, att_nameref
);
2095 if (var
&& nameref_p (var
))
2097 if (legal_identifier (nameref_cell (var
)) == 0)
2099 sh_invalidid (nameref_cell (var
) ? nameref_cell (var
) : "");
2100 return ((SHELL_VAR
*)INVALID_NAMEREF_VALUE
);
2107 find_variable_nameref_for_assignment (name
, flags
)
2113 /* See if we have a nameref pointing to a variable that hasn't been
2115 var
= find_variable_last_nameref (name
, 1);
2116 if (var
&& nameref_p (var
) && invisible_p (var
)) /* XXX - flags */
2118 internal_warning (_("%s: removing nameref attribute"), name
);
2119 VUNSETATTR (var
, att_nameref
);
2121 if (var
&& nameref_p (var
))
2123 if (valid_nameref_value (nameref_cell (var
), 1) == 0)
2125 sh_invalidid (nameref_cell (var
) ? nameref_cell (var
) : "");
2126 return ((SHELL_VAR
*)INVALID_NAMEREF_VALUE
);
2132 /* Find a variable, forcing a search of the temporary environment first */
2134 find_variable_tempenv (name
)
2139 var
= find_variable_internal (name
, FV_FORCETEMPENV
);
2140 if (var
&& nameref_p (var
))
2141 var
= find_variable_nameref (var
);
2145 /* Find a variable, not forcing a search of the temporary environment first */
2147 find_variable_notempenv (name
)
2152 var
= find_variable_internal (name
, 0);
2153 if (var
&& nameref_p (var
))
2154 var
= find_variable_nameref (var
);
2159 find_global_variable (name
)
2164 var
= var_lookup (name
, global_variables
);
2165 if (var
&& nameref_p (var
))
2166 var
= find_variable_nameref (var
);
2169 return ((SHELL_VAR
*)NULL
);
2171 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2175 find_global_variable_noref (name
)
2180 var
= var_lookup (name
, global_variables
);
2183 return ((SHELL_VAR
*)NULL
);
2185 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2189 find_shell_variable (name
)
2194 var
= var_lookup (name
, shell_variables
);
2195 if (var
&& nameref_p (var
))
2196 var
= find_variable_nameref (var
);
2199 return ((SHELL_VAR
*)NULL
);
2201 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2204 /* Look up the variable entry named NAME. Returns the entry or NULL. */
2206 find_variable (name
)
2212 last_table_searched
= 0;
2214 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2215 flags
|= FV_FORCETEMPENV
;
2216 v
= find_variable_internal (name
, flags
);
2217 if (v
&& nameref_p (v
))
2218 v
= find_variable_nameref (v
);
2222 /* Find the first instance of NAME in the variable context chain; return first
2223 one found without att_invisible set; return 0 if no non-invisible instances
2226 find_variable_no_invisible (name
)
2232 last_table_searched
= 0;
2233 flags
= FV_SKIPINVISIBLE
;
2234 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2235 flags
|= FV_FORCETEMPENV
;
2236 v
= find_variable_internal (name
, flags
);
2237 if (v
&& nameref_p (v
))
2238 v
= find_variable_nameref (v
);
2242 /* Find the first instance of NAME in the variable context chain; return first
2243 one found even if att_invisible set. */
2245 find_variable_for_assignment (name
)
2251 last_table_searched
= 0;
2253 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2254 flags
|= FV_FORCETEMPENV
;
2255 v
= find_variable_internal (name
, flags
);
2256 if (v
&& nameref_p (v
))
2257 v
= find_variable_nameref (v
);
2262 find_variable_noref (name
)
2269 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2270 flags
|= FV_FORCETEMPENV
;
2271 v
= find_variable_internal (name
, flags
);
2275 /* Look up the function entry whose name matches STRING.
2276 Returns the entry or NULL. */
2278 find_function (name
)
2281 return (hash_lookup (name
, shell_functions
));
2284 /* Find the function definition for the shell function named NAME. Returns
2285 the entry or NULL. */
2287 find_function_def (name
)
2290 #if defined (DEBUGGER)
2291 return ((FUNCTION_DEF
*)hash_lookup (name
, shell_function_defs
));
2293 return ((FUNCTION_DEF
*)0);
2297 /* Return the value of VAR. VAR is assumed to have been the result of a
2298 lookup without any subscript, if arrays are compiled into the shell. */
2300 get_variable_value (var
)
2304 return ((char *)NULL
);
2305 #if defined (ARRAY_VARS)
2306 else if (array_p (var
))
2307 return (array_reference (array_cell (var
), 0));
2308 else if (assoc_p (var
))
2309 return (assoc_reference (assoc_cell (var
), "0"));
2312 return (value_cell (var
));
2315 /* Return the string value of a variable. Return NULL if the variable
2316 doesn't exist. Don't cons a new string. This is a potential memory
2317 leak if the variable is found in the temporary environment, but doesn't
2318 leak in practice. Since functions and variables have separate name
2319 spaces, returns NULL if var_name is a shell function only. */
2321 get_string_value (var_name
)
2322 const char *var_name
;
2326 var
= find_variable (var_name
);
2327 return ((var
) ? get_variable_value (var
) : (char *)NULL
);
2330 /* This is present for use by the tilde and readline libraries. */
2332 sh_get_env_value (v
)
2335 return get_string_value (v
);
2338 /* **************************************************************** */
2340 /* Creating and setting variables */
2342 /* **************************************************************** */
2344 /* Set NAME to VALUE if NAME has no value. */
2346 set_if_not (name
, value
)
2351 if (shell_variables
== 0)
2352 create_variable_tables ();
2354 v
= find_variable (name
);
2356 v
= bind_variable_internal (name
, value
, global_variables
->table
, HASH_NOSRCH
, 0);
2360 /* Create a local variable referenced by NAME. */
2362 make_local_variable (name
)
2365 SHELL_VAR
*new_var
, *old_var
, *old_ref
;
2370 /* We don't want to follow the nameref chain when making local variables; we
2371 just want to create them. */
2372 old_ref
= find_variable_noref (name
);
2373 if (old_ref
&& nameref_p (old_ref
) == 0)
2375 /* local foo; local foo; is a no-op. */
2376 old_var
= find_variable (name
);
2377 if (old_ref
== 0 && old_var
&& local_p (old_var
) && old_var
->context
== variable_context
)
2380 /* local -n foo; local -n foo; is a no-op. */
2381 if (old_ref
&& local_p (old_ref
) && old_ref
->context
== variable_context
)
2384 /* From here on, we want to use the refvar, not the variable it references */
2388 was_tmpvar
= old_var
&& tempvar_p (old_var
);
2389 /* If we're making a local variable in a shell function, the temporary env
2390 has already been merged into the function's variable context stack. We
2391 can assume that a temporary var in the same context appears in the same
2392 VAR_CONTEXT and can safely be returned without creating a new variable
2393 (which results in duplicate names in the same VAR_CONTEXT->table */
2394 /* We can't just test tmpvar_p because variables in the temporary env given
2395 to a shell function appear in the function's local variable VAR_CONTEXT
2396 but retain their tempvar attribute. We want temporary variables that are
2397 found in temporary_env, hence the test for last_table_searched, which is
2398 set in hash_lookup and only (so far) checked here. */
2399 if (was_tmpvar
&& old_var
->context
== variable_context
&& last_table_searched
!= temporary_env
)
2401 VUNSETATTR (old_var
, att_invisible
); /* XXX */
2405 tmp_value
= value_cell (old_var
);
2407 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2408 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
2413 internal_error (_("make_local_variable: no function context at current scope"));
2414 return ((SHELL_VAR
*)NULL
);
2416 else if (vc
->table
== 0)
2417 vc
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
2419 /* Since this is called only from the local/declare/typeset code, we can
2420 call builtin_error here without worry (of course, it will also work
2421 for anything that sets this_command_name). Variables with the `noassign'
2422 attribute may not be made local. The test against old_var's context
2423 level is to disallow local copies of readonly global variables (since I
2424 believe that this could be a security hole). Readonly copies of calling
2425 function local variables are OK. */
2426 if (old_var
&& (noassign_p (old_var
) ||
2427 (readonly_p (old_var
) && old_var
->context
== 0)))
2429 if (readonly_p (old_var
))
2431 else if (noassign_p (old_var
))
2432 builtin_error (_("%s: variable may not be assigned value"), name
);
2434 /* Let noassign variables through with a warning */
2435 if (readonly_p (old_var
))
2437 return ((SHELL_VAR
*)NULL
);
2441 new_var
= make_new_variable (name
, vc
->table
);
2444 new_var
= make_new_variable (name
, vc
->table
);
2446 /* If we found this variable in one of the temporary environments,
2447 inherit its value. Watch to see if this causes problems with
2448 things like `x=4 local x'. XXX - see above for temporary env
2449 variables with the same context level as variable_context */
2450 /* XXX - we should only do this if the variable is not an array. */
2452 var_setvalue (new_var
, savestring (tmp_value
));
2454 new_var
->attributes
= exported_p (old_var
) ? att_exported
: 0;
2457 vc
->flags
|= VC_HASLOCAL
;
2459 new_var
->context
= variable_context
;
2460 VSETATTR (new_var
, att_local
);
2465 if (was_tmpvar
== 0 && no_invisible_vars
== 0)
2466 VSETATTR (new_var
, att_invisible
); /* XXX */
2470 /* Create a new shell variable with name NAME. */
2472 new_shell_variable (name
)
2477 entry
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
2479 entry
->name
= savestring (name
);
2480 var_setvalue (entry
, (char *)NULL
);
2481 CLEAR_EXPORTSTR (entry
);
2483 entry
->dynamic_value
= (sh_var_value_func_t
*)NULL
;
2484 entry
->assign_func
= (sh_var_assign_func_t
*)NULL
;
2486 entry
->attributes
= 0;
2488 /* Always assume variables are to be made at toplevel!
2489 make_local_variable has the responsibility of changing the
2490 variable context. */
2496 /* Create a new shell variable with name NAME and add it to the hash table
2499 make_new_variable (name
, table
)
2504 BUCKET_CONTENTS
*elt
;
2506 entry
= new_shell_variable (name
);
2508 /* Make sure we have a shell_variables hash table to add to. */
2509 if (shell_variables
== 0)
2510 create_variable_tables ();
2512 elt
= hash_insert (savestring (name
), table
, HASH_NOSRCH
);
2513 elt
->data
= (PTR_T
)entry
;
2518 #if defined (ARRAY_VARS)
2520 make_new_array_variable (name
)
2526 entry
= make_new_variable (name
, global_variables
->table
);
2527 array
= array_create ();
2529 var_setarray (entry
, array
);
2530 VSETATTR (entry
, att_array
);
2535 make_local_array_variable (name
, assoc_ok
)
2542 var
= make_local_variable (name
);
2543 if (var
== 0 || array_p (var
) || (assoc_ok
&& assoc_p (var
)))
2546 array
= array_create ();
2548 dispose_variable_value (var
);
2549 var_setarray (var
, array
);
2550 VSETATTR (var
, att_array
);
2555 make_new_assoc_variable (name
)
2561 entry
= make_new_variable (name
, global_variables
->table
);
2562 hash
= assoc_create (0);
2564 var_setassoc (entry
, hash
);
2565 VSETATTR (entry
, att_assoc
);
2570 make_local_assoc_variable (name
)
2576 var
= make_local_variable (name
);
2577 if (var
== 0 || assoc_p (var
))
2580 dispose_variable_value (var
);
2581 hash
= assoc_create (0);
2583 var_setassoc (var
, hash
);
2584 VSETATTR (var
, att_assoc
);
2590 make_variable_value (var
, value
, flags
)
2595 char *retval
, *oval
;
2596 intmax_t lval
, rval
;
2597 int expok
, olen
, op
;
2599 /* If this variable has had its type set to integer (via `declare -i'),
2600 then do expression evaluation on it and store the result. The
2601 functions in expr.c (evalexp()) and bind_int_variable() are responsible
2602 for turning off the integer flag if they don't want further
2604 if (integer_p (var
))
2606 if (flags
& ASS_APPEND
)
2608 oval
= value_cell (var
);
2609 lval
= evalexp (oval
, &expok
); /* ksh93 seems to do this */
2612 top_level_cleanup ();
2613 jump_to_top_level (DISCARD
);
2616 rval
= evalexp (value
, &expok
);
2619 top_level_cleanup ();
2620 jump_to_top_level (DISCARD
);
2622 /* This can be fooled if the variable's value changes while evaluating
2623 `rval'. We can change it if we move the evaluation of lval to here. */
2624 if (flags
& ASS_APPEND
)
2626 retval
= itos (rval
);
2628 #if defined (CASEMOD_ATTRS)
2629 else if (capcase_p (var
) || uppercase_p (var
) || lowercase_p (var
))
2631 if (flags
& ASS_APPEND
)
2633 oval
= get_variable_value (var
);
2634 if (oval
== 0) /* paranoia */
2636 olen
= STRLEN (oval
);
2637 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2638 strcpy (retval
, oval
);
2640 strcpy (retval
+olen
, value
);
2643 retval
= savestring (value
);
2646 retval
= (char *)xmalloc (1);
2649 op
= capcase_p (var
) ? CASE_CAPITALIZE
2650 : (uppercase_p (var
) ? CASE_UPPER
: CASE_LOWER
);
2651 oval
= sh_modcase (retval
, (char *)0, op
);
2655 #endif /* CASEMOD_ATTRS */
2658 if (flags
& ASS_APPEND
)
2660 oval
= get_variable_value (var
);
2661 if (oval
== 0) /* paranoia */
2663 olen
= STRLEN (oval
);
2664 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2665 strcpy (retval
, oval
);
2667 strcpy (retval
+olen
, value
);
2670 retval
= savestring (value
);
2673 retval
= (char *)xmalloc (1);
2678 retval
= (char *)NULL
;
2683 /* Bind a variable NAME to VALUE in the HASH_TABLE TABLE, which may be the
2684 temporary environment (but usually is not). */
2686 bind_variable_internal (name
, value
, table
, hflags
, aflags
)
2692 char *newval
, *tname
;
2693 SHELL_VAR
*entry
, *tentry
;
2695 entry
= (hflags
& HASH_NOSRCH
) ? (SHELL_VAR
*)NULL
: hash_lookup (name
, table
);
2696 /* Follow the nameref chain here if this is the global variables table */
2697 if (entry
&& nameref_p (entry
) && (invisible_p (entry
) == 0) && table
== global_variables
->table
)
2699 entry
= find_global_variable (entry
->name
);
2700 /* Let's see if we have a nameref referencing a variable that hasn't yet
2703 entry
= find_variable_last_nameref (name
, 0); /* XXX */
2704 if (entry
== 0) /* just in case */
2708 /* The first clause handles `declare -n ref; ref=x;' or `declare -n ref;
2710 if (entry
&& invisible_p (entry
) && nameref_p (entry
))
2712 if ((aflags
& ASS_FORCE
) == 0 && value
&& valid_nameref_value (value
, 0) == 0)
2714 sh_invalidid (value
);
2715 return ((SHELL_VAR
*)NULL
);
2719 else if (entry
&& nameref_p (entry
))
2721 newval
= nameref_cell (entry
);
2722 #if defined (ARRAY_VARS)
2723 /* declare -n foo=x[2] ; foo=bar */
2724 if (valid_array_reference (newval
, 0))
2726 tname
= array_variable_name (newval
, (char **)0, (int *)0);
2727 if (tname
&& (tentry
= find_variable_noref (tname
)) && nameref_p (tentry
))
2729 /* nameref variables can't be arrays */
2730 internal_warning (_("%s: removing nameref attribute"), name_cell (tentry
));
2731 FREE (value_cell (tentry
)); /* XXX - bash-4.3 compat */
2732 var_setvalue (tentry
, (char *)NULL
);
2733 VUNSETATTR (tentry
, att_nameref
);
2736 /* XXX - should it be aflags? */
2737 entry
= assign_array_element (newval
, make_variable_value (entry
, value
, 0), aflags
|ASS_NAMEREF
);
2744 entry
= make_new_variable (newval
, table
);
2745 var_setvalue (entry
, make_variable_value (entry
, value
, 0));
2748 else if (entry
== 0)
2750 entry
= make_new_variable (name
, table
);
2751 var_setvalue (entry
, make_variable_value (entry
, value
, 0)); /* XXX */
2753 else if (entry
->assign_func
) /* array vars have assign functions now */
2755 INVALIDATE_EXPORTSTR (entry
);
2756 newval
= (aflags
& ASS_APPEND
) ? make_variable_value (entry
, value
, aflags
) : value
;
2757 if (assoc_p (entry
))
2758 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, savestring ("0"));
2759 else if (array_p (entry
))
2760 entry
= (*(entry
->assign_func
)) (entry
, newval
, 0, 0);
2762 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, 0);
2763 if (newval
!= value
)
2770 if ((readonly_p (entry
) && (aflags
& ASS_FORCE
) == 0) || noassign_p (entry
))
2772 if (readonly_p (entry
))
2773 err_readonly (name_cell (entry
));
2777 /* Variables which are bound are visible. */
2778 VUNSETATTR (entry
, att_invisible
);
2780 #if defined (ARRAY_VARS)
2781 if (assoc_p (entry
) || array_p (entry
))
2782 newval
= make_array_variable_value (entry
, 0, "0", value
, aflags
);
2786 newval
= make_variable_value (entry
, value
, aflags
); /* XXX */
2788 /* Invalidate any cached export string */
2789 INVALIDATE_EXPORTSTR (entry
);
2791 #if defined (ARRAY_VARS)
2792 /* XXX -- this bears looking at again -- XXX */
2793 /* If an existing array variable x is being assigned to with x=b or
2794 `read x' or something of that nature, silently convert it to
2795 x[0]=b or `read x[0]'. */
2796 if (assoc_p (entry
))
2798 assoc_insert (assoc_cell (entry
), savestring ("0"), newval
);
2801 else if (array_p (entry
))
2803 array_insert (array_cell (entry
), 0, newval
);
2809 FREE (value_cell (entry
));
2810 var_setvalue (entry
, newval
);
2814 if (mark_modified_vars
)
2815 VSETATTR (entry
, att_exported
);
2817 if (exported_p (entry
))
2818 array_needs_making
= 1;
2823 /* Bind a variable NAME to VALUE. This conses up the name
2824 and value strings. If we have a temporary environment, we bind there
2825 first, then we bind into shell_variables. */
2828 bind_variable (name
, value
, flags
)
2834 VAR_CONTEXT
*vc
, *nvc
;
2837 if (shell_variables
== 0)
2838 create_variable_tables ();
2840 /* If we have a temporary environment, look there first for the variable,
2841 and, if found, modify the value there before modifying it in the
2842 shell_variables table. This allows sourced scripts to modify values
2843 given to them in a temporary environment while modifying the variable
2844 value that the caller sees. */
2845 if (temporary_env
&& value
) /* XXX - can value be null here? */
2846 bind_tempenv_variable (name
, value
);
2848 /* XXX -- handle local variables here. */
2849 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2851 if (vc_isfuncenv (vc
) || vc_isbltnenv (vc
))
2853 v
= hash_lookup (name
, vc
->table
);
2855 if (v
&& nameref_p (v
))
2857 nv
= find_variable_nameref_context (v
, vc
, &nvc
);
2860 nv
= find_variable_last_nameref_context (v
, vc
, &nvc
);
2861 if (nv
&& nameref_p (nv
))
2863 /* If this nameref variable doesn't have a value yet,
2864 set the value. Otherwise, assign using the value as
2866 if (nameref_cell (nv
) == 0)
2867 return (bind_variable_internal (nv
->name
, value
, nvc
->table
, 0, flags
));
2868 #if defined (ARRAY_VARS)
2869 else if (valid_array_reference (nameref_cell (nv
), 0))
2870 return (assign_array_element (nameref_cell (nv
), value
, flags
));
2873 return (bind_variable_internal (nameref_cell (nv
), value
, nvc
->table
, 0, flags
));
2875 else if (nv
== &nameref_maxloop_value
)
2877 internal_warning (_("%s: circular name reference"), v
->name
);
2879 return (bind_variable_value (v
, value
, flags
|ASS_NAMEREF
));
2881 v
= 0; /* backwards compat */
2887 else if (nv
== &nameref_maxloop_value
)
2889 internal_warning (_("%s: circular name reference"), v
->name
);
2891 return (bind_variable_value (v
, value
, flags
|ASS_NAMEREF
));
2893 v
= 0; /* backwards compat */
2900 return (bind_variable_internal (v
->name
, value
, nvc
->table
, 0, flags
));
2903 /* bind_variable_internal will handle nameref resolution in this case */
2904 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
2908 bind_global_variable (name
, value
, flags
)
2914 VAR_CONTEXT
*vc
, *nvc
;
2917 if (shell_variables
== 0)
2918 create_variable_tables ();
2920 /* bind_variable_internal will handle nameref resolution in this case */
2921 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
2924 /* Make VAR, a simple shell variable, have value VALUE. Once assigned a
2925 value, variables are no longer invisible. This is a duplicate of part
2926 of the internals of bind_variable. If the variable is exported, or
2927 all modified variables should be exported, mark the variable for export
2928 and note that the export environment needs to be recreated. */
2930 bind_variable_value (var
, value
, aflags
)
2938 invis
= invisible_p (var
);
2939 VUNSETATTR (var
, att_invisible
);
2941 if (var
->assign_func
)
2943 /* If we're appending, we need the old value, so use
2944 make_variable_value */
2945 t
= (aflags
& ASS_APPEND
) ? make_variable_value (var
, value
, aflags
) : value
;
2946 (*(var
->assign_func
)) (var
, t
, -1, 0);
2947 if (t
!= value
&& t
)
2952 t
= make_variable_value (var
, value
, aflags
);
2953 if ((aflags
& (ASS_NAMEREF
|ASS_FORCE
)) == ASS_NAMEREF
&& check_selfref (name_cell (var
), t
, 0))
2955 if (variable_context
)
2956 internal_warning (_("%s: circular name reference"), name_cell (var
));
2959 internal_error (_("%s: nameref variable self references not allowed"), name_cell (var
));
2962 VSETATTR (var
, att_invisible
); /* XXX */
2963 return ((SHELL_VAR
*)NULL
);
2966 if ((aflags
& ASS_NAMEREF
) && (valid_nameref_value (t
, 0) == 0))
2970 VSETATTR (var
, att_invisible
); /* XXX */
2971 return ((SHELL_VAR
*)NULL
);
2973 FREE (value_cell (var
));
2974 var_setvalue (var
, t
);
2977 INVALIDATE_EXPORTSTR (var
);
2979 if (mark_modified_vars
)
2980 VSETATTR (var
, att_exported
);
2982 if (exported_p (var
))
2983 array_needs_making
= 1;
2988 /* Bind/create a shell variable with the name LHS to the RHS.
2989 This creates or modifies a variable such that it is an integer.
2991 This used to be in expr.c, but it is here so that all of the
2992 variable binding stuff is localized. Since we don't want any
2993 recursive evaluation from bind_variable() (possible without this code,
2994 since bind_variable() calls the evaluator for variables with the integer
2995 attribute set), we temporarily turn off the integer attribute for each
2996 variable we set here, then turn it back on after binding as necessary. */
2999 bind_int_variable (lhs
, rhs
)
3002 register SHELL_VAR
*v
;
3003 int isint
, isarr
, implicitarray
;
3005 isint
= isarr
= implicitarray
= 0;
3006 #if defined (ARRAY_VARS)
3007 if (valid_array_reference (lhs
, 0))
3010 v
= array_variable_part (lhs
, (char **)0, (int *)0);
3014 v
= find_variable (lhs
);
3018 isint
= integer_p (v
);
3019 VUNSETATTR (v
, att_integer
);
3020 #if defined (ARRAY_VARS)
3021 if (array_p (v
) && isarr
== 0)
3026 #if defined (ARRAY_VARS)
3028 v
= assign_array_element (lhs
, rhs
, 0);
3029 else if (implicitarray
)
3030 v
= bind_array_variable (lhs
, 0, rhs
, 0);
3033 v
= bind_variable (lhs
, rhs
, 0);
3038 VSETATTR (v
, att_integer
);
3039 VUNSETATTR (v
, att_invisible
);
3042 if (v
&& nameref_p (v
))
3043 internal_warning (_("%s: assigning integer to name reference"), lhs
);
3049 bind_var_to_int (var
, val
)
3053 char ibuf
[INT_STRLEN_BOUND (intmax_t) + 1], *p
;
3055 p
= fmtulong (val
, 10, ibuf
, sizeof (ibuf
), 0);
3056 return (bind_int_variable (var
, p
));
3059 /* Do a function binding to a variable. You pass the name and
3060 the command to bind to. This conses the name and command. */
3062 bind_function (name
, value
)
3068 entry
= find_function (name
);
3071 BUCKET_CONTENTS
*elt
;
3073 elt
= hash_insert (savestring (name
), shell_functions
, HASH_NOSRCH
);
3074 entry
= new_shell_variable (name
);
3075 elt
->data
= (PTR_T
)entry
;
3078 INVALIDATE_EXPORTSTR (entry
);
3080 if (var_isset (entry
))
3081 dispose_command (function_cell (entry
));
3084 var_setfunc (entry
, copy_command (value
));
3086 var_setfunc (entry
, 0);
3088 VSETATTR (entry
, att_function
);
3090 if (mark_modified_vars
)
3091 VSETATTR (entry
, att_exported
);
3093 VUNSETATTR (entry
, att_invisible
); /* Just to be sure */
3095 if (exported_p (entry
))
3096 array_needs_making
= 1;
3098 #if defined (PROGRAMMABLE_COMPLETION)
3099 set_itemlist_dirty (&it_functions
);
3105 #if defined (DEBUGGER)
3106 /* Bind a function definition, which includes source file and line number
3107 information in addition to the command, into the FUNCTION_DEF hash table.*/
3109 bind_function_def (name
, value
)
3111 FUNCTION_DEF
*value
;
3113 FUNCTION_DEF
*entry
;
3114 BUCKET_CONTENTS
*elt
;
3117 entry
= find_function_def (name
);
3120 dispose_function_def_contents (entry
);
3121 entry
= copy_function_def_contents (value
, entry
);
3125 cmd
= value
->command
;
3127 entry
= copy_function_def (value
);
3128 value
->command
= cmd
;
3130 elt
= hash_insert (savestring (name
), shell_function_defs
, HASH_NOSRCH
);
3131 elt
->data
= (PTR_T
*)entry
;
3134 #endif /* DEBUGGER */
3136 /* Add STRING, which is of the form foo=bar, to the temporary environment
3137 HASH_TABLE (temporary_env). The functions in execute_cmd.c are
3138 responsible for moving the main temporary env to one of the other
3139 temporary environments. The expansion code in subst.c calls this. */
3141 assign_in_env (word
, flags
)
3146 char *name
, *temp
, *value
, *newname
;
3150 string
= word
->word
;
3153 offset
= assignment (string
, 0);
3154 newname
= name
= savestring (string
);
3155 value
= (char *)NULL
;
3157 if (name
[offset
] == '=')
3161 /* don't ignore the `+' when assigning temporary environment */
3162 if (name
[offset
- 1] == '+')
3164 name
[offset
- 1] = '\0';
3165 aflags
|= ASS_APPEND
;
3168 var
= find_variable (name
);
3171 var
= find_variable_last_nameref (name
, 1);
3172 /* If we're assigning a value to a nameref variable in the temp
3173 environment, and the value of the nameref is valid for assignment,
3174 but the variable does not already exist, assign to the nameref
3175 target and add the target to the temporary environment. This is
3177 if (var
&& nameref_p (var
) && valid_nameref_value (nameref_cell (var
), 1))
3179 newname
= nameref_cell (var
);
3180 var
= 0; /* don't use it for append */
3184 newname
= name_cell (var
); /* no-op if not nameref */
3186 if (var
&& (readonly_p (var
) || noassign_p (var
)))
3188 if (readonly_p (var
))
3189 err_readonly (name
);
3193 temp
= name
+ offset
+ 1;
3195 value
= expand_assignment_string_to_string (temp
, 0);
3197 if (var
&& (aflags
& ASS_APPEND
))
3201 value
= (char *)xmalloc (1); /* like do_assignment_internal */
3204 temp
= make_variable_value (var
, value
, aflags
);
3210 if (temporary_env
== 0)
3211 temporary_env
= hash_create (TEMPENV_HASH_BUCKETS
);
3213 var
= hash_lookup (newname
, temporary_env
);
3215 var
= make_new_variable (newname
, temporary_env
);
3217 FREE (value_cell (var
));
3221 value
= (char *)xmalloc (1); /* see above */
3225 var_setvalue (var
, value
);
3226 var
->attributes
|= (att_exported
|att_tempvar
);
3227 var
->context
= variable_context
; /* XXX */
3229 INVALIDATE_EXPORTSTR (var
);
3230 var
->exportstr
= mk_env_string (newname
, value
, 0);
3232 array_needs_making
= 1;
3235 stupidly_hack_special_variables (newname
);
3237 if (echo_command_at_execute
)
3238 /* The Korn shell prints the `+ ' in front of assignment statements,
3240 xtrace_print_assignment (name
, value
, 0, 1);
3246 /* **************************************************************** */
3248 /* Copying variables */
3250 /* **************************************************************** */
3252 #ifdef INCLUDE_UNUSED
3253 /* Copy VAR to a new data structure and return that structure. */
3258 SHELL_VAR
*copy
= (SHELL_VAR
*)NULL
;
3262 copy
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
3264 copy
->attributes
= var
->attributes
;
3265 copy
->name
= savestring (var
->name
);
3267 if (function_p (var
))
3268 var_setfunc (copy
, copy_command (function_cell (var
)));
3269 #if defined (ARRAY_VARS)
3270 else if (array_p (var
))
3271 var_setarray (copy
, array_copy (array_cell (var
)));
3272 else if (assoc_p (var
))
3273 var_setassoc (copy
, assoc_copy (assoc_cell (var
)));
3275 else if (nameref_cell (var
)) /* XXX - nameref */
3276 var_setref (copy
, savestring (nameref_cell (var
)));
3277 else if (value_cell (var
)) /* XXX - nameref */
3278 var_setvalue (copy
, savestring (value_cell (var
)));
3280 var_setvalue (copy
, (char *)NULL
);
3282 copy
->dynamic_value
= var
->dynamic_value
;
3283 copy
->assign_func
= var
->assign_func
;
3285 copy
->exportstr
= COPY_EXPORTSTR (var
);
3287 copy
->context
= var
->context
;
3293 /* **************************************************************** */
3295 /* Deleting and unsetting variables */
3297 /* **************************************************************** */
3299 /* Dispose of the information attached to VAR. */
3301 dispose_variable_value (var
)
3304 if (function_p (var
))
3305 dispose_command (function_cell (var
));
3306 #if defined (ARRAY_VARS)
3307 else if (array_p (var
))
3308 array_dispose (array_cell (var
));
3309 else if (assoc_p (var
))
3310 assoc_dispose (assoc_cell (var
));
3312 else if (nameref_p (var
))
3313 FREE (nameref_cell (var
));
3315 FREE (value_cell (var
));
3319 dispose_variable (var
)
3325 if (nofree_p (var
) == 0)
3326 dispose_variable_value (var
);
3328 FREE_EXPORTSTR (var
);
3332 if (exported_p (var
))
3333 array_needs_making
= 1;
3338 /* Unset the shell variable referenced by NAME. Unsetting a nameref variable
3339 unsets the variable it resolves to but leaves the nameref alone. */
3341 unbind_variable (name
)
3347 v
= var_lookup (name
, shell_variables
);
3348 nv
= (v
&& nameref_p (v
)) ? find_variable_nameref (v
) : (SHELL_VAR
*)NULL
;
3350 r
= nv
? makunbound (nv
->name
, shell_variables
) : makunbound (name
, shell_variables
);
3354 /* Unbind NAME, where NAME is assumed to be a nameref variable */
3356 unbind_nameref (name
)
3361 v
= var_lookup (name
, shell_variables
);
3362 if (v
&& nameref_p (v
))
3363 return makunbound (name
, shell_variables
);
3367 /* Unbind the first instance of NAME, whether it's a nameref or not */
3369 unbind_variable_noref (name
)
3374 v
= var_lookup (name
, shell_variables
);
3376 return makunbound (name
, shell_variables
);
3381 check_unbind_variable (name
)
3386 v
= find_variable (name
);
3387 if (v
&& readonly_p (v
))
3389 internal_error (_("%s: cannot unset: readonly %s"), name
, "variable");
3392 return (unbind_variable (name
));
3395 /* Unset the shell function named NAME. */
3400 BUCKET_CONTENTS
*elt
;
3403 elt
= hash_remove (name
, shell_functions
, 0);
3408 #if defined (PROGRAMMABLE_COMPLETION)
3409 set_itemlist_dirty (&it_functions
);
3412 func
= (SHELL_VAR
*)elt
->data
;
3415 if (exported_p (func
))
3416 array_needs_making
++;
3417 dispose_variable (func
);
3426 #if defined (DEBUGGER)
3428 unbind_function_def (name
)
3431 BUCKET_CONTENTS
*elt
;
3432 FUNCTION_DEF
*funcdef
;
3434 elt
= hash_remove (name
, shell_function_defs
, 0);
3439 funcdef
= (FUNCTION_DEF
*)elt
->data
;
3441 dispose_function_def (funcdef
);
3448 #endif /* DEBUGGER */
3451 delete_var (name
, vc
)
3455 BUCKET_CONTENTS
*elt
;
3459 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3460 if (elt
= hash_remove (name
, v
->table
, 0))
3466 old_var
= (SHELL_VAR
*)elt
->data
;
3470 dispose_variable (old_var
);
3474 /* Make the variable associated with NAME go away. HASH_LIST is the
3475 hash table from which this variable should be deleted (either
3476 shell_variables or shell_functions).
3477 Returns non-zero if the variable couldn't be found. */
3479 makunbound (name
, vc
)
3483 BUCKET_CONTENTS
*elt
, *new_elt
;
3488 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3489 if (elt
= hash_remove (name
, v
->table
, 0))
3495 old_var
= (SHELL_VAR
*)elt
->data
;
3497 if (old_var
&& exported_p (old_var
))
3498 array_needs_making
++;
3500 /* If we're unsetting a local variable and we're still executing inside
3501 the function, just mark the variable as invisible. The function
3502 eventually called by pop_var_context() will clean it up later. This
3503 must be done so that if the variable is subsequently assigned a new
3504 value inside the function, the `local' attribute is still present.
3505 We also need to add it back into the correct hash table. */
3506 if (old_var
&& local_p (old_var
) && variable_context
== old_var
->context
)
3508 if (nofree_p (old_var
))
3509 var_setvalue (old_var
, (char *)NULL
);
3510 #if defined (ARRAY_VARS)
3511 else if (array_p (old_var
))
3512 array_dispose (array_cell (old_var
));
3513 else if (assoc_p (old_var
))
3514 assoc_dispose (assoc_cell (old_var
));
3516 else if (nameref_p (old_var
))
3517 FREE (nameref_cell (old_var
));
3519 FREE (value_cell (old_var
));
3520 /* Reset the attributes. Preserve the export attribute if the variable
3521 came from a temporary environment. Make sure it stays local, and
3522 make it invisible. */
3523 old_var
->attributes
= (exported_p (old_var
) && tempvar_p (old_var
)) ? att_exported
: 0;
3524 VSETATTR (old_var
, att_local
);
3525 VSETATTR (old_var
, att_invisible
);
3526 var_setvalue (old_var
, (char *)NULL
);
3527 INVALIDATE_EXPORTSTR (old_var
);
3529 new_elt
= hash_insert (savestring (old_var
->name
), v
->table
, 0);
3530 new_elt
->data
= (PTR_T
)old_var
;
3531 stupidly_hack_special_variables (old_var
->name
);
3538 /* Have to save a copy of name here, because it might refer to
3539 old_var->name. If so, stupidly_hack_special_variables will
3540 reference freed memory. */
3541 t
= savestring (name
);
3546 dispose_variable (old_var
);
3547 stupidly_hack_special_variables (t
);
3553 /* Get rid of all of the variables in the current context. */
3555 kill_all_local_variables ()
3559 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3560 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
3565 if (vc
->table
&& vc_haslocals (vc
))
3567 delete_all_variables (vc
->table
);
3568 hash_dispose (vc
->table
);
3570 vc
->table
= (HASH_TABLE
*)NULL
;
3574 free_variable_hash_data (data
)
3579 var
= (SHELL_VAR
*)data
;
3580 dispose_variable (var
);
3583 /* Delete the entire contents of the hash table. */
3585 delete_all_variables (hashed_vars
)
3586 HASH_TABLE
*hashed_vars
;
3588 hash_flush (hashed_vars
, free_variable_hash_data
);
3591 /* **************************************************************** */
3593 /* Setting variable attributes */
3595 /* **************************************************************** */
3597 #define FIND_OR_MAKE_VARIABLE(name, entry) \
3600 entry = find_variable (name); \
3603 entry = bind_variable (name, "", 0); \
3604 if (!no_invisible_vars && entry) entry->attributes |= att_invisible; \
3609 /* Make the variable associated with NAME be readonly.
3610 If NAME does not exist yet, create it. */
3612 set_var_read_only (name
)
3617 FIND_OR_MAKE_VARIABLE (name
, entry
);
3618 VSETATTR (entry
, att_readonly
);
3621 #ifdef INCLUDE_UNUSED
3622 /* Make the function associated with NAME be readonly.
3623 If NAME does not exist, we just punt, like auto_export code below. */
3625 set_func_read_only (name
)
3630 entry
= find_function (name
);
3632 VSETATTR (entry
, att_readonly
);
3635 /* Make the variable associated with NAME be auto-exported.
3636 If NAME does not exist yet, create it. */
3638 set_var_auto_export (name
)
3643 FIND_OR_MAKE_VARIABLE (name
, entry
);
3644 set_auto_export (entry
);
3647 /* Make the function associated with NAME be auto-exported. */
3649 set_func_auto_export (name
)
3654 entry
= find_function (name
);
3656 set_auto_export (entry
);
3660 /* **************************************************************** */
3662 /* Creating lists of variables */
3664 /* **************************************************************** */
3667 vlist_alloc (nentries
)
3672 vlist
= (VARLIST
*)xmalloc (sizeof (VARLIST
));
3673 vlist
->list
= (SHELL_VAR
**)xmalloc ((nentries
+ 1) * sizeof (SHELL_VAR
*));
3674 vlist
->list_size
= nentries
;
3675 vlist
->list_len
= 0;
3676 vlist
->list
[0] = (SHELL_VAR
*)NULL
;
3682 vlist_realloc (vlist
, n
)
3687 return (vlist
= vlist_alloc (n
));
3688 if (n
> vlist
->list_size
)
3690 vlist
->list_size
= n
;
3691 vlist
->list
= (SHELL_VAR
**)xrealloc (vlist
->list
, (vlist
->list_size
+ 1) * sizeof (SHELL_VAR
*));
3697 vlist_add (vlist
, var
, flags
)
3704 for (i
= 0; i
< vlist
->list_len
; i
++)
3705 if (STREQ (var
->name
, vlist
->list
[i
]->name
))
3707 if (i
< vlist
->list_len
)
3710 if (i
>= vlist
->list_size
)
3711 vlist
= vlist_realloc (vlist
, vlist
->list_size
+ 16);
3713 vlist
->list
[vlist
->list_len
++] = var
;
3714 vlist
->list
[vlist
->list_len
] = (SHELL_VAR
*)NULL
;
3717 /* Map FUNCTION over the variables in VAR_HASH_TABLE. Return an array of the
3718 variables for which FUNCTION returns a non-zero value. A NULL value
3719 for FUNCTION means to use all variables. */
3721 map_over (function
, vc
)
3722 sh_var_map_func_t
*function
;
3730 for (nentries
= 0, v
= vc
; v
; v
= v
->down
)
3731 nentries
+= HASH_ENTRIES (v
->table
);
3734 return (SHELL_VAR
**)NULL
;
3736 vlist
= vlist_alloc (nentries
);
3738 for (v
= vc
; v
; v
= v
->down
)
3739 flatten (v
->table
, function
, vlist
, 0);
3747 map_over_funcs (function
)
3748 sh_var_map_func_t
*function
;
3753 if (shell_functions
== 0 || HASH_ENTRIES (shell_functions
) == 0)
3754 return ((SHELL_VAR
**)NULL
);
3756 vlist
= vlist_alloc (HASH_ENTRIES (shell_functions
));
3758 flatten (shell_functions
, function
, vlist
, 0);
3765 /* Flatten VAR_HASH_TABLE, applying FUNC to each member and adding those
3766 elements for which FUNC succeeds to VLIST->list. FLAGS is reserved
3767 for future use. Only unique names are added to VLIST. If FUNC is
3768 NULL, each variable in VAR_HASH_TABLE is added to VLIST. If VLIST is
3769 NULL, FUNC is applied to each SHELL_VAR in VAR_HASH_TABLE. If VLIST
3770 and FUNC are both NULL, nothing happens. */
3772 flatten (var_hash_table
, func
, vlist
, flags
)
3773 HASH_TABLE
*var_hash_table
;
3774 sh_var_map_func_t
*func
;
3779 register BUCKET_CONTENTS
*tlist
;
3783 if (var_hash_table
== 0 || (HASH_ENTRIES (var_hash_table
) == 0) || (vlist
== 0 && func
== 0))
3786 for (i
= 0; i
< var_hash_table
->nbuckets
; i
++)
3788 for (tlist
= hash_items (i
, var_hash_table
); tlist
; tlist
= tlist
->next
)
3790 var
= (SHELL_VAR
*)tlist
->data
;
3792 r
= func
? (*func
) (var
) : 1;
3794 vlist_add (vlist
, var
, flags
);
3800 sort_variables (array
)
3803 qsort (array
, strvec_len ((char **)array
), sizeof (SHELL_VAR
*), (QSFUNC
*)qsort_var_comp
);
3807 qsort_var_comp (var1
, var2
)
3808 SHELL_VAR
**var1
, **var2
;
3812 if ((result
= (*var1
)->name
[0] - (*var2
)->name
[0]) == 0)
3813 result
= strcmp ((*var1
)->name
, (*var2
)->name
);
3818 /* Apply FUNC to each variable in SHELL_VARIABLES, adding each one for
3819 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3822 sh_var_map_func_t
*func
;
3826 list
= map_over (func
, shell_variables
);
3827 if (list
/* && posixly_correct */)
3828 sort_variables (list
);
3832 /* Apply FUNC to each variable in SHELL_FUNCTIONS, adding each one for
3833 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3836 sh_var_map_func_t
*func
;
3840 list
= map_over_funcs (func
);
3841 if (list
/* && posixly_correct */)
3842 sort_variables (list
);
3846 /* Create a NULL terminated array of all the shell variables. */
3848 all_shell_variables ()
3850 return (vapply ((sh_var_map_func_t
*)NULL
));
3853 /* Create a NULL terminated array of all the shell functions. */
3855 all_shell_functions ()
3857 return (fapply ((sh_var_map_func_t
*)NULL
));
3864 return (invisible_p (var
) == 0);
3868 all_visible_functions ()
3870 return (fapply (visible_var
));
3874 all_visible_variables ()
3876 return (vapply (visible_var
));
3879 /* Return non-zero if the variable VAR is visible and exported. Array
3880 variables cannot be exported. */
3882 visible_and_exported (var
)
3885 return (invisible_p (var
) == 0 && exported_p (var
));
3888 /* Candidate variables for the export environment are either valid variables
3889 with the export attribute or invalid variables inherited from the initial
3890 environment and simply passed through. */
3892 export_environment_candidate (var
)
3895 return (exported_p (var
) && (invisible_p (var
) == 0 || imported_p (var
)));
3898 /* Return non-zero if VAR is a local variable in the current context and
3901 local_and_exported (var
)
3904 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
&& exported_p (var
));
3908 all_exported_variables ()
3910 return (vapply (visible_and_exported
));
3914 local_exported_variables ()
3916 return (vapply (local_and_exported
));
3920 variable_in_context (var
)
3923 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
);
3927 all_local_variables ()
3933 vc
= shell_variables
;
3934 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3935 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
3940 internal_error (_("all_local_variables: no function context at current scope"));
3941 return (SHELL_VAR
**)NULL
;
3943 if (vc
->table
== 0 || HASH_ENTRIES (vc
->table
) == 0 || vc_haslocals (vc
) == 0)
3944 return (SHELL_VAR
**)NULL
;
3946 vlist
= vlist_alloc (HASH_ENTRIES (vc
->table
));
3948 flatten (vc
->table
, variable_in_context
, vlist
, 0);
3953 sort_variables (ret
);
3957 #if defined (ARRAY_VARS)
3958 /* Return non-zero if the variable VAR is visible and an array. */
3960 visible_array_vars (var
)
3963 return (invisible_p (var
) == 0 && array_p (var
));
3967 all_array_variables ()
3969 return (vapply (visible_array_vars
));
3971 #endif /* ARRAY_VARS */
3974 all_variables_matching_prefix (prefix
)
3977 SHELL_VAR
**varlist
;
3979 int vind
, rind
, plen
;
3981 plen
= STRLEN (prefix
);
3982 varlist
= all_visible_variables ();
3983 for (vind
= 0; varlist
&& varlist
[vind
]; vind
++)
3985 if (varlist
== 0 || vind
== 0)
3986 return ((char **)NULL
);
3987 rlist
= strvec_create (vind
+ 1);
3988 for (vind
= rind
= 0; varlist
[vind
]; vind
++)
3990 if (plen
== 0 || STREQN (prefix
, varlist
[vind
]->name
, plen
))
3991 rlist
[rind
++] = savestring (varlist
[vind
]->name
);
3993 rlist
[rind
] = (char *)0;
3999 /* **************************************************************** */
4001 /* Managing temporary variable scopes */
4003 /* **************************************************************** */
4005 /* Make variable NAME have VALUE in the temporary environment. */
4007 bind_tempenv_variable (name
, value
)
4013 var
= temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
;
4017 FREE (value_cell (var
));
4018 var_setvalue (var
, savestring (value
));
4019 INVALIDATE_EXPORTSTR (var
);
4025 /* Find a variable in the temporary environment that is named NAME.
4026 Return the SHELL_VAR *, or NULL if not found. */
4028 find_tempenv_variable (name
)
4031 return (temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
);
4034 char **tempvar_list
;
4037 /* Push the variable described by (SHELL_VAR *)DATA down to the next
4038 variable context from the temporary environment. */
4040 push_temp_var (data
)
4044 HASH_TABLE
*binding_table
;
4046 var
= (SHELL_VAR
*)data
;
4048 binding_table
= shell_variables
->table
;
4049 if (binding_table
== 0)
4051 if (shell_variables
== global_variables
)
4052 /* shouldn't happen */
4053 binding_table
= shell_variables
->table
= global_variables
->table
= hash_create (VARIABLES_HASH_BUCKETS
);
4055 binding_table
= shell_variables
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
4058 v
= bind_variable_internal (var
->name
, value_cell (var
), binding_table
, 0, ASS_FORCE
);
4060 /* XXX - should we set the context here? It shouldn't matter because of how
4061 assign_in_env works, but might want to check. */
4062 if (binding_table
== global_variables
->table
) /* XXX */
4063 var
->attributes
&= ~(att_tempvar
|att_propagate
);
4066 var
->attributes
|= att_propagate
;
4067 if (binding_table
== shell_variables
->table
)
4068 shell_variables
->flags
|= VC_HASTMPVAR
;
4071 v
->attributes
|= var
->attributes
;
4073 if (find_special_var (var
->name
) >= 0)
4074 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
4076 dispose_variable (var
);
4080 propagate_temp_var (data
)
4085 var
= (SHELL_VAR
*)data
;
4086 if (tempvar_p (var
) && (var
->attributes
& att_propagate
))
4087 push_temp_var (data
);
4090 if (find_special_var (var
->name
) >= 0)
4091 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
4092 dispose_variable (var
);
4096 /* Free the storage used in the hash table for temporary
4097 environment variables. PUSHF is a function to be called
4098 to free each hash table entry. It takes care of pushing variables
4099 to previous scopes if appropriate. PUSHF stores names of variables
4100 that require special handling (e.g., IFS) on tempvar_list, so this
4101 function can call stupidly_hack_special_variables on all the
4102 variables in the list when the temporary hash table is destroyed. */
4104 dispose_temporary_env (pushf
)
4105 sh_free_func_t
*pushf
;
4109 tempvar_list
= strvec_create (HASH_ENTRIES (temporary_env
) + 1);
4110 tempvar_list
[tvlist_ind
= 0] = 0;
4112 hash_flush (temporary_env
, pushf
);
4113 hash_dispose (temporary_env
);
4114 temporary_env
= (HASH_TABLE
*)NULL
;
4116 tempvar_list
[tvlist_ind
] = 0;
4118 array_needs_making
= 1;
4121 sv_ifs ("IFS"); /* XXX here for now -- check setifs in assign_in_env */
4123 for (i
= 0; i
< tvlist_ind
; i
++)
4124 stupidly_hack_special_variables (tempvar_list
[i
]);
4126 strvec_dispose (tempvar_list
);
4132 dispose_used_env_vars ()
4136 dispose_temporary_env (propagate_temp_var
);
4137 maybe_make_export_env ();
4141 /* Take all of the shell variables in the temporary environment HASH_TABLE
4142 and make shell variables from them at the current variable context. */
4144 merge_temporary_env ()
4147 dispose_temporary_env (push_temp_var
);
4151 flush_temporary_env ()
4155 hash_flush (temporary_env
, free_variable_hash_data
);
4156 hash_dispose (temporary_env
);
4157 temporary_env
= (HASH_TABLE
*)NULL
;
4161 /* **************************************************************** */
4163 /* Creating and manipulating the environment */
4165 /* **************************************************************** */
4167 static inline char *
4168 mk_env_string (name
, value
, isfunc
)
4169 const char *name
, *value
;
4172 size_t name_len
, value_len
;
4175 name_len
= strlen (name
);
4176 value_len
= STRLEN (value
);
4178 /* If we are exporting a shell function, construct the encoded function
4180 if (isfunc
&& value
)
4182 p
= (char *)xmalloc (BASHFUNC_PREFLEN
+ name_len
+ BASHFUNC_SUFFLEN
+ value_len
+ 2);
4184 memcpy (q
, BASHFUNC_PREFIX
, BASHFUNC_PREFLEN
);
4185 q
+= BASHFUNC_PREFLEN
;
4186 memcpy (q
, name
, name_len
);
4188 memcpy (q
, BASHFUNC_SUFFIX
, BASHFUNC_SUFFLEN
);
4189 q
+= BASHFUNC_SUFFLEN
;
4193 p
= (char *)xmalloc (2 + name_len
+ value_len
);
4194 memcpy (p
, name
, name_len
);
4199 if (value
&& *value
)
4200 memcpy (q
+ 1, value
, value_len
+ 1);
4218 internal_error (_("%s has null exportstr"), v
->name
);
4221 if (legal_variable_starter ((unsigned char)*s
) == 0)
4223 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4226 for (s
= v
->exportstr
+ 1; s
&& *s
; s
++)
4230 if (legal_variable_char ((unsigned char)*s
) == 0)
4232 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4238 internal_error (_("no `=' in exportstr for %s"), v
->name
);
4246 make_env_array_from_var_list (vars
)
4249 register int i
, list_index
;
4250 register SHELL_VAR
*var
;
4251 char **list
, *value
;
4253 list
= strvec_create ((1 + strvec_len ((char **)vars
)));
4255 #define USE_EXPORTSTR (value == var->exportstr)
4257 for (i
= 0, list_index
= 0; var
= vars
[i
]; i
++)
4259 #if defined (__CYGWIN__)
4260 /* We don't use the exportstr stuff on Cygwin at all. */
4261 INVALIDATE_EXPORTSTR (var
);
4264 value
= var
->exportstr
;
4265 else if (function_p (var
))
4266 value
= named_function_string ((char *)NULL
, function_cell (var
), 0);
4267 #if defined (ARRAY_VARS)
4268 else if (array_p (var
))
4270 value
= array_to_assign (array_cell (var
), 0);
4272 continue; /* XXX array vars cannot yet be exported */
4273 # endif /* ARRAY_EXPORT */
4274 else if (assoc_p (var
))
4276 value
= assoc_to_assign (assoc_cell (var
), 0);
4278 continue; /* XXX associative array vars cannot yet be exported */
4282 value
= value_cell (var
);
4286 /* Gee, I'd like to get away with not using savestring() if we're
4287 using the cached exportstr... */
4288 list
[list_index
] = USE_EXPORTSTR
? savestring (value
)
4289 : mk_env_string (var
->name
, value
, function_p (var
));
4291 if (USE_EXPORTSTR
== 0)
4292 SAVE_EXPORTSTR (var
, list
[list_index
]);
4295 #undef USE_EXPORTSTR
4298 #if defined (ARRAY_VARS)
4299 if (array_p (var
) || assoc_p (var
))
4306 list
[list_index
] = (char *)NULL
;
4310 /* Make an array of assignment statements from the hash table
4311 HASHED_VARS which contains SHELL_VARs. Only visible, exported
4312 variables are eligible. */
4314 make_var_export_array (vcxt
)
4321 vars
= map_over (visible_and_exported
, vcxt
);
4323 vars
= map_over (export_environment_candidate
, vcxt
);
4327 return (char **)NULL
;
4329 list
= make_env_array_from_var_list (vars
);
4336 make_func_export_array ()
4341 vars
= map_over_funcs (visible_and_exported
);
4343 return (char **)NULL
;
4345 list
= make_env_array_from_var_list (vars
);
4351 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
4352 #define add_to_export_env(envstr,do_alloc) \
4355 if (export_env_index >= (export_env_size - 1)) \
4357 export_env_size += 16; \
4358 export_env = strvec_resize (export_env, export_env_size); \
4359 environ = export_env; \
4361 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
4362 export_env[export_env_index] = (char *)NULL; \
4365 /* Add ASSIGN to EXPORT_ENV, or supercede a previous assignment in the
4366 array with the same left-hand side. Return the new EXPORT_ENV. */
4368 add_or_supercede_exported_var (assign
, do_alloc
)
4375 equal_offset
= assignment (assign
, 0);
4376 if (equal_offset
== 0)
4377 return (export_env
);
4379 /* If this is a function, then only supersede the function definition.
4380 We do this by including the `=() {' in the comparison, like
4381 initialize_shell_variables does. */
4382 if (assign
[equal_offset
+ 1] == '(' &&
4383 strncmp (assign
+ equal_offset
+ 2, ") {", 3) == 0) /* } */
4386 for (i
= 0; i
< export_env_index
; i
++)
4388 if (STREQN (assign
, export_env
[i
], equal_offset
+ 1))
4390 free (export_env
[i
]);
4391 export_env
[i
] = do_alloc
? savestring (assign
) : assign
;
4392 return (export_env
);
4395 add_to_export_env (assign
, do_alloc
);
4396 return (export_env
);
4400 add_temp_array_to_env (temp_array
, do_alloc
, do_supercede
)
4402 int do_alloc
, do_supercede
;
4406 if (temp_array
== 0)
4409 for (i
= 0; temp_array
[i
]; i
++)
4412 export_env
= add_or_supercede_exported_var (temp_array
[i
], do_alloc
);
4414 add_to_export_env (temp_array
[i
], do_alloc
);
4420 /* Make the environment array for the command about to be executed, if the
4421 array needs making. Otherwise, do nothing. If a shell action could
4422 change the array that commands receive for their environment, then the
4423 code should `array_needs_making++'.
4425 The order to add to the array is:
4427 list of var contexts whose head is shell_variables
4430 This is the shell variable lookup order. We add only new variable
4431 names at each step, which allows local variables and variables in
4432 the temporary environments to shadow variables in the global (or
4433 any previous) scope.
4437 n_shell_variables ()
4442 for (n
= 0, vc
= shell_variables
; vc
; vc
= vc
->down
)
4443 n
+= HASH_ENTRIES (vc
->table
);
4453 v
= find_variable (name
);
4454 if (v
&& exported_p (v
))
4456 array_needs_making
= 1;
4457 maybe_make_export_env ();
4464 maybe_make_export_env ()
4466 register char **temp_array
;
4470 if (array_needs_making
)
4473 strvec_flush (export_env
);
4475 /* Make a guess based on how many shell variables and functions we
4476 have. Since there will always be array variables, and array
4477 variables are not (yet) exported, this will always be big enough
4478 for the exported variables and functions. */
4479 new_size
= n_shell_variables () + HASH_ENTRIES (shell_functions
) + 1 +
4480 HASH_ENTRIES (temporary_env
);
4481 if (new_size
> export_env_size
)
4483 export_env_size
= new_size
;
4484 export_env
= strvec_resize (export_env
, export_env_size
);
4485 environ
= export_env
;
4487 export_env
[export_env_index
= 0] = (char *)NULL
;
4489 /* Make a dummy variable context from the temporary_env, stick it on
4490 the front of shell_variables, call make_var_export_array on the
4491 whole thing to flatten it, and convert the list of SHELL_VAR *s
4492 to the form needed by the environment. */
4495 tcxt
= new_var_context ((char *)NULL
, 0);
4496 tcxt
->table
= temporary_env
;
4497 tcxt
->down
= shell_variables
;
4500 tcxt
= shell_variables
;
4502 temp_array
= make_var_export_array (tcxt
);
4504 add_temp_array_to_env (temp_array
, 0, 0);
4506 if (tcxt
!= shell_variables
)
4509 #if defined (RESTRICTED_SHELL)
4510 /* Restricted shells may not export shell functions. */
4511 temp_array
= restricted
? (char **)0 : make_func_export_array ();
4513 temp_array
= make_func_export_array ();
4516 add_temp_array_to_env (temp_array
, 0, 0);
4518 array_needs_making
= 0;
4522 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
4523 we will need to remake the exported environment every time we
4524 change directories. `_' is always put into the environment for
4525 every external command, so without special treatment it will always
4526 cause the environment to be remade.
4528 If there is no other reason to make the exported environment, we can
4529 just update the variables in place and mark the exported environment
4530 as no longer needing a remake. */
4532 update_export_env_inplace (env_prefix
, preflen
, value
)
4539 evar
= (char *)xmalloc (STRLEN (value
) + preflen
+ 1);
4540 strcpy (evar
, env_prefix
);
4542 strcpy (evar
+ preflen
, value
);
4543 export_env
= add_or_supercede_exported_var (evar
, 0);
4546 /* We always put _ in the environment as the name of this command. */
4548 put_command_name_into_env (command_name
)
4551 update_export_env_inplace ("_=", 2, command_name
);
4554 /* **************************************************************** */
4556 /* Managing variable contexts */
4558 /* **************************************************************** */
4560 /* Allocate and return a new variable context with NAME and FLAGS.
4561 NAME can be NULL. */
4564 new_var_context (name
, flags
)
4570 vc
= (VAR_CONTEXT
*)xmalloc (sizeof (VAR_CONTEXT
));
4571 vc
->name
= name
? savestring (name
) : (char *)NULL
;
4572 vc
->scope
= variable_context
;
4575 vc
->up
= vc
->down
= (VAR_CONTEXT
*)NULL
;
4576 vc
->table
= (HASH_TABLE
*)NULL
;
4581 /* Free a variable context and its data, including the hash table. Dispose
4582 all of the variables. */
4584 dispose_var_context (vc
)
4591 delete_all_variables (vc
->table
);
4592 hash_dispose (vc
->table
);
4598 /* Set VAR's scope level to the current variable context. */
4603 return (var
->context
= variable_context
);
4606 /* Make a new variable context with NAME and FLAGS and a HASH_TABLE of
4607 temporary variables, and push it onto shell_variables. This is
4608 for shell functions. */
4610 push_var_context (name
, flags
, tempvars
)
4613 HASH_TABLE
*tempvars
;
4617 vc
= new_var_context (name
, flags
);
4618 vc
->table
= tempvars
;
4621 /* Have to do this because the temp environment was created before
4622 variable_context was incremented. */
4623 flatten (tempvars
, set_context
, (VARLIST
*)NULL
, 0);
4624 vc
->flags
|= VC_HASTMPVAR
;
4626 vc
->down
= shell_variables
;
4627 shell_variables
->up
= vc
;
4629 return (shell_variables
= vc
);
4633 push_func_var (data
)
4638 var
= (SHELL_VAR
*)data
;
4640 if (local_p (var
) && STREQ (var
->name
, "-"))
4641 set_current_options (value_cell (var
));
4642 else if (tempvar_p (var
) && (posixly_correct
|| (var
->attributes
& att_propagate
)))
4644 /* Make sure we have a hash table to store the variable in while it is
4645 being propagated down to the global variables table. Create one if
4647 if ((vc_isfuncenv (shell_variables
) || vc_istempenv (shell_variables
)) && shell_variables
->table
== 0)
4648 shell_variables
->table
= hash_create (VARIABLES_HASH_BUCKETS
);
4649 /* XXX - should we set v->context here? */
4650 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
4651 #if defined (ARRAY_VARS)
4652 if (array_p (var
) || assoc_p (var
))
4654 FREE (value_cell (v
));
4656 var_setarray (v
, array_copy (array_cell (var
)));
4658 var_setassoc (v
, assoc_copy (assoc_cell (var
)));
4661 if (shell_variables
== global_variables
)
4662 var
->attributes
&= ~(att_tempvar
|att_propagate
);
4664 shell_variables
->flags
|= VC_HASTMPVAR
;
4666 v
->attributes
|= var
->attributes
;
4669 stupidly_hack_special_variables (var
->name
); /* XXX */
4671 dispose_variable (var
);
4674 /* Pop the top context off of VCXT and dispose of it, returning the rest of
4679 VAR_CONTEXT
*ret
, *vcxt
;
4681 vcxt
= shell_variables
;
4682 if (vc_isfuncenv (vcxt
) == 0)
4684 internal_error (_("pop_var_context: head of shell_variables not a function context"));
4688 if (ret
= vcxt
->down
)
4690 ret
->up
= (VAR_CONTEXT
*)NULL
;
4691 shell_variables
= ret
;
4693 hash_flush (vcxt
->table
, push_func_var
);
4694 dispose_var_context (vcxt
);
4697 internal_error (_("pop_var_context: no global_variables context"));
4700 /* Delete the HASH_TABLEs for all variable contexts beginning at VCXT, and
4701 all of the VAR_CONTEXTs except GLOBAL_VARIABLES. */
4703 delete_all_contexts (vcxt
)
4708 for (v
= vcxt
; v
!= global_variables
; v
= t
)
4711 dispose_var_context (v
);
4714 delete_all_variables (global_variables
->table
);
4715 shell_variables
= global_variables
;
4718 /* **************************************************************** */
4720 /* Pushing and Popping temporary variable scopes */
4722 /* **************************************************************** */
4725 push_scope (flags
, tmpvars
)
4727 HASH_TABLE
*tmpvars
;
4729 return (push_var_context ((char *)NULL
, flags
, tmpvars
));
4733 push_exported_var (data
)
4738 var
= (SHELL_VAR
*)data
;
4740 /* If a temp var had its export attribute set, or it's marked to be
4741 propagated, bind it in the previous scope before disposing it. */
4742 /* XXX - This isn't exactly right, because all tempenv variables have the
4743 export attribute set. */
4745 if (exported_p (var
) || (var
->attributes
& att_propagate
))
4747 if (tempvar_p (var
) && exported_p (var
) && (var
->attributes
& att_propagate
))
4750 var
->attributes
&= ~att_tempvar
; /* XXX */
4751 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
4752 if (shell_variables
== global_variables
)
4753 var
->attributes
&= ~att_propagate
;
4755 v
->attributes
|= var
->attributes
;
4758 stupidly_hack_special_variables (var
->name
); /* XXX */
4760 dispose_variable (var
);
4764 pop_scope (is_special
)
4767 VAR_CONTEXT
*vcxt
, *ret
;
4769 vcxt
= shell_variables
;
4770 if (vc_istempscope (vcxt
) == 0)
4772 internal_error (_("pop_scope: head of shell_variables not a temporary environment scope"));
4778 ret
->up
= (VAR_CONTEXT
*)NULL
;
4780 shell_variables
= ret
;
4782 /* Now we can take care of merging variables in VCXT into set of scopes
4783 whose head is RET (shell_variables). */
4788 hash_flush (vcxt
->table
, push_func_var
);
4790 hash_flush (vcxt
->table
, push_exported_var
);
4791 hash_dispose (vcxt
->table
);
4795 sv_ifs ("IFS"); /* XXX here for now */
4798 /* **************************************************************** */
4800 /* Pushing and Popping function contexts */
4802 /* **************************************************************** */
4804 static WORD_LIST
**dollar_arg_stack
= (WORD_LIST
**)NULL
;
4805 static int dollar_arg_stack_slots
;
4806 static int dollar_arg_stack_index
;
4808 /* XXX - should always be followed by remember_args () */
4810 push_context (name
, is_subshell
, tempvars
)
4811 char *name
; /* function name */
4813 HASH_TABLE
*tempvars
;
4815 if (is_subshell
== 0)
4816 push_dollar_vars ();
4818 push_var_context (name
, VC_FUNCENV
, tempvars
);
4821 /* Only called when subshell == 0, so we don't need to check, and can
4822 unconditionally pop the dollar vars off the stack. */
4830 sv_ifs ("IFS"); /* XXX here for now */
4833 /* Save the existing positional parameters on a stack. */
4837 if (dollar_arg_stack_index
+ 2 > dollar_arg_stack_slots
)
4839 dollar_arg_stack
= (WORD_LIST
**)
4840 xrealloc (dollar_arg_stack
, (dollar_arg_stack_slots
+= 10)
4841 * sizeof (WORD_LIST
*));
4843 dollar_arg_stack
[dollar_arg_stack_index
++] = list_rest_of_args ();
4844 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4847 /* Restore the positional parameters from our stack. */
4851 if (!dollar_arg_stack
|| dollar_arg_stack_index
== 0)
4854 remember_args (dollar_arg_stack
[--dollar_arg_stack_index
], 1);
4855 dispose_words (dollar_arg_stack
[dollar_arg_stack_index
]);
4856 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4857 set_dollar_vars_unchanged ();
4861 dispose_saved_dollar_vars ()
4863 if (!dollar_arg_stack
|| dollar_arg_stack_index
== 0)
4866 dispose_words (dollar_arg_stack
[dollar_arg_stack_index
]);
4867 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4870 /* Manipulate the special BASH_ARGV and BASH_ARGC variables. */
4876 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4877 SHELL_VAR
*bash_argv_v
, *bash_argc_v
;
4878 ARRAY
*bash_argv_a
, *bash_argc_a
;
4883 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v
, bash_argv_a
);
4884 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v
, bash_argc_a
);
4886 for (l
= list
, i
= 0; l
; l
= l
->next
, i
++)
4887 array_push (bash_argv_a
, l
->word
->word
);
4890 array_push (bash_argc_a
, t
);
4892 #endif /* ARRAY_VARS && DEBUGGER */
4895 /* Remove arguments from BASH_ARGV array. Pop top element off BASH_ARGC
4896 array and use that value as the count of elements to remove from
4901 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4902 SHELL_VAR
*bash_argv_v
, *bash_argc_v
;
4903 ARRAY
*bash_argv_a
, *bash_argc_a
;
4907 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v
, bash_argv_a
);
4908 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v
, bash_argc_a
);
4910 ce
= array_shift (bash_argc_a
, 1, 0);
4911 if (ce
== 0 || legal_number (element_value (ce
), &i
) == 0)
4915 array_pop (bash_argv_a
);
4916 array_dispose_element (ce
);
4917 #endif /* ARRAY_VARS && DEBUGGER */
4920 /*************************************************
4922 * Functions to manage special variables *
4924 *************************************************/
4926 /* Extern declarations for variables this code has to manage. */
4927 extern int eof_encountered
, eof_encountered_limit
, ignoreeof
;
4929 #if defined (READLINE)
4930 extern int hostname_list_initialized
;
4933 /* An alist of name.function for each special variable. Most of the
4934 functions don't do much, and in fact, this would be faster with a
4935 switch statement, but by the end of this file, I am sick of switch
4938 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
4940 /* This table will be sorted with qsort() the first time it's accessed. */
4941 struct name_and_function
{
4943 sh_sv_func_t
*function
;
4946 static struct name_and_function special_vars
[] = {
4947 { "BASH_COMPAT", sv_shcompat
},
4948 { "BASH_XTRACEFD", sv_xtracefd
},
4950 #if defined (JOB_CONTROL)
4951 { "CHILD_MAX", sv_childmax
},
4954 #if defined (READLINE)
4955 # if defined (STRICT_POSIX)
4956 { "COLUMNS", sv_winsize
},
4958 { "COMP_WORDBREAKS", sv_comp_wordbreaks
},
4961 { "EXECIGNORE", sv_execignore
},
4963 { "FUNCNEST", sv_funcnest
},
4965 { "GLOBIGNORE", sv_globignore
},
4967 #if defined (HISTORY)
4968 { "HISTCONTROL", sv_history_control
},
4969 { "HISTFILESIZE", sv_histsize
},
4970 { "HISTIGNORE", sv_histignore
},
4971 { "HISTSIZE", sv_histsize
},
4972 { "HISTTIMEFORMAT", sv_histtimefmt
},
4975 #if defined (__CYGWIN__)
4976 { "HOME", sv_home
},
4979 #if defined (READLINE)
4980 { "HOSTFILE", sv_hostfile
},
4984 { "IGNOREEOF", sv_ignoreeof
},
4986 { "LANG", sv_locale
},
4987 { "LC_ALL", sv_locale
},
4988 { "LC_COLLATE", sv_locale
},
4989 { "LC_CTYPE", sv_locale
},
4990 { "LC_MESSAGES", sv_locale
},
4991 { "LC_NUMERIC", sv_locale
},
4992 { "LC_TIME", sv_locale
},
4994 #if defined (READLINE) && defined (STRICT_POSIX)
4995 { "LINES", sv_winsize
},
4998 { "MAIL", sv_mail
},
4999 { "MAILCHECK", sv_mail
},
5000 { "MAILPATH", sv_mail
},
5002 { "OPTERR", sv_opterr
},
5003 { "OPTIND", sv_optind
},
5005 { "PATH", sv_path
},
5006 { "POSIXLY_CORRECT", sv_strict_posix
},
5008 #if defined (READLINE)
5009 { "TERM", sv_terminal
},
5010 { "TERMCAP", sv_terminal
},
5011 { "TERMINFO", sv_terminal
},
5012 #endif /* READLINE */
5014 { "TEXTDOMAIN", sv_locale
},
5015 { "TEXTDOMAINDIR", sv_locale
},
5017 #if defined (HAVE_TZSET)
5021 #if defined (HISTORY) && defined (BANG_HISTORY)
5022 { "histchars", sv_histchars
},
5023 #endif /* HISTORY && BANG_HISTORY */
5025 { "ignoreeof", sv_ignoreeof
},
5027 { (char *)0, (sh_sv_func_t
*)0 }
5030 #define N_SPECIAL_VARS (sizeof (special_vars) / sizeof (special_vars[0]) - 1)
5033 sv_compare (sv1
, sv2
)
5034 struct name_and_function
*sv1
, *sv2
;
5038 if ((r
= sv1
->name
[0] - sv2
->name
[0]) == 0)
5039 r
= strcmp (sv1
->name
, sv2
->name
);
5044 find_special_var (name
)
5049 for (i
= 0; special_vars
[i
].name
; i
++)
5051 r
= special_vars
[i
].name
[0] - name
[0];
5053 r
= strcmp (special_vars
[i
].name
, name
);
5057 /* Can't match any of rest of elements in sorted list. Take this out
5058 if it causes problems in certain environments. */
5064 /* The variable in NAME has just had its state changed. Check to see if it
5065 is one of the special ones where something special happens. */
5067 stupidly_hack_special_variables (name
)
5070 static int sv_sorted
= 0;
5073 if (sv_sorted
== 0) /* shouldn't need, but it's fairly cheap. */
5075 qsort (special_vars
, N_SPECIAL_VARS
, sizeof (special_vars
[0]),
5076 (QSFUNC
*)sv_compare
);
5080 i
= find_special_var (name
);
5082 (*(special_vars
[i
].function
)) (name
);
5085 /* Special variables that need hooks to be run when they are unset as part
5086 of shell reinitialization should have their sv_ functions run here. */
5088 reinit_special_variables ()
5090 #if defined (READLINE)
5091 sv_comp_wordbreaks ("COMP_WORDBREAKS");
5093 sv_globignore ("GLOBIGNORE");
5094 sv_opterr ("OPTERR");
5103 v
= find_variable ("IFS");
5107 /* What to do just after the PATH variable has changed. */
5116 /* What to do just after one of the MAILxxxx variables has changed. NAME
5117 is the name of the variable. This is called with NAME set to one of
5118 MAIL, MAILCHECK, or MAILPATH. */
5123 /* If the time interval for checking the files has changed, then
5124 reset the mail timer. Otherwise, one of the pathname vars
5125 to the users mailbox has changed, so rebuild the array of
5127 if (name
[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
5128 reset_mail_timer ();
5132 remember_mail_dates ();
5143 v
= find_variable (name
);
5146 else if (legal_number (value_cell (v
), &num
) == 0)
5152 /* What to do when EXECIGNORE changes. */
5154 sv_execignore (name
)
5157 setup_exec_ignore (name
);
5160 /* What to do when GLOBIGNORE changes. */
5162 sv_globignore (name
)
5165 if (privileged_mode
== 0)
5166 setup_glob_ignore (name
);
5169 #if defined (READLINE)
5171 sv_comp_wordbreaks (name
)
5176 sv
= find_variable (name
);
5178 reset_completer_word_break_chars ();
5181 /* What to do just after one of the TERMxxx variables has changed.
5182 If we are an interactive shell, then try to reset the terminal
5183 information in readline. */
5188 if (interactive_shell
&& no_line_editing
== 0)
5189 rl_reset_terminal (get_string_value ("TERM"));
5198 v
= find_variable (name
);
5200 clear_hostname_list ();
5202 hostname_list_initialized
= 0;
5205 #if defined (STRICT_POSIX)
5206 /* In strict posix mode, we allow assignments to LINES and COLUMNS (and values
5207 found in the initial environment) to override the terminal size reported by
5217 if (posixly_correct
== 0 || interactive_shell
== 0 || no_line_editing
)
5220 v
= find_variable (name
);
5221 if (v
== 0 || var_isset (v
) == 0)
5222 rl_reset_screen_size ();
5225 if (legal_number (value_cell (v
), &xd
) == 0)
5227 winsize_assignment
= 1;
5228 d
= xd
; /* truncate */
5229 if (name
[0] == 'L') /* LINES */
5230 rl_set_screen_size (d
, -1);
5232 rl_set_screen_size (-1, d
);
5233 winsize_assignment
= 0;
5236 #endif /* STRICT_POSIX */
5237 #endif /* READLINE */
5239 /* Update the value of HOME in the export environment so tilde expansion will
5241 #if defined (__CYGWIN__)
5245 array_needs_making
= 1;
5246 maybe_make_export_env ();
5250 #if defined (HISTORY)
5251 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
5252 If there is a value for this HISTSIZE (and it is numeric), then stifle
5253 the history. Otherwise, if there is NO value for this variable,
5254 unstifle the history. If name is HISTFILESIZE, and its value is
5255 numeric, truncate the history file to hold no more than that many
5265 temp
= get_string_value (name
);
5269 if (legal_number (temp
, &num
))
5272 if (hmax
< 0 && name
[4] == 'S')
5273 unstifle_history (); /* unstifle history if HISTSIZE < 0 */
5274 else if (name
[4] == 'S')
5276 stifle_history (hmax
);
5277 hmax
= where_history ();
5278 if (history_lines_this_session
> hmax
)
5279 history_lines_this_session
= hmax
;
5281 else if (hmax
>= 0) /* truncate HISTFILE if HISTFILESIZE >= 0 */
5283 history_truncate_file (get_string_value ("HISTFILE"), hmax
);
5284 /* If we just shrank the history file to fewer lines than we've
5285 already read, make sure we adjust our idea of how many lines
5286 we have read from the file. */
5287 if (hmax
< history_lines_in_file
)
5288 history_lines_in_file
= hmax
;
5292 else if (name
[4] == 'S')
5293 unstifle_history ();
5296 /* What to do after the HISTIGNORE variable changes. */
5298 sv_histignore (name
)
5301 setup_history_ignore (name
);
5304 /* What to do after the HISTCONTROL variable changes. */
5306 sv_history_control (name
)
5313 history_control
= 0;
5314 temp
= get_string_value (name
);
5316 if (temp
== 0 || *temp
== 0)
5320 while (val
= extract_colon_unit (temp
, &tptr
))
5322 if (STREQ (val
, "ignorespace"))
5323 history_control
|= HC_IGNSPACE
;
5324 else if (STREQ (val
, "ignoredups"))
5325 history_control
|= HC_IGNDUPS
;
5326 else if (STREQ (val
, "ignoreboth"))
5327 history_control
|= HC_IGNBOTH
;
5328 else if (STREQ (val
, "erasedups"))
5329 history_control
|= HC_ERASEDUPS
;
5335 #if defined (BANG_HISTORY)
5336 /* Setting/unsetting of the history expansion character. */
5343 temp
= get_string_value (name
);
5346 history_expansion_char
= *temp
;
5347 if (temp
[0] && temp
[1])
5349 history_subst_char
= temp
[1];
5351 history_comment_char
= temp
[2];
5356 history_expansion_char
= '!';
5357 history_subst_char
= '^';
5358 history_comment_char
= '#';
5361 #endif /* BANG_HISTORY */
5364 sv_histtimefmt (name
)
5369 if (v
= find_variable (name
))
5371 if (history_comment_char
== 0)
5372 history_comment_char
= '#';
5374 history_write_timestamps
= (v
!= 0);
5376 #endif /* HISTORY */
5378 #if defined (HAVE_TZSET)
5383 if (chkexport (name
))
5388 /* If the variable exists, then the value of it can be the number
5389 of times we actually ignore the EOF. The default is small,
5390 (smaller than csh, anyway). */
5398 eof_encountered
= 0;
5400 tmp_var
= find_variable (name
);
5401 ignoreeof
= tmp_var
&& var_isset (tmp_var
);
5402 temp
= tmp_var
? value_cell (tmp_var
) : (char *)NULL
;
5404 eof_encountered_limit
= (*temp
&& all_digits (temp
)) ? atoi (temp
) : 10;
5405 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
5416 var
= find_variable ("OPTIND");
5417 tt
= var
? get_variable_value (var
) : (char *)NULL
;
5419 /* Assume that if var->context < variable_context and variable_context > 0
5420 then we are restoring the variables's previous state while returning
5426 /* According to POSIX, setting OPTIND=1 resets the internal state
5428 if (s
< 0 || s
== 1)
5442 tt
= get_string_value ("OPTERR");
5443 sh_opterr
= (tt
&& *tt
) ? atoi (tt
) : 1;
5447 sv_strict_posix (name
)
5452 var
= find_variable (name
);
5453 posixly_correct
= var
&& var_isset (var
);
5454 posix_initialize (posixly_correct
);
5455 #if defined (READLINE)
5456 if (interactive_shell
)
5457 posix_readline_initialize (posixly_correct
);
5458 #endif /* READLINE */
5459 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
5469 v
= get_string_value (name
);
5470 if (name
[0] == 'L' && name
[1] == 'A') /* LANG */
5471 r
= set_lang (name
, v
);
5473 r
= set_locale_var (name
, v
); /* LC_*, TEXTDOMAIN* */
5476 if (r
== 0 && posixly_correct
)
5477 last_command_exit_value
= 1;
5481 #if defined (ARRAY_VARS)
5483 set_pipestatus_array (ps
, nproc
)
5491 char *t
, tbuf
[INT_STRLEN_BOUND(int) + 1];
5493 v
= find_variable ("PIPESTATUS");
5495 v
= make_new_array_variable ("PIPESTATUS");
5496 if (array_p (v
) == 0)
5497 return; /* Do nothing if not an array variable. */
5500 if (a
== 0 || array_num_elements (a
) == 0)
5502 for (i
= 0; i
< nproc
; i
++) /* was ps[i] != -1, not i < nproc */
5504 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5505 array_insert (a
, i
, t
);
5511 if (array_num_elements (a
) == nproc
&& nproc
== 1)
5513 ae
= element_forw (a
->head
);
5514 free (element_value (ae
));
5515 ae
->value
= itos (ps
[0]);
5517 else if (array_num_elements (a
) <= nproc
)
5519 /* modify in array_num_elements members in place, then add */
5521 for (i
= 0; i
< array_num_elements (a
); i
++)
5523 ae
= element_forw (ae
);
5524 free (element_value (ae
));
5525 ae
->value
= itos (ps
[i
]);
5528 for ( ; i
< nproc
; i
++)
5530 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5531 array_insert (a
, i
, t
);
5536 /* deleting elements. it's faster to rebuild the array. */
5538 for (i
= 0; ps
[i
] != -1; i
++)
5540 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5541 array_insert (a
, i
, t
);
5547 save_pipestatus_array ()
5552 v
= find_variable ("PIPESTATUS");
5553 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
5554 return ((ARRAY
*)NULL
);
5557 a2
= array_copy (array_cell (v
));
5563 restore_pipestatus_array (a
)
5569 v
= find_variable ("PIPESTATUS");
5570 /* XXX - should we still assign even if existing value is NULL? */
5571 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
5574 a2
= array_cell (v
);
5575 var_setarray (v
, a
);
5582 set_pipestatus_from_exit (s
)
5585 #if defined (ARRAY_VARS)
5586 static int v
[2] = { 0, -1 };
5589 set_pipestatus_array (v
, 1);
5602 v
= find_variable (name
);
5610 if (t
== 0 || *t
== 0)
5614 fd
= (int)strtol (t
, &e
, 10);
5615 if (e
!= t
&& *e
== '\0' && sh_validfd (fd
))
5617 fp
= fdopen (fd
, "w");
5619 internal_error (_("%s: %s: cannot open as FILE"), name
, value_cell (v
));
5621 xtrace_set (fd
, fp
);
5624 internal_error (_("%s: %s: invalid value for trace file descriptor"), name
, value_cell (v
));
5628 #define MIN_COMPAT_LEVEL 31
5636 int tens
, ones
, compatval
;
5638 v
= find_variable (name
);
5641 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5642 set_compatibility_opts ();
5645 val
= value_cell (v
);
5646 if (val
== 0 || *val
== '\0')
5648 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5649 set_compatibility_opts ();
5652 /* Handle decimal-like compatibility version specifications: 4.2 */
5653 if (ISDIGIT (val
[0]) && val
[1] == '.' && ISDIGIT (val
[2]) && val
[3] == 0)
5655 tens
= val
[0] - '0';
5656 ones
= val
[2] - '0';
5657 compatval
= tens
*10 + ones
;
5659 /* Handle integer-like compatibility version specifications: 42 */
5660 else if (ISDIGIT (val
[0]) && ISDIGIT (val
[1]) && val
[2] == 0)
5662 tens
= val
[0] - '0';
5663 ones
= val
[1] - '0';
5664 compatval
= tens
*10 + ones
;
5669 internal_error (_("%s: %s: compatibility value out of range"), name
, val
);
5670 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5671 set_compatibility_opts ();
5675 if (compatval
< MIN_COMPAT_LEVEL
|| compatval
> DEFAULT_COMPAT_LEVEL
)
5678 shell_compatibility_level
= compatval
;
5679 set_compatibility_opts ();
5682 #if defined (JOB_CONTROL)
5690 tt
= get_string_value (name
);
5691 s
= (tt
&& *tt
) ? atoi (tt
) : 0;