1 /* variables.c -- Functions for hacking shell variables. */
3 /* Copyright (C) 1987-2020 Free Software Foundation, Inc.
5 This file is part of GNU Bush, the Bourne Again SHell.
7 Bush 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 Bush 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 Bush. If not, see <http://www.gnu.org/licenses/>.
23 #include "bushtypes.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)
48 #define NEED_XTRACE_SET_DECL
51 #include "lxrgmr/parser.h"
53 #include "runner/execute_cmd.h"
54 #include "impl/findcmd.h"
55 #include "mailcheck.h"
56 #include "input/input.h"
58 #include "impl/pathexp.h"
59 #include "impl/alias.h"
64 #include "builtins/getopt.h"
65 #include "builtins/common.h"
66 #include "builtins/builtext.h"
68 #if defined (READLINE)
69 # include "input/bushline.h"
70 # include <readline/readline.h>
72 # include <tilde/tilde.h>
76 # include "bushhist.h"
77 # include <readline/history.h>
80 #if defined (PROGRAMMABLE_COMPLETION)
81 # include "pcomplete.h"
84 #define VARIABLES_HASH_BUCKETS 1024 /* must be power of two */
85 #define FUNCTIONS_HASH_BUCKETS 512
86 #define TEMPENV_HASH_BUCKETS 4 /* must be power of two */
88 #define BUSHFUNC_PREFIX "BUSH_FUNC_"
89 #define BUSHFUNC_PREFLEN 10 /* == strlen(BUSHFUNC_PREFIX */
90 #define BUSHFUNC_SUFFIX "%%"
91 #define BUSHFUNC_SUFFLEN 2 /* == strlen(BUSHFUNC_SUFFIX) */
93 /* flags for find_variable_internal */
95 #define FV_FORCETEMPENV 0x01
96 #define FV_SKIPINVISIBLE 0x02
97 #define FV_NODYNAMIC 0x04
99 extern char **environ
;
101 /* Variables used here and defined in other files. */
102 extern time_t shell_start_time
;
103 extern struct timeval shellstart
;
105 /* The list of shell variables that the user has created at the global
106 scope, or that came from the environment. */
107 VAR_CONTEXT
*global_variables
= (VAR_CONTEXT
*)NULL
;
109 /* The current list of shell variables, including function scopes */
110 VAR_CONTEXT
*shell_variables
= (VAR_CONTEXT
*)NULL
;
112 /* The list of shell functions that the user has created, or that came from
114 HASH_TABLE
*shell_functions
= (HASH_TABLE
*)NULL
;
116 HASH_TABLE
*invalid_env
= (HASH_TABLE
*)NULL
;
118 #if defined (DEBUGGER)
119 /* The table of shell function definitions that the user defined or that
120 came from the environment. */
121 HASH_TABLE
*shell_function_defs
= (HASH_TABLE
*)NULL
;
124 /* The current variable context. This is really a count of how deep into
125 executing functions we are. */
126 int variable_context
= 0;
128 /* If non-zero, local variables inherit values and attributes from a variable
129 with the same name at a previous scope. */
130 int localvar_inherit
= 0;
132 /* If non-zero, calling `unset' on local variables in previous scopes marks
133 them as invisible so lookups find them unset. This is the same behavior
134 as local variables in the current local scope. */
135 int localvar_unset
= 0;
137 /* The set of shell assignments which are made only in the environment
138 for a single command. */
139 HASH_TABLE
*temporary_env
= (HASH_TABLE
*)NULL
;
141 /* Set to non-zero if an assignment error occurs while putting variables
142 into the temporary environment. */
143 int tempenv_assign_error
;
145 /* Some funky variables which are known about specially. Here is where
146 "$*", "$1", and all the cruft is kept. */
147 char *dollar_vars
[10];
148 WORD_LIST
*rest_of_args
= (WORD_LIST
*)NULL
;
149 int posparam_count
= 0;
151 /* The value of $$. */
152 pid_t dollar_dollar_pid
;
154 /* Non-zero means that we have to remake EXPORT_ENV. */
155 int array_needs_making
= 1;
157 /* The number of times BUSH has been executed. This is set
158 by initialize_variables (). */
161 /* An array which is passed to commands as their environment. It is
162 manufactured from the union of the initial environment and the
163 shell variables that are marked for export. */
164 char **export_env
= (char **)NULL
;
165 static int export_env_index
;
166 static int export_env_size
;
168 #if defined (READLINE)
169 static int winsize_assignment
; /* currently assigning to LINES or COLUMNS */
172 SHELL_VAR nameref_invalid_value
;
173 static SHELL_VAR nameref_maxloop_value
;
175 static HASH_TABLE
*last_table_searched
; /* hash_lookup sets this */
176 static VAR_CONTEXT
*last_context_searched
;
178 /* Some forward declarations. */
179 static void create_variable_tables
PARAMS((void));
181 static void set_machine_vars
PARAMS((void));
182 static void set_home_var
PARAMS((void));
183 static void set_shell_var
PARAMS((void));
184 static char *get_bush_name
PARAMS((void));
185 static void initialize_shell_level
PARAMS((void));
186 static void uidset
PARAMS((void));
187 #if defined (ARRAY_VARS)
188 static void make_vers_array
PARAMS((void));
191 static SHELL_VAR
*null_assign
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
192 #if defined (ARRAY_VARS)
193 static SHELL_VAR
*null_array_assign
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
195 static SHELL_VAR
*get_self
PARAMS((SHELL_VAR
*));
197 #if defined (ARRAY_VARS)
198 static SHELL_VAR
*init_dynamic_array_var
PARAMS((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
199 static SHELL_VAR
*init_dynamic_assoc_var
PARAMS((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
202 static SHELL_VAR
*assign_seconds
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
203 static SHELL_VAR
*get_seconds
PARAMS((SHELL_VAR
*));
204 static SHELL_VAR
*init_seconds_var
PARAMS((void));
206 static SHELL_VAR
*assign_random
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
207 static SHELL_VAR
*get_random
PARAMS((SHELL_VAR
*));
209 static SHELL_VAR
*get_urandom
PARAMS((SHELL_VAR
*));
211 static SHELL_VAR
*assign_lineno
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
212 static SHELL_VAR
*get_lineno
PARAMS((SHELL_VAR
*));
214 static SHELL_VAR
*assign_subshell
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
215 static SHELL_VAR
*get_subshell
PARAMS((SHELL_VAR
*));
217 static SHELL_VAR
*get_epochseconds
PARAMS((SHELL_VAR
*));
218 static SHELL_VAR
*get_epochrealtime
PARAMS((SHELL_VAR
*));
220 static SHELL_VAR
*get_bushpid
PARAMS((SHELL_VAR
*));
222 static SHELL_VAR
*get_bush_argv0
PARAMS((SHELL_VAR
*));
223 static SHELL_VAR
*assign_bush_argv0
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
224 static void set_argv0
PARAMS((void));
226 #if defined (HISTORY)
227 static SHELL_VAR
*get_histcmd
PARAMS((SHELL_VAR
*));
230 #if defined (READLINE)
231 static SHELL_VAR
*get_comp_wordbreaks
PARAMS((SHELL_VAR
*));
232 static SHELL_VAR
*assign_comp_wordbreaks
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
235 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
236 static SHELL_VAR
*assign_dirstack
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
237 static SHELL_VAR
*get_dirstack
PARAMS((SHELL_VAR
*));
240 #if defined (ARRAY_VARS)
241 static SHELL_VAR
*get_groupset
PARAMS((SHELL_VAR
*));
242 # if defined (DEBUGGER)
243 static SHELL_VAR
*get_bushargcv
PARAMS((SHELL_VAR
*));
245 static SHELL_VAR
*build_hashcmd
PARAMS((SHELL_VAR
*));
246 static SHELL_VAR
*get_hashcmd
PARAMS((SHELL_VAR
*));
247 static SHELL_VAR
*assign_hashcmd
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
249 static SHELL_VAR
*build_aliasvar
PARAMS((SHELL_VAR
*));
250 static SHELL_VAR
*get_aliasvar
PARAMS((SHELL_VAR
*));
251 static SHELL_VAR
*assign_aliasvar
PARAMS((SHELL_VAR
*, char *, arrayind_t
, char *));
255 static SHELL_VAR
*get_funcname
PARAMS((SHELL_VAR
*));
256 static SHELL_VAR
*init_funcname_var
PARAMS((void));
258 static void initialize_dynamic_variables
PARAMS((void));
260 static SHELL_VAR
*bind_invalid_envvar
PARAMS((const char *, char *, int));
262 static int var_sametype
PARAMS((SHELL_VAR
*, SHELL_VAR
*));
264 static SHELL_VAR
*hash_lookup
PARAMS((const char *, HASH_TABLE
*));
265 static SHELL_VAR
*new_shell_variable
PARAMS((const char *));
266 static SHELL_VAR
*make_new_variable
PARAMS((const char *, HASH_TABLE
*));
267 static SHELL_VAR
*bind_variable_internal
PARAMS((const char *, char *, HASH_TABLE
*, int, int));
269 static void dispose_variable_value
PARAMS((SHELL_VAR
*));
270 static void free_variable_hash_data
PARAMS((PTR_T
));
272 static VARLIST
*vlist_alloc
PARAMS((int));
273 static VARLIST
*vlist_realloc
PARAMS((VARLIST
*, int));
274 static void vlist_add
PARAMS((VARLIST
*, SHELL_VAR
*, int));
276 static void flatten
PARAMS((HASH_TABLE
*, sh_var_map_func_t
*, VARLIST
*, int));
278 static int qsort_var_comp
PARAMS((SHELL_VAR
**, SHELL_VAR
**));
280 static SHELL_VAR
**vapply
PARAMS((sh_var_map_func_t
*));
281 static SHELL_VAR
**fapply
PARAMS((sh_var_map_func_t
*));
283 static int visible_var
PARAMS((SHELL_VAR
*));
284 static int visible_and_exported
PARAMS((SHELL_VAR
*));
285 static int export_environment_candidate
PARAMS((SHELL_VAR
*));
286 static int local_and_exported
PARAMS((SHELL_VAR
*));
287 static int visible_variable_in_context
PARAMS((SHELL_VAR
*));
288 static int variable_in_context
PARAMS((SHELL_VAR
*));
289 #if defined (ARRAY_VARS)
290 static int visible_array_vars
PARAMS((SHELL_VAR
*));
293 static SHELL_VAR
*find_variable_internal
PARAMS((const char *, int));
295 static SHELL_VAR
*find_nameref_at_context
PARAMS((SHELL_VAR
*, VAR_CONTEXT
*));
296 static SHELL_VAR
*find_variable_nameref_context
PARAMS((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
297 static SHELL_VAR
*find_variable_last_nameref_context
PARAMS((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
299 static SHELL_VAR
*bind_tempenv_variable
PARAMS((const char *, char *));
300 static void push_posix_temp_var
PARAMS((PTR_T
));
301 static void push_temp_var
PARAMS((PTR_T
));
302 static void propagate_temp_var
PARAMS((PTR_T
));
303 static void dispose_temporary_env
PARAMS((sh_free_func_t
*));
305 static inline char *mk_env_string
PARAMS((const char *, const char *, int));
306 static char **make_env_array_from_var_list
PARAMS((SHELL_VAR
**));
307 static char **make_var_export_array
PARAMS((VAR_CONTEXT
*));
308 static char **make_func_export_array
PARAMS((void));
309 static void add_temp_array_to_env
PARAMS((char **, int, int));
311 static int n_shell_variables
PARAMS((void));
312 static int set_context
PARAMS((SHELL_VAR
*));
314 static void push_func_var
PARAMS((PTR_T
));
315 static void push_builtin_var
PARAMS((PTR_T
));
316 static void push_exported_var
PARAMS((PTR_T
));
318 /* This needs to be looked at again. */
319 static inline void push_posix_tempvar_internal
PARAMS((SHELL_VAR
*, int));
321 static inline int find_special_var
PARAMS((const char *));
324 create_variable_tables ()
326 if (shell_variables
== 0)
328 shell_variables
= global_variables
= new_var_context ((char *)NULL
, 0);
329 shell_variables
->scope
= 0;
330 shell_variables
->table
= hash_create (VARIABLES_HASH_BUCKETS
);
333 if (shell_functions
== 0)
334 shell_functions
= hash_create (FUNCTIONS_HASH_BUCKETS
);
336 #if defined (DEBUGGER)
337 if (shell_function_defs
== 0)
338 shell_function_defs
= hash_create (FUNCTIONS_HASH_BUCKETS
);
342 /* Initialize the shell variables from the current environment.
343 If PRIVMODE is nonzero, don't import functions from ENV or
346 initialize_shell_variables (env
, privmode
)
350 char *name
, *string
, *temp_string
;
351 int c
, char_index
, string_index
, string_length
, ro
;
354 create_variable_tables ();
356 for (string_index
= 0; env
&& (string
= env
[string_index
++]); )
360 while ((c
= *string
++) && c
!= '=')
362 if (string
[-1] == '=')
363 char_index
= string
- name
- 1;
365 /* If there are weird things in the environment, like `=xxx' or a
366 string without an `=', just skip them. */
370 /* ASSERT(name[char_index] == '=') */
371 name
[char_index
] = '\0';
372 /* Now, name = env variable name, string = env variable value, and
373 char_index == strlen (name) */
375 temp_var
= (SHELL_VAR
*)NULL
;
377 #if defined (FUNCTION_IMPORT)
378 /* If exported function, define it now. Don't import functions from
379 the environment in privileged mode. */
380 if (privmode
== 0 && read_but_dont_execute
== 0 &&
381 STREQN (BUSHFUNC_PREFIX
, name
, BUSHFUNC_PREFLEN
) &&
382 STREQ (BUSHFUNC_SUFFIX
, name
+ char_index
- BUSHFUNC_SUFFLEN
) &&
383 STREQN ("() {", string
, 4))
386 char *tname
; /* desired imported function name */
388 namelen
= char_index
- BUSHFUNC_PREFLEN
- BUSHFUNC_SUFFLEN
;
390 tname
= name
+ BUSHFUNC_PREFLEN
; /* start of func name */
391 tname
[namelen
] = '\0'; /* now tname == func name */
393 string_length
= strlen (string
);
394 temp_string
= (char *)xmalloc (namelen
+ string_length
+ 2);
396 memcpy (temp_string
, tname
, namelen
);
397 temp_string
[namelen
] = ' ';
398 memcpy (temp_string
+ namelen
+ 1, string
, string_length
+ 1);
400 /* Don't import function names that are invalid identifiers from the
401 environment in posix mode, though we still allow them to be defined as
403 if (absolute_program (tname
) == 0 && (posixly_correct
== 0 || legal_identifier (tname
)))
404 parse_and_execute (temp_string
, tname
, SEVAL_NONINT
|SEVAL_NOHIST
|SEVAL_FUNCDEF
|SEVAL_ONECMD
);
406 free (temp_string
); /* parse_and_execute does this */
408 if (temp_var
= find_function (tname
))
410 VSETATTR (temp_var
, (att_exported
|att_imported
));
411 array_needs_making
= 1;
415 if (temp_var
= bind_invalid_envvar (name
, string
, 0))
417 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
418 array_needs_making
= 1;
420 last_command_exit_value
= EXECUTION_FAILURE
;
421 report_error (_("error importing function definition for `%s'"), tname
);
424 /* Restore original suffix */
425 tname
[namelen
] = BUSHFUNC_SUFFIX
[0];
428 #endif /* FUNCTION_IMPORT */
429 #if defined (ARRAY_VARS)
431 /* Array variables may not yet be exported. */
432 if (*string
== '(' && string
[1] == '[' && string
[strlen (string
) - 1] == ')')
435 temp_string
= extract_array_assignment_list (string
, &string_length
);
436 temp_var
= assign_array_from_string (name
, temp_string
, 0);
438 VSETATTR (temp_var
, (att_exported
| att_imported
));
439 array_needs_making
= 1;
442 # endif /* ARRAY_EXPORT */
446 /* If we processed a command-line option that caused SHELLOPTS to be
447 set, it may already be set (and read-only) by the time we process
448 the shell's environment. */
449 if (/* posixly_correct &&*/ STREQ (name
, "SHELLOPTS"))
451 temp_var
= find_variable ("SHELLOPTS");
452 ro
= temp_var
&& readonly_p (temp_var
);
454 VUNSETATTR (temp_var
, att_readonly
);
456 if (legal_identifier (name
))
458 temp_var
= bind_variable (name
, string
, 0);
461 VSETATTR (temp_var
, (att_exported
| att_imported
));
463 VSETATTR (temp_var
, att_readonly
);
468 temp_var
= bind_invalid_envvar (name
, string
, 0);
470 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
473 array_needs_making
= 1;
476 name
[char_index
] = '=';
477 /* temp_var can be NULL if it was an exported function with a syntax
478 error (a different bug, but it still shouldn't dump core). */
479 if (temp_var
&& function_p (temp_var
) == 0) /* XXX not yet */
481 CACHE_IMPORTSTR (temp_var
, name
);
487 /* Set up initial value of $_ */
488 temp_var
= set_if_not ("_", dollar_vars
[0]);
490 /* Remember this pid. */
491 dollar_dollar_pid
= getpid ();
493 /* Now make our own defaults in case the vars that we think are
494 important are missing. */
495 temp_var
= set_if_not ("PATH", DEFAULT_PATH_VALUE
);
496 temp_var
= set_if_not ("TERM", "dumb");
498 #if defined (__QNX__)
499 /* set node id -- don't import it from the environment */
502 # if defined (__QNXNTO__)
503 netmgr_ndtostr(ND2S_LOCAL_STR
, ND_LOCAL_NODE
, node_name
, sizeof(node_name
));
505 qnx_nidtostr (getnid (), node_name
, sizeof (node_name
));
507 temp_var
= bind_variable ("NODE", node_name
, 0);
509 set_auto_export (temp_var
);
513 /* set up the prompts. */
514 if (interactive_shell
)
516 #if defined (PROMPT_STRING_DECODE)
517 set_if_not ("PS1", primary_prompt
);
519 if (current_user
.uid
== -1)
520 get_current_user_info ();
521 set_if_not ("PS1", current_user
.euid
== 0 ? "# " : primary_prompt
);
523 set_if_not ("PS2", secondary_prompt
);
526 if (current_user
.euid
== 0)
527 bind_variable ("PS4", "+ ", 0);
529 set_if_not ("PS4", "+ ");
531 /* Don't allow IFS to be imported from the environment. */
532 temp_var
= bind_variable ("IFS", " \t\n", 0);
535 /* Magic machine types. Pretty convenient. */
538 /* Default MAILCHECK for interactive shells. Defer the creation of a
539 default MAILPATH until the startup files are read, because MAIL
540 names a mail file if MAILPATH is not set, and we should provide a
541 default only if neither is set. */
542 if (interactive_shell
)
544 temp_var
= set_if_not ("MAILCHECK", posixly_correct
? "600" : "60");
545 VSETATTR (temp_var
, att_integer
);
548 /* Do some things with shell level. */
549 initialize_shell_level ();
555 /* Initialize the `getopts' stuff. */
556 temp_var
= bind_variable ("OPTIND", "1", 0);
557 VSETATTR (temp_var
, att_integer
);
559 bind_variable ("OPTERR", "1", 0);
562 if (login_shell
== 1 && posixly_correct
== 0)
565 /* Get the full pathname to THIS shell, and set the BUSH variable
567 name
= get_bush_name ();
568 temp_var
= bind_variable ("BUSH", name
, 0);
571 /* Make the exported environment variable SHELL be the user's login
572 shell. Note that the `tset' command looks at this variable
573 to determine what style of commands to output; if it ends in "csh",
574 then C-shell commands are output, else Bourne shell commands. */
577 /* Make a variable called BUSH_VERSION which contains the version info. */
578 bind_variable ("BUSH_VERSION", shell_version_string (), 0);
579 #if defined (ARRAY_VARS)
583 if (command_execution_string
)
584 bind_variable ("BUSH_EXECUTION_STRING", command_execution_string
, 0);
586 /* Find out if we're supposed to be in Posix.2 mode via an
587 environment variable. */
588 temp_var
= find_variable ("POSIXLY_CORRECT");
590 temp_var
= find_variable ("POSIX_PEDANTIC");
591 if (temp_var
&& imported_p (temp_var
))
592 sv_strict_posix (temp_var
->name
);
594 #if defined (HISTORY)
595 /* Set history variables to defaults, and then do whatever we would
596 do if the variable had just been set. Do this only in the case
597 that we are remembering commands on the history list. */
598 if (remember_on_history
)
600 name
= bush_tilde_expand (posixly_correct
? "~/.sh_history" : "~/.bush_history", 0);
602 set_if_not ("HISTFILE", name
);
607 /* Seed the random number generators. */
611 /* Handle some "special" variables that we may have inherited from a
613 if (interactive_shell
)
615 temp_var
= find_variable ("IGNOREEOF");
617 temp_var
= find_variable ("ignoreeof");
618 if (temp_var
&& imported_p (temp_var
))
619 sv_ignoreeof (temp_var
->name
);
622 #if defined (HISTORY)
623 if (interactive_shell
&& remember_on_history
)
625 sv_history_control ("HISTCONTROL");
626 sv_histignore ("HISTIGNORE");
627 sv_histtimefmt ("HISTTIMEFORMAT");
631 #if defined (READLINE) && defined (STRICT_POSIX)
632 /* POSIXLY_CORRECT will be 1 here if the shell was compiled
633 -DSTRICT_POSIX or if POSIXLY_CORRECT was supplied in the shell's
635 if (interactive_shell
&& posixly_correct
&& no_line_editing
== 0)
636 rl_prefer_env_winsize
= 1;
637 #endif /* READLINE && STRICT_POSIX */
642 * I'm tired of the arguing and bug reports. Bush now leaves SSH_CLIENT
643 * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in
644 * isnetconn() to avoid running the startup files more often than wanted.
645 * That will, of course, only work if the user's login shell is bush, so
646 * I've made that behavior conditional on SSH_SOURCE_BUSHRC being defined
650 temp_var
= find_variable ("SSH_CLIENT");
651 if (temp_var
&& imported_p (temp_var
))
653 VUNSETATTR (temp_var
, att_exported
);
654 array_needs_making
= 1;
656 temp_var
= find_variable ("SSH2_CLIENT");
657 if (temp_var
&& imported_p (temp_var
))
659 VUNSETATTR (temp_var
, att_exported
);
660 array_needs_making
= 1;
664 /* Get the user's real and effective user ids. */
667 temp_var
= find_variable ("BUSH_XTRACEFD");
668 if (temp_var
&& imported_p (temp_var
))
669 sv_xtracefd (temp_var
->name
);
671 sv_shcompat ("BUSH_COMPAT");
673 /* Allow FUNCNEST to be inherited from the environment. */
674 sv_funcnest ("FUNCNEST");
676 /* Initialize the dynamic variables, and seed their values. */
677 initialize_dynamic_variables ();
680 /* **************************************************************** */
682 /* Setting values for special shell variables */
684 /* **************************************************************** */
691 temp_var
= set_if_not ("HOSTTYPE", HOSTTYPE
);
692 temp_var
= set_if_not ("OSTYPE", OSTYPE
);
693 temp_var
= set_if_not ("MACHTYPE", MACHTYPE
);
695 temp_var
= set_if_not ("HOSTNAME", current_host_name
);
698 /* Set $HOME to the information in the password file if we didn't get
699 it from the environment. */
701 /* This function is not static so the tilde and readline libraries can
706 if (current_user
.home_dir
== 0)
707 get_current_user_info ();
708 return current_user
.home_dir
;
716 temp_var
= find_variable ("HOME");
718 temp_var
= bind_variable ("HOME", sh_get_home_dir (), 0);
720 VSETATTR (temp_var
, att_exported
);
724 /* Set $SHELL to the user's login shell if it is not already set. Call
725 get_current_user_info if we haven't already fetched the shell. */
731 temp_var
= find_variable ("SHELL");
734 if (current_user
.shell
== 0)
735 get_current_user_info ();
736 temp_var
= bind_variable ("SHELL", current_user
.shell
, 0);
739 VSETATTR (temp_var
, att_exported
);
748 if ((login_shell
== 1) && RELPATH(shell_name
))
750 if (current_user
.shell
== 0)
751 get_current_user_info ();
752 name
= savestring (current_user
.shell
);
754 else if (ABSPATH(shell_name
))
755 name
= savestring (shell_name
);
756 else if (shell_name
[0] == '.' && shell_name
[1] == '/')
758 /* Fast path for common case. */
762 cdir
= get_string_value ("PWD");
766 name
= (char *)xmalloc (len
+ strlen (shell_name
) + 1);
768 strcpy (name
+ len
, shell_name
+ 1);
771 name
= savestring (shell_name
);
778 tname
= find_user_command (shell_name
);
782 /* Try the current directory. If there is not an executable
783 there, just punt and use the login shell. */
784 s
= file_status (shell_name
);
787 tname
= make_absolute (shell_name
, get_string_value ("PWD"));
788 if (*shell_name
== '.')
790 name
= sh_canonpath (tname
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
801 if (current_user
.shell
== 0)
802 get_current_user_info ();
803 name
= savestring (current_user
.shell
);
808 name
= full_pathname (tname
);
817 adjust_shell_level (change
)
820 char new_level
[5], *old_SHLVL
;
824 old_SHLVL
= get_string_value ("SHLVL");
825 if (old_SHLVL
== 0 || *old_SHLVL
== '\0' || legal_number (old_SHLVL
, &old_level
) == 0)
828 shell_level
= old_level
+ change
;
831 else if (shell_level
>= 1000)
833 internal_warning (_("shell level (%d) too high, resetting to 1"), shell_level
);
837 /* We don't need the full generality of itos here. */
838 if (shell_level
< 10)
840 new_level
[0] = shell_level
+ '0';
843 else if (shell_level
< 100)
845 new_level
[0] = (shell_level
/ 10) + '0';
846 new_level
[1] = (shell_level
% 10) + '0';
849 else if (shell_level
< 1000)
851 new_level
[0] = (shell_level
/ 100) + '0';
852 old_level
= shell_level
% 100;
853 new_level
[1] = (old_level
/ 10) + '0';
854 new_level
[2] = (old_level
% 10) + '0';
858 temp_var
= bind_variable ("SHLVL", new_level
, 0);
859 set_auto_export (temp_var
);
863 initialize_shell_level ()
865 adjust_shell_level (1);
868 /* If we got PWD from the environment, update our idea of the current
869 working directory. In any case, make sure that PWD exists before
870 checking it. It is possible for getcwd () to fail on shell startup,
871 and in that case, PWD would be undefined. If this is an interactive
872 login shell, see if $HOME is the current working directory, and if
873 that's not the same string as $PWD, set PWD=$HOME. */
878 SHELL_VAR
*temp_var
, *home_var
;
879 char *temp_string
, *home_string
, *current_dir
;
881 home_var
= find_variable ("HOME");
882 home_string
= home_var
? value_cell (home_var
) : (char *)NULL
;
884 temp_var
= find_variable ("PWD");
885 /* Follow posix rules for importing PWD */
886 if (temp_var
&& imported_p (temp_var
) &&
887 (temp_string
= value_cell (temp_var
)) &&
888 temp_string
[0] == '/' &&
889 same_file (temp_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
891 current_dir
= sh_canonpath (temp_string
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
892 if (current_dir
== 0)
893 current_dir
= get_working_directory ("shell_init");
895 set_working_directory (current_dir
);
896 if (posixly_correct
&& current_dir
)
898 temp_var
= bind_variable ("PWD", current_dir
, 0);
899 set_auto_export (temp_var
);
903 else if (home_string
&& interactive_shell
&& login_shell
&&
904 same_file (home_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
906 set_working_directory (home_string
);
907 temp_var
= bind_variable ("PWD", home_string
, 0);
908 set_auto_export (temp_var
);
912 temp_string
= get_working_directory ("shell-init");
915 temp_var
= bind_variable ("PWD", temp_string
, 0);
916 set_auto_export (temp_var
);
921 /* According to the Single Unix Specification, v2, $OLDPWD is an
922 `environment variable' and therefore should be auto-exported. If we
923 don't find OLDPWD in the environment, or it doesn't name a directory,
924 make a dummy invisible variable for OLDPWD, and mark it as exported. */
925 temp_var
= find_variable ("OLDPWD");
926 #if defined (OLDPWD_CHECK_DIRECTORY)
927 if (temp_var
== 0 || value_cell (temp_var
) == 0 || file_isdir (value_cell (temp_var
)) == 0)
929 if (temp_var
== 0 || value_cell (temp_var
) == 0)
932 temp_var
= bind_variable ("OLDPWD", (char *)NULL
, 0);
933 VSETATTR (temp_var
, (att_exported
| att_invisible
));
937 /* Make a variable $PPID, which holds the pid of the shell's parent. */
941 char namebuf
[INT_STRLEN_BOUND(pid_t
) + 1], *name
;
944 name
= inttostr (getppid (), namebuf
, sizeof(namebuf
));
945 temp_var
= find_variable ("PPID");
947 VUNSETATTR (temp_var
, (att_readonly
| att_exported
));
948 temp_var
= bind_variable ("PPID", name
, 0);
949 VSETATTR (temp_var
, (att_readonly
| att_integer
));
955 char buff
[INT_STRLEN_BOUND(uid_t
) + 1], *b
;
956 register SHELL_VAR
*v
;
958 b
= inttostr (current_user
.uid
, buff
, sizeof (buff
));
959 v
= find_variable ("UID");
962 v
= bind_variable ("UID", b
, 0);
963 VSETATTR (v
, (att_readonly
| att_integer
));
966 if (current_user
.euid
!= current_user
.uid
)
967 b
= inttostr (current_user
.euid
, buff
, sizeof (buff
));
969 v
= find_variable ("EUID");
972 v
= bind_variable ("EUID", b
, 0);
973 VSETATTR (v
, (att_readonly
| att_integer
));
977 #if defined (ARRAY_VARS)
983 char *s
, d
[32], b
[INT_STRLEN_BOUND(int) + 1];
985 unbind_variable_noref ("BUSH_VERSINFO");
987 vv
= make_new_array_variable ("BUSH_VERSINFO");
988 av
= array_cell (vv
);
989 strcpy (d
, dist_version
);
993 array_insert (av
, 0, d
);
994 array_insert (av
, 1, s
);
995 s
= inttostr (patch_level
, b
, sizeof (b
));
996 array_insert (av
, 2, s
);
997 s
= inttostr (build_version
, b
, sizeof (b
));
998 array_insert (av
, 3, s
);
999 array_insert (av
, 4, release_status
);
1000 array_insert (av
, 5, MACHTYPE
);
1002 VSETATTR (vv
, att_readonly
);
1004 #endif /* ARRAY_VARS */
1006 /* Set the environment variables $LINES and $COLUMNS in response to
1007 a window size change. */
1009 sh_set_lines_and_columns (lines
, cols
)
1012 char val
[INT_STRLEN_BOUND(int) + 1], *v
;
1014 #if defined (READLINE)
1015 /* If we are currently assigning to LINES or COLUMNS, don't do anything. */
1016 if (winsize_assignment
)
1020 v
= inttostr (lines
, val
, sizeof (val
));
1021 bind_variable ("LINES", v
, 0);
1023 v
= inttostr (cols
, val
, sizeof (val
));
1024 bind_variable ("COLUMNS", v
, 0);
1027 /* **************************************************************** */
1029 /* Printing variables and values */
1031 /* **************************************************************** */
1033 /* Print LIST (a list of shell variables) to stdout in such a way that
1034 they can be read back in. */
1036 print_var_list (list
)
1037 register SHELL_VAR
**list
;
1040 register SHELL_VAR
*var
;
1042 for (i
= 0; list
&& (var
= list
[i
]); i
++)
1043 if (invisible_p (var
) == 0)
1044 print_assignment (var
);
1047 /* Print LIST (a list of shell functions) to stdout in such a way that
1048 they can be read back in. */
1050 print_func_list (list
)
1051 register SHELL_VAR
**list
;
1054 register SHELL_VAR
*var
;
1056 for (i
= 0; list
&& (var
= list
[i
]); i
++)
1058 printf ("%s ", var
->name
);
1059 print_var_function (var
);
1064 /* Print the value of a single SHELL_VAR. No newline is
1065 output, but the variable is printed in such a way that
1066 it can be read back in. */
1068 print_assignment (var
)
1071 if (var_isset (var
) == 0)
1074 if (function_p (var
))
1076 printf ("%s", var
->name
);
1077 print_var_function (var
);
1080 #if defined (ARRAY_VARS)
1081 else if (array_p (var
))
1082 print_array_assignment (var
, 0);
1083 else if (assoc_p (var
))
1084 print_assoc_assignment (var
, 0);
1085 #endif /* ARRAY_VARS */
1088 printf ("%s=", var
->name
);
1089 print_var_value (var
, 1);
1094 /* Print the value cell of VAR, a shell variable. Do not print
1095 the name, nor leading/trailing newline. If QUOTE is non-zero,
1096 and the value contains shell metacharacters, quote the value
1097 in such a way that it can be read back in. */
1099 print_var_value (var
, quote
)
1105 if (var_isset (var
) == 0)
1108 if (quote
&& posixly_correct
== 0 && ansic_shouldquote (value_cell (var
)))
1110 t
= ansic_quote (value_cell (var
), 0, (int *)0);
1114 else if (quote
&& sh_contains_shell_metas (value_cell (var
)))
1116 t
= sh_single_quote (value_cell (var
));
1121 printf ("%s", value_cell (var
));
1124 /* Print the function cell of VAR, a shell variable. Do not
1125 print the name, nor leading/trailing newline. */
1127 print_var_function (var
)
1132 if (function_p (var
) && var_isset (var
))
1134 x
= named_function_string ((char *)NULL
, function_cell(var
), FUNC_MULTILINE
|FUNC_EXTERNAL
);
1139 /* **************************************************************** */
1141 /* Dynamic Variables */
1143 /* **************************************************************** */
1145 /* DYNAMIC VARIABLES
1147 These are variables whose values are generated anew each time they are
1148 referenced. These are implemented using a pair of function pointers
1149 in the struct variable: assign_func, which is called from bind_variable
1150 and, if arrays are compiled into the shell, some of the functions in
1151 arrayfunc.c, and dynamic_value, which is called from find_variable.
1153 assign_func is called from bind_variable_internal, if
1154 bind_variable_internal discovers that the variable being assigned to
1155 has such a function. The function is called as
1156 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value, ind)
1157 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
1158 is usually ENTRY (self). IND is an index for an array variable, and
1161 dynamic_value is called from find_variable_internal to return a `new'
1162 value for the specified dynamic variable. If this function is NULL,
1163 the variable is treated as a `normal' shell variable. If it is not,
1164 however, then this function is called like this:
1165 tempvar = (*(var->dynamic_value)) (var);
1167 Sometimes `tempvar' will replace the value of `var'. Other times, the
1168 shell will simply use the string value. Pretty object-oriented, huh?
1170 Be warned, though: if you `unset' a special variable, it loses its
1171 special meaning, even if you subsequently set it.
1173 The special assignment code would probably have been better put in
1174 subst.c: do_assignment_internal, in the same style as
1175 stupidly_hack_special_variables, but I wanted the changes as
1176 localized as possible. */
1178 #define INIT_DYNAMIC_VAR(var, val, gfunc, afunc) \
1181 v = bind_variable (var, (val), 0); \
1182 v->dynamic_value = gfunc; \
1183 v->assign_func = afunc; \
1187 #define INIT_DYNAMIC_ARRAY_VAR(var, gfunc, afunc) \
1190 v = make_new_array_variable (var); \
1191 v->dynamic_value = gfunc; \
1192 v->assign_func = afunc; \
1196 #define INIT_DYNAMIC_ASSOC_VAR(var, gfunc, afunc) \
1199 v = make_new_assoc_variable (var); \
1200 v->dynamic_value = gfunc; \
1201 v->assign_func = afunc; \
1206 null_assign (self
, value
, unused
, key
)
1215 #if defined (ARRAY_VARS)
1217 null_array_assign (self
, value
, ind
, key
)
1227 /* Degenerate `dynamic_value' function; just returns what's passed without
1236 #if defined (ARRAY_VARS)
1237 /* A generic dynamic array variable initializer. Initialize array variable
1238 NAME with dynamic value function GETFUNC and assignment function SETFUNC. */
1240 init_dynamic_array_var (name
, getfunc
, setfunc
, attrs
)
1242 sh_var_value_func_t
*getfunc
;
1243 sh_var_assign_func_t
*setfunc
;
1248 v
= find_variable (name
);
1251 INIT_DYNAMIC_ARRAY_VAR (name
, getfunc
, setfunc
);
1253 VSETATTR (v
, attrs
);
1258 init_dynamic_assoc_var (name
, getfunc
, setfunc
, attrs
)
1260 sh_var_value_func_t
*getfunc
;
1261 sh_var_assign_func_t
*setfunc
;
1266 v
= find_variable (name
);
1269 INIT_DYNAMIC_ASSOC_VAR (name
, getfunc
, setfunc
);
1271 VSETATTR (v
, attrs
);
1276 /* The value of $SECONDS. This is the number of seconds since shell
1277 invocation, or, the number of seconds since the last assignment + the
1278 value of the last assignment. */
1279 static intmax_t seconds_value_assigned
;
1282 assign_seconds (self
, value
, unused
, key
)
1291 if (integer_p (self
))
1292 nval
= evalexp (value
, 0, &expok
);
1294 expok
= legal_number (value
, &nval
);
1295 seconds_value_assigned
= expok
? nval
: 0;
1296 gettimeofday (&shellstart
, NULL
);
1297 shell_start_time
= shellstart
.tv_sec
;
1305 time_t time_since_start
;
1309 gettimeofday(&tv
, NULL
);
1310 time_since_start
= tv
.tv_sec
- shell_start_time
;
1311 p
= itos(seconds_value_assigned
+ time_since_start
);
1313 FREE (value_cell (var
));
1315 VSETATTR (var
, att_integer
);
1316 var_setvalue (var
, p
);
1325 v
= find_variable ("SECONDS");
1328 if (legal_number (value_cell(v
), &seconds_value_assigned
) == 0)
1329 seconds_value_assigned
= 0;
1331 INIT_DYNAMIC_VAR ("SECONDS", (v
? value_cell (v
) : (char *)NULL
), get_seconds
, assign_seconds
);
1335 /* Functions for $RANDOM and $SRANDOM */
1337 int last_random_value
;
1338 static int seeded_subshell
= 0;
1341 assign_random (self
, value
, unused
, key
)
1350 if (integer_p (self
))
1351 seedval
= evalexp (value
, 0, &expok
);
1353 expok
= legal_number (value
, &seedval
);
1357 if (subshell_environment
)
1358 seeded_subshell
= getpid ();
1363 get_random_number ()
1367 /* Reset for command and process substitution. */
1369 if (subshell_environment
&& seeded_subshell
!= pid
)
1372 seeded_subshell
= pid
;
1377 while (rv
== last_random_value
);
1379 return (last_random_value
= rv
);
1389 rv
= get_random_number ();
1392 FREE (value_cell (var
));
1394 VSETATTR (var
, att_integer
);
1395 var_setvalue (var
, p
);
1406 rv
= get_urandom32 ();
1409 FREE (value_cell (var
));
1411 VSETATTR (var
, att_integer
);
1412 var_setvalue (var
, p
);
1417 assign_lineno (var
, value
, unused
, key
)
1425 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1427 line_number
= line_number_base
= new_value
;
1431 /* Function which returns the current line number. */
1439 ln
= executing_line_number ();
1441 FREE (value_cell (var
));
1442 var_setvalue (var
, p
);
1447 assign_subshell (var
, value
, unused
, key
)
1455 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1457 subshell_level
= new_value
;
1467 p
= itos (subshell_level
);
1468 FREE (value_cell (var
));
1469 var_setvalue (var
, p
);
1474 get_epochseconds (var
)
1483 FREE (value_cell (var
));
1484 var_setvalue (var
, p
);
1489 get_epochrealtime (var
)
1496 gettimeofday (&tv
, NULL
);
1497 snprintf (buf
, sizeof (buf
), "%u%c%06u", (unsigned)tv
.tv_sec
,
1499 (unsigned)tv
.tv_usec
);
1501 p
= savestring (buf
);
1502 FREE (value_cell (var
));
1503 var_setvalue (var
, p
);
1517 FREE (value_cell (var
));
1518 VSETATTR (var
, att_integer
); /* XXX - was also att_readonly */
1519 var_setvalue (var
, p
);
1524 get_bush_argv0 (var
)
1529 p
= savestring (dollar_vars
[0]);
1530 FREE (value_cell (var
));
1531 var_setvalue (var
, p
);
1535 static char *static_shell_name
= 0;
1538 assign_bush_argv0 (var
, value
, unused
, key
)
1549 FREE (dollar_vars
[0]);
1550 dollar_vars
[0] = savestring (value
);
1552 /* Need these gyrations because shell_name isn't dynamically allocated */
1553 vlen
= STRLEN (value
);
1554 static_shell_name
= xrealloc (static_shell_name
, vlen
+ 1);
1555 strcpy (static_shell_name
, value
);
1557 shell_name
= static_shell_name
;
1566 v
= find_variable ("BUSH_ARGV0");
1567 if (v
&& imported_p (v
))
1568 assign_bush_argv0 (v
, value_cell (v
), 0, 0);
1572 get_bush_command (var
)
1577 if (the_printed_command_except_trap
)
1578 p
= savestring (the_printed_command_except_trap
);
1581 p
= (char *)xmalloc (1);
1584 FREE (value_cell (var
));
1585 var_setvalue (var
, p
);
1589 #if defined (HISTORY)
1597 /* Do the same adjustment here we do in parse.y:prompt_history_number,
1598 assuming that we are in one of two states: decoding this as part of
1599 the prompt string, in which case we do not want to assume that the
1600 command has been saved to the history and the history number incremented,
1601 or the expansion is part of the current command being executed and has
1602 already been saved to history and the history number incremented.
1603 Right now we use EXECUTING as the determinant. */
1604 n
= history_number () - executing
;
1606 FREE (value_cell (var
));
1607 var_setvalue (var
, p
);
1612 #if defined (READLINE)
1613 /* When this function returns, VAR->value points to malloced memory. */
1615 get_comp_wordbreaks (var
)
1618 /* If we don't have anything yet, assign a default value. */
1619 if (rl_completer_word_break_characters
== 0 && bush_readline_initialized
== 0)
1620 enable_hostname_completion (perform_hostname_completion
);
1622 FREE (value_cell (var
));
1623 var_setvalue (var
, savestring (rl_completer_word_break_characters
));
1628 /* When this function returns, rl_completer_word_break_characters points to
1631 assign_comp_wordbreaks (self
, value
, unused
, key
)
1637 if (rl_completer_word_break_characters
&&
1638 rl_completer_word_break_characters
!= rl_basic_word_break_characters
)
1639 free (rl_completer_word_break_characters
);
1641 rl_completer_word_break_characters
= savestring (value
);
1644 #endif /* READLINE */
1646 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1648 assign_dirstack (self
, value
, ind
, key
)
1654 set_dirstack_element (ind
, 1, value
);
1665 l
= get_directory_stack (0);
1666 a
= array_from_word_list (l
);
1667 array_dispose (array_cell (self
));
1669 var_setarray (self
, a
);
1672 #endif /* PUSHD AND POPD && ARRAY_VARS */
1674 #if defined (ARRAY_VARS)
1675 /* We don't want to initialize the group set with a call to getgroups()
1676 unless we're asked to, but we only want to do it once. */
1684 static char **group_set
= (char **)NULL
;
1688 group_set
= get_group_list (&ng
);
1689 a
= array_cell (self
);
1690 for (i
= 0; i
< ng
; i
++)
1691 array_insert (a
, i
, group_set
[i
]);
1696 # if defined (DEBUGGER)
1698 get_bushargcv (self
)
1701 static int self_semaphore
= 0;
1703 /* Backwards compatibility: if we refer to BUSH_ARGV or BUSH_ARGC at the
1704 top level without enabling debug mode, and we don't have an instance
1705 of the variable set, initialize the arg arrays.
1706 This will already have been done if debugging_mode != 0. */
1707 if (self_semaphore
== 0 && variable_context
== 0 && debugging_mode
== 0) /* don't do it for shell functions */
1718 build_hashcmd (self
)
1724 BUCKET_CONTENTS
*item
;
1726 h
= assoc_cell (self
);
1730 if (hashed_filenames
== 0 || HASH_ENTRIES (hashed_filenames
) == 0)
1732 var_setvalue (self
, (char *)NULL
);
1736 h
= assoc_create (hashed_filenames
->nbuckets
);
1737 for (i
= 0; i
< hashed_filenames
->nbuckets
; i
++)
1739 for (item
= hash_items (i
, hashed_filenames
); item
; item
= item
->next
)
1741 k
= savestring (item
->key
);
1742 v
= pathdata(item
)->path
;
1743 assoc_insert (h
, k
, v
);
1747 var_setvalue (self
, (char *)h
);
1755 build_hashcmd (self
);
1760 assign_hashcmd (self
, value
, ind
, key
)
1766 #if defined (RESTRICTED_SHELL)
1771 if (strchr (value
, '/'))
1773 sh_restricted (value
);
1774 return (SHELL_VAR
*)NULL
;
1776 /* If we are changing the hash table in a restricted shell, make sure the
1777 target pathname can be found using a $PATH search. */
1778 full_path
= find_user_command (value
);
1779 if (full_path
== 0 || *full_path
== 0 || executable_file (full_path
) == 0)
1781 sh_notfound (value
);
1783 return ((SHELL_VAR
*)NULL
);
1788 phash_insert (key
, value
, 0, 0);
1789 return (build_hashcmd (self
));
1794 build_aliasvar (self
)
1800 BUCKET_CONTENTS
*item
;
1802 h
= assoc_cell (self
);
1806 if (aliases
== 0 || HASH_ENTRIES (aliases
) == 0)
1808 var_setvalue (self
, (char *)NULL
);
1812 h
= assoc_create (aliases
->nbuckets
);
1813 for (i
= 0; i
< aliases
->nbuckets
; i
++)
1815 for (item
= hash_items (i
, aliases
); item
; item
= item
->next
)
1817 k
= savestring (item
->key
);
1818 v
= ((alias_t
*)(item
->data
))->value
;
1819 assoc_insert (h
, k
, v
);
1823 var_setvalue (self
, (char *)h
);
1831 build_aliasvar (self
);
1836 assign_aliasvar (self
, value
, ind
, key
)
1842 if (legal_alias_name (key
, 0) == 0)
1844 report_error (_("`%s': invalid alias name"), key
);
1847 add_alias (key
, value
);
1848 return (build_aliasvar (self
));
1852 #endif /* ARRAY_VARS */
1854 /* If ARRAY_VARS is not defined, this just returns the name of any
1855 currently-executing function. If we have arrays, it's a call stack. */
1860 #if ! defined (ARRAY_VARS)
1862 if (variable_context
&& this_shell_function
)
1864 FREE (value_cell (self
));
1865 t
= savestring (this_shell_function
->name
);
1866 var_setvalue (self
, t
);
1873 make_funcname_visible (on_or_off
)
1878 v
= find_variable ("FUNCNAME");
1879 if (v
== 0 || v
->dynamic_value
== 0)
1883 VUNSETATTR (v
, att_invisible
);
1885 VSETATTR (v
, att_invisible
);
1889 init_funcname_var ()
1893 v
= find_variable ("FUNCNAME");
1896 #if defined (ARRAY_VARS)
1897 INIT_DYNAMIC_ARRAY_VAR ("FUNCNAME", get_funcname
, null_array_assign
);
1899 INIT_DYNAMIC_VAR ("FUNCNAME", (char *)NULL
, get_funcname
, null_assign
);
1901 VSETATTR (v
, att_invisible
|att_noassign
);
1906 initialize_dynamic_variables ()
1910 v
= init_seconds_var ();
1912 INIT_DYNAMIC_VAR ("BUSH_ARGV0", (char *)NULL
, get_bush_argv0
, assign_bush_argv0
);
1914 INIT_DYNAMIC_VAR ("BUSH_COMMAND", (char *)NULL
, get_bush_command
, (sh_var_assign_func_t
*)NULL
);
1915 INIT_DYNAMIC_VAR ("BUSH_SUBSHELL", (char *)NULL
, get_subshell
, assign_subshell
);
1917 INIT_DYNAMIC_VAR ("RANDOM", (char *)NULL
, get_random
, assign_random
);
1918 VSETATTR (v
, att_integer
);
1919 INIT_DYNAMIC_VAR ("SRANDOM", (char *)NULL
, get_urandom
, (sh_var_assign_func_t
*)NULL
);
1920 VSETATTR (v
, att_integer
);
1921 INIT_DYNAMIC_VAR ("LINENO", (char *)NULL
, get_lineno
, assign_lineno
);
1922 VSETATTR (v
, att_regenerate
);
1924 INIT_DYNAMIC_VAR ("BUSHPID", (char *)NULL
, get_bushpid
, null_assign
);
1925 VSETATTR (v
, att_integer
);
1927 INIT_DYNAMIC_VAR ("EPOCHSECONDS", (char *)NULL
, get_epochseconds
, null_assign
);
1928 VSETATTR (v
, att_regenerate
);
1929 INIT_DYNAMIC_VAR ("EPOCHREALTIME", (char *)NULL
, get_epochrealtime
, null_assign
);
1930 VSETATTR (v
, att_regenerate
);
1932 #if defined (HISTORY)
1933 INIT_DYNAMIC_VAR ("HISTCMD", (char *)NULL
, get_histcmd
, (sh_var_assign_func_t
*)NULL
);
1934 VSETATTR (v
, att_integer
);
1937 #if defined (READLINE)
1938 INIT_DYNAMIC_VAR ("COMP_WORDBREAKS", (char *)NULL
, get_comp_wordbreaks
, assign_comp_wordbreaks
);
1941 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1942 v
= init_dynamic_array_var ("DIRSTACK", get_dirstack
, assign_dirstack
, 0);
1943 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1945 #if defined (ARRAY_VARS)
1946 v
= init_dynamic_array_var ("GROUPS", get_groupset
, null_array_assign
, att_noassign
);
1948 # if defined (DEBUGGER)
1949 v
= init_dynamic_array_var ("BUSH_ARGC", get_bushargcv
, null_array_assign
, att_noassign
|att_nounset
);
1950 v
= init_dynamic_array_var ("BUSH_ARGV", get_bushargcv
, null_array_assign
, att_noassign
|att_nounset
);
1951 # endif /* DEBUGGER */
1952 v
= init_dynamic_array_var ("BUSH_SOURCE", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1953 v
= init_dynamic_array_var ("BUSH_LINENO", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1955 v
= init_dynamic_assoc_var ("BUSH_CMDS", get_hashcmd
, assign_hashcmd
, att_nofree
);
1956 # if defined (ALIAS)
1957 v
= init_dynamic_assoc_var ("BUSH_ALIASES", get_aliasvar
, assign_aliasvar
, att_nofree
);
1961 v
= init_funcname_var ();
1964 /* **************************************************************** */
1966 /* Retrieving variables and values */
1968 /* **************************************************************** */
1975 return (var
->value
!= 0);
1982 return (var
->value
== 0);
1986 /* How to get a pointer to the shell variable or function named NAME.
1987 HASHED_VARS is a pointer to the hash table containing the list
1988 of interest (either variables or functions). */
1991 hash_lookup (name
, hashed_vars
)
1993 HASH_TABLE
*hashed_vars
;
1995 BUCKET_CONTENTS
*bucket
;
1997 bucket
= hash_search (name
, hashed_vars
, 0);
1998 /* If we find the name in HASHED_VARS, set LAST_TABLE_SEARCHED to that
2001 last_table_searched
= hashed_vars
;
2002 return (bucket
? (SHELL_VAR
*)bucket
->data
: (SHELL_VAR
*)NULL
);
2006 var_lookup (name
, vcontext
)
2008 VAR_CONTEXT
*vcontext
;
2013 v
= (SHELL_VAR
*)NULL
;
2014 for (vc
= vcontext
; vc
; vc
= vc
->down
)
2015 if (v
= hash_lookup (name
, vc
->table
))
2021 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
2022 then also search the temporarily built list of exported variables.
2023 The lookup order is:
2025 shell_variables list
2029 find_variable_internal (name
, flags
)
2034 int search_tempenv
, force_tempenv
;
2037 var
= (SHELL_VAR
*)NULL
;
2039 force_tempenv
= (flags
& FV_FORCETEMPENV
);
2041 /* If explicitly requested, first look in the temporary environment for
2042 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
2043 to get the `exported' value of $foo. This happens if we are executing
2044 a function or builtin, or if we are looking up a variable in a
2045 "subshell environment". */
2046 search_tempenv
= force_tempenv
|| (expanding_redir
== 0 && subshell_environment
);
2048 if (search_tempenv
&& temporary_env
)
2049 var
= hash_lookup (name
, temporary_env
);
2053 if ((flags
& FV_SKIPINVISIBLE
) == 0)
2054 var
= var_lookup (name
, shell_variables
);
2057 /* essentially var_lookup expanded inline so we can check for
2059 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2061 var
= hash_lookup (name
, vc
->table
);
2062 if (var
&& invisible_p (var
))
2071 return ((SHELL_VAR
*)NULL
);
2073 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2076 /* Look up and resolve the chain of nameref variables starting at V all the
2077 way to NULL or non-nameref. */
2079 find_variable_nameref (v
)
2084 SHELL_VAR
*orig
, *oldv
;
2088 while (v
&& nameref_p (v
))
2091 if (level
> NAMEREF_MAX
)
2092 return ((SHELL_VAR
*)0); /* error message here? */
2093 newname
= nameref_cell (v
);
2094 if (newname
== 0 || *newname
== '\0')
2095 return ((SHELL_VAR
*)0);
2098 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2099 flags
|= FV_FORCETEMPENV
;
2100 /* We don't handle array subscripts here. */
2101 v
= find_variable_internal (newname
, flags
);
2102 if (v
== orig
|| v
== oldv
)
2104 internal_warning (_("%s: circular name reference"), orig
->name
);
2106 /* XXX - provisional change - circular refs go to
2107 global scope for resolution, without namerefs. */
2108 if (variable_context
&& v
->context
)
2109 return (find_global_variable_noref (v
->name
));
2112 return ((SHELL_VAR
*)0);
2118 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
2120 find_variable_last_nameref (name
, vflags
)
2128 nv
= v
= find_variable_noref (name
);
2130 while (v
&& nameref_p (v
))
2133 if (level
> NAMEREF_MAX
)
2134 return ((SHELL_VAR
*)0); /* error message here? */
2135 newname
= nameref_cell (v
);
2136 if (newname
== 0 || *newname
== '\0')
2137 return ((vflags
&& invisible_p (v
)) ? v
: (SHELL_VAR
*)0);
2140 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2141 flags
|= FV_FORCETEMPENV
;
2142 /* We don't accommodate array subscripts here. */
2143 v
= find_variable_internal (newname
, flags
);
2148 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
2150 find_global_variable_last_nameref (name
, vflags
)
2158 nv
= v
= find_global_variable_noref (name
);
2160 while (v
&& nameref_p (v
))
2163 if (level
> NAMEREF_MAX
)
2164 return ((SHELL_VAR
*)0); /* error message here? */
2165 newname
= nameref_cell (v
);
2166 if (newname
== 0 || *newname
== '\0')
2167 return ((vflags
&& invisible_p (v
)) ? v
: (SHELL_VAR
*)0);
2169 /* We don't accommodate array subscripts here. */
2170 v
= find_global_variable_noref (newname
);
2176 find_nameref_at_context (v
, vc
)
2180 SHELL_VAR
*nv
, *nv2
;
2186 while (nv
&& nameref_p (nv
))
2189 if (level
> NAMEREF_MAX
)
2190 return (&nameref_maxloop_value
);
2191 newname
= nameref_cell (nv
);
2192 if (newname
== 0 || *newname
== '\0')
2193 return ((SHELL_VAR
*)NULL
);
2194 nv2
= hash_lookup (newname
, vc
->table
);
2202 /* Do nameref resolution from the VC, which is the local context for some
2203 function or builtin, `up' the chain to the global variables context. If
2204 NVCP is not NULL, return the variable context where we finally ended the
2205 nameref resolution (so the bind_variable_internal can use the correct
2206 variable context and hash table). */
2208 find_variable_nameref_context (v
, vc
, nvcp
)
2213 SHELL_VAR
*nv
, *nv2
;
2216 /* Look starting at the current context all the way `up' */
2217 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
2219 nv2
= find_nameref_at_context (nv
, nvc
);
2220 if (nv2
== &nameref_maxloop_value
)
2221 return (nv2
); /* XXX */
2227 if (nameref_p (nv
) == 0)
2230 return (nameref_p (nv
) ? (SHELL_VAR
*)NULL
: nv
);
2233 /* Do nameref resolution from the VC, which is the local context for some
2234 function or builtin, `up' the chain to the global variables context. If
2235 NVCP is not NULL, return the variable context where we finally ended the
2236 nameref resolution (so the bind_variable_internal can use the correct
2237 variable context and hash table). */
2239 find_variable_last_nameref_context (v
, vc
, nvcp
)
2244 SHELL_VAR
*nv
, *nv2
;
2247 /* Look starting at the current context all the way `up' */
2248 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
2250 nv2
= find_nameref_at_context (nv
, nvc
);
2251 if (nv2
== &nameref_maxloop_value
)
2252 return (nv2
); /* XXX */
2259 return (nameref_p (nv
) ? nv
: (SHELL_VAR
*)NULL
);
2263 find_variable_nameref_for_create (name
, flags
)
2269 /* See if we have a nameref pointing to a variable that hasn't been
2271 var
= find_variable_last_nameref (name
, 1);
2272 if ((flags
&1) && var
&& nameref_p (var
) && invisible_p (var
))
2274 internal_warning (_("%s: removing nameref attribute"), name
);
2275 VUNSETATTR (var
, att_nameref
);
2277 if (var
&& nameref_p (var
))
2279 if (legal_identifier (nameref_cell (var
)) == 0)
2281 sh_invalidid (nameref_cell (var
) ? nameref_cell (var
) : "");
2282 return ((SHELL_VAR
*)INVALID_NAMEREF_VALUE
);
2289 find_variable_nameref_for_assignment (name
, flags
)
2295 /* See if we have a nameref pointing to a variable that hasn't been
2297 var
= find_variable_last_nameref (name
, 1);
2298 if (var
&& nameref_p (var
) && invisible_p (var
)) /* XXX - flags */
2300 internal_warning (_("%s: removing nameref attribute"), name
);
2301 VUNSETATTR (var
, att_nameref
);
2303 if (var
&& nameref_p (var
))
2305 if (valid_nameref_value (nameref_cell (var
), 1) == 0)
2307 sh_invalidid (nameref_cell (var
) ? nameref_cell (var
) : "");
2308 return ((SHELL_VAR
*)INVALID_NAMEREF_VALUE
);
2314 /* If find_variable (name) returns NULL, check that it's not a nameref
2315 referencing a variable that doesn't exist. If it is, return the new
2316 name. If not, return the original name. Kind of like the previous
2317 function, but dealing strictly with names. This takes assignment flags
2318 so it can deal with the various assignment modes used by `declare'. */
2320 nameref_transform_name (name
, flags
)
2328 if (flags
& ASS_MKLOCAL
)
2330 v
= find_variable_last_nameref (name
, 1);
2331 /* If we're making local variables, only follow namerefs that point to
2332 non-existent variables at the same variable context. */
2333 if (v
&& v
->context
!= variable_context
)
2336 else if (flags
& ASS_MKGLOBAL
)
2337 v
= (flags
& ASS_CHKLOCAL
) ? find_variable_last_nameref (name
, 1)
2338 : find_global_variable_last_nameref (name
, 1);
2339 if (v
&& nameref_p (v
) && valid_nameref_value (nameref_cell (v
), 1))
2340 return nameref_cell (v
);
2344 /* Find a variable, forcing a search of the temporary environment first */
2346 find_variable_tempenv (name
)
2351 var
= find_variable_internal (name
, FV_FORCETEMPENV
);
2352 if (var
&& nameref_p (var
))
2353 var
= find_variable_nameref (var
);
2357 /* Find a variable, not forcing a search of the temporary environment first */
2359 find_variable_notempenv (name
)
2364 var
= find_variable_internal (name
, 0);
2365 if (var
&& nameref_p (var
))
2366 var
= find_variable_nameref (var
);
2371 find_global_variable (name
)
2376 var
= var_lookup (name
, global_variables
);
2377 if (var
&& nameref_p (var
))
2378 var
= find_variable_nameref (var
);
2381 return ((SHELL_VAR
*)NULL
);
2383 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2387 find_global_variable_noref (name
)
2392 var
= var_lookup (name
, global_variables
);
2395 return ((SHELL_VAR
*)NULL
);
2397 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2401 find_shell_variable (name
)
2406 var
= var_lookup (name
, shell_variables
);
2407 if (var
&& nameref_p (var
))
2408 var
= find_variable_nameref (var
);
2411 return ((SHELL_VAR
*)NULL
);
2413 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2416 /* Look up the variable entry named NAME. Returns the entry or NULL. */
2418 find_variable (name
)
2424 last_table_searched
= 0;
2426 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2427 flags
|= FV_FORCETEMPENV
;
2428 v
= find_variable_internal (name
, flags
);
2429 if (v
&& nameref_p (v
))
2430 v
= find_variable_nameref (v
);
2434 /* Find the first instance of NAME in the variable context chain; return first
2435 one found without att_invisible set; return 0 if no non-invisible instances
2438 find_variable_no_invisible (name
)
2444 last_table_searched
= 0;
2445 flags
= FV_SKIPINVISIBLE
;
2446 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2447 flags
|= FV_FORCETEMPENV
;
2448 v
= find_variable_internal (name
, flags
);
2449 if (v
&& nameref_p (v
))
2450 v
= find_variable_nameref (v
);
2454 /* Find the first instance of NAME in the variable context chain; return first
2455 one found even if att_invisible set. */
2457 find_variable_for_assignment (name
)
2463 last_table_searched
= 0;
2465 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2466 flags
|= FV_FORCETEMPENV
;
2467 v
= find_variable_internal (name
, flags
);
2468 if (v
&& nameref_p (v
))
2469 v
= find_variable_nameref (v
);
2474 find_variable_noref (name
)
2481 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2482 flags
|= FV_FORCETEMPENV
;
2483 v
= find_variable_internal (name
, flags
);
2487 /* Look up the function entry whose name matches STRING.
2488 Returns the entry or NULL. */
2490 find_function (name
)
2493 return (hash_lookup (name
, shell_functions
));
2496 /* Find the function definition for the shell function named NAME. Returns
2497 the entry or NULL. */
2499 find_function_def (name
)
2502 #if defined (DEBUGGER)
2503 return ((FUNCTION_DEF
*)hash_lookup (name
, shell_function_defs
));
2505 return ((FUNCTION_DEF
*)0);
2509 /* Return the value of VAR. VAR is assumed to have been the result of a
2510 lookup without any subscript, if arrays are compiled into the shell. */
2512 get_variable_value (var
)
2516 return ((char *)NULL
);
2517 #if defined (ARRAY_VARS)
2518 else if (array_p (var
))
2519 return (array_reference (array_cell (var
), 0));
2520 else if (assoc_p (var
))
2521 return (assoc_reference (assoc_cell (var
), "0"));
2524 return (value_cell (var
));
2527 /* Return the string value of a variable. Return NULL if the variable
2528 doesn't exist. Don't cons a new string. This is a potential memory
2529 leak if the variable is found in the temporary environment, but doesn't
2530 leak in practice. Since functions and variables have separate name
2531 spaces, returns NULL if var_name is a shell function only. */
2533 get_string_value (var_name
)
2534 const char *var_name
;
2538 var
= find_variable (var_name
);
2539 return ((var
) ? get_variable_value (var
) : (char *)NULL
);
2542 /* This is present for use by the tilde and readline libraries. */
2544 sh_get_env_value (v
)
2547 return get_string_value (v
);
2550 /* **************************************************************** */
2552 /* Creating and setting variables */
2554 /* **************************************************************** */
2557 var_sametype (v1
, v2
)
2561 if (v1
== 0 || v2
== 0)
2563 #if defined (ARRAY_VARS)
2564 else if (assoc_p (v1
) && assoc_p (v2
))
2566 else if (array_p (v1
) && array_p (v2
))
2568 else if (array_p (v1
) || array_p (v2
))
2570 else if (assoc_p (v1
) || assoc_p (v2
))
2578 validate_inherited_value (var
, type
)
2582 #if defined (ARRAY_VARS)
2583 if (type
== att_array
&& assoc_p (var
))
2585 else if (type
== att_assoc
&& array_p (var
))
2589 return 1; /* should we run convert_var_to_array here or let the caller? */
2592 /* Set NAME to VALUE if NAME has no value. */
2594 set_if_not (name
, value
)
2599 if (shell_variables
== 0)
2600 create_variable_tables ();
2602 v
= find_variable (name
);
2604 v
= bind_variable_internal (name
, value
, global_variables
->table
, HASH_NOSRCH
, 0);
2608 /* Create a local variable referenced by NAME. */
2610 make_local_variable (name
, flags
)
2614 SHELL_VAR
*new_var
, *old_var
, *old_ref
;
2619 /* We don't want to follow the nameref chain when making local variables; we
2620 just want to create them. */
2621 old_ref
= find_variable_noref (name
);
2622 if (old_ref
&& nameref_p (old_ref
) == 0)
2624 /* local foo; local foo; is a no-op. */
2625 old_var
= find_variable (name
);
2626 if (old_ref
== 0 && old_var
&& local_p (old_var
) && old_var
->context
== variable_context
)
2629 /* local -n foo; local -n foo; is a no-op. */
2630 if (old_ref
&& local_p (old_ref
) && old_ref
->context
== variable_context
)
2633 /* From here on, we want to use the refvar, not the variable it references */
2637 was_tmpvar
= old_var
&& tempvar_p (old_var
);
2638 /* If we're making a local variable in a shell function, the temporary env
2639 has already been merged into the function's variable context stack. We
2640 can assume that a temporary var in the same context appears in the same
2641 VAR_CONTEXT and can safely be returned without creating a new variable
2642 (which results in duplicate names in the same VAR_CONTEXT->table */
2643 /* We can't just test tmpvar_p because variables in the temporary env given
2644 to a shell function appear in the function's local variable VAR_CONTEXT
2645 but retain their tempvar attribute. We want temporary variables that are
2646 found in temporary_env, hence the test for last_table_searched, which is
2647 set in hash_lookup and only (so far) checked here. */
2648 if (was_tmpvar
&& old_var
->context
== variable_context
&& last_table_searched
!= temporary_env
)
2650 VUNSETATTR (old_var
, att_invisible
); /* XXX */
2651 /* We still want to flag this variable as local, though, and set things
2652 up so that it gets treated as a local variable. */
2654 /* Since we found the variable in a temporary environment, this will
2656 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2657 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
2659 goto set_local_var_flags
;
2664 /* If we want to change to "inherit the old variable's value" semantics,
2665 here is where to save the old value. */
2666 old_value
= was_tmpvar
? value_cell (old_var
) : (char *)NULL
;
2668 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2669 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
2674 internal_error (_("make_local_variable: no function context at current scope"));
2675 return ((SHELL_VAR
*)NULL
);
2677 else if (vc
->table
== 0)
2678 vc
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
2680 /* Since this is called only from the local/declare/typeset code, we can
2681 call builtin_error here without worry (of course, it will also work
2682 for anything that sets this_command_name). Variables with the `noassign'
2683 attribute may not be made local. The test against old_var's context
2684 level is to disallow local copies of readonly global variables (since I
2685 believe that this could be a security hole). Readonly copies of calling
2686 function local variables are OK. */
2687 if (old_var
&& (noassign_p (old_var
) ||
2688 (readonly_p (old_var
) && old_var
->context
== 0)))
2690 if (readonly_p (old_var
))
2692 else if (noassign_p (old_var
))
2693 builtin_error (_("%s: variable may not be assigned value"), name
);
2695 /* Let noassign variables through with a warning */
2696 if (readonly_p (old_var
))
2698 return ((SHELL_VAR
*)NULL
);
2702 new_var
= make_new_variable (name
, vc
->table
);
2705 new_var
= make_new_variable (name
, vc
->table
);
2707 /* If we found this variable in one of the temporary environments,
2708 inherit its value. Watch to see if this causes problems with
2709 things like `x=4 local x'. XXX - see above for temporary env
2710 variables with the same context level as variable_context */
2711 /* XXX - we should only do this if the variable is not an array. */
2712 /* If we want to change the local variable semantics to "inherit
2713 the old variable's value" here is where to set it. And we would
2714 need to use copy_variable (currently unused) to do it for all
2715 possible variable values. */
2717 var_setvalue (new_var
, savestring (old_value
));
2718 else if (localvar_inherit
|| (flags
& MKLOC_INHERIT
))
2720 /* This may not make sense for nameref variables that are shadowing
2721 variables with the same name, but we don't know that yet. */
2722 #if defined (ARRAY_VARS)
2723 if (assoc_p (old_var
))
2724 var_setassoc (new_var
, assoc_copy (assoc_cell (old_var
)));
2725 else if (array_p (old_var
))
2726 var_setarray (new_var
, array_copy (array_cell (old_var
)));
2727 else if (value_cell (old_var
))
2729 if (value_cell (old_var
))
2731 var_setvalue (new_var
, savestring (value_cell (old_var
)));
2733 var_setvalue (new_var
, (char *)NULL
);
2736 if (localvar_inherit
|| (flags
& MKLOC_INHERIT
))
2738 /* It doesn't make sense to inherit the nameref attribute */
2739 new_var
->attributes
= old_var
->attributes
& ~att_nameref
;
2740 new_var
->dynamic_value
= old_var
->dynamic_value
;
2741 new_var
->assign_func
= old_var
->assign_func
;
2744 /* We inherit the export attribute, but no others. */
2745 new_var
->attributes
= exported_p (old_var
) ? att_exported
: 0;
2748 set_local_var_flags
:
2749 vc
->flags
|= VC_HASLOCAL
;
2751 new_var
->context
= variable_context
;
2752 VSETATTR (new_var
, att_local
);
2757 /* value_cell will be 0 if localvar_inherit == 0 or there was no old variable
2758 with the same name or the old variable was invisible */
2759 if (was_tmpvar
== 0 && value_cell (new_var
) == 0)
2760 VSETATTR (new_var
, att_invisible
); /* XXX */
2764 /* Create a new shell variable with name NAME. */
2766 new_shell_variable (name
)
2771 entry
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
2773 entry
->name
= savestring (name
);
2774 var_setvalue (entry
, (char *)NULL
);
2775 CLEAR_EXPORTSTR (entry
);
2777 entry
->dynamic_value
= (sh_var_value_func_t
*)NULL
;
2778 entry
->assign_func
= (sh_var_assign_func_t
*)NULL
;
2780 entry
->attributes
= 0;
2782 /* Always assume variables are to be made at toplevel!
2783 make_local_variable has the responsibility of changing the
2784 variable context. */
2790 /* Create a new shell variable with name NAME and add it to the hash table
2793 make_new_variable (name
, table
)
2798 BUCKET_CONTENTS
*elt
;
2800 entry
= new_shell_variable (name
);
2802 /* Make sure we have a shell_variables hash table to add to. */
2803 if (shell_variables
== 0)
2804 create_variable_tables ();
2806 elt
= hash_insert (savestring (name
), table
, HASH_NOSRCH
);
2807 elt
->data
= (PTR_T
)entry
;
2812 #if defined (ARRAY_VARS)
2814 make_new_array_variable (name
)
2820 entry
= make_new_variable (name
, global_variables
->table
);
2821 array
= array_create ();
2823 var_setarray (entry
, array
);
2824 VSETATTR (entry
, att_array
);
2829 make_local_array_variable (name
, flags
)
2837 assoc_ok
= flags
& MKLOC_ASSOCOK
;
2839 var
= make_local_variable (name
, flags
& MKLOC_INHERIT
); /* XXX for now */
2840 /* If ASSOC_OK is non-zero, assume that we are ok with letting an assoc
2841 variable return to the caller without converting it. The caller will
2842 either flag an error or do the conversion itself. */
2843 if (var
== 0 || array_p (var
) || (assoc_ok
&& assoc_p (var
)))
2846 /* Validate any value we inherited from a variable instance at a previous
2847 scope and discard anything that's invalid. */
2848 if (localvar_inherit
&& assoc_p (var
))
2850 internal_warning ("%s: cannot inherit value from incompatible type", name
);
2851 VUNSETATTR (var
, att_assoc
);
2852 dispose_variable_value (var
);
2853 array
= array_create ();
2854 var_setarray (var
, array
);
2856 else if (localvar_inherit
)
2857 var
= convert_var_to_array (var
); /* XXX */
2860 dispose_variable_value (var
);
2861 array
= array_create ();
2862 var_setarray (var
, array
);
2865 VSETATTR (var
, att_array
);
2870 make_new_assoc_variable (name
)
2876 entry
= make_new_variable (name
, global_variables
->table
);
2877 hash
= assoc_create (ASSOC_HASH_BUCKETS
);
2879 var_setassoc (entry
, hash
);
2880 VSETATTR (entry
, att_assoc
);
2885 make_local_assoc_variable (name
, flags
)
2893 array_ok
= flags
& MKLOC_ARRAYOK
;
2895 var
= make_local_variable (name
, flags
& MKLOC_INHERIT
); /* XXX for now */
2896 /* If ARRAY_OK is non-zero, assume that we are ok with letting an array
2897 variable return to the caller without converting it. The caller will
2898 either flag an error or do the conversion itself. */
2899 if (var
== 0 || assoc_p (var
) || (array_ok
&& array_p (var
)))
2902 /* Validate any value we inherited from a variable instance at a previous
2903 scope and discard anything that's invalid. */
2904 if (localvar_inherit
&& array_p (var
))
2906 internal_warning ("%s: cannot inherit value from incompatible type", name
);
2907 VUNSETATTR (var
, att_array
);
2908 dispose_variable_value (var
);
2909 hash
= assoc_create (ASSOC_HASH_BUCKETS
);
2910 var_setassoc (var
, hash
);
2912 else if (localvar_inherit
)
2913 var
= convert_var_to_assoc (var
); /* XXX */
2916 dispose_variable_value (var
);
2917 hash
= assoc_create (ASSOC_HASH_BUCKETS
);
2918 var_setassoc (var
, hash
);
2921 VSETATTR (var
, att_assoc
);
2927 make_variable_value (var
, value
, flags
)
2932 char *retval
, *oval
;
2933 intmax_t lval
, rval
;
2934 int expok
, olen
, op
;
2936 /* If this variable has had its type set to integer (via `declare -i'),
2937 then do expression evaluation on it and store the result. The
2938 functions in expr.c (evalexp()) and bind_int_variable() are responsible
2939 for turning off the integer flag if they don't want further
2940 evaluation done. Callers that find it inconvenient to do this can set
2941 the ASS_NOEVAL flag. For the special case of arithmetic expression
2942 evaluation, the caller can set ASS_NOLONGJMP to avoid jumping out to
2944 if ((flags
& ASS_NOEVAL
) == 0 && integer_p (var
))
2946 if (flags
& ASS_APPEND
)
2948 oval
= value_cell (var
);
2949 lval
= evalexp (oval
, 0, &expok
); /* ksh93 seems to do this */
2952 if (flags
& ASS_NOLONGJMP
)
2956 top_level_cleanup ();
2957 jump_to_top_level (DISCARD
);
2961 rval
= evalexp (value
, 0, &expok
);
2964 if (flags
& ASS_NOLONGJMP
)
2968 top_level_cleanup ();
2969 jump_to_top_level (DISCARD
);
2972 /* This can be fooled if the variable's value changes while evaluating
2973 `rval'. We can change it if we move the evaluation of lval to here. */
2974 if (flags
& ASS_APPEND
)
2976 retval
= itos (rval
);
2978 #if defined (CASEMOD_ATTRS)
2979 else if ((flags
& ASS_NOEVAL
) == 0 && (capcase_p (var
) || uppercase_p (var
) || lowercase_p (var
)))
2981 if (flags
& ASS_APPEND
)
2983 oval
= get_variable_value (var
);
2984 if (oval
== 0) /* paranoia */
2986 olen
= STRLEN (oval
);
2987 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2988 strcpy (retval
, oval
);
2990 strcpy (retval
+olen
, value
);
2993 retval
= savestring (value
);
2996 retval
= (char *)xmalloc (1);
2999 op
= capcase_p (var
) ? CASE_CAPITALIZE
3000 : (uppercase_p (var
) ? CASE_UPPER
: CASE_LOWER
);
3001 oval
= sh_modcase (retval
, (char *)0, op
);
3005 #endif /* CASEMOD_ATTRS */
3009 if (flags
& ASS_APPEND
)
3011 oval
= get_variable_value (var
);
3012 if (oval
== 0) /* paranoia */
3014 olen
= STRLEN (oval
);
3015 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
3016 strcpy (retval
, oval
);
3018 strcpy (retval
+olen
, value
);
3021 retval
= savestring (value
);
3024 retval
= (char *)xmalloc (1);
3029 retval
= (char *)NULL
;
3034 /* If we can optimize appending to string variables, say so */
3036 can_optimize_assignment (entry
, value
, aflags
)
3041 if ((aflags
& ASS_APPEND
) == 0)
3043 #if defined (ARRAY_VARS)
3044 if (array_p (entry
) || assoc_p (entry
))
3047 if (integer_p (entry
) || uppercase_p (entry
) || lowercase_p (entry
) || capcase_p (entry
))
3049 if (readonly_p (entry
) || noassign_p (entry
))
3054 /* right now we optimize appends to string variables */
3056 optimized_assignment (entry
, value
, aflags
)
3064 v
= value_cell (entry
);
3066 vlen
= STRLEN (value
);
3068 new = (char *)xrealloc (v
, len
+ vlen
+ 8); /* for now */
3075 strcpy (new + len
, value
);
3076 var_setvalue (entry
, new);
3080 /* Bind a variable NAME to VALUE in the HASH_TABLE TABLE, which may be the
3081 temporary environment (but usually is not). HFLAGS controls how NAME
3082 is looked up in TABLE; AFLAGS controls how VALUE is assigned */
3084 bind_variable_internal (name
, value
, table
, hflags
, aflags
)
3090 char *newval
, *tname
;
3091 SHELL_VAR
*entry
, *tentry
;
3093 entry
= (hflags
& HASH_NOSRCH
) ? (SHELL_VAR
*)NULL
: hash_lookup (name
, table
);
3094 /* Follow the nameref chain here if this is the global variables table */
3095 if (entry
&& nameref_p (entry
) && (invisible_p (entry
) == 0) && table
== global_variables
->table
)
3097 entry
= find_global_variable (entry
->name
);
3098 /* Let's see if we have a nameref referencing a variable that hasn't yet
3101 entry
= find_variable_last_nameref (name
, 0); /* XXX */
3102 if (entry
== 0) /* just in case */
3106 /* The first clause handles `declare -n ref; ref=x;' or `declare -n ref;
3108 if (entry
&& invisible_p (entry
) && nameref_p (entry
))
3110 if ((aflags
& ASS_FORCE
) == 0 && value
&& valid_nameref_value (value
, 0) == 0)
3112 sh_invalidid (value
);
3113 return ((SHELL_VAR
*)NULL
);
3117 else if (entry
&& nameref_p (entry
))
3119 newval
= nameref_cell (entry
); /* XXX - newval can't be NULL here */
3120 if (valid_nameref_value (newval
, 0) == 0)
3122 sh_invalidid (newval
);
3123 return ((SHELL_VAR
*)NULL
);
3125 #if defined (ARRAY_VARS)
3126 /* declare -n foo=x[2] ; foo=bar */
3127 if (valid_array_reference (newval
, 0))
3129 tname
= array_variable_name (newval
, 0, (char **)0, (int *)0);
3130 if (tname
&& (tentry
= find_variable_noref (tname
)) && nameref_p (tentry
))
3132 /* nameref variables can't be arrays */
3133 internal_warning (_("%s: removing nameref attribute"), name_cell (tentry
));
3134 FREE (value_cell (tentry
)); /* XXX - bush-4.3 compat */
3135 var_setvalue (tentry
, (char *)NULL
);
3136 VUNSETATTR (tentry
, att_nameref
);
3139 /* XXX - should it be aflags? */
3140 entry
= assign_array_element (newval
, make_variable_value (entry
, value
, aflags
), aflags
|ASS_NAMEREF
);
3147 entry
= make_new_variable (newval
, table
);
3148 var_setvalue (entry
, make_variable_value (entry
, value
, aflags
));
3151 else if (entry
== 0)
3153 entry
= make_new_variable (name
, table
);
3154 var_setvalue (entry
, make_variable_value (entry
, value
, aflags
)); /* XXX */
3156 else if (entry
->assign_func
) /* array vars have assign functions now */
3158 if ((readonly_p (entry
) && (aflags
& ASS_FORCE
) == 0) || noassign_p (entry
))
3160 if (readonly_p (entry
))
3161 err_readonly (name_cell (entry
));
3165 INVALIDATE_EXPORTSTR (entry
);
3166 newval
= (aflags
& ASS_APPEND
) ? make_variable_value (entry
, value
, aflags
) : value
;
3167 if (assoc_p (entry
))
3168 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, savestring ("0"));
3169 else if (array_p (entry
))
3170 entry
= (*(entry
->assign_func
)) (entry
, newval
, 0, 0);
3172 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, 0);
3173 if (newval
!= value
)
3180 if ((readonly_p (entry
) && (aflags
& ASS_FORCE
) == 0) || noassign_p (entry
))
3182 if (readonly_p (entry
))
3183 err_readonly (name_cell (entry
));
3187 /* Variables which are bound are visible. */
3188 VUNSETATTR (entry
, att_invisible
);
3190 /* If we can optimize the assignment, do so and return. Right now, we
3191 optimize appends to string variables. */
3192 if (can_optimize_assignment (entry
, value
, aflags
))
3194 INVALIDATE_EXPORTSTR (entry
);
3195 optimized_assignment (entry
, value
, aflags
);
3197 if (mark_modified_vars
)
3198 VSETATTR (entry
, att_exported
);
3200 if (exported_p (entry
))
3201 array_needs_making
= 1;
3206 #if defined (ARRAY_VARS)
3207 if (assoc_p (entry
) || array_p (entry
))
3208 newval
= make_array_variable_value (entry
, 0, "0", value
, aflags
);
3211 newval
= make_variable_value (entry
, value
, aflags
); /* XXX */
3213 /* Invalidate any cached export string */
3214 INVALIDATE_EXPORTSTR (entry
);
3216 #if defined (ARRAY_VARS)
3217 /* XXX -- this bears looking at again -- XXX */
3218 /* If an existing array variable x is being assigned to with x=b or
3219 `read x' or something of that nature, silently convert it to
3220 x[0]=b or `read x[0]'. */
3221 if (assoc_p (entry
))
3223 assoc_insert (assoc_cell (entry
), savestring ("0"), newval
);
3226 else if (array_p (entry
))
3228 array_insert (array_cell (entry
), 0, newval
);
3234 FREE (value_cell (entry
));
3235 var_setvalue (entry
, newval
);
3239 if (mark_modified_vars
)
3240 VSETATTR (entry
, att_exported
);
3242 if (exported_p (entry
))
3243 array_needs_making
= 1;
3248 /* Bind a variable NAME to VALUE. This conses up the name
3249 and value strings. If we have a temporary environment, we bind there
3250 first, then we bind into shell_variables. */
3253 bind_variable (name
, value
, flags
)
3259 VAR_CONTEXT
*vc
, *nvc
;
3261 if (shell_variables
== 0)
3262 create_variable_tables ();
3264 /* If we have a temporary environment, look there first for the variable,
3265 and, if found, modify the value there before modifying it in the
3266 shell_variables table. This allows sourced scripts to modify values
3267 given to them in a temporary environment while modifying the variable
3268 value that the caller sees. */
3269 if (temporary_env
&& value
) /* XXX - can value be null here? */
3270 bind_tempenv_variable (name
, value
);
3272 /* XXX -- handle local variables here. */
3273 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3275 if (vc_isfuncenv (vc
) || vc_isbltnenv (vc
))
3277 v
= hash_lookup (name
, vc
->table
);
3279 if (v
&& nameref_p (v
))
3281 /* This starts at the context where we found the nameref. If we
3282 want to start the name resolution over again at the original
3283 context, this is where we need to change it */
3284 nv
= find_variable_nameref_context (v
, vc
, &nvc
);
3287 nv
= find_variable_last_nameref_context (v
, vc
, &nvc
);
3288 if (nv
&& nameref_p (nv
))
3290 /* If this nameref variable doesn't have a value yet,
3291 set the value. Otherwise, assign using the value as
3293 if (nameref_cell (nv
) == 0)
3294 return (bind_variable_internal (nv
->name
, value
, nvc
->table
, 0, flags
));
3295 #if defined (ARRAY_VARS)
3296 else if (valid_array_reference (nameref_cell (nv
), 0))
3297 return (assign_array_element (nameref_cell (nv
), value
, flags
));
3300 return (bind_variable_internal (nameref_cell (nv
), value
, nvc
->table
, 0, flags
));
3302 else if (nv
== &nameref_maxloop_value
)
3304 internal_warning (_("%s: circular name reference"), v
->name
);
3305 return (bind_global_variable (v
->name
, value
, flags
));
3310 else if (nv
== &nameref_maxloop_value
)
3312 internal_warning (_("%s: circular name reference"), v
->name
);
3313 return (bind_global_variable (v
->name
, value
, flags
));
3319 return (bind_variable_internal (v
->name
, value
, nvc
->table
, 0, flags
));
3322 /* bind_variable_internal will handle nameref resolution in this case */
3323 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
3327 bind_global_variable (name
, value
, flags
)
3332 if (shell_variables
== 0)
3333 create_variable_tables ();
3335 /* bind_variable_internal will handle nameref resolution in this case */
3336 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
3340 bind_invalid_envvar (name
, value
, flags
)
3345 if (invalid_env
== 0)
3346 invalid_env
= hash_create (64); /* XXX */
3347 return (bind_variable_internal (name
, value
, invalid_env
, HASH_NOSRCH
, flags
));
3350 /* Make VAR, a simple shell variable, have value VALUE. Once assigned a
3351 value, variables are no longer invisible. This is a duplicate of part
3352 of the internals of bind_variable. If the variable is exported, or
3353 all modified variables should be exported, mark the variable for export
3354 and note that the export environment needs to be recreated. */
3356 bind_variable_value (var
, value
, aflags
)
3364 invis
= invisible_p (var
);
3365 VUNSETATTR (var
, att_invisible
);
3367 if (var
->assign_func
)
3369 /* If we're appending, we need the old value, so use
3370 make_variable_value */
3371 t
= (aflags
& ASS_APPEND
) ? make_variable_value (var
, value
, aflags
) : value
;
3372 (*(var
->assign_func
)) (var
, t
, -1, 0);
3373 if (t
!= value
&& t
)
3378 t
= make_variable_value (var
, value
, aflags
);
3379 if ((aflags
& (ASS_NAMEREF
|ASS_FORCE
)) == ASS_NAMEREF
&& check_selfref (name_cell (var
), t
, 0))
3381 if (variable_context
)
3382 internal_warning (_("%s: circular name reference"), name_cell (var
));
3385 internal_error (_("%s: nameref variable self references not allowed"), name_cell (var
));
3388 VSETATTR (var
, att_invisible
); /* XXX */
3389 return ((SHELL_VAR
*)NULL
);
3392 if ((aflags
& ASS_NAMEREF
) && (valid_nameref_value (t
, 0) == 0))
3396 VSETATTR (var
, att_invisible
); /* XXX */
3397 return ((SHELL_VAR
*)NULL
);
3399 FREE (value_cell (var
));
3400 var_setvalue (var
, t
);
3403 INVALIDATE_EXPORTSTR (var
);
3405 if (mark_modified_vars
)
3406 VSETATTR (var
, att_exported
);
3408 if (exported_p (var
))
3409 array_needs_making
= 1;
3414 /* Bind/create a shell variable with the name LHS to the RHS.
3415 This creates or modifies a variable such that it is an integer.
3417 This used to be in expr.c, but it is here so that all of the
3418 variable binding stuff is localized. Since we don't want any
3419 recursive evaluation from bind_variable() (possible without this code,
3420 since bind_variable() calls the evaluator for variables with the integer
3421 attribute set), we temporarily turn off the integer attribute for each
3422 variable we set here, then turn it back on after binding as necessary. */
3425 bind_int_variable (lhs
, rhs
, flags
)
3429 register SHELL_VAR
*v
;
3430 int isint
, isarr
, implicitarray
;
3432 isint
= isarr
= implicitarray
= 0;
3433 #if defined (ARRAY_VARS)
3434 if (valid_array_reference (lhs
, (flags
& ASS_NOEXPAND
) != 0))
3437 v
= array_variable_part (lhs
, (flags
& ASS_NOEXPAND
) != 0, (char **)0, (int *)0);
3439 else if (legal_identifier (lhs
) == 0)
3442 return ((SHELL_VAR
*)NULL
);
3446 v
= find_variable (lhs
);
3450 isint
= integer_p (v
);
3451 VUNSETATTR (v
, att_integer
);
3452 #if defined (ARRAY_VARS)
3453 if (array_p (v
) && isarr
== 0)
3458 #if defined (ARRAY_VARS)
3460 v
= assign_array_element (lhs
, rhs
, flags
);
3461 else if (implicitarray
)
3462 v
= bind_array_variable (lhs
, 0, rhs
, 0); /* XXX - check on flags */
3465 v
= bind_variable (lhs
, rhs
, 0); /* why not use bind_variable_value? */
3470 VSETATTR (v
, att_integer
);
3471 VUNSETATTR (v
, att_invisible
);
3474 if (v
&& nameref_p (v
))
3475 internal_warning (_("%s: assigning integer to name reference"), lhs
);
3481 bind_var_to_int (var
, val
)
3485 char ibuf
[INT_STRLEN_BOUND (intmax_t) + 1], *p
;
3487 p
= fmtulong (val
, 10, ibuf
, sizeof (ibuf
), 0);
3488 return (bind_int_variable (var
, p
, 0));
3491 /* Do a function binding to a variable. You pass the name and
3492 the command to bind to. This conses the name and command. */
3494 bind_function (name
, value
)
3500 entry
= find_function (name
);
3503 BUCKET_CONTENTS
*elt
;
3505 elt
= hash_insert (savestring (name
), shell_functions
, HASH_NOSRCH
);
3506 entry
= new_shell_variable (name
);
3507 elt
->data
= (PTR_T
)entry
;
3510 INVALIDATE_EXPORTSTR (entry
);
3512 if (var_isset (entry
))
3513 dispose_command (function_cell (entry
));
3516 var_setfunc (entry
, copy_command (value
));
3518 var_setfunc (entry
, 0);
3520 VSETATTR (entry
, att_function
);
3522 if (mark_modified_vars
)
3523 VSETATTR (entry
, att_exported
);
3525 VUNSETATTR (entry
, att_invisible
); /* Just to be sure */
3527 if (exported_p (entry
))
3528 array_needs_making
= 1;
3530 #if defined (PROGRAMMABLE_COMPLETION)
3531 set_itemlist_dirty (&it_functions
);
3537 #if defined (DEBUGGER)
3538 /* Bind a function definition, which includes source file and line number
3539 information in addition to the command, into the FUNCTION_DEF hash table.
3540 If (FLAGS & 1), overwrite any existing definition. If FLAGS == 0, leave
3541 any existing definition alone. */
3543 bind_function_def (name
, value
, flags
)
3545 FUNCTION_DEF
*value
;
3548 FUNCTION_DEF
*entry
;
3549 BUCKET_CONTENTS
*elt
;
3552 entry
= find_function_def (name
);
3553 if (entry
&& (flags
& 1))
3555 dispose_function_def_contents (entry
);
3556 entry
= copy_function_def_contents (value
, entry
);
3562 cmd
= value
->command
;
3564 entry
= copy_function_def (value
);
3565 value
->command
= cmd
;
3567 elt
= hash_insert (savestring (name
), shell_function_defs
, HASH_NOSRCH
);
3568 elt
->data
= (PTR_T
*)entry
;
3571 #endif /* DEBUGGER */
3573 /* Add STRING, which is of the form foo=bar, to the temporary environment
3574 HASH_TABLE (temporary_env). The functions in execute_cmd.c are
3575 responsible for moving the main temporary env to one of the other
3576 temporary environments. The expansion code in subst.c calls this. */
3578 assign_in_env (word
, flags
)
3583 char *name
, *temp
, *value
, *newname
;
3587 string
= word
->word
;
3590 offset
= assignment (string
, 0);
3591 newname
= name
= savestring (string
);
3592 value
= (char *)NULL
;
3594 if (name
[offset
] == '=')
3598 /* don't ignore the `+' when assigning temporary environment */
3599 if (name
[offset
- 1] == '+')
3601 name
[offset
- 1] = '\0';
3602 aflags
|= ASS_APPEND
;
3605 if (legal_identifier (name
) == 0)
3607 sh_invalidid (name
);
3611 var
= find_variable (name
);
3614 var
= find_variable_last_nameref (name
, 1);
3615 /* If we're assigning a value to a nameref variable in the temp
3616 environment, and the value of the nameref is valid for assignment,
3617 but the variable does not already exist, assign to the nameref
3618 target and add the target to the temporary environment. This is
3620 /* We use 2 in the call to valid_nameref_value because we don't want
3621 to allow array references here at all (newname will be used to
3622 create a variable directly below) */
3623 if (var
&& nameref_p (var
) && valid_nameref_value (nameref_cell (var
), 2))
3625 newname
= nameref_cell (var
);
3626 var
= 0; /* don't use it for append */
3630 newname
= name_cell (var
); /* no-op if not nameref */
3632 if (var
&& (readonly_p (var
) || noassign_p (var
)))
3634 if (readonly_p (var
))
3635 err_readonly (name
);
3639 temp
= name
+ offset
+ 1;
3641 value
= expand_assignment_string_to_string (temp
, 0);
3643 if (var
&& (aflags
& ASS_APPEND
))
3647 value
= (char *)xmalloc (1); /* like do_assignment_internal */
3650 temp
= make_variable_value (var
, value
, aflags
);
3656 if (temporary_env
== 0)
3657 temporary_env
= hash_create (TEMPENV_HASH_BUCKETS
);
3659 var
= hash_lookup (newname
, temporary_env
);
3661 var
= make_new_variable (newname
, temporary_env
);
3663 FREE (value_cell (var
));
3667 value
= (char *)xmalloc (1); /* see above */
3671 var_setvalue (var
, value
);
3672 var
->attributes
|= (att_exported
|att_tempvar
);
3673 var
->context
= variable_context
; /* XXX */
3675 INVALIDATE_EXPORTSTR (var
);
3676 var
->exportstr
= mk_env_string (newname
, value
, 0);
3678 array_needs_making
= 1;
3682 if (STREQ (newname
, "POSIXLY_CORRECT") || STREQ (newname
, "POSIX_PEDANDTIC"))
3683 save_posix_options (); /* XXX one level of saving right now */
3684 stupidly_hack_special_variables (newname
);
3687 if (echo_command_at_execute
|| debug_info
)
3688 /* The Korn shell prints the `+ ' in front of assignment statements,
3690 xtrace_print_assignment (name
, value
, 0, 1);
3696 /* **************************************************************** */
3698 /* Copying variables */
3700 /* **************************************************************** */
3702 #ifdef INCLUDE_UNUSED
3703 /* Copy VAR to a new data structure and return that structure. */
3708 SHELL_VAR
*copy
= (SHELL_VAR
*)NULL
;
3712 copy
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
3714 copy
->attributes
= var
->attributes
;
3715 copy
->name
= savestring (var
->name
);
3717 if (function_p (var
))
3718 var_setfunc (copy
, copy_command (function_cell (var
)));
3719 #if defined (ARRAY_VARS)
3720 else if (array_p (var
))
3721 var_setarray (copy
, array_copy (array_cell (var
)));
3722 else if (assoc_p (var
))
3723 var_setassoc (copy
, assoc_copy (assoc_cell (var
)));
3725 else if (nameref_cell (var
)) /* XXX - nameref */
3726 var_setref (copy
, savestring (nameref_cell (var
)));
3727 else if (value_cell (var
)) /* XXX - nameref */
3728 var_setvalue (copy
, savestring (value_cell (var
)));
3730 var_setvalue (copy
, (char *)NULL
);
3732 copy
->dynamic_value
= var
->dynamic_value
;
3733 copy
->assign_func
= var
->assign_func
;
3735 copy
->exportstr
= COPY_EXPORTSTR (var
);
3737 copy
->context
= var
->context
;
3743 /* **************************************************************** */
3745 /* Deleting and unsetting variables */
3747 /* **************************************************************** */
3749 /* Dispose of the information attached to VAR. */
3751 dispose_variable_value (var
)
3754 if (function_p (var
))
3755 dispose_command (function_cell (var
));
3756 #if defined (ARRAY_VARS)
3757 else if (array_p (var
))
3758 array_dispose (array_cell (var
));
3759 else if (assoc_p (var
))
3760 assoc_dispose (assoc_cell (var
));
3762 else if (nameref_p (var
))
3763 FREE (nameref_cell (var
));
3765 FREE (value_cell (var
));
3769 dispose_variable (var
)
3775 if (nofree_p (var
) == 0)
3776 dispose_variable_value (var
);
3778 FREE_EXPORTSTR (var
);
3782 if (exported_p (var
))
3783 array_needs_making
= 1;
3788 /* Unset the shell variable referenced by NAME. Unsetting a nameref variable
3789 unsets the variable it resolves to but leaves the nameref alone. */
3791 unbind_variable (name
)
3797 v
= var_lookup (name
, shell_variables
);
3798 nv
= (v
&& nameref_p (v
)) ? find_variable_nameref (v
) : (SHELL_VAR
*)NULL
;
3800 r
= nv
? makunbound (nv
->name
, shell_variables
) : makunbound (name
, shell_variables
);
3804 /* Unbind NAME, where NAME is assumed to be a nameref variable */
3806 unbind_nameref (name
)
3811 v
= var_lookup (name
, shell_variables
);
3812 if (v
&& nameref_p (v
))
3813 return makunbound (name
, shell_variables
);
3817 /* Unbind the first instance of NAME, whether it's a nameref or not */
3819 unbind_variable_noref (name
)
3824 v
= var_lookup (name
, shell_variables
);
3826 return makunbound (name
, shell_variables
);
3831 check_unbind_variable (name
)
3836 v
= find_variable (name
);
3837 if (v
&& readonly_p (v
))
3839 internal_error (_("%s: cannot unset: readonly %s"), name
, "variable");
3842 else if (v
&& non_unsettable_p (v
))
3844 internal_error (_("%s: cannot unset"), name
);
3847 return (unbind_variable (name
));
3850 /* Unset the shell function named NAME. */
3855 BUCKET_CONTENTS
*elt
;
3858 elt
= hash_remove (name
, shell_functions
, 0);
3863 #if defined (PROGRAMMABLE_COMPLETION)
3864 set_itemlist_dirty (&it_functions
);
3867 func
= (SHELL_VAR
*)elt
->data
;
3870 if (exported_p (func
))
3871 array_needs_making
++;
3872 dispose_variable (func
);
3881 #if defined (DEBUGGER)
3883 unbind_function_def (name
)
3886 BUCKET_CONTENTS
*elt
;
3887 FUNCTION_DEF
*funcdef
;
3889 elt
= hash_remove (name
, shell_function_defs
, 0);
3894 funcdef
= (FUNCTION_DEF
*)elt
->data
;
3896 dispose_function_def (funcdef
);
3903 #endif /* DEBUGGER */
3906 delete_var (name
, vc
)
3910 BUCKET_CONTENTS
*elt
;
3914 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3915 if (elt
= hash_remove (name
, v
->table
, 0))
3921 old_var
= (SHELL_VAR
*)elt
->data
;
3925 dispose_variable (old_var
);
3929 /* Make the variable associated with NAME go away. HASH_LIST is the
3930 hash table from which this variable should be deleted (either
3931 shell_variables or shell_functions).
3932 Returns non-zero if the variable couldn't be found. */
3934 makunbound (name
, vc
)
3938 BUCKET_CONTENTS
*elt
, *new_elt
;
3943 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3944 if (elt
= hash_remove (name
, v
->table
, 0))
3950 old_var
= (SHELL_VAR
*)elt
->data
;
3952 if (old_var
&& exported_p (old_var
))
3953 array_needs_making
++;
3955 /* If we're unsetting a local variable and we're still executing inside
3956 the function, just mark the variable as invisible. The function
3957 eventually called by pop_var_context() will clean it up later. This
3958 must be done so that if the variable is subsequently assigned a new
3959 value inside the function, the `local' attribute is still present.
3960 We also need to add it back into the correct hash table. */
3961 if (old_var
&& local_p (old_var
) &&
3962 (old_var
->context
== variable_context
|| (localvar_unset
&& old_var
->context
< variable_context
)))
3964 if (nofree_p (old_var
))
3965 var_setvalue (old_var
, (char *)NULL
);
3966 #if defined (ARRAY_VARS)
3967 else if (array_p (old_var
))
3968 array_dispose (array_cell (old_var
));
3969 else if (assoc_p (old_var
))
3970 assoc_dispose (assoc_cell (old_var
));
3972 else if (nameref_p (old_var
))
3973 FREE (nameref_cell (old_var
));
3975 FREE (value_cell (old_var
));
3976 /* Reset the attributes. Preserve the export attribute if the variable
3977 came from a temporary environment. Make sure it stays local, and
3978 make it invisible. */
3979 old_var
->attributes
= (exported_p (old_var
) && tempvar_p (old_var
)) ? att_exported
: 0;
3980 VSETATTR (old_var
, att_local
);
3981 VSETATTR (old_var
, att_invisible
);
3982 var_setvalue (old_var
, (char *)NULL
);
3983 INVALIDATE_EXPORTSTR (old_var
);
3985 new_elt
= hash_insert (savestring (old_var
->name
), v
->table
, 0);
3986 new_elt
->data
= (PTR_T
)old_var
;
3987 stupidly_hack_special_variables (old_var
->name
);
3994 /* Have to save a copy of name here, because it might refer to
3995 old_var->name. If so, stupidly_hack_special_variables will
3996 reference freed memory. */
3997 t
= savestring (name
);
4002 dispose_variable (old_var
);
4003 stupidly_hack_special_variables (t
);
4009 /* Get rid of all of the variables in the current context. */
4011 kill_all_local_variables ()
4015 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
4016 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
4021 if (vc
->table
&& vc_haslocals (vc
))
4023 delete_all_variables (vc
->table
);
4024 hash_dispose (vc
->table
);
4026 vc
->table
= (HASH_TABLE
*)NULL
;
4030 free_variable_hash_data (data
)
4035 var
= (SHELL_VAR
*)data
;
4036 dispose_variable (var
);
4039 /* Delete the entire contents of the hash table. */
4041 delete_all_variables (hashed_vars
)
4042 HASH_TABLE
*hashed_vars
;
4044 hash_flush (hashed_vars
, free_variable_hash_data
);
4047 /* **************************************************************** */
4049 /* Setting variable attributes */
4051 /* **************************************************************** */
4053 #define FIND_OR_MAKE_VARIABLE(name, entry) \
4056 entry = find_variable (name); \
4059 entry = bind_variable (name, "", 0); \
4060 if (entry) entry->attributes |= att_invisible; \
4065 /* Make the variable associated with NAME be readonly.
4066 If NAME does not exist yet, create it. */
4068 set_var_read_only (name
)
4073 FIND_OR_MAKE_VARIABLE (name
, entry
);
4074 VSETATTR (entry
, att_readonly
);
4077 #ifdef INCLUDE_UNUSED
4078 /* Make the function associated with NAME be readonly.
4079 If NAME does not exist, we just punt, like auto_export code below. */
4081 set_func_read_only (name
)
4086 entry
= find_function (name
);
4088 VSETATTR (entry
, att_readonly
);
4091 /* Make the variable associated with NAME be auto-exported.
4092 If NAME does not exist yet, create it. */
4094 set_var_auto_export (name
)
4099 FIND_OR_MAKE_VARIABLE (name
, entry
);
4100 set_auto_export (entry
);
4103 /* Make the function associated with NAME be auto-exported. */
4105 set_func_auto_export (name
)
4110 entry
= find_function (name
);
4112 set_auto_export (entry
);
4116 /* **************************************************************** */
4118 /* Creating lists of variables */
4120 /* **************************************************************** */
4123 vlist_alloc (nentries
)
4128 vlist
= (VARLIST
*)xmalloc (sizeof (VARLIST
));
4129 vlist
->list
= (SHELL_VAR
**)xmalloc ((nentries
+ 1) * sizeof (SHELL_VAR
*));
4130 vlist
->list_size
= nentries
;
4131 vlist
->list_len
= 0;
4132 vlist
->list
[0] = (SHELL_VAR
*)NULL
;
4138 vlist_realloc (vlist
, n
)
4143 return (vlist
= vlist_alloc (n
));
4144 if (n
> vlist
->list_size
)
4146 vlist
->list_size
= n
;
4147 vlist
->list
= (SHELL_VAR
**)xrealloc (vlist
->list
, (vlist
->list_size
+ 1) * sizeof (SHELL_VAR
*));
4153 vlist_add (vlist
, var
, flags
)
4160 for (i
= 0; i
< vlist
->list_len
; i
++)
4161 if (STREQ (var
->name
, vlist
->list
[i
]->name
))
4163 if (i
< vlist
->list_len
)
4166 if (i
>= vlist
->list_size
)
4167 vlist
= vlist_realloc (vlist
, vlist
->list_size
+ 16);
4169 vlist
->list
[vlist
->list_len
++] = var
;
4170 vlist
->list
[vlist
->list_len
] = (SHELL_VAR
*)NULL
;
4173 /* Map FUNCTION over the variables in VAR_HASH_TABLE. Return an array of the
4174 variables for which FUNCTION returns a non-zero value. A NULL value
4175 for FUNCTION means to use all variables. */
4177 map_over (function
, vc
)
4178 sh_var_map_func_t
*function
;
4186 for (nentries
= 0, v
= vc
; v
; v
= v
->down
)
4187 nentries
+= HASH_ENTRIES (v
->table
);
4190 return (SHELL_VAR
**)NULL
;
4192 vlist
= vlist_alloc (nentries
);
4194 for (v
= vc
; v
; v
= v
->down
)
4195 flatten (v
->table
, function
, vlist
, 0);
4203 map_over_funcs (function
)
4204 sh_var_map_func_t
*function
;
4209 if (shell_functions
== 0 || HASH_ENTRIES (shell_functions
) == 0)
4210 return ((SHELL_VAR
**)NULL
);
4212 vlist
= vlist_alloc (HASH_ENTRIES (shell_functions
));
4214 flatten (shell_functions
, function
, vlist
, 0);
4221 /* Flatten VAR_HASH_TABLE, applying FUNC to each member and adding those
4222 elements for which FUNC succeeds to VLIST->list. FLAGS is reserved
4223 for future use. Only unique names are added to VLIST. If FUNC is
4224 NULL, each variable in VAR_HASH_TABLE is added to VLIST. If VLIST is
4225 NULL, FUNC is applied to each SHELL_VAR in VAR_HASH_TABLE. If VLIST
4226 and FUNC are both NULL, nothing happens. */
4228 flatten (var_hash_table
, func
, vlist
, flags
)
4229 HASH_TABLE
*var_hash_table
;
4230 sh_var_map_func_t
*func
;
4235 register BUCKET_CONTENTS
*tlist
;
4239 if (var_hash_table
== 0 || (HASH_ENTRIES (var_hash_table
) == 0) || (vlist
== 0 && func
== 0))
4242 for (i
= 0; i
< var_hash_table
->nbuckets
; i
++)
4244 for (tlist
= hash_items (i
, var_hash_table
); tlist
; tlist
= tlist
->next
)
4246 var
= (SHELL_VAR
*)tlist
->data
;
4248 r
= func
? (*func
) (var
) : 1;
4250 vlist_add (vlist
, var
, flags
);
4256 sort_variables (array
)
4259 qsort (array
, strvec_len ((char **)array
), sizeof (SHELL_VAR
*), (QSFUNC
*)qsort_var_comp
);
4263 qsort_var_comp (var1
, var2
)
4264 SHELL_VAR
**var1
, **var2
;
4268 if ((result
= (*var1
)->name
[0] - (*var2
)->name
[0]) == 0)
4269 result
= strcmp ((*var1
)->name
, (*var2
)->name
);
4274 /* Apply FUNC to each variable in SHELL_VARIABLES, adding each one for
4275 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
4278 sh_var_map_func_t
*func
;
4282 list
= map_over (func
, shell_variables
);
4283 if (list
/* && posixly_correct */)
4284 sort_variables (list
);
4288 /* Apply FUNC to each variable in SHELL_FUNCTIONS, adding each one for
4289 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
4292 sh_var_map_func_t
*func
;
4296 list
= map_over_funcs (func
);
4297 if (list
/* && posixly_correct */)
4298 sort_variables (list
);
4302 /* Create a NULL terminated array of all the shell variables. */
4304 all_shell_variables ()
4306 return (vapply ((sh_var_map_func_t
*)NULL
));
4309 /* Create a NULL terminated array of all the shell functions. */
4311 all_shell_functions ()
4313 return (fapply ((sh_var_map_func_t
*)NULL
));
4320 return (invisible_p (var
) == 0);
4324 all_visible_functions ()
4326 return (fapply (visible_var
));
4330 all_visible_variables ()
4332 return (vapply (visible_var
));
4335 /* Return non-zero if the variable VAR is visible and exported. Array
4336 variables cannot be exported. */
4338 visible_and_exported (var
)
4341 return (invisible_p (var
) == 0 && exported_p (var
));
4344 /* Candidate variables for the export environment are either valid variables
4345 with the export attribute or invalid variables inherited from the initial
4346 environment and simply passed through. */
4348 export_environment_candidate (var
)
4351 return (exported_p (var
) && (invisible_p (var
) == 0 || imported_p (var
)));
4354 /* Return non-zero if VAR is a local variable in the current context and
4357 local_and_exported (var
)
4360 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
&& exported_p (var
));
4364 all_exported_variables ()
4366 return (vapply (visible_and_exported
));
4370 local_exported_variables ()
4372 return (vapply (local_and_exported
));
4376 variable_in_context (var
)
4379 return (local_p (var
) && var
->context
== variable_context
);
4383 visible_variable_in_context (var
)
4386 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
);
4390 all_local_variables (visible_only
)
4397 vc
= shell_variables
;
4398 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
4399 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
4404 internal_error (_("all_local_variables: no function context at current scope"));
4405 return (SHELL_VAR
**)NULL
;
4407 if (vc
->table
== 0 || HASH_ENTRIES (vc
->table
) == 0 || vc_haslocals (vc
) == 0)
4408 return (SHELL_VAR
**)NULL
;
4410 vlist
= vlist_alloc (HASH_ENTRIES (vc
->table
));
4413 flatten (vc
->table
, visible_variable_in_context
, vlist
, 0);
4415 flatten (vc
->table
, variable_in_context
, vlist
, 0);
4420 sort_variables (ret
);
4424 #if defined (ARRAY_VARS)
4425 /* Return non-zero if the variable VAR is visible and an array. */
4427 visible_array_vars (var
)
4430 return (invisible_p (var
) == 0 && (array_p (var
) || assoc_p (var
)));
4434 all_array_variables ()
4436 return (vapply (visible_array_vars
));
4438 #endif /* ARRAY_VARS */
4441 all_variables_matching_prefix (prefix
)
4444 SHELL_VAR
**varlist
;
4446 int vind
, rind
, plen
;
4448 plen
= STRLEN (prefix
);
4449 varlist
= all_visible_variables ();
4450 for (vind
= 0; varlist
&& varlist
[vind
]; vind
++)
4452 if (varlist
== 0 || vind
== 0)
4453 return ((char **)NULL
);
4454 rlist
= strvec_create (vind
+ 1);
4455 for (vind
= rind
= 0; varlist
[vind
]; vind
++)
4457 if (plen
== 0 || STREQN (prefix
, varlist
[vind
]->name
, plen
))
4458 rlist
[rind
++] = savestring (varlist
[vind
]->name
);
4460 rlist
[rind
] = (char *)0;
4466 /* **************************************************************** */
4468 /* Managing temporary variable scopes */
4470 /* **************************************************************** */
4472 /* Make variable NAME have VALUE in the temporary environment. */
4474 bind_tempenv_variable (name
, value
)
4480 var
= temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
;
4484 FREE (value_cell (var
));
4485 var_setvalue (var
, savestring (value
));
4486 INVALIDATE_EXPORTSTR (var
);
4492 /* Find a variable in the temporary environment that is named NAME.
4493 Return the SHELL_VAR *, or NULL if not found. */
4495 find_tempenv_variable (name
)
4498 return (temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
);
4501 char **tempvar_list
;
4504 /* Take a variable from an assignment statement preceding a posix special
4505 builtin (including `return') and create a global variable from it. This
4506 is called from merge_temporary_env, which is only called when in posix
4509 push_posix_temp_var (data
)
4513 HASH_TABLE
*binding_table
;
4515 var
= (SHELL_VAR
*)data
;
4517 /* Just like do_assignment_internal(). This makes assignments preceding
4518 special builtins act like standalone assignment statements when in
4519 posix mode, satisfying the posix requirement that this affect the
4520 "current execution environment." */
4521 v
= bind_variable (var
->name
, value_cell (var
), ASS_FORCE
|ASS_NOLONGJMP
);
4523 /* XXX - do we need to worry about array variables here? */
4525 /* If this modifies an existing local variable, v->context will be non-zero.
4526 If it comes back with v->context == 0, we bound at the global context.
4527 Set binding_table appropriately. It doesn't matter whether it's correct
4528 if the variable is local, only that it's not global_variables->table */
4529 binding_table
= v
->context
? shell_variables
->table
: global_variables
->table
;
4531 /* global variables are no longer temporary and don't need propagating. */
4532 if (v
->context
== 0)
4533 var
->attributes
&= ~(att_tempvar
|att_propagate
);
4537 v
->attributes
|= var
->attributes
; /* preserve tempvar attribute if appropriate */
4538 /* If we don't bind a local variable, propagate the value. If we bind a
4539 local variable (the "current execution environment"), keep it as local
4540 and don't propagate it to the calling environment. */
4541 if (v
->context
> 0 && local_p (v
) == 0)
4542 v
->attributes
|= att_propagate
;
4544 v
->attributes
&= ~att_propagate
;
4547 if (find_special_var (var
->name
) >= 0)
4548 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
4550 dispose_variable (var
);
4553 /* Push the variable described by (SHELL_VAR *)DATA down to the next
4554 variable context from the temporary environment. This can be called
4556 1. propagate_temp_var: which is called to propagate variables in
4557 assignments like `var=value declare -x var' to the surrounding
4560 In this case, the variable should have the att_propagate flag set and
4561 we can create variables in the current scope.
4564 push_temp_var (data
)
4568 HASH_TABLE
*binding_table
;
4570 var
= (SHELL_VAR
*)data
;
4572 binding_table
= shell_variables
->table
;
4573 if (binding_table
== 0)
4575 if (shell_variables
== global_variables
)
4576 /* shouldn't happen */
4577 binding_table
= shell_variables
->table
= global_variables
->table
= hash_create (VARIABLES_HASH_BUCKETS
);
4579 binding_table
= shell_variables
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
4582 v
= bind_variable_internal (var
->name
, value_cell (var
), binding_table
, 0, ASS_FORCE
|ASS_NOLONGJMP
);
4584 /* XXX - should we set the context here? It shouldn't matter because of how
4585 assign_in_env works, but we do it anyway. */
4587 v
->context
= shell_variables
->scope
;
4589 if (binding_table
== global_variables
->table
) /* XXX */
4590 var
->attributes
&= ~(att_tempvar
|att_propagate
);
4593 var
->attributes
|= att_propagate
; /* XXX - propagate more than once? */
4594 if (binding_table
== shell_variables
->table
)
4595 shell_variables
->flags
|= VC_HASTMPVAR
;
4598 v
->attributes
|= var
->attributes
;
4600 if (find_special_var (var
->name
) >= 0)
4601 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
4603 dispose_variable (var
);
4606 /* Take a variable described by DATA and push it to the surrounding scope if
4607 the PROPAGATE attribute is set. That gets set by push_temp_var if we are
4608 taking a variable like `var=value declare -x var' and propagating it to
4609 the enclosing scope. */
4611 propagate_temp_var (data
)
4616 var
= (SHELL_VAR
*)data
;
4617 if (tempvar_p (var
) && (var
->attributes
& att_propagate
))
4618 push_temp_var (data
);
4621 if (find_special_var (var
->name
) >= 0)
4622 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
4623 dispose_variable (var
);
4627 /* Free the storage used in the hash table for temporary
4628 environment variables. PUSHF is a function to be called
4629 to free each hash table entry. It takes care of pushing variables
4630 to previous scopes if appropriate. PUSHF stores names of variables
4631 that require special handling (e.g., IFS) on tempvar_list, so this
4632 function can call stupidly_hack_special_variables on all the
4633 variables in the list when the temporary hash table is destroyed. */
4635 dispose_temporary_env (pushf
)
4636 sh_free_func_t
*pushf
;
4639 HASH_TABLE
*disposer
;
4641 tempvar_list
= strvec_create (HASH_ENTRIES (temporary_env
) + 1);
4642 tempvar_list
[tvlist_ind
= 0] = 0;
4644 disposer
= temporary_env
;
4645 temporary_env
= (HASH_TABLE
*)NULL
;
4647 hash_flush (disposer
, pushf
);
4648 hash_dispose (disposer
);
4650 tempvar_list
[tvlist_ind
] = 0;
4652 array_needs_making
= 1;
4654 for (i
= 0; i
< tvlist_ind
; i
++)
4655 stupidly_hack_special_variables (tempvar_list
[i
]);
4657 strvec_dispose (tempvar_list
);
4663 dispose_used_env_vars ()
4667 dispose_temporary_env (propagate_temp_var
);
4668 maybe_make_export_env ();
4672 /* Take all of the shell variables in the temporary environment HASH_TABLE
4673 and make shell variables from them at the current variable context.
4674 Right now, this is only called in Posix mode to implement the historical
4675 accident of creating global variables from assignment statements preceding
4676 special builtins, but we check in case this acquires another caller later. */
4678 merge_temporary_env ()
4681 dispose_temporary_env (posixly_correct
? push_posix_temp_var
: push_temp_var
);
4684 /* Temporary function to use if we want to separate function and special
4685 builtin behavior. */
4687 merge_function_temporary_env ()
4690 dispose_temporary_env (push_temp_var
);
4694 flush_temporary_env ()
4698 hash_flush (temporary_env
, free_variable_hash_data
);
4699 hash_dispose (temporary_env
);
4700 temporary_env
= (HASH_TABLE
*)NULL
;
4704 /* **************************************************************** */
4706 /* Creating and manipulating the environment */
4708 /* **************************************************************** */
4710 static inline char *
4711 mk_env_string (name
, value
, isfunc
)
4712 const char *name
, *value
;
4715 size_t name_len
, value_len
;
4718 name_len
= strlen (name
);
4719 value_len
= STRLEN (value
);
4721 /* If we are exporting a shell function, construct the encoded function
4723 if (isfunc
&& value
)
4725 p
= (char *)xmalloc (BUSHFUNC_PREFLEN
+ name_len
+ BUSHFUNC_SUFFLEN
+ value_len
+ 2);
4727 memcpy (q
, BUSHFUNC_PREFIX
, BUSHFUNC_PREFLEN
);
4728 q
+= BUSHFUNC_PREFLEN
;
4729 memcpy (q
, name
, name_len
);
4731 memcpy (q
, BUSHFUNC_SUFFIX
, BUSHFUNC_SUFFLEN
);
4732 q
+= BUSHFUNC_SUFFLEN
;
4736 p
= (char *)xmalloc (2 + name_len
+ value_len
);
4737 memcpy (p
, name
, name_len
);
4742 if (value
&& *value
)
4746 t
= dequote_escapes (value
);
4747 value_len
= STRLEN (t
);
4748 memcpy (q
+ 1, t
, value_len
+ 1);
4752 memcpy (q
+ 1, value
, value_len
+ 1);
4772 internal_error (_("%s has null exportstr"), v
->name
);
4775 if (legal_variable_starter ((unsigned char)*s
) == 0)
4777 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4780 for (s
= v
->exportstr
+ 1; s
&& *s
; s
++)
4785 if (legal_variable_char (c
) == 0)
4787 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4796 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4803 internal_error (_("no `=' in exportstr for %s"), v
->name
);
4806 printf("string = %s\n", string
);
4812 make_env_array_from_var_list (vars
)
4815 register int i
, list_index
;
4816 register SHELL_VAR
*var
;
4817 char **list
, *value
;
4819 list
= strvec_create ((1 + strvec_len ((char **)vars
)));
4821 #define USE_EXPORTSTR (value == var->exportstr)
4823 for (i
= 0, list_index
= 0; var
= vars
[i
]; i
++)
4825 #if defined (__CYGWIN__)
4826 /* We don't use the exportstr stuff on Cygwin at all. */
4827 INVALIDATE_EXPORTSTR (var
);
4830 /* If the value is generated dynamically, generate it here. */
4831 if (regen_p (var
) && var
->dynamic_value
)
4833 var
= (*(var
->dynamic_value
)) (var
);
4834 INVALIDATE_EXPORTSTR (var
);
4838 value
= var
->exportstr
;
4839 else if (function_p (var
))
4840 value
= named_function_string ((char *)NULL
, function_cell (var
), 0);
4841 #if defined (ARRAY_VARS)
4842 else if (array_p (var
))
4844 value
= array_to_assign (array_cell (var
), 0);
4846 continue; /* XXX array vars cannot yet be exported */
4847 # endif /* ARRAY_EXPORT */
4848 else if (assoc_p (var
))
4850 value
= assoc_to_assign (assoc_cell (var
), 0);
4852 continue; /* XXX associative array vars cannot yet be exported */
4856 value
= value_cell (var
);
4860 /* Gee, I'd like to get away with not using savestring() if we're
4861 using the cached exportstr... */
4862 list
[list_index
] = USE_EXPORTSTR
? savestring (value
)
4863 : mk_env_string (var
->name
, value
, function_p (var
));
4864 if (USE_EXPORTSTR
== 0)
4865 SAVE_EXPORTSTR (var
, list
[list_index
]);
4868 #undef USE_EXPORTSTR
4871 #if defined (ARRAY_VARS)
4872 if (array_p (var
) || assoc_p (var
))
4879 list
[list_index
] = (char *)NULL
;
4883 /* Make an array of assignment statements from the hash table
4884 HASHED_VARS which contains SHELL_VARs. Only visible, exported
4885 variables are eligible. */
4887 make_var_export_array (vcxt
)
4894 vars
= map_over (visible_and_exported
, vcxt
);
4896 vars
= map_over (export_environment_candidate
, vcxt
);
4900 return (char **)NULL
;
4902 list
= make_env_array_from_var_list (vars
);
4909 make_func_export_array ()
4914 vars
= map_over_funcs (visible_and_exported
);
4916 return (char **)NULL
;
4918 list
= make_env_array_from_var_list (vars
);
4924 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
4925 #define add_to_export_env(envstr,do_alloc) \
4928 if (export_env_index >= (export_env_size - 1)) \
4930 export_env_size += 16; \
4931 export_env = strvec_resize (export_env, export_env_size); \
4932 environ = export_env; \
4934 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
4935 export_env[export_env_index] = (char *)NULL; \
4938 /* Add ASSIGN to EXPORT_ENV, or supersede a previous assignment in the
4939 array with the same left-hand side. Return the new EXPORT_ENV. */
4941 add_or_supercede_exported_var (assign
, do_alloc
)
4948 equal_offset
= assignment (assign
, 0);
4949 if (equal_offset
== 0)
4950 return (export_env
);
4952 /* If this is a function, then only supersede the function definition.
4953 We do this by including the `=() {' in the comparison, like
4954 initialize_shell_variables does. */
4955 if (assign
[equal_offset
+ 1] == '(' &&
4956 strncmp (assign
+ equal_offset
+ 2, ") {", 3) == 0) /* } */
4959 for (i
= 0; i
< export_env_index
; i
++)
4961 if (STREQN (assign
, export_env
[i
], equal_offset
+ 1))
4963 free (export_env
[i
]);
4964 export_env
[i
] = do_alloc
? savestring (assign
) : assign
;
4965 return (export_env
);
4968 add_to_export_env (assign
, do_alloc
);
4969 return (export_env
);
4973 add_temp_array_to_env (temp_array
, do_alloc
, do_supercede
)
4975 int do_alloc
, do_supercede
;
4979 if (temp_array
== 0)
4982 for (i
= 0; temp_array
[i
]; i
++)
4985 export_env
= add_or_supercede_exported_var (temp_array
[i
], do_alloc
);
4987 add_to_export_env (temp_array
[i
], do_alloc
);
4993 /* Make the environment array for the command about to be executed, if the
4994 array needs making. Otherwise, do nothing. If a shell action could
4995 change the array that commands receive for their environment, then the
4996 code should `array_needs_making++'.
4998 The order to add to the array is:
5000 list of var contexts whose head is shell_variables
5003 This is the shell variable lookup order. We add only new variable
5004 names at each step, which allows local variables and variables in
5005 the temporary environments to shadow variables in the global (or
5006 any previous) scope.
5010 n_shell_variables ()
5015 for (n
= 0, vc
= shell_variables
; vc
; vc
= vc
->down
)
5016 n
+= HASH_ENTRIES (vc
->table
);
5026 v
= find_variable (name
);
5027 if (v
&& exported_p (v
))
5029 array_needs_making
= 1;
5030 maybe_make_export_env ();
5037 maybe_make_export_env ()
5039 register char **temp_array
;
5041 VAR_CONTEXT
*tcxt
, *icxt
;
5043 if (array_needs_making
)
5046 strvec_flush (export_env
);
5048 /* Make a guess based on how many shell variables and functions we
5049 have. Since there will always be array variables, and array
5050 variables are not (yet) exported, this will always be big enough
5051 for the exported variables and functions. */
5052 new_size
= n_shell_variables () + HASH_ENTRIES (shell_functions
) + 1 +
5053 HASH_ENTRIES (temporary_env
) + HASH_ENTRIES (invalid_env
);
5054 if (new_size
> export_env_size
)
5056 export_env_size
= new_size
;
5057 export_env
= strvec_resize (export_env
, export_env_size
);
5058 environ
= export_env
;
5060 export_env
[export_env_index
= 0] = (char *)NULL
;
5062 /* Make a dummy variable context from the temporary_env, stick it on
5063 the front of shell_variables, call make_var_export_array on the
5064 whole thing to flatten it, and convert the list of SHELL_VAR *s
5065 to the form needed by the environment. */
5068 tcxt
= new_var_context ((char *)NULL
, 0);
5069 tcxt
->table
= temporary_env
;
5070 tcxt
->down
= shell_variables
;
5073 tcxt
= shell_variables
;
5077 icxt
= new_var_context ((char *)NULL
, 0);
5078 icxt
->table
= invalid_env
;
5084 temp_array
= make_var_export_array (icxt
);
5086 add_temp_array_to_env (temp_array
, 0, 0);
5091 if (tcxt
!= shell_variables
)
5094 #if defined (RESTRICTED_SHELL)
5095 /* Restricted shells may not export shell functions. */
5096 temp_array
= restricted
? (char **)0 : make_func_export_array ();
5098 temp_array
= make_func_export_array ();
5101 add_temp_array_to_env (temp_array
, 0, 0);
5103 array_needs_making
= 0;
5107 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
5108 we will need to remake the exported environment every time we
5109 change directories. `_' is always put into the environment for
5110 every external command, so without special treatment it will always
5111 cause the environment to be remade.
5113 If there is no other reason to make the exported environment, we can
5114 just update the variables in place and mark the exported environment
5115 as no longer needing a remake. */
5117 update_export_env_inplace (env_prefix
, preflen
, value
)
5124 evar
= (char *)xmalloc (STRLEN (value
) + preflen
+ 1);
5125 strcpy (evar
, env_prefix
);
5127 strcpy (evar
+ preflen
, value
);
5128 export_env
= add_or_supercede_exported_var (evar
, 0);
5131 /* We always put _ in the environment as the name of this command. */
5133 put_command_name_into_env (command_name
)
5136 update_export_env_inplace ("_=", 2, command_name
);
5139 /* **************************************************************** */
5141 /* Managing variable contexts */
5143 /* **************************************************************** */
5145 /* Allocate and return a new variable context with NAME and FLAGS.
5146 NAME can be NULL. */
5149 new_var_context (name
, flags
)
5155 vc
= (VAR_CONTEXT
*)xmalloc (sizeof (VAR_CONTEXT
));
5156 vc
->name
= name
? savestring (name
) : (char *)NULL
;
5157 vc
->scope
= variable_context
;
5160 vc
->up
= vc
->down
= (VAR_CONTEXT
*)NULL
;
5161 vc
->table
= (HASH_TABLE
*)NULL
;
5166 /* Free a variable context and its data, including the hash table. Dispose
5167 all of the variables. */
5169 dispose_var_context (vc
)
5176 delete_all_variables (vc
->table
);
5177 hash_dispose (vc
->table
);
5183 /* Set VAR's scope level to the current variable context. */
5188 return (var
->context
= variable_context
);
5191 /* Make a new variable context with NAME and FLAGS and a HASH_TABLE of
5192 temporary variables, and push it onto shell_variables. This is
5193 for shell functions. */
5195 push_var_context (name
, flags
, tempvars
)
5198 HASH_TABLE
*tempvars
;
5201 int posix_func_behavior
;
5203 /* As of IEEE Std 1003.1-2017, assignment statements preceding shell
5204 functions no longer behave like assignment statements preceding
5205 special builtins, and do not persist in the current shell environment.
5206 This is austin group interp #654, though nobody implements it yet. */
5207 posix_func_behavior
= 0;
5209 vc
= new_var_context (name
, flags
);
5210 /* Posix interp 1009, temporary assignments preceding function calls modify
5211 the current environment *before* the command is executed. */
5212 if (posix_func_behavior
&& (flags
& VC_FUNCENV
) && tempvars
== temporary_env
)
5213 merge_temporary_env ();
5216 vc
->table
= tempvars
;
5217 /* Have to do this because the temp environment was created before
5218 variable_context was incremented. */
5219 /* XXX - only need to do it if flags&VC_FUNCENV */
5220 flatten (tempvars
, set_context
, (VARLIST
*)NULL
, 0);
5221 vc
->flags
|= VC_HASTMPVAR
;
5223 vc
->down
= shell_variables
;
5224 shell_variables
->up
= vc
;
5226 return (shell_variables
= vc
);
5229 /* This can be called from one of two code paths:
5230 1. pop_scope, which implements the posix rules for propagating variable
5231 assignments preceding special builtins to the surrounding scope
5232 (push_builtin_var -- isbltin == 1);
5233 2. pop_var_context, which is called from pop_context and implements the
5234 posix rules for propagating variable assignments preceding function
5235 calls to the surrounding scope (push_func_var -- isbltin == 0)
5237 It takes variables out of a temporary environment hash table. We take the
5242 push_posix_tempvar_internal (var
, isbltin
)
5247 int posix_var_behavior
;
5249 /* As of IEEE Std 1003.1-2017, assignment statements preceding shell
5250 functions no longer behave like assignment statements preceding
5251 special builtins, and do not persist in the current shell environment.
5252 This is austin group interp #654, though nobody implements it yet. */
5253 posix_var_behavior
= posixly_correct
&& isbltin
;
5256 if (local_p (var
) && STREQ (var
->name
, "-"))
5258 set_current_options (value_cell (var
));
5261 /* This takes variable assignments preceding special builtins that can execute
5262 multiple commands (source, eval, etc.) and performs the equivalent of
5263 an assignment statement to modify the closest enclosing variable (the
5264 posix "current execution environment"). This makes the behavior the same
5265 as push_posix_temp_var; but the circumstances of calling are slightly
5267 else if (tempvar_p (var
) && posix_var_behavior
)
5269 /* similar to push_posix_temp_var */
5270 v
= bind_variable (var
->name
, value_cell (var
), ASS_FORCE
|ASS_NOLONGJMP
);
5273 v
->attributes
|= var
->attributes
;
5274 if (v
->context
== 0)
5275 v
->attributes
&= ~(att_tempvar
|att_propagate
);
5276 /* XXX - set att_propagate here if v->context > 0? */
5279 else if (tempvar_p (var
) && propagate_p (var
))
5281 /* Make sure we have a hash table to store the variable in while it is
5282 being propagated down to the global variables table. Create one if
5284 if ((vc_isfuncenv (shell_variables
) || vc_istempenv (shell_variables
)) && shell_variables
->table
== 0)
5285 shell_variables
->table
= hash_create (VARIABLES_HASH_BUCKETS
);
5286 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
5287 /* XXX - should we set v->context here? */
5289 v
->context
= shell_variables
->scope
;
5290 if (shell_variables
== global_variables
)
5291 var
->attributes
&= ~(att_tempvar
|att_propagate
);
5293 shell_variables
->flags
|= VC_HASTMPVAR
;
5295 v
->attributes
|= var
->attributes
;
5298 stupidly_hack_special_variables (var
->name
); /* XXX */
5300 #if defined (ARRAY_VARS)
5301 if (v
&& (array_p (var
) || assoc_p (var
)))
5303 FREE (value_cell (v
));
5305 var_setarray (v
, array_copy (array_cell (var
)));
5307 var_setassoc (v
, assoc_copy (assoc_cell (var
)));
5311 dispose_variable (var
);
5315 push_func_var (data
)
5320 var
= (SHELL_VAR
*)data
;
5321 push_posix_tempvar_internal (var
, 0);
5325 push_builtin_var (data
)
5330 var
= (SHELL_VAR
*)data
;
5331 push_posix_tempvar_internal (var
, 1);
5334 /* Pop the top context off of VCXT and dispose of it, returning the rest of
5339 VAR_CONTEXT
*ret
, *vcxt
;
5341 vcxt
= shell_variables
;
5342 if (vc_isfuncenv (vcxt
) == 0)
5344 internal_error (_("pop_var_context: head of shell_variables not a function context"));
5348 if (ret
= vcxt
->down
)
5350 ret
->up
= (VAR_CONTEXT
*)NULL
;
5351 shell_variables
= ret
;
5353 hash_flush (vcxt
->table
, push_func_var
);
5354 dispose_var_context (vcxt
);
5357 internal_error (_("pop_var_context: no global_variables context"));
5360 /* Delete the HASH_TABLEs for all variable contexts beginning at VCXT, and
5361 all of the VAR_CONTEXTs except GLOBAL_VARIABLES. */
5363 delete_all_contexts (vcxt
)
5368 for (v
= vcxt
; v
!= global_variables
; v
= t
)
5371 dispose_var_context (v
);
5374 delete_all_variables (global_variables
->table
);
5375 shell_variables
= global_variables
;
5378 /* **************************************************************** */
5380 /* Pushing and Popping temporary variable scopes */
5382 /* **************************************************************** */
5385 push_scope (flags
, tmpvars
)
5387 HASH_TABLE
*tmpvars
;
5389 return (push_var_context ((char *)NULL
, flags
, tmpvars
));
5393 push_exported_var (data
)
5398 var
= (SHELL_VAR
*)data
;
5400 /* If a temp var had its export attribute set, or it's marked to be
5401 propagated, bind it in the previous scope before disposing it. */
5402 /* XXX - This isn't exactly right, because all tempenv variables have the
5403 export attribute set. */
5404 if (tempvar_p (var
) && exported_p (var
) && (var
->attributes
& att_propagate
))
5406 var
->attributes
&= ~att_tempvar
; /* XXX */
5407 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
5408 if (shell_variables
== global_variables
)
5409 var
->attributes
&= ~att_propagate
;
5412 v
->attributes
|= var
->attributes
;
5413 v
->context
= shell_variables
->scope
;
5417 stupidly_hack_special_variables (var
->name
); /* XXX */
5419 dispose_variable (var
);
5422 /* This is called to propagate variables in the temporary environment of a
5423 special builtin (if IS_SPECIAL != 0) or exported variables that are the
5424 result of a builtin like `source' or `command' that can operate on the
5425 variables in its temporary environment. In the first case, we call
5426 push_builtin_var, which does the right thing. */
5428 pop_scope (is_special
)
5431 VAR_CONTEXT
*vcxt
, *ret
;
5434 vcxt
= shell_variables
;
5435 if (vc_istempscope (vcxt
) == 0)
5437 internal_error (_("pop_scope: head of shell_variables not a temporary environment scope"));
5440 is_bltinenv
= vc_isbltnenv (vcxt
); /* XXX - for later */
5444 ret
->up
= (VAR_CONTEXT
*)NULL
;
5446 shell_variables
= ret
;
5448 /* Now we can take care of merging variables in VCXT into set of scopes
5449 whose head is RET (shell_variables). */
5454 hash_flush (vcxt
->table
, push_builtin_var
);
5456 hash_flush (vcxt
->table
, push_exported_var
);
5457 hash_dispose (vcxt
->table
);
5461 sv_ifs ("IFS"); /* XXX here for now */
5464 /* **************************************************************** */
5466 /* Pushing and Popping function contexts */
5468 /* **************************************************************** */
5470 struct saved_dollar_vars
{
5476 static struct saved_dollar_vars
*dollar_arg_stack
= (struct saved_dollar_vars
*)NULL
;
5477 static int dollar_arg_stack_slots
;
5478 static int dollar_arg_stack_index
;
5480 /* Functions to manipulate dollar_vars array. Need to keep these in sync with
5481 whatever remember_args() does. */
5488 ret
= strvec_create (10);
5489 for (i
= 1; i
< 10; i
++)
5491 ret
[i
] = dollar_vars
[i
];
5492 dollar_vars
[i
] = (char *)NULL
;
5498 restore_dollar_vars (args
)
5503 for (i
= 1; i
< 10; i
++)
5504 dollar_vars
[i
] = args
[i
];
5512 for (i
= 1; i
< 10; i
++)
5514 FREE (dollar_vars
[i
]);
5515 dollar_vars
[i
] = (char *)NULL
;
5520 free_saved_dollar_vars (args
)
5525 for (i
= 1; i
< 10; i
++)
5529 /* Do what remember_args (xxx, 1) would have done. */
5531 clear_dollar_vars ()
5533 free_dollar_vars ();
5534 dispose_words (rest_of_args
);
5536 rest_of_args
= (WORD_LIST
*)NULL
;
5540 /* XXX - should always be followed by remember_args () */
5542 push_context (name
, is_subshell
, tempvars
)
5543 char *name
; /* function name */
5545 HASH_TABLE
*tempvars
;
5547 if (is_subshell
== 0)
5548 push_dollar_vars ();
5550 push_var_context (name
, VC_FUNCENV
, tempvars
);
5553 /* Only called when subshell == 0, so we don't need to check, and can
5554 unconditionally pop the dollar vars off the stack. */
5562 sv_ifs ("IFS"); /* XXX here for now */
5565 /* Save the existing positional parameters on a stack. */
5569 if (dollar_arg_stack_index
+ 2 > dollar_arg_stack_slots
)
5571 dollar_arg_stack
= (struct saved_dollar_vars
*)
5572 xrealloc (dollar_arg_stack
, (dollar_arg_stack_slots
+= 10)
5573 * sizeof (struct saved_dollar_vars
));
5576 dollar_arg_stack
[dollar_arg_stack_index
].count
= posparam_count
;
5577 dollar_arg_stack
[dollar_arg_stack_index
].first_ten
= save_dollar_vars ();
5578 dollar_arg_stack
[dollar_arg_stack_index
++].rest
= rest_of_args
;
5579 rest_of_args
= (WORD_LIST
*)NULL
;
5582 dollar_arg_stack
[dollar_arg_stack_index
].first_ten
= (char **)NULL
;
5583 dollar_arg_stack
[dollar_arg_stack_index
].rest
= (WORD_LIST
*)NULL
;
5586 /* Restore the positional parameters from our stack. */
5590 if (dollar_arg_stack
== 0 || dollar_arg_stack_index
== 0)
5593 /* Wipe out current values */
5594 clear_dollar_vars ();
5596 rest_of_args
= dollar_arg_stack
[--dollar_arg_stack_index
].rest
;
5597 restore_dollar_vars (dollar_arg_stack
[dollar_arg_stack_index
].first_ten
);
5598 free (dollar_arg_stack
[dollar_arg_stack_index
].first_ten
);
5599 posparam_count
= dollar_arg_stack
[dollar_arg_stack_index
].count
;
5601 dollar_arg_stack
[dollar_arg_stack_index
].first_ten
= (char **)NULL
;
5602 dollar_arg_stack
[dollar_arg_stack_index
].rest
= (WORD_LIST
*)NULL
;
5603 dollar_arg_stack
[dollar_arg_stack_index
].count
= 0;
5605 set_dollar_vars_unchanged ();
5606 invalidate_cached_quoted_dollar_at ();
5610 dispose_saved_dollar_vars ()
5612 if (dollar_arg_stack
== 0 || dollar_arg_stack_index
== 0)
5615 dispose_words (dollar_arg_stack
[--dollar_arg_stack_index
].rest
);
5616 free_saved_dollar_vars (dollar_arg_stack
[dollar_arg_stack_index
].first_ten
);
5617 free (dollar_arg_stack
[dollar_arg_stack_index
].first_ten
);
5619 dollar_arg_stack
[dollar_arg_stack_index
].first_ten
= (char **)NULL
;
5620 dollar_arg_stack
[dollar_arg_stack_index
].rest
= (WORD_LIST
*)NULL
;
5621 dollar_arg_stack
[dollar_arg_stack_index
].count
= 0;
5624 /* Initialize BUSH_ARGV and BUSH_ARGC after turning on extdebug after the
5625 shell is initialized */
5629 if (bush_argv_initialized
== 0)
5632 bush_argv_initialized
= 1;
5641 list
= list_rest_of_args ();
5643 dispose_words (list
);
5646 /* Manipulate the special BUSH_ARGV and BUSH_ARGC variables. */
5652 #if defined (ARRAY_VARS) && defined (DEBUGGER)
5653 SHELL_VAR
*bush_argv_v
, *bush_argc_v
;
5654 ARRAY
*bush_argv_a
, *bush_argc_a
;
5659 GET_ARRAY_FROM_VAR ("BUSH_ARGV", bush_argv_v
, bush_argv_a
);
5660 GET_ARRAY_FROM_VAR ("BUSH_ARGC", bush_argc_v
, bush_argc_a
);
5662 for (l
= list
, i
= 0; l
; l
= l
->next
, i
++)
5663 array_push (bush_argv_a
, l
->word
->word
);
5666 array_push (bush_argc_a
, t
);
5668 #endif /* ARRAY_VARS && DEBUGGER */
5671 /* Remove arguments from BUSH_ARGV array. Pop top element off BUSH_ARGC
5672 array and use that value as the count of elements to remove from
5677 #if defined (ARRAY_VARS) && defined (DEBUGGER)
5678 SHELL_VAR
*bush_argv_v
, *bush_argc_v
;
5679 ARRAY
*bush_argv_a
, *bush_argc_a
;
5683 GET_ARRAY_FROM_VAR ("BUSH_ARGV", bush_argv_v
, bush_argv_a
);
5684 GET_ARRAY_FROM_VAR ("BUSH_ARGC", bush_argc_v
, bush_argc_a
);
5686 ce
= array_shift (bush_argc_a
, 1, 0);
5687 if (ce
== 0 || legal_number (element_value (ce
), &i
) == 0)
5691 array_pop (bush_argv_a
);
5692 array_dispose_element (ce
);
5693 #endif /* ARRAY_VARS && DEBUGGER */
5696 /*************************************************
5698 * Functions to manage special variables *
5700 *************************************************/
5702 /* Extern declarations for variables this code has to manage. */
5704 /* An alist of name.function for each special variable. Most of the
5705 functions don't do much, and in fact, this would be faster with a
5706 switch statement, but by the end of this file, I am sick of switch
5709 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
5711 /* This table will be sorted with qsort() the first time it's accessed. */
5712 struct name_and_function
{
5714 sh_sv_func_t
*function
;
5717 static struct name_and_function special_vars
[] = {
5718 { "BUSH_COMPAT", sv_shcompat
},
5719 { "BUSH_XTRACEFD", sv_xtracefd
},
5721 #if defined (JOB_CONTROL)
5722 { "CHILD_MAX", sv_childmax
},
5725 #if defined (READLINE)
5726 # if defined (STRICT_POSIX)
5727 { "COLUMNS", sv_winsize
},
5729 { "COMP_WORDBREAKS", sv_comp_wordbreaks
},
5732 { "EXECIGNORE", sv_execignore
},
5734 { "FUNCNEST", sv_funcnest
},
5736 { "GLOBIGNORE", sv_globignore
},
5738 #if defined (HISTORY)
5739 { "HISTCONTROL", sv_history_control
},
5740 { "HISTFILESIZE", sv_histsize
},
5741 { "HISTIGNORE", sv_histignore
},
5742 { "HISTSIZE", sv_histsize
},
5743 { "HISTTIMEFORMAT", sv_histtimefmt
},
5746 #if defined (__CYGWIN__)
5747 { "HOME", sv_home
},
5750 #if defined (READLINE)
5751 { "HOSTFILE", sv_hostfile
},
5755 { "IGNOREEOF", sv_ignoreeof
},
5757 { "LANG", sv_locale
},
5758 { "LC_ALL", sv_locale
},
5759 { "LC_COLLATE", sv_locale
},
5760 { "LC_CTYPE", sv_locale
},
5761 { "LC_MESSAGES", sv_locale
},
5762 { "LC_NUMERIC", sv_locale
},
5763 { "LC_TIME", sv_locale
},
5765 #if defined (READLINE) && defined (STRICT_POSIX)
5766 { "LINES", sv_winsize
},
5769 { "MAIL", sv_mail
},
5770 { "MAILCHECK", sv_mail
},
5771 { "MAILPATH", sv_mail
},
5773 { "OPTERR", sv_opterr
},
5774 { "OPTIND", sv_optind
},
5776 { "PATH", sv_path
},
5777 { "POSIXLY_CORRECT", sv_strict_posix
},
5779 #if defined (READLINE)
5780 { "TERM", sv_terminal
},
5781 { "TERMCAP", sv_terminal
},
5782 { "TERMINFO", sv_terminal
},
5783 #endif /* READLINE */
5785 { "TEXTDOMAIN", sv_locale
},
5786 { "TEXTDOMAINDIR", sv_locale
},
5788 #if defined (HAVE_TZSET)
5792 #if defined (HISTORY) && defined (BANG_HISTORY)
5793 { "histchars", sv_histchars
},
5794 #endif /* HISTORY && BANG_HISTORY */
5796 { "ignoreeof", sv_ignoreeof
},
5798 { (char *)0, (sh_sv_func_t
*)0 }
5801 #define N_SPECIAL_VARS (sizeof (special_vars) / sizeof (special_vars[0]) - 1)
5804 sv_compare (sv1
, sv2
)
5805 struct name_and_function
*sv1
, *sv2
;
5809 if ((r
= sv1
->name
[0] - sv2
->name
[0]) == 0)
5810 r
= strcmp (sv1
->name
, sv2
->name
);
5815 find_special_var (name
)
5820 for (i
= 0; special_vars
[i
].name
; i
++)
5822 r
= special_vars
[i
].name
[0] - name
[0];
5824 r
= strcmp (special_vars
[i
].name
, name
);
5828 /* Can't match any of rest of elements in sorted list. Take this out
5829 if it causes problems in certain environments. */
5835 /* The variable in NAME has just had its state changed. Check to see if it
5836 is one of the special ones where something special happens. */
5838 stupidly_hack_special_variables (name
)
5841 static int sv_sorted
= 0;
5844 if (sv_sorted
== 0) /* shouldn't need, but it's fairly cheap. */
5846 qsort (special_vars
, N_SPECIAL_VARS
, sizeof (special_vars
[0]),
5847 (QSFUNC
*)sv_compare
);
5851 i
= find_special_var (name
);
5853 (*(special_vars
[i
].function
)) (name
);
5856 /* Special variables that need hooks to be run when they are unset as part
5857 of shell reinitialization should have their sv_ functions run here. */
5859 reinit_special_variables ()
5861 #if defined (READLINE)
5862 sv_comp_wordbreaks ("COMP_WORDBREAKS");
5864 sv_globignore ("GLOBIGNORE");
5865 sv_opterr ("OPTERR");
5874 v
= find_variable ("IFS");
5878 /* What to do just after the PATH variable has changed. */
5887 /* What to do just after one of the MAILxxxx variables has changed. NAME
5888 is the name of the variable. This is called with NAME set to one of
5889 MAIL, MAILCHECK, or MAILPATH. */
5894 /* If the time interval for checking the files has changed, then
5895 reset the mail timer. Otherwise, one of the pathname vars
5896 to the users mailbox has changed, so rebuild the array of
5898 if (name
[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
5899 reset_mail_timer ();
5903 remember_mail_dates ();
5914 v
= find_variable (name
);
5917 else if (legal_number (value_cell (v
), &num
) == 0)
5923 /* What to do when EXECIGNORE changes. */
5925 sv_execignore (name
)
5928 setup_exec_ignore (name
);
5931 /* What to do when GLOBIGNORE changes. */
5933 sv_globignore (name
)
5936 if (privileged_mode
== 0)
5937 setup_glob_ignore (name
);
5940 #if defined (READLINE)
5942 sv_comp_wordbreaks (name
)
5947 sv
= find_variable (name
);
5949 reset_completer_word_break_chars ();
5952 /* What to do just after one of the TERMxxx variables has changed.
5953 If we are an interactive shell, then try to reset the terminal
5954 information in readline. */
5959 if (interactive_shell
&& no_line_editing
== 0)
5960 rl_reset_terminal (get_string_value ("TERM"));
5969 v
= find_variable (name
);
5971 clear_hostname_list ();
5973 hostname_list_initialized
= 0;
5976 #if defined (STRICT_POSIX)
5977 /* In strict posix mode, we allow assignments to LINES and COLUMNS (and values
5978 found in the initial environment) to override the terminal size reported by
5988 if (posixly_correct
== 0 || interactive_shell
== 0 || no_line_editing
)
5991 v
= find_variable (name
);
5992 if (v
== 0 || var_isset (v
) == 0)
5993 rl_reset_screen_size ();
5996 if (legal_number (value_cell (v
), &xd
) == 0)
5998 winsize_assignment
= 1;
5999 d
= xd
; /* truncate */
6000 if (name
[0] == 'L') /* LINES */
6001 rl_set_screen_size (d
, -1);
6003 rl_set_screen_size (-1, d
);
6004 winsize_assignment
= 0;
6007 #endif /* STRICT_POSIX */
6008 #endif /* READLINE */
6010 /* Update the value of HOME in the export environment so tilde expansion will
6012 #if defined (__CYGWIN__)
6016 array_needs_making
= 1;
6017 maybe_make_export_env ();
6021 #if defined (HISTORY)
6022 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
6023 If there is a value for this HISTSIZE (and it is numeric), then stifle
6024 the history. Otherwise, if there is NO value for this variable,
6025 unstifle the history. If name is HISTFILESIZE, and its value is
6026 numeric, truncate the history file to hold no more than that many
6036 temp
= get_string_value (name
);
6040 if (legal_number (temp
, &num
))
6043 if (hmax
< 0 && name
[4] == 'S')
6044 unstifle_history (); /* unstifle history if HISTSIZE < 0 */
6045 else if (name
[4] == 'S')
6047 stifle_history (hmax
);
6048 hmax
= where_history ();
6049 if (history_lines_this_session
> hmax
)
6050 history_lines_this_session
= hmax
;
6052 else if (hmax
>= 0) /* truncate HISTFILE if HISTFILESIZE >= 0 */
6054 history_truncate_file (get_string_value ("HISTFILE"), hmax
);
6055 /* If we just shrank the history file to fewer lines than we've
6056 already read, make sure we adjust our idea of how many lines
6057 we have read from the file. */
6058 if (hmax
< history_lines_in_file
)
6059 history_lines_in_file
= hmax
;
6063 else if (name
[4] == 'S')
6064 unstifle_history ();
6067 /* What to do after the HISTIGNORE variable changes. */
6069 sv_histignore (name
)
6072 setup_history_ignore (name
);
6075 /* What to do after the HISTCONTROL variable changes. */
6077 sv_history_control (name
)
6084 history_control
= 0;
6085 temp
= get_string_value (name
);
6087 if (temp
== 0 || *temp
== 0)
6091 while (val
= extract_colon_unit (temp
, &tptr
))
6093 if (STREQ (val
, "ignorespace"))
6094 history_control
|= HC_IGNSPACE
;
6095 else if (STREQ (val
, "ignoredups"))
6096 history_control
|= HC_IGNDUPS
;
6097 else if (STREQ (val
, "ignoreboth"))
6098 history_control
|= HC_IGNBOTH
;
6099 else if (STREQ (val
, "erasedups"))
6100 history_control
|= HC_ERASEDUPS
;
6106 #if defined (BANG_HISTORY)
6107 /* Setting/unsetting of the history expansion character. */
6114 temp
= get_string_value (name
);
6117 history_expansion_char
= *temp
;
6118 if (temp
[0] && temp
[1])
6120 history_subst_char
= temp
[1];
6122 history_comment_char
= temp
[2];
6127 history_expansion_char
= '!';
6128 history_subst_char
= '^';
6129 history_comment_char
= '#';
6132 #endif /* BANG_HISTORY */
6135 sv_histtimefmt (name
)
6140 if (v
= find_variable (name
))
6142 if (history_comment_char
== 0)
6143 history_comment_char
= '#';
6145 history_write_timestamps
= (v
!= 0);
6147 #endif /* HISTORY */
6149 #if defined (HAVE_TZSET)
6156 v
= find_variable (name
);
6157 if (v
&& exported_p (v
))
6158 array_needs_making
= 1;
6160 array_needs_making
= 1;
6162 if (array_needs_making
)
6164 maybe_make_export_env ();
6170 /* If the variable exists, then the value of it can be the number
6171 of times we actually ignore the EOF. The default is small,
6172 (smaller than csh, anyway). */
6180 eof_encountered
= 0;
6182 tmp_var
= find_variable (name
);
6183 ignoreeof
= tmp_var
&& var_isset (tmp_var
);
6184 temp
= tmp_var
? value_cell (tmp_var
) : (char *)NULL
;
6186 eof_encountered_limit
= (*temp
&& all_digits (temp
)) ? atoi (temp
) : 10;
6187 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
6198 var
= find_variable ("OPTIND");
6199 tt
= var
? get_variable_value (var
) : (char *)NULL
;
6201 /* Assume that if var->context < variable_context and variable_context > 0
6202 then we are restoring the variables's previous state while returning
6208 /* According to POSIX, setting OPTIND=1 resets the internal state
6210 if (s
< 0 || s
== 1)
6224 tt
= get_string_value ("OPTERR");
6225 sh_opterr
= (tt
&& *tt
) ? atoi (tt
) : 1;
6229 sv_strict_posix (name
)
6234 var
= find_variable (name
);
6235 posixly_correct
= var
&& var_isset (var
);
6236 posix_initialize (posixly_correct
);
6237 #if defined (READLINE)
6238 if (interactive_shell
)
6239 posix_readline_initialize (posixly_correct
);
6240 #endif /* READLINE */
6241 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
6251 v
= get_string_value (name
);
6252 if (name
[0] == 'L' && name
[1] == 'A') /* LANG */
6253 r
= set_lang (name
, v
);
6255 r
= set_locale_var (name
, v
); /* LC_*, TEXTDOMAIN* */
6258 if (r
== 0 && posixly_correct
)
6259 set_exit_status (EXECUTION_FAILURE
);
6263 #if defined (ARRAY_VARS)
6265 set_pipestatus_array (ps
, nproc
)
6273 char *t
, tbuf
[INT_STRLEN_BOUND(int) + 1];
6275 v
= find_variable ("PIPESTATUS");
6277 v
= make_new_array_variable ("PIPESTATUS");
6278 if (array_p (v
) == 0)
6279 return; /* Do nothing if not an array variable. */
6282 if (a
== 0 || array_num_elements (a
) == 0)
6284 for (i
= 0; i
< nproc
; i
++) /* was ps[i] != -1, not i < nproc */
6286 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
6287 array_insert (a
, i
, t
);
6293 if (array_num_elements (a
) == nproc
&& nproc
== 1)
6295 ae
= element_forw (a
->head
);
6296 free (element_value (ae
));
6297 set_element_value (ae
, itos (ps
[0]));
6299 else if (array_num_elements (a
) <= nproc
)
6301 /* modify in array_num_elements members in place, then add */
6303 for (i
= 0; i
< array_num_elements (a
); i
++)
6305 ae
= element_forw (ae
);
6306 free (element_value (ae
));
6307 set_element_value (ae
, itos (ps
[i
]));
6310 for ( ; i
< nproc
; i
++)
6312 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
6313 array_insert (a
, i
, t
);
6318 /* deleting elements. it's faster to rebuild the array. */
6320 for (i
= 0; ps
[i
] != -1; i
++)
6322 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
6323 array_insert (a
, i
, t
);
6329 save_pipestatus_array ()
6334 v
= find_variable ("PIPESTATUS");
6335 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
6336 return ((ARRAY
*)NULL
);
6338 a
= array_copy (array_cell (v
));
6344 restore_pipestatus_array (a
)
6350 v
= find_variable ("PIPESTATUS");
6351 /* XXX - should we still assign even if existing value is NULL? */
6352 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
6355 a2
= array_cell (v
);
6356 var_setarray (v
, a
);
6363 set_pipestatus_from_exit (s
)
6366 #if defined (ARRAY_VARS)
6367 static int v
[2] = { 0, -1 };
6370 set_pipestatus_array (v
, 1);
6383 v
= find_variable (name
);
6391 if (t
== 0 || *t
== 0)
6395 fd
= (int)strtol (t
, &e
, 10);
6396 if (e
!= t
&& *e
== '\0' && sh_validfd (fd
))
6398 fp
= fdopen (fd
, "w");
6400 internal_error (_("%s: %s: cannot open as FILE"), name
, value_cell (v
));
6402 xtrace_set (fd
, fp
);
6405 internal_error (_("%s: %s: invalid value for trace file descriptor"), name
, value_cell (v
));
6409 #define MIN_COMPAT_LEVEL 31
6417 int tens
, ones
, compatval
;
6419 v
= find_variable (name
);
6422 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
6423 set_compatibility_opts ();
6426 val
= value_cell (v
);
6427 if (val
== 0 || *val
== '\0')
6429 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
6430 set_compatibility_opts ();
6433 /* Handle decimal-like compatibility version specifications: 4.2 */
6434 if (ISDIGIT (val
[0]) && val
[1] == '.' && ISDIGIT (val
[2]) && val
[3] == 0)
6436 tens
= val
[0] - '0';
6437 ones
= val
[2] - '0';
6438 compatval
= tens
*10 + ones
;
6440 /* Handle integer-like compatibility version specifications: 42 */
6441 else if (ISDIGIT (val
[0]) && ISDIGIT (val
[1]) && val
[2] == 0)
6443 tens
= val
[0] - '0';
6444 ones
= val
[1] - '0';
6445 compatval
= tens
*10 + ones
;
6450 internal_error (_("%s: %s: compatibility value out of range"), name
, val
);
6451 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
6452 set_compatibility_opts ();
6456 if (compatval
< MIN_COMPAT_LEVEL
|| compatval
> DEFAULT_COMPAT_LEVEL
)
6459 shell_compatibility_level
= compatval
;
6460 set_compatibility_opts ();
6463 #if defined (JOB_CONTROL)
6471 tt
= get_string_value (name
);
6472 s
= (tt
&& *tt
) ? atoi (tt
) : 0;