1 /* variables.c -- Functions for hacking shell variables. */
3 /* Copyright (C) 1987-2014 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 /* flags for find_variable_internal */
93 #define FV_FORCETEMPENV 0x01
94 #define FV_SKIPINVISIBLE 0x02
96 extern char **environ
;
98 /* Variables used here and defined in other files. */
99 extern int posixly_correct
;
100 extern int line_number
, line_number_base
;
101 extern int subshell_environment
, indirection_level
, subshell_level
;
102 extern int build_version
, patch_level
;
103 extern int expanding_redir
;
104 extern int last_command_exit_value
;
105 extern char *dist_version
, *release_status
;
106 extern char *shell_name
;
107 extern char *primary_prompt
, *secondary_prompt
;
108 extern char *current_host_name
;
109 extern sh_builtin_func_t
*this_shell_builtin
;
110 extern SHELL_VAR
*this_shell_function
;
111 extern char *the_printed_command_except_trap
;
112 extern char *this_command_name
;
113 extern char *command_execution_string
;
114 extern time_t shell_start_time
;
115 extern int assigning_in_environment
;
116 extern int executing_builtin
;
117 extern int funcnest_max
;
119 #if defined (READLINE)
120 extern int no_line_editing
;
121 extern int perform_hostname_completion
;
124 /* The list of shell variables that the user has created at the global
125 scope, or that came from the environment. */
126 VAR_CONTEXT
*global_variables
= (VAR_CONTEXT
*)NULL
;
128 /* The current list of shell variables, including function scopes */
129 VAR_CONTEXT
*shell_variables
= (VAR_CONTEXT
*)NULL
;
131 /* The list of shell functions that the user has created, or that came from
133 HASH_TABLE
*shell_functions
= (HASH_TABLE
*)NULL
;
135 #if defined (DEBUGGER)
136 /* The table of shell function definitions that the user defined or that
137 came from the environment. */
138 HASH_TABLE
*shell_function_defs
= (HASH_TABLE
*)NULL
;
141 /* The current variable context. This is really a count of how deep into
142 executing functions we are. */
143 int variable_context
= 0;
145 /* The set of shell assignments which are made only in the environment
146 for a single command. */
147 HASH_TABLE
*temporary_env
= (HASH_TABLE
*)NULL
;
149 /* Set to non-zero if an assignment error occurs while putting variables
150 into the temporary environment. */
151 int tempenv_assign_error
;
153 /* Some funky variables which are known about specially. Here is where
154 "$*", "$1", and all the cruft is kept. */
155 char *dollar_vars
[10];
156 WORD_LIST
*rest_of_args
= (WORD_LIST
*)NULL
;
158 /* The value of $$. */
159 pid_t dollar_dollar_pid
;
161 /* Non-zero means that we have to remake EXPORT_ENV. */
162 int array_needs_making
= 1;
164 /* The number of times BASH has been executed. This is set
165 by initialize_variables (). */
168 /* An array which is passed to commands as their environment. It is
169 manufactured from the union of the initial environment and the
170 shell variables that are marked for export. */
171 char **export_env
= (char **)NULL
;
172 static int export_env_index
;
173 static int export_env_size
;
175 #if defined (READLINE)
176 static int winsize_assignment
; /* currently assigning to LINES or COLUMNS */
179 static HASH_TABLE
*last_table_searched
; /* hash_lookup sets this */
181 /* Some forward declarations. */
182 static void create_variable_tables
__P((void));
184 static void set_machine_vars
__P((void));
185 static void set_home_var
__P((void));
186 static void set_shell_var
__P((void));
187 static char *get_bash_name
__P((void));
188 static void initialize_shell_level
__P((void));
189 static void uidset
__P((void));
190 #if defined (ARRAY_VARS)
191 static void make_vers_array
__P((void));
194 static SHELL_VAR
*null_assign
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
195 #if defined (ARRAY_VARS)
196 static SHELL_VAR
*null_array_assign
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
198 static SHELL_VAR
*get_self
__P((SHELL_VAR
*));
200 #if defined (ARRAY_VARS)
201 static SHELL_VAR
*init_dynamic_array_var
__P((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
202 static SHELL_VAR
*init_dynamic_assoc_var
__P((char *, sh_var_value_func_t
*, sh_var_assign_func_t
*, int));
205 static SHELL_VAR
*assign_seconds
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
206 static SHELL_VAR
*get_seconds
__P((SHELL_VAR
*));
207 static SHELL_VAR
*init_seconds_var
__P((void));
209 static int brand
__P((void));
210 static void sbrand
__P((unsigned long)); /* set bash random number generator. */
211 static void seedrand
__P((void)); /* seed generator randomly */
212 static SHELL_VAR
*assign_random
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
213 static SHELL_VAR
*get_random
__P((SHELL_VAR
*));
215 static SHELL_VAR
*assign_lineno
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
216 static SHELL_VAR
*get_lineno
__P((SHELL_VAR
*));
218 static SHELL_VAR
*assign_subshell
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
219 static SHELL_VAR
*get_subshell
__P((SHELL_VAR
*));
221 static SHELL_VAR
*get_bashpid
__P((SHELL_VAR
*));
223 #if defined (HISTORY)
224 static SHELL_VAR
*get_histcmd
__P((SHELL_VAR
*));
227 #if defined (READLINE)
228 static SHELL_VAR
*get_comp_wordbreaks
__P((SHELL_VAR
*));
229 static SHELL_VAR
*assign_comp_wordbreaks
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
232 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
233 static SHELL_VAR
*assign_dirstack
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
234 static SHELL_VAR
*get_dirstack
__P((SHELL_VAR
*));
237 #if defined (ARRAY_VARS)
238 static SHELL_VAR
*get_groupset
__P((SHELL_VAR
*));
240 static SHELL_VAR
*build_hashcmd
__P((SHELL_VAR
*));
241 static SHELL_VAR
*get_hashcmd
__P((SHELL_VAR
*));
242 static SHELL_VAR
*assign_hashcmd
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
244 static SHELL_VAR
*build_aliasvar
__P((SHELL_VAR
*));
245 static SHELL_VAR
*get_aliasvar
__P((SHELL_VAR
*));
246 static SHELL_VAR
*assign_aliasvar
__P((SHELL_VAR
*, char *, arrayind_t
, char *));
250 static SHELL_VAR
*get_funcname
__P((SHELL_VAR
*));
251 static SHELL_VAR
*init_funcname_var
__P((void));
253 static void initialize_dynamic_variables
__P((void));
255 static SHELL_VAR
*hash_lookup
__P((const char *, HASH_TABLE
*));
256 static SHELL_VAR
*new_shell_variable
__P((const char *));
257 static SHELL_VAR
*make_new_variable
__P((const char *, HASH_TABLE
*));
258 static SHELL_VAR
*bind_variable_internal
__P((const char *, char *, HASH_TABLE
*, int, int));
260 static void dispose_variable_value
__P((SHELL_VAR
*));
261 static void free_variable_hash_data
__P((PTR_T
));
263 static VARLIST
*vlist_alloc
__P((int));
264 static VARLIST
*vlist_realloc
__P((VARLIST
*, int));
265 static void vlist_add
__P((VARLIST
*, SHELL_VAR
*, int));
267 static void flatten
__P((HASH_TABLE
*, sh_var_map_func_t
*, VARLIST
*, int));
269 static int qsort_var_comp
__P((SHELL_VAR
**, SHELL_VAR
**));
271 static SHELL_VAR
**vapply
__P((sh_var_map_func_t
*));
272 static SHELL_VAR
**fapply
__P((sh_var_map_func_t
*));
274 static int visible_var
__P((SHELL_VAR
*));
275 static int visible_and_exported
__P((SHELL_VAR
*));
276 static int export_environment_candidate
__P((SHELL_VAR
*));
277 static int local_and_exported
__P((SHELL_VAR
*));
278 static int variable_in_context
__P((SHELL_VAR
*));
279 #if defined (ARRAY_VARS)
280 static int visible_array_vars
__P((SHELL_VAR
*));
283 static SHELL_VAR
*find_nameref_at_context
__P((SHELL_VAR
*, VAR_CONTEXT
*));
284 static SHELL_VAR
*find_variable_nameref_context
__P((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
285 static SHELL_VAR
*find_variable_last_nameref_context
__P((SHELL_VAR
*, VAR_CONTEXT
*, VAR_CONTEXT
**));
287 static SHELL_VAR
*bind_tempenv_variable
__P((const char *, char *));
288 static void push_temp_var
__P((PTR_T
));
289 static void propagate_temp_var
__P((PTR_T
));
290 static void dispose_temporary_env
__P((sh_free_func_t
*));
292 static inline char *mk_env_string
__P((const char *, const char *, int));
293 static char **make_env_array_from_var_list
__P((SHELL_VAR
**));
294 static char **make_var_export_array
__P((VAR_CONTEXT
*));
295 static char **make_func_export_array
__P((void));
296 static void add_temp_array_to_env
__P((char **, int, int));
298 static int n_shell_variables
__P((void));
299 static int set_context
__P((SHELL_VAR
*));
301 static void push_func_var
__P((PTR_T
));
302 static void push_exported_var
__P((PTR_T
));
304 static inline int find_special_var
__P((const char *));
307 create_variable_tables ()
309 if (shell_variables
== 0)
311 shell_variables
= global_variables
= new_var_context ((char *)NULL
, 0);
312 shell_variables
->scope
= 0;
313 shell_variables
->table
= hash_create (0);
316 if (shell_functions
== 0)
317 shell_functions
= hash_create (0);
319 #if defined (DEBUGGER)
320 if (shell_function_defs
== 0)
321 shell_function_defs
= hash_create (0);
325 /* Initialize the shell variables from the current environment.
326 If PRIVMODE is nonzero, don't import functions from ENV or
329 initialize_shell_variables (env
, privmode
)
333 char *name
, *string
, *temp_string
;
334 int c
, char_index
, string_index
, string_length
, ro
;
337 create_variable_tables ();
339 for (string_index
= 0; string
= env
[string_index
++]; )
343 while ((c
= *string
++) && c
!= '=')
345 if (string
[-1] == '=')
346 char_index
= string
- name
- 1;
348 /* If there are weird things in the environment, like `=xxx' or a
349 string without an `=', just skip them. */
353 /* ASSERT(name[char_index] == '=') */
354 name
[char_index
] = '\0';
355 /* Now, name = env variable name, string = env variable value, and
356 char_index == strlen (name) */
358 temp_var
= (SHELL_VAR
*)NULL
;
360 /* If exported function, define it now. Don't import functions from
361 the environment in privileged mode. */
362 if (privmode
== 0 && read_but_dont_execute
== 0 &&
363 STREQN (BASHFUNC_PREFIX
, name
, BASHFUNC_PREFLEN
) &&
364 STREQ (BASHFUNC_SUFFIX
, name
+ char_index
- BASHFUNC_SUFFLEN
) &&
365 STREQN ("() {", string
, 4))
368 char *tname
; /* desired imported function name */
370 namelen
= char_index
- BASHFUNC_PREFLEN
- BASHFUNC_SUFFLEN
;
372 tname
= name
+ BASHFUNC_PREFLEN
; /* start of func name */
373 tname
[namelen
] = '\0'; /* now tname == func name */
375 string_length
= strlen (string
);
376 temp_string
= (char *)xmalloc (namelen
+ string_length
+ 2);
378 memcpy (temp_string
, tname
, namelen
);
379 temp_string
[namelen
] = ' ';
380 memcpy (temp_string
+ namelen
+ 1, string
, string_length
+ 1);
382 /* Don't import function names that are invalid identifiers from the
383 environment in posix mode, though we still allow them to be defined as
385 if (absolute_program (tname
) == 0 && (posixly_correct
== 0 || legal_identifier (tname
)))
386 parse_and_execute (temp_string
, tname
, SEVAL_NONINT
|SEVAL_NOHIST
|SEVAL_FUNCDEF
|SEVAL_ONECMD
);
388 free (temp_string
); /* parse_and_execute does this */
390 if (temp_var
= find_function (tname
))
392 VSETATTR (temp_var
, (att_exported
|att_imported
));
393 array_needs_making
= 1;
397 if (temp_var
= bind_variable (name
, string
, 0))
399 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
400 array_needs_making
= 1;
402 last_command_exit_value
= 1;
403 report_error (_("error importing function definition for `%s'"), tname
);
406 /* Restore original suffix */
407 tname
[namelen
] = BASHFUNC_SUFFIX
[0];
409 #if defined (ARRAY_VARS)
411 /* Array variables may not yet be exported. */
412 else if (*string
== '(' && string
[1] == '[' && string
[strlen (string
) - 1] == ')')
415 temp_string
= extract_array_assignment_list (string
, &string_length
);
416 temp_var
= assign_array_from_string (name
, temp_string
);
418 VSETATTR (temp_var
, (att_exported
| att_imported
));
419 array_needs_making
= 1;
421 # endif /* ARRAY_EXPORT */
424 else if (legal_identifier (name
))
430 if (posixly_correct
&& STREQ (name
, "SHELLOPTS"))
432 temp_var
= find_variable ("SHELLOPTS");
433 ro
= temp_var
&& readonly_p (temp_var
);
435 VUNSETATTR (temp_var
, att_readonly
);
437 temp_var
= bind_variable (name
, string
, 0);
440 if (legal_identifier (name
))
441 VSETATTR (temp_var
, (att_exported
| att_imported
));
443 VSETATTR (temp_var
, (att_exported
| att_imported
| att_invisible
));
445 VSETATTR (temp_var
, att_readonly
);
446 array_needs_making
= 1;
450 name
[char_index
] = '=';
451 /* temp_var can be NULL if it was an exported function with a syntax
452 error (a different bug, but it still shouldn't dump core). */
453 if (temp_var
&& function_p (temp_var
) == 0) /* XXX not yet */
455 CACHE_IMPORTSTR (temp_var
, name
);
461 /* Set up initial value of $_ */
462 temp_var
= set_if_not ("_", dollar_vars
[0]);
464 /* Remember this pid. */
465 dollar_dollar_pid
= getpid ();
467 /* Now make our own defaults in case the vars that we think are
468 important are missing. */
469 temp_var
= set_if_not ("PATH", DEFAULT_PATH_VALUE
);
471 set_auto_export (temp_var
); /* XXX */
474 temp_var
= set_if_not ("TERM", "dumb");
476 set_auto_export (temp_var
); /* XXX */
479 #if defined (__QNX__)
480 /* set node id -- don't import it from the environment */
483 # if defined (__QNXNTO__)
484 netmgr_ndtostr(ND2S_LOCAL_STR
, ND_LOCAL_NODE
, node_name
, sizeof(node_name
));
486 qnx_nidtostr (getnid (), node_name
, sizeof (node_name
));
488 temp_var
= bind_variable ("NODE", node_name
, 0);
489 set_auto_export (temp_var
);
493 /* set up the prompts. */
494 if (interactive_shell
)
496 #if defined (PROMPT_STRING_DECODE)
497 set_if_not ("PS1", primary_prompt
);
499 if (current_user
.uid
== -1)
500 get_current_user_info ();
501 set_if_not ("PS1", current_user
.euid
== 0 ? "# " : primary_prompt
);
503 set_if_not ("PS2", secondary_prompt
);
505 set_if_not ("PS4", "+ ");
507 /* Don't allow IFS to be imported from the environment. */
508 temp_var
= bind_variable ("IFS", " \t\n", 0);
511 /* Magic machine types. Pretty convenient. */
514 /* Default MAILCHECK for interactive shells. Defer the creation of a
515 default MAILPATH until the startup files are read, because MAIL
516 names a mail file if MAILPATH is not set, and we should provide a
517 default only if neither is set. */
518 if (interactive_shell
)
520 temp_var
= set_if_not ("MAILCHECK", posixly_correct
? "600" : "60");
521 VSETATTR (temp_var
, att_integer
);
524 /* Do some things with shell level. */
525 initialize_shell_level ();
529 /* Initialize the `getopts' stuff. */
530 temp_var
= bind_variable ("OPTIND", "1", 0);
531 VSETATTR (temp_var
, att_integer
);
533 bind_variable ("OPTERR", "1", 0);
536 if (login_shell
== 1 && posixly_correct
== 0)
539 /* Get the full pathname to THIS shell, and set the BASH variable
541 name
= get_bash_name ();
542 temp_var
= bind_variable ("BASH", name
, 0);
545 /* Make the exported environment variable SHELL be the user's login
546 shell. Note that the `tset' command looks at this variable
547 to determine what style of commands to output; if it ends in "csh",
548 then C-shell commands are output, else Bourne shell commands. */
551 /* Make a variable called BASH_VERSION which contains the version info. */
552 bind_variable ("BASH_VERSION", shell_version_string (), 0);
553 #if defined (ARRAY_VARS)
557 if (command_execution_string
)
558 bind_variable ("BASH_EXECUTION_STRING", command_execution_string
, 0);
560 /* Find out if we're supposed to be in Posix.2 mode via an
561 environment variable. */
562 temp_var
= find_variable ("POSIXLY_CORRECT");
564 temp_var
= find_variable ("POSIX_PEDANTIC");
565 if (temp_var
&& imported_p (temp_var
))
566 sv_strict_posix (temp_var
->name
);
568 #if defined (HISTORY)
569 /* Set history variables to defaults, and then do whatever we would
570 do if the variable had just been set. Do this only in the case
571 that we are remembering commands on the history list. */
572 if (remember_on_history
)
574 name
= bash_tilde_expand (posixly_correct
? "~/.sh_history" : "~/.bash_history", 0);
576 set_if_not ("HISTFILE", name
);
581 /* Seed the random number generator. */
584 /* Handle some "special" variables that we may have inherited from a
586 if (interactive_shell
)
588 temp_var
= find_variable ("IGNOREEOF");
590 temp_var
= find_variable ("ignoreeof");
591 if (temp_var
&& imported_p (temp_var
))
592 sv_ignoreeof (temp_var
->name
);
595 #if defined (HISTORY)
596 if (interactive_shell
&& remember_on_history
)
598 sv_history_control ("HISTCONTROL");
599 sv_histignore ("HISTIGNORE");
600 sv_histtimefmt ("HISTTIMEFORMAT");
604 #if defined (READLINE) && defined (STRICT_POSIX)
605 /* POSIXLY_CORRECT will only be 1 here if the shell was compiled
607 if (interactive_shell
&& posixly_correct
&& no_line_editing
== 0)
608 rl_prefer_env_winsize
= 1;
609 #endif /* READLINE && STRICT_POSIX */
614 * I'm tired of the arguing and bug reports. Bash now leaves SSH_CLIENT
615 * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in
616 * isnetconn() to avoid running the startup files more often than wanted.
617 * That will, of course, only work if the user's login shell is bash, so
618 * I've made that behavior conditional on SSH_SOURCE_BASHRC being defined
622 temp_var
= find_variable ("SSH_CLIENT");
623 if (temp_var
&& imported_p (temp_var
))
625 VUNSETATTR (temp_var
, att_exported
);
626 array_needs_making
= 1;
628 temp_var
= find_variable ("SSH2_CLIENT");
629 if (temp_var
&& imported_p (temp_var
))
631 VUNSETATTR (temp_var
, att_exported
);
632 array_needs_making
= 1;
636 /* Get the user's real and effective user ids. */
639 temp_var
= find_variable ("BASH_XTRACEFD");
640 if (temp_var
&& imported_p (temp_var
))
641 sv_xtracefd (temp_var
->name
);
643 /* Initialize the dynamic variables, and seed their values. */
644 initialize_dynamic_variables ();
647 /* **************************************************************** */
649 /* Setting values for special shell variables */
651 /* **************************************************************** */
658 temp_var
= set_if_not ("HOSTTYPE", HOSTTYPE
);
659 temp_var
= set_if_not ("OSTYPE", OSTYPE
);
660 temp_var
= set_if_not ("MACHTYPE", MACHTYPE
);
662 temp_var
= set_if_not ("HOSTNAME", current_host_name
);
665 /* Set $HOME to the information in the password file if we didn't get
666 it from the environment. */
668 /* This function is not static so the tilde and readline libraries can
673 if (current_user
.home_dir
== 0)
674 get_current_user_info ();
675 return current_user
.home_dir
;
683 temp_var
= find_variable ("HOME");
685 temp_var
= bind_variable ("HOME", sh_get_home_dir (), 0);
687 VSETATTR (temp_var
, att_exported
);
691 /* Set $SHELL to the user's login shell if it is not already set. Call
692 get_current_user_info if we haven't already fetched the shell. */
698 temp_var
= find_variable ("SHELL");
701 if (current_user
.shell
== 0)
702 get_current_user_info ();
703 temp_var
= bind_variable ("SHELL", current_user
.shell
, 0);
706 VSETATTR (temp_var
, att_exported
);
715 if ((login_shell
== 1) && RELPATH(shell_name
))
717 if (current_user
.shell
== 0)
718 get_current_user_info ();
719 name
= savestring (current_user
.shell
);
721 else if (ABSPATH(shell_name
))
722 name
= savestring (shell_name
);
723 else if (shell_name
[0] == '.' && shell_name
[1] == '/')
725 /* Fast path for common case. */
729 cdir
= get_string_value ("PWD");
733 name
= (char *)xmalloc (len
+ strlen (shell_name
) + 1);
735 strcpy (name
+ len
, shell_name
+ 1);
738 name
= savestring (shell_name
);
745 tname
= find_user_command (shell_name
);
749 /* Try the current directory. If there is not an executable
750 there, just punt and use the login shell. */
751 s
= file_status (shell_name
);
754 tname
= make_absolute (shell_name
, get_string_value ("PWD"));
755 if (*shell_name
== '.')
757 name
= sh_canonpath (tname
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
768 if (current_user
.shell
== 0)
769 get_current_user_info ();
770 name
= savestring (current_user
.shell
);
775 name
= full_pathname (tname
);
784 adjust_shell_level (change
)
787 char new_level
[5], *old_SHLVL
;
791 old_SHLVL
= get_string_value ("SHLVL");
792 if (old_SHLVL
== 0 || *old_SHLVL
== '\0' || legal_number (old_SHLVL
, &old_level
) == 0)
795 shell_level
= old_level
+ change
;
798 else if (shell_level
> 1000)
800 internal_warning (_("shell level (%d) too high, resetting to 1"), shell_level
);
804 /* We don't need the full generality of itos here. */
805 if (shell_level
< 10)
807 new_level
[0] = shell_level
+ '0';
810 else if (shell_level
< 100)
812 new_level
[0] = (shell_level
/ 10) + '0';
813 new_level
[1] = (shell_level
% 10) + '0';
816 else if (shell_level
< 1000)
818 new_level
[0] = (shell_level
/ 100) + '0';
819 old_level
= shell_level
% 100;
820 new_level
[1] = (old_level
/ 10) + '0';
821 new_level
[2] = (old_level
% 10) + '0';
825 temp_var
= bind_variable ("SHLVL", new_level
, 0);
826 set_auto_export (temp_var
);
830 initialize_shell_level ()
832 adjust_shell_level (1);
835 /* If we got PWD from the environment, update our idea of the current
836 working directory. In any case, make sure that PWD exists before
837 checking it. It is possible for getcwd () to fail on shell startup,
838 and in that case, PWD would be undefined. If this is an interactive
839 login shell, see if $HOME is the current working directory, and if
840 that's not the same string as $PWD, set PWD=$HOME. */
845 SHELL_VAR
*temp_var
, *home_var
;
846 char *temp_string
, *home_string
;
848 home_var
= find_variable ("HOME");
849 home_string
= home_var
? value_cell (home_var
) : (char *)NULL
;
851 temp_var
= find_variable ("PWD");
852 if (temp_var
&& imported_p (temp_var
) &&
853 (temp_string
= value_cell (temp_var
)) &&
854 same_file (temp_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
855 set_working_directory (temp_string
);
856 else if (home_string
&& interactive_shell
&& login_shell
&&
857 same_file (home_string
, ".", (struct stat
*)NULL
, (struct stat
*)NULL
))
859 set_working_directory (home_string
);
860 temp_var
= bind_variable ("PWD", home_string
, 0);
861 set_auto_export (temp_var
);
865 temp_string
= get_working_directory ("shell-init");
868 temp_var
= bind_variable ("PWD", temp_string
, 0);
869 set_auto_export (temp_var
);
874 /* According to the Single Unix Specification, v2, $OLDPWD is an
875 `environment variable' and therefore should be auto-exported.
876 Make a dummy invisible variable for OLDPWD, and mark it as exported. */
877 temp_var
= bind_variable ("OLDPWD", (char *)NULL
, 0);
878 VSETATTR (temp_var
, (att_exported
| att_invisible
));
881 /* Make a variable $PPID, which holds the pid of the shell's parent. */
885 char namebuf
[INT_STRLEN_BOUND(pid_t
) + 1], *name
;
888 name
= inttostr (getppid (), namebuf
, sizeof(namebuf
));
889 temp_var
= find_variable ("PPID");
891 VUNSETATTR (temp_var
, (att_readonly
| att_exported
));
892 temp_var
= bind_variable ("PPID", name
, 0);
893 VSETATTR (temp_var
, (att_readonly
| att_integer
));
899 char buff
[INT_STRLEN_BOUND(uid_t
) + 1], *b
;
900 register SHELL_VAR
*v
;
902 b
= inttostr (current_user
.uid
, buff
, sizeof (buff
));
903 v
= find_variable ("UID");
906 v
= bind_variable ("UID", b
, 0);
907 VSETATTR (v
, (att_readonly
| att_integer
));
910 if (current_user
.euid
!= current_user
.uid
)
911 b
= inttostr (current_user
.euid
, buff
, sizeof (buff
));
913 v
= find_variable ("EUID");
916 v
= bind_variable ("EUID", b
, 0);
917 VSETATTR (v
, (att_readonly
| att_integer
));
921 #if defined (ARRAY_VARS)
927 char *s
, d
[32], b
[INT_STRLEN_BOUND(int) + 1];
929 unbind_variable ("BASH_VERSINFO");
931 vv
= make_new_array_variable ("BASH_VERSINFO");
932 av
= array_cell (vv
);
933 strcpy (d
, dist_version
);
937 array_insert (av
, 0, d
);
938 array_insert (av
, 1, s
);
939 s
= inttostr (patch_level
, b
, sizeof (b
));
940 array_insert (av
, 2, s
);
941 s
= inttostr (build_version
, b
, sizeof (b
));
942 array_insert (av
, 3, s
);
943 array_insert (av
, 4, release_status
);
944 array_insert (av
, 5, MACHTYPE
);
946 VSETATTR (vv
, att_readonly
);
948 #endif /* ARRAY_VARS */
950 /* Set the environment variables $LINES and $COLUMNS in response to
951 a window size change. */
953 sh_set_lines_and_columns (lines
, cols
)
956 char val
[INT_STRLEN_BOUND(int) + 1], *v
;
958 #if defined (READLINE)
959 /* If we are currently assigning to LINES or COLUMNS, don't do anything. */
960 if (winsize_assignment
)
964 v
= inttostr (lines
, val
, sizeof (val
));
965 bind_variable ("LINES", v
, 0);
967 v
= inttostr (cols
, val
, sizeof (val
));
968 bind_variable ("COLUMNS", v
, 0);
971 /* **************************************************************** */
973 /* Printing variables and values */
975 /* **************************************************************** */
977 /* Print LIST (a list of shell variables) to stdout in such a way that
978 they can be read back in. */
980 print_var_list (list
)
981 register SHELL_VAR
**list
;
984 register SHELL_VAR
*var
;
986 for (i
= 0; list
&& (var
= list
[i
]); i
++)
987 if (invisible_p (var
) == 0)
988 print_assignment (var
);
991 /* Print LIST (a list of shell functions) to stdout in such a way that
992 they can be read back in. */
994 print_func_list (list
)
995 register SHELL_VAR
**list
;
998 register SHELL_VAR
*var
;
1000 for (i
= 0; list
&& (var
= list
[i
]); i
++)
1002 printf ("%s ", var
->name
);
1003 print_var_function (var
);
1008 /* Print the value of a single SHELL_VAR. No newline is
1009 output, but the variable is printed in such a way that
1010 it can be read back in. */
1012 print_assignment (var
)
1015 if (var_isset (var
) == 0)
1018 if (function_p (var
))
1020 printf ("%s", var
->name
);
1021 print_var_function (var
);
1024 #if defined (ARRAY_VARS)
1025 else if (array_p (var
))
1026 print_array_assignment (var
, 0);
1027 else if (assoc_p (var
))
1028 print_assoc_assignment (var
, 0);
1029 #endif /* ARRAY_VARS */
1032 printf ("%s=", var
->name
);
1033 print_var_value (var
, 1);
1038 /* Print the value cell of VAR, a shell variable. Do not print
1039 the name, nor leading/trailing newline. If QUOTE is non-zero,
1040 and the value contains shell metacharacters, quote the value
1041 in such a way that it can be read back in. */
1043 print_var_value (var
, quote
)
1049 if (var_isset (var
) == 0)
1052 if (quote
&& posixly_correct
== 0 && ansic_shouldquote (value_cell (var
)))
1054 t
= ansic_quote (value_cell (var
), 0, (int *)0);
1058 else if (quote
&& sh_contains_shell_metas (value_cell (var
)))
1060 t
= sh_single_quote (value_cell (var
));
1065 printf ("%s", value_cell (var
));
1068 /* Print the function cell of VAR, a shell variable. Do not
1069 print the name, nor leading/trailing newline. */
1071 print_var_function (var
)
1076 if (function_p (var
) && var_isset (var
))
1078 x
= named_function_string ((char *)NULL
, function_cell(var
), FUNC_MULTILINE
|FUNC_EXTERNAL
);
1083 /* **************************************************************** */
1085 /* Dynamic Variables */
1087 /* **************************************************************** */
1089 /* DYNAMIC VARIABLES
1091 These are variables whose values are generated anew each time they are
1092 referenced. These are implemented using a pair of function pointers
1093 in the struct variable: assign_func, which is called from bind_variable
1094 and, if arrays are compiled into the shell, some of the functions in
1095 arrayfunc.c, and dynamic_value, which is called from find_variable.
1097 assign_func is called from bind_variable_internal, if
1098 bind_variable_internal discovers that the variable being assigned to
1099 has such a function. The function is called as
1100 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value, ind)
1101 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
1102 is usually ENTRY (self). IND is an index for an array variable, and
1105 dynamic_value is called from find_variable_internal to return a `new'
1106 value for the specified dynamic varible. If this function is NULL,
1107 the variable is treated as a `normal' shell variable. If it is not,
1108 however, then this function is called like this:
1109 tempvar = (*(var->dynamic_value)) (var);
1111 Sometimes `tempvar' will replace the value of `var'. Other times, the
1112 shell will simply use the string value. Pretty object-oriented, huh?
1114 Be warned, though: if you `unset' a special variable, it loses its
1115 special meaning, even if you subsequently set it.
1117 The special assignment code would probably have been better put in
1118 subst.c: do_assignment_internal, in the same style as
1119 stupidly_hack_special_variables, but I wanted the changes as
1120 localized as possible. */
1122 #define INIT_DYNAMIC_VAR(var, val, gfunc, afunc) \
1125 v = bind_variable (var, (val), 0); \
1126 v->dynamic_value = gfunc; \
1127 v->assign_func = afunc; \
1131 #define INIT_DYNAMIC_ARRAY_VAR(var, gfunc, afunc) \
1134 v = make_new_array_variable (var); \
1135 v->dynamic_value = gfunc; \
1136 v->assign_func = afunc; \
1140 #define INIT_DYNAMIC_ASSOC_VAR(var, gfunc, afunc) \
1143 v = make_new_assoc_variable (var); \
1144 v->dynamic_value = gfunc; \
1145 v->assign_func = afunc; \
1150 null_assign (self
, value
, unused
, key
)
1159 #if defined (ARRAY_VARS)
1161 null_array_assign (self
, value
, ind
, key
)
1171 /* Degenerate `dynamic_value' function; just returns what's passed without
1180 #if defined (ARRAY_VARS)
1181 /* A generic dynamic array variable initializer. Initialize array variable
1182 NAME with dynamic value function GETFUNC and assignment function SETFUNC. */
1184 init_dynamic_array_var (name
, getfunc
, setfunc
, attrs
)
1186 sh_var_value_func_t
*getfunc
;
1187 sh_var_assign_func_t
*setfunc
;
1192 v
= find_variable (name
);
1195 INIT_DYNAMIC_ARRAY_VAR (name
, getfunc
, setfunc
);
1197 VSETATTR (v
, attrs
);
1202 init_dynamic_assoc_var (name
, getfunc
, setfunc
, attrs
)
1204 sh_var_value_func_t
*getfunc
;
1205 sh_var_assign_func_t
*setfunc
;
1210 v
= find_variable (name
);
1213 INIT_DYNAMIC_ASSOC_VAR (name
, getfunc
, setfunc
);
1215 VSETATTR (v
, attrs
);
1220 /* The value of $SECONDS. This is the number of seconds since shell
1221 invocation, or, the number of seconds since the last assignment + the
1222 value of the last assignment. */
1223 static intmax_t seconds_value_assigned
;
1226 assign_seconds (self
, value
, unused
, key
)
1232 if (legal_number (value
, &seconds_value_assigned
) == 0)
1233 seconds_value_assigned
= 0;
1234 shell_start_time
= NOW
;
1242 time_t time_since_start
;
1245 time_since_start
= NOW
- shell_start_time
;
1246 p
= itos(seconds_value_assigned
+ time_since_start
);
1248 FREE (value_cell (var
));
1250 VSETATTR (var
, att_integer
);
1251 var_setvalue (var
, p
);
1260 v
= find_variable ("SECONDS");
1263 if (legal_number (value_cell(v
), &seconds_value_assigned
) == 0)
1264 seconds_value_assigned
= 0;
1266 INIT_DYNAMIC_VAR ("SECONDS", (v
? value_cell (v
) : (char *)NULL
), get_seconds
, assign_seconds
);
1270 /* The random number seed. You can change this by setting RANDOM. */
1271 static unsigned long rseed
= 1;
1272 static int last_random_value
;
1273 static int seeded_subshell
= 0;
1275 /* A linear congruential random number generator based on the example
1276 one in the ANSI C standard. This one isn't very good, but a more
1277 complicated one is overkill. */
1279 /* Returns a pseudo-random number between 0 and 32767. */
1283 /* From "Random number generators: good ones are hard to find",
1284 Park and Miller, Communications of the ACM, vol. 31, no. 10,
1285 October 1988, p. 1195. filtered through FreeBSD */
1288 /* Can't seed with 0. */
1293 rseed
= 16807 * l
- 2836 * h
;
1296 rseed
+= 0x7fffffff;
1298 return ((unsigned int)(rseed
& 32767)); /* was % 32768 */
1301 /* Set the random number generator seed to SEED. */
1307 last_random_value
= 0;
1315 gettimeofday (&tv
, NULL
);
1316 sbrand (tv
.tv_sec
^ tv
.tv_usec
^ getpid ());
1320 assign_random (self
, value
, unused
, key
)
1326 sbrand (strtoul (value
, (char **)NULL
, 10));
1327 if (subshell_environment
)
1328 seeded_subshell
= getpid ();
1333 get_random_number ()
1337 /* Reset for command and process substitution. */
1339 if (subshell_environment
&& seeded_subshell
!= pid
)
1342 seeded_subshell
= pid
;
1347 while (rv
== last_random_value
);
1358 rv
= get_random_number ();
1359 last_random_value
= rv
;
1362 FREE (value_cell (var
));
1364 VSETATTR (var
, att_integer
);
1365 var_setvalue (var
, p
);
1370 assign_lineno (var
, value
, unused
, key
)
1378 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1380 line_number
= line_number_base
= new_value
;
1384 /* Function which returns the current line number. */
1392 ln
= executing_line_number ();
1394 FREE (value_cell (var
));
1395 var_setvalue (var
, p
);
1400 assign_subshell (var
, value
, unused
, key
)
1408 if (value
== 0 || *value
== '\0' || legal_number (value
, &new_value
) == 0)
1410 subshell_level
= new_value
;
1420 p
= itos (subshell_level
);
1421 FREE (value_cell (var
));
1422 var_setvalue (var
, p
);
1436 FREE (value_cell (var
));
1437 VSETATTR (var
, att_integer
|att_readonly
);
1438 var_setvalue (var
, p
);
1443 get_bash_command (var
)
1448 if (the_printed_command_except_trap
)
1449 p
= savestring (the_printed_command_except_trap
);
1452 p
= (char *)xmalloc (1);
1455 FREE (value_cell (var
));
1456 var_setvalue (var
, p
);
1460 #if defined (HISTORY)
1467 p
= itos (history_number ());
1468 FREE (value_cell (var
));
1469 var_setvalue (var
, p
);
1474 #if defined (READLINE)
1475 /* When this function returns, VAR->value points to malloced memory. */
1477 get_comp_wordbreaks (var
)
1480 /* If we don't have anything yet, assign a default value. */
1481 if (rl_completer_word_break_characters
== 0 && bash_readline_initialized
== 0)
1482 enable_hostname_completion (perform_hostname_completion
);
1484 FREE (value_cell (var
));
1485 var_setvalue (var
, savestring (rl_completer_word_break_characters
));
1490 /* When this function returns, rl_completer_word_break_characters points to
1493 assign_comp_wordbreaks (self
, value
, unused
, key
)
1499 if (rl_completer_word_break_characters
&&
1500 rl_completer_word_break_characters
!= rl_basic_word_break_characters
)
1501 free (rl_completer_word_break_characters
);
1503 rl_completer_word_break_characters
= savestring (value
);
1506 #endif /* READLINE */
1508 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1510 assign_dirstack (self
, value
, ind
, key
)
1516 set_dirstack_element (ind
, 1, value
);
1527 l
= get_directory_stack (0);
1528 a
= array_from_word_list (l
);
1529 array_dispose (array_cell (self
));
1531 var_setarray (self
, a
);
1534 #endif /* PUSHD AND POPD && ARRAY_VARS */
1536 #if defined (ARRAY_VARS)
1537 /* We don't want to initialize the group set with a call to getgroups()
1538 unless we're asked to, but we only want to do it once. */
1546 static char **group_set
= (char **)NULL
;
1550 group_set
= get_group_list (&ng
);
1551 a
= array_cell (self
);
1552 for (i
= 0; i
< ng
; i
++)
1553 array_insert (a
, i
, group_set
[i
]);
1559 build_hashcmd (self
)
1565 BUCKET_CONTENTS
*item
;
1567 h
= assoc_cell (self
);
1571 if (hashed_filenames
== 0 || HASH_ENTRIES (hashed_filenames
) == 0)
1573 var_setvalue (self
, (char *)NULL
);
1577 h
= assoc_create (hashed_filenames
->nbuckets
);
1578 for (i
= 0; i
< hashed_filenames
->nbuckets
; i
++)
1580 for (item
= hash_items (i
, hashed_filenames
); item
; item
= item
->next
)
1582 k
= savestring (item
->key
);
1583 v
= pathdata(item
)->path
;
1584 assoc_insert (h
, k
, v
);
1588 var_setvalue (self
, (char *)h
);
1596 build_hashcmd (self
);
1601 assign_hashcmd (self
, value
, ind
, key
)
1607 phash_insert (key
, value
, 0, 0);
1608 return (build_hashcmd (self
));
1613 build_aliasvar (self
)
1619 BUCKET_CONTENTS
*item
;
1621 h
= assoc_cell (self
);
1625 if (aliases
== 0 || HASH_ENTRIES (aliases
) == 0)
1627 var_setvalue (self
, (char *)NULL
);
1631 h
= assoc_create (aliases
->nbuckets
);
1632 for (i
= 0; i
< aliases
->nbuckets
; i
++)
1634 for (item
= hash_items (i
, aliases
); item
; item
= item
->next
)
1636 k
= savestring (item
->key
);
1637 v
= ((alias_t
*)(item
->data
))->value
;
1638 assoc_insert (h
, k
, v
);
1642 var_setvalue (self
, (char *)h
);
1650 build_aliasvar (self
);
1655 assign_aliasvar (self
, value
, ind
, key
)
1661 add_alias (key
, value
);
1662 return (build_aliasvar (self
));
1666 #endif /* ARRAY_VARS */
1668 /* If ARRAY_VARS is not defined, this just returns the name of any
1669 currently-executing function. If we have arrays, it's a call stack. */
1674 #if ! defined (ARRAY_VARS)
1676 if (variable_context
&& this_shell_function
)
1678 FREE (value_cell (self
));
1679 t
= savestring (this_shell_function
->name
);
1680 var_setvalue (self
, t
);
1687 make_funcname_visible (on_or_off
)
1692 v
= find_variable ("FUNCNAME");
1693 if (v
== 0 || v
->dynamic_value
== 0)
1697 VUNSETATTR (v
, att_invisible
);
1699 VSETATTR (v
, att_invisible
);
1703 init_funcname_var ()
1707 v
= find_variable ("FUNCNAME");
1710 #if defined (ARRAY_VARS)
1711 INIT_DYNAMIC_ARRAY_VAR ("FUNCNAME", get_funcname
, null_array_assign
);
1713 INIT_DYNAMIC_VAR ("FUNCNAME", (char *)NULL
, get_funcname
, null_assign
);
1715 VSETATTR (v
, att_invisible
|att_noassign
);
1720 initialize_dynamic_variables ()
1724 v
= init_seconds_var ();
1726 INIT_DYNAMIC_VAR ("BASH_COMMAND", (char *)NULL
, get_bash_command
, (sh_var_assign_func_t
*)NULL
);
1727 INIT_DYNAMIC_VAR ("BASH_SUBSHELL", (char *)NULL
, get_subshell
, assign_subshell
);
1729 INIT_DYNAMIC_VAR ("RANDOM", (char *)NULL
, get_random
, assign_random
);
1730 VSETATTR (v
, att_integer
);
1731 INIT_DYNAMIC_VAR ("LINENO", (char *)NULL
, get_lineno
, assign_lineno
);
1732 VSETATTR (v
, att_integer
);
1734 INIT_DYNAMIC_VAR ("BASHPID", (char *)NULL
, get_bashpid
, null_assign
);
1735 VSETATTR (v
, att_integer
|att_readonly
);
1737 #if defined (HISTORY)
1738 INIT_DYNAMIC_VAR ("HISTCMD", (char *)NULL
, get_histcmd
, (sh_var_assign_func_t
*)NULL
);
1739 VSETATTR (v
, att_integer
);
1742 #if defined (READLINE)
1743 INIT_DYNAMIC_VAR ("COMP_WORDBREAKS", (char *)NULL
, get_comp_wordbreaks
, assign_comp_wordbreaks
);
1746 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1747 v
= init_dynamic_array_var ("DIRSTACK", get_dirstack
, assign_dirstack
, 0);
1748 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1750 #if defined (ARRAY_VARS)
1751 v
= init_dynamic_array_var ("GROUPS", get_groupset
, null_array_assign
, att_noassign
);
1753 # if defined (DEBUGGER)
1754 v
= init_dynamic_array_var ("BASH_ARGC", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1755 v
= init_dynamic_array_var ("BASH_ARGV", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1756 # endif /* DEBUGGER */
1757 v
= init_dynamic_array_var ("BASH_SOURCE", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1758 v
= init_dynamic_array_var ("BASH_LINENO", get_self
, null_array_assign
, att_noassign
|att_nounset
);
1760 v
= init_dynamic_assoc_var ("BASH_CMDS", get_hashcmd
, assign_hashcmd
, att_nofree
);
1761 # if defined (ALIAS)
1762 v
= init_dynamic_assoc_var ("BASH_ALIASES", get_aliasvar
, assign_aliasvar
, att_nofree
);
1766 v
= init_funcname_var ();
1769 /* **************************************************************** */
1771 /* Retrieving variables and values */
1773 /* **************************************************************** */
1775 /* How to get a pointer to the shell variable or function named NAME.
1776 HASHED_VARS is a pointer to the hash table containing the list
1777 of interest (either variables or functions). */
1780 hash_lookup (name
, hashed_vars
)
1782 HASH_TABLE
*hashed_vars
;
1784 BUCKET_CONTENTS
*bucket
;
1786 bucket
= hash_search (name
, hashed_vars
, 0);
1787 /* If we find the name in HASHED_VARS, set LAST_TABLE_SEARCHED to that
1790 last_table_searched
= hashed_vars
;
1791 return (bucket
? (SHELL_VAR
*)bucket
->data
: (SHELL_VAR
*)NULL
);
1795 var_lookup (name
, vcontext
)
1797 VAR_CONTEXT
*vcontext
;
1802 v
= (SHELL_VAR
*)NULL
;
1803 for (vc
= vcontext
; vc
; vc
= vc
->down
)
1804 if (v
= hash_lookup (name
, vc
->table
))
1810 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
1811 then also search the temporarily built list of exported variables.
1812 The lookup order is:
1814 shell_variables list
1818 find_variable_internal (name
, flags
)
1823 int search_tempenv
, force_tempenv
;
1826 var
= (SHELL_VAR
*)NULL
;
1828 force_tempenv
= (flags
& FV_FORCETEMPENV
);
1830 /* If explicitly requested, first look in the temporary environment for
1831 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
1832 to get the `exported' value of $foo. This happens if we are executing
1833 a function or builtin, or if we are looking up a variable in a
1834 "subshell environment". */
1835 search_tempenv
= force_tempenv
|| (expanding_redir
== 0 && subshell_environment
);
1837 if (search_tempenv
&& temporary_env
)
1838 var
= hash_lookup (name
, temporary_env
);
1842 if ((flags
& FV_SKIPINVISIBLE
) == 0)
1843 var
= var_lookup (name
, shell_variables
);
1846 /* essentially var_lookup expanded inline so we can check for
1848 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
1850 var
= hash_lookup (name
, vc
->table
);
1851 if (var
&& invisible_p (var
))
1860 return ((SHELL_VAR
*)NULL
);
1862 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
1865 /* Look up and resolve the chain of nameref variables starting at V all the
1866 way to NULL or non-nameref. */
1868 find_variable_nameref (v
)
1873 SHELL_VAR
*orig
, *oldv
;
1877 while (v
&& nameref_p (v
))
1880 if (level
> NAMEREF_MAX
)
1881 return ((SHELL_VAR
*)0); /* error message here? */
1882 newname
= nameref_cell (v
);
1883 if (newname
== 0 || *newname
== '\0')
1884 return ((SHELL_VAR
*)0);
1887 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
1888 flags
|= FV_FORCETEMPENV
;
1889 v
= find_variable_internal (newname
, flags
);
1890 if (v
== orig
|| v
== oldv
)
1892 internal_warning (_("%s: circular name reference"), orig
->name
);
1893 return ((SHELL_VAR
*)0);
1899 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
1901 find_variable_last_nameref (name
)
1908 nv
= v
= find_variable_noref (name
);
1910 while (v
&& nameref_p (v
))
1913 if (level
> NAMEREF_MAX
)
1914 return ((SHELL_VAR
*)0); /* error message here? */
1915 newname
= nameref_cell (v
);
1916 if (newname
== 0 || *newname
== '\0')
1917 return ((SHELL_VAR
*)0);
1920 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
1921 flags
|= FV_FORCETEMPENV
;
1922 v
= find_variable_internal (newname
, flags
);
1927 /* Resolve the chain of nameref variables for NAME. XXX - could change later */
1929 find_global_variable_last_nameref (name
)
1936 nv
= v
= find_global_variable_noref (name
);
1938 while (v
&& nameref_p (v
))
1941 if (level
> NAMEREF_MAX
)
1942 return ((SHELL_VAR
*)0); /* error message here? */
1943 newname
= nameref_cell (v
);
1944 if (newname
== 0 || *newname
== '\0')
1945 return ((SHELL_VAR
*)0);
1947 v
= find_global_variable_noref (newname
);
1953 find_nameref_at_context (v
, vc
)
1957 SHELL_VAR
*nv
, *nv2
;
1964 while (nv
&& nameref_p (nv
))
1967 if (level
> NAMEREF_MAX
)
1968 return ((SHELL_VAR
*)NULL
);
1969 newname
= nameref_cell (nv
);
1970 if (newname
== 0 || *newname
== '\0')
1971 return ((SHELL_VAR
*)NULL
);
1972 nv2
= hash_lookup (newname
, vc
->table
);
1980 /* Do nameref resolution from the VC, which is the local context for some
1981 function or builtin, `up' the chain to the global variables context. If
1982 NVCP is not NULL, return the variable context where we finally ended the
1983 nameref resolution (so the bind_variable_internal can use the correct
1984 variable context and hash table). */
1986 find_variable_nameref_context (v
, vc
, nvcp
)
1991 SHELL_VAR
*nv
, *nv2
;
1994 /* Look starting at the current context all the way `up' */
1995 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
1997 nv2
= find_nameref_at_context (nv
, nvc
);
2003 if (nameref_p (nv
) == 0)
2006 return (nameref_p (nv
) ? (SHELL_VAR
*)NULL
: nv
);
2009 /* Do nameref resolution from the VC, which is the local context for some
2010 function or builtin, `up' the chain to the global variables context. If
2011 NVCP is not NULL, return the variable context where we finally ended the
2012 nameref resolution (so the bind_variable_internal can use the correct
2013 variable context and hash table). */
2015 find_variable_last_nameref_context (v
, vc
, nvcp
)
2020 SHELL_VAR
*nv
, *nv2
;
2023 /* Look starting at the current context all the way `up' */
2024 for (nv
= v
, nvc
= vc
; nvc
; nvc
= nvc
->down
)
2026 nv2
= find_nameref_at_context (nv
, nvc
);
2033 return (nameref_p (nv
) ? nv
: (SHELL_VAR
*)NULL
);
2036 /* Find a variable, forcing a search of the temporary environment first */
2038 find_variable_tempenv (name
)
2043 var
= find_variable_internal (name
, FV_FORCETEMPENV
);
2044 if (var
&& nameref_p (var
))
2045 var
= find_variable_nameref (var
);
2049 /* Find a variable, not forcing a search of the temporary environment first */
2051 find_variable_notempenv (name
)
2056 var
= find_variable_internal (name
, 0);
2057 if (var
&& nameref_p (var
))
2058 var
= find_variable_nameref (var
);
2063 find_global_variable (name
)
2068 var
= var_lookup (name
, global_variables
);
2069 if (var
&& nameref_p (var
))
2070 var
= find_variable_nameref (var
);
2073 return ((SHELL_VAR
*)NULL
);
2075 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2079 find_global_variable_noref (name
)
2084 var
= var_lookup (name
, global_variables
);
2087 return ((SHELL_VAR
*)NULL
);
2089 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2093 find_shell_variable (name
)
2098 var
= var_lookup (name
, shell_variables
);
2099 if (var
&& nameref_p (var
))
2100 var
= find_variable_nameref (var
);
2103 return ((SHELL_VAR
*)NULL
);
2105 return (var
->dynamic_value
? (*(var
->dynamic_value
)) (var
) : var
);
2108 /* Look up the variable entry named NAME. Returns the entry or NULL. */
2110 find_variable (name
)
2116 last_table_searched
= 0;
2118 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2119 flags
|= FV_FORCETEMPENV
;
2120 v
= find_variable_internal (name
, flags
);
2121 if (v
&& nameref_p (v
))
2122 v
= find_variable_nameref (v
);
2126 /* Find the first instance of NAME in the variable context chain; return first
2127 one found without att_invisible set; return 0 if no non-invisible instances
2130 find_variable_no_invisible (name
)
2136 last_table_searched
= 0;
2137 flags
= FV_SKIPINVISIBLE
;
2138 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2139 flags
|= FV_FORCETEMPENV
;
2140 v
= find_variable_internal (name
, flags
);
2141 if (v
&& nameref_p (v
))
2142 v
= find_variable_nameref (v
);
2146 /* Find the first instance of NAME in the variable context chain; return first
2147 one found even if att_invisible set. */
2149 find_variable_for_assignment (name
)
2155 last_table_searched
= 0;
2157 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2158 flags
|= FV_FORCETEMPENV
;
2159 v
= find_variable_internal (name
, flags
);
2160 if (v
&& nameref_p (v
))
2161 v
= find_variable_nameref (v
);
2166 find_variable_noref (name
)
2173 if (expanding_redir
== 0 && (assigning_in_environment
|| executing_builtin
))
2174 flags
|= FV_FORCETEMPENV
;
2175 v
= find_variable_internal (name
, flags
);
2179 /* Look up the function entry whose name matches STRING.
2180 Returns the entry or NULL. */
2182 find_function (name
)
2185 return (hash_lookup (name
, shell_functions
));
2188 /* Find the function definition for the shell function named NAME. Returns
2189 the entry or NULL. */
2191 find_function_def (name
)
2194 #if defined (DEBUGGER)
2195 return ((FUNCTION_DEF
*)hash_lookup (name
, shell_function_defs
));
2197 return ((FUNCTION_DEF
*)0);
2201 /* Return the value of VAR. VAR is assumed to have been the result of a
2202 lookup without any subscript, if arrays are compiled into the shell. */
2204 get_variable_value (var
)
2208 return ((char *)NULL
);
2209 #if defined (ARRAY_VARS)
2210 else if (array_p (var
))
2211 return (array_reference (array_cell (var
), 0));
2212 else if (assoc_p (var
))
2213 return (assoc_reference (assoc_cell (var
), "0"));
2216 return (value_cell (var
));
2219 /* Return the string value of a variable. Return NULL if the variable
2220 doesn't exist. Don't cons a new string. This is a potential memory
2221 leak if the variable is found in the temporary environment. Since
2222 functions and variables have separate name spaces, returns NULL if
2223 var_name is a shell function only. */
2225 get_string_value (var_name
)
2226 const char *var_name
;
2230 var
= find_variable (var_name
);
2231 return ((var
) ? get_variable_value (var
) : (char *)NULL
);
2234 /* This is present for use by the tilde and readline libraries. */
2236 sh_get_env_value (v
)
2239 return get_string_value (v
);
2242 /* **************************************************************** */
2244 /* Creating and setting variables */
2246 /* **************************************************************** */
2248 /* Set NAME to VALUE if NAME has no value. */
2250 set_if_not (name
, value
)
2255 if (shell_variables
== 0)
2256 create_variable_tables ();
2258 v
= find_variable (name
);
2260 v
= bind_variable_internal (name
, value
, global_variables
->table
, HASH_NOSRCH
, 0);
2264 /* Create a local variable referenced by NAME. */
2266 make_local_variable (name
)
2269 SHELL_VAR
*new_var
, *old_var
;
2274 /* local foo; local foo; is a no-op. */
2275 old_var
= find_variable (name
);
2276 if (old_var
&& local_p (old_var
) && old_var
->context
== variable_context
)
2279 was_tmpvar
= old_var
&& tempvar_p (old_var
);
2280 /* If we're making a local variable in a shell function, the temporary env
2281 has already been merged into the function's variable context stack. We
2282 can assume that a temporary var in the same context appears in the same
2283 VAR_CONTEXT and can safely be returned without creating a new variable
2284 (which results in duplicate names in the same VAR_CONTEXT->table */
2285 /* We can't just test tmpvar_p because variables in the temporary env given
2286 to a shell function appear in the function's local variable VAR_CONTEXT
2287 but retain their tempvar attribute. We want temporary variables that are
2288 found in temporary_env, hence the test for last_table_searched, which is
2289 set in hash_lookup and only (so far) checked here. */
2290 if (was_tmpvar
&& old_var
->context
== variable_context
&& last_table_searched
!= temporary_env
)
2292 VUNSETATTR (old_var
, att_invisible
); /* XXX */
2296 tmp_value
= value_cell (old_var
);
2298 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2299 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
2304 internal_error (_("make_local_variable: no function context at current scope"));
2305 return ((SHELL_VAR
*)NULL
);
2307 else if (vc
->table
== 0)
2308 vc
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
2310 /* Since this is called only from the local/declare/typeset code, we can
2311 call builtin_error here without worry (of course, it will also work
2312 for anything that sets this_command_name). Variables with the `noassign'
2313 attribute may not be made local. The test against old_var's context
2314 level is to disallow local copies of readonly global variables (since I
2315 believe that this could be a security hole). Readonly copies of calling
2316 function local variables are OK. */
2317 if (old_var
&& (noassign_p (old_var
) ||
2318 (readonly_p (old_var
) && old_var
->context
== 0)))
2320 if (readonly_p (old_var
))
2322 else if (noassign_p (old_var
))
2323 builtin_error (_("%s: variable may not be assigned value"), name
);
2325 /* Let noassign variables through with a warning */
2326 if (readonly_p (old_var
))
2328 return ((SHELL_VAR
*)NULL
);
2332 new_var
= make_new_variable (name
, vc
->table
);
2335 new_var
= make_new_variable (name
, vc
->table
);
2337 /* If we found this variable in one of the temporary environments,
2338 inherit its value. Watch to see if this causes problems with
2339 things like `x=4 local x'. XXX - see above for temporary env
2340 variables with the same context level as variable_context */
2341 /* XXX - we should only do this if the variable is not an array. */
2343 var_setvalue (new_var
, savestring (tmp_value
));
2345 new_var
->attributes
= exported_p (old_var
) ? att_exported
: 0;
2348 vc
->flags
|= VC_HASLOCAL
;
2350 new_var
->context
= variable_context
;
2351 VSETATTR (new_var
, att_local
);
2356 if (was_tmpvar
== 0 && no_invisible_vars
== 0)
2357 VSETATTR (new_var
, att_invisible
); /* XXX */
2361 /* Create a new shell variable with name NAME. */
2363 new_shell_variable (name
)
2368 entry
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
2370 entry
->name
= savestring (name
);
2371 var_setvalue (entry
, (char *)NULL
);
2372 CLEAR_EXPORTSTR (entry
);
2374 entry
->dynamic_value
= (sh_var_value_func_t
*)NULL
;
2375 entry
->assign_func
= (sh_var_assign_func_t
*)NULL
;
2377 entry
->attributes
= 0;
2379 /* Always assume variables are to be made at toplevel!
2380 make_local_variable has the responsibility of changing the
2381 variable context. */
2387 /* Create a new shell variable with name NAME and add it to the hash table
2390 make_new_variable (name
, table
)
2395 BUCKET_CONTENTS
*elt
;
2397 entry
= new_shell_variable (name
);
2399 /* Make sure we have a shell_variables hash table to add to. */
2400 if (shell_variables
== 0)
2401 create_variable_tables ();
2403 elt
= hash_insert (savestring (name
), table
, HASH_NOSRCH
);
2404 elt
->data
= (PTR_T
)entry
;
2409 #if defined (ARRAY_VARS)
2411 make_new_array_variable (name
)
2417 entry
= make_new_variable (name
, global_variables
->table
);
2418 array
= array_create ();
2420 var_setarray (entry
, array
);
2421 VSETATTR (entry
, att_array
);
2426 make_local_array_variable (name
, assoc_ok
)
2433 var
= make_local_variable (name
);
2434 if (var
== 0 || array_p (var
) || (assoc_ok
&& assoc_p (var
)))
2437 array
= array_create ();
2439 dispose_variable_value (var
);
2440 var_setarray (var
, array
);
2441 VSETATTR (var
, att_array
);
2446 make_new_assoc_variable (name
)
2452 entry
= make_new_variable (name
, global_variables
->table
);
2453 hash
= assoc_create (0);
2455 var_setassoc (entry
, hash
);
2456 VSETATTR (entry
, att_assoc
);
2461 make_local_assoc_variable (name
)
2467 var
= make_local_variable (name
);
2468 if (var
== 0 || assoc_p (var
))
2471 dispose_variable_value (var
);
2472 hash
= assoc_create (0);
2474 var_setassoc (var
, hash
);
2475 VSETATTR (var
, att_assoc
);
2481 make_variable_value (var
, value
, flags
)
2486 char *retval
, *oval
;
2487 intmax_t lval
, rval
;
2488 int expok
, olen
, op
;
2490 /* If this variable has had its type set to integer (via `declare -i'),
2491 then do expression evaluation on it and store the result. The
2492 functions in expr.c (evalexp()) and bind_int_variable() are responsible
2493 for turning off the integer flag if they don't want further
2495 if (integer_p (var
))
2497 if (flags
& ASS_APPEND
)
2499 oval
= value_cell (var
);
2500 lval
= evalexp (oval
, &expok
); /* ksh93 seems to do this */
2503 top_level_cleanup ();
2504 jump_to_top_level (DISCARD
);
2507 rval
= evalexp (value
, &expok
);
2510 top_level_cleanup ();
2511 jump_to_top_level (DISCARD
);
2513 /* This can be fooled if the variable's value changes while evaluating
2514 `rval'. We can change it if we move the evaluation of lval to here. */
2515 if (flags
& ASS_APPEND
)
2517 retval
= itos (rval
);
2519 #if defined (CASEMOD_ATTRS)
2520 else if (capcase_p (var
) || uppercase_p (var
) || lowercase_p (var
))
2522 if (flags
& ASS_APPEND
)
2524 oval
= get_variable_value (var
);
2525 if (oval
== 0) /* paranoia */
2527 olen
= STRLEN (oval
);
2528 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2529 strcpy (retval
, oval
);
2531 strcpy (retval
+olen
, value
);
2534 retval
= savestring (value
);
2537 retval
= (char *)xmalloc (1);
2540 op
= capcase_p (var
) ? CASE_CAPITALIZE
2541 : (uppercase_p (var
) ? CASE_UPPER
: CASE_LOWER
);
2542 oval
= sh_modcase (retval
, (char *)0, op
);
2546 #endif /* CASEMOD_ATTRS */
2549 if (flags
& ASS_APPEND
)
2551 oval
= get_variable_value (var
);
2552 if (oval
== 0) /* paranoia */
2554 olen
= STRLEN (oval
);
2555 retval
= (char *)xmalloc (olen
+ (value
? STRLEN (value
) : 0) + 1);
2556 strcpy (retval
, oval
);
2558 strcpy (retval
+olen
, value
);
2561 retval
= savestring (value
);
2564 retval
= (char *)xmalloc (1);
2569 retval
= (char *)NULL
;
2574 /* Bind a variable NAME to VALUE in the HASH_TABLE TABLE, which may be the
2575 temporary environment (but usually is not). */
2577 bind_variable_internal (name
, value
, table
, hflags
, aflags
)
2586 entry
= (hflags
& HASH_NOSRCH
) ? (SHELL_VAR
*)NULL
: hash_lookup (name
, table
);
2587 /* Follow the nameref chain here if this is the global variables table */
2588 if (entry
&& nameref_p (entry
) && (invisible_p (entry
) == 0) && table
== global_variables
->table
)
2590 entry
= find_global_variable (entry
->name
);
2591 /* Let's see if we have a nameref referencing a variable that hasn't yet
2594 entry
= find_variable_last_nameref (name
); /* XXX */
2595 if (entry
== 0) /* just in case */
2599 /* The first clause handles `declare -n ref; ref=x;' */
2600 if (entry
&& invisible_p (entry
) && nameref_p (entry
))
2602 else if (entry
&& nameref_p (entry
))
2604 newval
= nameref_cell (entry
);
2605 #if defined (ARRAY_VARS)
2606 /* declare -n foo=x[2] */
2607 if (valid_array_reference (newval
))
2608 /* XXX - should it be aflags? */
2609 entry
= assign_array_element (newval
, make_variable_value (entry
, value
, 0), aflags
);
2613 entry
= make_new_variable (newval
, table
);
2614 var_setvalue (entry
, make_variable_value (entry
, value
, 0));
2617 else if (entry
== 0)
2619 entry
= make_new_variable (name
, table
);
2620 var_setvalue (entry
, make_variable_value (entry
, value
, 0)); /* XXX */
2622 else if (entry
->assign_func
) /* array vars have assign functions now */
2624 INVALIDATE_EXPORTSTR (entry
);
2625 newval
= (aflags
& ASS_APPEND
) ? make_variable_value (entry
, value
, aflags
) : value
;
2626 if (assoc_p (entry
))
2627 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, savestring ("0"));
2628 else if (array_p (entry
))
2629 entry
= (*(entry
->assign_func
)) (entry
, newval
, 0, 0);
2631 entry
= (*(entry
->assign_func
)) (entry
, newval
, -1, 0);
2632 if (newval
!= value
)
2639 if (readonly_p (entry
) || noassign_p (entry
))
2641 if (readonly_p (entry
))
2642 err_readonly (name
);
2646 /* Variables which are bound are visible. */
2647 VUNSETATTR (entry
, att_invisible
);
2649 #if defined (ARRAY_VARS)
2650 if (assoc_p (entry
) || array_p (entry
))
2651 newval
= make_array_variable_value (entry
, 0, "0", value
, aflags
);
2655 newval
= make_variable_value (entry
, value
, aflags
); /* XXX */
2657 /* Invalidate any cached export string */
2658 INVALIDATE_EXPORTSTR (entry
);
2660 #if defined (ARRAY_VARS)
2661 /* XXX -- this bears looking at again -- XXX */
2662 /* If an existing array variable x is being assigned to with x=b or
2663 `read x' or something of that nature, silently convert it to
2664 x[0]=b or `read x[0]'. */
2665 if (assoc_p (entry
))
2667 assoc_insert (assoc_cell (entry
), savestring ("0"), newval
);
2670 else if (array_p (entry
))
2672 array_insert (array_cell (entry
), 0, newval
);
2678 FREE (value_cell (entry
));
2679 var_setvalue (entry
, newval
);
2683 if (mark_modified_vars
)
2684 VSETATTR (entry
, att_exported
);
2686 if (exported_p (entry
))
2687 array_needs_making
= 1;
2692 /* Bind a variable NAME to VALUE. This conses up the name
2693 and value strings. If we have a temporary environment, we bind there
2694 first, then we bind into shell_variables. */
2697 bind_variable (name
, value
, flags
)
2703 VAR_CONTEXT
*vc
, *nvc
;
2706 if (shell_variables
== 0)
2707 create_variable_tables ();
2709 /* If we have a temporary environment, look there first for the variable,
2710 and, if found, modify the value there before modifying it in the
2711 shell_variables table. This allows sourced scripts to modify values
2712 given to them in a temporary environment while modifying the variable
2713 value that the caller sees. */
2715 bind_tempenv_variable (name
, value
);
2717 /* XXX -- handle local variables here. */
2718 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
2720 if (vc_isfuncenv (vc
) || vc_isbltnenv (vc
))
2722 v
= hash_lookup (name
, vc
->table
);
2724 if (v
&& nameref_p (v
))
2726 nv
= find_variable_nameref_context (v
, vc
, &nvc
);
2729 nv
= find_variable_last_nameref_context (v
, vc
, &nvc
);
2730 if (nv
&& nameref_p (nv
))
2732 /* If this nameref variable doesn't have a value yet,
2733 set the value. Otherwise, assign using the value as
2735 if (nameref_cell (nv
) == 0)
2736 return (bind_variable_internal (nv
->name
, value
, nvc
->table
, 0, flags
));
2737 #if defined (ARRAY_VARS)
2738 else if (valid_array_reference (nameref_cell (nv
)))
2739 return (assign_array_element (nameref_cell (nv
), value
, flags
));
2742 return (bind_variable_internal (nameref_cell (nv
), value
, nvc
->table
, 0, flags
));
2751 return (bind_variable_internal (v
->name
, value
, nvc
->table
, 0, flags
));
2754 /* bind_variable_internal will handle nameref resolution in this case */
2755 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
2759 bind_global_variable (name
, value
, flags
)
2765 VAR_CONTEXT
*vc
, *nvc
;
2768 if (shell_variables
== 0)
2769 create_variable_tables ();
2771 /* bind_variable_internal will handle nameref resolution in this case */
2772 return (bind_variable_internal (name
, value
, global_variables
->table
, 0, flags
));
2775 /* Make VAR, a simple shell variable, have value VALUE. Once assigned a
2776 value, variables are no longer invisible. This is a duplicate of part
2777 of the internals of bind_variable. If the variable is exported, or
2778 all modified variables should be exported, mark the variable for export
2779 and note that the export environment needs to be recreated. */
2781 bind_variable_value (var
, value
, aflags
)
2789 invis
= invisible_p (var
);
2790 VUNSETATTR (var
, att_invisible
);
2792 if (var
->assign_func
)
2794 /* If we're appending, we need the old value, so use
2795 make_variable_value */
2796 t
= (aflags
& ASS_APPEND
) ? make_variable_value (var
, value
, aflags
) : value
;
2797 (*(var
->assign_func
)) (var
, t
, -1, 0);
2798 if (t
!= value
&& t
)
2803 t
= make_variable_value (var
, value
, aflags
);
2804 #if defined (ARRAY_VARS)
2805 if ((aflags
& ASS_NAMEREF
) && (t
== 0 || *t
== 0 || (legal_identifier (t
) == 0 && valid_array_reference (t
) == 0)))
2807 if ((aflags
& ASS_NAMEREF
) && (t
== 0 || *t
== 0 || legal_identifier (t
) == 0))
2812 VSETATTR (var
, att_invisible
); /* XXX */
2813 return ((SHELL_VAR
*)NULL
);
2815 FREE (value_cell (var
));
2816 var_setvalue (var
, t
);
2819 INVALIDATE_EXPORTSTR (var
);
2821 if (mark_modified_vars
)
2822 VSETATTR (var
, att_exported
);
2824 if (exported_p (var
))
2825 array_needs_making
= 1;
2830 /* Bind/create a shell variable with the name LHS to the RHS.
2831 This creates or modifies a variable such that it is an integer.
2833 This used to be in expr.c, but it is here so that all of the
2834 variable binding stuff is localized. Since we don't want any
2835 recursive evaluation from bind_variable() (possible without this code,
2836 since bind_variable() calls the evaluator for variables with the integer
2837 attribute set), we temporarily turn off the integer attribute for each
2838 variable we set here, then turn it back on after binding as necessary. */
2841 bind_int_variable (lhs
, rhs
)
2844 register SHELL_VAR
*v
;
2845 int isint
, isarr
, implicitarray
;
2847 isint
= isarr
= implicitarray
= 0;
2848 #if defined (ARRAY_VARS)
2849 if (valid_array_reference (lhs
))
2852 v
= array_variable_part (lhs
, (char **)0, (int *)0);
2856 v
= find_variable (lhs
);
2860 isint
= integer_p (v
);
2861 VUNSETATTR (v
, att_integer
);
2862 #if defined (ARRAY_VARS)
2863 if (array_p (v
) && isarr
== 0)
2868 #if defined (ARRAY_VARS)
2870 v
= assign_array_element (lhs
, rhs
, 0);
2871 else if (implicitarray
)
2872 v
= bind_array_variable (lhs
, 0, rhs
, 0);
2875 v
= bind_variable (lhs
, rhs
, 0);
2878 VSETATTR (v
, att_integer
);
2880 VUNSETATTR (v
, att_invisible
);
2886 bind_var_to_int (var
, val
)
2890 char ibuf
[INT_STRLEN_BOUND (intmax_t) + 1], *p
;
2892 p
= fmtulong (val
, 10, ibuf
, sizeof (ibuf
), 0);
2893 return (bind_int_variable (var
, p
));
2896 /* Do a function binding to a variable. You pass the name and
2897 the command to bind to. This conses the name and command. */
2899 bind_function (name
, value
)
2905 entry
= find_function (name
);
2908 BUCKET_CONTENTS
*elt
;
2910 elt
= hash_insert (savestring (name
), shell_functions
, HASH_NOSRCH
);
2911 entry
= new_shell_variable (name
);
2912 elt
->data
= (PTR_T
)entry
;
2915 INVALIDATE_EXPORTSTR (entry
);
2917 if (var_isset (entry
))
2918 dispose_command (function_cell (entry
));
2921 var_setfunc (entry
, copy_command (value
));
2923 var_setfunc (entry
, 0);
2925 VSETATTR (entry
, att_function
);
2927 if (mark_modified_vars
)
2928 VSETATTR (entry
, att_exported
);
2930 VUNSETATTR (entry
, att_invisible
); /* Just to be sure */
2932 if (exported_p (entry
))
2933 array_needs_making
= 1;
2935 #if defined (PROGRAMMABLE_COMPLETION)
2936 set_itemlist_dirty (&it_functions
);
2942 #if defined (DEBUGGER)
2943 /* Bind a function definition, which includes source file and line number
2944 information in addition to the command, into the FUNCTION_DEF hash table.*/
2946 bind_function_def (name
, value
)
2948 FUNCTION_DEF
*value
;
2950 FUNCTION_DEF
*entry
;
2951 BUCKET_CONTENTS
*elt
;
2954 entry
= find_function_def (name
);
2957 dispose_function_def_contents (entry
);
2958 entry
= copy_function_def_contents (value
, entry
);
2962 cmd
= value
->command
;
2964 entry
= copy_function_def (value
);
2965 value
->command
= cmd
;
2967 elt
= hash_insert (savestring (name
), shell_function_defs
, HASH_NOSRCH
);
2968 elt
->data
= (PTR_T
*)entry
;
2971 #endif /* DEBUGGER */
2973 /* Add STRING, which is of the form foo=bar, to the temporary environment
2974 HASH_TABLE (temporary_env). The functions in execute_cmd.c are
2975 responsible for moving the main temporary env to one of the other
2976 temporary environments. The expansion code in subst.c calls this. */
2978 assign_in_env (word
, flags
)
2983 char *name
, *temp
, *value
;
2987 string
= word
->word
;
2990 offset
= assignment (string
, 0);
2991 name
= savestring (string
);
2992 value
= (char *)NULL
;
2994 if (name
[offset
] == '=')
2998 /* don't ignore the `+' when assigning temporary environment */
2999 if (name
[offset
- 1] == '+')
3001 name
[offset
- 1] = '\0';
3002 aflags
|= ASS_APPEND
;
3005 var
= find_variable (name
);
3006 if (var
&& (readonly_p (var
) || noassign_p (var
)))
3008 if (readonly_p (var
))
3009 err_readonly (name
);
3014 temp
= name
+ offset
+ 1;
3015 value
= expand_assignment_string_to_string (temp
, 0);
3017 if (var
&& (aflags
& ASS_APPEND
))
3019 temp
= make_variable_value (var
, value
, aflags
);
3025 if (temporary_env
== 0)
3026 temporary_env
= hash_create (TEMPENV_HASH_BUCKETS
);
3028 var
= hash_lookup (name
, temporary_env
);
3030 var
= make_new_variable (name
, temporary_env
);
3032 FREE (value_cell (var
));
3036 value
= (char *)xmalloc (1); /* like do_assignment_internal */
3040 var_setvalue (var
, value
);
3041 var
->attributes
|= (att_exported
|att_tempvar
);
3042 var
->context
= variable_context
; /* XXX */
3044 INVALIDATE_EXPORTSTR (var
);
3045 var
->exportstr
= mk_env_string (name
, value
, 0);
3047 array_needs_making
= 1;
3050 stupidly_hack_special_variables (name
);
3052 if (echo_command_at_execute
)
3053 /* The Korn shell prints the `+ ' in front of assignment statements,
3055 xtrace_print_assignment (name
, value
, 0, 1);
3061 /* **************************************************************** */
3063 /* Copying variables */
3065 /* **************************************************************** */
3067 #ifdef INCLUDE_UNUSED
3068 /* Copy VAR to a new data structure and return that structure. */
3073 SHELL_VAR
*copy
= (SHELL_VAR
*)NULL
;
3077 copy
= (SHELL_VAR
*)xmalloc (sizeof (SHELL_VAR
));
3079 copy
->attributes
= var
->attributes
;
3080 copy
->name
= savestring (var
->name
);
3082 if (function_p (var
))
3083 var_setfunc (copy
, copy_command (function_cell (var
)));
3084 #if defined (ARRAY_VARS)
3085 else if (array_p (var
))
3086 var_setarray (copy
, array_copy (array_cell (var
)));
3087 else if (assoc_p (var
))
3088 var_setassoc (copy
, assoc_copy (assoc_cell (var
)));
3090 else if (nameref_cell (var
)) /* XXX - nameref */
3091 var_setref (copy
, savestring (nameref_cell (var
)));
3092 else if (value_cell (var
)) /* XXX - nameref */
3093 var_setvalue (copy
, savestring (value_cell (var
)));
3095 var_setvalue (copy
, (char *)NULL
);
3097 copy
->dynamic_value
= var
->dynamic_value
;
3098 copy
->assign_func
= var
->assign_func
;
3100 copy
->exportstr
= COPY_EXPORTSTR (var
);
3102 copy
->context
= var
->context
;
3108 /* **************************************************************** */
3110 /* Deleting and unsetting variables */
3112 /* **************************************************************** */
3114 /* Dispose of the information attached to VAR. */
3116 dispose_variable_value (var
)
3119 if (function_p (var
))
3120 dispose_command (function_cell (var
));
3121 #if defined (ARRAY_VARS)
3122 else if (array_p (var
))
3123 array_dispose (array_cell (var
));
3124 else if (assoc_p (var
))
3125 assoc_dispose (assoc_cell (var
));
3127 else if (nameref_p (var
))
3128 FREE (nameref_cell (var
));
3130 FREE (value_cell (var
));
3134 dispose_variable (var
)
3140 if (nofree_p (var
) == 0)
3141 dispose_variable_value (var
);
3143 FREE_EXPORTSTR (var
);
3147 if (exported_p (var
))
3148 array_needs_making
= 1;
3153 /* Unset the shell variable referenced by NAME. Unsetting a nameref variable
3154 unsets the variable it resolves to but leaves the nameref alone. */
3156 unbind_variable (name
)
3162 v
= var_lookup (name
, shell_variables
);
3163 nv
= (v
&& nameref_p (v
)) ? find_variable_nameref (v
) : (SHELL_VAR
*)NULL
;
3165 r
= nv
? makunbound (nv
->name
, shell_variables
) : makunbound (name
, shell_variables
);
3169 /* Unbind NAME, where NAME is assumed to be a nameref variable */
3171 unbind_nameref (name
)
3176 v
= var_lookup (name
, shell_variables
);
3177 if (v
&& nameref_p (v
))
3178 return makunbound (name
, shell_variables
);
3182 /* Unset the shell function named NAME. */
3187 BUCKET_CONTENTS
*elt
;
3190 elt
= hash_remove (name
, shell_functions
, 0);
3195 #if defined (PROGRAMMABLE_COMPLETION)
3196 set_itemlist_dirty (&it_functions
);
3199 func
= (SHELL_VAR
*)elt
->data
;
3202 if (exported_p (func
))
3203 array_needs_making
++;
3204 dispose_variable (func
);
3213 #if defined (DEBUGGER)
3215 unbind_function_def (name
)
3218 BUCKET_CONTENTS
*elt
;
3219 FUNCTION_DEF
*funcdef
;
3221 elt
= hash_remove (name
, shell_function_defs
, 0);
3226 funcdef
= (FUNCTION_DEF
*)elt
->data
;
3228 dispose_function_def (funcdef
);
3235 #endif /* DEBUGGER */
3238 delete_var (name
, vc
)
3242 BUCKET_CONTENTS
*elt
;
3246 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3247 if (elt
= hash_remove (name
, v
->table
, 0))
3253 old_var
= (SHELL_VAR
*)elt
->data
;
3257 dispose_variable (old_var
);
3261 /* Make the variable associated with NAME go away. HASH_LIST is the
3262 hash table from which this variable should be deleted (either
3263 shell_variables or shell_functions).
3264 Returns non-zero if the variable couldn't be found. */
3266 makunbound (name
, vc
)
3270 BUCKET_CONTENTS
*elt
, *new_elt
;
3275 for (elt
= (BUCKET_CONTENTS
*)NULL
, v
= vc
; v
; v
= v
->down
)
3276 if (elt
= hash_remove (name
, v
->table
, 0))
3282 old_var
= (SHELL_VAR
*)elt
->data
;
3284 if (old_var
&& exported_p (old_var
))
3285 array_needs_making
++;
3287 /* If we're unsetting a local variable and we're still executing inside
3288 the function, just mark the variable as invisible. The function
3289 eventually called by pop_var_context() will clean it up later. This
3290 must be done so that if the variable is subsequently assigned a new
3291 value inside the function, the `local' attribute is still present.
3292 We also need to add it back into the correct hash table. */
3293 if (old_var
&& local_p (old_var
) && variable_context
== old_var
->context
)
3295 if (nofree_p (old_var
))
3296 var_setvalue (old_var
, (char *)NULL
);
3297 #if defined (ARRAY_VARS)
3298 else if (array_p (old_var
))
3299 array_dispose (array_cell (old_var
));
3300 else if (assoc_p (old_var
))
3301 assoc_dispose (assoc_cell (old_var
));
3303 else if (nameref_p (old_var
))
3304 FREE (nameref_cell (old_var
));
3306 FREE (value_cell (old_var
));
3307 /* Reset the attributes. Preserve the export attribute if the variable
3308 came from a temporary environment. Make sure it stays local, and
3309 make it invisible. */
3310 old_var
->attributes
= (exported_p (old_var
) && tempvar_p (old_var
)) ? att_exported
: 0;
3311 VSETATTR (old_var
, att_local
);
3312 VSETATTR (old_var
, att_invisible
);
3313 var_setvalue (old_var
, (char *)NULL
);
3314 INVALIDATE_EXPORTSTR (old_var
);
3316 new_elt
= hash_insert (savestring (old_var
->name
), v
->table
, 0);
3317 new_elt
->data
= (PTR_T
)old_var
;
3318 stupidly_hack_special_variables (old_var
->name
);
3325 /* Have to save a copy of name here, because it might refer to
3326 old_var->name. If so, stupidly_hack_special_variables will
3327 reference freed memory. */
3328 t
= savestring (name
);
3333 dispose_variable (old_var
);
3334 stupidly_hack_special_variables (t
);
3340 /* Get rid of all of the variables in the current context. */
3342 kill_all_local_variables ()
3346 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3347 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
3352 if (vc
->table
&& vc_haslocals (vc
))
3354 delete_all_variables (vc
->table
);
3355 hash_dispose (vc
->table
);
3357 vc
->table
= (HASH_TABLE
*)NULL
;
3361 free_variable_hash_data (data
)
3366 var
= (SHELL_VAR
*)data
;
3367 dispose_variable (var
);
3370 /* Delete the entire contents of the hash table. */
3372 delete_all_variables (hashed_vars
)
3373 HASH_TABLE
*hashed_vars
;
3375 hash_flush (hashed_vars
, free_variable_hash_data
);
3378 /* **************************************************************** */
3380 /* Setting variable attributes */
3382 /* **************************************************************** */
3384 #define FIND_OR_MAKE_VARIABLE(name, entry) \
3387 entry = find_variable (name); \
3390 entry = bind_variable (name, "", 0); \
3391 if (!no_invisible_vars && entry) entry->attributes |= att_invisible; \
3396 /* Make the variable associated with NAME be readonly.
3397 If NAME does not exist yet, create it. */
3399 set_var_read_only (name
)
3404 FIND_OR_MAKE_VARIABLE (name
, entry
);
3405 VSETATTR (entry
, att_readonly
);
3408 #ifdef INCLUDE_UNUSED
3409 /* Make the function associated with NAME be readonly.
3410 If NAME does not exist, we just punt, like auto_export code below. */
3412 set_func_read_only (name
)
3417 entry
= find_function (name
);
3419 VSETATTR (entry
, att_readonly
);
3422 /* Make the variable associated with NAME be auto-exported.
3423 If NAME does not exist yet, create it. */
3425 set_var_auto_export (name
)
3430 FIND_OR_MAKE_VARIABLE (name
, entry
);
3431 set_auto_export (entry
);
3434 /* Make the function associated with NAME be auto-exported. */
3436 set_func_auto_export (name
)
3441 entry
= find_function (name
);
3443 set_auto_export (entry
);
3447 /* **************************************************************** */
3449 /* Creating lists of variables */
3451 /* **************************************************************** */
3454 vlist_alloc (nentries
)
3459 vlist
= (VARLIST
*)xmalloc (sizeof (VARLIST
));
3460 vlist
->list
= (SHELL_VAR
**)xmalloc ((nentries
+ 1) * sizeof (SHELL_VAR
*));
3461 vlist
->list_size
= nentries
;
3462 vlist
->list_len
= 0;
3463 vlist
->list
[0] = (SHELL_VAR
*)NULL
;
3469 vlist_realloc (vlist
, n
)
3474 return (vlist
= vlist_alloc (n
));
3475 if (n
> vlist
->list_size
)
3477 vlist
->list_size
= n
;
3478 vlist
->list
= (SHELL_VAR
**)xrealloc (vlist
->list
, (vlist
->list_size
+ 1) * sizeof (SHELL_VAR
*));
3484 vlist_add (vlist
, var
, flags
)
3491 for (i
= 0; i
< vlist
->list_len
; i
++)
3492 if (STREQ (var
->name
, vlist
->list
[i
]->name
))
3494 if (i
< vlist
->list_len
)
3497 if (i
>= vlist
->list_size
)
3498 vlist
= vlist_realloc (vlist
, vlist
->list_size
+ 16);
3500 vlist
->list
[vlist
->list_len
++] = var
;
3501 vlist
->list
[vlist
->list_len
] = (SHELL_VAR
*)NULL
;
3504 /* Map FUNCTION over the variables in VAR_HASH_TABLE. Return an array of the
3505 variables for which FUNCTION returns a non-zero value. A NULL value
3506 for FUNCTION means to use all variables. */
3508 map_over (function
, vc
)
3509 sh_var_map_func_t
*function
;
3517 for (nentries
= 0, v
= vc
; v
; v
= v
->down
)
3518 nentries
+= HASH_ENTRIES (v
->table
);
3521 return (SHELL_VAR
**)NULL
;
3523 vlist
= vlist_alloc (nentries
);
3525 for (v
= vc
; v
; v
= v
->down
)
3526 flatten (v
->table
, function
, vlist
, 0);
3534 map_over_funcs (function
)
3535 sh_var_map_func_t
*function
;
3540 if (shell_functions
== 0 || HASH_ENTRIES (shell_functions
) == 0)
3541 return ((SHELL_VAR
**)NULL
);
3543 vlist
= vlist_alloc (HASH_ENTRIES (shell_functions
));
3545 flatten (shell_functions
, function
, vlist
, 0);
3552 /* Flatten VAR_HASH_TABLE, applying FUNC to each member and adding those
3553 elements for which FUNC succeeds to VLIST->list. FLAGS is reserved
3554 for future use. Only unique names are added to VLIST. If FUNC is
3555 NULL, each variable in VAR_HASH_TABLE is added to VLIST. If VLIST is
3556 NULL, FUNC is applied to each SHELL_VAR in VAR_HASH_TABLE. If VLIST
3557 and FUNC are both NULL, nothing happens. */
3559 flatten (var_hash_table
, func
, vlist
, flags
)
3560 HASH_TABLE
*var_hash_table
;
3561 sh_var_map_func_t
*func
;
3566 register BUCKET_CONTENTS
*tlist
;
3570 if (var_hash_table
== 0 || (HASH_ENTRIES (var_hash_table
) == 0) || (vlist
== 0 && func
== 0))
3573 for (i
= 0; i
< var_hash_table
->nbuckets
; i
++)
3575 for (tlist
= hash_items (i
, var_hash_table
); tlist
; tlist
= tlist
->next
)
3577 var
= (SHELL_VAR
*)tlist
->data
;
3579 r
= func
? (*func
) (var
) : 1;
3581 vlist_add (vlist
, var
, flags
);
3587 sort_variables (array
)
3590 qsort (array
, strvec_len ((char **)array
), sizeof (SHELL_VAR
*), (QSFUNC
*)qsort_var_comp
);
3594 qsort_var_comp (var1
, var2
)
3595 SHELL_VAR
**var1
, **var2
;
3599 if ((result
= (*var1
)->name
[0] - (*var2
)->name
[0]) == 0)
3600 result
= strcmp ((*var1
)->name
, (*var2
)->name
);
3605 /* Apply FUNC to each variable in SHELL_VARIABLES, adding each one for
3606 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3609 sh_var_map_func_t
*func
;
3613 list
= map_over (func
, shell_variables
);
3614 if (list
/* && posixly_correct */)
3615 sort_variables (list
);
3619 /* Apply FUNC to each variable in SHELL_FUNCTIONS, adding each one for
3620 which FUNC succeeds to an array of SHELL_VAR *s. Returns the array. */
3623 sh_var_map_func_t
*func
;
3627 list
= map_over_funcs (func
);
3628 if (list
/* && posixly_correct */)
3629 sort_variables (list
);
3633 /* Create a NULL terminated array of all the shell variables. */
3635 all_shell_variables ()
3637 return (vapply ((sh_var_map_func_t
*)NULL
));
3640 /* Create a NULL terminated array of all the shell functions. */
3642 all_shell_functions ()
3644 return (fapply ((sh_var_map_func_t
*)NULL
));
3651 return (invisible_p (var
) == 0);
3655 all_visible_functions ()
3657 return (fapply (visible_var
));
3661 all_visible_variables ()
3663 return (vapply (visible_var
));
3666 /* Return non-zero if the variable VAR is visible and exported. Array
3667 variables cannot be exported. */
3669 visible_and_exported (var
)
3672 return (invisible_p (var
) == 0 && exported_p (var
));
3675 /* Candidate variables for the export environment are either valid variables
3676 with the export attribute or invalid variables inherited from the initial
3677 environment and simply passed through. */
3679 export_environment_candidate (var
)
3682 return (exported_p (var
) && (invisible_p (var
) == 0 || imported_p (var
)));
3685 /* Return non-zero if VAR is a local variable in the current context and
3688 local_and_exported (var
)
3691 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
&& exported_p (var
));
3695 all_exported_variables ()
3697 return (vapply (visible_and_exported
));
3701 local_exported_variables ()
3703 return (vapply (local_and_exported
));
3707 variable_in_context (var
)
3710 return (invisible_p (var
) == 0 && local_p (var
) && var
->context
== variable_context
);
3714 all_local_variables ()
3720 vc
= shell_variables
;
3721 for (vc
= shell_variables
; vc
; vc
= vc
->down
)
3722 if (vc_isfuncenv (vc
) && vc
->scope
== variable_context
)
3727 internal_error (_("all_local_variables: no function context at current scope"));
3728 return (SHELL_VAR
**)NULL
;
3730 if (vc
->table
== 0 || HASH_ENTRIES (vc
->table
) == 0 || vc_haslocals (vc
) == 0)
3731 return (SHELL_VAR
**)NULL
;
3733 vlist
= vlist_alloc (HASH_ENTRIES (vc
->table
));
3735 flatten (vc
->table
, variable_in_context
, vlist
, 0);
3740 sort_variables (ret
);
3744 #if defined (ARRAY_VARS)
3745 /* Return non-zero if the variable VAR is visible and an array. */
3747 visible_array_vars (var
)
3750 return (invisible_p (var
) == 0 && array_p (var
));
3754 all_array_variables ()
3756 return (vapply (visible_array_vars
));
3758 #endif /* ARRAY_VARS */
3761 all_variables_matching_prefix (prefix
)
3764 SHELL_VAR
**varlist
;
3766 int vind
, rind
, plen
;
3768 plen
= STRLEN (prefix
);
3769 varlist
= all_visible_variables ();
3770 for (vind
= 0; varlist
&& varlist
[vind
]; vind
++)
3772 if (varlist
== 0 || vind
== 0)
3773 return ((char **)NULL
);
3774 rlist
= strvec_create (vind
+ 1);
3775 for (vind
= rind
= 0; varlist
[vind
]; vind
++)
3777 if (plen
== 0 || STREQN (prefix
, varlist
[vind
]->name
, plen
))
3778 rlist
[rind
++] = savestring (varlist
[vind
]->name
);
3780 rlist
[rind
] = (char *)0;
3786 /* **************************************************************** */
3788 /* Managing temporary variable scopes */
3790 /* **************************************************************** */
3792 /* Make variable NAME have VALUE in the temporary environment. */
3794 bind_tempenv_variable (name
, value
)
3800 var
= temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
;
3804 FREE (value_cell (var
));
3805 var_setvalue (var
, savestring (value
));
3806 INVALIDATE_EXPORTSTR (var
);
3812 /* Find a variable in the temporary environment that is named NAME.
3813 Return the SHELL_VAR *, or NULL if not found. */
3815 find_tempenv_variable (name
)
3818 return (temporary_env
? hash_lookup (name
, temporary_env
) : (SHELL_VAR
*)NULL
);
3821 char **tempvar_list
;
3824 /* Push the variable described by (SHELL_VAR *)DATA down to the next
3825 variable context from the temporary environment. */
3827 push_temp_var (data
)
3831 HASH_TABLE
*binding_table
;
3833 var
= (SHELL_VAR
*)data
;
3835 binding_table
= shell_variables
->table
;
3836 if (binding_table
== 0)
3838 if (shell_variables
== global_variables
)
3839 /* shouldn't happen */
3840 binding_table
= shell_variables
->table
= global_variables
->table
= hash_create (0);
3842 binding_table
= shell_variables
->table
= hash_create (TEMPENV_HASH_BUCKETS
);
3845 v
= bind_variable_internal (var
->name
, value_cell (var
), binding_table
, 0, 0);
3847 /* XXX - should we set the context here? It shouldn't matter because of how
3848 assign_in_env works, but might want to check. */
3849 if (binding_table
== global_variables
->table
) /* XXX */
3850 var
->attributes
&= ~(att_tempvar
|att_propagate
);
3853 var
->attributes
|= att_propagate
;
3854 if (binding_table
== shell_variables
->table
)
3855 shell_variables
->flags
|= VC_HASTMPVAR
;
3857 v
->attributes
|= var
->attributes
;
3859 if (find_special_var (var
->name
) >= 0)
3860 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
3862 dispose_variable (var
);
3866 propagate_temp_var (data
)
3871 var
= (SHELL_VAR
*)data
;
3872 if (tempvar_p (var
) && (var
->attributes
& att_propagate
))
3873 push_temp_var (data
);
3876 if (find_special_var (var
->name
) >= 0)
3877 tempvar_list
[tvlist_ind
++] = savestring (var
->name
);
3878 dispose_variable (var
);
3882 /* Free the storage used in the hash table for temporary
3883 environment variables. PUSHF is a function to be called
3884 to free each hash table entry. It takes care of pushing variables
3885 to previous scopes if appropriate. PUSHF stores names of variables
3886 that require special handling (e.g., IFS) on tempvar_list, so this
3887 function can call stupidly_hack_special_variables on all the
3888 variables in the list when the temporary hash table is destroyed. */
3890 dispose_temporary_env (pushf
)
3891 sh_free_func_t
*pushf
;
3895 tempvar_list
= strvec_create (HASH_ENTRIES (temporary_env
) + 1);
3896 tempvar_list
[tvlist_ind
= 0] = 0;
3898 hash_flush (temporary_env
, pushf
);
3899 hash_dispose (temporary_env
);
3900 temporary_env
= (HASH_TABLE
*)NULL
;
3902 tempvar_list
[tvlist_ind
] = 0;
3904 array_needs_making
= 1;
3907 sv_ifs ("IFS"); /* XXX here for now -- check setifs in assign_in_env */
3909 for (i
= 0; i
< tvlist_ind
; i
++)
3910 stupidly_hack_special_variables (tempvar_list
[i
]);
3912 strvec_dispose (tempvar_list
);
3918 dispose_used_env_vars ()
3922 dispose_temporary_env (propagate_temp_var
);
3923 maybe_make_export_env ();
3927 /* Take all of the shell variables in the temporary environment HASH_TABLE
3928 and make shell variables from them at the current variable context. */
3930 merge_temporary_env ()
3933 dispose_temporary_env (push_temp_var
);
3936 /* **************************************************************** */
3938 /* Creating and manipulating the environment */
3940 /* **************************************************************** */
3942 static inline char *
3943 mk_env_string (name
, value
, isfunc
)
3944 const char *name
, *value
;
3947 size_t name_len
, value_len
;
3950 name_len
= strlen (name
);
3951 value_len
= STRLEN (value
);
3953 /* If we are exporting a shell function, construct the encoded function
3955 if (isfunc
&& value
)
3957 p
= (char *)xmalloc (BASHFUNC_PREFLEN
+ name_len
+ BASHFUNC_SUFFLEN
+ value_len
+ 2);
3959 memcpy (q
, BASHFUNC_PREFIX
, BASHFUNC_PREFLEN
);
3960 q
+= BASHFUNC_PREFLEN
;
3961 memcpy (q
, name
, name_len
);
3963 memcpy (q
, BASHFUNC_SUFFIX
, BASHFUNC_SUFFLEN
);
3964 q
+= BASHFUNC_SUFFLEN
;
3968 p
= (char *)xmalloc (2 + name_len
+ value_len
);
3969 memcpy (p
, name
, name_len
);
3974 if (value
&& *value
)
3975 memcpy (q
+ 1, value
, value_len
+ 1);
3993 internal_error (_("%s has null exportstr"), v
->name
);
3996 if (legal_variable_starter ((unsigned char)*s
) == 0)
3998 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4001 for (s
= v
->exportstr
+ 1; s
&& *s
; s
++)
4005 if (legal_variable_char ((unsigned char)*s
) == 0)
4007 internal_error (_("invalid character %d in exportstr for %s"), *s
, v
->name
);
4013 internal_error (_("no `=' in exportstr for %s"), v
->name
);
4021 make_env_array_from_var_list (vars
)
4024 register int i
, list_index
;
4025 register SHELL_VAR
*var
;
4026 char **list
, *value
;
4028 list
= strvec_create ((1 + strvec_len ((char **)vars
)));
4030 #define USE_EXPORTSTR (value == var->exportstr)
4032 for (i
= 0, list_index
= 0; var
= vars
[i
]; i
++)
4034 #if defined (__CYGWIN__)
4035 /* We don't use the exportstr stuff on Cygwin at all. */
4036 INVALIDATE_EXPORTSTR (var
);
4039 value
= var
->exportstr
;
4040 else if (function_p (var
))
4041 value
= named_function_string ((char *)NULL
, function_cell (var
), 0);
4042 #if defined (ARRAY_VARS)
4043 else if (array_p (var
))
4045 value
= array_to_assignment_string (array_cell (var
));
4047 continue; /* XXX array vars cannot yet be exported */
4048 # endif /* ARRAY_EXPORT */
4049 else if (assoc_p (var
))
4051 value
= assoc_to_assignment_string (assoc_cell (var
));
4053 continue; /* XXX associative array vars cannot yet be exported */
4057 value
= value_cell (var
);
4061 /* Gee, I'd like to get away with not using savestring() if we're
4062 using the cached exportstr... */
4063 list
[list_index
] = USE_EXPORTSTR
? savestring (value
)
4064 : mk_env_string (var
->name
, value
, function_p (var
));
4066 if (USE_EXPORTSTR
== 0)
4067 SAVE_EXPORTSTR (var
, list
[list_index
]);
4070 #undef USE_EXPORTSTR
4073 #if defined (ARRAY_VARS)
4074 if (array_p (var
) || assoc_p (var
))
4081 list
[list_index
] = (char *)NULL
;
4085 /* Make an array of assignment statements from the hash table
4086 HASHED_VARS which contains SHELL_VARs. Only visible, exported
4087 variables are eligible. */
4089 make_var_export_array (vcxt
)
4096 vars
= map_over (visible_and_exported
, vcxt
);
4098 vars
= map_over (export_environment_candidate
, vcxt
);
4102 return (char **)NULL
;
4104 list
= make_env_array_from_var_list (vars
);
4111 make_func_export_array ()
4116 vars
= map_over_funcs (visible_and_exported
);
4118 return (char **)NULL
;
4120 list
= make_env_array_from_var_list (vars
);
4126 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
4127 #define add_to_export_env(envstr,do_alloc) \
4130 if (export_env_index >= (export_env_size - 1)) \
4132 export_env_size += 16; \
4133 export_env = strvec_resize (export_env, export_env_size); \
4134 environ = export_env; \
4136 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
4137 export_env[export_env_index] = (char *)NULL; \
4140 /* Add ASSIGN to EXPORT_ENV, or supercede a previous assignment in the
4141 array with the same left-hand side. Return the new EXPORT_ENV. */
4143 add_or_supercede_exported_var (assign
, do_alloc
)
4150 equal_offset
= assignment (assign
, 0);
4151 if (equal_offset
== 0)
4152 return (export_env
);
4154 /* If this is a function, then only supersede the function definition.
4155 We do this by including the `=() {' in the comparison, like
4156 initialize_shell_variables does. */
4157 if (assign
[equal_offset
+ 1] == '(' &&
4158 strncmp (assign
+ equal_offset
+ 2, ") {", 3) == 0) /* } */
4161 for (i
= 0; i
< export_env_index
; i
++)
4163 if (STREQN (assign
, export_env
[i
], equal_offset
+ 1))
4165 free (export_env
[i
]);
4166 export_env
[i
] = do_alloc
? savestring (assign
) : assign
;
4167 return (export_env
);
4170 add_to_export_env (assign
, do_alloc
);
4171 return (export_env
);
4175 add_temp_array_to_env (temp_array
, do_alloc
, do_supercede
)
4177 int do_alloc
, do_supercede
;
4181 if (temp_array
== 0)
4184 for (i
= 0; temp_array
[i
]; i
++)
4187 export_env
= add_or_supercede_exported_var (temp_array
[i
], do_alloc
);
4189 add_to_export_env (temp_array
[i
], do_alloc
);
4195 /* Make the environment array for the command about to be executed, if the
4196 array needs making. Otherwise, do nothing. If a shell action could
4197 change the array that commands receive for their environment, then the
4198 code should `array_needs_making++'.
4200 The order to add to the array is:
4202 list of var contexts whose head is shell_variables
4205 This is the shell variable lookup order. We add only new variable
4206 names at each step, which allows local variables and variables in
4207 the temporary environments to shadow variables in the global (or
4208 any previous) scope.
4212 n_shell_variables ()
4217 for (n
= 0, vc
= shell_variables
; vc
; vc
= vc
->down
)
4218 n
+= HASH_ENTRIES (vc
->table
);
4228 v
= find_variable (name
);
4229 if (v
&& exported_p (v
))
4231 array_needs_making
= 1;
4232 maybe_make_export_env ();
4239 maybe_make_export_env ()
4241 register char **temp_array
;
4245 if (array_needs_making
)
4248 strvec_flush (export_env
);
4250 /* Make a guess based on how many shell variables and functions we
4251 have. Since there will always be array variables, and array
4252 variables are not (yet) exported, this will always be big enough
4253 for the exported variables and functions. */
4254 new_size
= n_shell_variables () + HASH_ENTRIES (shell_functions
) + 1 +
4255 HASH_ENTRIES (temporary_env
);
4256 if (new_size
> export_env_size
)
4258 export_env_size
= new_size
;
4259 export_env
= strvec_resize (export_env
, export_env_size
);
4260 environ
= export_env
;
4262 export_env
[export_env_index
= 0] = (char *)NULL
;
4264 /* Make a dummy variable context from the temporary_env, stick it on
4265 the front of shell_variables, call make_var_export_array on the
4266 whole thing to flatten it, and convert the list of SHELL_VAR *s
4267 to the form needed by the environment. */
4270 tcxt
= new_var_context ((char *)NULL
, 0);
4271 tcxt
->table
= temporary_env
;
4272 tcxt
->down
= shell_variables
;
4275 tcxt
= shell_variables
;
4277 temp_array
= make_var_export_array (tcxt
);
4279 add_temp_array_to_env (temp_array
, 0, 0);
4281 if (tcxt
!= shell_variables
)
4284 #if defined (RESTRICTED_SHELL)
4285 /* Restricted shells may not export shell functions. */
4286 temp_array
= restricted
? (char **)0 : make_func_export_array ();
4288 temp_array
= make_func_export_array ();
4291 add_temp_array_to_env (temp_array
, 0, 0);
4293 array_needs_making
= 0;
4297 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
4298 we will need to remake the exported environment every time we
4299 change directories. `_' is always put into the environment for
4300 every external command, so without special treatment it will always
4301 cause the environment to be remade.
4303 If there is no other reason to make the exported environment, we can
4304 just update the variables in place and mark the exported environment
4305 as no longer needing a remake. */
4307 update_export_env_inplace (env_prefix
, preflen
, value
)
4314 evar
= (char *)xmalloc (STRLEN (value
) + preflen
+ 1);
4315 strcpy (evar
, env_prefix
);
4317 strcpy (evar
+ preflen
, value
);
4318 export_env
= add_or_supercede_exported_var (evar
, 0);
4321 /* We always put _ in the environment as the name of this command. */
4323 put_command_name_into_env (command_name
)
4326 update_export_env_inplace ("_=", 2, command_name
);
4329 /* **************************************************************** */
4331 /* Managing variable contexts */
4333 /* **************************************************************** */
4335 /* Allocate and return a new variable context with NAME and FLAGS.
4336 NAME can be NULL. */
4339 new_var_context (name
, flags
)
4345 vc
= (VAR_CONTEXT
*)xmalloc (sizeof (VAR_CONTEXT
));
4346 vc
->name
= name
? savestring (name
) : (char *)NULL
;
4347 vc
->scope
= variable_context
;
4350 vc
->up
= vc
->down
= (VAR_CONTEXT
*)NULL
;
4351 vc
->table
= (HASH_TABLE
*)NULL
;
4356 /* Free a variable context and its data, including the hash table. Dispose
4357 all of the variables. */
4359 dispose_var_context (vc
)
4366 delete_all_variables (vc
->table
);
4367 hash_dispose (vc
->table
);
4373 /* Set VAR's scope level to the current variable context. */
4378 return (var
->context
= variable_context
);
4381 /* Make a new variable context with NAME and FLAGS and a HASH_TABLE of
4382 temporary variables, and push it onto shell_variables. This is
4383 for shell functions. */
4385 push_var_context (name
, flags
, tempvars
)
4388 HASH_TABLE
*tempvars
;
4392 vc
= new_var_context (name
, flags
);
4393 vc
->table
= tempvars
;
4396 /* Have to do this because the temp environment was created before
4397 variable_context was incremented. */
4398 flatten (tempvars
, set_context
, (VARLIST
*)NULL
, 0);
4399 vc
->flags
|= VC_HASTMPVAR
;
4401 vc
->down
= shell_variables
;
4402 shell_variables
->up
= vc
;
4404 return (shell_variables
= vc
);
4408 push_func_var (data
)
4413 var
= (SHELL_VAR
*)data
;
4415 if (tempvar_p (var
) && (posixly_correct
|| (var
->attributes
& att_propagate
)))
4417 /* Make sure we have a hash table to store the variable in while it is
4418 being propagated down to the global variables table. Create one if
4420 if ((vc_isfuncenv (shell_variables
) || vc_istempenv (shell_variables
)) && shell_variables
->table
== 0)
4421 shell_variables
->table
= hash_create (0);
4422 /* XXX - should we set v->context here? */
4423 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
4424 if (shell_variables
== global_variables
)
4425 var
->attributes
&= ~(att_tempvar
|att_propagate
);
4427 shell_variables
->flags
|= VC_HASTMPVAR
;
4428 v
->attributes
|= var
->attributes
;
4431 stupidly_hack_special_variables (var
->name
); /* XXX */
4433 dispose_variable (var
);
4436 /* Pop the top context off of VCXT and dispose of it, returning the rest of
4441 VAR_CONTEXT
*ret
, *vcxt
;
4443 vcxt
= shell_variables
;
4444 if (vc_isfuncenv (vcxt
) == 0)
4446 internal_error (_("pop_var_context: head of shell_variables not a function context"));
4450 if (ret
= vcxt
->down
)
4452 ret
->up
= (VAR_CONTEXT
*)NULL
;
4453 shell_variables
= ret
;
4455 hash_flush (vcxt
->table
, push_func_var
);
4456 dispose_var_context (vcxt
);
4459 internal_error (_("pop_var_context: no global_variables context"));
4462 /* Delete the HASH_TABLEs for all variable contexts beginning at VCXT, and
4463 all of the VAR_CONTEXTs except GLOBAL_VARIABLES. */
4465 delete_all_contexts (vcxt
)
4470 for (v
= vcxt
; v
!= global_variables
; v
= t
)
4473 dispose_var_context (v
);
4476 delete_all_variables (global_variables
->table
);
4477 shell_variables
= global_variables
;
4480 /* **************************************************************** */
4482 /* Pushing and Popping temporary variable scopes */
4484 /* **************************************************************** */
4487 push_scope (flags
, tmpvars
)
4489 HASH_TABLE
*tmpvars
;
4491 return (push_var_context ((char *)NULL
, flags
, tmpvars
));
4495 push_exported_var (data
)
4500 var
= (SHELL_VAR
*)data
;
4502 /* If a temp var had its export attribute set, or it's marked to be
4503 propagated, bind it in the previous scope before disposing it. */
4504 /* XXX - This isn't exactly right, because all tempenv variables have the
4505 export attribute set. */
4507 if (exported_p (var
) || (var
->attributes
& att_propagate
))
4509 if (tempvar_p (var
) && exported_p (var
) && (var
->attributes
& att_propagate
))
4512 var
->attributes
&= ~att_tempvar
; /* XXX */
4513 v
= bind_variable_internal (var
->name
, value_cell (var
), shell_variables
->table
, 0, 0);
4514 if (shell_variables
== global_variables
)
4515 var
->attributes
&= ~att_propagate
;
4516 v
->attributes
|= var
->attributes
;
4519 stupidly_hack_special_variables (var
->name
); /* XXX */
4521 dispose_variable (var
);
4525 pop_scope (is_special
)
4528 VAR_CONTEXT
*vcxt
, *ret
;
4530 vcxt
= shell_variables
;
4531 if (vc_istempscope (vcxt
) == 0)
4533 internal_error (_("pop_scope: head of shell_variables not a temporary environment scope"));
4539 ret
->up
= (VAR_CONTEXT
*)NULL
;
4541 shell_variables
= ret
;
4543 /* Now we can take care of merging variables in VCXT into set of scopes
4544 whose head is RET (shell_variables). */
4549 hash_flush (vcxt
->table
, push_func_var
);
4551 hash_flush (vcxt
->table
, push_exported_var
);
4552 hash_dispose (vcxt
->table
);
4556 sv_ifs ("IFS"); /* XXX here for now */
4559 /* **************************************************************** */
4561 /* Pushing and Popping function contexts */
4563 /* **************************************************************** */
4565 static WORD_LIST
**dollar_arg_stack
= (WORD_LIST
**)NULL
;
4566 static int dollar_arg_stack_slots
;
4567 static int dollar_arg_stack_index
;
4569 /* XXX - we might want to consider pushing and popping the `getopts' state
4570 when we modify the positional parameters. */
4572 push_context (name
, is_subshell
, tempvars
)
4573 char *name
; /* function name */
4575 HASH_TABLE
*tempvars
;
4577 if (is_subshell
== 0)
4578 push_dollar_vars ();
4580 push_var_context (name
, VC_FUNCENV
, tempvars
);
4583 /* Only called when subshell == 0, so we don't need to check, and can
4584 unconditionally pop the dollar vars off the stack. */
4592 sv_ifs ("IFS"); /* XXX here for now */
4595 /* Save the existing positional parameters on a stack. */
4599 if (dollar_arg_stack_index
+ 2 > dollar_arg_stack_slots
)
4601 dollar_arg_stack
= (WORD_LIST
**)
4602 xrealloc (dollar_arg_stack
, (dollar_arg_stack_slots
+= 10)
4603 * sizeof (WORD_LIST
*));
4605 dollar_arg_stack
[dollar_arg_stack_index
++] = list_rest_of_args ();
4606 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4609 /* Restore the positional parameters from our stack. */
4613 if (!dollar_arg_stack
|| dollar_arg_stack_index
== 0)
4616 remember_args (dollar_arg_stack
[--dollar_arg_stack_index
], 1);
4617 dispose_words (dollar_arg_stack
[dollar_arg_stack_index
]);
4618 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4619 set_dollar_vars_unchanged ();
4623 dispose_saved_dollar_vars ()
4625 if (!dollar_arg_stack
|| dollar_arg_stack_index
== 0)
4628 dispose_words (dollar_arg_stack
[dollar_arg_stack_index
]);
4629 dollar_arg_stack
[dollar_arg_stack_index
] = (WORD_LIST
*)NULL
;
4632 /* Manipulate the special BASH_ARGV and BASH_ARGC variables. */
4638 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4639 SHELL_VAR
*bash_argv_v
, *bash_argc_v
;
4640 ARRAY
*bash_argv_a
, *bash_argc_a
;
4645 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v
, bash_argv_a
);
4646 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v
, bash_argc_a
);
4648 for (l
= list
, i
= 0; l
; l
= l
->next
, i
++)
4649 array_push (bash_argv_a
, l
->word
->word
);
4652 array_push (bash_argc_a
, t
);
4654 #endif /* ARRAY_VARS && DEBUGGER */
4657 /* Remove arguments from BASH_ARGV array. Pop top element off BASH_ARGC
4658 array and use that value as the count of elements to remove from
4663 #if defined (ARRAY_VARS) && defined (DEBUGGER)
4664 SHELL_VAR
*bash_argv_v
, *bash_argc_v
;
4665 ARRAY
*bash_argv_a
, *bash_argc_a
;
4669 GET_ARRAY_FROM_VAR ("BASH_ARGV", bash_argv_v
, bash_argv_a
);
4670 GET_ARRAY_FROM_VAR ("BASH_ARGC", bash_argc_v
, bash_argc_a
);
4672 ce
= array_shift (bash_argc_a
, 1, 0);
4673 if (ce
== 0 || legal_number (element_value (ce
), &i
) == 0)
4677 array_pop (bash_argv_a
);
4678 array_dispose_element (ce
);
4679 #endif /* ARRAY_VARS && DEBUGGER */
4682 /*************************************************
4684 * Functions to manage special variables *
4686 *************************************************/
4688 /* Extern declarations for variables this code has to manage. */
4689 extern int eof_encountered
, eof_encountered_limit
, ignoreeof
;
4691 #if defined (READLINE)
4692 extern int hostname_list_initialized
;
4695 /* An alist of name.function for each special variable. Most of the
4696 functions don't do much, and in fact, this would be faster with a
4697 switch statement, but by the end of this file, I am sick of switch
4700 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
4702 /* This table will be sorted with qsort() the first time it's accessed. */
4703 struct name_and_function
{
4705 sh_sv_func_t
*function
;
4708 static struct name_and_function special_vars
[] = {
4709 { "BASH_COMPAT", sv_shcompat
},
4710 { "BASH_XTRACEFD", sv_xtracefd
},
4712 #if defined (JOB_CONTROL)
4713 { "CHILD_MAX", sv_childmax
},
4716 #if defined (READLINE)
4717 # if defined (STRICT_POSIX)
4718 { "COLUMNS", sv_winsize
},
4720 { "COMP_WORDBREAKS", sv_comp_wordbreaks
},
4723 { "FUNCNEST", sv_funcnest
},
4725 { "GLOBIGNORE", sv_globignore
},
4727 #if defined (HISTORY)
4728 { "HISTCONTROL", sv_history_control
},
4729 { "HISTFILESIZE", sv_histsize
},
4730 { "HISTIGNORE", sv_histignore
},
4731 { "HISTSIZE", sv_histsize
},
4732 { "HISTTIMEFORMAT", sv_histtimefmt
},
4735 #if defined (__CYGWIN__)
4736 { "HOME", sv_home
},
4739 #if defined (READLINE)
4740 { "HOSTFILE", sv_hostfile
},
4744 { "IGNOREEOF", sv_ignoreeof
},
4746 { "LANG", sv_locale
},
4747 { "LC_ALL", sv_locale
},
4748 { "LC_COLLATE", sv_locale
},
4749 { "LC_CTYPE", sv_locale
},
4750 { "LC_MESSAGES", sv_locale
},
4751 { "LC_NUMERIC", sv_locale
},
4752 { "LC_TIME", sv_locale
},
4754 #if defined (READLINE) && defined (STRICT_POSIX)
4755 { "LINES", sv_winsize
},
4758 { "MAIL", sv_mail
},
4759 { "MAILCHECK", sv_mail
},
4760 { "MAILPATH", sv_mail
},
4762 { "OPTERR", sv_opterr
},
4763 { "OPTIND", sv_optind
},
4765 { "PATH", sv_path
},
4766 { "POSIXLY_CORRECT", sv_strict_posix
},
4768 #if defined (READLINE)
4769 { "TERM", sv_terminal
},
4770 { "TERMCAP", sv_terminal
},
4771 { "TERMINFO", sv_terminal
},
4772 #endif /* READLINE */
4774 { "TEXTDOMAIN", sv_locale
},
4775 { "TEXTDOMAINDIR", sv_locale
},
4777 #if defined (HAVE_TZSET)
4781 #if defined (HISTORY) && defined (BANG_HISTORY)
4782 { "histchars", sv_histchars
},
4783 #endif /* HISTORY && BANG_HISTORY */
4785 { "ignoreeof", sv_ignoreeof
},
4787 { (char *)0, (sh_sv_func_t
*)0 }
4790 #define N_SPECIAL_VARS (sizeof (special_vars) / sizeof (special_vars[0]) - 1)
4793 sv_compare (sv1
, sv2
)
4794 struct name_and_function
*sv1
, *sv2
;
4798 if ((r
= sv1
->name
[0] - sv2
->name
[0]) == 0)
4799 r
= strcmp (sv1
->name
, sv2
->name
);
4804 find_special_var (name
)
4809 for (i
= 0; special_vars
[i
].name
; i
++)
4811 r
= special_vars
[i
].name
[0] - name
[0];
4813 r
= strcmp (special_vars
[i
].name
, name
);
4817 /* Can't match any of rest of elements in sorted list. Take this out
4818 if it causes problems in certain environments. */
4824 /* The variable in NAME has just had its state changed. Check to see if it
4825 is one of the special ones where something special happens. */
4827 stupidly_hack_special_variables (name
)
4830 static int sv_sorted
= 0;
4833 if (sv_sorted
== 0) /* shouldn't need, but it's fairly cheap. */
4835 qsort (special_vars
, N_SPECIAL_VARS
, sizeof (special_vars
[0]),
4836 (QSFUNC
*)sv_compare
);
4840 i
= find_special_var (name
);
4842 (*(special_vars
[i
].function
)) (name
);
4845 /* Special variables that need hooks to be run when they are unset as part
4846 of shell reinitialization should have their sv_ functions run here. */
4848 reinit_special_variables ()
4850 #if defined (READLINE)
4851 sv_comp_wordbreaks ("COMP_WORDBREAKS");
4853 sv_globignore ("GLOBIGNORE");
4854 sv_opterr ("OPTERR");
4863 v
= find_variable ("IFS");
4867 /* What to do just after the PATH variable has changed. */
4876 /* What to do just after one of the MAILxxxx variables has changed. NAME
4877 is the name of the variable. This is called with NAME set to one of
4878 MAIL, MAILCHECK, or MAILPATH. */
4883 /* If the time interval for checking the files has changed, then
4884 reset the mail timer. Otherwise, one of the pathname vars
4885 to the users mailbox has changed, so rebuild the array of
4887 if (name
[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
4888 reset_mail_timer ();
4892 remember_mail_dates ();
4903 v
= find_variable (name
);
4906 else if (legal_number (value_cell (v
), &num
) == 0)
4912 /* What to do when GLOBIGNORE changes. */
4914 sv_globignore (name
)
4917 if (privileged_mode
== 0)
4918 setup_glob_ignore (name
);
4921 #if defined (READLINE)
4923 sv_comp_wordbreaks (name
)
4928 sv
= find_variable (name
);
4930 reset_completer_word_break_chars ();
4933 /* What to do just after one of the TERMxxx variables has changed.
4934 If we are an interactive shell, then try to reset the terminal
4935 information in readline. */
4940 if (interactive_shell
&& no_line_editing
== 0)
4941 rl_reset_terminal (get_string_value ("TERM"));
4950 v
= find_variable (name
);
4952 clear_hostname_list ();
4954 hostname_list_initialized
= 0;
4957 #if defined (STRICT_POSIX)
4958 /* In strict posix mode, we allow assignments to LINES and COLUMNS (and values
4959 found in the initial environment) to override the terminal size reported by
4969 if (posixly_correct
== 0 || interactive_shell
== 0 || no_line_editing
)
4972 v
= find_variable (name
);
4973 if (v
== 0 || var_isnull (v
))
4974 rl_reset_screen_size ();
4977 if (legal_number (value_cell (v
), &xd
) == 0)
4979 winsize_assignment
= 1;
4980 d
= xd
; /* truncate */
4981 if (name
[0] == 'L') /* LINES */
4982 rl_set_screen_size (d
, -1);
4984 rl_set_screen_size (-1, d
);
4985 winsize_assignment
= 0;
4988 #endif /* STRICT_POSIX */
4989 #endif /* READLINE */
4991 /* Update the value of HOME in the export environment so tilde expansion will
4993 #if defined (__CYGWIN__)
4997 array_needs_making
= 1;
4998 maybe_make_export_env ();
5002 #if defined (HISTORY)
5003 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
5004 If there is a value for this HISTSIZE (and it is numeric), then stifle
5005 the history. Otherwise, if there is NO value for this variable,
5006 unstifle the history. If name is HISTFILESIZE, and its value is
5007 numeric, truncate the history file to hold no more than that many
5017 temp
= get_string_value (name
);
5021 if (legal_number (temp
, &num
))
5024 if (hmax
< 0 && name
[4] == 'S')
5025 unstifle_history (); /* unstifle history if HISTSIZE < 0 */
5026 else if (name
[4] == 'S')
5028 stifle_history (hmax
);
5029 hmax
= where_history ();
5030 if (history_lines_this_session
> hmax
)
5031 history_lines_this_session
= hmax
;
5033 else if (hmax
>= 0) /* truncate HISTFILE if HISTFILESIZE >= 0 */
5035 history_truncate_file (get_string_value ("HISTFILE"), hmax
);
5036 if (hmax
<= history_lines_in_file
)
5037 history_lines_in_file
= hmax
;
5041 else if (name
[4] == 'S')
5042 unstifle_history ();
5045 /* What to do after the HISTIGNORE variable changes. */
5047 sv_histignore (name
)
5050 setup_history_ignore (name
);
5053 /* What to do after the HISTCONTROL variable changes. */
5055 sv_history_control (name
)
5062 history_control
= 0;
5063 temp
= get_string_value (name
);
5065 if (temp
== 0 || *temp
== 0)
5069 while (val
= extract_colon_unit (temp
, &tptr
))
5071 if (STREQ (val
, "ignorespace"))
5072 history_control
|= HC_IGNSPACE
;
5073 else if (STREQ (val
, "ignoredups"))
5074 history_control
|= HC_IGNDUPS
;
5075 else if (STREQ (val
, "ignoreboth"))
5076 history_control
|= HC_IGNBOTH
;
5077 else if (STREQ (val
, "erasedups"))
5078 history_control
|= HC_ERASEDUPS
;
5084 #if defined (BANG_HISTORY)
5085 /* Setting/unsetting of the history expansion character. */
5092 temp
= get_string_value (name
);
5095 history_expansion_char
= *temp
;
5096 if (temp
[0] && temp
[1])
5098 history_subst_char
= temp
[1];
5100 history_comment_char
= temp
[2];
5105 history_expansion_char
= '!';
5106 history_subst_char
= '^';
5107 history_comment_char
= '#';
5110 #endif /* BANG_HISTORY */
5113 sv_histtimefmt (name
)
5118 if (v
= find_variable (name
))
5120 if (history_comment_char
== 0)
5121 history_comment_char
= '#';
5123 history_write_timestamps
= (v
!= 0);
5125 #endif /* HISTORY */
5127 #if defined (HAVE_TZSET)
5132 if (chkexport (name
))
5137 /* If the variable exists, then the value of it can be the number
5138 of times we actually ignore the EOF. The default is small,
5139 (smaller than csh, anyway). */
5147 eof_encountered
= 0;
5149 tmp_var
= find_variable (name
);
5150 ignoreeof
= tmp_var
!= 0;
5151 temp
= tmp_var
? value_cell (tmp_var
) : (char *)NULL
;
5153 eof_encountered_limit
= (*temp
&& all_digits (temp
)) ? atoi (temp
) : 10;
5154 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
5164 tt
= get_string_value ("OPTIND");
5169 /* According to POSIX, setting OPTIND=1 resets the internal state
5171 if (s
< 0 || s
== 1)
5185 tt
= get_string_value ("OPTERR");
5186 sh_opterr
= (tt
&& *tt
) ? atoi (tt
) : 1;
5190 sv_strict_posix (name
)
5193 SET_INT_VAR (name
, posixly_correct
);
5194 posix_initialize (posixly_correct
);
5195 #if defined (READLINE)
5196 if (interactive_shell
)
5197 posix_readline_initialize (posixly_correct
);
5198 #endif /* READLINE */
5199 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
5209 v
= get_string_value (name
);
5210 if (name
[0] == 'L' && name
[1] == 'A') /* LANG */
5211 r
= set_lang (name
, v
);
5213 r
= set_locale_var (name
, v
); /* LC_*, TEXTDOMAIN* */
5216 if (r
== 0 && posixly_correct
)
5217 last_command_exit_value
= 1;
5221 #if defined (ARRAY_VARS)
5223 set_pipestatus_array (ps
, nproc
)
5231 char *t
, tbuf
[INT_STRLEN_BOUND(int) + 1];
5233 v
= find_variable ("PIPESTATUS");
5235 v
= make_new_array_variable ("PIPESTATUS");
5236 if (array_p (v
) == 0)
5237 return; /* Do nothing if not an array variable. */
5240 if (a
== 0 || array_num_elements (a
) == 0)
5242 for (i
= 0; i
< nproc
; i
++) /* was ps[i] != -1, not i < nproc */
5244 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5245 array_insert (a
, i
, t
);
5251 if (array_num_elements (a
) == nproc
&& nproc
== 1)
5253 ae
= element_forw (a
->head
);
5254 free (element_value (ae
));
5255 ae
->value
= itos (ps
[0]);
5257 else if (array_num_elements (a
) <= nproc
)
5259 /* modify in array_num_elements members in place, then add */
5261 for (i
= 0; i
< array_num_elements (a
); i
++)
5263 ae
= element_forw (ae
);
5264 free (element_value (ae
));
5265 ae
->value
= itos (ps
[i
]);
5268 for ( ; i
< nproc
; i
++)
5270 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5271 array_insert (a
, i
, t
);
5276 /* deleting elements. it's faster to rebuild the array. */
5278 for (i
= 0; ps
[i
] != -1; i
++)
5280 t
= inttostr (ps
[i
], tbuf
, sizeof (tbuf
));
5281 array_insert (a
, i
, t
);
5287 save_pipestatus_array ()
5292 v
= find_variable ("PIPESTATUS");
5293 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
5294 return ((ARRAY
*)NULL
);
5297 a2
= array_copy (array_cell (v
));
5303 restore_pipestatus_array (a
)
5309 v
= find_variable ("PIPESTATUS");
5310 /* XXX - should we still assign even if existing value is NULL? */
5311 if (v
== 0 || array_p (v
) == 0 || array_cell (v
) == 0)
5314 a2
= array_cell (v
);
5315 var_setarray (v
, a
);
5322 set_pipestatus_from_exit (s
)
5325 #if defined (ARRAY_VARS)
5326 static int v
[2] = { 0, -1 };
5329 set_pipestatus_array (v
, 1);
5342 v
= find_variable (name
);
5350 if (t
== 0 || *t
== 0)
5354 fd
= (int)strtol (t
, &e
, 10);
5355 if (e
!= t
&& *e
== '\0' && sh_validfd (fd
))
5357 fp
= fdopen (fd
, "w");
5359 internal_error (_("%s: %s: cannot open as FILE"), name
, value_cell (v
));
5361 xtrace_set (fd
, fp
);
5364 internal_error (_("%s: %s: invalid value for trace file descriptor"), name
, value_cell (v
));
5368 #define MIN_COMPAT_LEVEL 31
5376 int tens
, ones
, compatval
;
5378 v
= find_variable (name
);
5381 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5382 set_compatibility_opts ();
5385 val
= value_cell (v
);
5386 if (val
== 0 || *val
== '\0')
5388 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5389 set_compatibility_opts ();
5392 /* Handle decimal-like compatibility version specifications: 4.2 */
5393 if (isdigit (val
[0]) && val
[1] == '.' && isdigit (val
[2]) && val
[3] == 0)
5395 tens
= val
[0] - '0';
5396 ones
= val
[2] - '0';
5397 compatval
= tens
*10 + ones
;
5399 /* Handle integer-like compatibility version specifications: 42 */
5400 else if (isdigit (val
[0]) && isdigit (val
[1]) && val
[2] == 0)
5402 tens
= val
[0] - '0';
5403 ones
= val
[1] - '0';
5404 compatval
= tens
*10 + ones
;
5409 internal_error (_("%s: %s: compatibility value out of range"), name
, val
);
5410 shell_compatibility_level
= DEFAULT_COMPAT_LEVEL
;
5411 set_compatibility_opts ();
5415 if (compatval
< MIN_COMPAT_LEVEL
|| compatval
> DEFAULT_COMPAT_LEVEL
)
5418 shell_compatibility_level
= compatval
;
5419 set_compatibility_opts ();
5422 #if defined (JOB_CONTROL)
5430 tt
= get_string_value (name
);
5431 s
= (tt
&& *tt
) ? atoi (tt
) : 0;