mirrored from git://git.code.sf.net/p/zsh/code
-
Notifications
You must be signed in to change notification settings - Fork 438
/
builtin.c
7614 lines (7080 loc) · 198 KB
/
builtin.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* builtin.c - builtin commands
*
* This file is part of zsh, the Z shell.
*
* Copyright (c) 1992-1997 Paul Falstad
* All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and to distribute modified versions of this software for any
* purpose, provided that the above copyright notice and the following
* two paragraphs appear in all copies of this software.
*
* In no event shall Paul Falstad or the Zsh Development Group be liable
* to any party for direct, indirect, special, incidental, or consequential
* damages arising out of the use of this software and its documentation,
* even if Paul Falstad and the Zsh Development Group have been advised of
* the possibility of such damage.
*
* Paul Falstad and the Zsh Development Group specifically disclaim any
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose. The software
* provided hereunder is on an "as is" basis, and Paul Falstad and the
* Zsh Development Group have no obligation to provide maintenance,
* support, updates, enhancements, or modifications.
*
*/
/* this is defined so we get the prototype for open_memstream */
#define _GNU_SOURCE 1
#include "zsh.mdh"
#include "builtin.pro"
#include <math.h>
/* Builtins in the main executable */
static struct builtin builtins[] =
{
BIN_PREFIX("-", BINF_DASH),
BIN_PREFIX("builtin", BINF_BUILTIN),
BIN_PREFIX("command", BINF_COMMAND),
BIN_PREFIX("exec", BINF_EXEC),
BIN_PREFIX("noglob", BINF_NOGLOB),
BUILTIN("[", BINF_HANDLES_OPTS, bin_test, 0, -1, BIN_BRACKET, NULL, NULL),
BUILTIN(".", BINF_PSPECIAL, bin_dot, 1, -1, 0, NULL, NULL),
BUILTIN(":", BINF_PSPECIAL, bin_true, 0, -1, 0, NULL, NULL),
BUILTIN("alias", BINF_MAGICEQUALS | BINF_PLUSOPTS, bin_alias, 0, -1, 0, "Lgmrs", NULL),
BUILTIN("autoload", BINF_PLUSOPTS, bin_functions, 0, -1, 0, "dmktrRTUwWXz", "u"),
BUILTIN("bg", 0, bin_fg, 0, -1, BIN_BG, NULL, NULL),
BUILTIN("break", BINF_PSPECIAL, bin_break, 0, 1, BIN_BREAK, NULL, NULL),
BUILTIN("bye", 0, bin_break, 0, 1, BIN_EXIT, NULL, NULL),
BUILTIN("cd", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 2, BIN_CD, "qsPL", NULL),
BUILTIN("chdir", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 2, BIN_CD, "qsPL", NULL),
BUILTIN("continue", BINF_PSPECIAL, bin_break, 0, 1, BIN_CONTINUE, NULL, NULL),
BUILTIN("declare", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%afghi:%klmnp:%rtuxz", NULL),
BUILTIN("dirs", 0, bin_dirs, 0, -1, 0, "clpv", NULL),
BUILTIN("disable", 0, bin_enable, 0, -1, BIN_DISABLE, "afmprs", NULL),
BUILTIN("disown", 0, bin_fg, 0, -1, BIN_DISOWN, NULL, NULL),
BUILTIN("echo", BINF_SKIPINVALID, bin_print, 0, -1, BIN_ECHO, "neE", "-"),
BUILTIN("emulate", 0, bin_emulate, 0, -1, 0, "lLR", NULL),
BUILTIN("enable", 0, bin_enable, 0, -1, BIN_ENABLE, "afmprs", NULL),
BUILTIN("eval", BINF_PSPECIAL, bin_eval, 0, -1, BIN_EVAL, NULL, NULL),
BUILTIN("exit", BINF_PSPECIAL, bin_break, 0, 1, BIN_EXIT, NULL, NULL),
BUILTIN("export", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, BIN_EXPORT, "E:%F:%HL:%R:%TUZ:%afhi:%lp:%rtu", "xg"),
BUILTIN("false", 0, bin_false, 0, -1, 0, NULL, NULL),
/*
* We used to behave as if the argument to -e was optional.
* But that's actually not useful, so it's more consistent to
* cause an error.
*/
BUILTIN("fc", 0, bin_fc, 0, -1, BIN_FC, "aAdDe:EfiIlLmnpPrRst:W", NULL),
BUILTIN("fg", 0, bin_fg, 0, -1, BIN_FG, NULL, NULL),
BUILTIN("float", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "E:%F:%HL:%R:%Z:%ghlp:%rtux", "E"),
BUILTIN("functions", BINF_PLUSOPTS, bin_functions, 0, -1, 0, "ckmMstTuUWx:z", NULL),
BUILTIN("getln", 0, bin_read, 0, -1, 0, "ecnAlE", "zr"),
BUILTIN("getopts", 0, bin_getopts, 2, -1, 0, NULL, NULL),
BUILTIN("hash", BINF_MAGICEQUALS, bin_hash, 0, -1, 0, "Ldfmrv", NULL),
#ifdef ZSH_HASH_DEBUG
BUILTIN("hashinfo", 0, bin_hashinfo, 0, 0, 0, NULL, NULL),
#endif
BUILTIN("history", 0, bin_fc, 0, -1, BIN_FC, "adDEfiLmnpPrt:", "l"),
BUILTIN("integer", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "HL:%R:%Z:%ghi:%lp:%rtux", "i"),
BUILTIN("jobs", 0, bin_fg, 0, -1, BIN_JOBS, "dlpZrs", NULL),
BUILTIN("kill", BINF_HANDLES_OPTS, bin_kill, 0, -1, 0, NULL, NULL),
BUILTIN("let", 0, bin_let, 1, -1, 0, NULL, NULL),
BUILTIN("local", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%ahi:%lnp:%rtux", NULL),
BUILTIN("logout", 0, bin_break, 0, 1, BIN_LOGOUT, NULL, NULL),
#if defined(ZSH_MEM) & defined(ZSH_MEM_DEBUG)
BUILTIN("mem", 0, bin_mem, 0, 0, 0, "v", NULL),
#endif
#if defined(ZSH_PAT_DEBUG)
BUILTIN("patdebug", 0, bin_patdebug, 1, -1, 0, "p", NULL),
#endif
BUILTIN("popd", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 1, BIN_POPD, "q", NULL),
BUILTIN("print", BINF_PRINTOPTS, bin_print, 0, -1, BIN_PRINT, "abcC:Df:ilmnNoOpPrRsSu:v:x:X:z-", NULL),
BUILTIN("printf", BINF_SKIPINVALID | BINF_SKIPDASH, bin_print, 1, -1, BIN_PRINTF, "v:", NULL),
BUILTIN("pushd", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 2, BIN_PUSHD, "qsPL", NULL),
BUILTIN("pushln", 0, bin_print, 0, -1, BIN_PRINT, NULL, "-nz"),
BUILTIN("pwd", 0, bin_pwd, 0, 0, 0, "rLP", NULL),
BUILTIN("r", 0, bin_fc, 0, -1, BIN_R, "IlLnr", NULL),
BUILTIN("read", 0, bin_read, 0, -1, 0, "cd:ek:%lnpqrst:%zu:AE", NULL),
BUILTIN("readonly", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, BIN_READONLY, "AE:%F:%HL:%R:%TUZ:%afghi:%lptux", "r"),
BUILTIN("rehash", 0, bin_hash, 0, 0, 0, "df", "r"),
BUILTIN("return", BINF_PSPECIAL, bin_break, 0, 1, BIN_RETURN, NULL, NULL),
BUILTIN("set", BINF_PSPECIAL | BINF_HANDLES_OPTS, bin_set, 0, -1, 0, NULL, NULL),
BUILTIN("setopt", 0, bin_setopt, 0, -1, BIN_SETOPT, NULL, NULL),
BUILTIN("shift", BINF_PSPECIAL, bin_shift, 0, -1, 0, "p", NULL),
BUILTIN("source", BINF_PSPECIAL, bin_dot, 1, -1, 0, NULL, NULL),
BUILTIN("suspend", 0, bin_suspend, 0, 0, 0, "f", NULL),
BUILTIN("test", BINF_HANDLES_OPTS, bin_test, 0, -1, BIN_TEST, NULL, NULL),
BUILTIN("ttyctl", 0, bin_ttyctl, 0, 0, 0, "fu", NULL),
BUILTIN("times", BINF_PSPECIAL, bin_times, 0, 0, 0, NULL, NULL),
BUILTIN("trap", BINF_PSPECIAL | BINF_HANDLES_OPTS, bin_trap, 0, -1, 0, NULL, NULL),
BUILTIN("true", 0, bin_true, 0, -1, 0, NULL, NULL),
BUILTIN("type", 0, bin_whence, 0, -1, 0, "ampfsSw", "v"),
BUILTIN("typeset", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%afghi:%klp:%rtuxmnz", NULL),
BUILTIN("umask", 0, bin_umask, 0, 1, 0, "S", NULL),
BUILTIN("unalias", 0, bin_unhash, 0, -1, BIN_UNALIAS, "ams", NULL),
BUILTIN("unfunction", 0, bin_unhash, 1, -1, BIN_UNFUNCTION, "m", "f"),
BUILTIN("unhash", 0, bin_unhash, 1, -1, BIN_UNHASH, "adfms", NULL),
BUILTIN("unset", BINF_PSPECIAL, bin_unset, 1, -1, BIN_UNSET, "fmvn", NULL),
BUILTIN("unsetopt", 0, bin_setopt, 0, -1, BIN_UNSETOPT, NULL, NULL),
BUILTIN("wait", 0, bin_fg, 0, -1, BIN_WAIT, NULL, NULL),
BUILTIN("whence", 0, bin_whence, 0, -1, 0, "acmpvfsSwx:", NULL),
BUILTIN("where", 0, bin_whence, 0, -1, 0, "pmsSwx:", "ca"),
BUILTIN("which", 0, bin_whence, 0, -1, 0, "ampsSwx:", "c"),
BUILTIN("zmodload", 0, bin_zmodload, 0, -1, 0, "AFRILP:abcfdilmpsue", NULL),
BUILTIN("zcompile", 0, bin_zcompile, 0, -1, 0, "tUMRcmzka", NULL),
};
/****************************************/
/* Builtin Command Hash Table Functions */
/****************************************/
/* hash table containing builtin commands */
/**/
mod_export HashTable builtintab;
/**/
void
createbuiltintable(void)
{
builtintab = newhashtable(85, "builtintab", NULL);
builtintab->hash = hasher;
builtintab->emptytable = NULL;
builtintab->filltable = NULL;
builtintab->cmpnodes = strcmp;
builtintab->addnode = addhashnode;
builtintab->getnode = gethashnode;
builtintab->getnode2 = gethashnode2;
builtintab->removenode = removehashnode;
builtintab->disablenode = disablehashnode;
builtintab->enablenode = enablehashnode;
builtintab->freenode = freebuiltinnode;
builtintab->printnode = printbuiltinnode;
(void)addbuiltins("zsh", builtins, sizeof(builtins)/sizeof(*builtins));
}
/* Print a builtin */
/**/
static void
printbuiltinnode(HashNode hn, int printflags)
{
Builtin bn = (Builtin) hn;
if (printflags & PRINT_WHENCE_WORD) {
printf("%s: builtin\n", bn->node.nam);
return;
}
if (printflags & PRINT_WHENCE_CSH) {
printf("%s: shell built-in command\n", bn->node.nam);
return;
}
if (printflags & PRINT_WHENCE_VERBOSE) {
printf("%s is a shell builtin\n", bn->node.nam);
return;
}
/* default is name only */
printf("%s\n", bn->node.nam);
}
/**/
static void
freebuiltinnode(HashNode hn)
{
Builtin bn = (Builtin) hn;
if(!(bn->node.flags & BINF_ADDED)) {
zsfree(bn->node.nam);
zsfree(bn->optstr);
zfree(bn, sizeof(struct builtin));
}
}
/**/
void
init_builtins(void)
{
if (!EMULATION(EMULATE_ZSH)) {
HashNode hn = reswdtab->getnode2(reswdtab, "repeat");
if (hn)
reswdtab->disablenode(hn, 0);
}
}
/* Make sure we have space for a new option and increment. */
#define OPT_ALLOC_CHUNK 16
/**/
static int
new_optarg(Options ops)
{
/* Argument index must be a non-zero 6-bit number. */
if (ops->argscount == 63)
return 1;
if (ops->argsalloc == ops->argscount) {
char **newptr =
(char **)zhalloc((ops->argsalloc + OPT_ALLOC_CHUNK) *
sizeof(char *));
if (ops->argsalloc)
memcpy(newptr, ops->args, ops->argsalloc * sizeof(char *));
ops->args = newptr;
ops->argsalloc += OPT_ALLOC_CHUNK;
}
ops->argscount++;
return 0;
}
/* execute a builtin handler function after parsing the arguments */
/**/
int
execbuiltin(LinkList args, LinkList assigns, Builtin bn)
{
char *pp, *name, *optstr;
int flags, argc, execop, xtr = isset(XTRACE);
struct options ops;
/* initialise options structure */
memset(ops.ind, 0, MAX_OPS*sizeof(unsigned char));
ops.args = NULL;
ops.argscount = ops.argsalloc = 0;
/* initialize some local variables */
name = (char *) ugetnode(args);
if (!bn->handlerfunc) {
DPUTS(1, "Missing builtin detected too late");
deletebuiltin(bn->node.nam);
return 1;
}
/* get some information about the command */
flags = bn->node.flags;
optstr = bn->optstr;
/* Set up the argument list. */
/* count the arguments */
argc = countlinknodes(args);
{
/*
* Keep all arguments, including options, in an array.
* We don't actually need the option part of the argument
* after option processing, but it makes XTRACE output
* much simpler.
*/
VARARR(char *, argarr, argc + 1);
char **argv;
/*
* Get the actual arguments, into argv. Remember argarr
* may be an array declaration, depending on the compiler.
*/
argv = argarr;
while ((*argv++ = (char *)ugetnode(args)));
argv = argarr;
/* Sort out the options. */
if (optstr) {
char *arg = *argv;
int sense; /* 1 for -x, 0 for +x */
/* while arguments look like options ... */
while (arg &&
/* Must begin with - or maybe + */
((sense = (*arg == '-')) ||
((flags & BINF_PLUSOPTS) && *arg == '+'))) {
/* Digits aren't arguments unless the command says they are. */
if (!(flags & BINF_KEEPNUM) && idigit(arg[1]))
break;
/* For cd and friends, a single dash is not an option. */
if ((flags & BINF_SKIPDASH) && !arg[1])
break;
if ((flags & BINF_DASHDASHVALID) && !strcmp(arg, "--")) {
/*
* Need to skip this before checking whether this is
* really an option.
*/
argv++;
break;
}
/*
* Unrecognised options to echo etc. are not really
* options.
*
* Note this flag is not smart enough to handle option
* arguments. In fact, ideally it shouldn't be added
* to any new builtins, to preserve standard option
* handling as much as possible.
*/
if (flags & BINF_SKIPINVALID) {
char *p = arg;
while (*++p && strchr(optstr, (int) *p));
if (*p)
break;
}
/* handle -- or - (ops.ind['-']), and +
* (ops.ind['-'] and ops.ind['+']) */
if (arg[1] == '-')
arg++;
if (!arg[1]) {
ops.ind['-'] = 1;
if (!sense)
ops.ind['+'] = 1;
}
/* save options in ops, as long as they are in bn->optstr */
while (*++arg) {
char *optptr;
if ((optptr = strchr(optstr, execop = (int)*arg))) {
ops.ind[(int)*arg] = (sense) ? 1 : 2;
if (optptr[1] == ':') {
char *argptr = NULL;
if (optptr[2] == ':') {
if (arg[1])
argptr = arg+1;
/* Optional argument in same word*/
} else if (optptr[2] == '%') {
/* Optional numeric argument in same
* or next word. */
if (arg[1] && idigit(arg[1]))
argptr = arg+1;
else if (argv[1] && idigit(*argv[1]))
argptr = arg = *++argv;
} else {
/* Mandatory argument */
if (arg[1])
argptr = arg+1;
else if ((arg = *++argv))
argptr = arg;
else {
zwarnnam(name, "argument expected: -%c",
execop);
return 1;
}
}
if (argptr) {
if (new_optarg(&ops)) {
zwarnnam(name,
"too many option arguments");
return 1;
}
ops.ind[execop] |= ops.argscount << 2;
ops.args[ops.argscount-1] = argptr;
while (arg[1])
arg++;
}
}
} else
break;
}
/* The above loop may have exited on an invalid option. (We *
* assume that any option requiring metafication is invalid.) */
if (*arg) {
if(*arg == Meta)
*++arg ^= 32;
zwarnnam(name, "bad option: %c%c", "+-"[sense], *arg);
return 1;
}
arg = *++argv;
/* for the "print" builtin, the options after -R are treated as
options to "echo" */
if ((flags & BINF_PRINTOPTS) && ops.ind['R'] &&
!ops.ind['f']) {
optstr = "ne";
flags |= BINF_SKIPINVALID;
}
/* the option -- indicates the end of the options */
if (ops.ind['-'])
break;
}
} else if (!(flags & BINF_HANDLES_OPTS) && *argv &&
!strcmp(*argv, "--")) {
ops.ind['-'] = 1;
argv++;
}
/* handle built-in options, for overloaded handler functions */
if ((pp = bn->defopts)) {
while (*pp) {
/* only if not already set */
if (!ops.ind[(int)*pp])
ops.ind[(int)*pp] = 1;
pp++;
}
}
/* Fix the argument count by subtracting option arguments */
argc -= argv - argarr;
if (errflag) {
errflag &= ~ERRFLAG_ERROR;
return 1;
}
/* check that the argument count lies within the specified bounds */
if (argc < bn->minargs || (argc > bn->maxargs && bn->maxargs != -1)) {
zwarnnam(name, (argc < bn->minargs)
? "not enough arguments" : "too many arguments");
return 1;
}
/* display execution trace information, if required */
if (xtr) {
/* Use full argument list including options for trace output */
char **fullargv = argarr;
printprompt4();
fprintf(xtrerr, "%s", name);
while (*fullargv) {
fputc(' ', xtrerr);
quotedzputs(*fullargv++, xtrerr);
}
if (assigns) {
LinkNode node;
for (node = firstnode(assigns); node; incnode(node)) {
Asgment asg = (Asgment)node;
fputc(' ', xtrerr);
quotedzputs(asg->name, xtrerr);
if (asg->flags & ASG_ARRAY) {
fprintf(xtrerr, "=(");
if (asg->value.array) {
if (asg->flags & ASG_KEY_VALUE) {
LinkNode keynode, valnode;
keynode = firstnode(asg->value.array);
for (;;) {
if (!keynode)
break;
valnode = nextnode(keynode);
if (!valnode)
break;
fputc('[', xtrerr);
quotedzputs((char *)getdata(keynode),
xtrerr);
fprintf(stderr, "]=");
quotedzputs((char *)getdata(valnode),
xtrerr);
keynode = nextnode(valnode);
}
} else {
LinkNode arrnode;
for (arrnode = firstnode(asg->value.array);
arrnode;
incnode(arrnode)) {
fputc(' ', xtrerr);
quotedzputs((char *)getdata(arrnode),
xtrerr);
}
}
}
fprintf(xtrerr, " )");
} else if (asg->value.scalar) {
fputc('=', xtrerr);
quotedzputs(asg->value.scalar, xtrerr);
}
}
}
fputc('\n', xtrerr);
fflush(xtrerr);
}
/* call the handler function, and return its return value */
if (flags & BINF_ASSIGN)
{
/*
* Takes two sets of arguments.
*/
HandlerFuncAssign assignfunc = (HandlerFuncAssign)bn->handlerfunc;
return (*(assignfunc)) (name, argv, assigns, &ops, bn->funcid);
}
else
{
return (*(bn->handlerfunc)) (name, argv, &ops, bn->funcid);
}
}
}
/* Enable/disable an element in one of the internal hash tables. *
* With no arguments, it lists all the currently enabled/disabled *
* elements in that particular hash table. */
/**/
int
bin_enable(char *name, char **argv, Options ops, int func)
{
HashTable ht;
HashNode hn;
ScanFunc scanfunc;
Patprog pprog;
int flags1 = 0, flags2 = 0;
int match = 0, returnval = 0;
/* Find out which hash table we are working with. */
if (OPT_ISSET(ops,'p')) {
return pat_enables(name, argv, func == BIN_ENABLE);
} else if (OPT_ISSET(ops,'f'))
ht = shfunctab;
else if (OPT_ISSET(ops,'r'))
ht = reswdtab;
else if (OPT_ISSET(ops,'s'))
ht = sufaliastab;
else if (OPT_ISSET(ops,'a'))
ht = aliastab;
else
ht = builtintab;
/* Do we want to enable or disable? */
if (func == BIN_ENABLE) {
flags2 = DISABLED;
scanfunc = ht->enablenode;
} else {
flags1 = DISABLED;
scanfunc = ht->disablenode;
}
/* Given no arguments, print the names of the enabled/disabled elements *
* in this hash table. If func == BIN_ENABLE, then scanhashtable will *
* print nodes NOT containing the DISABLED flag, else scanhashtable will *
* print nodes containing the DISABLED flag. */
if (!*argv) {
queue_signals();
scanhashtable(ht, 1, flags1, flags2, ht->printnode, 0);
unqueue_signals();
return 0;
}
/* With -m option, treat arguments as glob patterns. */
if (OPT_ISSET(ops,'m')) {
for (; *argv; argv++) {
queue_signals();
/* parse pattern */
tokenize(*argv);
if ((pprog = patcompile(*argv, PAT_STATIC, 0)))
match += scanmatchtable(ht, pprog, 0, 0, 0, scanfunc, 0);
else {
untokenize(*argv);
zwarnnam(name, "bad pattern : %s", *argv);
returnval = 1;
}
unqueue_signals();
}
/* If we didn't match anything, we return 1. */
if (!match)
returnval = 1;
return returnval;
}
/* Take arguments literally -- do not glob */
queue_signals();
for (; *argv; argv++) {
if ((hn = ht->getnode2(ht, *argv))) {
scanfunc(hn, 0);
} else {
zwarnnam(name, "no such hash table element: %s", *argv);
returnval = 1;
}
}
unqueue_signals();
return returnval;
}
/* set: either set the shell options, or set the shell arguments, *
* or declare an array, or show various things */
/**/
int
bin_set(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
{
int action, optno, array = 0, hadopt = 0,
hadplus = 0, hadend = 0, sort = 0;
char **x, *arrayname = NULL;
/* Obsolescent sh compatibility: set - is the same as set +xv *
* and set - args is the same as set +xv -- args */
if (!EMULATION(EMULATE_ZSH) && *args && **args == '-' && !args[0][1]) {
dosetopt(VERBOSE, 0, 0, opts);
dosetopt(XTRACE, 0, 0, opts);
if (!args[1])
return 0;
}
/* loop through command line options (begins with "-" or "+") */
while (*args && (**args == '-' || **args == '+')) {
action = (**args == '-');
hadplus |= !action;
if(!args[0][1])
*args = "--";
while (*++*args) {
if(**args == Meta)
*++*args ^= 32;
if(**args != '-' || action)
hadopt = 1;
/* The pseudo-option `--' signifies the end of options. */
if (**args == '-') {
hadend = 1;
args++;
goto doneoptions;
} else if (**args == 'o') {
if (!*++*args)
args++;
if (!*args) {
printoptionstates(hadplus);
inittyptab();
return 0;
}
if(!(optno = optlookup(*args)))
zerrnam(nam, "no such option: %s", *args);
else if(dosetopt(optno, action, 0, opts))
zerrnam(nam, "can't change option: %s", *args);
break;
} else if(**args == 'A') {
if(!*++*args)
args++;
array = action ? 1 : -1;
arrayname = *args;
if (!arrayname)
goto doneoptions;
else if (!isset(KSHARRAYS))
{
args++;
goto doneoptions;
}
break;
} else if (**args == 's')
sort = action ? 1 : -1;
else {
if (!(optno = optlookupc(**args)))
zerrnam(nam, "bad option: -%c", **args);
else if(dosetopt(optno, action, 0, opts))
zerrnam(nam, "can't change option: -%c", **args);
}
}
args++;
}
if (errflag)
return 1;
doneoptions:
inittyptab();
/* Show the parameters, possibly with values */
queue_signals();
if (!arrayname)
{
if (!hadopt && !*args)
scanhashtable(paramtab, 1, 0, 0, paramtab->printnode,
hadplus ? PRINT_NAMEONLY : 0);
if (array) {
/* display arrays */
scanhashtable(paramtab, 1, PM_ARRAY, 0, paramtab->printnode,
hadplus ? PRINT_NAMEONLY : 0);
}
if (!*args && !hadend) {
unqueue_signals();
return 0;
}
}
if (sort)
strmetasort(args, sort < 0 ? SORTIT_BACKWARDS : 0, NULL);
if (array) {
/* create an array with the specified elements */
char **a = NULL, **y;
int len = arrlen(args);
if (array < 0 && (a = getaparam(arrayname)) && arrlen_gt(a, len)) {
a += len;
len += arrlen(a);
}
for (x = y = zalloc((len + 1) * sizeof(char *)); len--;) {
if (!*args)
args = a;
*y++ = ztrdup(*args++);
}
*y++ = NULL;
setaparam(arrayname, x);
} else {
/* set shell arguments */
freearray(pparams);
pparams = zarrdup(args);
}
unqueue_signals();
return 0;
}
/**** directory-handling builtins ****/
/**/
int doprintdir = 0; /* set in exec.c (for autocd, cdpath, etc.) */
/* pwd: display the name of the current directory */
/**/
int
bin_pwd(UNUSED(char *name), UNUSED(char **argv), Options ops, UNUSED(int func))
{
if (OPT_ISSET(ops,'r') || OPT_ISSET(ops,'P') ||
(isset(CHASELINKS) && !OPT_ISSET(ops,'L')))
printf("%s\n", zgetcwd());
else {
zputs(pwd, stdout);
putchar('\n');
}
return 0;
}
/* the directory stack */
/**/
mod_export LinkList dirstack;
/* dirs: list the directory stack, or replace it with a provided list */
/**/
int
bin_dirs(UNUSED(char *name), char **argv, Options ops, UNUSED(int func))
{
LinkList l;
queue_signals();
/* with -v, -p or no arguments display the directory stack */
if (!(*argv || OPT_ISSET(ops,'c')) || OPT_ISSET(ops,'v') ||
OPT_ISSET(ops,'p')) {
LinkNode node;
char *fmt;
int pos = 1;
/* with the -v option, display a numbered list, starting at zero */
if (OPT_ISSET(ops,'v')) {
printf("0\t");
fmt = "\n%d\t";
/* with the -p option, display entries one per line */
} else if (OPT_ISSET(ops,'p'))
fmt = "\n";
else
fmt = " ";
if (OPT_ISSET(ops,'l'))
zputs(pwd, stdout);
else
fprintdir(pwd, stdout);
for (node = firstnode(dirstack); node; incnode(node)) {
printf(fmt, pos++);
if (OPT_ISSET(ops,'l'))
zputs(getdata(node), stdout);
else
fprintdir(getdata(node), stdout);
}
unqueue_signals();
putchar('\n');
return 0;
}
/* replace the stack with the specified directories */
l = znewlinklist();
while (*argv)
zaddlinknode(l, ztrdup(*argv++));
freelinklist(dirstack, freestr);
dirstack = l;
unqueue_signals();
return 0;
}
/* cd, chdir, pushd, popd */
/**/
void
set_pwd_env(void)
{
Param pm;
/* update the PWD and OLDPWD shell parameters */
pm = (Param) paramtab->getnode(paramtab, "PWD");
if (pm && PM_TYPE(pm->node.flags) != PM_SCALAR) {
pm->node.flags &= ~PM_READONLY;
unsetparam_pm(pm, 0, 1);
}
pm = (Param) paramtab->getnode(paramtab, "OLDPWD");
if (pm && PM_TYPE(pm->node.flags) != PM_SCALAR) {
pm->node.flags &= ~PM_READONLY;
unsetparam_pm(pm, 0, 1);
}
assignsparam("PWD", ztrdup(pwd), 0);
assignsparam("OLDPWD", ztrdup(oldpwd), 0);
pm = (Param) paramtab->getnode(paramtab, "PWD");
if (!(pm->node.flags & PM_EXPORTED))
addenv(pm, pwd);
pm = (Param) paramtab->getnode(paramtab, "OLDPWD");
if (!(pm->node.flags & PM_EXPORTED))
addenv(pm, oldpwd);
}
/* set if we are resolving links to their true paths */
static int chasinglinks;
/* The main pwd changing function. The real work is done by other *
* functions. cd_get_dest() does the initial argument processing; *
* cd_do_chdir() actually changes directory, if possible; cd_new_pwd() *
* does the ancillary processing associated with actually changing *
* directory. */
/**/
int
bin_cd(char *nam, char **argv, Options ops, int func)
{
LinkNode dir;
if (isset(RESTRICTED)) {
zwarnnam(nam, "restricted");
return 1;
}
doprintdir = (doprintdir == -1);
chasinglinks = OPT_ISSET(ops,'P') ||
(isset(CHASELINKS) && !OPT_ISSET(ops,'L'));
queue_signals();
zpushnode(dirstack, ztrdup(pwd));
if (!(dir = cd_get_dest(nam, argv, OPT_ISSET(ops,'s'), func))) {
zsfree(getlinknode(dirstack));
unqueue_signals();
return 1;
}
cd_new_pwd(func, dir, OPT_ISSET(ops, 'q'));
unqueue_signals();
return 0;
}
/* Get directory to chdir to */
/**/
static LinkNode
cd_get_dest(char *nam, char **argv, int hard, int func)
{
LinkNode dir = NULL;
LinkNode target;
char *dest;
if (!argv[0]) {
if (func == BIN_POPD && !nextnode(firstnode(dirstack))) {
zwarnnam(nam, "directory stack empty");
return NULL;
}
if (func == BIN_PUSHD && unset(PUSHDTOHOME))
dir = nextnode(firstnode(dirstack));
if (dir)
zinsertlinknode(dirstack, dir, getlinknode(dirstack));
else if (func != BIN_POPD) {
if (!home) {
zwarnnam(nam, "HOME not set");
return NULL;
}
zpushnode(dirstack, ztrdup(home));
}
} else if (!argv[1]) {
int dd;
char *end;
doprintdir++;
if (!isset(POSIXCD) && argv[0][1] && (argv[0][0] == '+' || argv[0][0] == '-')
&& strspn(argv[0]+1, "0123456789") == strlen(argv[0]+1)) {
dd = zstrtol(argv[0] + 1, &end, 10);
if (*end == '\0') {
if ((argv[0][0] == '+') ^ isset(PUSHDMINUS))
for (dir = firstnode(dirstack); dir && dd; dd--, incnode(dir));
else
for (dir = lastnode(dirstack); dir != (LinkNode) dirstack && dd;
dd--, dir = prevnode(dir));
if (!dir || dir == (LinkNode) dirstack) {
zwarnnam(nam, "no such entry in dir stack");
return NULL;
}
}
}
if (!dir)
zpushnode(dirstack, ztrdup(strcmp(argv[0], "-")
? (doprintdir--, argv[0]) : oldpwd));
} else {
char *u, *d;
int len1, len2, len3;
if (!(u = strstr(pwd, argv[0]))) {
zwarnnam(nam, "string not in pwd: %s", argv[0]);
return NULL;
}
len1 = strlen(argv[0]);
len2 = strlen(argv[1]);
len3 = u - pwd;
d = (char *)zalloc(len3 + len2 + strlen(u + len1) + 1);
strncpy(d, pwd, len3);
strcpy(d + len3, argv[1]);
strcat(d, u + len1);
zpushnode(dirstack, d);
doprintdir++;
}
target = dir;
if (func == BIN_POPD) {
if (!dir) {
target = dir = firstnode(dirstack);
} else if (dir != firstnode(dirstack)) {
return dir;
}
dir = nextnode(dir);
}
if (!dir) {
dir = firstnode(dirstack);
}
if (!dir || !getdata(dir)) {
DPUTS(1, "Directory not set, not detected early enough");
return NULL;
}
if (!(dest = cd_do_chdir(nam, getdata(dir), hard))) {
if (!target)
zsfree(getlinknode(dirstack));
if (func == BIN_POPD)
zsfree(remnode(dirstack, dir));
return NULL;
}
if (dest != (char *)getdata(dir)) {
zsfree(getdata(dir));
setdata(dir, dest);
}
return target ? target : dir;
}
/* Change to given directory, if possible. This function works out *
* exactly how the directory should be interpreted, including cdpath *
* and CDABLEVARS. For each possible interpretation of the given *
* path, this calls cd_try_chdir(), which attempts to chdir to that *
* particular path. */
/**/
static char *
cd_do_chdir(char *cnam, char *dest, int hard)
{
char **pp, *ret;
int hasdot = 0, eno = ENOENT;
/*
* nocdpath indicates that cdpath should not be used.
* This is the case iff dest is a relative path
* whose first segment is . or .., but if the path is
* absolute then cdpath won't be used anyway.
*/
int nocdpath;
#ifdef __CYGWIN__
/*
* Normalize path under Cygwin to avoid messing with
* DOS style names with drives in them
*/
static char buf[PATH_MAX+1];
#ifdef HAVE_CYGWIN_CONV_PATH
cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, dest, buf,
PATH_MAX);
#else
#ifndef _SYS_CYGWIN_H
void cygwin_conv_to_posix_path(const char *, char *);
#endif
cygwin_conv_to_posix_path(dest, buf);
#endif
dest = buf;
#endif
nocdpath = dest[0] == '.' &&