2c8b939b912d1ad99efec0941ec1d4b45a71b9c8
[platform/upstream/bash.git] / variables.c
1 /* variables.c -- Functions for hacking shell variables. */
2
3 /* Copyright (C) 1987,1989 Free Software Foundation, Inc.
4
5    This file is part of GNU Bash, the Bourne Again SHell.
6
7    Bash is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 1, or (at your option)
10    any later version.
11
12    Bash is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash; see the file COPYING.  If not, write to the Free
19    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
20
21 #include "config.h"
22
23 #include "bashtypes.h"
24 #include "posixstat.h"
25
26 #if defined (HAVE_UNISTD_H)
27 #  include <unistd.h>
28 #endif
29
30 #include <stdio.h>
31 #include <ctype.h>
32 #include <pwd.h>
33 #include "bashansi.h"
34
35 #include "shell.h"
36 #include "flags.h"
37 #include "execute_cmd.h"
38 #include "mailcheck.h"
39 #include "input.h"
40
41 #include "builtins/common.h"
42 #include <tilde/tilde.h>
43
44 #if defined (HISTORY)
45 #  include "bashhist.h"
46 #endif /* HISTORY */
47
48 /* Variables used here and defined in other files. */
49 extern int posixly_correct;
50 extern int variable_context, line_number;
51 extern int interactive, interactive_shell, login_shell;
52 extern int subshell_environment, indirection_level;
53 extern int build_version, patch_level;
54 extern char *dist_version, *release_status;
55 extern char *shell_name;
56 extern char *primary_prompt, *secondary_prompt;
57 extern char *current_host_name;
58 extern Function *this_shell_builtin;
59 extern char *this_command_name;
60 extern time_t shell_start_time;
61
62 /* The list of shell variables that the user has created, or that came from
63    the environment. */
64 HASH_TABLE *shell_variables = (HASH_TABLE *)NULL;
65
66 /* The list of shell functions that the user has created, or that came from
67    the environment. */
68 HASH_TABLE *shell_functions = (HASH_TABLE *)NULL;
69
70 /* The current variable context.  This is really a count of how deep into
71    executing functions we are. */
72 int variable_context = 0;
73
74 /* The array of shell assignments which are made only in the environment
75    for a single command. */
76 char **temporary_env = (char **)NULL;
77
78 /* The array of shell assignments which are in the environment for the
79    execution of a shell function. */
80 char **function_env = (char **)NULL;
81
82 /* The array of shell assignments which are made only in the environment
83    for the execution of a shell builtin command which may cause more than
84    one command to be executed (e.g., "source"). */
85 char **builtin_env = (char **)NULL;
86
87 /* Some funky variables which are known about specially.  Here is where
88    "$*", "$1", and all the cruft is kept. */
89 char *dollar_vars[10];
90 WORD_LIST *rest_of_args = (WORD_LIST *)NULL;
91
92 /* The value of $$. */
93 int dollar_dollar_pid;
94
95 /* An array which is passed to commands as their environment.  It is
96    manufactured from the overlap of the initial environment and the
97    shell variables that are marked for export. */
98 char **export_env = (char **)NULL;
99
100 /* Non-zero means that we have to remake EXPORT_ENV. */
101 int array_needs_making = 1;
102
103 /* The number of times BASH has been executed.  This is set
104    by initialize_variables (). */
105 int shell_level = 0;
106
107 static char *have_local_variables;
108 static int local_variable_stack_size;
109
110 /* Some forward declarations. */
111 static void uidset ();
112 static void initialize_dynamic_variables ();
113 static void make_vers_array ();
114 static void sbrand ();          /* set bash random number generator. */
115 static int qsort_var_comp ();
116
117 /* Make VAR be auto-exported.  VAR is a pointer to a SHELL_VAR. */
118 #define set_auto_export(var) \
119   do { var->attributes |= att_exported; array_needs_making = 1; } while (0)
120
121 /* Initialize the shell variables from the current environment. */
122 void
123 initialize_shell_variables (env, no_functions)
124      char **env;
125      int no_functions;  /* If set, don't import functions from ENV. */
126 {
127   char *name, *string, *temp_string;
128   int c, char_index, string_index, string_length;
129   SHELL_VAR *temp_var;
130
131   if (!shell_variables)
132     shell_variables = make_hash_table (0);
133
134   if (!shell_functions)
135     shell_functions = make_hash_table (0);
136
137   for (string_index = 0; string = env[string_index++]; )
138     {
139       char_index = 0;
140
141       string_length = strlen (string);
142       name = xmalloc (1 + string_length);
143
144       while ((c = *string++) && c != '=')
145         name[char_index++] = c;
146
147       name[char_index] = '\0';
148
149       /* If exported function, define it now. */
150       if (no_functions == 0 && STREQN ("() {", string, 4))
151         {
152           temp_string = xmalloc (3 + string_length + strlen (name));
153           sprintf (temp_string, "%s %s", name, string);
154
155           parse_and_execute (temp_string, name, 0);
156
157           if (name[char_index - 1] == ')')
158             name[char_index - 2] = '\0';
159
160           if (temp_var = find_function (name))
161             {
162               temp_var->attributes |= (att_exported | att_imported);
163               array_needs_making = 1;
164             }
165           else
166             report_error ("error importing function definition for `%s'", name);
167         }
168 #if defined (ARRAY_VARS)
169 #  if 0
170       /* Array variables may not yet be exported. */
171       else if (*string == '(' && string[1] == '[' && strchr (string, ')'))
172         {
173           string_length = 1;
174           temp_string = extract_array_assignment_list (string, &string_length);
175           temp_var = assign_array_from_string (name, temp_string);
176           FREE (temp_string);
177           temp_var->attributes |= (att_exported | att_imported);
178           array_needs_making = 1;
179         }
180 #  endif
181 #endif
182       else
183         {
184           temp_var = bind_variable (name, string);
185           temp_var->attributes |= (att_exported | att_imported);
186           array_needs_making = 1;
187         }
188       free (name);
189     }
190
191   /* If we got PWD from the environment, update our idea of the current
192      working directory.  In any case, make sure that PWD exists before
193      checking it.  It is possible for getcwd () to fail on shell startup,
194      and in that case, PWD would be undefined. */
195   temp_var = find_variable ("PWD");
196   if (temp_var && imported_p (temp_var) &&
197       (temp_string = value_cell (temp_var)) &&
198       same_file (temp_string, ".", (struct stat *)NULL, (struct stat *)NULL))
199     set_working_directory (temp_string);
200   else
201     {
202       temp_string = get_working_directory ("shell-init");
203       if (temp_string)
204         {
205           bind_variable ("PWD", temp_string);
206           free (temp_string);
207         }
208     }
209
210   /* Set up initial value of $_ */
211   temp_var = bind_variable ("_", dollar_vars[0]);
212
213   /* Remember this pid. */
214   dollar_dollar_pid = (int)getpid ();
215
216   /* Now make our own defaults in case the vars that we think are
217      important are missing. */
218   temp_var = set_if_not ("PATH", DEFAULT_PATH_VALUE);
219   set_auto_export (temp_var);
220
221   temp_var = set_if_not ("TERM", "dumb");
222   set_auto_export (temp_var);
223
224   /* set up the prompts. */
225   if (interactive_shell)
226     {
227       set_if_not ("PS1", primary_prompt);
228       set_if_not ("PS2", secondary_prompt);
229     }
230   set_if_not ("PS4", "+ ");
231
232   /* Don't allow IFS to be imported from the environment. */
233   temp_var = bind_variable ("IFS", " \t\n");
234
235   /* Magic machine types.  Pretty convenient. */
236   temp_var = bind_variable ("HOSTTYPE", HOSTTYPE);
237   set_auto_export (temp_var);
238   temp_var = bind_variable ("OSTYPE", OSTYPE);
239   set_auto_export (temp_var);
240   temp_var = bind_variable ("MACHTYPE", MACHTYPE);
241   set_auto_export (temp_var);
242   temp_var = bind_variable ("HOSTNAME", current_host_name);
243   set_auto_export (temp_var);
244
245   /* Default MAILCHECK for interactive shells.  Defer the creation of a
246      default MAILPATH until the startup files are read, because MAIL
247      names a mail file if MAILCHECK is not set, and we should provide a
248      default only if neither is set. */
249   if (interactive_shell)
250     set_if_not ("MAILCHECK", "60");
251
252   /* Do some things with shell level. */
253   temp_var = set_if_not ("SHLVL", "0");
254   set_auto_export (temp_var);
255   adjust_shell_level (1);
256
257   /* Make a variable $PPID, which holds the pid of the shell's parent.  */
258   name = itos ((int) getppid ());
259   temp_var = find_variable ("PPID");
260   if (temp_var)
261     temp_var->attributes &= ~(att_readonly | att_exported);
262   temp_var = bind_variable ("PPID", name);
263   temp_var->attributes |= (att_readonly | att_integer);
264   free (name);
265
266   /* Initialize the `getopts' stuff. */
267   bind_variable ("OPTIND", "1");
268   sv_optind ("OPTIND");
269   bind_variable ("OPTERR", "1");
270   sv_opterr ("OPTERR");
271
272   /* Get the full pathname to THIS shell, and set the BASH variable
273      to it. */
274   if ((login_shell == 1) && (*shell_name != '/'))
275     {
276       /* If HOME doesn't exist, set it. */
277       temp_var = set_if_not ("HOME", current_user.home_dir);
278       temp_var->attributes |= att_exported;
279
280       name = savestring (current_user.shell);
281     }
282   else if (*shell_name == '/')
283     name = savestring (shell_name);
284   else
285     {
286       char *tname;
287       int s;
288
289       tname = find_user_command (shell_name);
290
291       if (tname == 0)
292         {
293           /* Try the current directory.  If there is not an executable
294              there, just punt and use the login shell. */
295           s = file_status (shell_name);
296           if (s & FS_EXECABLE)
297             {
298               tname = make_absolute (shell_name, get_string_value ("PWD"));
299               if (*shell_name == '.')
300                 {
301                   name = canonicalize_pathname (tname);
302                   if (name == 0)
303                     name = tname;
304                   else
305                     free (tname);
306                 }
307              else
308                 name = tname;
309             }
310           else
311             name = savestring (current_user.shell);
312         }
313       else
314         {
315           name = full_pathname (tname);
316           free (tname);
317         }
318     }
319   temp_var = bind_variable ("BASH", name);
320   free (name);
321
322   /* Make the exported environment variable SHELL be the user's login
323      shell.  Note that the `tset' command looks at this variable
324      to determine what style of commands to output; if it ends in "csh",
325      then C-shell commands are output, else Bourne shell commands. */
326   temp_var = set_if_not ("SHELL", current_user.shell);
327   set_auto_export (temp_var);
328
329   /* Make a variable called BASH_VERSION which contains the version info. */
330   bind_variable ("BASH_VERSION", shell_version_string ());
331 #if defined (ARRAY_VARS)
332   make_vers_array ();
333 #endif
334
335   /* Find out if we're supposed to be in Posix.2 mode via an
336      environment variable. */
337   temp_var = find_variable ("POSIXLY_CORRECT");
338   if (!temp_var)
339     temp_var = find_variable ("POSIX_PEDANTIC");
340   if (temp_var && imported_p (temp_var))
341     sv_strict_posix (temp_var->name);
342
343 #if defined (HISTORY)
344   /* Set history variables to defaults, and then do whatever we would
345      do if the variable had just been set.  Do this only in the case
346      that we are remembering commands on the history list. */
347   if (remember_on_history)
348     {
349       name = bash_tilde_expand (posixly_correct ? "~/.sh_history" : "~/.bash_history");
350
351       set_if_not ("HISTFILE", name);
352       free (name);
353
354       set_if_not ("HISTSIZE", "500");
355       sv_histsize ("HISTSIZE");
356     }
357 #endif /* HISTORY */
358
359   /* Seed the random number generator. */
360   sbrand (dollar_dollar_pid + (long)shell_start_time);
361
362   /* Handle some "special" variables that we may have inherited from a
363      parent shell. */
364
365   temp_var = find_variable ("IGNOREEOF");
366   if (!temp_var)
367     temp_var = find_variable ("ignoreeof");
368   if (temp_var && imported_p (temp_var))
369     sv_ignoreeof (temp_var->name);
370
371 #if defined (HISTORY)
372   if (interactive_shell && remember_on_history)
373     {
374       sv_history_control ("HISTCONTROL");
375       sv_histignore ("HISTIGNORE");
376     }
377 #endif /* HISTORY */
378
379   /* Get the user's real and effective user ids. */
380   uidset ();
381
382   /* Initialize the dynamic variables, and seed their values. */
383   initialize_dynamic_variables ();
384 }
385
386 void
387 adjust_shell_level (change)
388      int change;
389 {
390   char *new_level, *old_SHLVL;
391   int old_level;
392
393   old_SHLVL = get_string_value ("SHLVL");
394   if (old_SHLVL)
395     old_level = atoi (old_SHLVL);
396   else
397     old_level = 0;
398
399   shell_level = old_level + change;
400   if (shell_level < 0)
401     shell_level = 0;
402   new_level = itos (shell_level);
403   bind_variable ("SHLVL", new_level);
404   free (new_level);
405 }
406
407 static void
408 uidset ()
409 {
410   char *buff;
411   register SHELL_VAR *v;
412
413   buff = itos (current_user.uid);
414   v = find_variable ("UID");
415   if (v)
416     v->attributes &= ~att_readonly;
417
418   v = bind_variable ("UID", buff);
419   v->attributes |= (att_readonly | att_integer);
420
421   if (current_user.euid != current_user.uid)
422     {
423       free (buff);
424       buff = itos (current_user.euid);
425     }
426
427   v = find_variable ("EUID");
428   if (v)
429     v->attributes &= ~att_readonly;
430
431   v = bind_variable ("EUID", buff);
432   v->attributes |= (att_readonly | att_integer);
433   free (buff);
434 }
435
436 #if defined (ARRAY_VARS)
437 static void
438 make_vers_array ()
439 {
440   SHELL_VAR *vv;
441   ARRAY *av;
442   char *s, d[16];
443
444   makunbound ("BASH_VERSINFO", shell_variables);
445
446   vv = make_new_array_variable ("BASH_VERSINFO");
447   av = array_cell (vv);
448   strcpy (d, dist_version);
449   s = strchr (d, '.');
450   if (s)
451     *s++ = '\0';
452   array_add_element (av, 0, d);
453   array_add_element (av, 1, s);
454   s = itos (patch_level);
455   array_add_element (av, 2, s);
456   free (s);
457   s = itos (build_version);
458   array_add_element (av, 3, s);
459   free (s);
460   array_add_element (av, 4, release_status);
461   array_add_element (av, 5, MACHTYPE);
462
463   vv->attributes |= att_readonly;
464 }
465 #endif /* ARRAY_VARS */
466
467 /* Set the environment variables $LINES and $COLUMNS in response to
468    a window size change. */
469 void
470 set_lines_and_columns (lines, cols)
471      int lines, cols;
472 {
473   char *val;
474
475   val = itos (lines);
476   bind_variable ("LINES", val);
477   free (val);
478
479   val = itos (cols);
480   bind_variable ("COLUMNS", val);
481   free (val);
482 }
483
484 /* Set NAME to VALUE if NAME has no value. */
485 SHELL_VAR *
486 set_if_not (name, value)
487      char *name, *value;
488 {
489   SHELL_VAR *v;
490
491   v = find_variable (name);
492   if (!v)
493     v = bind_variable (name, value);
494   return (v);
495 }
496
497 /* Map FUNCTION over the variables in VARIABLES.  Return an array of the
498    variables that satisfy FUNCTION.  Satisfy means that FUNCTION returns
499    a non-zero value for.  A NULL value for FUNCTION means to use all
500    variables. */
501 SHELL_VAR **
502 map_over (function, var_hash_table)
503      Function *function;
504      HASH_TABLE* var_hash_table;
505 {
506   register int i;
507   register BUCKET_CONTENTS *tlist;
508   SHELL_VAR *var, **list = (SHELL_VAR **)NULL;
509   int list_index = 0, list_size = 0;
510
511   for (i = 0; i < var_hash_table->nbuckets; i++)
512     {
513       tlist = get_hash_bucket (i, var_hash_table);
514
515       while (tlist)
516         {
517           var = (SHELL_VAR *)tlist->data;
518
519           if (!function || (*function) (var))
520             {
521               if (list_index + 1 >= list_size)
522                 list = (SHELL_VAR **)
523                   xrealloc (list, (list_size += 20) * sizeof (SHELL_VAR *));
524
525               list[list_index++] = var;
526               list[list_index] = (SHELL_VAR *)NULL;
527             }
528           tlist = tlist->next;
529         }
530     }
531   return (list);
532 }
533
534 void
535 sort_variables (array)
536      SHELL_VAR **array;
537 {
538   qsort (array, array_len ((char **)array), sizeof (SHELL_VAR *), qsort_var_comp);
539 }
540
541 static int
542 qsort_var_comp (var1, var2)
543      SHELL_VAR **var1, **var2;
544 {
545   int result;
546
547   if ((result = (*var1)->name[0] - (*var2)->name[0]) == 0)
548     result = strcmp ((*var1)->name, (*var2)->name);
549
550   return (result);
551 }
552
553 /* Create a NULL terminated array of all the shell variables in TABLE. */
554 static SHELL_VAR **
555 all_vars (table)
556      HASH_TABLE *table;
557 {
558   SHELL_VAR **list;
559
560   list = map_over ((Function *)NULL, table);
561   if (list && posixly_correct)
562     sort_variables (list);
563   return (list);
564 }
565
566 /* Create a NULL terminated array of all the shell variables. */
567 SHELL_VAR **
568 all_shell_variables ()
569 {
570   return (all_vars (shell_variables));
571 }
572
573 /* Create a NULL terminated array of all the shell functions. */
574 SHELL_VAR **
575 all_shell_functions ()
576 {
577   return (all_vars (shell_functions));
578 }
579
580 /* Print VARS to stdout in such a way that they can be read back in. */
581 void
582 print_var_list (list)
583      register SHELL_VAR **list;
584 {
585   register int i;
586   register SHELL_VAR *var;
587
588   for (i = 0; list && (var = list[i]); i++)
589     if (!invisible_p (var))
590       print_assignment (var);
591 }
592
593 #if defined (NOTDEF)
594 /* Print LIST (a linked list of shell variables) to stdout
595    by printing the names, without the values.  Used to support the
596    `set +' command. */
597 void
598 print_vars_no_values (list)
599      register SHELL_VAR **list;
600 {
601   register int i;
602   register SHELL_VAR *var;
603
604   for (i = 0; list && (var = list[i]); i++)
605     if (!invisible_p (var))
606       printf ("%s\n", var->name);
607 }
608 #endif
609
610 /* Print the value of a single SHELL_VAR.  No newline is
611    output, but the variable is printed in such a way that
612    it can be read back in. */
613 void
614 print_assignment (var)
615      SHELL_VAR *var;
616 {
617   if (function_p (var) && var->value)
618     {
619       printf ("%s=", var->name);
620       print_var_function (var);
621       printf ("\n");
622     }
623 #if defined (ARRAY_VARS)
624   else if (array_p (var) && var->value)
625     print_array_assignment (var, 0);
626 #endif /* ARRAY_VARS */
627   else if (var->value)
628     {
629       printf ("%s=", var->name);
630       print_var_value (var, 1);
631       printf ("\n");
632     }
633 }
634
635 /* Print the value cell of VAR, a shell variable.  Do not print
636    the name, nor leading/trailing newline.  If QUOTE is non-zero,
637    and the value contains shell metacharacters, quote the value
638    in such a way that it can be read back in. */
639 void
640 print_var_value (var, quote)
641      SHELL_VAR *var;
642      int quote;
643 {
644   char *t;
645
646   if (var->value)
647     {
648       if (quote && contains_shell_metas (var->value))
649         {
650           t = single_quote (var->value);
651           printf ("%s", t);
652           free (t);
653         }
654       else
655         printf ("%s", var->value);
656     }
657 }
658
659 /* Print the function cell of VAR, a shell variable.  Do not
660    print the name, nor leading/trailing newline. */
661 void
662 print_var_function (var)
663      SHELL_VAR *var;
664 {
665   if (function_p (var) && var->value)
666     printf ("%s", named_function_string ((char *)NULL, function_cell(var), 1));
667 }
668
669 #if defined (ARRAY_VARS)
670 void
671 print_array_assignment (var, quoted)
672      SHELL_VAR *var;
673      int quoted;
674 {
675   char *vstr;
676
677   if (quoted)
678     vstr = quoted_array_assignment_string (array_cell (var));
679   else
680     vstr = array_to_assignment_string (array_cell (var));
681
682   if (vstr == 0)
683     printf ("%s=%s\n", var->name, quoted ? "'()'" : "()");
684   else
685     {
686       printf ("%s=%s\n", var->name, vstr);
687       free (vstr);
688     }
689 }
690 #endif /* ARRAY_VARS */
691
692 /* **************************************************************** */
693 /*                                                                  */
694 /*               Dynamic Variable Extension                         */
695 /*                                                                  */
696 /* **************************************************************** */
697
698 /* DYNAMIC VARIABLES
699
700    These are variables whose values are generated anew each time they are
701    referenced.  These are implemented using a pair of function pointers
702    in the struct variable: assign_func, which is called from bind_variable,
703    and dynamic_value, which is called from find_variable.
704
705    assign_func is called from bind_variable, if bind_variable discovers
706    that the variable being assigned to has such a function.  The function
707    is called as
708         SHELL_VAR *temp = (*(entry->assign_func)) (entry, value)
709    and the (SHELL_VAR *)temp is returned as the value of bind_variable.  It
710    is usually ENTRY (self).
711
712    dynamic_value is called from find_variable to return a `new' value for
713    the specified dynamic varible.  If this function is NULL, the variable
714    is treated as a `normal' shell variable.  If it is not, however, then
715    this function is called like this:
716         tempvar = (*(var->dynamic_value)) (var);
717
718    Sometimes `tempvar' will replace the value of `var'.  Other times, the
719    shell will simply use the string value.  Pretty object-oriented, huh?
720
721    Be warned, though: if you `unset' a special variable, it loses its
722    special meaning, even if you subsequently set it.
723
724    The special assignment code would probably have been better put in
725    subst.c: do_assignment, in the same style as
726    stupidly_hack_special_variables, but I wanted the changes as
727    localized as possible.  */
728
729 /* The value of $SECONDS.  This is the number of seconds since shell
730    invocation, or, the number of seconds since the last assignment + the
731    value of the last assignment. */
732 static long seconds_value_assigned;
733
734 static SHELL_VAR *
735 assign_seconds (self, value)
736      SHELL_VAR *self;
737      char *value;
738 {
739   seconds_value_assigned = string_to_long (value);
740   shell_start_time = NOW;
741   return (self);
742 }
743
744 static SHELL_VAR *
745 get_seconds (var)
746      SHELL_VAR *var;
747 {
748   time_t time_since_start;
749   char *p;
750
751   time_since_start = NOW - shell_start_time;
752   p = itos((int) seconds_value_assigned + time_since_start);
753
754   FREE (var->value);
755
756   var->attributes |= att_integer;
757   var->value = p;
758   return (var);
759 }
760
761 /* The random number seed.  You can change this by setting RANDOM. */
762 static unsigned long rseed = 1;
763 static unsigned long last_random_value;
764
765 /* A linear congruential random number generator based on the ANSI
766    C standard.  A more complicated one is overkill.  */
767
768 /* Returns a pseudo-random number between 0 and 32767. */
769 static int
770 brand ()
771 {
772   rseed = rseed * 1103515245 + 12345;
773   return ((unsigned int)(rseed / 65536) % 32768);
774 }
775
776 /* Set the random number generator seed to SEED. */
777 static void
778 sbrand (seed)
779      int seed;
780 {
781   rseed = seed;
782 }
783
784 static SHELL_VAR *
785 assign_random (self, value)
786      SHELL_VAR *self;
787      char *value;
788 {
789   sbrand (atoi (value));
790   return (self);
791 }
792
793 static SHELL_VAR *
794 get_random (var)
795      SHELL_VAR *var;
796 {
797   int rv;
798   char *p;
799
800   /* Reset for command and process substitution. */
801   if (subshell_environment)
802     sbrand ((int)(getpid() + NOW));
803
804   do
805     rv = brand ();
806   while (rv == (int)last_random_value);
807
808   last_random_value = rv;
809   p = itos ((int)rv);
810
811   FREE (var->value);
812
813   var->attributes |= att_integer;
814   var->value = p;
815   return (var);
816 }
817
818 /* Function which returns the current line number. */
819 static SHELL_VAR *
820 get_lineno (var)
821      SHELL_VAR *var;
822 {
823   char *p;
824   int ln;
825
826   ln = executing_line_number ();
827   p = itos (ln);
828   FREE (var->value);
829   var->value = p;
830   return (var);
831 }
832
833 static SHELL_VAR *
834 assign_lineno (var, value)
835      SHELL_VAR *var;
836      char *value;
837 {
838   line_number = atoi (value);
839   return var;
840 }
841
842 #if defined (HISTORY)
843 static SHELL_VAR *
844 get_histcmd (var)
845      SHELL_VAR *var;
846 {
847   char *p;
848
849   p = itos (history_number ());
850   FREE (var->value);
851   var->value = p;
852   return (var);
853 }
854 #endif
855
856 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
857 static SHELL_VAR *
858 get_dirstack (self)
859      SHELL_VAR *self;
860 {
861   ARRAY *a;
862   WORD_LIST *l;
863
864   l = get_directory_stack ();
865   a = word_list_to_array (l);
866   dispose_array (array_cell (self));
867   self->value = (char *)a;
868   return self;
869 }
870
871 static  SHELL_VAR *
872 assign_dirstack (self, ind, value)
873      SHELL_VAR *self;
874      int ind;
875      char *value;
876 {
877   set_dirstack_element (ind, 1, value);
878   return self;
879 }
880 #endif /* PUSHD AND POPD && ARRAY_VARS */
881
882 static void
883 initialize_dynamic_variables ()
884 {
885   SHELL_VAR *v;
886
887   v = bind_variable ("SECONDS", (char *)NULL);
888   v->dynamic_value = get_seconds;
889   v->assign_func = assign_seconds;
890
891   v = bind_variable ("RANDOM", (char *)NULL);
892   v->dynamic_value = get_random;
893   v->assign_func = assign_random;
894
895   v = bind_variable ("LINENO", (char *)NULL);
896   v->dynamic_value = get_lineno;
897   v->assign_func = assign_lineno;
898
899 #if defined (HISTORY)
900   v = bind_variable ("HISTCMD", (char *)NULL);
901   v->dynamic_value = get_histcmd;
902   v->assign_func = (DYNAMIC_FUNC *)NULL;
903 #endif
904
905 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
906   v = make_new_array_variable ("DIRSTACK");
907   v->dynamic_value = get_dirstack;
908   v->assign_func = assign_dirstack;
909 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
910 }
911
912 /* How to get a pointer to the shell variable or function named NAME.
913    HASHED_VARS is a pointer to the hash table containing the list
914    of interest (either variables or functions). */
915 SHELL_VAR *
916 var_lookup (name, hashed_vars)
917      char *name;
918      HASH_TABLE *hashed_vars;
919 {
920   BUCKET_CONTENTS *bucket;
921
922   bucket = find_hash_item (name, hashed_vars);
923   return (bucket ? (SHELL_VAR *)bucket->data : (SHELL_VAR *)NULL);
924 }
925
926 /* Look up the variable entry named NAME.  If SEARCH_TEMPENV is non-zero,
927    then also search the temporarily built list of exported variables. */
928 SHELL_VAR *
929 find_variable_internal (name, search_tempenv)
930      char *name;
931      int search_tempenv;
932 {
933   SHELL_VAR *var = (SHELL_VAR *)NULL;
934
935   /* If explicitly requested, first look in the temporary environment for
936      the variable.  This allows constructs such as "foo=x eval 'echo $foo'"
937      to get the `exported' value of $foo.  This happens if we are executing
938      a function or builtin, or if we are looking up a variable in a
939      "subshell environment". */
940   if ((search_tempenv || subshell_environment) &&
941       (temporary_env || builtin_env || function_env))
942     var = find_tempenv_variable (name);
943
944   if (!var)
945     var = var_lookup (name, shell_variables);
946
947   if (!var)
948     return ((SHELL_VAR *)NULL);
949
950   return (var->dynamic_value ? (*(var->dynamic_value)) (var) : var);
951 }
952
953 /* Look up the variable entry named NAME.  Returns the entry or NULL. */
954 SHELL_VAR *
955 find_variable (name)
956      char *name;
957 {
958   return (find_variable_internal
959           (name, (variable_context || this_shell_builtin || builtin_env)));
960 }
961
962 /* Look up the function entry whose name matches STRING.
963    Returns the entry or NULL. */
964 SHELL_VAR *
965 find_function (name)
966      char *name;
967 {
968   return (var_lookup (name, shell_functions));
969 }
970
971 /* Return the string value of a variable.  Return NULL if the variable
972    doesn't exist, or only has a function as a value.  Don't cons a new
973    string. */
974 char *
975 get_string_value (var_name)
976      char *var_name;
977 {
978   SHELL_VAR *var = find_variable (var_name);
979
980   if (!var)
981     return (char *)NULL;
982 #if defined (ARRAY_VARS)
983   else if (array_p (var))
984     return (array_reference (array_cell (var), 0));
985 #endif
986   else
987     return (var->value);
988 }
989
990 /* Create a local variable referenced by NAME. */
991 SHELL_VAR *
992 make_local_variable (name)
993      char *name;
994 {
995   SHELL_VAR *new_var, *old_var;
996   BUCKET_CONTENTS *elt;
997
998   /* local foo; local foo;  is a no-op. */
999   old_var = find_variable (name);
1000   if (old_var && old_var->context == variable_context)
1001     return (old_var);
1002
1003   elt = remove_hash_item (name, shell_variables);
1004   if (elt)
1005     {
1006       old_var = (SHELL_VAR *)elt->data;
1007       free (elt->key);
1008       free (elt);
1009     }
1010   else
1011     old_var = (SHELL_VAR *)NULL;
1012
1013   /* If a variable does not already exist with this name, then
1014      just make a new one. */
1015   if (!old_var)
1016     {
1017       new_var = bind_variable (name, "");
1018     }
1019   else
1020     {
1021       new_var = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1022
1023       new_var->name = savestring (name);
1024       new_var->value = xmalloc (1);
1025       new_var->value[0] = '\0';
1026
1027       new_var->dynamic_value = (DYNAMIC_FUNC *)NULL;
1028       new_var->assign_func = (DYNAMIC_FUNC *)NULL;
1029
1030       new_var->attributes = exported_p (old_var) ? att_exported : 0;
1031
1032       new_var->prev_context = old_var;
1033       elt = add_hash_item (savestring (name), shell_variables);
1034       elt->data = (char *)new_var;
1035     }
1036
1037   new_var->context = variable_context;
1038   new_var->attributes |= att_local;
1039
1040   /* XXX */
1041   if (variable_context >= local_variable_stack_size)
1042     {
1043       int old_size = local_variable_stack_size;
1044       RESIZE_MALLOCED_BUFFER (have_local_variables, variable_context, 1,
1045                               local_variable_stack_size, 8);
1046       bzero ((char *)have_local_variables + old_size,
1047              local_variable_stack_size - old_size);
1048     }
1049   have_local_variables[variable_context] = 1;           /* XXX */
1050
1051   return (new_var);
1052 }
1053
1054 #if defined (ARRAY_VARS)
1055 SHELL_VAR *
1056 make_local_array_variable (name)
1057      char *name;
1058 {
1059   SHELL_VAR *var;
1060   ARRAY *array;
1061
1062   var = make_local_variable (name);
1063   array = new_array ();
1064
1065   FREE (value_cell(var));
1066   var->value = (char *)array;
1067   var->attributes |= att_array;
1068   return var;
1069 }
1070 #endif /* ARRAY_VARS */
1071
1072 /* Create a new shell variable with name NAME and add it to the hash table
1073    of shell variables. */
1074 static
1075 SHELL_VAR *
1076 make_new_variable (name)
1077      char *name;
1078 {
1079   SHELL_VAR *entry;
1080   BUCKET_CONTENTS *elt;
1081
1082   entry = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1083
1084   entry->attributes = 0;
1085   entry->name = savestring (name);
1086   entry->value = (char *)NULL;
1087
1088   entry->dynamic_value = (DYNAMIC_FUNC *)NULL;
1089   entry->assign_func = (DYNAMIC_FUNC *)NULL;
1090
1091   /* Always assume variables are to be made at toplevel!
1092      make_local_variable has the responsibilty of changing the
1093      variable context. */
1094   entry->context = 0;
1095   entry->prev_context = (SHELL_VAR *)NULL;
1096
1097   elt = add_hash_item (savestring (name), shell_variables);
1098   elt->data = (char *)entry;
1099
1100   return entry;
1101 }
1102
1103 #if defined (ARRAY_VARS)
1104 SHELL_VAR *
1105 make_new_array_variable (name)
1106      char *name;
1107 {
1108   SHELL_VAR *entry;
1109   ARRAY *array;
1110
1111   entry = make_new_variable (name);
1112   array = new_array ();
1113   entry->value = (char *)array;
1114   entry->attributes |= att_array;
1115   return entry;
1116 }
1117 #endif
1118
1119 char *
1120 make_variable_value (var, value)
1121      SHELL_VAR *var;
1122      char *value;
1123 {
1124   char *retval;
1125   long lval;
1126
1127   /* If this variable has had its type set to integer (via `declare -i'),
1128      then do expression evaluation on it and store the result.  The
1129      functions in expr.c (evalexp and bind_int_variable) are responsible
1130      for turning off the integer flag if they don't want further
1131      evaluation done. */
1132   if (integer_p (var))
1133     {
1134       lval = evalexp (value);
1135       retval = itos (lval);
1136     }
1137   else if (value)
1138     {
1139       if (*value)
1140         retval = savestring (value);
1141       else
1142         {
1143           retval = xmalloc (1);
1144           retval[0] = '\0';
1145         }
1146     }
1147   else
1148     retval = (char *)NULL;
1149
1150   return retval;
1151 }
1152
1153 /* Bind a variable NAME to VALUE.  This conses up the name
1154    and value strings. */
1155 SHELL_VAR *
1156 bind_variable (name, value)
1157      char *name, *value;
1158 {
1159   char *newval;
1160   SHELL_VAR *entry;
1161
1162   entry = var_lookup (name, shell_variables);
1163
1164   if (entry == 0)
1165     {
1166       entry = make_new_variable (name);
1167       entry->value = make_variable_value (entry, value);
1168     }
1169 #if defined (ARRAY_VARS)
1170   else if (entry->assign_func && array_p (entry) == 0)
1171 #else
1172   else if (entry->assign_func)
1173 #endif
1174     return ((*(entry->assign_func)) (entry, value));
1175   else
1176     {
1177       if (readonly_p (entry))
1178         {
1179           report_error ("%s: readonly variable", name);
1180           return (entry);
1181         }
1182
1183       /* Variables which are bound are visible. */
1184       entry->attributes &= ~att_invisible;
1185
1186       newval = make_variable_value (entry, value);
1187
1188 #if defined (ARRAY_VARS)
1189       /* XXX -- this bears looking at again -- XXX */
1190       /* If an existing array variable x is being assigned to with x=b or
1191          `read x' or something of that nature, silently convert it to
1192          x[0]=b or `read x[0]'. */
1193       if (array_p (entry))
1194         array_add_element (array_cell (entry), 0, newval);
1195       else
1196         {
1197           FREE (entry->value);
1198           entry->value = newval;
1199         }
1200 #else
1201       FREE (entry->value);
1202       entry->value = newval;
1203 #endif
1204     }
1205
1206   if (mark_modified_vars)
1207     entry->attributes |= att_exported;
1208
1209   if (exported_p (entry))
1210     array_needs_making = 1;
1211
1212   return (entry);
1213 }
1214
1215 #if defined (ARRAY_VARS)
1216 /* Convert a shell variable to an array variable.  The original value is
1217    saved as array[0]. */
1218 SHELL_VAR *
1219 convert_var_to_array (var)
1220      SHELL_VAR *var;
1221 {
1222   char *oldval;
1223   ARRAY *array;
1224
1225   oldval = value_cell (var);
1226   array = new_array ();
1227   array_add_element (array, 0, oldval);
1228   FREE (value_cell (var));
1229   var->value = (char *)array;
1230   var->attributes |= att_array;
1231   var->attributes &= ~att_invisible;
1232
1233   return var;
1234 }
1235
1236 /* Perform an array assignment name[ind]=value.  If NAME already exists and
1237    is not an array, and IND is 0, perform name=value instead.  If NAME exists
1238    and is not an array, and IND is not 0, convert it into an array with the
1239    existing value as name[0].
1240
1241    If NAME does not exist, just create an array variable, no matter what
1242    IND's value may be. */
1243 SHELL_VAR *
1244 bind_array_variable (name, ind, value)
1245      char *name;
1246      int ind;
1247      char *value;
1248 {
1249   SHELL_VAR *entry;
1250   char *newval;
1251
1252   entry = var_lookup (name, shell_variables);
1253
1254   if (entry == (SHELL_VAR *) 0)
1255     entry = make_new_array_variable (name);
1256   else if (readonly_p (entry))
1257     {
1258       report_error ("%s: readonly variable", name);
1259       return (entry);
1260     }
1261   else if (array_p (entry) == 0)
1262     entry = convert_var_to_array (entry);
1263
1264   /* ENTRY is an array variable, and ARRAY points to the value. */
1265   newval = make_variable_value (entry, value);
1266   if (entry->assign_func)
1267     (*entry->assign_func) (entry, ind, newval);
1268   else
1269     array_add_element (array_cell (entry), ind, newval);
1270   FREE (newval);
1271
1272   return (entry);
1273 }
1274
1275 SHELL_VAR *
1276 assign_array_from_string (name, value)
1277      char *name, *value;
1278 {
1279   SHELL_VAR *var;
1280
1281   var = find_variable (name);
1282   if (var == 0)
1283     var = make_new_array_variable (name);
1284   else if (array_p (var) == 0)
1285     var = convert_var_to_array (var);
1286
1287   return (assign_array_var_from_string (var, value));
1288 }
1289
1290 SHELL_VAR *
1291 assign_array_var_from_word_list (var, list)
1292      SHELL_VAR *var;
1293      WORD_LIST *list;
1294 {
1295   register int i;
1296   register WORD_LIST *l;
1297   ARRAY *a;
1298
1299   for (a = array_cell (var), l = list, i = 0; l; l = l->next, i++)
1300     if (var->assign_func)
1301       (*var->assign_func) (var, i, l->word->word);
1302     else
1303       array_add_element (a, i, l->word->word);
1304   return var;
1305 }
1306
1307 SHELL_VAR *
1308 assign_array_var_from_string (var, value)
1309      SHELL_VAR *var;
1310      char *value;
1311 {
1312   ARRAY *a;
1313   WORD_LIST *list, *nlist;
1314   char *w, *val, *nval;
1315   int ni, len, ind, last_ind;
1316
1317   a = array_cell (var);
1318
1319   /* Expand the value string into a list of words, performing all the
1320      shell expansions including word splitting. */
1321   if (*value == '(')
1322     {
1323       ni = 1;
1324       val = extract_array_assignment_list (value, &ni);
1325       if (val == 0)
1326         return var;
1327       nlist = expand_string (val, 0);
1328       free (val);
1329     }
1330   else
1331     nlist = expand_string (value, 0);
1332
1333   for (last_ind = 0, list = nlist; list; list = list->next)
1334     {
1335       w = list->word->word;
1336
1337       /* We have a word of the form [ind]=value */
1338       if (w[0] == '[')
1339         {
1340           len = skipsubscript (w, 0);
1341
1342           if (w[len] != ']' || w[len+1] != '=')
1343             {
1344               nval = make_variable_value (var, w);
1345               if (var->assign_func)
1346                 (*var->assign_func) (var, last_ind, nval);
1347               else
1348                 array_add_element (a, last_ind, nval);
1349               FREE (nval);
1350               last_ind++;
1351               continue;
1352             }
1353
1354           if (len == 1)
1355             {
1356               report_error ("%s: bad array subscript", w);
1357               continue;
1358             }
1359
1360           if (ALL_ELEMENT_SUB (w[1]) && len == 2)
1361             {
1362               report_error ("%s: cannot assign to non-numeric index", w);
1363               continue;
1364             }
1365
1366           ind = array_expand_index (w + 1, len);
1367           if (ind < 0)
1368             {
1369               report_error ("%s: bad array subscript", w);
1370               continue;
1371             }
1372           last_ind = ind;
1373           val = w + len + 2;
1374         }
1375       else              /* No [ind]=value, just a stray `=' */
1376         {
1377           ind = last_ind;
1378           val = w;
1379         }
1380
1381       if (integer_p (var))
1382         this_command_name = (char *)NULL;       /* no command name for errors */
1383       nval = make_variable_value (var, val);
1384       if (var->assign_func)
1385         (*var->assign_func) (var, ind, nval);
1386       else
1387         array_add_element (a, ind, nval);
1388       FREE (nval);
1389       last_ind++;
1390     }
1391
1392   dispose_words (nlist);
1393   return (var);
1394 }
1395 #endif /* ARRAY_VARS */
1396
1397 /* Dispose of the information attached to VAR. */
1398 void
1399 dispose_variable (var)
1400      SHELL_VAR *var;
1401 {
1402   if (!var)
1403     return;
1404
1405   if (function_p (var))
1406     dispose_command (function_cell (var));
1407 #if defined (ARRAY_VARS)
1408   else if (array_p (var))
1409     dispose_array (array_cell (var));
1410 #endif
1411   else
1412     FREE (value_cell (var));
1413
1414   free (var->name);
1415
1416   if (exported_p (var))
1417     array_needs_making = 1;
1418
1419   free (var);
1420 }
1421
1422 #if defined (ARRAY_VARS)
1423 /* This function is called with SUB pointing to just after the beginning
1424    `[' of an array subscript. */
1425 int
1426 unbind_array_element (var, sub)
1427      SHELL_VAR *var;
1428      char *sub;
1429 {
1430   int len, ind;
1431   ARRAY_ELEMENT *ae;
1432
1433   len = skipsubscript (sub, 0);
1434   if (sub[len] != ']' || len == 0)
1435     {
1436       builtin_error ("%s[%s: bad array subscript", var->name, sub);
1437       return -1;
1438     }
1439   sub[len] = '\0';
1440
1441   if (ALL_ELEMENT_SUB (sub[0]) && sub[1] == 0)
1442     {
1443       makunbound (var->name, shell_variables);
1444       return (0);
1445     }
1446   ind = array_expand_index (sub, len+1);
1447   if (ind < 0)
1448     {
1449       builtin_error ("[%s: bad array subscript", sub);
1450       return -1;
1451     }
1452   ae = array_delete_element (array_cell (var), ind);
1453   if (ae)
1454     destroy_array_element (ae);
1455   return 0;
1456 }
1457 #endif
1458
1459 /* Unset the variable referenced by NAME. */
1460 int
1461 unbind_variable (name)
1462      char *name;
1463 {
1464   SHELL_VAR *var = find_variable (name);
1465
1466   if (!var)
1467     return (-1);
1468
1469   /* This function should never be called with an array variable name. */
1470 #if defined (ARRAY_VARS)
1471   if (array_p (var) == 0 && var->value)
1472 #else
1473   if (var->value)
1474 #endif
1475     {
1476       free (var->value);
1477       var->value = (char *)NULL;
1478     }
1479
1480   makunbound (name, shell_variables);
1481
1482   return (0);
1483 }
1484
1485 /* Make the variable associated with NAME go away.  HASH_LIST is the
1486    hash table from which this variable should be deleted (either
1487    shell_variables or shell_functions).
1488    Returns non-zero if the variable couldn't be found. */
1489 int
1490 makunbound (name, hash_list)
1491      char *name;
1492      HASH_TABLE *hash_list;
1493 {
1494   BUCKET_CONTENTS *elt;
1495   SHELL_VAR *old_var, *new_var;
1496   char *t;
1497
1498   elt = remove_hash_item (name, hash_list);
1499
1500   if (!elt)
1501     return (-1);
1502
1503   old_var = (SHELL_VAR *)elt->data;
1504   new_var = old_var->prev_context;
1505
1506   if (old_var && exported_p (old_var))
1507     array_needs_making++;
1508
1509   /* If we're unsetting a local variable and we're still executing inside
1510      the function, just mark the variable as invisible.
1511      kill_all_local_variables will clean it up later.  This must be done
1512      so that if the variable is subsequently assigned a new value inside
1513      the function, the `local' attribute is still present.  We also need
1514      to add it back into the correct hash table. */
1515   if (old_var && local_p (old_var) && variable_context == old_var->context)
1516     {
1517       old_var->attributes |= att_invisible;
1518       elt = add_hash_item (savestring (old_var->name), hash_list);
1519       elt->data = (char *)old_var;
1520       stupidly_hack_special_variables (old_var->name);
1521       return (0);
1522     }
1523
1524   if (new_var)
1525     {
1526       /* Has to be a variable, functions don't have previous contexts. */
1527       BUCKET_CONTENTS *new_elt;
1528
1529       new_elt = add_hash_item (savestring (new_var->name), hash_list);
1530       new_elt->data = (char *)new_var;
1531
1532       if (exported_p (new_var))
1533         set_auto_export (new_var);
1534     }
1535
1536   /* Have to save a copy of name here, because it might refer to
1537      old_var->name.  If so, stupidly_hack_special_variables will
1538      reference freed memory. */
1539   t = savestring (name);
1540
1541   free (elt->key);
1542   free (elt);
1543
1544   dispose_variable (old_var);
1545   stupidly_hack_special_variables (t);
1546   free (t);
1547   return (0);
1548 }
1549
1550 /* Remove the variable with NAME if it is a local variable in the
1551    current context. */
1552 int
1553 kill_local_variable (name)
1554      char *name;
1555 {
1556   SHELL_VAR *temp = find_variable (name);
1557
1558   if (temp && temp->context == variable_context)
1559     {
1560       makunbound (name, shell_variables);
1561       return (0);
1562     }
1563   return (-1);
1564 }
1565
1566 /* Get rid of all of the variables in the current context. */
1567 int
1568 variable_in_context (var)
1569      SHELL_VAR *var;
1570 {
1571   return (var && var->context == variable_context);
1572 }
1573
1574 void
1575 kill_all_local_variables ()
1576 {
1577   register int i, pass;
1578   register SHELL_VAR *var, **list;
1579   HASH_TABLE *varlist;
1580
1581   /* If HAVE_LOCAL_VARIABLES == 0, it means that we don't have any local
1582      variables at all.  If VARIABLE_CONTEXT >= LOCAL_VARIABLE_STACK_SIZE,
1583      it means that we have some local variables, but not in this variable
1584      context (level of function nesting).  Also, if
1585      HAVE_LOCAL_VARIABLES[VARIABLE_CONTEXT] == 0, we have no local variables
1586      at this context. */
1587   if (have_local_variables == 0 ||
1588       variable_context >= local_variable_stack_size ||
1589       have_local_variables[variable_context] == 0)
1590     return;
1591
1592   for (pass = 0; pass < 2; pass++)
1593     {
1594       varlist = pass ? shell_functions : shell_variables;
1595
1596       list = map_over (variable_in_context, varlist);
1597
1598       if (list)
1599         {
1600           for (i = 0; var = list[i]; i++)
1601             {
1602               var->attributes &= ~att_local;
1603               makunbound (var->name, varlist);
1604             }
1605           free (list);
1606         }
1607     }
1608
1609   have_local_variables[variable_context] = 0;           /* XXX */
1610 }
1611
1612 static void
1613 free_variable_hash_data (data)
1614      char *data;
1615 {
1616   SHELL_VAR *var, *prev;
1617
1618   var = (SHELL_VAR *)data;
1619   while (var)
1620     {
1621       prev = var->prev_context;
1622       dispose_variable (var);
1623       var = prev;
1624     }
1625 }
1626
1627 /* Delete the entire contents of the hash table. */
1628 void
1629 delete_all_variables (hashed_vars)
1630      HASH_TABLE *hashed_vars;
1631 {
1632   flush_hash_table (hashed_vars, free_variable_hash_data);
1633 }
1634
1635 static SHELL_VAR *
1636 new_shell_variable (name)
1637      char *name;
1638 {
1639   SHELL_VAR *var;
1640
1641   var = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1642
1643   bzero ((char *)var, sizeof (SHELL_VAR));
1644   var->name = savestring (name);
1645   return (var);
1646 }
1647
1648 /* Do a function binding to a variable.  You pass the name and
1649    the command to bind to.  This conses the name and command. */
1650 SHELL_VAR *
1651 bind_function (name, value)
1652      char *name;
1653      COMMAND *value;
1654 {
1655   SHELL_VAR *entry;
1656
1657   entry = find_function (name);
1658   if (!entry)
1659     {
1660       BUCKET_CONTENTS *elt;
1661
1662       elt = add_hash_item (savestring (name), shell_functions);
1663
1664       elt->data = (char *)new_shell_variable (name);
1665       entry = (SHELL_VAR *)elt->data;
1666       entry->dynamic_value = entry->assign_func = (DYNAMIC_FUNC *)NULL;
1667
1668       /* Functions are always made at the top level.  This allows a
1669          function to define another function (like autoload). */
1670       entry->context = 0;
1671     }
1672
1673   if (entry->value)
1674     dispose_command ((COMMAND *)entry->value);
1675
1676   entry->value = value ? (char *)copy_command (value) : (char *)NULL;
1677   entry->attributes |= att_function;
1678
1679   if (mark_modified_vars)
1680     entry->attributes |= att_exported;
1681
1682   entry->attributes &= ~att_invisible;  /* Just to be sure */
1683
1684   if (exported_p (entry))
1685     array_needs_making = 1;
1686
1687   return (entry);
1688 }
1689
1690 /* Copy VAR to a new data structure and return that structure. */
1691 SHELL_VAR *
1692 copy_variable (var)
1693      SHELL_VAR *var;
1694 {
1695   SHELL_VAR *copy = (SHELL_VAR *)NULL;
1696
1697   if (var)
1698     {
1699       copy = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1700
1701       copy->attributes = var->attributes;
1702       copy->name = savestring (var->name);
1703
1704       if (function_p (var))
1705         copy->value = (char *)copy_command (function_cell (var));
1706 #if defined (ARRAY_VARS)
1707       else if (array_p (var))
1708         copy->value = (char *)dup_array (array_cell (var));
1709 #endif
1710       else if (value_cell (var))
1711         copy->value = savestring (value_cell (var));
1712       else
1713         copy->value = (char *)NULL;
1714
1715       copy->dynamic_value = var->dynamic_value;
1716       copy->assign_func = var->assign_func;
1717
1718       copy->context = var->context;
1719
1720       /* Don't bother copying previous contexts along with this variable. */
1721       copy->prev_context = (SHELL_VAR *)NULL;
1722     }
1723   return (copy);
1724 }
1725
1726 #define FIND_OR_MAKE_VARIABLE(name, entry) \
1727   do \
1728     { \
1729       entry = find_variable (name); \
1730       if (!entry) \
1731         { \
1732           entry = bind_variable (name, ""); \
1733           if (!no_invisible_vars) entry->attributes |= att_invisible; \
1734         } \
1735     } \
1736   while (0)
1737
1738 /* Make the variable associated with NAME be readonly.
1739    If NAME does not exist yet, create it. */
1740 void
1741 set_var_read_only (name)
1742      char *name;
1743 {
1744   SHELL_VAR *entry;
1745
1746   FIND_OR_MAKE_VARIABLE (name, entry);
1747   entry->attributes |= att_readonly;
1748 }
1749
1750 /* Make the function associated with NAME be readonly.
1751    If NAME does not exist, we just punt, like auto_export code below. */
1752 void
1753 set_func_read_only (name)
1754      char *name;
1755 {
1756   SHELL_VAR *entry = find_function (name);
1757
1758   if (entry)
1759     entry->attributes |= att_readonly;
1760 }
1761
1762 /* Make the variable associated with NAME be auto-exported.
1763    If NAME does not exist yet, create it. */
1764 void
1765 set_var_auto_export (name)
1766      char *name;
1767 {
1768   SHELL_VAR *entry;
1769
1770   FIND_OR_MAKE_VARIABLE (name, entry);
1771   set_auto_export (entry);
1772 }
1773
1774 /* Make the function associated with NAME be auto-exported. */
1775 void
1776 set_func_auto_export (name)
1777      char *name;
1778 {
1779   SHELL_VAR *entry;
1780
1781   entry = find_function (name);
1782   if (entry)
1783     set_auto_export (entry);
1784 }
1785
1786 #if defined (ARRAY_VARS)
1787 /* This function assumes s[i] == '['; returns with s[ret] == ']' if
1788    an array subscript is correctly parsed. */
1789 int
1790 skipsubscript (s, i)
1791      char *s;
1792      int i;
1793 {
1794   int count, c;
1795
1796   for (count = 1; count && (c = s[++i]); )
1797     {
1798       if (c == '[')
1799         count++;
1800       else if (c == ']')
1801         count--;
1802     }
1803   return i;
1804 }
1805 #endif /* ARRAY_VARS */
1806
1807 /* Returns non-zero if STRING is an assignment statement.  The returned value
1808    is the index of the `=' sign. */
1809 int
1810 assignment (string)
1811      char *string;
1812 {
1813   register int c, newi, indx;
1814
1815   c = string[indx = 0];
1816
1817   if (legal_variable_starter (c) == 0)
1818     return (0);
1819
1820   while (c = string[indx])
1821     {
1822       /* The following is safe.  Note that '=' at the start of a word
1823          is not an assignment statement. */
1824       if (c == '=')
1825         return (indx);
1826
1827 #if defined (ARRAY_VARS)
1828       if (c == '[')
1829         {
1830           newi = skipsubscript (string, indx);
1831           if (string[newi++] != ']')
1832             return (0);
1833           return ((string[newi] == '=') ? newi : 0);
1834         }
1835 #endif /* ARRAY_VARS */
1836
1837       /* Variable names in assignment statements may contain only letters,
1838          digits, and `_'. */
1839       if (legal_variable_char (c) == 0)
1840         return (0);
1841
1842       indx++;
1843     }
1844   return (0);
1845 }
1846
1847 static int
1848 visible_var (var)
1849      SHELL_VAR *var;
1850 {
1851   return (invisible_p (var) == 0);
1852 }
1853
1854 static SHELL_VAR **
1855 _visible_names (table)
1856      HASH_TABLE *table;
1857 {
1858   SHELL_VAR **list;
1859
1860   list = map_over (visible_var, table);
1861
1862   if (list && posixly_correct)
1863     sort_variables (list);
1864
1865   return (list);
1866 }
1867
1868 SHELL_VAR **
1869 all_visible_variables ()
1870 {
1871   return (_visible_names (shell_variables));
1872 }
1873
1874 SHELL_VAR **
1875 all_visible_functions ()
1876 {
1877   return (_visible_names (shell_functions));
1878 }
1879
1880 /* Return non-zero if the variable VAR is visible and exported.  Array
1881    variables cannot be exported. */
1882 static int
1883 visible_and_exported (var)
1884      SHELL_VAR *var;
1885 {
1886   return (invisible_p (var) == 0 && exported_p (var));
1887 }
1888
1889 /* Make an array of assignment statements from the hash table
1890    HASHED_VARS which contains SHELL_VARs.  Only visible, exported
1891    variables are eligible. */
1892 char **
1893 make_var_array (hashed_vars)
1894      HASH_TABLE *hashed_vars;
1895 {
1896   register int i, list_index;
1897   register SHELL_VAR *var;
1898   char **list, *value;
1899   SHELL_VAR **vars;
1900
1901   list = (char **)NULL;
1902   vars = map_over (visible_and_exported, hashed_vars);
1903
1904   if (!vars)
1905     return (char **)NULL;
1906
1907   list = (char **)xmalloc ((1 + array_len ((char **)vars)) * sizeof (char *));
1908
1909   for (i = 0, list_index = 0; var = vars[i]; i++)
1910     {
1911       if (function_p (var))
1912         value = named_function_string ((char *)NULL, function_cell (var), 0);
1913 #if defined (ARRAY_VARS)
1914       else if (array_p (var))
1915 #  if 0
1916         value = array_to_assignment_string (array_cell (var));
1917 #  else
1918         continue;       /* XXX array vars cannot yet be exported */
1919 #  endif
1920 #endif
1921       else
1922         value = value_cell (var);
1923
1924       if (value)
1925         {
1926           int name_len, value_len;
1927           char  *p;
1928
1929           name_len = strlen (var->name);
1930           value_len = strlen (value);
1931           p = list[list_index] = xmalloc (2 + name_len + value_len);
1932           strcpy (p, var->name);
1933           p[name_len] = '=';
1934           strcpy (p + name_len + 1, value);
1935           list_index++;
1936 #if defined (ARRAY_VARS)
1937           if (array_p (var))
1938             free (value);
1939 #endif
1940         }
1941     }
1942
1943   free (vars);
1944   list[list_index] = (char *)NULL;
1945   return (list);
1946 }
1947
1948 /* Add STRING to the array of foo=bar strings that we already
1949    have to add to the environment.  */
1950 int
1951 assign_in_env (string)
1952      char *string;
1953 {
1954   int size, offset;
1955   char *name, *temp, *value;
1956   int nlen, vlen;
1957   WORD_LIST *list;
1958   SHELL_VAR *var;
1959
1960   offset = assignment (string);
1961   name = savestring (string);
1962   value = (char *)NULL;
1963
1964 #define freetemp nlen
1965   if (name[offset] == '=')
1966     {
1967       name[offset] = 0;
1968
1969       var = find_variable (name);
1970       if (var && readonly_p (var))
1971         {
1972           report_error ("%s: readonly variable", name);
1973           return (0);
1974         }
1975       temp = name + offset + 1;
1976       freetemp = strchr (temp, '~') != 0;
1977       if (freetemp)
1978         temp = bash_tilde_expand (temp);
1979
1980       list = expand_string_unsplit (temp, 0);
1981       value = string_list (list);
1982
1983       if (list)
1984         dispose_words (list);
1985
1986       if (freetemp)
1987         free (temp);
1988     }
1989 #undef freetemp
1990
1991   nlen = strlen (name);
1992   vlen = value ? strlen (value) : 0;
1993   temp = xmalloc (2 + nlen + vlen);
1994   strcpy (temp, name);
1995   temp[nlen] = '=';
1996   temp[nlen + 1] = '\0';
1997   if (value)
1998     {
1999       if (*value)
2000         strcpy (temp + nlen + 1, value);
2001       free (value);
2002     }
2003   free (name);
2004
2005   if (temporary_env == 0)
2006     {
2007       temporary_env = (char **)xmalloc (sizeof (char *));
2008       temporary_env [0] = (char *)NULL;
2009     }
2010
2011   size = array_len (temporary_env);
2012   temporary_env = (char **)
2013     xrealloc (temporary_env, (size + 2) * (sizeof (char *)));
2014
2015   temporary_env[size] = temp;
2016   temporary_env[size + 1] = (char *)NULL;
2017   array_needs_making = 1;
2018
2019   if (echo_command_at_execute)
2020     {
2021       /* The Korn shell prints the `+ ' in front of assignment statements,
2022          so we do too. */
2023       fprintf (stderr, "%s%s\n", indirection_level_string (), temp);
2024       fflush (stderr);
2025     }
2026
2027   return 1;
2028 }
2029
2030 /* Search for NAME in ARRAY, an array of strings in the same format as the
2031    environment array (i.e, name=value).  If NAME is present, make a new
2032    variable and return it.  Otherwise, return NULL. */
2033 static SHELL_VAR *
2034 find_name_in_env_array (name, array)
2035      char *name;
2036      char **array;
2037 {
2038   register int i, l;
2039
2040   if (array == 0)
2041     return ((SHELL_VAR *)NULL);
2042
2043   for (i = 0, l = strlen (name); array[i]; i++)
2044     {
2045       if (STREQN (array[i], name, l) && array[i][l] == '=')
2046         {
2047           SHELL_VAR *temp;
2048           char *w;
2049
2050           temp = new_shell_variable (name);
2051           w = array[i] + l + 1;
2052
2053           temp->value = *w ? savestring (w) : (char *)NULL;
2054
2055           temp->attributes = att_exported;
2056           temp->context = 0;
2057           temp->prev_context = (SHELL_VAR *)NULL;
2058
2059           temp->dynamic_value = temp->assign_func = (DYNAMIC_FUNC *)NULL;
2060
2061           return (temp);
2062         }
2063     }
2064   return ((SHELL_VAR *)NULL);
2065 }
2066
2067 /* Find a variable in the temporary environment that is named NAME.
2068    The temporary environment can be either the environment provided
2069    to a simple command, or the environment provided to a shell function.
2070    We only search the function environment if we are currently executing
2071    a shell function body (variable_context > 0).  Return a consed variable,
2072    or NULL if not found. */
2073 SHELL_VAR *
2074 find_tempenv_variable (name)
2075      char *name;
2076 {
2077   SHELL_VAR *var = (SHELL_VAR *)NULL;
2078
2079   if (temporary_env)
2080     var = find_name_in_env_array (name, temporary_env);
2081
2082   /* We don't check this_shell_builtin because the command that needs the
2083      value from builtin_env may be a disk command run inside a script run
2084      with `.' and a temporary env. */
2085   if (!var && builtin_env)
2086     var = find_name_in_env_array (name, builtin_env);
2087
2088   if (!var && variable_context && function_env)
2089     var = find_name_in_env_array (name, function_env);
2090
2091   return (var);
2092 }
2093
2094 /* Free the storage allocated to the string array pointed to by ARRAYP, and
2095    make that variable have a null pointer as a value. */
2096 static void
2097 dispose_temporary_vars (arrayp)
2098      char ***arrayp;
2099 {
2100   if (!*arrayp)
2101     return;
2102
2103   free_array (*arrayp);
2104   *arrayp = (char **)NULL;
2105   array_needs_making = 1;
2106 }
2107
2108 /* Free the storage used in the variable array for temporary
2109    environment variables. */
2110 void
2111 dispose_used_env_vars ()
2112 {
2113   dispose_temporary_vars (&temporary_env);
2114 }
2115
2116 /* Free the storage used for temporary environment variables given to
2117    commands when executing inside of a function body. */
2118 void
2119 dispose_function_env ()
2120 {
2121   dispose_temporary_vars (&function_env);
2122 }
2123
2124 /* Free the storage used for temporary environment variables given to
2125    commands when executing a builtin command such as "source". */
2126 void
2127 dispose_builtin_env ()
2128 {
2129   dispose_temporary_vars (&builtin_env);
2130 }
2131
2132 /* Take all of the shell variables in ENV_ARRAY and make shell variables
2133    from them at the current variable context. */
2134 static void
2135 merge_env_array (env_array)
2136      char **env_array;
2137 {
2138   register int i, l;
2139   SHELL_VAR *temp;
2140   char *w, *name;
2141
2142   if (env_array == 0)
2143     return;
2144
2145   for (i = 0; env_array[i]; i++)
2146     {
2147       l = assignment (env_array[i]);
2148       name = env_array[i];
2149       w = env_array[i] + l + 1;
2150       name[l] = '\0';
2151       temp = bind_variable (name, w);
2152       name[l] = '=';
2153     }
2154 }
2155
2156 void
2157 merge_temporary_env ()
2158 {
2159   merge_env_array (temporary_env);
2160 }
2161
2162 void
2163 merge_builtin_env ()
2164 {
2165   merge_env_array (builtin_env);
2166 }
2167
2168 #define ISFUNC(s, o) ((s[o + 1] == '(')  && (s[o + 2] == ')'))
2169
2170 /* Add ASSIGN to ARRAY, or supercede a previous assignment in the
2171    array with the same left-hand side.  Return the new array. */
2172 char **
2173 add_or_supercede (assign, array)
2174      char *assign;
2175      register char **array;
2176 {
2177   register int i;
2178   int equal_offset = assignment (assign);
2179
2180   if (!equal_offset)
2181     return (array);
2182
2183   /* If this is a function, then only supercede the function definition.
2184      We do this by including the `=(' in the comparison.  */
2185   if (assign[equal_offset + 1] == '(')
2186     equal_offset++;
2187
2188   for (i = 0; array && array[i]; i++)
2189     {
2190       if (STREQN (assign, array[i], equal_offset + 1))
2191         {
2192           free (array[i]);
2193           array[i] = savestring (assign);
2194           return (array);
2195         }
2196     }
2197   array = (char **)xrealloc (array, ((2 + i) * sizeof (char *)));
2198   array[i++] = savestring (assign);
2199   array[i] = (char *)NULL;
2200   return (array);
2201 }
2202
2203 /* Make the environment array for the command about to be executed.  If the
2204    array needs making.  Otherwise, do nothing.  If a shell action could
2205    change the array that commands receive for their environment, then the
2206    code should `array_needs_making++'. */
2207 void
2208 maybe_make_export_env ()
2209 {
2210   register int i;
2211   register char **temp_array;
2212
2213   if (array_needs_making)
2214     {
2215       if (export_env)
2216         free_array (export_env);
2217
2218       export_env = (char **)xmalloc (sizeof (char *));
2219       export_env[0] = (char *)NULL;
2220
2221       temp_array = make_var_array (shell_variables);
2222       for (i = 0; temp_array && temp_array[i]; i++)
2223         export_env = add_or_supercede (temp_array[i], export_env);
2224       free_array (temp_array);
2225
2226       temp_array = make_var_array (shell_functions);
2227       for (i = 0; temp_array && temp_array[i]; i++)
2228         export_env = add_or_supercede (temp_array[i], export_env);
2229       free_array (temp_array);
2230
2231       if (function_env)
2232         for (i = 0; function_env[i]; i++)
2233           export_env = add_or_supercede (function_env[i], export_env);
2234
2235       if (temporary_env)
2236         for (i = 0; temporary_env[i]; i++)
2237           export_env = add_or_supercede (temporary_env[i], export_env);
2238
2239 #if 0
2240       /* If we changed the array, then sort it alphabetically. */
2241       if (posixly_correct == 0 && (temporary_env || function_env))
2242         sort_char_array (export_env);
2243 #endif
2244
2245       array_needs_making = 0;
2246     }
2247 }
2248
2249 /* We always put _ in the environment as the name of this command. */
2250 void
2251 put_command_name_into_env (command_name)
2252      char *command_name;
2253 {
2254   char *dummy;
2255
2256   dummy = xmalloc (4 + strlen (command_name));
2257
2258   /* These three statements replace a call to sprintf */
2259   dummy[0] = '_';
2260   dummy[1] = '=';
2261   strcpy (dummy + 2, command_name);
2262   export_env = add_or_supercede (dummy, export_env);
2263   free (dummy);
2264 }
2265
2266 void
2267 put_gnu_argv_flags_into_env (pid, flags_string)
2268      int pid;
2269      char *flags_string;
2270 {
2271   char *dummy, *pbuf;
2272   int l, fl;
2273
2274   pbuf = itos (pid);
2275   l = strlen (pbuf);
2276
2277   fl = strlen (flags_string);
2278
2279   dummy = xmalloc (l + fl + 30);
2280   dummy[0] = '_';
2281   strcpy (dummy + 1, pbuf);
2282   strcpy (dummy + 1 + l, "_GNU_nonoption_argv_flags_");
2283   dummy[l + 27] = '=';
2284   strcpy (dummy + l + 28, flags_string);
2285
2286   free (pbuf);
2287
2288   export_env = add_or_supercede (dummy, export_env);
2289   free (dummy);
2290 }
2291
2292 /* Return a string denoting what our indirection level is. */
2293 static char indirection_string[100];
2294
2295 char *
2296 indirection_level_string ()
2297 {
2298   register int i, j;
2299   char *ps4;
2300
2301   indirection_string[0] = '\0';
2302   ps4 = get_string_value ("PS4");
2303
2304   if (ps4 == 0 || *ps4 == '\0')
2305     return (indirection_string);
2306
2307   ps4 = decode_prompt_string (ps4);
2308
2309   for (i = 0; *ps4 && i < indirection_level && i < 99; i++)
2310     indirection_string[i] = *ps4;
2311
2312   for (j = 1; *ps4 && ps4[j] && i < 99; i++, j++)
2313     indirection_string[i] = ps4[j];
2314
2315   indirection_string[i] = '\0';
2316   free (ps4);
2317   return (indirection_string);
2318 }