1 /* variables.c -- Functions for hacking shell variables. */
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #include "bashtypes.h"
24 #include "posixstat.h"
25 #include "posixtime.h"
28 # if defined (__QNXNTO__)
29 # include <sys/netmgr.h>
32 # endif /* !__QNXNTO__ */
35 #if defined (HAVE_UNISTD_H)
40 #include "chartypes.h"
41 #if defined (HAVE_PWD_H)
49 #include "execute_cmd.h"
51 #include "mailcheck.h"
57 #include "builtins/getopt.h"
58 #include "builtins/common.h"
60 #if defined (READLINE)
61 # include "bashline.h"
62 # include <readline/readline.h>
64 # include <tilde/tilde.h>
68 # include "bashhist.h"
69 # include <readline/history.h>
72 #if defined (PROGRAMMABLE_COMPLETION)
73 # include "pcomplete.h"
76 #define TEMPENV_HASH_BUCKETS 4 /* must be power of two */
78 #define ifsname(s) ((s)[0] == 'I' && (s)[1] == 'F' && (s)[2] == 'S' && (s)[3] == '\0')
80 extern char **environ;
82 /* Variables used here and defined in other files. */
83 extern int posixly_correct;
84 extern int line_number;
85 extern int subshell_environment, indirection_level, subshell_level;
86 extern int build_version, patch_level;
87 extern int expanding_redir;
88 extern char *dist_version, *release_status;
89 extern char *shell_name;
90 extern char *primary_prompt, *secondary_prompt;
91 extern char *current_host_name;
92 extern sh_builtin_func_t *this_shell_builtin;
93 extern SHELL_VAR *this_shell_function;
94 extern char *the_printed_command_except_trap;
95 extern char *this_command_name;
96 extern char *command_execution_string;
97 extern time_t shell_start_time;
98 extern int assigning_in_environment;
99 extern int executing_builtin;
101 #if defined (READLINE)
102 extern int no_line_editing;
103 extern int perform_hostname_completion;
106 /* The list of shell variables that the user has created at the global
107 scope, or that came from the environment. */
108 VAR_CONTEXT *global_variables = (VAR_CONTEXT *)NULL;
110 /* The current list of shell variables, including function scopes */
111 VAR_CONTEXT *shell_variables = (VAR_CONTEXT *)NULL;
113 /* The list of shell functions that the user has created, or that came from
115 HASH_TABLE *shell_functions = (HASH_TABLE *)NULL;
117 #if defined (DEBUGGER)
118 /* The table of shell function definitions that the user defined or that
119 came from the environment. */
120 HASH_TABLE *shell_function_defs = (HASH_TABLE *)NULL;
123 /* The current variable context. This is really a count of how deep into
124 executing functions we are. */
125 int variable_context = 0;
127 /* The set of shell assignments which are made only in the environment
128 for a single command. */
129 HASH_TABLE *temporary_env = (HASH_TABLE *)NULL;
131 /* Set to non-zero if an assignment error occurs while putting variables
132 into the temporary environment. */
133 int tempenv_assign_error;
135 /* Some funky variables which are known about specially. Here is where
136 "$*", "$1", and all the cruft is kept. */
137 char *dollar_vars[10];
138 WORD_LIST *rest_of_args = (WORD_LIST *)NULL;
140 /* The value of $$. */
141 pid_t dollar_dollar_pid;
143 /* Non-zero means that we have to remake EXPORT_ENV. */
144 int array_needs_making = 1;
146 /* The number of times BASH has been executed. This is set
147 by initialize_variables (). */
150 /* An array which is passed to commands as their environment. It is
151 manufactured from the union of the initial environment and the
152 shell variables that are marked for export. */
153 char **export_env = (char **)NULL;
154 static int export_env_index;
155 static int export_env_size;
157 #if defined (READLINE)
158 static int winsize_assignment; /* currently assigning to LINES or COLUMNS */
159 static int winsize_assigned; /* assigned to LINES or COLUMNS */
162 /* Some forward declarations. */
163 static void create_variable_tables __P((void));
165 static void set_machine_vars __P((void));
166 static void set_home_var __P((void));
167 static void set_shell_var __P((void));
168 static char *get_bash_name __P((void));
169 static void initialize_shell_level __P((void));
170 static void uidset __P((void));
171 #if defined (ARRAY_VARS)
172 static void make_vers_array __P((void));
175 static SHELL_VAR *null_assign __P((SHELL_VAR *, char *, arrayind_t, char *));
176 #if defined (ARRAY_VARS)
177 static SHELL_VAR *null_array_assign __P((SHELL_VAR *, char *, arrayind_t, char *));
179 static SHELL_VAR *get_self __P((SHELL_VAR *));
181 #if defined (ARRAY_VARS)
182 static SHELL_VAR *init_dynamic_array_var __P((char *, sh_var_value_func_t *, sh_var_assign_func_t *, int));
183 static SHELL_VAR *init_dynamic_assoc_var __P((char *, sh_var_value_func_t *, sh_var_assign_func_t *, int));
186 static SHELL_VAR *assign_seconds __P((SHELL_VAR *, char *, arrayind_t, char *));
187 static SHELL_VAR *get_seconds __P((SHELL_VAR *));
188 static SHELL_VAR *init_seconds_var __P((void));
190 static int brand __P((void));
191 static void sbrand __P((unsigned long)); /* set bash random number generator. */
192 static void seedrand __P((void)); /* seed generator randomly */
193 static SHELL_VAR *assign_random __P((SHELL_VAR *, char *, arrayind_t, char *));
194 static SHELL_VAR *get_random __P((SHELL_VAR *));
196 static SHELL_VAR *assign_lineno __P((SHELL_VAR *, char *, arrayind_t, char *));
197 static SHELL_VAR *get_lineno __P((SHELL_VAR *));
199 static SHELL_VAR *assign_subshell __P((SHELL_VAR *, char *, arrayind_t, char *));
200 static SHELL_VAR *get_subshell __P((SHELL_VAR *));
202 static SHELL_VAR *get_bashpid __P((SHELL_VAR *));
204 #if defined (HISTORY)
205 static SHELL_VAR *get_histcmd __P((SHELL_VAR *));
208 #if defined (READLINE)
209 static SHELL_VAR *get_comp_wordbreaks __P((SHELL_VAR *));
210 static SHELL_VAR *assign_comp_wordbreaks __P((SHELL_VAR *, char *, arrayind_t, char *));
213 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
214 static SHELL_VAR *assign_dirstack __P((SHELL_VAR *, char *, arrayind_t, char *));
215 static SHELL_VAR *get_dirstack __P((SHELL_VAR *));
218 #if defined (ARRAY_VARS)
219 static SHELL_VAR *get_groupset __P((SHELL_VAR *));
221 static SHELL_VAR *build_hashcmd __P((SHELL_VAR *));
222 static SHELL_VAR *get_hashcmd __P((SHELL_VAR *));
223 static SHELL_VAR *assign_hashcmd __P((SHELL_VAR *, char *, arrayind_t, char *));
224 static SHELL_VAR *build_aliasvar __P((SHELL_VAR *));
225 static SHELL_VAR *get_aliasvar __P((SHELL_VAR *));
226 static SHELL_VAR *assign_aliasvar __P((SHELL_VAR *, char *, arrayind_t, char *));
229 static SHELL_VAR *get_funcname __P((SHELL_VAR *));
230 static SHELL_VAR *init_funcname_var __P((void));
232 static void initialize_dynamic_variables __P((void));
234 static SHELL_VAR *hash_lookup __P((const char *, HASH_TABLE *));
235 static SHELL_VAR *new_shell_variable __P((const char *));
236 static SHELL_VAR *make_new_variable __P((const char *, HASH_TABLE *));
237 static SHELL_VAR *bind_variable_internal __P((const char *, char *, HASH_TABLE *, int, int));
239 static void dispose_variable_value __P((SHELL_VAR *));
240 static void free_variable_hash_data __P((PTR_T));
242 static VARLIST *vlist_alloc __P((int));
243 static VARLIST *vlist_realloc __P((VARLIST *, int));
244 static void vlist_add __P((VARLIST *, SHELL_VAR *, int));
246 static void flatten __P((HASH_TABLE *, sh_var_map_func_t *, VARLIST *, int));
248 static int qsort_var_comp __P((SHELL_VAR **, SHELL_VAR **));
250 static SHELL_VAR **vapply __P((sh_var_map_func_t *));
251 static SHELL_VAR **fapply __P((sh_var_map_func_t *));
253 static int visible_var __P((SHELL_VAR *));
254 static int visible_and_exported __P((SHELL_VAR *));
255 static int export_environment_candidate __P((SHELL_VAR *));
256 static int local_and_exported __P((SHELL_VAR *));
257 static int variable_in_context __P((SHELL_VAR *));
258 #if defined (ARRAY_VARS)
259 static int visible_array_vars __P((SHELL_VAR *));
262 static SHELL_VAR *bind_tempenv_variable __P((const char *, char *));
263 static void push_temp_var __P((PTR_T));
264 static void propagate_temp_var __P((PTR_T));
265 static void dispose_temporary_env __P((sh_free_func_t *));
267 static inline char *mk_env_string __P((const char *, const char *));
268 static char **make_env_array_from_var_list __P((SHELL_VAR **));
269 static char **make_var_export_array __P((VAR_CONTEXT *));
270 static char **make_func_export_array __P((void));
271 static void add_temp_array_to_env __P((char **, int, int));
273 static int n_shell_variables __P((void));
274 static int set_context __P((SHELL_VAR *));
276 static void push_func_var __P((PTR_T));
277 static void push_exported_var __P((PTR_T));
279 static inline int find_special_var __P((const char *));
282 create_variable_tables ()
284 if (shell_variables == 0)
286 shell_variables = global_variables = new_var_context ((char *)NULL, 0);
287 shell_variables->scope = 0;
288 shell_variables->table = hash_create (0);
291 if (shell_functions == 0)
292 shell_functions = hash_create (0);
294 #if defined (DEBUGGER)
295 if (shell_function_defs == 0)
296 shell_function_defs = hash_create (0);
300 /* Initialize the shell variables from the current environment.
301 If PRIVMODE is nonzero, don't import functions from ENV or
304 initialize_shell_variables (env, privmode)
308 char *name, *string, *temp_string;
309 int c, char_index, string_index, string_length;
312 create_variable_tables ();
314 for (string_index = 0; string = env[string_index++]; )
318 while ((c = *string++) && c != '=')
320 if (string[-1] == '=')
321 char_index = string - name - 1;
323 /* If there are weird things in the environment, like `=xxx' or a
324 string without an `=', just skip them. */
328 /* ASSERT(name[char_index] == '=') */
329 name[char_index] = '\0';
330 /* Now, name = env variable name, string = env variable value, and
331 char_index == strlen (name) */
333 temp_var = (SHELL_VAR *)NULL;
335 /* If exported function, define it now. Don't import functions from
336 the environment in privileged mode. */
337 if (privmode == 0 && read_but_dont_execute == 0 && STREQN ("() {", string, 4))
339 string_length = strlen (string);
340 temp_string = (char *)xmalloc (3 + string_length + char_index);
342 strcpy (temp_string, name);
343 temp_string[char_index] = ' ';
344 strcpy (temp_string + char_index + 1, string);
346 parse_and_execute (temp_string, name, SEVAL_NONINT|SEVAL_NOHIST);
348 /* Ancient backwards compatibility. Old versions of bash exported
349 functions like name()=() {...} */
350 if (name[char_index - 1] == ')' && name[char_index - 2] == '(')
351 name[char_index - 2] = '\0';
353 if (temp_var = find_function (name))
355 VSETATTR (temp_var, (att_exported|att_imported));
356 array_needs_making = 1;
359 report_error (_("error importing function definition for `%s'"), name);
362 if (name[char_index - 1] == ')' && name[char_index - 2] == '\0')
363 name[char_index - 2] = '('; /* ) */
365 #if defined (ARRAY_VARS)
367 /* Array variables may not yet be exported. */
368 else if (*string == '(' && string[1] == '[' && string[strlen (string) - 1] == ')')
371 temp_string = extract_array_assignment_list (string, &string_length);
372 temp_var = assign_array_from_string (name, temp_string);
374 VSETATTR (temp_var, (att_exported | att_imported));
375 array_needs_making = 1;
380 else if (legal_identifier (name))
385 temp_var = bind_variable (name, string, 0);
386 if (legal_identifier (name))
387 VSETATTR (temp_var, (att_exported | att_imported));
389 VSETATTR (temp_var, (att_exported | att_imported | att_invisible));
390 array_needs_making = 1;
393 name[char_index] = '=';
394 /* temp_var can be NULL if it was an exported function with a syntax
395 error (a different bug, but it still shouldn't dump core). */
396 if (temp_var && function_p (temp_var) == 0) /* XXX not yet */
398 CACHE_IMPORTSTR (temp_var, name);
404 /* Set up initial value of $_ */
405 temp_var = set_if_not ("_", dollar_vars[0]);
407 /* Remember this pid. */
408 dollar_dollar_pid = getpid ();
410 /* Now make our own defaults in case the vars that we think are
411 important are missing. */
412 temp_var = set_if_not ("PATH", DEFAULT_PATH_VALUE);
414 set_auto_export (temp_var); /* XXX */
417 temp_var = set_if_not ("TERM", "dumb");
419 set_auto_export (temp_var); /* XXX */
422 #if defined (__QNX__)
423 /* set node id -- don't import it from the environment */
426 # if defined (__QNXNTO__)
427 netmgr_ndtostr(ND2S_LOCAL_STR, ND_LOCAL_NODE, node_name, sizeof(node_name));
429 qnx_nidtostr (getnid (), node_name, sizeof (node_name));
431 temp_var = bind_variable ("NODE", node_name, 0);
432 set_auto_export (temp_var);
436 /* set up the prompts. */
437 if (interactive_shell)
439 #if defined (PROMPT_STRING_DECODE)
440 set_if_not ("PS1", primary_prompt);
442 if (current_user.uid == -1)
443 get_current_user_info ();
444 set_if_not ("PS1", current_user.euid == 0 ? "# " : primary_prompt);
446 set_if_not ("PS2", secondary_prompt);
448 set_if_not ("PS4", "+ ");
450 /* Don't allow IFS to be imported from the environment. */
451 temp_var = bind_variable ("IFS", " \t\n", 0);
454 /* Magic machine types. Pretty convenient. */
457 /* Default MAILCHECK for interactive shells. Defer the creation of a
458 default MAILPATH until the startup files are read, because MAIL
459 names a mail file if MAILPATH is not set, and we should provide a
460 default only if neither is set. */
461 if (interactive_shell)
463 temp_var = set_if_not ("MAILCHECK", posixly_correct ? "600" : "60");
464 VSETATTR (temp_var, att_integer);
467 /* Do some things with shell level. */
468 initialize_shell_level ();
472 /* Initialize the `getopts' stuff. */
473 temp_var = bind_variable ("OPTIND", "1", 0);
474 VSETATTR (temp_var, att_integer);
476 bind_variable ("OPTERR", "1", 0);
479 if (login_shell == 1 && posixly_correct == 0)
482 /* Get the full pathname to THIS shell, and set the BASH variable
484 name = get_bash_name ();
485 temp_var = bind_variable ("BASH", name, 0);
488 /* Make the exported environment variable SHELL be the user's login
489 shell. Note that the `tset' command looks at this variable
490 to determine what style of commands to output; if it ends in "csh",
491 then C-shell commands are output, else Bourne shell commands. */
494 /* Make a variable called BASH_VERSION which contains the version info. */
495 bind_variable ("BASH_VERSION", shell_version_string (), 0);
496 #if defined (ARRAY_VARS)
500 if (command_execution_string)
501 bind_variable ("BASH_EXECUTION_STRING", command_execution_string, 0);
503 /* Find out if we're supposed to be in Posix.2 mode via an
504 environment variable. */
505 temp_var = find_variable ("POSIXLY_CORRECT");
507 temp_var = find_variable ("POSIX_PEDANTIC");
508 if (temp_var && imported_p (temp_var))
509 sv_strict_posix (temp_var->name);
511 #if defined (HISTORY)
512 /* Set history variables to defaults, and then do whatever we would
513 do if the variable had just been set. Do this only in the case
514 that we are remembering commands on the history list. */
515 if (remember_on_history)
517 name = bash_tilde_expand (posixly_correct ? "~/.sh_history" : "~/.bash_history", 0);
519 set_if_not ("HISTFILE", name);
523 set_if_not ("HISTSIZE", "500");
524 sv_histsize ("HISTSIZE");
529 /* Seed the random number generator. */
532 /* Handle some "special" variables that we may have inherited from a
534 if (interactive_shell)
536 temp_var = find_variable ("IGNOREEOF");
538 temp_var = find_variable ("ignoreeof");
539 if (temp_var && imported_p (temp_var))
540 sv_ignoreeof (temp_var->name);
543 #if defined (HISTORY)
544 if (interactive_shell && remember_on_history)
546 sv_history_control ("HISTCONTROL");
547 sv_histignore ("HISTIGNORE");
548 sv_histtimefmt ("HISTTIMEFORMAT");
552 #if defined (READLINE) && defined (STRICT_POSIX)
553 /* POSIXLY_CORRECT will only be 1 here if the shell was compiled
555 if (interactive_shell && posixly_correct && no_line_editing == 0)
556 rl_prefer_env_winsize = 1;
557 #endif /* READLINE && STRICT_POSIX */
562 * I'm tired of the arguing and bug reports. Bash now leaves SSH_CLIENT
563 * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in
564 * isnetconn() to avoid running the startup files more often than wanted.
565 * That will, of course, only work if the user's login shell is bash, so
566 * I've made that behavior conditional on SSH_SOURCE_BASHRC being defined
570 temp_var = find_variable ("SSH_CLIENT");
571 if (temp_var && imported_p (temp_var))
573 VUNSETATTR (temp_var, att_exported);
574 array_needs_making = 1;
576 temp_var = find_variable ("SSH2_CLIENT");
577 if (temp_var && imported_p (temp_var))
579 VUNSETATTR (temp_var, att_exported);
580 array_needs_making = 1;
584 /* Get the user's real and effective user ids. */
587 /* Initialize the dynamic variables, and seed their values. */
588 initialize_dynamic_variables ();
591 /* **************************************************************** */
593 /* Setting values for special shell variables */
595 /* **************************************************************** */
602 temp_var = set_if_not ("HOSTTYPE", HOSTTYPE);
603 temp_var = set_if_not ("OSTYPE", OSTYPE);
604 temp_var = set_if_not ("MACHTYPE", MACHTYPE);
606 temp_var = set_if_not ("HOSTNAME", current_host_name);
609 /* Set $HOME to the information in the password file if we didn't get
610 it from the environment. */
612 /* This function is not static so the tilde and readline libraries can
617 if (current_user.home_dir == 0)
618 get_current_user_info ();
619 return current_user.home_dir;
627 temp_var = find_variable ("HOME");
629 temp_var = bind_variable ("HOME", sh_get_home_dir (), 0);
631 VSETATTR (temp_var, att_exported);
635 /* Set $SHELL to the user's login shell if it is not already set. Call
636 get_current_user_info if we haven't already fetched the shell. */
642 temp_var = find_variable ("SHELL");
645 if (current_user.shell == 0)
646 get_current_user_info ();
647 temp_var = bind_variable ("SHELL", current_user.shell, 0);
650 VSETATTR (temp_var, att_exported);
659 if ((login_shell == 1) && RELPATH(shell_name))
661 if (current_user.shell == 0)
662 get_current_user_info ();
663 name = savestring (current_user.shell);
665 else if (ABSPATH(shell_name))
666 name = savestring (shell_name);
667 else if (shell_name[0] == '.' && shell_name[1] == '/')
669 /* Fast path for common case. */
673 cdir = get_string_value ("PWD");
677 name = (char *)xmalloc (len + strlen (shell_name) + 1);
679 strcpy (name + len, shell_name + 1);
682 name = savestring (shell_name);
689 tname = find_user_command (shell_name);
693 /* Try the current directory. If there is not an executable
694 there, just punt and use the login shell. */
695 s = file_status (shell_name);
698 tname = make_absolute (shell_name, get_string_value ("PWD"));
699 if (*shell_name == '.')
701 name = sh_canonpath (tname, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
712 if (current_user.shell == 0)
713 get_current_user_info ();
714 name = savestring (current_user.shell);
719 name = full_pathname (tname);
728 adjust_shell_level (change)
731 char new_level[5], *old_SHLVL;
735 old_SHLVL = get_string_value ("SHLVL");
736 if (old_SHLVL == 0 || *old_SHLVL == '\0' || legal_number (old_SHLVL, &old_level) == 0)
739 shell_level = old_level + change;
742 else if (shell_level > 1000)
744 internal_warning (_("shell level (%d) too high, resetting to 1"), shell_level);
748 /* We don't need the full generality of itos here. */
749 if (shell_level < 10)
751 new_level[0] = shell_level + '0';
754 else if (shell_level < 100)
756 new_level[0] = (shell_level / 10) + '0';
757 new_level[1] = (shell_level % 10) + '0';
760 else if (shell_level < 1000)
762 new_level[0] = (shell_level / 100) + '0';
763 old_level = shell_level % 100;
764 new_level[1] = (old_level / 10) + '0';
765 new_level[2] = (old_level % 10) + '0';
769 temp_var = bind_variable ("SHLVL", new_level, 0);
770 set_auto_export (temp_var);
774 initialize_shell_level ()
776 adjust_shell_level (1);
779 /* If we got PWD from the environment, update our idea of the current
780 working directory. In any case, make sure that PWD exists before
781 checking it. It is possible for getcwd () to fail on shell startup,
782 and in that case, PWD would be undefined. If this is an interactive
783 login shell, see if $HOME is the current working directory, and if
784 that's not the same string as $PWD, set PWD=$HOME. */
789 SHELL_VAR *temp_var, *home_var;
790 char *temp_string, *home_string;
792 home_var = find_variable ("HOME");
793 home_string = home_var ? value_cell (home_var) : (char *)NULL;
795 temp_var = find_variable ("PWD");
796 if (temp_var && imported_p (temp_var) &&
797 (temp_string = value_cell (temp_var)) &&
798 same_file (temp_string, ".", (struct stat *)NULL, (struct stat *)NULL))
799 set_working_directory (temp_string);
800 else if (home_string && interactive_shell && login_shell &&
801 same_file (home_string, ".", (struct stat *)NULL, (struct stat *)NULL))
803 set_working_directory (home_string);
804 temp_var = bind_variable ("PWD", home_string, 0);
805 set_auto_export (temp_var);
809 temp_string = get_working_directory ("shell-init");
812 temp_var = bind_variable ("PWD", temp_string, 0);
813 set_auto_export (temp_var);
818 /* According to the Single Unix Specification, v2, $OLDPWD is an
819 `environment variable' and therefore should be auto-exported.
820 Make a dummy invisible variable for OLDPWD, and mark it as exported. */
821 temp_var = bind_variable ("OLDPWD", (char *)NULL, 0);
822 VSETATTR (temp_var, (att_exported | att_invisible));
825 /* Make a variable $PPID, which holds the pid of the shell's parent. */
829 char namebuf[INT_STRLEN_BOUND(pid_t) + 1], *name;
832 name = inttostr (getppid (), namebuf, sizeof(namebuf));
833 temp_var = find_variable ("PPID");
835 VUNSETATTR (temp_var, (att_readonly | att_exported));
836 temp_var = bind_variable ("PPID", name, 0);
837 VSETATTR (temp_var, (att_readonly | att_integer));
843 char buff[INT_STRLEN_BOUND(uid_t) + 1], *b;
844 register SHELL_VAR *v;
846 b = inttostr (current_user.uid, buff, sizeof (buff));
847 v = find_variable ("UID");
850 v = bind_variable ("UID", b, 0);
851 VSETATTR (v, (att_readonly | att_integer));
854 if (current_user.euid != current_user.uid)
855 b = inttostr (current_user.euid, buff, sizeof (buff));
857 v = find_variable ("EUID");
860 v = bind_variable ("EUID", b, 0);
861 VSETATTR (v, (att_readonly | att_integer));
865 #if defined (ARRAY_VARS)
871 char *s, d[32], b[INT_STRLEN_BOUND(int) + 1];
873 unbind_variable ("BASH_VERSINFO");
875 vv = make_new_array_variable ("BASH_VERSINFO");
876 av = array_cell (vv);
877 strcpy (d, dist_version);
878 s = xstrchr (d, '.');
881 array_insert (av, 0, d);
882 array_insert (av, 1, s);
883 s = inttostr (patch_level, b, sizeof (b));
884 array_insert (av, 2, s);
885 s = inttostr (build_version, b, sizeof (b));
886 array_insert (av, 3, s);
887 array_insert (av, 4, release_status);
888 array_insert (av, 5, MACHTYPE);
890 VSETATTR (vv, att_readonly);
892 #endif /* ARRAY_VARS */
894 /* Set the environment variables $LINES and $COLUMNS in response to
895 a window size change. */
897 sh_set_lines_and_columns (lines, cols)
900 char val[INT_STRLEN_BOUND(int) + 1], *v;
902 #if defined (READLINE)
903 /* If we are currently assigning to LINES or COLUMNS, don't do anything. */
904 if (winsize_assignment)
908 v = inttostr (lines, val, sizeof (val));
909 bind_variable ("LINES", v, 0);
911 v = inttostr (cols, val, sizeof (val));
912 bind_variable ("COLUMNS", v, 0);
915 /* **************************************************************** */
917 /* Printing variables and values */
919 /* **************************************************************** */
921 /* Print LIST (a list of shell variables) to stdout in such a way that
922 they can be read back in. */
924 print_var_list (list)
925 register SHELL_VAR **list;
928 register SHELL_VAR *var;
930 for (i = 0; list && (var = list[i]); i++)
931 if (invisible_p (var) == 0)
932 print_assignment (var);
935 /* Print LIST (a list of shell functions) to stdout in such a way that
936 they can be read back in. */
938 print_func_list (list)
939 register SHELL_VAR **list;
942 register SHELL_VAR *var;
944 for (i = 0; list && (var = list[i]); i++)
946 printf ("%s ", var->name);
947 print_var_function (var);
952 /* Print the value of a single SHELL_VAR. No newline is
953 output, but the variable is printed in such a way that
954 it can be read back in. */
956 print_assignment (var)
959 if (var_isset (var) == 0)
962 if (function_p (var))
964 printf ("%s", var->name);
965 print_var_function (var);
968 #if defined (ARRAY_VARS)
969 else if (array_p (var))
970 print_array_assignment (var, 0);
971 else if (assoc_p (var))
972 print_assoc_assignment (var, 0);
973 #endif /* ARRAY_VARS */
976 printf ("%s=", var->name);
977 print_var_value (var, 1);
982 /* Print the value cell of VAR, a shell variable. Do not print
983 the name, nor leading/trailing newline. If QUOTE is non-zero,
984 and the value contains shell metacharacters, quote the value
985 in such a way that it can be read back in. */
987 print_var_value (var, quote)
993 if (var_isset (var) == 0)
996 if (quote && posixly_correct == 0 && ansic_shouldquote (value_cell (var)))
998 t = ansic_quote (value_cell (var), 0, (int *)0);
1002 else if (quote && sh_contains_shell_metas (value_cell (var)))
1004 t = sh_single_quote (value_cell (var));
1009 printf ("%s", value_cell (var));
1012 /* Print the function cell of VAR, a shell variable. Do not
1013 print the name, nor leading/trailing newline. */
1015 print_var_function (var)
1020 if (function_p (var) && var_isset (var))
1022 x = named_function_string ((char *)NULL, function_cell(var), FUNC_MULTILINE|FUNC_EXTERNAL);
1027 /* **************************************************************** */
1029 /* Dynamic Variables */
1031 /* **************************************************************** */
1033 /* DYNAMIC VARIABLES
1035 These are variables whose values are generated anew each time they are
1036 referenced. These are implemented using a pair of function pointers
1037 in the struct variable: assign_func, which is called from bind_variable
1038 and, if arrays are compiled into the shell, some of the functions in
1039 arrayfunc.c, and dynamic_value, which is called from find_variable.
1041 assign_func is called from bind_variable_internal, if
1042 bind_variable_internal discovers that the variable being assigned to
1043 has such a function. The function is called as
1044 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value, ind)
1045 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
1046 is usually ENTRY (self). IND is an index for an array variable, and
1049 dynamic_value is called from find_variable_internal to return a `new'
1050 value for the specified dynamic varible. If this function is NULL,
1051 the variable is treated as a `normal' shell variable. If it is not,
1052 however, then this function is called like this:
1053 tempvar = (*(var->dynamic_value)) (var);
1055 Sometimes `tempvar' will replace the value of `var'. Other times, the
1056 shell will simply use the string value. Pretty object-oriented, huh?
1058 Be warned, though: if you `unset' a special variable, it loses its
1059 special meaning, even if you subsequently set it.
1061 The special assignment code would probably have been better put in
1062 subst.c: do_assignment_internal, in the same style as
1063 stupidly_hack_special_variables, but I wanted the changes as
1064 localized as possible. */
1066 #define INIT_DYNAMIC_VAR(var, val, gfunc, afunc) \
1069 v = bind_variable (var, (val), 0); \
1070 v->dynamic_value = gfunc; \
1071 v->assign_func = afunc; \
1075 #define INIT_DYNAMIC_ARRAY_VAR(var, gfunc, afunc) \
1078 v = make_new_array_variable (var); \
1079 v->dynamic_value = gfunc; \
1080 v->assign_func = afunc; \
1084 #define INIT_DYNAMIC_ASSOC_VAR(var, gfunc, afunc) \
1087 v = make_new_assoc_variable (var); \
1088 v->dynamic_value = gfunc; \
1089 v->assign_func = afunc; \
1094 null_assign (self, value, unused, key)
1103 #if defined (ARRAY_VARS)
1105 null_array_assign (self, value, ind, key)
1115 /* Degenerate `dynamic_value' function; just returns what's passed without
1124 #if defined (ARRAY_VARS)
1125 /* A generic dynamic array variable initializer. Intialize array variable
1126 NAME with dynamic value function GETFUNC and assignment function SETFUNC. */
1128 init_dynamic_array_var (name, getfunc, setfunc, attrs)
1130 sh_var_value_func_t *getfunc;
1131 sh_var_assign_func_t *setfunc;
1136 v = find_variable (name);
1139 INIT_DYNAMIC_ARRAY_VAR (name, getfunc, setfunc);
1141 VSETATTR (v, attrs);
1146 init_dynamic_assoc_var (name, getfunc, setfunc, attrs)
1148 sh_var_value_func_t *getfunc;
1149 sh_var_assign_func_t *setfunc;
1154 v = find_variable (name);
1157 INIT_DYNAMIC_ASSOC_VAR (name, getfunc, setfunc);
1159 VSETATTR (v, attrs);
1164 /* The value of $SECONDS. This is the number of seconds since shell
1165 invocation, or, the number of seconds since the last assignment + the
1166 value of the last assignment. */
1167 static intmax_t seconds_value_assigned;
1170 assign_seconds (self, value, unused, key)
1176 if (legal_number (value, &seconds_value_assigned) == 0)
1177 seconds_value_assigned = 0;
1178 shell_start_time = NOW;
1186 time_t time_since_start;
1189 time_since_start = NOW - shell_start_time;
1190 p = itos(seconds_value_assigned + time_since_start);
1192 FREE (value_cell (var));
1194 VSETATTR (var, att_integer);
1195 var_setvalue (var, p);
1204 v = find_variable ("SECONDS");
1207 if (legal_number (value_cell(v), &seconds_value_assigned) == 0)
1208 seconds_value_assigned = 0;
1210 INIT_DYNAMIC_VAR ("SECONDS", (v ? value_cell (v) : (char *)NULL), get_seconds, assign_seconds);
1214 /* The random number seed. You can change this by setting RANDOM. */
1215 static unsigned long rseed = 1;
1216 static int last_random_value;
1217 static int seeded_subshell = 0;
1219 /* A linear congruential random number generator based on the example
1220 one in the ANSI C standard. This one isn't very good, but a more
1221 complicated one is overkill. */
1223 /* Returns a pseudo-random number between 0 and 32767. */
1228 rseed = rseed * 1103515245 + 12345;
1229 return ((unsigned int)((rseed >> 16) & 32767)); /* was % 32768 */
1231 /* From "Random number generators: good ones are hard to find",
1232 Park and Miller, Communications of the ACM, vol. 31, no. 10,
1233 October 1988, p. 1195. filtered through FreeBSD */
1240 rseed = 16807 * l - 2836 * h;
1243 rseed += 0x7fffffff;
1245 return ((unsigned int)(rseed & 32767)); /* was % 32768 */
1249 /* Set the random number generator seed to SEED. */
1255 last_random_value = 0;
1263 gettimeofday (&tv, NULL);
1264 sbrand (tv.tv_sec ^ tv.tv_usec ^ getpid ());
1268 assign_random (self, value, unused, key)
1274 sbrand (strtoul (value, (char **)NULL, 10));
1275 if (subshell_environment)
1276 seeded_subshell = getpid ();
1281 get_random_number ()
1285 /* Reset for command and process substitution. */
1287 if (subshell_environment && seeded_subshell != pid)
1290 seeded_subshell = pid;
1295 while (rv == last_random_value);
1306 rv = get_random_number ();
1307 last_random_value = rv;
1310 FREE (value_cell (var));
1312 VSETATTR (var, att_integer);
1313 var_setvalue (var, p);
1318 assign_lineno (var, value, unused, key)
1326 if (value == 0 || *value == '\0' || legal_number (value, &new_value) == 0)
1328 line_number = new_value;
1332 /* Function which returns the current line number. */
1340 ln = executing_line_number ();
1342 FREE (value_cell (var));
1343 var_setvalue (var, p);
1348 assign_subshell (var, value, unused, key)
1356 if (value == 0 || *value == '\0' || legal_number (value, &new_value) == 0)
1358 subshell_level = new_value;
1368 p = itos (subshell_level);
1369 FREE (value_cell (var));
1370 var_setvalue (var, p);
1384 FREE (value_cell (var));
1385 VSETATTR (var, att_integer|att_readonly);
1386 var_setvalue (var, p);
1391 get_bash_command (var)
1396 if (the_printed_command_except_trap)
1397 p = savestring (the_printed_command_except_trap);
1400 p = (char *)xmalloc (1);
1403 FREE (value_cell (var));
1404 var_setvalue (var, p);
1408 #if defined (HISTORY)
1415 p = itos (history_number ());
1416 FREE (value_cell (var));
1417 var_setvalue (var, p);
1422 #if defined (READLINE)
1423 /* When this function returns, VAR->value points to malloced memory. */
1425 get_comp_wordbreaks (var)
1428 /* If we don't have anything yet, assign a default value. */
1429 if (rl_completer_word_break_characters == 0 && bash_readline_initialized == 0)
1430 enable_hostname_completion (perform_hostname_completion);
1432 FREE (value_cell (var));
1433 var_setvalue (var, savestring (rl_completer_word_break_characters));
1438 /* When this function returns, rl_completer_word_break_characters points to
1441 assign_comp_wordbreaks (self, value, unused, key)
1447 if (rl_completer_word_break_characters &&
1448 rl_completer_word_break_characters != rl_basic_word_break_characters)
1449 free (rl_completer_word_break_characters);
1451 rl_completer_word_break_characters = savestring (value);
1454 #endif /* READLINE */
1456 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1458 assign_dirstack (self, value, ind, key)
1464 set_dirstack_element (ind, 1, value);
1475 l = get_directory_stack (0);
1476 a = array_from_word_list (l);
1477 array_dispose (array_cell (self));
1479 var_setarray (self, a);
1482 #endif /* PUSHD AND POPD && ARRAY_VARS */
1484 #if defined (ARRAY_VARS)
1485 /* We don't want to initialize the group set with a call to getgroups()
1486 unless we're asked to, but we only want to do it once. */
1494 static char **group_set = (char **)NULL;
1498 group_set = get_group_list (&ng);
1499 a = array_cell (self);
1500 for (i = 0; i < ng; i++)
1501 array_insert (a, i, group_set[i]);
1507 build_hashcmd (self)
1513 BUCKET_CONTENTS *item;
1515 h = assoc_cell (self);
1519 if (hashed_filenames == 0 || HASH_ENTRIES (hashed_filenames) == 0)
1521 var_setvalue (self, (char *)NULL);
1525 h = assoc_create (hashed_filenames->nbuckets);
1526 for (i = 0; i < hashed_filenames->nbuckets; i++)
1528 for (item = hash_items (i, hashed_filenames); item; item = item->next)
1530 k = savestring (item->key);
1531 v = pathdata(item)->path;
1532 assoc_insert (h, k, v);
1536 var_setvalue (self, (char *)h);
1544 build_hashcmd (self);
1549 assign_hashcmd (self, value, ind, key)
1555 phash_insert (key, value, 0, 0);
1556 return (build_hashcmd (self));
1560 build_aliasvar (self)
1566 BUCKET_CONTENTS *item;
1568 h = assoc_cell (self);
1572 if (aliases == 0 || HASH_ENTRIES (aliases) == 0)
1574 var_setvalue (self, (char *)NULL);
1578 h = assoc_create (aliases->nbuckets);
1579 for (i = 0; i < aliases->nbuckets; i++)
1581 for (item = hash_items (i, aliases); item; item = item->next)
1583 k = savestring (item->key);
1584 v = ((alias_t *)(item->data))->value;
1585 assoc_insert (h, k, v);
1589 var_setvalue (self, (char *)h);
1597 build_aliasvar (self);
1602 assign_aliasvar (self, value, ind, key)
1608 add_alias (key, value);
1609 return (build_aliasvar (self));
1611 #endif /* ARRAY_VARS */
1613 /* If ARRAY_VARS is not defined, this just returns the name of any
1614 currently-executing function. If we have arrays, it's a call stack. */
1619 #if ! defined (ARRAY_VARS)
1621 if (variable_context && this_shell_function)
1623 FREE (value_cell (self));
1624 t = savestring (this_shell_function->name);
1625 var_setvalue (self, t);
1632 make_funcname_visible (on_or_off)
1637 v = find_variable ("FUNCNAME");
1638 if (v == 0 || v->dynamic_value == 0)
1642 VUNSETATTR (v, att_invisible);
1644 VSETATTR (v, att_invisible);
1648 init_funcname_var ()
1652 v = find_variable ("FUNCNAME");
1655 #if defined (ARRAY_VARS)
1656 INIT_DYNAMIC_ARRAY_VAR ("FUNCNAME", get_funcname, null_array_assign);
1658 INIT_DYNAMIC_VAR ("FUNCNAME", (char *)NULL, get_funcname, null_assign);
1660 VSETATTR (v, att_invisible|att_noassign);
1665 initialize_dynamic_variables ()
1669 v = init_seconds_var ();
1671 INIT_DYNAMIC_VAR ("BASH_COMMAND", (char *)NULL, get_bash_command, (sh_var_assign_func_t *)NULL);
1672 INIT_DYNAMIC_VAR ("BASH_SUBSHELL", (char *)NULL, get_subshell, assign_subshell);
1674 INIT_DYNAMIC_VAR ("RANDOM", (char *)NULL, get_random, assign_random);
1675 VSETATTR (v, att_integer);
1676 INIT_DYNAMIC_VAR ("LINENO", (char *)NULL, get_lineno, assign_lineno);
1677 VSETATTR (v, att_integer);
1679 INIT_DYNAMIC_VAR ("BASHPID", (char *)NULL, get_bashpid, null_assign);
1680 VSETATTR (v, att_integer|att_readonly);
1682 #if defined (HISTORY)
1683 INIT_DYNAMIC_VAR ("HISTCMD", (char *)NULL, get_histcmd, (sh_var_assign_func_t *)NULL);
1684 VSETATTR (v, att_integer);
1687 #if defined (READLINE)
1688 INIT_DYNAMIC_VAR ("COMP_WORDBREAKS", (char *)NULL, get_comp_wordbreaks, assign_comp_wordbreaks);
1691 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1692 v = init_dynamic_array_var ("DIRSTACK", get_dirstack, assign_dirstack, 0);
1693 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1695 #if defined (ARRAY_VARS)
1696 v = init_dynamic_array_var ("GROUPS", get_groupset, null_array_assign, att_noassign);
1698 # if defined (DEBUGGER)
1699 v = init_dynamic_array_var ("BASH_ARGC", get_self, null_array_assign, att_noassign|att_nounset);
1700 v = init_dynamic_array_var ("BASH_ARGV", get_self, null_array_assign, att_noassign|att_nounset);
1701 # endif /* DEBUGGER */
1702 v = init_dynamic_array_var ("BASH_SOURCE", get_self, null_array_assign, att_noassign|att_nounset);
1703 v = init_dynamic_array_var ("BASH_LINENO", get_self, null_array_assign, att_noassign|att_nounset);
1705 v = init_dynamic_assoc_var ("BASH_CMDS", get_hashcmd, assign_hashcmd, att_nofree);
1706 v = init_dynamic_assoc_var ("BASH_ALIASES", get_aliasvar, assign_aliasvar, att_nofree);
1709 v = init_funcname_var ();
1712 /* **************************************************************** */
1714 /* Retrieving variables and values */
1716 /* **************************************************************** */
1718 /* How to get a pointer to the shell variable or function named NAME.
1719 HASHED_VARS is a pointer to the hash table containing the list
1720 of interest (either variables or functions). */
1723 hash_lookup (name, hashed_vars)
1725 HASH_TABLE *hashed_vars;
1727 BUCKET_CONTENTS *bucket;
1729 bucket = hash_search (name, hashed_vars, 0);
1730 return (bucket ? (SHELL_VAR *)bucket->data : (SHELL_VAR *)NULL);
1734 var_lookup (name, vcontext)
1736 VAR_CONTEXT *vcontext;
1741 v = (SHELL_VAR *)NULL;
1742 for (vc = vcontext; vc; vc = vc->down)
1743 if (v = hash_lookup (name, vc->table))
1749 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
1750 then also search the temporarily built list of exported variables.
1751 The lookup order is:
1753 shell_variables list
1757 find_variable_internal (name, force_tempenv)
1764 var = (SHELL_VAR *)NULL;
1766 /* If explicitly requested, first look in the temporary environment for
1767 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
1768 to get the `exported' value of $foo. This happens if we are executing
1769 a function or builtin, or if we are looking up a variable in a
1770 "subshell environment". */
1771 search_tempenv = force_tempenv || (expanding_redir == 0 && subshell_environment);
1773 if (search_tempenv && temporary_env)
1774 var = hash_lookup (name, temporary_env);
1777 var = var_lookup (name, shell_variables);
1780 return ((SHELL_VAR *)NULL);
1782 return (var->dynamic_value ? (*(var->dynamic_value)) (var) : var);
1785 /* Look up the variable entry named NAME. Returns the entry or NULL. */
1787 find_variable (name)
1790 return (find_variable_internal (name, (expanding_redir == 0 && (assigning_in_environment || executing_builtin))));
1793 /* Look up the function entry whose name matches STRING.
1794 Returns the entry or NULL. */
1796 find_function (name)
1799 return (hash_lookup (name, shell_functions));
1802 /* Find the function definition for the shell function named NAME. Returns
1803 the entry or NULL. */
1805 find_function_def (name)
1808 #if defined (DEBUGGER)
1809 return ((FUNCTION_DEF *)hash_lookup (name, shell_function_defs));
1811 return ((FUNCTION_DEF *)0);
1815 /* Return the value of VAR. VAR is assumed to have been the result of a
1816 lookup without any subscript, if arrays are compiled into the shell. */
1818 get_variable_value (var)
1822 return ((char *)NULL);
1823 #if defined (ARRAY_VARS)
1824 else if (array_p (var))
1825 return (array_reference (array_cell (var), 0));
1826 else if (assoc_p (var))
1827 return (assoc_reference (assoc_cell (var), "0"));
1830 return (value_cell (var));
1833 /* Return the string value of a variable. Return NULL if the variable
1834 doesn't exist. Don't cons a new string. This is a potential memory
1835 leak if the variable is found in the temporary environment. Since
1836 functions and variables have separate name spaces, returns NULL if
1837 var_name is a shell function only. */
1839 get_string_value (var_name)
1840 const char *var_name;
1844 var = find_variable (var_name);
1845 return ((var) ? get_variable_value (var) : (char *)NULL);
1848 /* This is present for use by the tilde and readline libraries. */
1850 sh_get_env_value (v)
1853 return get_string_value (v);
1856 /* **************************************************************** */
1858 /* Creating and setting variables */
1860 /* **************************************************************** */
1862 /* Set NAME to VALUE if NAME has no value. */
1864 set_if_not (name, value)
1869 if (shell_variables == 0)
1870 create_variable_tables ();
1872 v = find_variable (name);
1874 v = bind_variable_internal (name, value, global_variables->table, HASH_NOSRCH, 0);
1878 /* Create a local variable referenced by NAME. */
1880 make_local_variable (name)
1883 SHELL_VAR *new_var, *old_var;
1888 /* local foo; local foo; is a no-op. */
1889 old_var = find_variable (name);
1890 if (old_var && local_p (old_var) && old_var->context == variable_context)
1892 VUNSETATTR (old_var, att_invisible);
1896 was_tmpvar = old_var && tempvar_p (old_var);
1898 tmp_value = value_cell (old_var);
1900 for (vc = shell_variables; vc; vc = vc->down)
1901 if (vc_isfuncenv (vc) && vc->scope == variable_context)
1906 internal_error (_("make_local_variable: no function context at current scope"));
1907 return ((SHELL_VAR *)NULL);
1909 else if (vc->table == 0)
1910 vc->table = hash_create (TEMPENV_HASH_BUCKETS);
1912 /* Since this is called only from the local/declare/typeset code, we can
1913 call builtin_error here without worry (of course, it will also work
1914 for anything that sets this_command_name). Variables with the `noassign'
1915 attribute may not be made local. The test against old_var's context
1916 level is to disallow local copies of readonly global variables (since I
1917 believe that this could be a security hole). Readonly copies of calling
1918 function local variables are OK. */
1919 if (old_var && (noassign_p (old_var) ||
1920 (readonly_p (old_var) && old_var->context == 0)))
1922 if (readonly_p (old_var))
1924 return ((SHELL_VAR *)NULL);
1928 new_var = make_new_variable (name, vc->table);
1931 new_var = make_new_variable (name, vc->table);
1933 /* If we found this variable in one of the temporary environments,
1934 inherit its value. Watch to see if this causes problems with
1935 things like `x=4 local x'. */
1937 var_setvalue (new_var, savestring (tmp_value));
1939 new_var->attributes = exported_p (old_var) ? att_exported : 0;
1942 vc->flags |= VC_HASLOCAL;
1944 new_var->context = variable_context;
1945 VSETATTR (new_var, att_local);
1953 /* Create a new shell variable with name NAME. */
1955 new_shell_variable (name)
1960 entry = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1962 entry->name = savestring (name);
1963 var_setvalue (entry, (char *)NULL);
1964 CLEAR_EXPORTSTR (entry);
1966 entry->dynamic_value = (sh_var_value_func_t *)NULL;
1967 entry->assign_func = (sh_var_assign_func_t *)NULL;
1969 entry->attributes = 0;
1971 /* Always assume variables are to be made at toplevel!
1972 make_local_variable has the responsibilty of changing the
1973 variable context. */
1979 /* Create a new shell variable with name NAME and add it to the hash table
1982 make_new_variable (name, table)
1987 BUCKET_CONTENTS *elt;
1989 entry = new_shell_variable (name);
1991 /* Make sure we have a shell_variables hash table to add to. */
1992 if (shell_variables == 0)
1993 create_variable_tables ();
1995 elt = hash_insert (savestring (name), table, HASH_NOSRCH);
1996 elt->data = (PTR_T)entry;
2001 #if defined (ARRAY_VARS)
2003 make_new_array_variable (name)
2009 entry = make_new_variable (name, global_variables->table);
2010 array = array_create ();
2012 var_setarray (entry, array);
2013 VSETATTR (entry, att_array);
2018 make_local_array_variable (name)
2024 var = make_local_variable (name);
2025 if (var == 0 || array_p (var))
2028 array = array_create ();
2030 dispose_variable_value (var);
2031 var_setarray (var, array);
2032 VSETATTR (var, att_array);
2037 make_new_assoc_variable (name)
2043 entry = make_new_variable (name, global_variables->table);
2044 hash = assoc_create (0);
2046 var_setassoc (entry, hash);
2047 VSETATTR (entry, att_assoc);
2052 make_local_assoc_variable (name)
2058 var = make_local_variable (name);
2059 if (var == 0 || assoc_p (var))
2062 dispose_variable_value (var);
2063 hash = assoc_create (0);
2065 var_setassoc (var, hash);
2066 VSETATTR (var, att_assoc);
2072 make_variable_value (var, value, flags)
2077 char *retval, *oval;
2078 intmax_t lval, rval;
2079 int expok, olen, op;
2081 /* If this variable has had its type set to integer (via `declare -i'),
2082 then do expression evaluation on it and store the result. The
2083 functions in expr.c (evalexp()) and bind_int_variable() are responsible
2084 for turning off the integer flag if they don't want further
2086 if (integer_p (var))
2088 if (flags & ASS_APPEND)
2090 oval = value_cell (var);
2091 lval = evalexp (oval, &expok); /* ksh93 seems to do this */
2094 top_level_cleanup ();
2095 jump_to_top_level (DISCARD);
2098 rval = evalexp (value, &expok);
2101 top_level_cleanup ();
2102 jump_to_top_level (DISCARD);
2104 if (flags & ASS_APPEND)
2106 retval = itos (rval);
2108 #if defined (CASEMOD_ATTRS)
2109 else if (capcase_p (var) || uppercase_p (var) || lowercase_p (var))
2111 if (flags & ASS_APPEND)
2113 oval = get_variable_value (var);
2114 if (oval == 0) /* paranoia */
2116 olen = STRLEN (oval);
2117 retval = (char *)xmalloc (olen + (value ? STRLEN (value) : 0) + 1);
2118 strcpy (retval, oval);
2120 strcpy (retval+olen, value);
2123 retval = savestring (value);
2126 retval = (char *)xmalloc (1);
2129 op = capcase_p (var) ? CASE_CAPITALIZE
2130 : (uppercase_p (var) ? CASE_UPPER : CASE_LOWER);
2131 oval = sh_modcase (retval, (char *)0, op);
2135 #endif /* CASEMOD_ATTRS */
2138 if (flags & ASS_APPEND)
2140 oval = get_variable_value (var);
2141 if (oval == 0) /* paranoia */
2143 olen = STRLEN (oval);
2144 retval = (char *)xmalloc (olen + (value ? STRLEN (value) : 0) + 1);
2145 strcpy (retval, oval);
2147 strcpy (retval+olen, value);
2150 retval = savestring (value);
2153 retval = (char *)xmalloc (1);
2158 retval = (char *)NULL;
2163 /* Bind a variable NAME to VALUE in the HASH_TABLE TABLE, which may be the
2164 temporary environment (but usually is not). */
2166 bind_variable_internal (name, value, table, hflags, aflags)
2175 entry = (hflags & HASH_NOSRCH) ? (SHELL_VAR *)NULL : hash_lookup (name, table);
2179 entry = make_new_variable (name, table);
2180 var_setvalue (entry, make_variable_value (entry, value, 0)); /* XXX */
2182 else if (entry->assign_func) /* array vars have assign functions now */
2184 INVALIDATE_EXPORTSTR (entry);
2185 newval = (aflags & ASS_APPEND) ? make_variable_value (entry, value, aflags) : value;
2186 entry = (*(entry->assign_func)) (entry, newval, -1, 0);
2187 if (newval != value)
2193 if (readonly_p (entry) || noassign_p (entry))
2195 if (readonly_p (entry))
2196 err_readonly (name);
2200 /* Variables which are bound are visible. */
2201 VUNSETATTR (entry, att_invisible);
2203 newval = make_variable_value (entry, value, aflags); /* XXX */
2205 /* Invalidate any cached export string */
2206 INVALIDATE_EXPORTSTR (entry);
2208 #if defined (ARRAY_VARS)
2209 /* XXX -- this bears looking at again -- XXX */
2210 /* If an existing array variable x is being assigned to with x=b or
2211 `read x' or something of that nature, silently convert it to
2212 x[0]=b or `read x[0]'. */
2213 if (array_p (entry))
2215 array_insert (array_cell (entry), 0, newval);
2218 else if (assoc_p (entry))
2220 assoc_insert (assoc_cell (entry), savestring ("0"), newval);
2226 FREE (value_cell (entry));
2227 var_setvalue (entry, newval);
2231 if (mark_modified_vars)
2232 VSETATTR (entry, att_exported);
2234 if (exported_p (entry))
2235 array_needs_making = 1;
2240 /* Bind a variable NAME to VALUE. This conses up the name
2241 and value strings. If we have a temporary environment, we bind there
2242 first, then we bind into shell_variables. */
2245 bind_variable (name, value, flags)
2253 if (shell_variables == 0)
2254 create_variable_tables ();
2256 /* If we have a temporary environment, look there first for the variable,
2257 and, if found, modify the value there before modifying it in the
2258 shell_variables table. This allows sourced scripts to modify values
2259 given to them in a temporary environment while modifying the variable
2260 value that the caller sees. */
2262 bind_tempenv_variable (name, value);
2264 /* XXX -- handle local variables here. */
2265 for (vc = shell_variables; vc; vc = vc->down)
2267 if (vc_isfuncenv (vc) || vc_isbltnenv (vc))
2269 v = hash_lookup (name, vc->table);
2271 return (bind_variable_internal (name, value, vc->table, 0, flags));
2274 return (bind_variable_internal (name, value, global_variables->table, 0, flags));
2277 /* Make VAR, a simple shell variable, have value VALUE. Once assigned a
2278 value, variables are no longer invisible. This is a duplicate of part
2279 of the internals of bind_variable. If the variable is exported, or
2280 all modified variables should be exported, mark the variable for export
2281 and note that the export environment needs to be recreated. */
2283 bind_variable_value (var, value, aflags)
2290 VUNSETATTR (var, att_invisible);
2292 if (var->assign_func)
2294 /* If we're appending, we need the old value, so use
2295 make_variable_value */
2296 t = (aflags & ASS_APPEND) ? make_variable_value (var, value, aflags) : value;
2297 (*(var->assign_func)) (var, t, -1, 0);
2298 if (t != value && t)
2303 t = make_variable_value (var, value, aflags);
2304 FREE (value_cell (var));
2305 var_setvalue (var, t);
2308 INVALIDATE_EXPORTSTR (var);
2310 if (mark_modified_vars)
2311 VSETATTR (var, att_exported);
2313 if (exported_p (var))
2314 array_needs_making = 1;
2319 /* Bind/create a shell variable with the name LHS to the RHS.
2320 This creates or modifies a variable such that it is an integer.
2322 This used to be in expr.c, but it is here so that all of the
2323 variable binding stuff is localized. Since we don't want any
2324 recursive evaluation from bind_variable() (possible without this code,
2325 since bind_variable() calls the evaluator for variables with the integer
2326 attribute set), we temporarily turn off the integer attribute for each
2327 variable we set here, then turn it back on after binding as necessary. */
2330 bind_int_variable (lhs, rhs)
2333 register SHELL_VAR *v;
2337 #if defined (ARRAY_VARS)
2338 if (valid_array_reference (lhs))
2341 v = array_variable_part (lhs, (char **)0, (int *)0);
2345 v = find_variable (lhs);
2349 isint = integer_p (v);
2350 VUNSETATTR (v, att_integer);
2353 #if defined (ARRAY_VARS)
2355 v = assign_array_element (lhs, rhs, 0);
2358 v = bind_variable (lhs, rhs, 0);
2361 VSETATTR (v, att_integer);
2367 bind_var_to_int (var, val)
2371 char ibuf[INT_STRLEN_BOUND (intmax_t) + 1], *p;
2373 p = fmtulong (val, 10, ibuf, sizeof (ibuf), 0);
2374 return (bind_int_variable (var, p));
2377 /* Do a function binding to a variable. You pass the name and
2378 the command to bind to. This conses the name and command. */
2380 bind_function (name, value)
2386 entry = find_function (name);
2389 BUCKET_CONTENTS *elt;
2391 elt = hash_insert (savestring (name), shell_functions, HASH_NOSRCH);
2392 entry = new_shell_variable (name);
2393 elt->data = (PTR_T)entry;
2396 INVALIDATE_EXPORTSTR (entry);
2398 if (var_isset (entry))
2399 dispose_command (function_cell (entry));
2402 var_setfunc (entry, copy_command (value));
2404 var_setfunc (entry, 0);
2406 VSETATTR (entry, att_function);
2408 if (mark_modified_vars)
2409 VSETATTR (entry, att_exported);
2411 VUNSETATTR (entry, att_invisible); /* Just to be sure */
2413 if (exported_p (entry))
2414 array_needs_making = 1;
2416 #if defined (PROGRAMMABLE_COMPLETION)
2417 set_itemlist_dirty (&it_functions);
2423 #if defined (DEBUGGER)
2424 /* Bind a function definition, which includes source file and line number
2425 information in addition to the command, into the FUNCTION_DEF hash table.*/
2427 bind_function_def (name, value)
2429 FUNCTION_DEF *value;
2431 FUNCTION_DEF *entry;
2432 BUCKET_CONTENTS *elt;
2435 entry = find_function_def (name);
2438 dispose_function_def_contents (entry);
2439 entry = copy_function_def_contents (value, entry);
2443 cmd = value->command;
2445 entry = copy_function_def (value);
2446 value->command = cmd;
2448 elt = hash_insert (savestring (name), shell_function_defs, HASH_NOSRCH);
2449 elt->data = (PTR_T *)entry;
2452 #endif /* DEBUGGER */
2454 /* Add STRING, which is of the form foo=bar, to the temporary environment
2455 HASH_TABLE (temporary_env). The functions in execute_cmd.c are
2456 responsible for moving the main temporary env to one of the other
2457 temporary environments. The expansion code in subst.c calls this. */
2459 assign_in_env (word)
2463 char *name, *temp, *value;
2467 string = word->word;
2469 offset = assignment (string, 0);
2470 name = savestring (string);
2471 value = (char *)NULL;
2473 if (name[offset] == '=')
2477 /* ignore the `+' when assigning temporary environment */
2478 if (name[offset - 1] == '+')
2479 name[offset - 1] = '\0';
2481 var = find_variable (name);
2482 if (var && (readonly_p (var) || noassign_p (var)))
2484 if (readonly_p (var))
2485 err_readonly (name);
2490 temp = name + offset + 1;
2491 value = expand_assignment_string_to_string (temp, 0);
2494 if (temporary_env == 0)
2495 temporary_env = hash_create (TEMPENV_HASH_BUCKETS);
2497 var = hash_lookup (name, temporary_env);
2499 var = make_new_variable (name, temporary_env);
2501 FREE (value_cell (var));
2505 value = (char *)xmalloc (1); /* like do_assignment_internal */
2509 var_setvalue (var, value);
2510 var->attributes |= (att_exported|att_tempvar);
2511 var->context = variable_context; /* XXX */
2513 INVALIDATE_EXPORTSTR (var);
2514 var->exportstr = mk_env_string (name, value);
2516 array_needs_making = 1;
2521 if (echo_command_at_execute)
2522 /* The Korn shell prints the `+ ' in front of assignment statements,
2524 xtrace_print_assignment (name, value, 0, 1);
2530 /* **************************************************************** */
2532 /* Copying variables */
2534 /* **************************************************************** */
2536 #ifdef INCLUDE_UNUSED
2537 /* Copy VAR to a new data structure and return that structure. */
2542 SHELL_VAR *copy = (SHELL_VAR *)NULL;
2546 copy = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
2548 copy->attributes = var->attributes;
2549 copy->name = savestring (var->name);
2551 if (function_p (var))
2552 var_setfunc (copy, copy_command (function_cell (var)));
2553 #if defined (ARRAY_VARS)
2554 else if (array_p (var))
2555 var_setarray (copy, array_copy (array_cell (var)));
2556 else if (assoc_p (var))
2557 var_setassoc (copy, assoc_copy (assoc_cell (var)));
2559 else if (value_cell (var))
2560 var_setvalue (copy, savestring (value_cell (var)));
2562 var_setvalue (copy, (char *)NULL);
2564 copy->dynamic_value = var->dynamic_value;
2565 copy->assign_func = var->assign_func;
2567 copy->exportstr = COPY_EXPORTSTR (var);
2569 copy->context = var->context;
2575 /* **************************************************************** */
2577 /* Deleting and unsetting variables */
2579 /* **************************************************************** */
2581 /* Dispose of the information attached to VAR. */
2583 dispose_variable_value (var)
2586 if (function_p (var))
2587 dispose_command (function_cell (var));
2588 #if defined (ARRAY_VARS)
2589 else if (array_p (var))
2590 array_dispose (array_cell (var));
2591 else if (assoc_p (var))
2592 assoc_dispose (assoc_cell (var));
2595 FREE (value_cell (var));
2599 dispose_variable (var)
2605 if (nofree_p (var) == 0)
2606 dispose_variable_value (var);
2608 FREE_EXPORTSTR (var);
2612 if (exported_p (var))
2613 array_needs_making = 1;
2618 /* Unset the shell variable referenced by NAME. */
2620 unbind_variable (name)
2623 return makunbound (name, shell_variables);
2626 /* Unset the shell function named NAME. */
2631 BUCKET_CONTENTS *elt;
2634 elt = hash_remove (name, shell_functions, 0);
2639 #if defined (PROGRAMMABLE_COMPLETION)
2640 set_itemlist_dirty (&it_functions);
2643 func = (SHELL_VAR *)elt->data;
2646 if (exported_p (func))
2647 array_needs_making++;
2648 dispose_variable (func);
2657 #if defined (DEBUGGER)
2659 unbind_function_def (name)
2662 BUCKET_CONTENTS *elt;
2663 FUNCTION_DEF *funcdef;
2665 elt = hash_remove (name, shell_function_defs, 0);
2670 funcdef = (FUNCTION_DEF *)elt->data;
2672 dispose_function_def (funcdef);
2679 #endif /* DEBUGGER */
2681 /* Make the variable associated with NAME go away. HASH_LIST is the
2682 hash table from which this variable should be deleted (either
2683 shell_variables or shell_functions).
2684 Returns non-zero if the variable couldn't be found. */
2686 makunbound (name, vc)
2690 BUCKET_CONTENTS *elt, *new_elt;
2695 for (elt = (BUCKET_CONTENTS *)NULL, v = vc; v; v = v->down)
2696 if (elt = hash_remove (name, v->table, 0))
2702 old_var = (SHELL_VAR *)elt->data;
2704 if (old_var && exported_p (old_var))
2705 array_needs_making++;
2707 /* If we're unsetting a local variable and we're still executing inside
2708 the function, just mark the variable as invisible. The function
2709 eventually called by pop_var_context() will clean it up later. This
2710 must be done so that if the variable is subsequently assigned a new
2711 value inside the function, the `local' attribute is still present.
2712 We also need to add it back into the correct hash table. */
2713 if (old_var && local_p (old_var) && variable_context == old_var->context)
2715 if (nofree_p (old_var))
2716 var_setvalue (old_var, (char *)NULL);
2717 #if defined (ARRAY_VARS)
2718 else if (array_p (old_var))
2719 array_dispose (array_cell (old_var));
2720 else if (assoc_p (old_var))
2721 assoc_dispose (assoc_cell (old_var));
2724 FREE (value_cell (old_var));
2725 /* Reset the attributes. Preserve the export attribute if the variable
2726 came from a temporary environment. Make sure it stays local, and
2727 make it invisible. */
2728 old_var->attributes = (exported_p (old_var) && tempvar_p (old_var)) ? att_exported : 0;
2729 VSETATTR (old_var, att_local);
2730 VSETATTR (old_var, att_invisible);
2731 var_setvalue (old_var, (char *)NULL);
2732 INVALIDATE_EXPORTSTR (old_var);
2734 new_elt = hash_insert (savestring (old_var->name), v->table, 0);
2735 new_elt->data = (PTR_T)old_var;
2736 stupidly_hack_special_variables (old_var->name);
2743 /* Have to save a copy of name here, because it might refer to
2744 old_var->name. If so, stupidly_hack_special_variables will
2745 reference freed memory. */
2746 t = savestring (name);
2751 dispose_variable (old_var);
2752 stupidly_hack_special_variables (t);
2758 /* Get rid of all of the variables in the current context. */
2760 kill_all_local_variables ()
2764 for (vc = shell_variables; vc; vc = vc->down)
2765 if (vc_isfuncenv (vc) && vc->scope == variable_context)
2770 if (vc->table && vc_haslocals (vc))
2772 delete_all_variables (vc->table);
2773 hash_dispose (vc->table);
2775 vc->table = (HASH_TABLE *)NULL;
2779 free_variable_hash_data (data)
2784 var = (SHELL_VAR *)data;
2785 dispose_variable (var);
2788 /* Delete the entire contents of the hash table. */
2790 delete_all_variables (hashed_vars)
2791 HASH_TABLE *hashed_vars;
2793 hash_flush (hashed_vars, free_variable_hash_data);
2796 /* **************************************************************** */
2798 /* Setting variable attributes */
2800 /* **************************************************************** */
2802 #define FIND_OR_MAKE_VARIABLE(name, entry) \
2805 entry = find_variable (name); \
2808 entry = bind_variable (name, "", 0); \
2809 if (!no_invisible_vars) entry->attributes |= att_invisible; \
2814 /* Make the variable associated with NAME be readonly.
2815 If NAME does not exist yet, create it. */
2817 set_var_read_only (name)
2822 FIND_OR_MAKE_VARIABLE (name, entry);
2823 VSETATTR (entry, att_readonly);
2826 #ifdef INCLUDE_UNUSED
2827 /* Make the function associated with NAME be readonly.
2828 If NAME does not exist, we just punt, like auto_export code below. */
2830 set_func_read_only (name)
2835 entry = find_function (name);
2837 VSETATTR (entry, att_readonly);
2840 /* Make the variable associated with NAME be auto-exported.
2841 If NAME does not exist yet, create it. */
2843 set_var_auto_export (name)
2848 FIND_OR_MAKE_VARIABLE (name, entry);
2849 set_auto_export (entry);
2852 /* Make the function associated with NAME be auto-exported. */
2854 set_func_auto_export (name)
2859 entry = find_function (name);
2861 set_auto_export (entry);
2865 /* **************************************************************** */
2867 /* Creating lists of variables */
2869 /* **************************************************************** */
2872 vlist_alloc (nentries)
2877 vlist = (VARLIST *)xmalloc (sizeof (VARLIST));
2878 vlist->list = (SHELL_VAR **)xmalloc ((nentries + 1) * sizeof (SHELL_VAR *));
2879 vlist->list_size = nentries;
2880 vlist->list_len = 0;
2881 vlist->list[0] = (SHELL_VAR *)NULL;
2887 vlist_realloc (vlist, n)
2892 return (vlist = vlist_alloc (n));
2893 if (n > vlist->list_size)
2895 vlist->list_size = n;
2896 vlist->list = (SHELL_VAR **)xrealloc (vlist->list, (vlist->list_size + 1) * sizeof (SHELL_VAR *));
2902 vlist_add (vlist, var, flags)
2909 for (i = 0; i < vlist->list_len; i++)
2910 if (STREQ (var->name, vlist->list[i]->name))
2912 if (i < vlist->list_len)
2915 if (i >= vlist->list_size)
2916 vlist = vlist_realloc (vlist, vlist->list_size + 16);
2918 vlist->list[vlist->list_len++] = var;
2919 vlist->list[vlist->list_len] = (SHELL_VAR *)NULL;
2922 /* Map FUNCTION over the variables in VAR_HASH_TABLE. Return an array of the
2923 variables for which FUNCTION returns a non-zero value. A NULL value
2924 for FUNCTION means to use all variables. */
2926 map_over (function, vc)
2927 sh_var_map_func_t *function;
2935 for (nentries = 0, v = vc; v; v = v->down)
2936 nentries += HASH_ENTRIES (v->table);
2939 return (SHELL_VAR **)NULL;
2941 vlist = vlist_alloc (nentries);
2943 for (v = vc; v; v = v->down)
2944 flatten (v->table, function, vlist, 0);
2952 map_over_funcs (function)
2953 sh_var_map_func_t *function;
2958 if (shell_functions == 0 || HASH_ENTRIES (shell_functions) == 0)
2959 return ((SHELL_VAR **)NULL);
2961 vlist = vlist_alloc (HASH_ENTRIES (shell_functions));
2963 flatten (shell_functions, function, vlist, 0);
2970 /* Flatten VAR_HASH_TABLE, applying FUNC to each member and adding those
2971 elements for which FUNC succeeds to VLIST->list. FLAGS is reserved
2972 for future use. Only unique names are added to VLIST. If FUNC is
2973 NULL, each variable in VAR_HASH_TABLE is added to VLIST. If VLIST is
2974 NULL, FUNC is applied to each SHELL_VAR in VAR_HASH_TABLE. If VLIST
2975 and FUNC are both NULL, nothing happens. */
2977 flatten (var_hash_table, func, vlist, flags)
2978 HASH_TABLE *var_hash_table;
2979 sh_var_map_func_t *func;
2984 register BUCKET_CONTENTS *tlist;
2988 if (var_hash_table == 0 || (HASH_ENTRIES (var_hash_table) == 0) || (vlist == 0 && func == 0))
2991 for (i = 0; i < var_hash_table->nbuckets; i++)
2993 for (tlist = hash_items (i, var_hash_table); tlist; tlist = tlist->next)
2995 var = (SHELL_VAR *)tlist->data;
2997 r = func ? (*func) (var) : 1;
2999 vlist_add (vlist, var, flags);
3005 sort_variables (array)
3008 qsort (array, strvec_len ((char **)array), sizeof (SHELL_VAR *), (QSFUNC *)qsort_var_comp);
3012 qsort_var_comp (var1, var2)
3013 SHELL_VAR **var1, **var2;
3017 if ((result = (*var1)->name[0] - (*var2)->name[0]) == 0)
3018 result = strcmp ((*var1)->name, (*var2)->name);
3023 /* Apply FUNC to each variable in SHELL_VARIABLES, adding each one for
3024 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3027 sh_var_map_func_t *func;
3031 list = map_over (func, shell_variables);
3032 if (list /* && posixly_correct */)
3033 sort_variables (list);
3037 /* Apply FUNC to each variable in SHELL_FUNCTIONS, adding each one for
3038 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3041 sh_var_map_func_t *func;
3045 list = map_over_funcs (func);
3046 if (list /* && posixly_correct */)
3047 sort_variables (list);
3051 /* Create a NULL terminated array of all the shell variables. */
3053 all_shell_variables ()
3055 return (vapply ((sh_var_map_func_t *)NULL));
3058 /* Create a NULL terminated array of all the shell functions. */
3060 all_shell_functions ()
3062 return (fapply ((sh_var_map_func_t *)NULL));
3069 return (invisible_p (var) == 0);
3073 all_visible_functions ()
3075 return (fapply (visible_var));
3079 all_visible_variables ()
3081 return (vapply (visible_var));
3084 /* Return non-zero if the variable VAR is visible and exported. Array
3085 variables cannot be exported. */
3087 visible_and_exported (var)
3090 return (invisible_p (var) == 0 && exported_p (var));
3093 /* Candidate variables for the export environment are either valid variables
3094 with the export attribute or invalid variables inherited from the initial
3095 environment and simply passed through. */
3097 export_environment_candidate (var)
3100 return (exported_p (var) && (invisible_p (var) == 0 || imported_p (var)));
3103 /* Return non-zero if VAR is a local variable in the current context and
3106 local_and_exported (var)
3109 return (invisible_p (var) == 0 && local_p (var) && var->context == variable_context && exported_p (var));
3113 all_exported_variables ()
3115 return (vapply (visible_and_exported));
3119 local_exported_variables ()
3121 return (vapply (local_and_exported));
3125 variable_in_context (var)
3128 return (invisible_p (var) == 0 && local_p (var) && var->context == variable_context);
3132 all_local_variables ()
3138 vc = shell_variables;
3139 for (vc = shell_variables; vc; vc = vc->down)
3140 if (vc_isfuncenv (vc) && vc->scope == variable_context)
3145 internal_error (_("all_local_variables: no function context at current scope"));
3146 return (SHELL_VAR **)NULL;
3148 if (vc->table == 0 || HASH_ENTRIES (vc->table) == 0 || vc_haslocals (vc) == 0)
3149 return (SHELL_VAR **)NULL;
3151 vlist = vlist_alloc (HASH_ENTRIES (vc->table));
3153 flatten (vc->table, variable_in_context, vlist, 0);
3158 sort_variables (ret);
3162 #if defined (ARRAY_VARS)
3163 /* Return non-zero if the variable VAR is visible and an array. */
3165 visible_array_vars (var)
3168 return (invisible_p (var) == 0 && array_p (var));
3172 all_array_variables ()
3174 return (vapply (visible_array_vars));
3176 #endif /* ARRAY_VARS */
3179 all_variables_matching_prefix (prefix)
3182 SHELL_VAR **varlist;
3184 int vind, rind, plen;
3186 plen = STRLEN (prefix);
3187 varlist = all_visible_variables ();
3188 for (vind = 0; varlist && varlist[vind]; vind++)
3190 if (varlist == 0 || vind == 0)
3191 return ((char **)NULL);
3192 rlist = strvec_create (vind + 1);
3193 for (vind = rind = 0; varlist[vind]; vind++)
3195 if (plen == 0 || STREQN (prefix, varlist[vind]->name, plen))
3196 rlist[rind++] = savestring (varlist[vind]->name);
3198 rlist[rind] = (char *)0;
3204 /* **************************************************************** */
3206 /* Managing temporary variable scopes */
3208 /* **************************************************************** */
3210 /* Make variable NAME have VALUE in the temporary environment. */
3212 bind_tempenv_variable (name, value)
3218 var = temporary_env ? hash_lookup (name, temporary_env) : (SHELL_VAR *)NULL;
3222 FREE (value_cell (var));
3223 var_setvalue (var, savestring (value));
3224 INVALIDATE_EXPORTSTR (var);
3230 /* Find a variable in the temporary environment that is named NAME.
3231 Return the SHELL_VAR *, or NULL if not found. */
3233 find_tempenv_variable (name)
3236 return (temporary_env ? hash_lookup (name, temporary_env) : (SHELL_VAR *)NULL);
3239 /* Push the variable described by (SHELL_VAR *)DATA down to the next
3240 variable context from the temporary environment. */
3242 push_temp_var (data)
3246 HASH_TABLE *binding_table;
3248 var = (SHELL_VAR *)data;
3250 binding_table = shell_variables->table;
3251 if (binding_table == 0)
3253 if (shell_variables == global_variables)
3254 /* shouldn't happen */
3255 binding_table = shell_variables->table = global_variables->table = hash_create (0);
3257 binding_table = shell_variables->table = hash_create (TEMPENV_HASH_BUCKETS);
3260 v = bind_variable_internal (var->name, value_cell (var), binding_table, 0, 0);
3262 /* XXX - should we set the context here? It shouldn't matter because of how
3263 assign_in_env works, but might want to check. */
3264 if (binding_table == global_variables->table) /* XXX */
3265 var->attributes &= ~(att_tempvar|att_propagate);
3268 var->attributes |= att_propagate;
3269 if (binding_table == shell_variables->table)
3270 shell_variables->flags |= VC_HASTMPVAR;
3272 v->attributes |= var->attributes;
3274 dispose_variable (var);
3278 propagate_temp_var (data)
3283 var = (SHELL_VAR *)data;
3284 if (tempvar_p (var) && (var->attributes & att_propagate))
3285 push_temp_var (data);
3287 dispose_variable (var);
3290 /* Free the storage used in the hash table for temporary
3291 environment variables. PUSHF is a function to be called
3292 to free each hash table entry. It takes care of pushing variables
3293 to previous scopes if appropriate. */
3295 dispose_temporary_env (pushf)
3296 sh_free_func_t *pushf;
3298 hash_flush (temporary_env, pushf);
3299 hash_dispose (temporary_env);
3300 temporary_env = (HASH_TABLE *)NULL;
3302 array_needs_making = 1;
3304 sv_ifs ("IFS"); /* XXX here for now */
3308 dispose_used_env_vars ()
3312 dispose_temporary_env (propagate_temp_var);
3313 maybe_make_export_env ();
3317 /* Take all of the shell variables in the temporary environment HASH_TABLE
3318 and make shell variables from them at the current variable context. */
3320 merge_temporary_env ()
3323 dispose_temporary_env (push_temp_var);
3326 /* **************************************************************** */
3328 /* Creating and manipulating the environment */
3330 /* **************************************************************** */
3332 static inline char *
3333 mk_env_string (name, value)
3334 const char *name, *value;
3336 int name_len, value_len;
3339 name_len = strlen (name);
3340 value_len = STRLEN (value);
3341 p = (char *)xmalloc (2 + name_len + value_len);
3344 if (value && *value)
3345 strcpy (p + name_len + 1, value);
3347 p[name_len + 1] = '\0';
3360 if (legal_variable_starter ((unsigned char)*s) == 0)
3362 internal_error (_("invalid character %d in exportstr for %s"), *s, v->name);
3365 for (s = v->exportstr + 1; s && *s; s++)
3369 if (legal_variable_char ((unsigned char)*s) == 0)
3371 internal_error (_("invalid character %d in exportstr for %s"), *s, v->name);
3377 internal_error (_("no `=' in exportstr for %s"), v->name);
3385 make_env_array_from_var_list (vars)
3388 register int i, list_index;
3389 register SHELL_VAR *var;
3390 char **list, *value;
3392 list = strvec_create ((1 + strvec_len ((char **)vars)));
3394 #define USE_EXPORTSTR (value == var->exportstr)
3396 for (i = 0, list_index = 0; var = vars[i]; i++)
3398 #if defined (__CYGWIN__)
3399 /* We don't use the exportstr stuff on Cygwin at all. */
3400 INVALIDATE_EXPORTSTR (var);
3403 value = var->exportstr;
3404 else if (function_p (var))
3405 value = named_function_string ((char *)NULL, function_cell (var), 0);
3406 #if defined (ARRAY_VARS)
3407 else if (array_p (var))
3409 value = array_to_assignment_string (array_cell (var));
3411 continue; /* XXX array vars cannot yet be exported */
3413 else if (assoc_p (var))
3415 value = assoc_to_assignment_string (assoc_cell (var));
3417 continue; /* XXX associative array vars cannot yet be exported */
3421 value = value_cell (var);
3425 /* Gee, I'd like to get away with not using savestring() if we're
3426 using the cached exportstr... */
3427 list[list_index] = USE_EXPORTSTR ? savestring (value)
3428 : mk_env_string (var->name, value);
3430 if (USE_EXPORTSTR == 0)
3431 SAVE_EXPORTSTR (var, list[list_index]);
3434 #undef USE_EXPORTSTR
3437 #if defined (ARRAY_VARS)
3438 if (array_p (var) || assoc_p (var))
3445 list[list_index] = (char *)NULL;
3449 /* Make an array of assignment statements from the hash table
3450 HASHED_VARS which contains SHELL_VARs. Only visible, exported
3451 variables are eligible. */
3453 make_var_export_array (vcxt)
3460 vars = map_over (visible_and_exported, vcxt);
3462 vars = map_over (export_environment_candidate, vcxt);
3466 return (char **)NULL;
3468 list = make_env_array_from_var_list (vars);
3475 make_func_export_array ()
3480 vars = map_over_funcs (visible_and_exported);
3482 return (char **)NULL;
3484 list = make_env_array_from_var_list (vars);
3490 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
3491 #define add_to_export_env(envstr,do_alloc) \
3494 if (export_env_index >= (export_env_size - 1)) \
3496 export_env_size += 16; \
3497 export_env = strvec_resize (export_env, export_env_size); \
3498 environ = export_env; \
3500 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
3501 export_env[export_env_index] = (char *)NULL; \
3504 /* Add ASSIGN to EXPORT_ENV, or supercede a previous assignment in the
3505 array with the same left-hand side. Return the new EXPORT_ENV. */
3507 add_or_supercede_exported_var (assign, do_alloc)
3514 equal_offset = assignment (assign, 0);
3515 if (equal_offset == 0)
3516 return (export_env);
3518 /* If this is a function, then only supersede the function definition.
3519 We do this by including the `=() {' in the comparison, like
3520 initialize_shell_variables does. */
3521 if (assign[equal_offset + 1] == '(' &&
3522 strncmp (assign + equal_offset + 2, ") {", 3) == 0) /* } */
3525 for (i = 0; i < export_env_index; i++)
3527 if (STREQN (assign, export_env[i], equal_offset + 1))
3529 free (export_env[i]);
3530 export_env[i] = do_alloc ? savestring (assign) : assign;
3531 return (export_env);
3534 add_to_export_env (assign, do_alloc);
3535 return (export_env);
3539 add_temp_array_to_env (temp_array, do_alloc, do_supercede)
3541 int do_alloc, do_supercede;
3545 if (temp_array == 0)
3548 for (i = 0; temp_array[i]; i++)
3551 export_env = add_or_supercede_exported_var (temp_array[i], do_alloc);
3553 add_to_export_env (temp_array[i], do_alloc);
3559 /* Make the environment array for the command about to be executed, if the
3560 array needs making. Otherwise, do nothing. If a shell action could
3561 change the array that commands receive for their environment, then the
3562 code should `array_needs_making++'.
3564 The order to add to the array is:
3566 list of var contexts whose head is shell_variables
3569 This is the shell variable lookup order. We add only new variable
3570 names at each step, which allows local variables and variables in
3571 the temporary environments to shadow variables in the global (or
3572 any previous) scope.
3576 n_shell_variables ()
3581 for (n = 0, vc = shell_variables; vc; vc = vc->down)
3582 n += HASH_ENTRIES (vc->table);
3587 maybe_make_export_env ()
3589 register char **temp_array;
3593 if (array_needs_making)
3596 strvec_flush (export_env);
3598 /* Make a guess based on how many shell variables and functions we
3599 have. Since there will always be array variables, and array
3600 variables are not (yet) exported, this will always be big enough
3601 for the exported variables and functions. */
3602 new_size = n_shell_variables () + HASH_ENTRIES (shell_functions) + 1 +
3603 HASH_ENTRIES (temporary_env);
3604 if (new_size > export_env_size)
3606 export_env_size = new_size;
3607 export_env = strvec_resize (export_env, export_env_size);
3608 environ = export_env;
3610 export_env[export_env_index = 0] = (char *)NULL;
3612 /* Make a dummy variable context from the temporary_env, stick it on
3613 the front of shell_variables, call make_var_export_array on the
3614 whole thing to flatten it, and convert the list of SHELL_VAR *s
3615 to the form needed by the environment. */
3618 tcxt = new_var_context ((char *)NULL, 0);
3619 tcxt->table = temporary_env;
3620 tcxt->down = shell_variables;
3623 tcxt = shell_variables;
3625 temp_array = make_var_export_array (tcxt);
3627 add_temp_array_to_env (temp_array, 0, 0);
3629 if (tcxt != shell_variables)
3632 #if defined (RESTRICTED_SHELL)
3633 /* Restricted shells may not export shell functions. */
3634 temp_array = restricted ? (char **)0 : make_func_export_array ();
3636 temp_array = make_func_export_array ();
3639 add_temp_array_to_env (temp_array, 0, 0);
3641 array_needs_making = 0;
3645 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
3646 we will need to remake the exported environment every time we
3647 change directories. `_' is always put into the environment for
3648 every external command, so without special treatment it will always
3649 cause the environment to be remade.
3651 If there is no other reason to make the exported environment, we can
3652 just update the variables in place and mark the exported environment
3653 as no longer needing a remake. */
3655 update_export_env_inplace (env_prefix, preflen, value)
3662 evar = (char *)xmalloc (STRLEN (value) + preflen + 1);
3663 strcpy (evar, env_prefix);
3665 strcpy (evar + preflen, value);
3666 export_env = add_or_supercede_exported_var (evar, 0);
3669 /* We always put _ in the environment as the name of this command. */
3671 put_command_name_into_env (command_name)
3674 update_export_env_inplace ("_=", 2, command_name);
3677 #if 0 /* UNUSED -- it caused too many problems */
3679 put_gnu_argv_flags_into_env (pid, flags_string)
3689 fl = strlen (flags_string);
3691 dummy = (char *)xmalloc (l + fl + 30);
3693 strcpy (dummy + 1, pbuf);
3694 strcpy (dummy + 1 + l, "_GNU_nonoption_argv_flags_");
3695 dummy[l + 27] = '=';
3696 strcpy (dummy + l + 28, flags_string);
3700 export_env = add_or_supercede_exported_var (dummy, 0);
3704 /* **************************************************************** */
3706 /* Managing variable contexts */
3708 /* **************************************************************** */
3710 /* Allocate and return a new variable context with NAME and FLAGS.
3711 NAME can be NULL. */
3714 new_var_context (name, flags)
3720 vc = (VAR_CONTEXT *)xmalloc (sizeof (VAR_CONTEXT));
3721 vc->name = name ? savestring (name) : (char *)NULL;
3722 vc->scope = variable_context;
3725 vc->up = vc->down = (VAR_CONTEXT *)NULL;
3726 vc->table = (HASH_TABLE *)NULL;
3731 /* Free a variable context and its data, including the hash table. Dispose
3732 all of the variables. */
3734 dispose_var_context (vc)
3741 delete_all_variables (vc->table);
3742 hash_dispose (vc->table);
3748 /* Set VAR's scope level to the current variable context. */
3753 return (var->context = variable_context);
3756 /* Make a new variable context with NAME and FLAGS and a HASH_TABLE of
3757 temporary variables, and push it onto shell_variables. This is
3758 for shell functions. */
3760 push_var_context (name, flags, tempvars)
3763 HASH_TABLE *tempvars;
3767 vc = new_var_context (name, flags);
3768 vc->table = tempvars;
3771 /* Have to do this because the temp environment was created before
3772 variable_context was incremented. */
3773 flatten (tempvars, set_context, (VARLIST *)NULL, 0);
3774 vc->flags |= VC_HASTMPVAR;
3776 vc->down = shell_variables;
3777 shell_variables->up = vc;
3779 return (shell_variables = vc);
3783 push_func_var (data)
3788 var = (SHELL_VAR *)data;
3790 if (tempvar_p (var) && (posixly_correct || (var->attributes & att_propagate)))
3792 /* XXX - should we set v->context here? */
3793 v = bind_variable_internal (var->name, value_cell (var), shell_variables->table, 0, 0);
3794 if (shell_variables == global_variables)
3795 var->attributes &= ~(att_tempvar|att_propagate);
3797 shell_variables->flags |= VC_HASTMPVAR;
3798 v->attributes |= var->attributes;
3801 stupidly_hack_special_variables (var->name); /* XXX */
3803 dispose_variable (var);
3806 /* Pop the top context off of VCXT and dispose of it, returning the rest of
3811 VAR_CONTEXT *ret, *vcxt;
3813 vcxt = shell_variables;
3814 if (vc_isfuncenv (vcxt) == 0)
3816 internal_error (_("pop_var_context: head of shell_variables not a function context"));
3820 if (ret = vcxt->down)
3822 ret->up = (VAR_CONTEXT *)NULL;
3823 shell_variables = ret;
3825 hash_flush (vcxt->table, push_func_var);
3826 dispose_var_context (vcxt);
3829 internal_error (_("pop_var_context: no global_variables context"));
3832 /* Delete the HASH_TABLEs for all variable contexts beginning at VCXT, and
3833 all of the VAR_CONTEXTs except GLOBAL_VARIABLES. */
3835 delete_all_contexts (vcxt)
3840 for (v = vcxt; v != global_variables; v = t)
3843 dispose_var_context (v);
3846 delete_all_variables (global_variables->table);
3847 shell_variables = global_variables;
3850 /* **************************************************************** */
3852 /* Pushing and Popping temporary variable scopes */
3854 /* **************************************************************** */
3857 push_scope (flags, tmpvars)
3859 HASH_TABLE *tmpvars;
3861 return (push_var_context ((char *)NULL, flags, tmpvars));
3865 push_exported_var (data)
3870 var = (SHELL_VAR *)data;
3872 /* If a temp var had its export attribute set, or it's marked to be
3873 propagated, bind it in the previous scope before disposing it. */
3874 /* XXX - This isn't exactly right, because all tempenv variables have the
3875 export attribute set. */
3877 if (exported_p (var) || (var->attributes & att_propagate))
3879 if (tempvar_p (var) && exported_p (var) && (var->attributes & att_propagate))
3882 var->attributes &= ~att_tempvar; /* XXX */
3883 v = bind_variable_internal (var->name, value_cell (var), shell_variables->table, 0, 0);
3884 if (shell_variables == global_variables)
3885 var->attributes &= ~att_propagate;
3886 v->attributes |= var->attributes;
3889 stupidly_hack_special_variables (var->name); /* XXX */
3891 dispose_variable (var);
3895 pop_scope (is_special)
3898 VAR_CONTEXT *vcxt, *ret;
3900 vcxt = shell_variables;
3901 if (vc_istempscope (vcxt) == 0)
3903 internal_error (_("pop_scope: head of shell_variables not a temporary environment scope"));
3909 ret->up = (VAR_CONTEXT *)NULL;
3911 shell_variables = ret;
3913 /* Now we can take care of merging variables in VCXT into set of scopes
3914 whose head is RET (shell_variables). */
3919 hash_flush (vcxt->table, push_func_var);
3921 hash_flush (vcxt->table, push_exported_var);
3922 hash_dispose (vcxt->table);
3926 sv_ifs ("IFS"); /* XXX here for now */
3929 /* **************************************************************** */
3931 /* Pushing and Popping function contexts */
3933 /* **************************************************************** */
3935 static WORD_LIST **dollar_arg_stack = (WORD_LIST **)NULL;
3936 static int dollar_arg_stack_slots;
3937 static int dollar_arg_stack_index;
3939 /* XXX - we might want to consider pushing and popping the `getopts' state
3940 when we modify the positional parameters. */
3942 push_context (name, is_subshell, tempvars)
3943 char *name; /* function name */
3945 HASH_TABLE *tempvars;
3947 if (is_subshell == 0)
3948 push_dollar_vars ();
3950 push_var_context (name, VC_FUNCENV, tempvars);
3953 /* Only called when subshell == 0, so we don't need to check, and can
3954 unconditionally pop the dollar vars off the stack. */
3962 sv_ifs ("IFS"); /* XXX here for now */
3965 /* Save the existing positional parameters on a stack. */
3969 if (dollar_arg_stack_index + 2 > dollar_arg_stack_slots)
3971 dollar_arg_stack = (WORD_LIST **)
3972 xrealloc (dollar_arg_stack, (dollar_arg_stack_slots += 10)
3973 * sizeof (WORD_LIST **));
3975 dollar_arg_stack[dollar_arg_stack_index++] = list_rest_of_args ();
3976 dollar_arg_stack[dollar_arg_stack_index] = (WORD_LIST *)NULL;
3979 /* Restore the positional parameters from our stack. */
3983 if (!dollar_arg_stack || dollar_arg_stack_index == 0)
3986 remember_args (dollar_arg_stack[--dollar_arg_stack_index], 1);
3987 dispose_words (dollar_arg_stack[dollar_arg_stack_index]);
3988 dollar_arg_stack[dollar_arg_stack_index] = (WORD_LIST *)NULL;
3989 set_dollar_vars_unchanged ();
3993 dispose_saved_dollar_vars ()
3995 if (!dollar_arg_stack || dollar_arg_stack_index == 0)
3998 dispose_words (dollar_arg_stack[dollar_arg_stack_index]);
3999 dollar_arg_stack[dollar_arg_stack_index] = (WORD_LIST *)NULL;
4002 /* Manipulate the special BASH_ARGV and BASH_ARGC variables. */
4008 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4009 SHELL_VAR *bash_argv_v, *bash_argc_v;
4010 ARRAY *bash_argv_a, *bash_argc_a;
4015 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v, bash_argv_a);
4016 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v, bash_argc_a);
4018 for (l = list, i = 0; l; l = l->next, i++)
4019 array_push (bash_argv_a, l->word->word);
4022 array_push (bash_argc_a, t);
4024 #endif /* ARRAY_VARS && DEBUGGER */
4027 /* Remove arguments from BASH_ARGV array. Pop top element off BASH_ARGC
4028 array and use that value as the count of elements to remove from
4033 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4034 SHELL_VAR *bash_argv_v, *bash_argc_v;
4035 ARRAY *bash_argv_a, *bash_argc_a;
4039 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v, bash_argv_a);
4040 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v, bash_argc_a);
4042 ce = array_shift (bash_argc_a, 1, 0);
4043 if (ce == 0 || legal_number (element_value (ce), &i) == 0)
4047 array_pop (bash_argv_a);
4048 array_dispose_element (ce);
4049 #endif /* ARRAY_VARS && DEBUGGER */
4052 /*************************************************
4054 * Functions to manage special variables *
4056 *************************************************/
4058 /* Extern declarations for variables this code has to manage. */
4059 extern int eof_encountered, eof_encountered_limit, ignoreeof;
4061 #if defined (READLINE)
4062 extern int hostname_list_initialized;
4065 /* An alist of name.function for each special variable. Most of the
4066 functions don't do much, and in fact, this would be faster with a
4067 switch statement, but by the end of this file, I am sick of switch
4070 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
4072 /* This table will be sorted with qsort() the first time it's accessed. */
4073 struct name_and_function {
4075 sh_sv_func_t *function;
4078 static struct name_and_function special_vars[] = {
4079 #if defined (READLINE)
4080 # if defined (STRICT_POSIX)
4081 { "COLUMNS", sv_winsize },
4083 { "COMP_WORDBREAKS", sv_comp_wordbreaks },
4086 { "GLOBIGNORE", sv_globignore },
4088 #if defined (HISTORY)
4089 { "HISTCONTROL", sv_history_control },
4090 { "HISTFILESIZE", sv_histsize },
4091 { "HISTIGNORE", sv_histignore },
4092 { "HISTSIZE", sv_histsize },
4093 { "HISTTIMEFORMAT", sv_histtimefmt },
4096 #if defined (__CYGWIN__)
4097 { "HOME", sv_home },
4100 #if defined (READLINE)
4101 { "HOSTFILE", sv_hostfile },
4105 { "IGNOREEOF", sv_ignoreeof },
4107 { "LANG", sv_locale },
4108 { "LC_ALL", sv_locale },
4109 { "LC_COLLATE", sv_locale },
4110 { "LC_CTYPE", sv_locale },
4111 { "LC_MESSAGES", sv_locale },
4112 { "LC_NUMERIC", sv_locale },
4113 { "LC_TIME", sv_locale },
4115 #if defined (READLINE) && defined (STRICT_POSIX)
4116 { "LINES", sv_winsize },
4119 { "MAIL", sv_mail },
4120 { "MAILCHECK", sv_mail },
4121 { "MAILPATH", sv_mail },
4123 { "OPTERR", sv_opterr },
4124 { "OPTIND", sv_optind },
4126 { "PATH", sv_path },
4127 { "POSIXLY_CORRECT", sv_strict_posix },
4129 #if defined (READLINE)
4130 { "TERM", sv_terminal },
4131 { "TERMCAP", sv_terminal },
4132 { "TERMINFO", sv_terminal },
4133 #endif /* READLINE */
4135 { "TEXTDOMAIN", sv_locale },
4136 { "TEXTDOMAINDIR", sv_locale },
4138 #if defined (HAVE_TZSET) && defined (PROMPT_STRING_DECODE)
4142 #if defined (HISTORY) && defined (BANG_HISTORY)
4143 { "histchars", sv_histchars },
4144 #endif /* HISTORY && BANG_HISTORY */
4146 { "ignoreeof", sv_ignoreeof },
4148 { (char *)0, (sh_sv_func_t *)0 }
4151 #define N_SPECIAL_VARS (sizeof (special_vars) / sizeof (special_vars[0]) - 1)
4154 sv_compare (sv1, sv2)
4155 struct name_and_function *sv1, *sv2;
4159 if ((r = sv1->name[0] - sv2->name[0]) == 0)
4160 r = strcmp (sv1->name, sv2->name);
4165 find_special_var (name)
4170 for (i = 0; special_vars[i].name; i++)
4172 r = special_vars[i].name[0] - name[0];
4174 r = strcmp (special_vars[i].name, name);
4178 /* Can't match any of rest of elements in sorted list. Take this out
4179 if it causes problems in certain environments. */
4185 /* The variable in NAME has just had its state changed. Check to see if it
4186 is one of the special ones where something special happens. */
4188 stupidly_hack_special_variables (name)
4191 static int sv_sorted = 0;
4194 if (sv_sorted == 0) /* shouldn't need, but it's fairly cheap. */
4196 qsort (special_vars, N_SPECIAL_VARS, sizeof (special_vars[0]),
4197 (QSFUNC *)sv_compare);
4201 i = find_special_var (name);
4203 (*(special_vars[i].function)) (name);
4206 /* Special variables that need hooks to be run when they are unset as part
4207 of shell reinitialization should have their sv_ functions run here. */
4209 reinit_special_variables ()
4211 #if defined (READLINE)
4212 sv_comp_wordbreaks ("COMP_WORDBREAKS");
4214 sv_globignore ("GLOBIGNORE");
4215 sv_opterr ("OPTERR");
4224 v = find_variable ("IFS");
4228 /* What to do just after the PATH variable has changed. */
4237 /* What to do just after one of the MAILxxxx variables has changed. NAME
4238 is the name of the variable. This is called with NAME set to one of
4239 MAIL, MAILCHECK, or MAILPATH. */
4244 /* If the time interval for checking the files has changed, then
4245 reset the mail timer. Otherwise, one of the pathname vars
4246 to the users mailbox has changed, so rebuild the array of
4248 if (name[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
4249 reset_mail_timer ();
4253 remember_mail_dates ();
4257 /* What to do when GLOBIGNORE changes. */
4259 sv_globignore (name)
4262 if (privileged_mode == 0)
4263 setup_glob_ignore (name);
4266 #if defined (READLINE)
4268 sv_comp_wordbreaks (name)
4273 sv = find_variable (name);
4275 reset_completer_word_break_chars ();
4278 /* What to do just after one of the TERMxxx variables has changed.
4279 If we are an interactive shell, then try to reset the terminal
4280 information in readline. */
4285 if (interactive_shell && no_line_editing == 0)
4286 rl_reset_terminal (get_string_value ("TERM"));
4295 v = find_variable (name);
4297 clear_hostname_list ();
4299 hostname_list_initialized = 0;
4302 #if defined (STRICT_POSIX)
4303 /* In strict posix mode, we allow assignments to LINES and COLUMNS (and values
4304 found in the initial environment) to override the terminal size reported by
4314 if (posixly_correct == 0 || interactive_shell == 0 || no_line_editing)
4317 v = find_variable (name);
4318 if (v == 0 || var_isnull (v))
4319 rl_reset_screen_size ();
4322 if (legal_number (value_cell (v), &xd) == 0)
4324 winsize_assignment = winsize_assigned = 1;
4325 d = xd; /* truncate */
4326 if (name[0] == 'L') /* LINES */
4327 rl_set_screen_size (d, -1);
4329 rl_set_screen_size (-1, d);
4330 winsize_assignment = 0;
4333 #endif /* STRICT_POSIX */
4334 #endif /* READLINE */
4336 /* Update the value of HOME in the export environment so tilde expansion will
4338 #if defined (__CYGWIN__)
4342 array_needs_making = 1;
4343 maybe_make_export_env ();
4347 #if defined (HISTORY)
4348 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
4349 If there is a value for this HISTSIZE (and it is numeric), then stifle
4350 the history. Otherwise, if there is NO value for this variable,
4351 unstifle the history. If name is HISTFILESIZE, and its value is
4352 numeric, truncate the history file to hold no more than that many
4362 temp = get_string_value (name);
4366 if (legal_number (temp, &num))
4371 stifle_history (hmax);
4372 hmax = where_history ();
4373 if (history_lines_this_session > hmax)
4374 history_lines_this_session = hmax;
4378 history_truncate_file (get_string_value ("HISTFILE"), hmax);
4379 if (hmax <= history_lines_in_file)
4380 history_lines_in_file = hmax;
4384 else if (name[4] == 'S')
4385 unstifle_history ();
4388 /* What to do after the HISTIGNORE variable changes. */
4390 sv_histignore (name)
4393 setup_history_ignore (name);
4396 /* What to do after the HISTCONTROL variable changes. */
4398 sv_history_control (name)
4405 history_control = 0;
4406 temp = get_string_value (name);
4408 if (temp == 0 || *temp == 0)
4412 while (val = extract_colon_unit (temp, &tptr))
4414 if (STREQ (val, "ignorespace"))
4415 history_control |= HC_IGNSPACE;
4416 else if (STREQ (val, "ignoredups"))
4417 history_control |= HC_IGNDUPS;
4418 else if (STREQ (val, "ignoreboth"))
4419 history_control |= HC_IGNBOTH;
4420 else if (STREQ (val, "erasedups"))
4421 history_control |= HC_ERASEDUPS;
4427 #if defined (BANG_HISTORY)
4428 /* Setting/unsetting of the history expansion character. */
4435 temp = get_string_value (name);
4438 history_expansion_char = *temp;
4439 if (temp[0] && temp[1])
4441 history_subst_char = temp[1];
4443 history_comment_char = temp[2];
4448 history_expansion_char = '!';
4449 history_subst_char = '^';
4450 history_comment_char = '#';
4453 #endif /* BANG_HISTORY */
4456 sv_histtimefmt (name)
4461 v = find_variable (name);
4462 history_write_timestamps = (v != 0);
4464 #endif /* HISTORY */
4466 #if defined (HAVE_TZSET) && defined (PROMPT_STRING_DECODE)
4475 /* If the variable exists, then the value of it can be the number
4476 of times we actually ignore the EOF. The default is small,
4477 (smaller than csh, anyway). */
4485 eof_encountered = 0;
4487 tmp_var = find_variable (name);
4488 ignoreeof = tmp_var != 0;
4489 temp = tmp_var ? value_cell (tmp_var) : (char *)NULL;
4491 eof_encountered_limit = (*temp && all_digits (temp)) ? atoi (temp) : 10;
4492 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
4502 tt = get_string_value ("OPTIND");
4507 /* According to POSIX, setting OPTIND=1 resets the internal state
4509 if (s < 0 || s == 1)
4523 tt = get_string_value ("OPTERR");
4524 sh_opterr = (tt && *tt) ? atoi (tt) : 1;
4528 sv_strict_posix (name)
4531 SET_INT_VAR (name, posixly_correct);
4532 posix_initialize (posixly_correct);
4533 #if defined (READLINE)
4534 if (interactive_shell)
4535 posix_readline_initialize (posixly_correct);
4536 #endif /* READLINE */
4537 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
4546 v = get_string_value (name);
4547 if (name[0] == 'L' && name[1] == 'A') /* LANG */
4550 set_locale_var (name, v); /* LC_*, TEXTDOMAIN* */
4553 #if defined (ARRAY_VARS)
4555 set_pipestatus_array (ps, nproc)
4563 char *t, tbuf[INT_STRLEN_BOUND(int) + 1];
4565 v = find_variable ("PIPESTATUS");
4567 v = make_new_array_variable ("PIPESTATUS");
4568 if (array_p (v) == 0)
4569 return; /* Do nothing if not an array variable. */
4572 if (a == 0 || array_num_elements (a) == 0)
4574 for (i = 0; i < nproc; i++) /* was ps[i] != -1, not i < nproc */
4576 t = inttostr (ps[i], tbuf, sizeof (tbuf));
4577 array_insert (a, i, t);
4583 if (array_num_elements (a) == nproc && nproc == 1)
4585 ae = element_forw (a->head);
4586 free (element_value (ae));
4587 ae->value = itos (ps[0]);
4589 else if (array_num_elements (a) <= nproc)
4591 /* modify in array_num_elements members in place, then add */
4593 for (i = 0; i < array_num_elements (a); i++)
4595 ae = element_forw (ae);
4596 free (element_value (ae));
4597 ae->value = itos (ps[i]);
4600 for ( ; i < nproc; i++)
4602 t = inttostr (ps[i], tbuf, sizeof (tbuf));
4603 array_insert (a, i, t);
4608 /* deleting elements. it's faster to rebuild the array. */
4610 for (i = 0; ps[i] != -1; i++)
4612 t = inttostr (ps[i], tbuf, sizeof (tbuf));
4613 array_insert (a, i, t);
4620 set_pipestatus_from_exit (s)
4623 #if defined (ARRAY_VARS)
4624 static int v[2] = { 0, -1 };
4627 set_pipestatus_array (v, 1);