1 /* variables.c -- Functions for hacking shell variables. */
3 /* Copyright (C) 1987-2013 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #include "bashtypes.h"
24 #include "posixstat.h"
25 #include "posixtime.h"
28 # if defined (__QNXNTO__)
29 # include <sys/netmgr.h>
32 # endif /* !__QNXNTO__ */
35 #if defined (HAVE_UNISTD_H)
40 #include "chartypes.h"
41 #if defined (HAVE_PWD_H)
47 #define NEED_XTRACE_SET_DECL
51 #include "execute_cmd.h"
53 #include "mailcheck.h"
62 #include "builtins/getopt.h"
63 #include "builtins/common.h"
64 #include "builtins/builtext.h"
66 #if defined (READLINE)
67 # include "bashline.h"
68 # include <readline/readline.h>
70 # include <tilde/tilde.h>
74 # include "bashhist.h"
75 # include <readline/history.h>
78 #if defined (PROGRAMMABLE_COMPLETION)
79 # include "pcomplete.h"
82 #define TEMPENV_HASH_BUCKETS 4 /* must be power of two */
84 #define ifsname(s) ((s)[0] == 'I' && (s)[1] == 'F' && (s)[2] == 'S' && (s)[3] == '\0')
86 #define BASHFUNC_PREFIX "BASH_FUNC_"
87 #define BASHFUNC_PREFLEN 10 /* == strlen(BASHFUNC_PREFIX */
88 #define BASHFUNC_SUFFIX "%%"
89 #define BASHFUNC_SUFFLEN 2 /* == strlen(BASHFUNC_SUFFIX) */
91 extern char **environ
;
93 /* Variables used here and defined in other files. */
94 extern int posixly_correct
;
95 extern int line_number
, line_number_base
;
96 extern int subshell_environment
, indirection_level
, subshell_level
;
97 extern int build_version
, patch_level
;
98 extern int expanding_redir
;
99 extern int last_command_exit_value
;
100 extern char *dist_version
, *release_status
;
101 extern char *shell_name
;
102 extern char *primary_prompt
, *secondary_prompt
;
103 extern char *current_host_name
;
104 extern sh_builtin_func_t
*this_shell_builtin
;
105 extern SHELL_VAR
*this_shell_function
;
106 extern char *the_printed_command_except_trap
;
107 extern char *this_command_name
;
108 extern char *command_execution_string
;
109 extern time_t shell_start_time
;
110 extern int assigning_in_environment
;
111 extern int executing_builtin
;
112 extern int funcnest_max
;
114 #if defined (READLINE)
115 extern int no_line_editing
;
116 extern int perform_hostname_completion
;
119 /* The list of shell variables that the user has created at the global
120 scope, or that came from the environment. */
121 VAR_CONTEXT
*global_variables
= (VAR_CONTEXT
*)NULL
;
123 /* The current list of shell variables, including function scopes */
124 VAR_CONTEXT
*shell_variables
= (VAR_CONTEXT
*)NULL
;
126 /* The list of shell functions that the user has created, or that came from
128 HASH_TABLE
*shell_functions
= (HASH_TABLE
*)NULL
;
130 #if defined (DEBUGGER)
131 /* The table of shell function definitions that the user defined or that
132 came from the environment. */
133 HASH_TABLE
*shell_function_defs
= (HASH_TABLE
*)NULL
;
136 /* The current variable context. This is really a count of how deep into
137 executing functions we are. */
138 int variable_context
= 0;
140 /* The set of shell assignments which are made only in the environment
141 for a single command. */
142 HASH_TABLE
*temporary_env
= (HASH_TABLE
*)NULL
;
144 /* Set to non-zero if an assignment error occurs while putting variables
145 into the temporary environment. */
146 int tempenv_assign_error
;
148 /* Some funky variables which are known about specially. Here is where
149 "$*", "$1", and all the cruft is kept. */
150 char *dollar_vars
[10];
151 WORD_LIST
*rest_of_args
= (WORD_LIST
*)NULL
;
153 /* The value of $$. */
154 pid_t dollar_dollar_pid
;
156 /* Non-zero means that we have to remake EXPORT_ENV. */
157 int array_needs_making
= 1;
159 /* The number of times BASH has been executed. This is set
160 by initialize_variables (). */
163 /* An array which is passed to commands as their environment. It is
164 manufactured from the union of the initial environment and the
165 shell variables that are marked for export. */
166 char **export_env
= (char **)NULL
;
167 static int export_env_index
;
168 static int export_env_size
;
170 #if defined (READLINE)
171 static int winsize_assignment
; /* currently assigning to LINES or COLUMNS */
174 static HASH_TABLE
*last_table_searched
; /* hash_lookup sets this */
176 /* Some forward declarations. */
177 static void create_variable_tables
__P((void));
179 static void set_machine_vars
__P((void));
180 static void set_home_var
__P((void));
181 static void set_shell_var
__P((void));
182 static char *get_bash_name
__P((void));
183 static void initialize_shell_level
__P((void));
184 static void uidset
__P((void));
185 #if defined (ARRAY_VARS)
186 static void make_vers_array
__P((void));
189 static SHELL_VAR
*null_assign
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
190 #if defined (ARRAY_VARS)
191 static SHELL_VAR
*null_array_assign
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
193 static SHELL_VAR
*get_self
__P((SHELL_VAR
*));
195 #if defined (ARRAY_VARS)
196 static SHELL_VAR
*init_dynamic_array_var
__P((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
197 static SHELL_VAR
*init_dynamic_assoc_var
__P((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
200 static SHELL_VAR
*assign_seconds
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
201 static SHELL_VAR
*get_seconds
__P((SHELL_VAR
*));
202 static SHELL_VAR
*init_seconds_var
__P((void));
204 static int brand
__P((void));
205 static void sbrand
__P((unsigned long)); /* set bash random number generator. */
206 static void seedrand
__P((void)); /* seed generator randomly */
207 static SHELL_VAR
*assign_random
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
208 static SHELL_VAR
*get_random
__P((SHELL_VAR
*));
210 static SHELL_VAR
*assign_lineno
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
211 static SHELL_VAR
*get_lineno
__P((SHELL_VAR
*));
213 static SHELL_VAR
*assign_subshell
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
214 static SHELL_VAR
*get_subshell
__P((SHELL_VAR
*));
216 static SHELL_VAR
*get_bashpid
__P((SHELL_VAR
*));
218 #if defined (HISTORY)
219 static SHELL_VAR
*get_histcmd
__P((SHELL_VAR
*));
222 #if defined (READLINE)
223 static SHELL_VAR
*get_comp_wordbreaks
__P((SHELL_VAR
*));
224 static SHELL_VAR
*assign_comp_wordbreaks
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
227 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
228 static SHELL_VAR
*assign_dirstack
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
229 static SHELL_VAR
*get_dirstack
__P((SHELL_VAR
*));
232 #if defined (ARRAY_VARS)
233 static SHELL_VAR
*get_groupset
__P((SHELL_VAR
*));
235 static SHELL_VAR
*build_hashcmd
__P((SHELL_VAR
*));
236 static SHELL_VAR
*get_hashcmd
__P((SHELL_VAR
*));
237 static SHELL_VAR
*assign_hashcmd
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
239 static SHELL_VAR
*build_aliasvar
__P((SHELL_VAR
*));
240 static SHELL_VAR
*get_aliasvar
__P((SHELL_VAR
*));
241 static SHELL_VAR
*assign_aliasvar
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
245 static SHELL_VAR
*get_funcname
__P((SHELL_VAR
*));
246 static SHELL_VAR
*init_funcname_var
__P((void));
248 static void initialize_dynamic_variables
__P((void));
250 static SHELL_VAR
*hash_lookup
__P((const char *, HASH_TABLE
*));
251 static SHELL_VAR
*new_shell_variable
__P((const char *));
252 static SHELL_VAR
*make_new_variable
__P((const char *, HASH_TABLE
*));
253 static SHELL_VAR
*bind_variable_internal
__P((const char *, char *, HASH_TABLE
*, int, int));
255 static void dispose_variable_value
__P((SHELL_VAR
*));
256 static void free_variable_hash_data
__P((PTR_T
));
258 static VARLIST
*vlist_alloc
__P((int));
259 static VARLIST
*vlist_realloc
__P((VARLIST
*, int));
260 static void vlist_add
__P((VARLIST
*, SHELL_VAR
*, int));
262 static void flatten
__P((HASH_TABLE
*, sh_var_map_func_t
*, VARLIST
*, int));
264 static int qsort_var_comp
__P((SHELL_VAR
**, SHELL_VAR
**));
266 static SHELL_VAR
**vapply
__P((sh_var_map_func_t
*));
267 static SHELL_VAR
**fapply
__P((sh_var_map_func_t
*));
269 static int visible_var
__P((SHELL_VAR
*));
270 static int visible_and_exported
__P((SHELL_VAR
*));
271 static int export_environment_candidate
__P((SHELL_VAR
*));
272 static int local_and_exported
__P((SHELL_VAR
*));
273 static int variable_in_context
__P((SHELL_VAR
*));
274 #if defined (ARRAY_VARS)
275 static int visible_array_vars
__P((SHELL_VAR
*));
278 static SHELL_VAR
*find_nameref_at_context
__P((SHELL_VAR
*, VAR_CONTEXT
*));
279 static SHELL_VAR
*find_variable_nameref_context
__P((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
280 static SHELL_VAR
*find_variable_last_nameref_context
__P((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
282 static SHELL_VAR
*bind_tempenv_variable
__P((const char *, char *));
283 static void push_temp_var
__P((PTR_T
));
284 static void propagate_temp_var
__P((PTR_T
));
285 static void dispose_temporary_env
__P((sh_free_func_t
*));
287 static inline char *mk_env_string
__P((const char *, const char *, int));
288 static char **make_env_array_from_var_list
__P((SHELL_VAR
**));
289 static char **make_var_export_array
__P((VAR_CONTEXT
*));
290 static char **make_func_export_array
__P((void));
291 static void add_temp_array_to_env
__P((char **, int, int));
293 static int n_shell_variables
__P((void));
294 static int set_context
__P((SHELL_VAR
*));
296 static void push_func_var
__P((PTR_T
));
297 static void push_exported_var
__P((PTR_T
));
299 static inline int find_special_var
__P((const char *));
302 create_variable_tables ()
304 if (shell_variables
== 0)
306 shell_variables
= global_variables
= new_var_context ((char *)NULL
, 0);
307 shell_variables
->scope
= 0;
308 shell_variables
->table
= hash_create (0);
311 if (shell_functions
== 0)
312 shell_functions
= hash_create (0);
314 #if defined (DEBUGGER)
315 if (shell_function_defs
== 0)
316 shell_function_defs
= hash_create (0);
320 /* Initialize the shell variables from the current environment.
321 If PRIVMODE is nonzero, don't import functions from ENV or
324 initialize_shell_variables (env
, privmode
)
328 char *name
, *string
, *temp_string
;
329 int c
, char_index
, string_index
, string_length
, ro
;
332 create_variable_tables ();
334 for (string_index
= 0; string
= env
[string_index
++]; )
338 while ((c
= *string
++) && c
!= '=')
340 if (string
[-1] == '=')
341 char_index
= string
- name
- 1;
343 /* If there are weird things in the environment, like `=xxx' or a
344 string without an `=', just skip them. */
348 /* ASSERT(name[char_index] == '=') */
349 name
[char_index
] = '\0';
350 /* Now, name = env variable name, string = env variable value, and
351 char_index == strlen (name) */
353 temp_var
= (SHELL_VAR
*)NULL
;
355 /* If exported function, define it now. Don't import functions from
356 the environment in privileged mode. */
357 if (privmode
== 0 && read_but_dont_execute
== 0 &&
358 STREQN (BASHFUNC_PREFIX
, name
, BASHFUNC_PREFLEN
) &&
359 STREQ (BASHFUNC_SUFFIX
, name
+ char_index
- BASHFUNC_SUFFLEN
) &&
360 STREQN ("() {", string
, 4))
363 char *tname
; /* desired imported function name */
365 namelen
= char_index
- BASHFUNC_PREFLEN
- BASHFUNC_SUFFLEN
;
367 tname
= name
+ BASHFUNC_PREFLEN
; /* start of func name */
368 tname
[namelen
] = '\0'; /* now tname == func name */
370 string_length
= strlen (string
);
371 temp_string
= (char *)xmalloc (namelen
+ string_length
+ 2);
373 memcpy (temp_string
, tname
, namelen
);
374 temp_string
[namelen
] = ' ';
375 memcpy (temp_string
+ namelen
+ 1, string
, string_length
+ 1);
377 /* Don't import function names that are invalid identifiers from the
378 environment, though we still allow them to be defined as shell
380 if (absolute_program (tname
) == 0 && (posixly_correct
== 0 || legal_identifier (tname
)))
381 parse_and_execute (temp_string
, tname
, SEVAL_NONINT
|SEVAL_NOHIST
|SEVAL_FUNCDEF
|SEVAL_ONECMD
);
383 if (temp_var
= find_function (tname
))
385 VSETATTR (temp_var
, (att_exported
|att_imported
));
386 array_needs_making
= 1;
390 if (temp_var
= bind_variable (name
, string
, 0))
392 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
393 array_needs_making
= 1;
395 last_command_exit_value
= 1;
396 report_error (_("error importing function definition for `%s'"), tname
);
399 /* Restore original suffix */
400 tname
[namelen
] = BASHFUNC_SUFFIX
[0];
402 #if defined (ARRAY_VARS)
404 /* Array variables may not yet be exported. */
405 else if (*string
== '(' && string
[1] == '[' && string
[strlen (string
) - 1] == ')')
408 temp_string
= extract_array_assignment_list (string
, &string_length
);
409 temp_var
= assign_array_from_string (name
, temp_string
);
411 VSETATTR (temp_var
, (att_exported
| att_imported
));
412 array_needs_making
= 1;
414 # endif /* ARRAY_EXPORT */
417 else if (legal_identifier (name
))
423 if (posixly_correct
&& STREQ (name
, "SHELLOPTS"))
425 temp_var
= find_variable ("SHELLOPTS");
426 ro
= temp_var
&& readonly_p (temp_var
);
428 VUNSETATTR (temp_var
, att_readonly
);
430 temp_var
= bind_variable (name
, string
, 0);
433 if (legal_identifier (name
))
434 VSETATTR (temp_var
, (att_exported
| att_imported
));
436 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
438 VSETATTR (temp_var
, att_readonly
);
439 array_needs_making
= 1;
443 name
[char_index
] = '=';
444 /* temp_var can be NULL if it was an exported function with a syntax
445 error (a different bug, but it still shouldn't dump core). */
446 if (temp_var
&& function_p (temp_var
) == 0) /* XXX not yet */
448 CACHE_IMPORTSTR (temp_var
, name
);
454 /* Set up initial value of $_ */
455 temp_var
= set_if_not ("_", dollar_vars
[0]);
457 /* Remember this pid. */
458 dollar_dollar_pid
= getpid ();
460 /* Now make our own defaults in case the vars that we think are
461 important are missing. */
462 temp_var
= set_if_not ("PATH", DEFAULT_PATH_VALUE
);
464 set_auto_export (temp_var
); /* XXX */
467 temp_var
= set_if_not ("TERM", "dumb");
469 set_auto_export (temp_var
); /* XXX */
472 #if defined (__QNX__)
473 /* set node id -- don't import it from the environment */
476 # if defined (__QNXNTO__)
477 netmgr_ndtostr(ND2S_LOCAL_STR
, ND_LOCAL_NODE
, node_name
, sizeof(node_name
));
479 qnx_nidtostr (getnid (), node_name
, sizeof (node_name
));
481 temp_var
= bind_variable ("NODE", node_name
, 0);
482 set_auto_export (temp_var
);
486 /* set up the prompts. */
487 if (interactive_shell
)
489 #if defined (PROMPT_STRING_DECODE)
490 set_if_not ("PS1", primary_prompt
);
492 if (current_user
.uid
== -1)
493 get_current_user_info ();
494 set_if_not ("PS1", current_user
.euid
== 0 ? "# " : primary_prompt
);
496 set_if_not ("PS2", secondary_prompt
);
498 set_if_not ("PS4", "+ ");
500 /* Don't allow IFS to be imported from the environment. */
501 temp_var
= bind_variable ("IFS", " \t\n", 0);
504 /* Magic machine types. Pretty convenient. */
507 /* Default MAILCHECK for interactive shells. Defer the creation of a
508 default MAILPATH until the startup files are read, because MAIL
509 names a mail file if MAILPATH is not set, and we should provide a
510 default only if neither is set. */
511 if (interactive_shell
)
513 temp_var
= set_if_not ("MAILCHECK", posixly_correct
? "600" : "60");
514 VSETATTR (temp_var
, att_integer
);
517 /* Do some things with shell level. */
518 initialize_shell_level ();
522 /* Initialize the `getopts' stuff. */
523 temp_var
= bind_variable ("OPTIND", "1", 0);
524 VSETATTR (temp_var
, att_integer
);
526 bind_variable ("OPTERR", "1", 0);
529 if (login_shell
== 1 && posixly_correct
== 0)
532 /* Get the full pathname to THIS shell, and set the BASH variable
534 name
= get_bash_name ();
535 temp_var
= bind_variable ("BASH", name
, 0);
538 /* Make the exported environment variable SHELL be the user's login
539 shell. Note that the `tset' command looks at this variable
540 to determine what style of commands to output; if it ends in "csh",
541 then C-shell commands are output, else Bourne shell commands. */
544 /* Make a variable called BASH_VERSION which contains the version info. */
545 bind_variable ("BASH_VERSION", shell_version_string (), 0);
546 #if defined (ARRAY_VARS)
550 if (command_execution_string
)
551 bind_variable ("BASH_EXECUTION_STRING", command_execution_string
, 0);
553 /* Find out if we're supposed to be in Posix.2 mode via an
554 environment variable. */
555 temp_var
= find_variable ("POSIXLY_CORRECT");
557 temp_var
= find_variable ("POSIX_PEDANTIC");
558 if (temp_var
&& imported_p (temp_var
))
559 sv_strict_posix (temp_var
->name
);
561 #if defined (HISTORY)
562 /* Set history variables to defaults, and then do whatever we would
563 do if the variable had just been set. Do this only in the case
564 that we are remembering commands on the history list. */
565 if (remember_on_history
)
567 name
= bash_tilde_expand (posixly_correct
? "~/.sh_history" : "~/.bash_history", 0);
569 set_if_not ("HISTFILE", name
);
574 /* Seed the random number generator. */
577 /* Handle some "special" variables that we may have inherited from a
579 if (interactive_shell
)
581 temp_var
= find_variable ("IGNOREEOF");
583 temp_var
= find_variable ("ignoreeof");
584 if (temp_var
&& imported_p (temp_var
))
585 sv_ignoreeof (temp_var
->name
);
588 #if defined (HISTORY)
589 if (interactive_shell
&& remember_on_history
)
591 sv_history_control ("HISTCONTROL");
592 sv_histignore ("HISTIGNORE");
593 sv_histtimefmt ("HISTTIMEFORMAT");
597 #if defined (READLINE) && defined (STRICT_POSIX)
598 /* POSIXLY_CORRECT will only be 1 here if the shell was compiled
600 if (interactive_shell
&& posixly_correct
&& no_line_editing
== 0)
601 rl_prefer_env_winsize
= 1;
602 #endif /* READLINE && STRICT_POSIX */
607 * I'm tired of the arguing and bug reports. Bash now leaves SSH_CLIENT
608 * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in
609 * isnetconn() to avoid running the startup files more often than wanted.
610 * That will, of course, only work if the user's login shell is bash, so
611 * I've made that behavior conditional on SSH_SOURCE_BASHRC being defined
615 temp_var
= find_variable ("SSH_CLIENT");
616 if (temp_var
&& imported_p (temp_var
))
618 VUNSETATTR (temp_var
, att_exported
);
619 array_needs_making
= 1;
621 temp_var
= find_variable ("SSH2_CLIENT");
622 if (temp_var
&& imported_p (temp_var
))
624 VUNSETATTR (temp_var
, att_exported
);
625 array_needs_making
= 1;
629 /* Get the user's real and effective user ids. */
632 temp_var
= find_variable ("BASH_XTRACEFD");
633 if (temp_var
&& imported_p (temp_var
))
634 sv_xtracefd (temp_var
->name
);
636 /* Initialize the dynamic variables, and seed their values. */
637 initialize_dynamic_variables ();
640 /* **************************************************************** */
642 /* Setting values for special shell variables */
644 /* **************************************************************** */
651 temp_var
= set_if_not ("HOSTTYPE", HOSTTYPE
);
652 temp_var
= set_if_not ("OSTYPE", OSTYPE
);
653 temp_var
= set_if_not ("MACHTYPE", MACHTYPE
);
655 temp_var
= set_if_not ("HOSTNAME", current_host_name
);
658 /* Set $HOME to the information in the password file if we didn't get
659 it from the environment. */
661 /* This function is not static so the tilde and readline libraries can
666 if (current_user
.home_dir
== 0)
667 get_current_user_info ();
668 return current_user
.home_dir
;
676 temp_var
= find_variable ("HOME");
678 temp_var
= bind_variable ("HOME", sh_get_home_dir (), 0);
680 VSETATTR (temp_var
, att_exported
);
684 /* Set $SHELL to the user's login shell if it is not already set. Call
685 get_current_user_info if we haven't already fetched the shell. */
691 temp_var
= find_variable ("SHELL");
694 if (current_user
.shell
== 0)
695 get_current_user_info ();
696 temp_var
= bind_variable ("SHELL", current_user
.shell
, 0);
699 VSETATTR (temp_var
, att_exported
);
708 if ((login_shell
== 1) && RELPATH(shell_name
))
710 if (current_user
.shell
== 0)
711 get_current_user_info ();
712 name
= savestring (current_user
.shell
);
714 else if (ABSPATH(shell_name
))
715 name
= savestring (shell_name
);
716 else if (shell_name
[0] == '.' && shell_name
[1] == '/')
718 /* Fast path for common case. */
722 cdir
= get_string_value ("PWD");
726 name
= (char *)xmalloc (len
+ strlen (shell_name
) + 1);
728 strcpy (name
+ len
, shell_name
+ 1);
731 name
= savestring (shell_name
);
738 tname
= find_user_command (shell_name
);
742 /* Try the current directory. If there is not an executable
743 there, just punt and use the login shell. */
744 s
= file_status (shell_name
);
747 tname
= make_absolute (shell_name
, get_string_value ("PWD"));
748 if (*shell_name
== '.')
750 name
= sh_canonpath (tname
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
761 if (current_user
.shell
== 0)
762 get_current_user_info ();
763 name
= savestring (current_user
.shell
);
768 name
= full_pathname (tname
);
777 adjust_shell_level (change
)
780 char new_level
[5], *old_SHLVL
;
784 old_SHLVL
= get_string_value ("SHLVL");
785 if (old_SHLVL
== 0 || *old_SHLVL
== '\0' || legal_number (old_SHLVL
, &old_level
) == 0)
788 shell_level
= old_level
+ change
;
791 else if (shell_level
> 1000)
793 internal_warning (_("shell level (%d) too high, resetting to 1"), shell_level
);
797 /* We don't need the full generality of itos here. */
798 if (shell_level
< 10)
800 new_level
[0] = shell_level
+ '0';
803 else if (shell_level
< 100)
805 new_level
[0] = (shell_level
/ 10) + '0';
806 new_level
[1] = (shell_level
% 10) + '0';
809 else if (shell_level
< 1000)
811 new_level
[0] = (shell_level
/ 100) + '0';
812 old_level
= shell_level
% 100;
813 new_level
[1] = (old_level
/ 10) + '0';
814 new_level
[2] = (old_level
% 10) + '0';
818 temp_var
= bind_variable ("SHLVL", new_level
, 0);
819 set_auto_export (temp_var
);
823 initialize_shell_level ()
825 adjust_shell_level (1);
828 /* If we got PWD from the environment, update our idea of the current
829 working directory. In any case, make sure that PWD exists before
830 checking it. It is possible for getcwd () to fail on shell startup,
831 and in that case, PWD would be undefined. If this is an interactive
832 login shell, see if $HOME is the current working directory, and if
833 that's not the same string as $PWD, set PWD=$HOME. */
838 SHELL_VAR
*temp_var
, *home_var
;
839 char *temp_string
, *home_string
;
841 home_var
= find_variable ("HOME");
842 home_string
= home_var
? value_cell (home_var
) : (char *)NULL
;
844 temp_var
= find_variable ("PWD");
845 if (temp_var
&& imported_p (temp_var
) &&
846 (temp_string
= value_cell (temp_var
)) &&
847 same_file (temp_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
848 set_working_directory (temp_string
);
849 else if (home_string
&& interactive_shell
&& login_shell
&&
850 same_file (home_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
852 set_working_directory (home_string
);
853 temp_var
= bind_variable ("PWD", home_string
, 0);
854 set_auto_export (temp_var
);
858 temp_string
= get_working_directory ("shell-init");
861 temp_var
= bind_variable ("PWD", temp_string
, 0);
862 set_auto_export (temp_var
);
867 /* According to the Single Unix Specification, v2, $OLDPWD is an
868 `environment variable' and therefore should be auto-exported.
869 Make a dummy invisible variable for OLDPWD, and mark it as exported. */
870 temp_var
= bind_variable ("OLDPWD", (char *)NULL
, 0);
871 VSETATTR (temp_var
, (att_exported
| att_invisible
));
874 /* Make a variable $PPID, which holds the pid of the shell's parent. */
878 char namebuf
[INT_STRLEN_BOUND(pid_t
) + 1], *name
;
881 name
= inttostr (getppid (), namebuf
, sizeof(namebuf
));
882 temp_var
= find_variable ("PPID");
884 VUNSETATTR (temp_var
, (att_readonly
| att_exported
));
885 temp_var
= bind_variable ("PPID", name
, 0);
886 VSETATTR (temp_var
, (att_readonly
| att_integer
));
892 char buff
[INT_STRLEN_BOUND(uid_t
) + 1], *b
;
893 register SHELL_VAR
*v
;
895 b
= inttostr (current_user
.uid
, buff
, sizeof (buff
));
896 v
= find_variable ("UID");
899 v
= bind_variable ("UID", b
, 0);
900 VSETATTR (v
, (att_readonly
| att_integer
));
903 if (current_user
.euid
!= current_user
.uid
)
904 b
= inttostr (current_user
.euid
, buff
, sizeof (buff
));
906 v
= find_variable ("EUID");
909 v
= bind_variable ("EUID", b
, 0);
910 VSETATTR (v
, (att_readonly
| att_integer
));
914 #if defined (ARRAY_VARS)
920 char *s
, d
[32], b
[INT_STRLEN_BOUND(int) + 1];
922 unbind_variable ("BASH_VERSINFO");
924 vv
= make_new_array_variable ("BASH_VERSINFO");
925 av
= array_cell (vv
);
926 strcpy (d
, dist_version
);
930 array_insert (av
, 0, d
);
931 array_insert (av
, 1, s
);
932 s
= inttostr (patch_level
, b
, sizeof (b
));
933 array_insert (av
, 2, s
);
934 s
= inttostr (build_version
, b
, sizeof (b
));
935 array_insert (av
, 3, s
);
936 array_insert (av
, 4, release_status
);
937 array_insert (av
, 5, MACHTYPE
);
939 VSETATTR (vv
, att_readonly
);
941 #endif /* ARRAY_VARS */
943 /* Set the environment variables $LINES and $COLUMNS in response to
944 a window size change. */
946 sh_set_lines_and_columns (lines
, cols
)
949 char val
[INT_STRLEN_BOUND(int) + 1], *v
;
951 #if defined (READLINE)
952 /* If we are currently assigning to LINES or COLUMNS, don't do anything. */
953 if (winsize_assignment
)
957 v
= inttostr (lines
, val
, sizeof (val
));
958 bind_variable ("LINES", v
, 0);
960 v
= inttostr (cols
, val
, sizeof (val
));
961 bind_variable ("COLUMNS", v
, 0);
964 /* **************************************************************** */
966 /* Printing variables and values */
968 /* **************************************************************** */
970 /* Print LIST (a list of shell variables) to stdout in such a way that
971 they can be read back in. */
973 print_var_list (list
)
974 register SHELL_VAR
**list
;
977 register SHELL_VAR
*var
;
979 for (i
= 0; list
&& (var
= list
[i
]); i
++)
980 if (invisible_p (var
) == 0)
981 print_assignment (var
);
984 /* Print LIST (a list of shell functions) to stdout in such a way that
985 they can be read back in. */
987 print_func_list (list
)
988 register SHELL_VAR
**list
;
991 register SHELL_VAR
*var
;
993 for (i
= 0; list
&& (var
= list
[i
]); i
++)
995 printf ("%s ", var
->name
);
996 print_var_function (var
);
1001 /* Print the value of a single SHELL_VAR. No newline is
1002 output, but the variable is printed in such a way that
1003 it can be read back in. */
1005 print_assignment (var
)
1008 if (var_isset (var
) == 0)
1011 if (function_p (var
))
1013 printf ("%s", var
->name
);
1014 print_var_function (var
);
1017 #if defined (ARRAY_VARS)
1018 else if (array_p (var
))
1019 print_array_assignment (var
, 0);
1020 else if (assoc_p (var
))
1021 print_assoc_assignment (var
, 0);
1022 #endif /* ARRAY_VARS */
1025 printf ("%s=", var
->name
);
1026 print_var_value (var
, 1);
1031 /* Print the value cell of VAR, a shell variable. Do not print
1032 the name, nor leading/trailing newline. If QUOTE is non-zero,
1033 and the value contains shell metacharacters, quote the value
1034 in such a way that it can be read back in. */
1036 print_var_value (var
, quote
)
1042 if (var_isset (var
) == 0)
1045 if (quote
&& posixly_correct
== 0 && ansic_shouldquote (value_cell (var
)))
1047 t
= ansic_quote (value_cell (var
), 0, (int *)0);
1051 else if (quote
&& sh_contains_shell_metas (value_cell (var
)))
1053 t
= sh_single_quote (value_cell (var
));
1058 printf ("%s", value_cell (var
));
1061 /* Print the function cell of VAR, a shell variable. Do not
1062 print the name, nor leading/trailing newline. */
1064 print_var_function (var
)
1069 if (function_p (var
) && var_isset (var
))
1071 x
= named_function_string ((char *)NULL
, function_cell(var
), FUNC_MULTILINE
|FUNC_EXTERNAL
);
1076 /* **************************************************************** */
1078 /* Dynamic Variables */
1080 /* **************************************************************** */
1082 /* DYNAMIC VARIABLES
1084 These are variables whose values are generated anew each time they are
1085 referenced. These are implemented using a pair of function pointers
1086 in the struct variable: assign_func, which is called from bind_variable
1087 and, if arrays are compiled into the shell, some of the functions in
1088 arrayfunc.c, and dynamic_value, which is called from find_variable.
1090 assign_func is called from bind_variable_internal, if
1091 bind_variable_internal discovers that the variable being assigned to
1092 has such a function. The function is called as
1093 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value, ind)
1094 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
1095 is usually ENTRY (self). IND is an index for an array variable, and
1098 dynamic_value is called from find_variable_internal to return a `new'
1099 value for the specified dynamic varible. If this function is NULL,
1100 the variable is treated as a `normal' shell variable. If it is not,
1101 however, then this function is called like this:
1102 tempvar = (*(var->dynamic_value)) (var);
1104 Sometimes `tempvar' will replace the value of `var'. Other times, the
1105 shell will simply use the string value. Pretty object-oriented, huh?
1107 Be warned, though: if you `unset' a special variable, it loses its
1108 special meaning, even if you subsequently set it.
1110 The special assignment code would probably have been better put in
1111 subst.c: do_assignment_internal, in the same style as
1112 stupidly_hack_special_variables, but I wanted the changes as
1113 localized as possible. */
1115 #define INIT_DYNAMIC_VAR(var, val, gfunc, afunc) \
1118 v = bind_variable (var, (val), 0); \
1119 v->dynamic_value = gfunc; \
1120 v->assign_func = afunc; \
1124 #define INIT_DYNAMIC_ARRAY_VAR(var, gfunc, afunc) \
1127 v = make_new_array_variable (var); \
1128 v->dynamic_value = gfunc; \
1129 v->assign_func = afunc; \
1133 #define INIT_DYNAMIC_ASSOC_VAR(var, gfunc, afunc) \
1136 v = make_new_assoc_variable (var); \
1137 v->dynamic_value = gfunc; \
1138 v->assign_func = afunc; \
1143 null_assign (self
, value
, unused
, key
)
1152 #if defined (ARRAY_VARS)
1154 null_array_assign (self
, value
, ind
, key
)
1164 /* Degenerate `dynamic_value' function; just returns what's passed without
1173 #if defined (ARRAY_VARS)
1174 /* A generic dynamic array variable initializer. Initialize array variable
1175 NAME with dynamic value function GETFUNC and assignment function SETFUNC. */
1177 init_dynamic_array_var (name
, getfunc
, setfunc
, attrs
)
1179 sh_var_value_func_t
*getfunc
;
1180 sh_var_assign_func_t
*setfunc
;
1185 v
= find_variable (name
);
1188 INIT_DYNAMIC_ARRAY_VAR (name
, getfunc
, setfunc
);
1190 VSETATTR (v
, attrs
);
1195 init_dynamic_assoc_var (name
, getfunc
, setfunc
, attrs
)
1197 sh_var_value_func_t
*getfunc
;
1198 sh_var_assign_func_t
*setfunc
;
1203 v
= find_variable (name
);
1206 INIT_DYNAMIC_ASSOC_VAR (name
, getfunc
, setfunc
);
1208 VSETATTR (v
, attrs
);
1213 /* The value of $SECONDS. This is the number of seconds since shell
1214 invocation, or, the number of seconds since the last assignment + the
1215 value of the last assignment. */
1216 static intmax_t seconds_value_assigned
;
1219 assign_seconds (self
, value
, unused
, key
)
1225 if (legal_number (value
, &seconds_value_assigned
) == 0)
1226 seconds_value_assigned
= 0;
1227 shell_start_time
= NOW
;
1235 time_t time_since_start
;
1238 time_since_start
= NOW
- shell_start_time
;
1239 p
= itos(seconds_value_assigned
+ time_since_start
);
1241 FREE (value_cell (var
));
1243 VSETATTR (var
, att_integer
);
1244 var_setvalue (var
, p
);
1253 v
= find_variable ("SECONDS");
1256 if (legal_number (value_cell(v
), &seconds_value_assigned
) == 0)
1257 seconds_value_assigned
= 0;
1259 INIT_DYNAMIC_VAR ("SECONDS", (v
? value_cell (v
) : (char *)NULL
), get_seconds
, assign_seconds
);
1263 /* The random number seed. You can change this by setting RANDOM. */
1264 static unsigned long rseed
= 1;
1265 static int last_random_value
;
1266 static int seeded_subshell
= 0;
1268 /* A linear congruential random number generator based on the example
1269 one in the ANSI C standard. This one isn't very good, but a more
1270 complicated one is overkill. */
1272 /* Returns a pseudo-random number between 0 and 32767. */
1276 /* From "Random number generators: good ones are hard to find",
1277 Park and Miller, Communications of the ACM, vol. 31, no. 10,
1278 October 1988, p. 1195. filtered through FreeBSD */
1281 /* Can't seed with 0. */
1286 rseed
= 16807 * l
- 2836 * h
;
1289 rseed
+= 0x7fffffff;
1291 return ((unsigned int)(rseed
& 32767)); /* was % 32768 */
1294 /* Set the random number generator seed to SEED. */
1300 last_random_value
= 0;
1308 gettimeofday (&tv
, NULL
);
1309 sbrand (tv
.tv_sec
^ tv
.tv_usec
^ getpid ());
1313 assign_random (self
, value
, unused
, key
)
1319 sbrand (strtoul (value
, (char **)NULL
, 10));
1320 if (subshell_environment
)
1321 seeded_subshell
= getpid ();
1326 get_random_number ()
1330 /* Reset for command and process substitution. */
1332 if (subshell_environment
&& seeded_subshell
!= pid
)
1335 seeded_subshell
= pid
;
1340 while (rv
== last_random_value
);
1351 rv
= get_random_number ();
1352 last_random_value
= rv
;
1355 FREE (value_cell (var
));
1357 VSETATTR (var
, att_integer
);
1358 var_setvalue (var
, p
);
1363 assign_lineno (var
, value
, unused
, key
)
1371 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1373 line_number
= line_number_base
= new_value
;
1377 /* Function which returns the current line number. */
1385 ln
= executing_line_number ();
1387 FREE (value_cell (var
));
1388 var_setvalue (var
, p
);
1393 assign_subshell (var
, value
, unused
, key
)
1401 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1403 subshell_level
= new_value
;
1413 p
= itos (subshell_level
);
1414 FREE (value_cell (var
));
1415 var_setvalue (var
, p
);
1429 FREE (value_cell (var
));
1430 VSETATTR (var
, att_integer
|att_readonly
);
1431 var_setvalue (var
, p
);
1436 get_bash_command (var
)
1441 if (the_printed_command_except_trap
)
1442 p
= savestring (the_printed_command_except_trap
);
1445 p
= (char *)xmalloc (1);
1448 FREE (value_cell (var
));
1449 var_setvalue (var
, p
);
1453 #if defined (HISTORY)
1460 p
= itos (history_number ());
1461 FREE (value_cell (var
));
1462 var_setvalue (var
, p
);
1467 #if defined (READLINE)
1468 /* When this function returns, VAR->value points to malloced memory. */
1470 get_comp_wordbreaks (var
)
1473 /* If we don't have anything yet, assign a default value. */
1474 if (rl_completer_word_break_characters
== 0 && bash_readline_initialized
== 0)
1475 enable_hostname_completion (perform_hostname_completion
);
1477 FREE (value_cell (var
));
1478 var_setvalue (var
, savestring (rl_completer_word_break_characters
));
1483 /* When this function returns, rl_completer_word_break_characters points to
1486 assign_comp_wordbreaks (self
, value
, unused
, key
)
1492 if (rl_completer_word_break_characters
&&
1493 rl_completer_word_break_characters
!= rl_basic_word_break_characters
)
1494 free (rl_completer_word_break_characters
);
1496 rl_completer_word_break_characters
= savestring (value
);
1499 #endif /* READLINE */
1501 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1503 assign_dirstack (self
, value
, ind
, key
)
1509 set_dirstack_element (ind
, 1, value
);
1520 l
= get_directory_stack (0);
1521 a
= array_from_word_list (l
);
1522 array_dispose (array_cell (self
));
1524 var_setarray (self
, a
);
1527 #endif /* PUSHD AND POPD && ARRAY_VARS */
1529 #if defined (ARRAY_VARS)
1530 /* We don't want to initialize the group set with a call to getgroups()
1531 unless we're asked to, but we only want to do it once. */
1539 static char **group_set
= (char **)NULL
;
1543 group_set
= get_group_list (&ng
);
1544 a
= array_cell (self
);
1545 for (i
= 0; i
< ng
; i
++)
1546 array_insert (a
, i
, group_set
[i
]);
1552 build_hashcmd (self
)
1558 BUCKET_CONTENTS
*item
;
1560 h
= assoc_cell (self
);
1564 if (hashed_filenames
== 0 || HASH_ENTRIES (hashed_filenames
) == 0)
1566 var_setvalue (self
, (char *)NULL
);
1570 h
= assoc_create (hashed_filenames
->nbuckets
);
1571 for (i
= 0; i
< hashed_filenames
->nbuckets
; i
++)
1573 for (item
= hash_items (i
, hashed_filenames
); item
; item
= item
->next
)
1575 k
= savestring (item
->key
);
1576 v
= pathdata(item
)->path
;
1577 assoc_insert (h
, k
, v
);
1581 var_setvalue (self
, (char *)h
);
1589 build_hashcmd (self
);
1594 assign_hashcmd (self
, value
, ind
, key
)
1600 phash_insert (key
, value
, 0, 0);
1601 return (build_hashcmd (self
));
1606 build_aliasvar (self
)
1612 BUCKET_CONTENTS
*item
;
1614 h
= assoc_cell (self
);
1618 if (aliases
== 0 || HASH_ENTRIES (aliases
) == 0)
1620 var_setvalue (self
, (char *)NULL
);
1624 h
= assoc_create (aliases
->nbuckets
);
1625 for (i
= 0; i
< aliases
->nbuckets
; i
++)
1627 for (item
= hash_items (i
, aliases
); item
; item
= item
->next
)
1629 k
= savestring (item
->key
);
1630 v
= ((alias_t
*)(item
->data
))->value
;
1631 assoc_insert (h
, k
, v
);
1635 var_setvalue (self
, (char *)h
);
1643 build_aliasvar (self
);
1648 assign_aliasvar (self
, value
, ind
, key
)
1654 add_alias (key
, value
);
1655 return (build_aliasvar (self
));
1659 #endif /* ARRAY_VARS */
1661 /* If ARRAY_VARS is not defined, this just returns the name of any
1662 currently-executing function. If we have arrays, it's a call stack. */
1667 #if ! defined (ARRAY_VARS)
1669 if (variable_context
&& this_shell_function
)
1671 FREE (value_cell (self
));
1672 t
= savestring (this_shell_function
->name
);
1673 var_setvalue (self
, t
);
1680 make_funcname_visible (on_or_off
)
1685 v
= find_variable ("FUNCNAME");
1686 if (v
== 0 || v
->dynamic_value
== 0)
1690 VUNSETATTR (v
, att_invisible
);
1692 VSETATTR (v
, att_invisible
);
1696 init_funcname_var ()
1700 v
= find_variable ("FUNCNAME");
1703 #if defined (ARRAY_VARS)
1704 INIT_DYNAMIC_ARRAY_VAR ("FUNCNAME", get_funcname
, null_array_assign
);
1706 INIT_DYNAMIC_VAR ("FUNCNAME", (char *)NULL
, get_funcname
, null_assign
);
1708 VSETATTR (v
, att_invisible
|att_noassign
);
1713 initialize_dynamic_variables ()
1717 v
= init_seconds_var ();
1719 INIT_DYNAMIC_VAR ("BASH_COMMAND", (char *)NULL
, get_bash_command
, (sh_var_assign_func_t
*)NULL
);
1720 INIT_DYNAMIC_VAR ("BASH_SUBSHELL", (char *)NULL
, get_subshell
, assign_subshell
);
1722 INIT_DYNAMIC_VAR ("RANDOM", (char *)NULL
, get_random
, assign_random
);
1723 VSETATTR (v
, att_integer
);
1724 INIT_DYNAMIC_VAR ("LINENO", (char *)NULL
, get_lineno
, assign_lineno
);
1725 VSETATTR (v
, att_integer
);
1727 INIT_DYNAMIC_VAR ("BASHPID", (char *)NULL
, get_bashpid
, null_assign
);
1728 VSETATTR (v
, att_integer
|att_readonly
);
1730 #if defined (HISTORY)
1731 INIT_DYNAMIC_VAR ("HISTCMD", (char *)NULL
, get_histcmd
, (sh_var_assign_func_t
*)NULL
);
1732 VSETATTR (v
, att_integer
);
1735 #if defined (READLINE)
1736 INIT_DYNAMIC_VAR ("COMP_WORDBREAKS", (char *)NULL
, get_comp_wordbreaks
, assign_comp_wordbreaks
);
1739 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1740 v
= init_dynamic_array_var ("DIRSTACK", get_dirstack
, assign_dirstack
, 0);
1741 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1743 #if defined (ARRAY_VARS)
1744 v
= init_dynamic_array_var ("GROUPS", get_groupset
, null_array_assign
, att_noassign
);
1746 # if defined (DEBUGGER)
1747 v
= init_dynamic_array_var ("BASH_ARGC", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1748 v
= init_dynamic_array_var ("BASH_ARGV", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1749 # endif /* DEBUGGER */
1750 v
= init_dynamic_array_var ("BASH_SOURCE", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1751 v
= init_dynamic_array_var ("BASH_LINENO", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1753 v
= init_dynamic_assoc_var ("BASH_CMDS", get_hashcmd
, assign_hashcmd
, att_nofree
);
1754 # if defined (ALIAS)
1755 v
= init_dynamic_assoc_var ("BASH_ALIASES", get_aliasvar
, assign_aliasvar
, att_nofree
);
1759 v
= init_funcname_var ();
1762 /* **************************************************************** */
1764 /* Retrieving variables and values */
1766 /* **************************************************************** */
1768 /* How to get a pointer to the shell variable or function named NAME.
1769 HASHED_VARS is a pointer to the hash table containing the list
1770 of interest (either variables or functions). */
1773 hash_lookup (name
, hashed_vars
)
1775 HASH_TABLE
*hashed_vars
;
1777 BUCKET_CONTENTS
*bucket
;
1779 bucket
= hash_search (name
, hashed_vars
, 0);
1780 /* If we find the name in HASHED_VARS, set LAST_TABLE_SEARCHED to that
1783 last_table_searched
= hashed_vars
;
1784 return (bucket
? (SHELL_VAR
*)bucket
->data
: (SHELL_VAR
*)NULL
);
1788 var_lookup (name
, vcontext
)
1790 VAR_CONTEXT
*vcontext
;
1795 v
= (SHELL_VAR
*)NULL
;
1796 for (vc
= vcontext
; vc
; vc
= vc
->down
)
1797 if (v
= hash_lookup (name
, vc
->table
))
1803 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
1804 then also search the temporarily built list of exported variables.
1805 The lookup order is:
1807 shell_variables list
1811 find_variable_internal (name
, force_tempenv
)
1819 var
= (SHELL_VAR
*)NULL
;
1821 /* If explicitly requested, first look in the temporary environment for
1822 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
1823 to get the `exported' value of $foo. This happens if we are executing
1824 a function or builtin, or if we are looking up a variable in a
1825 "subshell environment". */
1826 search_tempenv
= force_tempenv
|| (expanding_redir
== 0 && subshell_environment
);
1828 if (search_tempenv
&& temporary_env
)
1829 var
= hash_lookup (name
, temporary_env
);
1831 vc
= shell_variables
;
1833 if (search_tempenv
== 0 && /* (subshell_environment & SUBSHELL_COMSUB) && */
1835 (this_shell_builtin
== eval_builtin
|| this_shell_builtin
== command_builtin
))
1837 itrace("find_variable_internal: search_tempenv == 0: skipping VC_BLTNENV");
1838 while (vc
&& (vc
->flags
& VC_BLTNENV
))
1841 vc
= shell_variables
;
1846 var
= var_lookup (name
, vc
);
1849 return ((SHELL_VAR
*)NULL
);
1851 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
1854 /* Look up and resolve the chain of nameref variables starting at V all the
1855 way to NULL or non-nameref. */
1857 find_variable_nameref (v
)
1862 SHELL_VAR
*orig
, *oldv
;
1866 while (v
&& nameref_p (v
))
1869 if (level
> NAMEREF_MAX
)
1870 return ((SHELL_VAR
*)0); /* error message here? */
1871 newname
= nameref_cell (v
);
1872 if (newname
== 0 || *newname
== '\0')
1873 return ((SHELL_VAR
*)0);
1875 v
= find_variable_internal (newname
, (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
)));
1876 if (v
== orig
|| v
== oldv
)
1878 internal_warning (_("%s: circular name reference"), orig
->name
);
1879 return ((SHELL_VAR
*)0);
1885 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
1887 find_variable_last_nameref (name
)
1894 nv
= v
= find_variable_noref (name
);
1896 while (v
&& nameref_p (v
))
1899 if (level
> NAMEREF_MAX
)
1900 return ((SHELL_VAR
*)0); /* error message here? */
1901 newname
= nameref_cell (v
);
1902 if (newname
== 0 || *newname
== '\0')
1903 return ((SHELL_VAR
*)0);
1905 v
= find_variable_internal (newname
, (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
)));
1910 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
1912 find_global_variable_last_nameref (name
)
1919 nv
= v
= find_global_variable_noref (name
);
1921 while (v
&& nameref_p (v
))
1924 if (level
> NAMEREF_MAX
)
1925 return ((SHELL_VAR
*)0); /* error message here? */
1926 newname
= nameref_cell (v
);
1927 if (newname
== 0 || *newname
== '\0')
1928 return ((SHELL_VAR
*)0);
1930 v
= find_global_variable_noref (newname
);
1936 find_nameref_at_context (v
, vc
)
1940 SHELL_VAR
*nv
, *nv2
;
1947 while (nv
&& nameref_p (nv
))
1950 if (level
> NAMEREF_MAX
)
1951 return ((SHELL_VAR
*)NULL
);
1952 newname
= nameref_cell (nv
);
1953 if (newname
== 0 || *newname
== '\0')
1954 return ((SHELL_VAR
*)NULL
);
1955 nv2
= hash_lookup (newname
, vc
->table
);
1963 /* Do nameref resolution from the VC, which is the local context for some
1964 function or builtin, `up' the chain to the global variables context. If
1965 NVCP is not NULL, return the variable context where we finally ended the
1966 nameref resolution (so the bind_variable_internal can use the correct
1967 variable context and hash table). */
1969 find_variable_nameref_context (v
, vc
, nvcp
)
1974 SHELL_VAR
*nv
, *nv2
;
1977 /* Look starting at the current context all the way `up' */
1978 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
1980 nv2
= find_nameref_at_context (nv
, nvc
);
1986 if (nameref_p (nv
) == 0)
1989 return (nameref_p (nv
) ? (SHELL_VAR
*)NULL
: nv
);
1992 /* Do nameref resolution from the VC, which is the local context for some
1993 function or builtin, `up' the chain to the global variables context. If
1994 NVCP is not NULL, return the variable context where we finally ended the
1995 nameref resolution (so the bind_variable_internal can use the correct
1996 variable context and hash table). */
1998 find_variable_last_nameref_context (v
, vc
, nvcp
)
2003 SHELL_VAR
*nv
, *nv2
;
2006 /* Look starting at the current context all the way `up' */
2007 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
2009 nv2
= find_nameref_at_context (nv
, nvc
);
2016 return (nameref_p (nv
) ? nv
: (SHELL_VAR
*)NULL
);
2019 /* Find a variable, forcing a search of the temporary environment first */
2021 find_variable_tempenv (name
)
2026 var
= find_variable_internal (name
, 1);
2027 if (var
&& nameref_p (var
))
2028 var
= find_variable_nameref (var
);
2032 /* Find a variable, not forcing a search of the temporary environment first */
2034 find_variable_notempenv (name
)
2039 var
= find_variable_internal (name
, 0);
2040 if (var
&& nameref_p (var
))
2041 var
= find_variable_nameref (var
);
2046 find_global_variable (name
)
2051 var
= var_lookup (name
, global_variables
);
2052 if (var
&& nameref_p (var
))
2053 var
= find_variable_nameref (var
);
2056 return ((SHELL_VAR
*)NULL
);
2058 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2062 find_global_variable_noref (name
)
2067 var
= var_lookup (name
, global_variables
);
2070 return ((SHELL_VAR
*)NULL
);
2072 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2076 find_shell_variable (name
)
2081 var
= var_lookup (name
, shell_variables
);
2082 if (var
&& nameref_p (var
))
2083 var
= find_variable_nameref (var
);
2086 return ((SHELL_VAR
*)NULL
);
2088 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2091 /* Look up the variable entry named NAME. Returns the entry or NULL. */
2093 find_variable (name
)
2098 last_table_searched
= 0;
2099 v
= find_variable_internal (name
, (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
)));
2100 if (v
&& nameref_p (v
))
2101 v
= find_variable_nameref (v
);
2106 find_variable_noref (name
)
2111 v
= find_variable_internal (name
, (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
)));
2115 /* Look up the function entry whose name matches STRING.
2116 Returns the entry or NULL. */
2118 find_function (name
)
2121 return (hash_lookup (name
, shell_functions
));
2124 /* Find the function definition for the shell function named NAME. Returns
2125 the entry or NULL. */
2127 find_function_def (name
)
2130 #if defined (DEBUGGER)
2131 return ((FUNCTION_DEF
*)hash_lookup (name
, shell_function_defs
));
2133 return ((FUNCTION_DEF
*)0);
2137 /* Return the value of VAR. VAR is assumed to have been the result of a
2138 lookup without any subscript, if arrays are compiled into the shell. */
2140 get_variable_value (var
)
2144 return ((char *)NULL
);
2145 #if defined (ARRAY_VARS)
2146 else if (array_p (var
))
2147 return (array_reference (array_cell (var
), 0));
2148 else if (assoc_p (var
))
2149 return (assoc_reference (assoc_cell (var
), "0"));
2152 return (value_cell (var
));
2155 /* Return the string value of a variable. Return NULL if the variable
2156 doesn't exist. Don't cons a new string. This is a potential memory
2157 leak if the variable is found in the temporary environment. Since
2158 functions and variables have separate name spaces, returns NULL if
2159 var_name is a shell function only. */
2161 get_string_value (var_name
)
2162 const char *var_name
;
2166 var
= find_variable (var_name
);
2167 return ((var
) ? get_variable_value (var
) : (char *)NULL
);
2170 /* This is present for use by the tilde and readline libraries. */
2172 sh_get_env_value (v
)
2175 return get_string_value (v
);
2178 /* **************************************************************** */
2180 /* Creating and setting variables */
2182 /* **************************************************************** */
2184 /* Set NAME to VALUE if NAME has no value. */
2186 set_if_not (name
, value
)
2191 if (shell_variables
== 0)
2192 create_variable_tables ();
2194 v
= find_variable (name
);
2196 v
= bind_variable_internal (name
, value
, global_variables
->table
, HASH_NOSRCH
, 0);
2200 /* Create a local variable referenced by NAME. */
2202 make_local_variable (name
)
2205 SHELL_VAR
*new_var
, *old_var
;
2210 /* local foo; local foo; is a no-op. */
2211 old_var
= find_variable (name
);
2212 if (old_var
&& local_p (old_var
) && old_var
->context
== variable_context
)
2215 was_tmpvar
= old_var
&& tempvar_p (old_var
);
2216 /* If we're making a local variable in a shell function, the temporary env
2217 has already been merged into the function's variable context stack. We
2218 can assume that a temporary var in the same context appears in the same
2219 VAR_CONTEXT and can safely be returned without creating a new variable
2220 (which results in duplicate names in the same VAR_CONTEXT->table */
2221 /* We can't just test tmpvar_p because variables in the temporary env given
2222 to a shell function appear in the function's local variable VAR_CONTEXT
2223 but retain their tempvar attribute. We want temporary variables that are
2224 found in temporary_env, hence the test for last_table_searched, which is
2225 set in hash_lookup and only (so far) checked here. */
2226 if (was_tmpvar
&& old_var
->context
== variable_context
&& last_table_searched
!= temporary_env
)
2228 VUNSETATTR (old_var
, att_invisible
);
2232 tmp_value
= value_cell (old_var
);
2234 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2235 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
2240 internal_error (_("make_local_variable: no function context at current scope"));
2241 return ((SHELL_VAR
*)NULL
);
2243 else if (vc
->table
== 0)
2244 vc
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
2246 /* Since this is called only from the local/declare/typeset code, we can
2247 call builtin_error here without worry (of course, it will also work
2248 for anything that sets this_command_name). Variables with the `noassign'
2249 attribute may not be made local. The test against old_var's context
2250 level is to disallow local copies of readonly global variables (since I
2251 believe that this could be a security hole). Readonly copies of calling
2252 function local variables are OK. */
2253 if (old_var
&& (noassign_p (old_var
) ||
2254 (readonly_p (old_var
) && old_var
->context
== 0)))
2256 if (readonly_p (old_var
))
2258 else if (noassign_p (old_var
))
2259 builtin_error (_("%s: variable may not be assigned value"), name
);
2261 /* Let noassign variables through with a warning */
2262 if (readonly_p (old_var
))
2264 return ((SHELL_VAR
*)NULL
);
2268 new_var
= make_new_variable (name
, vc
->table
);
2271 new_var
= make_new_variable (name
, vc
->table
);
2273 /* If we found this variable in one of the temporary environments,
2274 inherit its value. Watch to see if this causes problems with
2275 things like `x=4 local x'. XXX - see above for temporary env
2276 variables with the same context level as variable_context */
2277 /* XXX - we should only do this if the variable is not an array. */
2279 var_setvalue (new_var
, savestring (tmp_value
));
2281 new_var
->attributes
= exported_p (old_var
) ? att_exported
: 0;
2284 vc
->flags
|= VC_HASLOCAL
;
2286 new_var
->context
= variable_context
;
2287 VSETATTR (new_var
, att_local
);
2292 if (was_tmpvar
== 0)
2293 VSETATTR (new_var
, att_invisible
); /* XXX */
2297 /* Create a new shell variable with name NAME. */
2299 new_shell_variable (name
)
2304 entry
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
2306 entry
->name
= savestring (name
);
2307 var_setvalue (entry
, (char *)NULL
);
2308 CLEAR_EXPORTSTR (entry
);
2310 entry
->dynamic_value
= (sh_var_value_func_t
*)NULL
;
2311 entry
->assign_func
= (sh_var_assign_func_t
*)NULL
;
2313 entry
->attributes
= 0;
2315 /* Always assume variables are to be made at toplevel!
2316 make_local_variable has the responsibility of changing the
2317 variable context. */
2323 /* Create a new shell variable with name NAME and add it to the hash table
2326 make_new_variable (name
, table
)
2331 BUCKET_CONTENTS
*elt
;
2333 entry
= new_shell_variable (name
);
2335 /* Make sure we have a shell_variables hash table to add to. */
2336 if (shell_variables
== 0)
2337 create_variable_tables ();
2339 elt
= hash_insert (savestring (name
), table
, HASH_NOSRCH
);
2340 elt
->data
= (PTR_T
)entry
;
2345 #if defined (ARRAY_VARS)
2347 make_new_array_variable (name
)
2353 entry
= make_new_variable (name
, global_variables
->table
);
2354 array
= array_create ();
2356 var_setarray (entry
, array
);
2357 VSETATTR (entry
, att_array
);
2362 make_local_array_variable (name
, assoc_ok
)
2369 var
= make_local_variable (name
);
2370 if (var
== 0 || array_p (var
) || (assoc_ok
&& assoc_p (var
)))
2373 array
= array_create ();
2375 dispose_variable_value (var
);
2376 var_setarray (var
, array
);
2377 VSETATTR (var
, att_array
);
2382 make_new_assoc_variable (name
)
2388 entry
= make_new_variable (name
, global_variables
->table
);
2389 hash
= assoc_create (0);
2391 var_setassoc (entry
, hash
);
2392 VSETATTR (entry
, att_assoc
);
2397 make_local_assoc_variable (name
)
2403 var
= make_local_variable (name
);
2404 if (var
== 0 || assoc_p (var
))
2407 dispose_variable_value (var
);
2408 hash
= assoc_create (0);
2410 var_setassoc (var
, hash
);
2411 VSETATTR (var
, att_assoc
);
2417 make_variable_value (var
, value
, flags
)
2422 char *retval
, *oval
;
2423 intmax_t lval
, rval
;
2424 int expok
, olen
, op
;
2426 /* If this variable has had its type set to integer (via `declare -i'),
2427 then do expression evaluation on it and store the result. The
2428 functions in expr.c (evalexp()) and bind_int_variable() are responsible
2429 for turning off the integer flag if they don't want further
2431 if (integer_p (var
))
2433 if (flags
& ASS_APPEND
)
2435 oval
= value_cell (var
);
2436 lval
= evalexp (oval
, &expok
); /* ksh93 seems to do this */
2439 top_level_cleanup ();
2440 jump_to_top_level (DISCARD
);
2443 rval
= evalexp (value
, &expok
);
2446 top_level_cleanup ();
2447 jump_to_top_level (DISCARD
);
2449 /* This can be fooled if the variable's value changes while evaluating
2450 `rval'. We can change it if we move the evaluation of lval to here. */
2451 if (flags
& ASS_APPEND
)
2453 retval
= itos (rval
);
2455 #if defined (CASEMOD_ATTRS)
2456 else if (capcase_p (var
) || uppercase_p (var
) || lowercase_p (var
))
2458 if (flags
& ASS_APPEND
)
2460 oval
= get_variable_value (var
);
2461 if (oval
== 0) /* paranoia */
2463 olen
= STRLEN (oval
);
2464 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2465 strcpy (retval
, oval
);
2467 strcpy (retval
+olen
, value
);
2470 retval
= savestring (value
);
2473 retval
= (char *)xmalloc (1);
2476 op
= capcase_p (var
) ? CASE_CAPITALIZE
2477 : (uppercase_p (var
) ? CASE_UPPER
: CASE_LOWER
);
2478 oval
= sh_modcase (retval
, (char *)0, op
);
2482 #endif /* CASEMOD_ATTRS */
2485 if (flags
& ASS_APPEND
)
2487 oval
= get_variable_value (var
);
2488 if (oval
== 0) /* paranoia */
2490 olen
= STRLEN (oval
);
2491 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2492 strcpy (retval
, oval
);
2494 strcpy (retval
+olen
, value
);
2497 retval
= savestring (value
);
2500 retval
= (char *)xmalloc (1);
2505 retval
= (char *)NULL
;
2510 /* Bind a variable NAME to VALUE in the HASH_TABLE TABLE, which may be the
2511 temporary environment (but usually is not). */
2513 bind_variable_internal (name
, value
, table
, hflags
, aflags
)
2519 char *newname
, *newval
;
2521 #if defined (ARRAY_VARS)
2528 #if defined (ARRAY_VARS)
2529 if ((aflags
& ASS_FROMREF
) && (hflags
& HASH_NOSRCH
) == 0 && valid_array_reference (name
))
2531 newname
= array_variable_name (name
, &subp
, &sublen
);
2533 return (SHELL_VAR
*)NULL
; /* XXX */
2534 entry
= hash_lookup (newname
, table
);
2538 entry
= (hflags
& HASH_NOSRCH
) ? (SHELL_VAR
*)NULL
: hash_lookup (name
, table
);
2540 /* Follow the nameref chain here if this is the global variables table */
2541 if (entry
&& nameref_p (entry
) && (invisible_p (entry
) == 0) && table
== global_variables
->table
)
2543 entry
= find_global_variable (entry
->name
);
2544 /* Let's see if we have a nameref referencing a variable that hasn't yet
2547 entry
= find_variable_last_nameref (name
); /* XXX */
2548 if (entry
== 0) /* just in case */
2552 /* The first clause handles `declare -n ref; ref=x;' */
2553 if (entry
&& invisible_p (entry
) && nameref_p (entry
))
2555 else if (entry
&& nameref_p (entry
))
2557 newval
= nameref_cell (entry
);
2558 #if defined (ARRAY_VARS)
2559 /* declare -n foo=x[2] */
2560 if (valid_array_reference (newval
))
2561 /* XXX - should it be aflags? */
2562 entry
= assign_array_element (newval
, make_variable_value (entry
, value
, 0), aflags
);
2566 entry
= make_new_variable (newval
, table
);
2567 var_setvalue (entry
, make_variable_value (entry
, value
, 0));
2570 #if defined (ARRAY_VARS)
2571 else if (entry
== 0 && newname
)
2573 entry
= make_new_array_variable (newname
); /* indexed array by default */
2576 ind
= array_expand_index (name
, subp
, sublen
);
2577 bind_array_element (entry
, ind
, value
, aflags
);
2580 else if (entry
== 0)
2582 entry
= make_new_variable (name
, table
);
2583 var_setvalue (entry
, make_variable_value (entry
, value
, 0)); /* XXX */
2585 else if (entry
->assign_func
) /* array vars have assign functions now */
2587 INVALIDATE_EXPORTSTR (entry
);
2588 newval
= (aflags
& ASS_APPEND
) ? make_variable_value (entry
, value
, aflags
) : value
;
2589 if (assoc_p (entry
))
2590 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, savestring ("0"));
2591 else if (array_p (entry
))
2592 entry
= (*(entry
->assign_func
)) (entry
, newval
, 0, 0);
2594 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, 0);
2595 if (newval
!= value
)
2602 if (readonly_p (entry
) || noassign_p (entry
))
2604 if (readonly_p (entry
))
2605 err_readonly (name
);
2609 /* Variables which are bound are visible. */
2610 VUNSETATTR (entry
, att_invisible
);
2612 #if defined (ARRAY_VARS)
2613 if (assoc_p (entry
) || array_p (entry
))
2614 newval
= make_array_variable_value (entry
, 0, "0", value
, aflags
);
2618 newval
= make_variable_value (entry
, value
, aflags
); /* XXX */
2620 /* Invalidate any cached export string */
2621 INVALIDATE_EXPORTSTR (entry
);
2623 #if defined (ARRAY_VARS)
2624 /* XXX -- this bears looking at again -- XXX */
2625 /* If an existing array variable x is being assigned to with x=b or
2626 `read x' or something of that nature, silently convert it to
2627 x[0]=b or `read x[0]'. */
2628 if (assoc_p (entry
))
2630 assoc_insert (assoc_cell (entry
), savestring ("0"), newval
);
2633 else if (array_p (entry
))
2635 array_insert (array_cell (entry
), 0, newval
);
2641 FREE (value_cell (entry
));
2642 var_setvalue (entry
, newval
);
2646 if (mark_modified_vars
)
2647 VSETATTR (entry
, att_exported
);
2649 if (exported_p (entry
))
2650 array_needs_making
= 1;
2655 /* Bind a variable NAME to VALUE. This conses up the name
2656 and value strings. If we have a temporary environment, we bind there
2657 first, then we bind into shell_variables. */
2660 bind_variable (name
, value
, flags
)
2666 VAR_CONTEXT
*vc
, *nvc
;
2669 if (shell_variables
== 0)
2670 create_variable_tables ();
2672 /* If we have a temporary environment, look there first for the variable,
2673 and, if found, modify the value there before modifying it in the
2674 shell_variables table. This allows sourced scripts to modify values
2675 given to them in a temporary environment while modifying the variable
2676 value that the caller sees. */
2678 bind_tempenv_variable (name
, value
);
2680 /* XXX -- handle local variables here. */
2681 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2683 if (vc_isfuncenv (vc
) || vc_isbltnenv (vc
))
2685 v
= hash_lookup (name
, vc
->table
);
2687 if (v
&& nameref_p (v
))
2689 nv
= find_variable_nameref_context (v
, vc
, &nvc
);
2692 nv
= find_variable_last_nameref_context (v
, vc
, &nvc
);
2693 if (nv
&& nameref_p (nv
))
2695 /* If this nameref variable doesn't have a value yet,
2696 set the value. Otherwise, assign using the value as
2698 if (nameref_cell (nv
) == 0)
2699 return (bind_variable_internal (nv
->name
, value
, nvc
->table
, 0, flags
));
2700 /* XXX - bug here with ref=array[index] */
2701 return (bind_variable_internal (nameref_cell (nv
), value
, nvc
->table
, 0, flags
|ASS_FROMREF
));
2710 return (bind_variable_internal (v
->name
, value
, nvc
->table
, 0, flags
));
2713 /* bind_variable_internal will handle nameref resolution in this case */
2714 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
2718 bind_global_variable (name
, value
, flags
)
2724 VAR_CONTEXT
*vc
, *nvc
;
2727 if (shell_variables
== 0)
2728 create_variable_tables ();
2730 /* bind_variable_internal will handle nameref resolution in this case */
2731 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
2734 /* Make VAR, a simple shell variable, have value VALUE. Once assigned a
2735 value, variables are no longer invisible. This is a duplicate of part
2736 of the internals of bind_variable. If the variable is exported, or
2737 all modified variables should be exported, mark the variable for export
2738 and note that the export environment needs to be recreated. */
2740 bind_variable_value (var
, value
, aflags
)
2748 invis
= invisible_p (var
);
2749 VUNSETATTR (var
, att_invisible
);
2751 if (var
->assign_func
)
2753 /* If we're appending, we need the old value, so use
2754 make_variable_value */
2755 t
= (aflags
& ASS_APPEND
) ? make_variable_value (var
, value
, aflags
) : value
;
2756 (*(var
->assign_func
)) (var
, t
, -1, 0);
2757 if (t
!= value
&& t
)
2762 t
= make_variable_value (var
, value
, aflags
);
2763 #if defined (ARRAY_VARS)
2764 if ((aflags
& ASS_NAMEREF
) && (t
== 0 || *t
== 0 || (legal_identifier (t
) == 0 && valid_array_reference (t
) == 0)))
2766 if ((aflags
& ASS_NAMEREF
) && (t
== 0 || *t
== 0 || legal_identifier (t
) == 0))
2771 VSETATTR (var
, att_invisible
); /* XXX */
2772 return ((SHELL_VAR
*)NULL
);
2774 FREE (value_cell (var
));
2775 var_setvalue (var
, t
);
2778 INVALIDATE_EXPORTSTR (var
);
2780 if (mark_modified_vars
)
2781 VSETATTR (var
, att_exported
);
2783 if (exported_p (var
))
2784 array_needs_making
= 1;
2789 /* Bind/create a shell variable with the name LHS to the RHS.
2790 This creates or modifies a variable such that it is an integer.
2792 This used to be in expr.c, but it is here so that all of the
2793 variable binding stuff is localized. Since we don't want any
2794 recursive evaluation from bind_variable() (possible without this code,
2795 since bind_variable() calls the evaluator for variables with the integer
2796 attribute set), we temporarily turn off the integer attribute for each
2797 variable we set here, then turn it back on after binding as necessary. */
2800 bind_int_variable (lhs
, rhs
)
2803 register SHELL_VAR
*v
;
2804 int isint
, isarr
, implicitarray
;
2806 isint
= isarr
= implicitarray
= 0;
2807 #if defined (ARRAY_VARS)
2808 if (valid_array_reference (lhs
))
2811 v
= array_variable_part (lhs
, (char **)0, (int *)0);
2815 v
= find_variable (lhs
);
2819 isint
= integer_p (v
);
2820 VUNSETATTR (v
, att_integer
);
2821 #if defined (ARRAY_VARS)
2822 if (array_p (v
) && isarr
== 0)
2827 #if defined (ARRAY_VARS)
2829 v
= assign_array_element (lhs
, rhs
, 0);
2830 else if (implicitarray
)
2831 v
= bind_array_variable (lhs
, 0, rhs
, 0);
2834 v
= bind_variable (lhs
, rhs
, 0);
2839 VSETATTR (v
, att_integer
);
2840 VUNSETATTR (v
, att_invisible
);
2847 bind_var_to_int (var
, val
)
2851 char ibuf
[INT_STRLEN_BOUND (intmax_t) + 1], *p
;
2853 p
= fmtulong (val
, 10, ibuf
, sizeof (ibuf
), 0);
2854 return (bind_int_variable (var
, p
));
2857 /* Do a function binding to a variable. You pass the name and
2858 the command to bind to. This conses the name and command. */
2860 bind_function (name
, value
)
2866 entry
= find_function (name
);
2869 BUCKET_CONTENTS
*elt
;
2871 elt
= hash_insert (savestring (name
), shell_functions
, HASH_NOSRCH
);
2872 entry
= new_shell_variable (name
);
2873 elt
->data
= (PTR_T
)entry
;
2876 INVALIDATE_EXPORTSTR (entry
);
2878 if (var_isset (entry
))
2879 dispose_command (function_cell (entry
));
2882 var_setfunc (entry
, copy_command (value
));
2884 var_setfunc (entry
, 0);
2886 VSETATTR (entry
, att_function
);
2888 if (mark_modified_vars
)
2889 VSETATTR (entry
, att_exported
);
2891 VUNSETATTR (entry
, att_invisible
); /* Just to be sure */
2893 if (exported_p (entry
))
2894 array_needs_making
= 1;
2896 #if defined (PROGRAMMABLE_COMPLETION)
2897 set_itemlist_dirty (&it_functions
);
2903 #if defined (DEBUGGER)
2904 /* Bind a function definition, which includes source file and line number
2905 information in addition to the command, into the FUNCTION_DEF hash table.*/
2907 bind_function_def (name
, value
)
2909 FUNCTION_DEF
*value
;
2911 FUNCTION_DEF
*entry
;
2912 BUCKET_CONTENTS
*elt
;
2915 entry
= find_function_def (name
);
2918 dispose_function_def_contents (entry
);
2919 entry
= copy_function_def_contents (value
, entry
);
2923 cmd
= value
->command
;
2925 entry
= copy_function_def (value
);
2926 value
->command
= cmd
;
2928 elt
= hash_insert (savestring (name
), shell_function_defs
, HASH_NOSRCH
);
2929 elt
->data
= (PTR_T
*)entry
;
2932 #endif /* DEBUGGER */
2934 /* Add STRING, which is of the form foo=bar, to the temporary environment
2935 HASH_TABLE (temporary_env). The functions in execute_cmd.c are
2936 responsible for moving the main temporary env to one of the other
2937 temporary environments. The expansion code in subst.c calls this. */
2939 assign_in_env (word
, flags
)
2944 char *name
, *temp
, *value
;
2948 string
= word
->word
;
2951 offset
= assignment (string
, 0);
2952 name
= savestring (string
);
2953 value
= (char *)NULL
;
2955 if (name
[offset
] == '=')
2959 /* don't ignore the `+' when assigning temporary environment */
2960 if (name
[offset
- 1] == '+')
2962 name
[offset
- 1] = '\0';
2963 aflags
|= ASS_APPEND
;
2966 var
= find_variable (name
);
2967 if (var
&& (readonly_p (var
) || noassign_p (var
)))
2969 if (readonly_p (var
))
2970 err_readonly (name
);
2975 temp
= name
+ offset
+ 1;
2976 value
= expand_assignment_string_to_string (temp
, 0);
2978 if (var
&& (aflags
& ASS_APPEND
))
2980 temp
= make_variable_value (var
, value
, aflags
);
2986 if (temporary_env
== 0)
2987 temporary_env
= hash_create (TEMPENV_HASH_BUCKETS
);
2989 var
= hash_lookup (name
, temporary_env
);
2991 var
= make_new_variable (name
, temporary_env
);
2993 FREE (value_cell (var
));
2997 value
= (char *)xmalloc (1); /* like do_assignment_internal */
3001 var_setvalue (var
, value
);
3002 var
->attributes
|= (att_exported
|att_tempvar
);
3003 var
->context
= variable_context
; /* XXX */
3005 INVALIDATE_EXPORTSTR (var
);
3006 var
->exportstr
= mk_env_string (name
, value
, 0);
3008 array_needs_making
= 1;
3011 stupidly_hack_special_variables (name
);
3013 if (echo_command_at_execute
)
3014 /* The Korn shell prints the `+ ' in front of assignment statements,
3016 xtrace_print_assignment (name
, value
, 0, 1);
3022 /* **************************************************************** */
3024 /* Copying variables */
3026 /* **************************************************************** */
3028 #ifdef INCLUDE_UNUSED
3029 /* Copy VAR to a new data structure and return that structure. */
3034 SHELL_VAR
*copy
= (SHELL_VAR
*)NULL
;
3038 copy
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
3040 copy
->attributes
= var
->attributes
;
3041 copy
->name
= savestring (var
->name
);
3043 if (function_p (var
))
3044 var_setfunc (copy
, copy_command (function_cell (var
)));
3045 #if defined (ARRAY_VARS)
3046 else if (array_p (var
))
3047 var_setarray (copy
, array_copy (array_cell (var
)));
3048 else if (assoc_p (var
))
3049 var_setassoc (copy
, assoc_copy (assoc_cell (var
)));
3051 else if (nameref_cell (var
)) /* XXX - nameref */
3052 var_setref (copy
, savestring (nameref_cell (var
)));
3053 else if (value_cell (var
)) /* XXX - nameref */
3054 var_setvalue (copy
, savestring (value_cell (var
)));
3056 var_setvalue (copy
, (char *)NULL
);
3058 copy
->dynamic_value
= var
->dynamic_value
;
3059 copy
->assign_func
= var
->assign_func
;
3061 copy
->exportstr
= COPY_EXPORTSTR (var
);
3063 copy
->context
= var
->context
;
3069 /* **************************************************************** */
3071 /* Deleting and unsetting variables */
3073 /* **************************************************************** */
3075 /* Dispose of the information attached to VAR. */
3077 dispose_variable_value (var
)
3080 if (function_p (var
))
3081 dispose_command (function_cell (var
));
3082 #if defined (ARRAY_VARS)
3083 else if (array_p (var
))
3084 array_dispose (array_cell (var
));
3085 else if (assoc_p (var
))
3086 assoc_dispose (assoc_cell (var
));
3088 else if (nameref_p (var
))
3089 FREE (nameref_cell (var
));
3091 FREE (value_cell (var
));
3095 dispose_variable (var
)
3101 if (nofree_p (var
) == 0)
3102 dispose_variable_value (var
);
3104 FREE_EXPORTSTR (var
);
3108 if (exported_p (var
))
3109 array_needs_making
= 1;
3114 /* Unset the shell variable referenced by NAME. Unsetting a nameref variable
3115 unsets the variable it resolves to but leaves the nameref alone. */
3117 unbind_variable (name
)
3123 v
= var_lookup (name
, shell_variables
);
3124 nv
= (v
&& nameref_p (v
)) ? find_variable_nameref (v
) : (SHELL_VAR
*)NULL
;
3126 r
= nv
? makunbound (nv
->name
, shell_variables
) : makunbound (name
, shell_variables
);
3130 /* Unbind NAME, where NAME is assumed to be a nameref variable */
3132 unbind_nameref (name
)
3137 v
= var_lookup (name
, shell_variables
);
3138 if (v
&& nameref_p (v
))
3139 return makunbound (name
, shell_variables
);
3143 /* Unset the shell function named NAME. */
3148 BUCKET_CONTENTS
*elt
;
3151 elt
= hash_remove (name
, shell_functions
, 0);
3156 #if defined (PROGRAMMABLE_COMPLETION)
3157 set_itemlist_dirty (&it_functions
);
3160 func
= (SHELL_VAR
*)elt
->data
;
3163 if (exported_p (func
))
3164 array_needs_making
++;
3165 dispose_variable (func
);
3174 #if defined (DEBUGGER)
3176 unbind_function_def (name
)
3179 BUCKET_CONTENTS
*elt
;
3180 FUNCTION_DEF
*funcdef
;
3182 elt
= hash_remove (name
, shell_function_defs
, 0);
3187 funcdef
= (FUNCTION_DEF
*)elt
->data
;
3189 dispose_function_def (funcdef
);
3196 #endif /* DEBUGGER */
3199 delete_var (name
, vc
)
3203 BUCKET_CONTENTS
*elt
;
3207 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3208 if (elt
= hash_remove (name
, v
->table
, 0))
3214 old_var
= (SHELL_VAR
*)elt
->data
;
3218 dispose_variable (old_var
);
3222 /* Make the variable associated with NAME go away. HASH_LIST is the
3223 hash table from which this variable should be deleted (either
3224 shell_variables or shell_functions).
3225 Returns non-zero if the variable couldn't be found. */
3227 makunbound (name
, vc
)
3231 BUCKET_CONTENTS
*elt
, *new_elt
;
3236 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3237 if (elt
= hash_remove (name
, v
->table
, 0))
3243 old_var
= (SHELL_VAR
*)elt
->data
;
3245 if (old_var
&& exported_p (old_var
))
3246 array_needs_making
++;
3248 /* If we're unsetting a local variable and we're still executing inside
3249 the function, just mark the variable as invisible. The function
3250 eventually called by pop_var_context() will clean it up later. This
3251 must be done so that if the variable is subsequently assigned a new
3252 value inside the function, the `local' attribute is still present.
3253 We also need to add it back into the correct hash table. */
3254 if (old_var
&& local_p (old_var
) && variable_context
== old_var
->context
)
3256 if (nofree_p (old_var
))
3257 var_setvalue (old_var
, (char *)NULL
);
3258 #if defined (ARRAY_VARS)
3259 else if (array_p (old_var
))
3260 array_dispose (array_cell (old_var
));
3261 else if (assoc_p (old_var
))
3262 assoc_dispose (assoc_cell (old_var
));
3264 else if (nameref_p (old_var
))
3265 FREE (nameref_cell (old_var
));
3267 FREE (value_cell (old_var
));
3268 /* Reset the attributes. Preserve the export attribute if the variable
3269 came from a temporary environment. Make sure it stays local, and
3270 make it invisible. */
3271 old_var
->attributes
= (exported_p (old_var
) && tempvar_p (old_var
)) ? att_exported
: 0;
3272 VSETATTR (old_var
, att_local
);
3273 VSETATTR (old_var
, att_invisible
);
3274 var_setvalue (old_var
, (char *)NULL
);
3275 INVALIDATE_EXPORTSTR (old_var
);
3277 new_elt
= hash_insert (savestring (old_var
->name
), v
->table
, 0);
3278 new_elt
->data
= (PTR_T
)old_var
;
3279 stupidly_hack_special_variables (old_var
->name
);
3286 /* Have to save a copy of name here, because it might refer to
3287 old_var->name. If so, stupidly_hack_special_variables will
3288 reference freed memory. */
3289 t
= savestring (name
);
3294 dispose_variable (old_var
);
3295 stupidly_hack_special_variables (t
);
3301 /* Get rid of all of the variables in the current context. */
3303 kill_all_local_variables ()
3307 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3308 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
3313 if (vc
->table
&& vc_haslocals (vc
))
3315 delete_all_variables (vc
->table
);
3316 hash_dispose (vc
->table
);
3318 vc
->table
= (HASH_TABLE
*)NULL
;
3322 free_variable_hash_data (data
)
3327 var
= (SHELL_VAR
*)data
;
3328 dispose_variable (var
);
3331 /* Delete the entire contents of the hash table. */
3333 delete_all_variables (hashed_vars
)
3334 HASH_TABLE
*hashed_vars
;
3336 hash_flush (hashed_vars
, free_variable_hash_data
);
3339 /* **************************************************************** */
3341 /* Setting variable attributes */
3343 /* **************************************************************** */
3345 #define FIND_OR_MAKE_VARIABLE(name, entry) \
3348 entry = find_variable (name); \
3351 entry = bind_variable (name, "", 0); \
3352 if (!no_invisible_vars && entry) entry->attributes |= att_invisible; \
3357 /* Make the variable associated with NAME be readonly.
3358 If NAME does not exist yet, create it. */
3360 set_var_read_only (name
)
3365 FIND_OR_MAKE_VARIABLE (name
, entry
);
3366 VSETATTR (entry
, att_readonly
);
3369 #ifdef INCLUDE_UNUSED
3370 /* Make the function associated with NAME be readonly.
3371 If NAME does not exist, we just punt, like auto_export code below. */
3373 set_func_read_only (name
)
3378 entry
= find_function (name
);
3380 VSETATTR (entry
, att_readonly
);
3383 /* Make the variable associated with NAME be auto-exported.
3384 If NAME does not exist yet, create it. */
3386 set_var_auto_export (name
)
3391 FIND_OR_MAKE_VARIABLE (name
, entry
);
3392 set_auto_export (entry
);
3395 /* Make the function associated with NAME be auto-exported. */
3397 set_func_auto_export (name
)
3402 entry
= find_function (name
);
3404 set_auto_export (entry
);
3408 /* **************************************************************** */
3410 /* Creating lists of variables */
3412 /* **************************************************************** */
3415 vlist_alloc (nentries
)
3420 vlist
= (VARLIST
*)xmalloc (sizeof (VARLIST
));
3421 vlist
->list
= (SHELL_VAR
**)xmalloc ((nentries
+ 1) * sizeof (SHELL_VAR
*));
3422 vlist
->list_size
= nentries
;
3423 vlist
->list_len
= 0;
3424 vlist
->list
[0] = (SHELL_VAR
*)NULL
;
3430 vlist_realloc (vlist
, n
)
3435 return (vlist
= vlist_alloc (n
));
3436 if (n
> vlist
->list_size
)
3438 vlist
->list_size
= n
;
3439 vlist
->list
= (SHELL_VAR
**)xrealloc (vlist
->list
, (vlist
->list_size
+ 1) * sizeof (SHELL_VAR
*));
3445 vlist_add (vlist
, var
, flags
)
3452 for (i
= 0; i
< vlist
->list_len
; i
++)
3453 if (STREQ (var
->name
, vlist
->list
[i
]->name
))
3455 if (i
< vlist
->list_len
)
3458 if (i
>= vlist
->list_size
)
3459 vlist
= vlist_realloc (vlist
, vlist
->list_size
+ 16);
3461 vlist
->list
[vlist
->list_len
++] = var
;
3462 vlist
->list
[vlist
->list_len
] = (SHELL_VAR
*)NULL
;
3465 /* Map FUNCTION over the variables in VAR_HASH_TABLE. Return an array of the
3466 variables for which FUNCTION returns a non-zero value. A NULL value
3467 for FUNCTION means to use all variables. */
3469 map_over (function
, vc
)
3470 sh_var_map_func_t
*function
;
3478 for (nentries
= 0, v
= vc
; v
; v
= v
->down
)
3479 nentries
+= HASH_ENTRIES (v
->table
);
3482 return (SHELL_VAR
**)NULL
;
3484 vlist
= vlist_alloc (nentries
);
3486 for (v
= vc
; v
; v
= v
->down
)
3487 flatten (v
->table
, function
, vlist
, 0);
3495 map_over_funcs (function
)
3496 sh_var_map_func_t
*function
;
3501 if (shell_functions
== 0 || HASH_ENTRIES (shell_functions
) == 0)
3502 return ((SHELL_VAR
**)NULL
);
3504 vlist
= vlist_alloc (HASH_ENTRIES (shell_functions
));
3506 flatten (shell_functions
, function
, vlist
, 0);
3513 /* Flatten VAR_HASH_TABLE, applying FUNC to each member and adding those
3514 elements for which FUNC succeeds to VLIST->list. FLAGS is reserved
3515 for future use. Only unique names are added to VLIST. If FUNC is
3516 NULL, each variable in VAR_HASH_TABLE is added to VLIST. If VLIST is
3517 NULL, FUNC is applied to each SHELL_VAR in VAR_HASH_TABLE. If VLIST
3518 and FUNC are both NULL, nothing happens. */
3520 flatten (var_hash_table
, func
, vlist
, flags
)
3521 HASH_TABLE
*var_hash_table
;
3522 sh_var_map_func_t
*func
;
3527 register BUCKET_CONTENTS
*tlist
;
3531 if (var_hash_table
== 0 || (HASH_ENTRIES (var_hash_table
) == 0) || (vlist
== 0 && func
== 0))
3534 for (i
= 0; i
< var_hash_table
->nbuckets
; i
++)
3536 for (tlist
= hash_items (i
, var_hash_table
); tlist
; tlist
= tlist
->next
)
3538 var
= (SHELL_VAR
*)tlist
->data
;
3540 r
= func
? (*func
) (var
) : 1;
3542 vlist_add (vlist
, var
, flags
);
3548 sort_variables (array
)
3551 qsort (array
, strvec_len ((char **)array
), sizeof (SHELL_VAR
*), (QSFUNC
*)qsort_var_comp
);
3555 qsort_var_comp (var1
, var2
)
3556 SHELL_VAR
**var1
, **var2
;
3560 if ((result
= (*var1
)->name
[0] - (*var2
)->name
[0]) == 0)
3561 result
= strcmp ((*var1
)->name
, (*var2
)->name
);
3566 /* Apply FUNC to each variable in SHELL_VARIABLES, adding each one for
3567 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3570 sh_var_map_func_t
*func
;
3574 list
= map_over (func
, shell_variables
);
3575 if (list
/* && posixly_correct */)
3576 sort_variables (list
);
3580 /* Apply FUNC to each variable in SHELL_FUNCTIONS, adding each one for
3581 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3584 sh_var_map_func_t
*func
;
3588 list
= map_over_funcs (func
);
3589 if (list
/* && posixly_correct */)
3590 sort_variables (list
);
3594 /* Create a NULL terminated array of all the shell variables. */
3596 all_shell_variables ()
3598 return (vapply ((sh_var_map_func_t
*)NULL
));
3601 /* Create a NULL terminated array of all the shell functions. */
3603 all_shell_functions ()
3605 return (fapply ((sh_var_map_func_t
*)NULL
));
3612 return (invisible_p (var
) == 0);
3616 all_visible_functions ()
3618 return (fapply (visible_var
));
3622 all_visible_variables ()
3624 return (vapply (visible_var
));
3627 /* Return non-zero if the variable VAR is visible and exported. Array
3628 variables cannot be exported. */
3630 visible_and_exported (var
)
3633 return (invisible_p (var
) == 0 && exported_p (var
));
3636 /* Candidate variables for the export environment are either valid variables
3637 with the export attribute or invalid variables inherited from the initial
3638 environment and simply passed through. */
3640 export_environment_candidate (var
)
3643 return (exported_p (var
) && (invisible_p (var
) == 0 || imported_p (var
)));
3646 /* Return non-zero if VAR is a local variable in the current context and
3649 local_and_exported (var
)
3652 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
&& exported_p (var
));
3656 all_exported_variables ()
3658 return (vapply (visible_and_exported
));
3662 local_exported_variables ()
3664 return (vapply (local_and_exported
));
3668 variable_in_context (var
)
3671 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
);
3675 all_local_variables ()
3681 vc
= shell_variables
;
3682 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3683 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
3688 internal_error (_("all_local_variables: no function context at current scope"));
3689 return (SHELL_VAR
**)NULL
;
3691 if (vc
->table
== 0 || HASH_ENTRIES (vc
->table
) == 0 || vc_haslocals (vc
) == 0)
3692 return (SHELL_VAR
**)NULL
;
3694 vlist
= vlist_alloc (HASH_ENTRIES (vc
->table
));
3696 flatten (vc
->table
, variable_in_context
, vlist
, 0);
3701 sort_variables (ret
);
3705 #if defined (ARRAY_VARS)
3706 /* Return non-zero if the variable VAR is visible and an array. */
3708 visible_array_vars (var
)
3711 return (invisible_p (var
) == 0 && array_p (var
));
3715 all_array_variables ()
3717 return (vapply (visible_array_vars
));
3719 #endif /* ARRAY_VARS */
3722 all_variables_matching_prefix (prefix
)
3725 SHELL_VAR
**varlist
;
3727 int vind
, rind
, plen
;
3729 plen
= STRLEN (prefix
);
3730 varlist
= all_visible_variables ();
3731 for (vind
= 0; varlist
&& varlist
[vind
]; vind
++)
3733 if (varlist
== 0 || vind
== 0)
3734 return ((char **)NULL
);
3735 rlist
= strvec_create (vind
+ 1);
3736 for (vind
= rind
= 0; varlist
[vind
]; vind
++)
3738 if (plen
== 0 || STREQN (prefix
, varlist
[vind
]->name
, plen
))
3739 rlist
[rind
++] = savestring (varlist
[vind
]->name
);
3741 rlist
[rind
] = (char *)0;
3747 /* **************************************************************** */
3749 /* Managing temporary variable scopes */
3751 /* **************************************************************** */
3753 /* Make variable NAME have VALUE in the temporary environment. */
3755 bind_tempenv_variable (name
, value
)
3761 var
= temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
;
3765 FREE (value_cell (var
));
3766 var_setvalue (var
, savestring (value
));
3767 INVALIDATE_EXPORTSTR (var
);
3773 /* Find a variable in the temporary environment that is named NAME.
3774 Return the SHELL_VAR *, or NULL if not found. */
3776 find_tempenv_variable (name
)
3779 return (temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
);
3782 char **tempvar_list
;
3785 /* Push the variable described by (SHELL_VAR *)DATA down to the next
3786 variable context from the temporary environment. */
3788 push_temp_var (data
)
3792 HASH_TABLE
*binding_table
;
3794 var
= (SHELL_VAR
*)data
;
3796 binding_table
= shell_variables
->table
;
3797 if (binding_table
== 0)
3799 if (shell_variables
== global_variables
)
3800 /* shouldn't happen */
3801 binding_table
= shell_variables
->table
= global_variables
->table
= hash_create (0);
3803 binding_table
= shell_variables
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
3806 v
= bind_variable_internal (var
->name
, value_cell (var
), binding_table
, 0, 0);
3808 /* XXX - should we set the context here? It shouldn't matter because of how
3809 assign_in_env works, but might want to check. */
3810 if (binding_table
== global_variables
->table
) /* XXX */
3811 var
->attributes
&= ~(att_tempvar
|att_propagate
);
3814 var
->attributes
|= att_propagate
;
3815 if (binding_table
== shell_variables
->table
)
3816 shell_variables
->flags
|= VC_HASTMPVAR
;
3818 v
->attributes
|= var
->attributes
;
3820 if (find_special_var (var
->name
) >= 0)
3821 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
3823 dispose_variable (var
);
3827 propagate_temp_var (data
)
3832 var
= (SHELL_VAR
*)data
;
3833 if (tempvar_p (var
) && (var
->attributes
& att_propagate
))
3834 push_temp_var (data
);
3837 if (find_special_var (var
->name
) >= 0)
3838 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
3839 dispose_variable (var
);
3843 /* Free the storage used in the hash table for temporary
3844 environment variables. PUSHF is a function to be called
3845 to free each hash table entry. It takes care of pushing variables
3846 to previous scopes if appropriate. PUSHF stores names of variables
3847 that require special handling (e.g., IFS) on tempvar_list, so this
3848 function can call stupidly_hack_special_variables on all the
3849 variables in the list when the temporary hash table is destroyed. */
3851 dispose_temporary_env (pushf
)
3852 sh_free_func_t
*pushf
;
3856 tempvar_list
= strvec_create (HASH_ENTRIES (temporary_env
) + 1);
3857 tempvar_list
[tvlist_ind
= 0] = 0;
3859 hash_flush (temporary_env
, pushf
);
3860 hash_dispose (temporary_env
);
3861 temporary_env
= (HASH_TABLE
*)NULL
;
3863 tempvar_list
[tvlist_ind
] = 0;
3865 array_needs_making
= 1;
3868 sv_ifs ("IFS"); /* XXX here for now -- check setifs in assign_in_env */
3870 for (i
= 0; i
< tvlist_ind
; i
++)
3871 stupidly_hack_special_variables (tempvar_list
[i
]);
3873 strvec_dispose (tempvar_list
);
3879 dispose_used_env_vars ()
3883 dispose_temporary_env (propagate_temp_var
);
3884 maybe_make_export_env ();
3888 /* Take all of the shell variables in the temporary environment HASH_TABLE
3889 and make shell variables from them at the current variable context. */
3891 merge_temporary_env ()
3894 dispose_temporary_env (push_temp_var
);
3897 /* **************************************************************** */
3899 /* Creating and manipulating the environment */
3901 /* **************************************************************** */
3903 static inline char *
3904 mk_env_string (name
, value
, isfunc
)
3905 const char *name
, *value
;
3908 size_t name_len
, value_len
;
3911 name_len
= strlen (name
);
3912 value_len
= STRLEN (value
);
3914 /* If we are exporting a shell function, construct the encoded function
3916 if (isfunc
&& value
)
3918 p
= (char *)xmalloc (BASHFUNC_PREFLEN
+ name_len
+ BASHFUNC_SUFFLEN
+ value_len
+ 2);
3920 memcpy (q
, BASHFUNC_PREFIX
, BASHFUNC_PREFLEN
);
3921 q
+= BASHFUNC_PREFLEN
;
3922 memcpy (q
, name
, name_len
);
3924 memcpy (q
, BASHFUNC_SUFFIX
, BASHFUNC_SUFFLEN
);
3925 q
+= BASHFUNC_SUFFLEN
;
3929 p
= (char *)xmalloc (2 + name_len
+ value_len
);
3930 memcpy (p
, name
, name_len
);
3935 if (value
&& *value
)
3936 memcpy (q
+ 1, value
, value_len
+ 1);
3954 internal_error (_("%s has null exportstr"), v
->name
);
3957 if (legal_variable_starter ((unsigned char)*s
) == 0)
3959 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
3962 for (s
= v
->exportstr
+ 1; s
&& *s
; s
++)
3966 if (legal_variable_char ((unsigned char)*s
) == 0)
3968 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
3974 internal_error (_("no `=' in exportstr for %s"), v
->name
);
3982 make_env_array_from_var_list (vars
)
3985 register int i
, list_index
;
3986 register SHELL_VAR
*var
;
3987 char **list
, *value
;
3989 list
= strvec_create ((1 + strvec_len ((char **)vars
)));
3991 #define USE_EXPORTSTR (value == var->exportstr)
3993 for (i
= 0, list_index
= 0; var
= vars
[i
]; i
++)
3995 #if defined (__CYGWIN__)
3996 /* We don't use the exportstr stuff on Cygwin at all. */
3997 INVALIDATE_EXPORTSTR (var
);
4000 value
= var
->exportstr
;
4001 else if (function_p (var
))
4002 value
= named_function_string ((char *)NULL
, function_cell (var
), 0);
4003 #if defined (ARRAY_VARS)
4004 else if (array_p (var
))
4006 value
= array_to_assignment_string (array_cell (var
));
4008 continue; /* XXX array vars cannot yet be exported */
4009 # endif /* ARRAY_EXPORT */
4010 else if (assoc_p (var
))
4012 value
= assoc_to_assignment_string (assoc_cell (var
));
4014 continue; /* XXX associative array vars cannot yet be exported */
4018 value
= value_cell (var
);
4022 /* Gee, I'd like to get away with not using savestring() if we're
4023 using the cached exportstr... */
4024 list
[list_index
] = USE_EXPORTSTR
? savestring (value
)
4025 : mk_env_string (var
->name
, value
, function_p (var
));
4027 if (USE_EXPORTSTR
== 0)
4028 SAVE_EXPORTSTR (var
, list
[list_index
]);
4031 #undef USE_EXPORTSTR
4034 #if defined (ARRAY_VARS)
4035 if (array_p (var
) || assoc_p (var
))
4042 list
[list_index
] = (char *)NULL
;
4046 /* Make an array of assignment statements from the hash table
4047 HASHED_VARS which contains SHELL_VARs. Only visible, exported
4048 variables are eligible. */
4050 make_var_export_array (vcxt
)
4057 vars
= map_over (visible_and_exported
, vcxt
);
4059 vars
= map_over (export_environment_candidate
, vcxt
);
4063 return (char **)NULL
;
4065 list
= make_env_array_from_var_list (vars
);
4072 make_func_export_array ()
4077 vars
= map_over_funcs (visible_and_exported
);
4079 return (char **)NULL
;
4081 list
= make_env_array_from_var_list (vars
);
4087 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
4088 #define add_to_export_env(envstr,do_alloc) \
4091 if (export_env_index >= (export_env_size - 1)) \
4093 export_env_size += 16; \
4094 export_env = strvec_resize (export_env, export_env_size); \
4095 environ = export_env; \
4097 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
4098 export_env[export_env_index] = (char *)NULL; \
4101 /* Add ASSIGN to EXPORT_ENV, or supercede a previous assignment in the
4102 array with the same left-hand side. Return the new EXPORT_ENV. */
4104 add_or_supercede_exported_var (assign
, do_alloc
)
4111 equal_offset
= assignment (assign
, 0);
4112 if (equal_offset
== 0)
4113 return (export_env
);
4115 /* If this is a function, then only supersede the function definition.
4116 We do this by including the `=() {' in the comparison, like
4117 initialize_shell_variables does. */
4118 if (assign
[equal_offset
+ 1] == '(' &&
4119 strncmp (assign
+ equal_offset
+ 2, ") {", 3) == 0) /* } */
4122 for (i
= 0; i
< export_env_index
; i
++)
4124 if (STREQN (assign
, export_env
[i
], equal_offset
+ 1))
4126 free (export_env
[i
]);
4127 export_env
[i
] = do_alloc
? savestring (assign
) : assign
;
4128 return (export_env
);
4131 add_to_export_env (assign
, do_alloc
);
4132 return (export_env
);
4136 add_temp_array_to_env (temp_array
, do_alloc
, do_supercede
)
4138 int do_alloc
, do_supercede
;
4142 if (temp_array
== 0)
4145 for (i
= 0; temp_array
[i
]; i
++)
4148 export_env
= add_or_supercede_exported_var (temp_array
[i
], do_alloc
);
4150 add_to_export_env (temp_array
[i
], do_alloc
);
4156 /* Make the environment array for the command about to be executed, if the
4157 array needs making. Otherwise, do nothing. If a shell action could
4158 change the array that commands receive for their environment, then the
4159 code should `array_needs_making++'.
4161 The order to add to the array is:
4163 list of var contexts whose head is shell_variables
4166 This is the shell variable lookup order. We add only new variable
4167 names at each step, which allows local variables and variables in
4168 the temporary environments to shadow variables in the global (or
4169 any previous) scope.
4173 n_shell_variables ()
4178 for (n
= 0, vc
= shell_variables
; vc
; vc
= vc
->down
)
4179 n
+= HASH_ENTRIES (vc
->table
);
4189 v
= find_variable (name
);
4190 if (v
&& exported_p (v
))
4192 array_needs_making
= 1;
4193 maybe_make_export_env ();
4200 maybe_make_export_env ()
4202 register char **temp_array
;
4206 if (array_needs_making
)
4209 strvec_flush (export_env
);
4211 /* Make a guess based on how many shell variables and functions we
4212 have. Since there will always be array variables, and array
4213 variables are not (yet) exported, this will always be big enough
4214 for the exported variables and functions. */
4215 new_size
= n_shell_variables () + HASH_ENTRIES (shell_functions
) + 1 +
4216 HASH_ENTRIES (temporary_env
);
4217 if (new_size
> export_env_size
)
4219 export_env_size
= new_size
;
4220 export_env
= strvec_resize (export_env
, export_env_size
);
4221 environ
= export_env
;
4223 export_env
[export_env_index
= 0] = (char *)NULL
;
4225 /* Make a dummy variable context from the temporary_env, stick it on
4226 the front of shell_variables, call make_var_export_array on the
4227 whole thing to flatten it, and convert the list of SHELL_VAR *s
4228 to the form needed by the environment. */
4231 tcxt
= new_var_context ((char *)NULL
, 0);
4232 tcxt
->table
= temporary_env
;
4233 tcxt
->down
= shell_variables
;
4236 tcxt
= shell_variables
;
4238 temp_array
= make_var_export_array (tcxt
);
4240 add_temp_array_to_env (temp_array
, 0, 0);
4242 if (tcxt
!= shell_variables
)
4245 #if defined (RESTRICTED_SHELL)
4246 /* Restricted shells may not export shell functions. */
4247 temp_array
= restricted
? (char **)0 : make_func_export_array ();
4249 temp_array
= make_func_export_array ();
4252 add_temp_array_to_env (temp_array
, 0, 0);
4254 array_needs_making
= 0;
4258 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
4259 we will need to remake the exported environment every time we
4260 change directories. `_' is always put into the environment for
4261 every external command, so without special treatment it will always
4262 cause the environment to be remade.
4264 If there is no other reason to make the exported environment, we can
4265 just update the variables in place and mark the exported environment
4266 as no longer needing a remake. */
4268 update_export_env_inplace (env_prefix
, preflen
, value
)
4275 evar
= (char *)xmalloc (STRLEN (value
) + preflen
+ 1);
4276 strcpy (evar
, env_prefix
);
4278 strcpy (evar
+ preflen
, value
);
4279 export_env
= add_or_supercede_exported_var (evar
, 0);
4282 /* We always put _ in the environment as the name of this command. */
4284 put_command_name_into_env (command_name
)
4287 update_export_env_inplace ("_=", 2, command_name
);
4290 /* **************************************************************** */
4292 /* Managing variable contexts */
4294 /* **************************************************************** */
4296 /* Allocate and return a new variable context with NAME and FLAGS.
4297 NAME can be NULL. */
4300 new_var_context (name
, flags
)
4306 vc
= (VAR_CONTEXT
*)xmalloc (sizeof (VAR_CONTEXT
));
4307 vc
->name
= name
? savestring (name
) : (char *)NULL
;
4308 vc
->scope
= variable_context
;
4311 vc
->up
= vc
->down
= (VAR_CONTEXT
*)NULL
;
4312 vc
->table
= (HASH_TABLE
*)NULL
;
4317 /* Free a variable context and its data, including the hash table. Dispose
4318 all of the variables. */
4320 dispose_var_context (vc
)
4327 delete_all_variables (vc
->table
);
4328 hash_dispose (vc
->table
);
4334 /* Set VAR's scope level to the current variable context. */
4339 return (var
->context
= variable_context
);
4342 /* Make a new variable context with NAME and FLAGS and a HASH_TABLE of
4343 temporary variables, and push it onto shell_variables. This is
4344 for shell functions. */
4346 push_var_context (name
, flags
, tempvars
)
4349 HASH_TABLE
*tempvars
;
4353 vc
= new_var_context (name
, flags
);
4354 vc
->table
= tempvars
;
4357 /* Have to do this because the temp environment was created before
4358 variable_context was incremented. */
4359 flatten (tempvars
, set_context
, (VARLIST
*)NULL
, 0);
4360 vc
->flags
|= VC_HASTMPVAR
;
4362 vc
->down
= shell_variables
;
4363 shell_variables
->up
= vc
;
4365 return (shell_variables
= vc
);
4369 push_func_var (data
)
4374 var
= (SHELL_VAR
*)data
;
4376 if (tempvar_p (var
) && (posixly_correct
|| (var
->attributes
& att_propagate
)))
4378 /* Make sure we have a hash table to store the variable in while it is
4379 being propagated down to the global variables table. Create one if
4381 if ((vc_isfuncenv (shell_variables
) || vc_istempenv (shell_variables
)) && shell_variables
->table
== 0)
4382 shell_variables
->table
= hash_create (0);
4383 /* XXX - should we set v->context here? */
4384 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
4385 if (shell_variables
== global_variables
)
4386 var
->attributes
&= ~(att_tempvar
|att_propagate
);
4388 shell_variables
->flags
|= VC_HASTMPVAR
;
4389 v
->attributes
|= var
->attributes
;
4392 stupidly_hack_special_variables (var
->name
); /* XXX */
4394 dispose_variable (var
);
4397 /* Pop the top context off of VCXT and dispose of it, returning the rest of
4402 VAR_CONTEXT
*ret
, *vcxt
;
4404 vcxt
= shell_variables
;
4405 if (vc_isfuncenv (vcxt
) == 0)
4407 internal_error (_("pop_var_context: head of shell_variables not a function context"));
4411 if (ret
= vcxt
->down
)
4413 ret
->up
= (VAR_CONTEXT
*)NULL
;
4414 shell_variables
= ret
;
4416 hash_flush (vcxt
->table
, push_func_var
);
4417 dispose_var_context (vcxt
);
4420 internal_error (_("pop_var_context: no global_variables context"));
4423 /* Delete the HASH_TABLEs for all variable contexts beginning at VCXT, and
4424 all of the VAR_CONTEXTs except GLOBAL_VARIABLES. */
4426 delete_all_contexts (vcxt
)
4431 for (v
= vcxt
; v
!= global_variables
; v
= t
)
4434 dispose_var_context (v
);
4437 delete_all_variables (global_variables
->table
);
4438 shell_variables
= global_variables
;
4441 /* **************************************************************** */
4443 /* Pushing and Popping temporary variable scopes */
4445 /* **************************************************************** */
4448 push_scope (flags
, tmpvars
)
4450 HASH_TABLE
*tmpvars
;
4452 return (push_var_context ((char *)NULL
, flags
, tmpvars
));
4456 push_exported_var (data
)
4461 var
= (SHELL_VAR
*)data
;
4463 /* If a temp var had its export attribute set, or it's marked to be
4464 propagated, bind it in the previous scope before disposing it. */
4465 /* XXX - This isn't exactly right, because all tempenv variables have the
4466 export attribute set. */
4468 if (exported_p (var
) || (var
->attributes
& att_propagate
))
4470 if (tempvar_p (var
) && exported_p (var
) && (var
->attributes
& att_propagate
))
4473 var
->attributes
&= ~att_tempvar
; /* XXX */
4474 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
4475 if (shell_variables
== global_variables
)
4476 var
->attributes
&= ~att_propagate
;
4477 v
->attributes
|= var
->attributes
;
4480 stupidly_hack_special_variables (var
->name
); /* XXX */
4482 dispose_variable (var
);
4486 pop_scope (is_special
)
4489 VAR_CONTEXT
*vcxt
, *ret
;
4491 vcxt
= shell_variables
;
4492 if (vc_istempscope (vcxt
) == 0)
4494 internal_error (_("pop_scope: head of shell_variables not a temporary environment scope"));
4500 ret
->up
= (VAR_CONTEXT
*)NULL
;
4502 shell_variables
= ret
;
4504 /* Now we can take care of merging variables in VCXT into set of scopes
4505 whose head is RET (shell_variables). */
4510 hash_flush (vcxt
->table
, push_func_var
);
4512 hash_flush (vcxt
->table
, push_exported_var
);
4513 hash_dispose (vcxt
->table
);
4517 sv_ifs ("IFS"); /* XXX here for now */
4520 /* **************************************************************** */
4522 /* Pushing and Popping function contexts */
4524 /* **************************************************************** */
4526 static WORD_LIST
**dollar_arg_stack
= (WORD_LIST
**)NULL
;
4527 static int dollar_arg_stack_slots
;
4528 static int dollar_arg_stack_index
;
4530 /* XXX - we might want to consider pushing and popping the `getopts' state
4531 when we modify the positional parameters. */
4533 push_context (name
, is_subshell
, tempvars
)
4534 char *name
; /* function name */
4536 HASH_TABLE
*tempvars
;
4538 if (is_subshell
== 0)
4539 push_dollar_vars ();
4541 push_var_context (name
, VC_FUNCENV
, tempvars
);
4544 /* Only called when subshell == 0, so we don't need to check, and can
4545 unconditionally pop the dollar vars off the stack. */
4553 sv_ifs ("IFS"); /* XXX here for now */
4556 /* Save the existing positional parameters on a stack. */
4560 if (dollar_arg_stack_index
+ 2 > dollar_arg_stack_slots
)
4562 dollar_arg_stack
= (WORD_LIST
**)
4563 xrealloc (dollar_arg_stack
, (dollar_arg_stack_slots
+= 10)
4564 * sizeof (WORD_LIST
*));
4566 dollar_arg_stack
[dollar_arg_stack_index
++] = list_rest_of_args ();
4567 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4570 /* Restore the positional parameters from our stack. */
4574 if (!dollar_arg_stack
|| dollar_arg_stack_index
== 0)
4577 remember_args (dollar_arg_stack
[--dollar_arg_stack_index
], 1);
4578 dispose_words (dollar_arg_stack
[dollar_arg_stack_index
]);
4579 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4580 set_dollar_vars_unchanged ();
4584 dispose_saved_dollar_vars ()
4586 if (!dollar_arg_stack
|| dollar_arg_stack_index
== 0)
4589 dispose_words (dollar_arg_stack
[dollar_arg_stack_index
]);
4590 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4593 /* Manipulate the special BASH_ARGV and BASH_ARGC variables. */
4599 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4600 SHELL_VAR
*bash_argv_v
, *bash_argc_v
;
4601 ARRAY
*bash_argv_a
, *bash_argc_a
;
4606 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v
, bash_argv_a
);
4607 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v
, bash_argc_a
);
4609 for (l
= list
, i
= 0; l
; l
= l
->next
, i
++)
4610 array_push (bash_argv_a
, l
->word
->word
);
4613 array_push (bash_argc_a
, t
);
4615 #endif /* ARRAY_VARS && DEBUGGER */
4618 /* Remove arguments from BASH_ARGV array. Pop top element off BASH_ARGC
4619 array and use that value as the count of elements to remove from
4624 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4625 SHELL_VAR
*bash_argv_v
, *bash_argc_v
;
4626 ARRAY
*bash_argv_a
, *bash_argc_a
;
4630 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v
, bash_argv_a
);
4631 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v
, bash_argc_a
);
4633 ce
= array_shift (bash_argc_a
, 1, 0);
4634 if (ce
== 0 || legal_number (element_value (ce
), &i
) == 0)
4638 array_pop (bash_argv_a
);
4639 array_dispose_element (ce
);
4640 #endif /* ARRAY_VARS && DEBUGGER */
4643 /*************************************************
4645 * Functions to manage special variables *
4647 *************************************************/
4649 /* Extern declarations for variables this code has to manage. */
4650 extern int eof_encountered
, eof_encountered_limit
, ignoreeof
;
4652 #if defined (READLINE)
4653 extern int hostname_list_initialized
;
4656 /* An alist of name.function for each special variable. Most of the
4657 functions don't do much, and in fact, this would be faster with a
4658 switch statement, but by the end of this file, I am sick of switch
4661 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
4663 /* This table will be sorted with qsort() the first time it's accessed. */
4664 struct name_and_function
{
4666 sh_sv_func_t
*function
;
4669 static struct name_and_function special_vars
[] = {
4670 { "BASH_COMPAT", sv_shcompat
},
4671 { "BASH_XTRACEFD", sv_xtracefd
},
4673 #if defined (JOB_CONTROL)
4674 { "CHILD_MAX", sv_childmax
},
4677 #if defined (READLINE)
4678 # if defined (STRICT_POSIX)
4679 { "COLUMNS", sv_winsize
},
4681 { "COMP_WORDBREAKS", sv_comp_wordbreaks
},
4684 { "FUNCNEST", sv_funcnest
},
4686 { "GLOBIGNORE", sv_globignore
},
4688 #if defined (HISTORY)
4689 { "HISTCONTROL", sv_history_control
},
4690 { "HISTFILESIZE", sv_histsize
},
4691 { "HISTIGNORE", sv_histignore
},
4692 { "HISTSIZE", sv_histsize
},
4693 { "HISTTIMEFORMAT", sv_histtimefmt
},
4696 #if defined (__CYGWIN__)
4697 { "HOME", sv_home
},
4700 #if defined (READLINE)
4701 { "HOSTFILE", sv_hostfile
},
4705 { "IGNOREEOF", sv_ignoreeof
},
4707 { "LANG", sv_locale
},
4708 { "LC_ALL", sv_locale
},
4709 { "LC_COLLATE", sv_locale
},
4710 { "LC_CTYPE", sv_locale
},
4711 { "LC_MESSAGES", sv_locale
},
4712 { "LC_NUMERIC", sv_locale
},
4713 { "LC_TIME", sv_locale
},
4715 #if defined (READLINE) && defined (STRICT_POSIX)
4716 { "LINES", sv_winsize
},
4719 { "MAIL", sv_mail
},
4720 { "MAILCHECK", sv_mail
},
4721 { "MAILPATH", sv_mail
},
4723 { "OPTERR", sv_opterr
},
4724 { "OPTIND", sv_optind
},
4726 { "PATH", sv_path
},
4727 { "POSIXLY_CORRECT", sv_strict_posix
},
4729 #if defined (READLINE)
4730 { "TERM", sv_terminal
},
4731 { "TERMCAP", sv_terminal
},
4732 { "TERMINFO", sv_terminal
},
4733 #endif /* READLINE */
4735 { "TEXTDOMAIN", sv_locale
},
4736 { "TEXTDOMAINDIR", sv_locale
},
4738 #if defined (HAVE_TZSET)
4742 #if defined (HISTORY) && defined (BANG_HISTORY)
4743 { "histchars", sv_histchars
},
4744 #endif /* HISTORY && BANG_HISTORY */
4746 { "ignoreeof", sv_ignoreeof
},
4748 { (char *)0, (sh_sv_func_t
*)0 }
4751 #define N_SPECIAL_VARS (sizeof (special_vars) / sizeof (special_vars[0]) - 1)
4754 sv_compare (sv1
, sv2
)
4755 struct name_and_function
*sv1
, *sv2
;
4759 if ((r
= sv1
->name
[0] - sv2
->name
[0]) == 0)
4760 r
= strcmp (sv1
->name
, sv2
->name
);
4765 find_special_var (name
)
4770 for (i
= 0; special_vars
[i
].name
; i
++)
4772 r
= special_vars
[i
].name
[0] - name
[0];
4774 r
= strcmp (special_vars
[i
].name
, name
);
4778 /* Can't match any of rest of elements in sorted list. Take this out
4779 if it causes problems in certain environments. */
4785 /* The variable in NAME has just had its state changed. Check to see if it
4786 is one of the special ones where something special happens. */
4788 stupidly_hack_special_variables (name
)
4791 static int sv_sorted
= 0;
4794 if (sv_sorted
== 0) /* shouldn't need, but it's fairly cheap. */
4796 qsort (special_vars
, N_SPECIAL_VARS
, sizeof (special_vars
[0]),
4797 (QSFUNC
*)sv_compare
);
4801 i
= find_special_var (name
);
4803 (*(special_vars
[i
].function
)) (name
);
4806 /* Special variables that need hooks to be run when they are unset as part
4807 of shell reinitialization should have their sv_ functions run here. */
4809 reinit_special_variables ()
4811 #if defined (READLINE)
4812 sv_comp_wordbreaks ("COMP_WORDBREAKS");
4814 sv_globignore ("GLOBIGNORE");
4815 sv_opterr ("OPTERR");
4824 v
= find_variable ("IFS");
4828 /* What to do just after the PATH variable has changed. */
4837 /* What to do just after one of the MAILxxxx variables has changed. NAME
4838 is the name of the variable. This is called with NAME set to one of
4839 MAIL, MAILCHECK, or MAILPATH. */
4844 /* If the time interval for checking the files has changed, then
4845 reset the mail timer. Otherwise, one of the pathname vars
4846 to the users mailbox has changed, so rebuild the array of
4848 if (name
[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
4849 reset_mail_timer ();
4853 remember_mail_dates ();
4864 v
= find_variable (name
);
4867 else if (legal_number (value_cell (v
), &num
) == 0)
4873 /* What to do when GLOBIGNORE changes. */
4875 sv_globignore (name
)
4878 if (privileged_mode
== 0)
4879 setup_glob_ignore (name
);
4882 #if defined (READLINE)
4884 sv_comp_wordbreaks (name
)
4889 sv
= find_variable (name
);
4891 reset_completer_word_break_chars ();
4894 /* What to do just after one of the TERMxxx variables has changed.
4895 If we are an interactive shell, then try to reset the terminal
4896 information in readline. */
4901 if (interactive_shell
&& no_line_editing
== 0)
4902 rl_reset_terminal (get_string_value ("TERM"));
4911 v
= find_variable (name
);
4913 clear_hostname_list ();
4915 hostname_list_initialized
= 0;
4918 #if defined (STRICT_POSIX)
4919 /* In strict posix mode, we allow assignments to LINES and COLUMNS (and values
4920 found in the initial environment) to override the terminal size reported by
4930 if (posixly_correct
== 0 || interactive_shell
== 0 || no_line_editing
)
4933 v
= find_variable (name
);
4934 if (v
== 0 || var_isnull (v
))
4935 rl_reset_screen_size ();
4938 if (legal_number (value_cell (v
), &xd
) == 0)
4940 winsize_assignment
= 1;
4941 d
= xd
; /* truncate */
4942 if (name
[0] == 'L') /* LINES */
4943 rl_set_screen_size (d
, -1);
4945 rl_set_screen_size (-1, d
);
4946 winsize_assignment
= 0;
4949 #endif /* STRICT_POSIX */
4950 #endif /* READLINE */
4952 /* Update the value of HOME in the export environment so tilde expansion will
4954 #if defined (__CYGWIN__)
4958 array_needs_making
= 1;
4959 maybe_make_export_env ();
4963 #if defined (HISTORY)
4964 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
4965 If there is a value for this HISTSIZE (and it is numeric), then stifle
4966 the history. Otherwise, if there is NO value for this variable,
4967 unstifle the history. If name is HISTFILESIZE, and its value is
4968 numeric, truncate the history file to hold no more than that many
4978 temp
= get_string_value (name
);
4982 if (legal_number (temp
, &num
))
4985 if (hmax
< 0 && name
[4] == 'S')
4986 unstifle_history (); /* unstifle history if HISTSIZE < 0 */
4987 else if (name
[4] == 'S')
4989 stifle_history (hmax
);
4990 hmax
= where_history ();
4991 if (history_lines_this_session
> hmax
)
4992 history_lines_this_session
= hmax
;
4994 else if (hmax
>= 0) /* truncate HISTFILE if HISTFILESIZE >= 0 */
4996 history_truncate_file (get_string_value ("HISTFILE"), hmax
);
4997 if (hmax
<= history_lines_in_file
)
4998 history_lines_in_file
= hmax
;
5002 else if (name
[4] == 'S')
5003 unstifle_history ();
5006 /* What to do after the HISTIGNORE variable changes. */
5008 sv_histignore (name
)
5011 setup_history_ignore (name
);
5014 /* What to do after the HISTCONTROL variable changes. */
5016 sv_history_control (name
)
5023 history_control
= 0;
5024 temp
= get_string_value (name
);
5026 if (temp
== 0 || *temp
== 0)
5030 while (val
= extract_colon_unit (temp
, &tptr
))
5032 if (STREQ (val
, "ignorespace"))
5033 history_control
|= HC_IGNSPACE
;
5034 else if (STREQ (val
, "ignoredups"))
5035 history_control
|= HC_IGNDUPS
;
5036 else if (STREQ (val
, "ignoreboth"))
5037 history_control
|= HC_IGNBOTH
;
5038 else if (STREQ (val
, "erasedups"))
5039 history_control
|= HC_ERASEDUPS
;
5045 #if defined (BANG_HISTORY)
5046 /* Setting/unsetting of the history expansion character. */
5053 temp
= get_string_value (name
);
5056 history_expansion_char
= *temp
;
5057 if (temp
[0] && temp
[1])
5059 history_subst_char
= temp
[1];
5061 history_comment_char
= temp
[2];
5066 history_expansion_char
= '!';
5067 history_subst_char
= '^';
5068 history_comment_char
= '#';
5071 #endif /* BANG_HISTORY */
5074 sv_histtimefmt (name
)
5079 if (v
= find_variable (name
))
5081 if (history_comment_char
== 0)
5082 history_comment_char
= '#';
5084 history_write_timestamps
= (v
!= 0);
5086 #endif /* HISTORY */
5088 #if defined (HAVE_TZSET)
5093 if (chkexport (name
))
5098 /* If the variable exists, then the value of it can be the number
5099 of times we actually ignore the EOF. The default is small,
5100 (smaller than csh, anyway). */
5108 eof_encountered
= 0;
5110 tmp_var
= find_variable (name
);
5111 ignoreeof
= tmp_var
!= 0;
5112 temp
= tmp_var
? value_cell (tmp_var
) : (char *)NULL
;
5114 eof_encountered_limit
= (*temp
&& all_digits (temp
)) ? atoi (temp
) : 10;
5115 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
5125 tt
= get_string_value ("OPTIND");
5130 /* According to POSIX, setting OPTIND=1 resets the internal state
5132 if (s
< 0 || s
== 1)
5146 tt
= get_string_value ("OPTERR");
5147 sh_opterr
= (tt
&& *tt
) ? atoi (tt
) : 1;
5151 sv_strict_posix (name
)
5154 SET_INT_VAR (name
, posixly_correct
);
5155 posix_initialize (posixly_correct
);
5156 #if defined (READLINE)
5157 if (interactive_shell
)
5158 posix_readline_initialize (posixly_correct
);
5159 #endif /* READLINE */
5160 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
5170 v
= get_string_value (name
);
5171 if (name
[0] == 'L' && name
[1] == 'A') /* LANG */
5172 r
= set_lang (name
, v
);
5174 r
= set_locale_var (name
, v
); /* LC_*, TEXTDOMAIN* */
5177 if (r
== 0 && posixly_correct
)
5178 last_command_exit_value
= 1;
5182 #if defined (ARRAY_VARS)
5184 set_pipestatus_array (ps
, nproc
)
5192 char *t
, tbuf
[INT_STRLEN_BOUND(int) + 1];
5194 v
= find_variable ("PIPESTATUS");
5196 v
= make_new_array_variable ("PIPESTATUS");
5197 if (array_p (v
) == 0)
5198 return; /* Do nothing if not an array variable. */
5201 if (a
== 0 || array_num_elements (a
) == 0)
5203 for (i
= 0; i
< nproc
; i
++) /* was ps[i] != -1, not i < nproc */
5205 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5206 array_insert (a
, i
, t
);
5212 if (array_num_elements (a
) == nproc
&& nproc
== 1)
5214 ae
= element_forw (a
->head
);
5215 free (element_value (ae
));
5216 ae
->value
= itos (ps
[0]);
5218 else if (array_num_elements (a
) <= nproc
)
5220 /* modify in array_num_elements members in place, then add */
5222 for (i
= 0; i
< array_num_elements (a
); i
++)
5224 ae
= element_forw (ae
);
5225 free (element_value (ae
));
5226 ae
->value
= itos (ps
[i
]);
5229 for ( ; i
< nproc
; i
++)
5231 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5232 array_insert (a
, i
, t
);
5237 /* deleting elements. it's faster to rebuild the array. */
5239 for (i
= 0; ps
[i
] != -1; i
++)
5241 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5242 array_insert (a
, i
, t
);
5248 save_pipestatus_array ()
5253 v
= find_variable ("PIPESTATUS");
5254 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
5255 return ((ARRAY
*)NULL
);
5258 a2
= array_copy (array_cell (v
));
5264 restore_pipestatus_array (a
)
5270 v
= find_variable ("PIPESTATUS");
5271 /* XXX - should we still assign even if existing value is NULL? */
5272 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
5275 a2
= array_cell (v
);
5276 var_setarray (v
, a
);
5283 set_pipestatus_from_exit (s
)
5286 #if defined (ARRAY_VARS)
5287 static int v
[2] = { 0, -1 };
5290 set_pipestatus_array (v
, 1);
5303 v
= find_variable (name
);
5311 if (t
== 0 || *t
== 0)
5315 fd
= (int)strtol (t
, &e
, 10);
5316 if (e
!= t
&& *e
== '\0' && sh_validfd (fd
))
5318 fp
= fdopen (fd
, "w");
5320 internal_error (_("%s: %s: cannot open as FILE"), name
, value_cell (v
));
5322 xtrace_set (fd
, fp
);
5325 internal_error (_("%s: %s: invalid value for trace file descriptor"), name
, value_cell (v
));
5329 #define MIN_COMPAT_LEVEL 31
5337 int tens
, ones
, compatval
;
5339 v
= find_variable (name
);
5342 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5343 set_compatibility_opts ();
5346 val
= value_cell (v
);
5347 if (val
== 0 || *val
== '\0')
5349 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5350 set_compatibility_opts ();
5353 /* Handle decimal-like compatibility version specifications: 4.2 */
5354 if (isdigit (val
[0]) && val
[1] == '.' && isdigit (val
[2]) && val
[3] == 0)
5356 tens
= val
[0] - '0';
5357 ones
= val
[2] - '0';
5358 compatval
= tens
*10 + ones
;
5360 /* Handle integer-like compatibility version specifications: 42 */
5361 else if (isdigit (val
[0]) && isdigit (val
[1]) && val
[2] == 0)
5363 tens
= val
[0] - '0';
5364 ones
= val
[1] - '0';
5365 compatval
= tens
*10 + ones
;
5370 internal_error (_("%s: %s: compatibility value out of range"), name
, val
);
5371 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5372 set_compatibility_opts ();
5376 if (compatval
< MIN_COMPAT_LEVEL
|| compatval
> DEFAULT_COMPAT_LEVEL
)
5379 shell_compatibility_level
= compatval
;
5380 set_compatibility_opts ();
5383 #if defined (JOB_CONTROL)
5391 tt
= get_string_value (name
);
5392 s
= (tt
&& *tt
) ? atoi (tt
) : 0;