Remove Unixware and openserver support
[oweals/cde.git] / cde / programs / dtksh / ksh93 / src / cmd / ksh93 / sh / init.c
1 /*
2  * CDE - Common Desktop Environment
3  *
4  * Copyright (c) 1993-2012, The Open Group. All rights reserved.
5  *
6  * These libraries and programs are free software; you can
7  * redistribute them and/or modify them under the terms of the GNU
8  * Lesser General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option)
10  * any later version.
11  *
12  * These libraries and programs are distributed in the hope that
13  * they will be useful, but WITHOUT ANY WARRANTY; without even the
14  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with these libraries and programs; if not, write
20  * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21  * Floor, Boston, MA 02110-1301 USA
22  */
23 /* $XConsortium: init.c /main/4 1995/11/17 15:16:52 rswiston $ */
24 /***************************************************************
25 *                                                              *
26 *                      AT&T - PROPRIETARY                      *
27 *                                                              *
28 *        THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF        *
29 *                    AT&T BELL LABORATORIES                    *
30 *         AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN         *
31 *            ACCORDANCE WITH APPLICABLE AGREEMENTS             *
32 *                                                              *
33 *                Copyright (c) 1995 AT&T Corp.                 *
34 *              Unpublished & Not for Publication               *
35 *                     All Rights Reserved                      *
36 *                                                              *
37 *       The copyright notice above does not evidence any       *
38 *      actual or intended publication of such source code      *
39 *                                                              *
40 *               This software was created by the               *
41 *           Advanced Software Technology Department            *
42 *                    AT&T Bell Laboratories                    *
43 *                                                              *
44 *               For further information contact                *
45 *                    {research,attmail}!dgk                    *
46 *                                                              *
47 ***************************************************************/
48
49 /* : : generated by proto : : */
50
51 #if !defined(__PROTO__)
52 #if defined(__STDC__) || defined(__cplusplus) || defined(_proto) || defined(c_plusplus)
53 #if defined(__cplusplus)
54 #define __MANGLE__      "C"
55 #else
56 #define __MANGLE__
57 #endif
58 #define __STDARG__
59 #define __PROTO__(x)    x
60 #define __OTORP__(x)
61 #define __PARAM__(n,o)  n
62 #if !defined(__STDC__) && !defined(__cplusplus)
63 #if !defined(c_plusplus)
64 #define const
65 #endif
66 #define signed
67 #define void            int
68 #define volatile
69 #define __V_            char
70 #else
71 #define __V_            void
72 #endif
73 #else
74 #define __PROTO__(x)    ()
75 #define __OTORP__(x)    x
76 #define __PARAM__(n,o)  o
77 #define __MANGLE__
78 #define __V_            char
79 #define const
80 #define signed
81 #define void            int
82 #define volatile
83 #endif
84 #if defined(__cplusplus) || defined(c_plusplus)
85 #define __VARARG__      ...
86 #else
87 #define __VARARG__
88 #endif
89 #if defined(__STDARG__)
90 #define __VA_START__(p,a)       va_start(p,a)
91 #else
92 #define __VA_START__(p,a)       va_start(p)
93 #endif
94 #endif
95 #include        "defs.h"
96 #include        <stak.h>
97 #include        <ctype.h>
98 #include        "variables.h"
99 #include        "path.h"
100 #include        "fault.h"
101 #include        "name.h"
102 #include        "jobs.h"
103 #include        "io.h"
104 #include        "FEATURE/time"
105 #include        "FEATURE/dynamic"
106 #include        "lexstates.h"
107 #include        "FEATURE/locale"
108 #include        "national.h"
109
110 #if _hdr_wchar && _lib_wctype && _lib_iswctype
111 /* on linux wchar.h can include FILE without stdio.h which clashes with sfio_t */
112 #if defined(linux)
113  #ifndef __FILE_defined
114   #define __FILE_defined 1
115  #endif
116 #endif
117 #   include <wchar.h>
118 #   undef  isalpha
119 #   define isalpha(x)      iswalpha(x)
120 #   undef  isblank
121 #   define isblank(x)      iswblank(x)
122 #   if !_lib_iswblank
123
124         static int
125         iswblank __PARAM__((wint_t wc), (wc)) __OTORP__(wint_t wc;){
126                 static int      initialized;
127                 static wctype_t wt;
128
129                 if (!initialized)
130                 {
131                         initialized = 1;
132                         wt = wctype("blank");
133                 }
134                 return(iswctype(wc, wt));
135         }
136 #   endif
137 #else
138 #   undef  _lib_wctype
139 #   ifndef isblank
140 #       define isblank(x)      ((x)==' '||(x)=='\t')
141 #   endif
142 #endif
143
144 #ifdef _hdr_locale
145 #   include     <locale.h>
146 #   ifndef LC_MESSAGES
147 #       define LC_MESSAGES      LC_ALL
148 #   endif /* LC_MESSAGES */
149 #endif /* _hdr_locale */
150
151 #define RANDMASK        0x7fff
152 #ifndef CLK_TCK
153 #   define CLK_TCK      60
154 #endif /* CLK_TCK */
155
156 extern __MANGLE__ char  **environ;
157 #ifdef MTRACE
158     extern __MANGLE__ int Mt_certify;
159 #endif /* MTRACE */
160
161 static void             env_init __PROTO__((void));
162 static void             nv_init __PROTO__((void));
163 static Hashtab_t        *inittree __PROTO__((const struct shtable2*));
164
165 static const char       rsh_pattern[] = "@(rk|kr|r)sh";
166 static int              rand_shift;
167 static Namval_t         *ifsnp;
168
169
170 /*
171  * Invalidate all path name bindings
172  */
173 static void rehash __PARAM__((register Namval_t *np), (np)) __OTORP__(register Namval_t *np;){
174         nv_onattr(np,NV_NOALIAS);
175 }
176
177 /*
178  * out of memory routine for stak routines
179  */
180 static char *nospace __PARAM__((int unused), (unused)) __OTORP__(int unused;){
181         NOT_USED(unused);
182         error(ERROR_exit(3),e_nospace);
183         return(NIL(char*));
184 }
185
186 #ifdef SHOPT_MULTIBYTE
187 #   include     "edit.h"
188     /* Trap for CSWIDTH variable */
189     static void put_cswidth __PARAM__((Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t* np;const char *val;int flags;Namfun_t *fp;){
190         register char *cp;
191         register char *name = nv_name(np);
192         if(ed_setwidth(val?val:"") && !(flags&NV_IMPORT))
193                 error(ERROR_exit(1),e_format,nv_name(np));
194         nv_putv(np, val, flags, fp);
195     }
196 #endif /* SHOPT_MULTIBYTE */
197
198 /* Trap for VISUAL and EDITOR variables */
199 static void put_ed __PARAM__((register Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(register Namval_t* np;const char *val;int flags;Namfun_t *fp;){
200         register const char *cp, *name=nv_name(np);
201         if(*name=='E' && nv_getval(nv_scoped(VISINOD)))
202                 goto done;
203         sh_offoption(SH_VI|SH_EMACS|SH_GMACS);
204         if(!(cp=val) && (*name=='E' || !(cp=nv_getval(nv_scoped(EDITNOD)))))
205                 goto done;
206         /* turn on vi or emacs option if editor name is either*/
207         cp = path_basename(cp);
208         if(strmatch(cp,"*vi"))
209                 sh_onoption(SH_VI);
210         if(strmatch(cp,"*macs"))
211         {
212                 if(*cp=='g')
213                         sh_onoption(SH_GMACS);
214                 else
215                         sh_onoption(SH_EMACS);
216         }
217 done:
218         nv_putv(np, val, flags, fp);
219 }
220
221 /* Trap for OPTINDEX */
222 static void put_optindex __PARAM__((Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t* np;const char *val;int flags;Namfun_t *fp;){
223         sh.st.opterror = sh.st.optchar = 0;
224         nv_putv(np, val, flags, fp);
225 }
226
227 /* Trap for restricted variables PATH, SHELL, ENV */
228 static void put_restricted __PARAM__((register Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(register Namval_t* np;const char *val;int flags;Namfun_t *fp;){
229         if(!(flags&NV_RDONLY) && sh_isoption(SH_RESTRICTED))
230                 error(ERROR_exit(1),e_restricted,nv_name(np));
231         if(nv_name(np)==nv_name(PATHNOD))                       
232         {
233                 sh.lastpath = 0;
234                 nv_scan(sh.track_tree,rehash,NV_TAGGED,NV_TAGGED);
235         }
236         nv_putv(np, val, flags, fp);
237 }
238
239 #ifdef apollo
240     /* Trap for SYSTYPE variable */
241     static void put_systype __PARAM__((Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t* np;const char *val;int flags;Namfun_t *fp;){
242         sh.lastpath = 0;
243         nv_scan(sh.track_tree,rehash,NV_TAGGED,NV_TAGGED);
244         nv_putv(np, val, flags, fp);
245     }
246 #endif
247
248 #ifdef _hdr_locale
249
250 /*
251  * The following struct is based on an alphanumerically sorted list of
252  * all ksh-generated messages which might be displayed, and
253  * must be looked up in a message catalog.  The point of this is to 
254  * translate from the AT&T/UI style of string-based message indexing
255  * to the X/OPEN style of message number lookup.  The following struct
256  * allows us to do a binary search on the strings to find the associated
257  * set number and message ID.  While we could have used the string index 
258  * as the message number, that would cause headaches if/when we
259  * need to add more messages, as all following messages would have to
260  * be renumbered.
261  */
262 typedef struct {
263         char *string;
264         int setNum;
265         int msgNum;
266 } MsgStr, *MsgPtr;
267
268 static MsgStr allmsgs[] = {
269         {" Done", 25, 1},
270         {" Running", 25, 3},
271         {" [-n] [arg...]", 25, 4},
272         {" [arg...]", 25, 5},
273         {" [dir] [list]", 25, 6},
274         {" [job...]", 25, 7},
275         {" [n]", 25, 8},
276         {" [name [pathname] ]", 25, 9},
277         {" [name]", 25, 10},
278         {" [top] [base]", 25, 11},
279         {" expr...", 25, 12},
280         {" format [arg...]", 25, 13},
281         {" is a function", 25, 14},
282         {" is a keyword", 25, 15},
283         {" is a shell builtin", 25, 16},
284         {" is an exported function", 25, 17},
285         {" is an undefined function", 25, 18},
286         {" name [arg...]", 25, 19},
287         {":a:[name] optstring name [args...]", 25, 20},
288         {" seconds", 25, 21},
289         {"${HOME:-.}/.profile", 25, 23},
290         {"%c: invalid character in expression - %s", 25, 24},
291         {"%c: unknown format specifier", 25, 25},
292         {"%d-%d: invalid range", 25, 26},
293         {"%d: invalid binary script version", 25, 27},
294         {"%s is an alias for ", 25, 28},
295         {"%s is an exported alias for ", 25, 29},
296         {"%s missing", 25, 30},
297         {"%s unknown base", 25, 31},
298         {"%s: ':' expected for '?' operator", 25, 32},
299         {"%s: Ambiguous", 25, 33},
300         {"%s: Arguments must be %job or process ids", 25, 34},
301         {"%s: alias not found\n", 25, 35},
302         {"%s: arithmetic syntax error", 25, 36},
303         {"%s: assignment requires lvalue", 25, 37},
304         {"%s: bad file unit number", 25, 38},
305         {"%s: bad format", 25, 39},
306         {"%s: bad number", 25, 40},
307         {"%s: bad option(s)", 25, 41},
308         {"%s: bad substitution", 25, 42},
309         {"%s: bad trap", 25, 43},
310         {"%s: cannot create", 25, 44},
311         {"%s: cannot execute", 25, 45},
312         {"%s: cannot open", 25, 46},
313         {"%s: divide by zero", 25, 47},
314         {"%s: domain exception", 25, 48},
315         {"%s: fails %s", 25, 49},
316         {"%s: file already exists", 25, 50},
317         {"%s: illegal function name", 25, 51},
318         {"%s: invalid alias name", 25, 52},
319         {"%s: invalid discipline function", 25, 53},
320         {"%s: invalid export name", 25, 54},
321         {"%s: invalid function name", 25, 55},
322         {"%s: invalid name", 25, 56},
323         {"%s: invalid regular expression", 25, 57},
324         {"%s: invalid self reference", 25, 58},
325         {"%s: invalid use of :", 25, 59},
326         {"%s: invalid variable name", 25, 60},
327         {"%s: is not an identifier", 25, 61},
328         {"%s: is read only", 25, 62},
329         {"%s: label not implemented", 25, 63},
330         {"%s: limit exceeded", 25, 64},
331         {"%s: more tokens expected", 25, 65},
332         {"%s: no parent", 25, 66},
333         {"%s: no reference name", 25, 67},
334         {"%s: not found", 25, 68},
335         {"%s: not implemented", 25, 69},
336         {"%s: operands have incompatible types", 25, 70},
337         {"%s: overflow exception", 25, 71},
338         {"%s: parameter not set", 25, 72},
339         {"%s: parameter null or not set", 25, 73},
340         {"%s: recursion too deep", 25, 74},
341         {"%s: reference variable cannot be an array", 25, 75},
342         {"%s: requires pathname argument", 25, 76},
343         {"%s: restricted", 25, 77},
344         {"%s: singularity exception", 25, 78},
345         {"%s: subscript out of range", 25, 79},
346         {"%s: unbalanced parenthesis", 25, 80},
347         {"%s: unknown function", 25, 81},
348         {"%s: unknown locale", 25, 82},
349         {"%s: unknown operator", 25, 83},
350         {"%s: unknown signal name", 25, 84},
351         {"%s: would cause loop", 25, 85},
352         {"(coredump)", 25, 86},
353         {"-c requires argument", 25, 87},
354         {"-e - requires single argument", 25, 88},
355         {"/vpix", 25, 89},
356         {"<command unknown>", 25, 90},
357         {"AC:E#?F#?H:[name]L#?R#?Z#?fi#?[base]lnprtux [name=[value]...]", 25, 91},
358         {"AE#?F#?HL#?R#?Z#?fi#?[base]lnprtux [name=[value]...]", 25, 92},
359         {"Abort", 25, 93},
360         {"Ad:[delim]prst#[timeout]u#[filenum] [name...]", 25, 94},
361         {"Alarm call", 25, 95},
362         {"Bad root node specification", 25, 96},
363         {"Bad system call", 25, 97},
364         {"Broken Pipe", 25, 98},
365         {"Bus error", 25, 99},
366         {"Cannot start job control", 25, 100},
367         {"Current option settings", 25, 101},
368         {"DIL signal", 25, 102},
369         {"Death of Child", 25, 103},
370         {"DircabefhkmnpstuvxCR:[file]o:?[option] [arg...]", 25, 104},
371         {"DircabefhkmnpstuvxCo:?[option] [arg...]", 25, 105},
372         {"EMT trap", 25, 106},
373         {"Exceeded CPU time limit", 25, 107},
374         {"Exceeded file size limit", 25, 108},
375         {"Floating exception", 25, 109},
376         {"HSacdfmnstv [limit]", 25, 110},
377         {"Hangup", 25, 111},
378         {"IO signal", 25, 112},
379         {"Illegal instruction", 25, 113},
380         {"Interrupt", 25, 114},
381         {"Killed", 25, 115},
382         {"LP [dir] [change]", 25, 116},
383         {"Memory fault", 25, 117},
384         {"Migrate process", 25, 118},
385         {"No job control", 25, 119},
386         {"Phone interrupt", 25, 120},
387         {"Polling alarm", 25, 121},
388         {"Power fail", 25, 122},
389         {"Profiling time alarm", 25, 123},
390         {"Quit", 25, 124},
391         {"Resources lost", 25, 125},
392         {"Reverting to old tty driver...", 25, 126},
393         {"S [mask]", 25, 127},
394         {"SIGAPOLLO", 25, 128},
395         {"Security label changed", 25, 129},
396         {"Socket interrupt", 25, 130},
397         {"Sound completed", 25, 131},
398         {"Stopped (signal)", 25, 132},
399         {"Stopped (tty input)", 25, 133},
400         {"Stopped process continued", 25, 134},
401         {"Stopped", 25, 135},
402         {"Stopped(tty output)", 25, 136},
403         {"Switching to new tty driver...", 25, 137},
404         {"System crash soon", 25, 138},
405         {"Terminated", 25, 139},
406         {"Trace/BPT trap", 25, 140},
407         {"Unrecognized version", 25, 141},
408         {"Use 'exit' to terminate this shell", 25, 142},
409         {"User signal 1", 25, 143},
410         {"User signal 2", 25, 144},
411         {"Version not defined", 25, 145},
412         {"Virtual time alarm", 25, 146},
413         {"Window size change", 25, 147},
414         {"You have running jobs", 25, 148},
415         {"You have stopped jobs", 25, 149},
416         {"[_[:alpha:]]*([_[:alnum:]])", 25, 150},
417         {"\n@(#)Version 12/28/93\0\n", 25, 151},
418         {"\n@(#)Version M-12/28/93\0\n", 25, 152},
419         {"\nreal", 25, 153},
420         {"\r\n\007shell will timeout in 60 seconds due to inactivity", 25, 154},
421         {"a name...", 25, 155},
422         {"a:c [command [args...] ]", 25, 156},
423         {"afpv name...", 25, 157},
424         {"alarm %s %.3f\n", 25, 158},
425         {"alarm -r %s +%.3g\n", 25, 159},
426         {"argument expected", 25, 160},
427         {"bad directory", 25, 161},
428         {"bad file unit number", 25, 162},
429         {"bad substitution", 25, 163},
430         {"cannot access parent directories", 25, 164},
431         {"cannot create pipe", 25, 165},
432         {"cannot create tempory file", 25, 166},
433         {"cannot fork", 25, 167},
434         {"cannot get %s", 25, 168},
435         {"cannot set %s", 25, 169},
436         {"cannot set alarm", 25, 170},
437         {"condition(s) required", 25, 171},
438         {"dsf:[library] [name...]", 25, 172},
439         {"e:[editor]lnrsN# [first] [last]", 25, 173},
440         {"end of file", 25, 174},
441         {"f:[format]enprsu:[filenum] [arg...]", 25, 175},
442         {"fnv name...", 25, 176},
443         {"hist -e \"${VISUAL:-${EDITOR:-vi}}\" ", 25, 177},
444         {"history file cannot open", 25, 178},
445         {"incorrect syntax", 25, 179},
446         {"invalid argument of type %c", 25, 180},
447         {"is a shell builtin version of", 25, 181},
448         {"is a tracked alias for", 25, 182},
449         {"kill", 25, 183},
450         {"line %d: $ not preceded by \\", 25, 184},
451         {"line %d: %c within ${} should be quoted", 25, 185},
452         {"line %d: %s unknown label", 25, 186},
453         {"line %d: %s within [[...]] obsolete, use ((...))", 25, 187},
454         {"line %d: '=' obsolete, use '=='", 25, 188},
455         {"line %d: -a obsolete, use -e", 25, 189},
456         {"line %d: \\ in front of %c reserved for future use", 25, 190},
457         {"line %d: `...` obsolete, use $(...)", 25, 191},
458         {"line %d: escape %c to avoid ambiguities", 25, 192},
459         {"line %d: label %s ignored", 25, 193},
460         {"line %d: quote %c to avoid ambiguities", 25, 194},
461         {"line %d: set %s obsolete", 25, 195},
462         {"line %d: spaces required for nested subshell", 25, 196},
463         {"line %d: use braces to avoid ambiguities with $id[...]", 25, 197},
464         {"line %d: use space or tab to separate operators %c and %c", 25, 198},
465         {"ln#[signum]s:[signame] sig...", 25, 199},
466         {"login setuid/setgid shells prohibited", 25, 200},
467         {"mapping", 25, 201},
468         {"newline", 25, 202},
469         {"nlp [job...]", 25, 203},
470         {"no history file", 25, 204},
471         {"no query process", 25, 205},
472         {"no such job", 25, 206},
473         {"no such process", 25, 207},
474         {"not supported", 25, 208},
475         {"off", 25, 209},
476         {"on", 25, 210},
477         {"open file limit exceeded", 25, 211},
478         {"out of memory", 25, 212},
479         {"p [action condition...]", 25, 213},
480         {"p [name[=value]...]", 25, 214},
481         {"parameter not set", 25, 215},
482         {"permission denied", 25, 216},
483         {"process already exists", 25, 217},
484         {"ptx [name=[value]...]", 25, 218},
485         {"pvV name [arg]...", 25, 219},
486         {"r [varname seconds]", 25, 220},
487         {"syntax error at line %d: `%s' %s", 25, 221},
488         {"syntax error at line %d: duplicate label %s", 25, 222},
489         {"syntax error: `%s' %s", 25, 223},
490         {"sys", 25, 224},
491         {"timed out waiting for input", 25, 225},
492         {"unexpected", 25, 226},
493         {"universe not accessible", 25, 227},
494         {"unlimited", 25, 228},
495         {"unmatched", 25, 229},
496         {"user", 25, 230},
497         {"versions", 25, 231},
498         {"write to %d failed", 25, 232},
499         {"you have mail in $_", 25, 233},
500         {"zero byte", 25, 234},
501 };
502 #ifdef __ultrix
503 #define _CLIENT_CAT_NAME "dtksh.cat"
504 #else  /* __ultrix */
505 #define _CLIENT_CAT_NAME "dtksh"
506 #endif /* __ultrix */
507
508 /*
509  * Without this proto, standard C says that _DtGetMessage() returns
510  * an int, even though it really returns a pointer.  The compiler is
511  * then free to use the high 32-bits of the return register for
512  * something else (like scratch), and that can garble the pointer.
513  */
514 char *_DtGetMessage __PROTO__((char *filename, int set, int n, char *s));
515 #define GETMESSAGE(set, number, string)\
516         (_DtGetMessage(_CLIENT_CAT_NAME, set, number, string))
517
518 #include <nl_types.h>
519
520 static int localeChanged = 1;
521
522     void LocaleChanged __PARAM__((Namval_t *np, const char *val, int flags, Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t *np; const char *val; int flags; Namfun_t *fp;)
523 {
524    localeChanged = 1;
525    nv_putv(np, val, flags, fp);
526    setlocale(LC_ALL, "");
527 }
528
529
530 /****************************************************************************
531  *
532  * The following two functions are ugly, but necessary.  Ksh reserves file
533  * descriptors 0 - 9 for use by shell scripts, and has intimate knowledge
534  * of how and when they were opened.  Unfortunately, certain dtksh functions
535  * (XtInitialize, catopen, ttdt_open, _DtActionInvoke, others) open file
536  * descriptors which are not known to ksh.  We can't let these file
537  * descriptors fall in the 0 - 9 range, because we can't afford to have
538  * the shell script overriding our file descriptors.  Therefore, any of
539  * our commands which open files must first lock our file descriptors 0 - 9,
540  * thus forcing the command to get a file descriptor out of the shell's
541  * range.  After the command has opened its file descriptor, it then needs
542  * to unlock file descriptors 0 - 9, so that the shell script will have
543  * access to them again.
544  *
545  **************************************************************************/
546
547
548 /*
549  * Return a list of the file descriptors we had to open, to lock out file
550  * descriptors 0 - 9; this list should be freed (and the file descriptors
551  * closed) by calling UnlockkshFileDescriptors().
552  */
553
554     int *LockKshFileDescriptors __PARAM__((void),())
555 {
556    int * fdList;
557    int i;
558    int fd, newfd;
559
560    fdList = (int *)malloc(sizeof(int) * 10);
561    for (i = 0; i < 10; i++)
562       fdList[i] = -1;
563
564    if ((fd = open("/dev/null", O_RDONLY)) >= 0)
565    {
566       if (fd < 10)
567       {
568          fdList[0] = fd;
569          for (i = 1; i < 10; i++)
570          {
571             if ((newfd = dup(fd)) < 10)
572                fdList[i] = newfd;
573             else
574             {
575                close(newfd);
576                break;
577             }
578          }
579       }
580       else
581          close(fd);
582    }
583
584    return(fdList);
585 }
586
587     void UnlockKshFileDescriptors __PARAM__((int *fdList), (fdList)) __OTORP__(int *fdList;)
588 {
589    int i;
590
591    for (i = 0; i < 10; i++)
592    {
593       if (fdList[i] != (-1))
594          close(fdList[i]);
595    }
596
597    free((char *)fdList);
598 }
599
600 /*
601  * This function overrides the traditional libDtSvc version of this function.
602  * Since ksh dynamically changes to match the user's locale, we potentially
603  * need to change our message catalog in the middle of running.
604  */
605 char *savedNlsPath;
606
607     char *_DtGetMessage __PARAM__((char *filename, int set, int n, char *s), (filename, set, n, s)) __OTORP__(char *filename; int set; int n; char *s;)
608 {
609         nl_catd catopen();
610         char *catgets();
611         int catclose();
612
613         static nl_catd nlmsg_fd = (nl_catd)-1;
614         static char *lang = NULL;
615         char *msg;
616         char * newLang;
617         int * lockedFds;
618         int swappedNlsPath = 0;
619         char *pEqual;
620         static char pathBuf[1024] = {(char)'N', (char)'L', (char)'S', (char)'P',
621                                                                 (char)'A', (char)'T', (char)'H', (char)'='};
622
623         if ( localeChanged ) 
624         {
625                 char *oldPath;
626                 localeChanged = 0;
627
628                 newLang = (char *) getenv ("LANG");
629                 if (lang)
630                    free(lang);
631                 if (newLang)
632                    lang = strdup(newLang);
633                 else
634                    lang = NULL;
635
636                 if (nlmsg_fd != (nl_catd)-1)
637                    catclose(nlmsg_fd);
638                 if(strcmp((oldPath = getenv("NLSPATH")), savedNlsPath) != 0)
639                 {
640                         swappedNlsPath = 1;
641                         pEqual = strchr(pathBuf, '=');
642                         strcpy(pEqual + 1, savedNlsPath);
643                         /*
644                          * Only call putenv if pathBuf isn't already holding NLSPATH
645                          * in the environment.
646                          */
647                         if(oldPath != (pEqual + 1))
648                             putenv(pathBuf);
649                 }
650                 lockedFds = LockKshFileDescriptors();
651                 nlmsg_fd = catopen(filename, 0);
652                 UnlockKshFileDescriptors(lockedFds);
653                 if(swappedNlsPath != 0)
654                 {
655                         swappedNlsPath = 0;
656                         pEqual = strchr(pathBuf, '=');
657                         strcpy(pEqual + 1, oldPath);
658                         if(oldPath != (pEqual + 1))
659                             putenv(pathBuf);
660                 }
661         }
662         msg=catgets(nlmsg_fd,set,n,s);
663         return (msg);
664 }
665
666     /*
667      * This function needs to be modified to handle international
668      * error message translations
669      */
670     static char *msg_translate __PARAM__((const char *message,int type), (message, type)) __OTORP__(const char *message;int type;)
671 {
672         int startIndex = 0, endIndex = sizeof(allmsgs)/sizeof(MsgStr) - 1, 
673             midIndex, res, weFoundIt = 0;
674         
675         if(type != 1) /* if it's not a shell message, don't translate */
676             return((char*)message);
677
678         while(startIndex != endIndex)
679         {
680                 midIndex = (startIndex + endIndex) / 2;
681                 if(midIndex == startIndex)
682                 {
683                         if((res = strcmp(allmsgs[startIndex].string, message)) == 0)
684                         {
685                                 weFoundIt = 1;
686                                 midIndex = startIndex;
687                                 break;
688                         }
689                         else if(res < 0)
690                         {
691                                 if((res = strcmp(allmsgs[endIndex].string, message)) == 0)
692                                 {
693                                         weFoundIt = 1;
694                                         midIndex = endIndex;
695                                         break;
696                                 }
697                         }
698                         /* we didn't find a match in the table */
699                         weFoundIt = 0;
700                         break;
701                 }
702                 else
703                 {
704                         if((res = strcmp(allmsgs[midIndex].string, message)) == 0)
705                         {
706                                 weFoundIt = 1;
707                                 break; /* we found it */
708                         }
709                         else if(res < 0)
710                                 startIndex = midIndex;
711                         else
712                                 endIndex = midIndex;
713                 }
714         }
715         if(weFoundIt)
716                 return GETMESSAGE(allmsgs[midIndex].setNum, allmsgs[midIndex].msgNum, (char *)message);
717
718         return((char*)message);
719     }
720
721
722 #   ifdef SHOPT_MULTIBYTE
723         void charsize_init __PARAM__((void), ()){
724                 static char fc[3] = { 0301,  ESS2, ESS3};
725                 char buff[8];
726                 register int i,n;
727                 wchar_t wc;
728                 memset(buff,0301,MB_CUR_MAX);
729                 for(i=0; i<=2; i++)
730                 {
731                         buff[0] = fc[i];
732                         if((n=mbtowc(&wc,buff,MB_CUR_MAX))>0)
733                         {
734                                 if((int_charsize[i+1] = n-(i>0))>0)
735                                         int_charsize[i+5] = wcwidth(wc);
736                                 else
737                                         int_charsize[i+5] = 0;
738                         }
739                 }
740         }
741 #   endif /* SHOPT_MULTIBYTE */
742
743     /* Trap for LC_ALL, LC_TYPE, LC_MESSAGES, LC_COLLATE and LANG */
744     static void put_lang __PARAM__((Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t* np;const char *val;int flags;Namfun_t *fp;){
745         int type;
746         char *lc_all = nv_getval(LCALLNOD);
747         if(nv_name(np)==nv_name(LCTYPENOD))
748                 type = LC_CTYPE;
749         else if(nv_name(np)==nv_name(LCMSGNOD))
750                 type = LC_MESSAGES;
751         else if(nv_name(np)==nv_name(LCCOLLNOD))
752                 type = LC_COLLATE;
753         else if(nv_name(np)==nv_name(LCNUMNOD))
754                 type = LC_NUMERIC;
755         else if(nv_name(np)==nv_name(LANGNOD) && !lc_all)
756                 type= -1;
757         else
758                 type = LC_ALL;
759         if(type>=0 && type!=LC_ALL && !lc_all)
760                 type= -1;
761         if(type>=0)
762         {
763                 if(!setlocale(type,val?val:""))
764                 {
765                         error(0,e_badlocale,val);
766                         return;
767                 }
768         }
769         if(type==LC_ALL || type==LC_CTYPE)
770         {
771                 if(sh_lexstates[ST_BEGIN]!=sh_lexrstates[ST_BEGIN])
772                         free((__V_*)sh_lexstates[ST_BEGIN]);
773                 if(ast.locale.set&LC_SET_CTYPE)
774                 {
775                         register int c;
776                         char *state[4];
777                         sh_lexstates[ST_BEGIN] = state[0] = (char*)malloc(4*(1<<CHAR_BIT));
778                         memcpy(state[0],sh_lexrstates[ST_BEGIN],(1<<CHAR_BIT));
779                         sh_lexstates[ST_NAME] = state[1] = state[0] + (1<<CHAR_BIT);
780                         memcpy(state[1],sh_lexrstates[ST_NAME],(1<<CHAR_BIT));
781                         sh_lexstates[ST_DOL] = state[2] = state[1] + (1<<CHAR_BIT);
782                         memcpy(state[2],sh_lexrstates[ST_DOL],(1<<CHAR_BIT));
783                         sh_lexstates[ST_BRACE] = state[3] = state[2] + (1<<CHAR_BIT);
784                         memcpy(state[3],sh_lexrstates[ST_BRACE],(1<<CHAR_BIT));
785                         for(c=0; c<(1<<CHAR_BIT); c++)
786                         {
787                                 if(isblank(c))
788                                 {
789                                         state[0][c]=0;
790                                         state[1][c]=S_BREAK;
791                                         state[2][c]=S_BREAK;
792                                         continue;
793                                 }
794                                 if(!isalpha(c))
795                                         continue;
796                                 if(state[0][c]==S_REG)
797                                         state[0][c]=S_NAME;
798                                 if(state[1][c]==S_REG)
799                                         state[1][c]=0;
800                                 if(state[2][c]==S_ERR)
801                                         state[2][c]=S_ALP;
802                                 if(state[3][c]==S_ERR)
803                                         state[3][c]=0;
804                         }
805                 }
806                 else
807                 {
808                         sh_lexstates[ST_BEGIN]=(char*)sh_lexrstates[ST_BEGIN];
809                         sh_lexstates[ST_NAME]=(char*)sh_lexrstates[ST_NAME];
810                         sh_lexstates[ST_DOL]=(char*)sh_lexrstates[ST_DOL];
811                         sh_lexstates[ST_BRACE]=(char*)sh_lexrstates[ST_BRACE];
812                 }
813 #ifdef SHOPT_MULTIBYTE
814                 charsize_init();
815 #endif /* SHOPT_MULTIBYTE */
816         }
817         if(type==LC_ALL || type==LC_MESSAGES)
818                 error_info.translate = msg_translate;
819         nv_putv(np, val, flags, fp);
820     }
821 #endif /* _hdr_locale */
822
823 /* Trap for IFS assignment and invalidates state table */
824 static void put_ifs __PARAM__((register Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(register Namval_t* np;const char *val;int flags;Namfun_t *fp;){
825         ifsnp = 0;
826         nv_putv(np, val, flags, fp);
827 }
828
829 /*
830  * This is the lookup function for IFS
831  * It keeps the sh.ifstable up to date
832  */
833 static char* get_ifs __PARAM__((register Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(register Namval_t* np; Namfun_t *fp;){
834         register char *cp, *value;
835         register int c,n;
836         value = nv_getv(np,fp);
837         if(np!=ifsnp)
838         {
839                 ifsnp = np;
840                 memset(sh.ifstable,0,(1<<CHAR_BIT));
841                 if(cp=value)
842                 {
843 #ifdef SHOPT_MULTIBYTE
844                         while(n=mbtowc(0,cp,MB_CUR_MAX),c= *(unsigned char*)cp)
845 #else
846                         while(c= *(unsigned char*)cp++)
847 #endif /* SHOPT_MULTIBYTE */
848                         {
849 #ifdef SHOPT_MULTIBYTE
850                                 cp+=n;
851                                 if(n>1)
852                                 {
853                                         sh.ifstable[c] = S_MBYTE;
854                                         continue;
855                                 }
856 #endif /* SHOPT_MULTIBYTE */
857                                 n = S_DELIM;
858                                 if(c== *cp)
859                                         cp++;
860                                 else if(isspace(c))
861                                         n = S_SPACE;
862                                 sh.ifstable[c] = n;
863                         }
864                 }
865                 else
866                 {
867                         sh.ifstable[' '] = sh.ifstable['\t'] = S_SPACE;
868                         sh.ifstable['\n'] = S_NL;
869                 }
870         }
871         return(value);
872 }
873
874 /*
875  * these functions are used to get and set the SECONDS variable
876  */
877 #ifdef _lib_gettimeofday
878 #   define dtime(tp) ((double)((tp)->tv_sec)+1e-6*((double)((tp)->tv_usec)))
879 #   define tms  timeval
880 #else
881 #   define dtime(tp)    (((double)times(tp))/sh.lim.clk_tck)
882 #   define gettimeofday(a,b)
883 #endif
884
885 static void put_seconds __PARAM__((register Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(register Namval_t* np;const char *val;int flags;Namfun_t *fp;){
886         static double sec_offset;
887         double d;
888         struct tms tp;
889         NOT_USED(fp);
890         if(!val)
891         {
892                 nv_stack(np, NIL(Namfun_t*));
893                 nv_unset(np);
894                 return;
895         }
896         if(flags&NV_INTEGER)
897                 d = *(double*)val;
898         else
899                 d = sh_arith(val);
900         gettimeofday(&tp,NIL(void *));
901         sec_offset = dtime(&tp)-d;
902         if(!np->nvalue.dp)
903         {
904                 nv_setsize(np,3);
905                 np->nvalue.dp = &sec_offset;
906         }
907 }
908
909 static char* get_seconds __PARAM__((register Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(register Namval_t* np; Namfun_t *fp;){
910         struct tms tp;
911         double d;
912         NOT_USED(fp);
913         gettimeofday(&tp,NIL(void *));
914         d = dtime(&tp)- *np->nvalue.dp;
915         return(sh_ftos(d,nv_size(np)));
916 }
917
918 static double nget_seconds __PARAM__((register Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(register Namval_t* np; Namfun_t *fp;){
919         struct tms tp;
920         NOT_USED(fp);
921         gettimeofday(&tp,NIL(void *));
922         return(dtime(&tp)- *np->nvalue.dp);
923 }
924
925 /*
926  * These three functions are used to get and set the RANDOM variable
927  */
928 static void put_rand __PARAM__((register Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(register Namval_t* np;const char *val;int flags;Namfun_t *fp;){
929         static long rand_last;
930         register long n;
931         NOT_USED(fp);
932         if(!val)
933         {
934                 nv_stack(np, NIL(Namfun_t*));
935                 nv_unset(np);
936                 return;
937         }
938         if(flags&NV_INTEGER)
939                 n = *(double*)val;
940         else
941                 n = sh_arith(val);
942         srand((int)(n&RANDMASK));
943         rand_last = -1;
944         if(!np->nvalue.lp)
945                 np->nvalue.lp = &rand_last;
946 }
947
948 /*
949  * get random number in range of 0 - 2**15
950  * never pick same number twice in a row
951  */
952 static double nget_rand __PARAM__((register Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(register Namval_t* np; Namfun_t *fp;){
953         register long cur, last= *np->nvalue.lp;
954         NOT_USED(fp);
955         do
956                 cur = (rand()>>rand_shift)&RANDMASK;
957         while(cur==last);
958         *np->nvalue.lp = cur;
959         return((double)cur);
960 }
961
962 static char* get_rand __PARAM__((register Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(register Namval_t* np; Namfun_t *fp;){
963         register long n = nget_rand(np,fp);
964         return(fmtbase(n, 10, 0));
965 }
966
967 /*
968  * These three routines are for LINENO
969  */
970 static double nget_lineno __PARAM__((Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(Namval_t* np; Namfun_t *fp;){
971         double d=1;
972         if(error_info.line >0)
973                 d = error_info.line;
974         else if(error_info.context && error_info.context->line>0)
975                 d = error_info.context->line;
976         NOT_USED(np);
977         NOT_USED(fp);
978         return(d);
979 }
980
981 static void put_lineno __PARAM__((Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t* np;const char *val;int flags;Namfun_t *fp;){
982         register long n;
983         NOT_USED(fp);
984         if(!val)
985         {
986                 nv_stack(np, NIL(Namfun_t*));
987                 nv_unset(np);
988                 return;
989         }
990         if(flags&NV_INTEGER)
991                 n = *(double*)val;
992         else
993                 n = sh_arith(val);
994         sh.st.firstline += nget_lineno(np,fp)+1-n;
995 }
996
997 static char* get_lineno __PARAM__((register Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(register Namval_t* np; Namfun_t *fp;){
998         register long n = nget_lineno(np,fp);
999         return(fmtbase(n, 10, 0));
1000 }
1001
1002 static char* get_lastarg __PARAM__((Namval_t* np, Namfun_t *fp), (np, fp)) __OTORP__(Namval_t* np; Namfun_t *fp;){
1003         NOT_USED(np);
1004         NOT_USED(fp);
1005         return(sh.lastarg);
1006 }
1007
1008 static void put_lastarg __PARAM__((Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(Namval_t* np;const char *val;int flags;Namfun_t *fp;){
1009         NOT_USED(fp);
1010         if(flags&NV_INTEGER)
1011                 val = sh_etos(*((double*)val),12);
1012         if(sh.lastarg && !nv_isattr(np,NV_NOFREE))
1013                 free((__V_*)sh.lastarg);
1014         else
1015                 nv_offattr(np,NV_NOFREE);
1016         if(val)
1017                 sh.lastarg = strdup(val);
1018         else
1019                 sh.lastarg = 0;
1020 }
1021
1022 #ifdef SHOPT_FS_3D
1023     /*
1024      * set or unset the mappings given a colon separated list of directories
1025      */
1026     static void vpath_set __PARAM__((char *str, int mode), (str, mode)) __OTORP__(char *str; int mode;){
1027         register char *lastp, *oldp=str, *newp=strchr(oldp,':');
1028         if(!sh.lim.fs3d)
1029                 return;
1030         while(newp)
1031         {
1032                 *newp++ = 0;
1033                 if(lastp=strchr(newp,':'))
1034                         *lastp = 0;
1035                 mount((mode?newp:""),oldp,FS3D_VIEW,0);
1036                 newp[-1] = ':';
1037                 oldp = newp;
1038                 newp=lastp;
1039         }
1040     }
1041
1042     /* catch vpath assignments */
1043     static void put_vpath __PARAM__((register Namval_t* np,const char *val,int flags,Namfun_t *fp), (np, val, flags, fp)) __OTORP__(register Namval_t* np;const char *val;int flags;Namfun_t *fp;){
1044         register char *cp;
1045         if(cp = nv_getval(np))
1046                 vpath_set(cp,0);
1047         if(val)
1048                 vpath_set((char*)val,1);
1049         nv_putv(np,val,flags,fp);
1050     }
1051     static const Namdisc_t VPATH_disc   = { 0, put_vpath  };
1052     static Namfun_t VPATH_init  = { &VPATH_disc  };
1053 #endif /* SHOPT_FS_3D */
1054
1055 static const Namdisc_t IFS_disc         = {  0, put_ifs, get_ifs };
1056 static const Namdisc_t RESTRICTED_disc  = {  0, put_restricted };
1057 static const Namdisc_t EDITOR_disc      = {  0, put_ed };
1058 static const Namdisc_t OPTINDEX_disc    = {  0, put_optindex };
1059 static const Namdisc_t SECONDS_disc     = {  0, put_seconds, get_seconds, nget_seconds };
1060 static const Namdisc_t RAND_disc        = {  0, put_rand, get_rand, nget_rand };
1061 static const Namdisc_t LINENO_disc      = {  0, put_lineno, get_lineno, nget_lineno };
1062 static const Namdisc_t L_ARG_disc       = {  0, put_lastarg, get_lastarg };
1063 static Namfun_t IFS_init        = {  &IFS_disc};
1064 static Namfun_t PATH_init       = {  &RESTRICTED_disc};
1065 static Namfun_t SHELL_init      = {  &RESTRICTED_disc};
1066 static Namfun_t ENV_init        = {  &RESTRICTED_disc};
1067 static Namfun_t VISUAL_init     = {  &EDITOR_disc};
1068 static Namfun_t EDITOR_init     = {  &EDITOR_disc};
1069 static Namfun_t OPTINDEX_init   = {  &OPTINDEX_disc};
1070 static Namfun_t SECONDS_init    = {  &SECONDS_disc};
1071 static Namfun_t RAND_init       = {  &RAND_disc};
1072 static Namfun_t LINENO_init     = {  &LINENO_disc};
1073 static Namfun_t L_ARG_init      = {  &L_ARG_disc};
1074 #ifdef _hdr_locale
1075     static const Namdisc_t LC_disc      = {  0, put_lang };
1076     static Namfun_t LC_TYPE_init        = {  &LC_disc};
1077     static Namfun_t LC_NUM_init         = {  &LC_disc};
1078     static Namfun_t LC_COLL_init        = {  &LC_disc};
1079     static Namfun_t LC_MSG_init         = {  &LC_disc};
1080     static Namfun_t LC_ALL_init         = {  &LC_disc};
1081     static Namfun_t LANG_init           = {  &LC_disc};
1082 #endif /* _hdr_locale */
1083 #ifdef apollo
1084     static const Namdisc_t SYSTYPE_disc = {  0, put_systype };
1085     static Namfun_t SYSTYPE_init        = {  &SYSTYPEdisc};
1086 #endif /* apollo */
1087 #ifdef SHOPT_MULTIBYTE
1088     static const Namdisc_t CSWIDTH_disc = {  0, put_cswidth };
1089     static Namfun_t CSWIDTH_init        = {  &CSWIDTH_disc};
1090 #endif /* SHOPT_MULTIBYTE */
1091
1092 /*
1093  * This function will get called whenever a configuration parameter changes
1094  */
1095 static int newconf __PARAM__((const char *name, const char *path, const char *value), (name, path, value)) __OTORP__(const char *name; const char *path; const char *value;){
1096         register char *arg;
1097         if(strcmp(name,"UNIVERSE")==0 && strcmp(astconf(name,0,0),value))
1098         {
1099                 sh.universe = 0;
1100                 /* set directory in new universe */
1101                 if(*(arg = path_pwd(0))=='/')
1102                         chdir(arg);
1103                 /* clear out old tracked alias */
1104                 stakseek(0);
1105                 stakputs(nv_getval(PATHNOD));
1106                 stakputc(0);
1107                 nv_putval(PATHNOD,stakseek(0),NV_RDONLY);
1108         }
1109         return(1);
1110 }
1111
1112 /*
1113  * initialize the shell
1114  */
1115 int sh_init __PARAM__((register int argc,register char *argv[]), (argc, argv)) __OTORP__(register int argc;register char *argv[];){
1116         register char *name;
1117         register int n,prof;
1118 #ifdef MTRACE
1119         Mt_certify = 1;
1120 #endif /* MTRACE */
1121         memcpy(sh_lexstates,sh_lexrstates,ST_NONE*sizeof(char*));
1122         sh_onstate(SH_INIT);
1123         error_info.exit = sh_exit;
1124         error_info.id = path_basename(argv[0]);
1125         sh.cpipe[0] = -1;
1126         sh.coutpipe = -1;
1127         sh.userid=getuid();
1128         sh.euserid=geteuid();
1129         sh.groupid=getgid();
1130         sh.egroupid=getegid();
1131         for(n=0;n < 10; n++)
1132         {
1133                 /* don't use lower bits when rand() generates large numbers */
1134                 if(rand() > RANDMASK)
1135                 {
1136                         rand_shift = 3;
1137                         break;
1138                 }
1139         }
1140         sh.lim.clk_tck = sysconf(_SC_CLK_TCK);
1141         sh.lim.open_max = sysconf(_SC_OPEN_MAX);
1142         sh.lim.child_max = sysconf(_SC_CHILD_MAX);
1143         sh.lim.ngroups_max = sysconf(_SC_NGROUPS_MAX);
1144         sh.lim.posix_version = sysconf(_SC_VERSION);
1145         sh.lim.posix_jobcontrol = sysconf(_SC_JOB_CONTROL);
1146         if(sh.lim.child_max <=0)
1147                 sh.lim.child_max = CHILD_MAX;
1148         if(sh.lim.open_max <0)
1149                 sh.lim.open_max = OPEN_MAX;
1150         if(sh.lim.clk_tck <=0)
1151                 sh.lim.clk_tck = CLK_TCK;
1152 #ifdef SHOPT_FS_3D
1153         if(mount(".", NIL(char*),FS3D_GET|FS3D_VERSION,0) >= 0)
1154                 sh.lim.fs3d = 1;
1155 #endif /* SHOPT_FS_3D */
1156         sh_ioinit();
1157         /* initialize signal handling */
1158         sh_siginit();
1159         stakinstall(NIL(Stak_t*),nospace);
1160         /* set up memory for name-value pairs */
1161         nv_init();
1162         /* read the environment */
1163 #ifdef SHOPT_MULTIBYTE
1164         charsize_init();
1165 #endif /* SHOPT_MULTIBYTE */
1166         env_init();
1167         nv_putval(IFSNOD,(char*)e_sptbnl,NV_RDONLY);
1168 #ifdef SHOPT_FS_3D
1169         nv_stack(VPATHNOD, &VPATH_init);
1170 #endif /* SHOPT_FS_3D */
1171         astconfdisc(newconf);
1172 #ifdef SHOPT_TIMEOUT
1173         sh.tmout = SHOPT_TIMEOUT;
1174 #endif /* SHOPT_TIMEOUT */
1175         /* initialize jobs table */
1176         job_clear();
1177         if(argc>0)
1178         {
1179                 name = path_basename(*argv);
1180                 if(*name=='-')
1181                 {
1182                         name++;
1183                         sh.login_sh = 2;
1184                 }
1185                 /* check for restricted shell */
1186                 if(argc>0 && strmatch(name,rsh_pattern))
1187                         sh_onoption(SH_RESTRICTED);
1188                 /* look for options */
1189                 /* sh.st.dolc is $#     */
1190                 if((sh.st.dolc = sh_argopts(-argc,argv)) < 0)
1191                 {
1192                         sh.exitval = 2;
1193                         sh_done(0);
1194                 }
1195                 sh.st.dolv=argv+(argc-1)-sh.st.dolc;
1196                 sh.st.dolv[0] = argv[0];
1197                 if(sh.st.dolc < 1)
1198                         sh_onoption(SH_SFLAG);
1199                 if(!sh_isoption(SH_SFLAG))
1200                 {
1201                         sh.st.dolc--;
1202                         sh.st.dolv++;
1203                 }
1204         }
1205         /* set[ug]id scripts require the -p flag */
1206         prof = !sh_isoption(SH_PRIVILEGED);
1207         if(sh.userid!=sh.euserid || sh.groupid!=sh.egroupid)
1208         {
1209 #ifdef SHOPT_P_SUID
1210                 /* require sh -p to run setuid and/or setgid */
1211                 if(!sh_isoption(SH_PRIVILEGED) && sh.euserid < SHOPT_P_SUID)
1212                 {
1213                         setuid(sh.euserid=sh.userid);
1214                         seTgid(sh.egroupid=sh.groupid);
1215                 }
1216                 else
1217 #else
1218                 {
1219                         sh_onoption(SH_PRIVILEGED);
1220                         prof = 0;
1221                 }
1222 #endif /* SHOPT_P_SUID */
1223 #ifdef SHELLMAGIC
1224                 /* careful of #! setuid scripts with name beginning with - */
1225                 if(sh.login_sh && strcmp(argv[0],argv[1])==0)
1226                         error(ERROR_exit(1),e_prohibited);
1227 #endif /*SHELLMAGIC*/
1228         }
1229         else
1230                 sh_offoption(SH_PRIVILEGED);
1231         sh.shname = strdup(sh.st.dolv[0]); /* shname for $0 in profiles */
1232         /*
1233          * return here for shell script execution
1234          * but not for parenthesis subshells
1235          */
1236         error_info.id = strdup(sh.st.dolv[0]); /* error_info.id is $0 */
1237         sh_offstate(SH_INIT);
1238         return(prof);
1239 }
1240
1241 /*
1242  * reinitialize before executing a script
1243  */
1244 void sh_reinit __PARAM__((char *argv[]), (argv)) __OTORP__(char *argv[];){
1245         /* remove locals */
1246         nv_scan(sh.var_tree,sh_envnolocal,NV_EXPORT,0);
1247         hashfree(sh.fun_tree);
1248         sh.fun_tree = hashalloc(sh.bltin_tree,HASH_set,HASH_SCOPE|HASH_ALLOCATE,0);
1249         hashfree(sh.alias_tree);
1250         sh.alias_tree = inittree(shtab_aliases);
1251         /* set up new args */
1252         sh.arglist = sh_argcreate(argv);
1253 }
1254
1255 /*
1256  * set when creating a local variable of this name
1257  */
1258 Namfun_t *nv_cover __PARAM__((register Namval_t *np), (np)) __OTORP__(register Namval_t *np;){
1259         register Namfun_t *nfp=0;
1260         if(np==IFSNOD)
1261                 nfp = &IFS_init;
1262         else if(np==PATHNOD)
1263                 nfp = &PATH_init;
1264         else if(np==SHELLNOD)
1265                 nfp = &SHELL_init;
1266         return(nfp);
1267 }
1268
1269 /*
1270  * Initialize the shell name and alias table
1271  */
1272 static void nv_init __PARAM__((void), ()){
1273         double d=0;
1274         sh.var_base = sh.var_tree = inittree(shtab_variables);
1275         nv_stack(IFSNOD, &IFS_init);
1276         nv_stack(PATHNOD, &PATH_init);
1277         nv_stack(SHELLNOD, &SHELL_init);
1278         nv_stack(ENVNOD, &ENV_init);
1279         nv_stack(VISINOD, &VISUAL_init);
1280         nv_stack(EDITNOD, &EDITOR_init);
1281         nv_stack(OPTINDNOD, &OPTINDEX_init);
1282         nv_stack(SECONDS, &SECONDS_init);
1283         nv_stack(L_ARGNOD, &L_ARG_init);
1284         nv_putval(SECONDS, (char*)&d, NV_INTEGER);
1285         nv_stack(RANDNOD, &RAND_init);
1286         d = (sh.pid&RANDMASK);
1287         nv_putval(RANDNOD, (char*)&d, NV_INTEGER);
1288         nv_stack(LINENO, &LINENO_init);
1289 #ifdef _hdr_locale
1290         nv_stack(LCTYPENOD, &LC_TYPE_init);
1291         nv_stack(LCALLNOD, &LC_ALL_init);
1292         nv_stack(LCMSGNOD, &LC_MSG_init);
1293         nv_stack(LCCOLLNOD, &LC_COLL_init);
1294         nv_stack(LCNUMNOD, &LC_NUM_init);
1295         nv_stack(LANGNOD, &LANG_init);
1296 #endif /* _hdr_locale */
1297 #ifdef apollo
1298         nv_stack(SYSTYPENOD, &SYSTYPE_init);
1299 #endif /* apollo */
1300 #ifdef SHOPT_MULTIBYTE
1301         nv_stack(CSWIDTHNOD, &CSWIDTH_init);
1302 #endif /* SHOPT_MULTIBYTE */
1303         (PPIDNOD)->nvalue.lp = (&sh.ppid);
1304         (TMOUTNOD)->nvalue.lp = (&sh.tmout);
1305         (MCHKNOD)->nvalue.lp = (long*)(&sh_mailchk);
1306         (OPTINDNOD)->nvalue.lp = (&sh.st.optindex);
1307         /* set up the seconds clock */
1308         sh.alias_tree = inittree(shtab_aliases);
1309         sh.track_tree = hashalloc(sh.var_tree,HASH_set,HASH_ALLOCATE,0);
1310         sh.bltin_tree = inittree((const struct shtable2*)shtab_builtins);
1311         sh.fun_tree = hashalloc(sh.bltin_tree,HASH_set,HASH_SCOPE|HASH_ALLOCATE,0);
1312 }
1313
1314 /*
1315  * initialize name-value pairs
1316  */
1317
1318 static Hashtab_t *inittree __PARAM__((const struct shtable2 *name_vals), (name_vals)) __OTORP__(const struct shtable2 *name_vals;){
1319         register Namval_t *np;
1320         register const struct shtable2 *tp;
1321         register unsigned n = 0;
1322         register Hashtab_t *treep;
1323         for(tp=name_vals;*tp->sh_name;tp++)
1324                 n++;
1325         np = (Namval_t*)calloc(n,sizeof(Namval_t));
1326         if(!sh.bltin_nodes)
1327                 sh.bltin_nodes = np;
1328         else if(name_vals==(const struct shtable2*)shtab_builtins)
1329                 sh.bltin_cmds = np;
1330 #ifndef xxx
1331         treep = hashalloc(sh.var_tree,HASH_set,HASH_BUCKET,HASH_name,"vars",sh.var_tree?0:HASH_free,nv_unset,0);
1332         treep->root->flags |= HASH_BUCKET;
1333 #else
1334         treep = hashalloc(sh.var_tree,HASH_name,"vars",sh.var_tree?0:HASH_unset,nv_unset,0);
1335 #endif
1336         for(tp=name_vals;*tp->sh_name;tp++,np++)
1337         {
1338                 np->name = (char*)tp->sh_name;
1339                 np->nvenv = 0;
1340                 if(name_vals==(const struct shtable2*)shtab_builtins)
1341                 {
1342                         np->nvalue.bfp = ((struct shtable3*)tp)->sh_value;
1343                         if(*np->name=='/')
1344                         {
1345                                 np->nvenv = np->name;
1346                                 np->name = path_basename(np->name);
1347                         }
1348                 }
1349                 else
1350                         np->nvalue.cp = (char*)tp->sh_value;
1351                 nv_setattr(np,tp->sh_number);
1352                 if(nv_isattr(np,NV_INTEGER))
1353                         nv_setsize(np,10);
1354                 else
1355                         nv_setsize(np,0);
1356                 nv_link(treep,np);
1357         }
1358         hashset(treep,HASH_ALLOCATE);
1359         return(treep);
1360 }
1361
1362 /*
1363  * read in the process environment and set up name-value pairs
1364  * skip over items that are not name-value pairs
1365  */
1366
1367 static void env_init __PARAM__((void), ()){
1368         register char *cp;
1369         register Namval_t       *np;
1370         register char **ep=environ;
1371         register char *next=0;
1372         if(ep)
1373         {
1374                 while(cp= *ep++)
1375                 {
1376                         if(*cp=='A' && cp[1]=='_' && cp[2]=='_' && cp[3]=='z' && cp[4]=='=')
1377                                 next = cp+4;
1378                         else if(np=nv_open(cp,sh.var_tree,(NV_EXPORT|NV_IDENT|NV_ASSIGN))) 
1379                         {
1380                                 nv_onattr(np,NV_IMPORT);
1381                                 np->nvenv = cp;
1382                                 nv_close(np);
1383                         }
1384                 }
1385                 while(cp=next)
1386                 {
1387                         if(next = strchr(++cp,'='))
1388                                 *next = 0;
1389                         np = nv_search(cp+2,sh.var_tree,NV_ADD);
1390                         if(nv_isattr(np,NV_IMPORT|NV_EXPORT))
1391                                 nv_newattr(np,(unsigned)(cp[0]-' ')|NV_IMPORT|NV_EXPORT,cp[1]-' ');
1392                 }
1393         }
1394         if(nv_isattr(PWDNOD,NV_TAGGED))
1395         {
1396                 nv_offattr(PWDNOD,NV_TAGGED);
1397                 path_pwd(0);
1398         }
1399         if(cp = nv_getval(SHELLNOD))
1400         {
1401                 cp = path_basename(cp);
1402                 if(strmatch(cp,rsh_pattern))
1403                         sh_onoption(SH_RESTRICTED); /* restricted shell */
1404         }
1405         return;
1406 }
1407
1408 /*
1409  * terminate shell and free up the space
1410  */
1411 int sh_term __PARAM__((void), ()){
1412         sfdisc(sfstdin,SF_POPDISC);
1413         free((char*)sh.outbuff);
1414         stakset(NIL(char*),0);
1415         return(0);
1416 }
1417