-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathexpand.c
2159 lines (1969 loc) · 74.2 KB
/
expand.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
/* Yash: yet another shell */
/* expand.c: word expansion */
/* (C) 2007-2025 magicant */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "common.h"
#include "expand.h"
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>
#include "arith.h"
#include "exec.h"
#include "input.h"
#include "option.h"
#include "parser.h"
#include "path.h"
#include "plist.h"
#include "sig.h"
#include "strbuf.h"
#include "util.h"
#include "variable.h"
#include "xfnmatch.h"
#include "yash.h"
/* result of word expansion */
struct expand_four_T {
plist_T valuelist, cclist;
};
/* `valuelist' is a list of pointers to newly malloced wide strings that contain
* the expanded word value. `cclist' is a list of pointers to newly malloced
* single-byte strings whose values are charcategory_T cast to char. `cclist'
* must have as many strings as `valuelist' and each string in `cclist' must
* have the same length as the corresponding wide string in `valuelist'. */
static plist_T expand_word(const wordunit_T *w)
__attribute__((warn_unused_result));
static struct expand_four_T expand_four(const wordunit_T *restrict w,
tildetype_T tilde, quoting_T quoting, charcategory_T defaultcc)
__attribute__((warn_unused_result));
static inline void fill_ccbuf(
const xwcsbuf_T *restrict valuebuf, xstrbuf_T *restrict ccbuf,
charcategory_T c)
__attribute__((nonnull));
static wchar_t *expand_tilde(const wchar_t **ss,
bool hasnextwordunit, bool stopatcolon)
__attribute__((nonnull,malloc,warn_unused_result));
enum indextype_T { IDX_NONE, IDX_ALL, IDX_CONCAT, IDX_NUMBER, };
static struct expand_four_T expand_param(const paramexp_T *p, bool indq)
__attribute__((nonnull));
static enum indextype_T parse_indextype(const wchar_t *indexstr)
__attribute__((nonnull,pure));
static wchar_t *trim_wstring(wchar_t *s, ssize_t startindex, ssize_t endindex)
__attribute__((nonnull));
static void **trim_array(void **a, ssize_t startindex, ssize_t endindex)
__attribute__((nonnull));
static void print_subst_as_error(const paramexp_T *p, quoting_T quoting)
__attribute__((nonnull));
static void match_each(void **restrict slist, const wchar_t *restrict pattern,
paramexptype_T type)
__attribute__((nonnull));
static void subst_each(void **restrict slist, const wchar_t *pattern,
const wchar_t *subst, paramexptype_T type)
__attribute__((nonnull));
static wchar_t *concatenate_values(void **values, bool escape)
__attribute__((nonnull,malloc,warn_unused_result));
static void **concatenate_values_into_array(void **values, bool escape)
__attribute__((nonnull,malloc,warn_unused_result));
static void subst_length_each(void **slist)
__attribute__((nonnull));
static void merge_expand_four(
struct expand_four_T *restrict from,
struct expand_four_T *restrict to,
xwcsbuf_T *restrict valuebuf, xstrbuf_T *restrict ccbuf)
__attribute__((nonnull));
/* data used in brace expansion */
struct brace_expand_T {
const wchar_t *word; /* the word to expand */
const char *cc; /* the corresponding charcategory_T string */
void *const *graph; /* see the comment in the `expand_brace` function */
plist_T *valuelist; /* the list to add the results (words) */
plist_T *cclist; /* the list to add the results (charcategory_T) */
};
static void expand_brace_each(
void *const *restrict values, void *const *restrict ccs,
plist_T *restrict valuelist, plist_T *restrict cclist)
__attribute__((nonnull));
static void expand_brace(
wchar_t *restrict word, char *restrict cc,
plist_T *restrict valuelist, plist_T *restrict cclist)
__attribute__((nonnull));
static void generate_brace_expand_results(
const struct brace_expand_T *restrict e, size_t ci,
xwcsbuf_T *restrict valuebuf, xstrbuf_T *restrict ccbuf)
__attribute__((nonnull));
static bool try_expand_brace_sequence(
const struct brace_expand_T *restrict e, size_t ci,
xwcsbuf_T *restrict valuebuf, xstrbuf_T *restrict ccbuf)
__attribute__((nonnull));
static bool has_leading_zero(const wchar_t *restrict s, bool *restrict sign)
__attribute__((nonnull));
static void fieldsplit(void **restrict valuelist, void **restrict cclist,
plist_T *restrict outvaluelist, plist_T *restrict outcclist)
__attribute__((nonnull));
static bool is_ifs_char(wchar_t c, charcategory_T cc, const wchar_t *ifs)
__attribute__((nonnull,pure));
static bool is_ifs_whitespace(wchar_t c, charcategory_T cc, const wchar_t *ifs)
__attribute__((nonnull,pure));
static bool is_non_ifs_char(wchar_t c, charcategory_T cc, const wchar_t *ifs)
__attribute__((nonnull,pure));
static void add_empty_field(plist_T *dest, const wchar_t *p)
__attribute__((nonnull));
static inline void add_sq(
const wchar_t *restrict *ss, xwcsbuf_T *restrict buf, bool escape)
__attribute__((nonnull));
static wchar_t *interpret_dsq(const wchar_t *restrict *ss)
__attribute__((nonnull,malloc,warn_unused_result));
static inline bool should_escape(charcategory_T cc, escaping_T escaping)
__attribute__((const));
static wchar_t *quote_removal_free(
wchar_t *restrict s, char *restrict cc, escaping_T escaping)
__attribute__((nonnull,malloc,warn_unused_result));
static enum wglobflags_T get_wglobflags(void)
__attribute__((pure));
static void glob_all(
struct expand_four_T *restrict e, plist_T *restrict results)
__attribute__((nonnull));
static void maybe_exit_on_error(void);
/********** Entry Points **********/
/* Expands a command line.
* `args' is a NULL-terminated array of pointers to `const wordunit_T'
* to expand.
* If `assignsingle' is true, assignment-like words are expanded to single
* fields like expanding assignment tokens. Otherwise, all words are expanded to
* multiple fields as usual.
* If successful, a list of pointers to newly malloced wide strings is returned.
* On error, a non-initialized pointer list is returned whose `contents' field
* is NULL.
* On error in a non-interactive shell, the shell exits. */
plist_T expand_line(void *const *args, bool assignsingle)
{
plist_T list;
pl_init(&list);
for (; *args != NULL; args++) {
const wordunit_T *w = *args;
bool success;
if (!assignsingle || w == NULL || w->wu_type != WT_STRING ||
!is_assignment_prefix(w->wu_string)) {
success = expand_multiple(w, &list);
} else {
wchar_t *s = expand_single(w, TT_ASSIGN, Q_WORD, ES_NONE);
success = (s != NULL);
if (success)
pl_add(&list, s);
}
if (!success) {
plfree(pl_toary(&list), free);
list.contents = NULL;
break;
}
}
return list;
}
/* Expands a word to (possibly any number of) fields.
* The operation includes the four expansions, brace expansion, field splitting,
* pathname expansion, and quote removal.
* The results are added to `list' as newly-malloced wide strings.
* The return value is true iff successful.
* On error in a non-interactive shell, the shell exits. */
bool expand_multiple(const wordunit_T *w, plist_T *list)
{
/* four expansions (w -> valuelist) */
struct expand_four_T expand = expand_four(w, TT_SINGLE, Q_WORD, CC_LITERAL);
if (expand.valuelist.contents == NULL) {
maybe_exit_on_error();
return false;
}
/* brace expansion (valuelist -> valuelist2) */
plist_T valuelist2, cclist2;
if (shopt_braceexpand) {
pl_init(&valuelist2);
pl_init(&cclist2);
expand_brace_each(expand.valuelist.contents, expand.cclist.contents,
&valuelist2, &cclist2);
pl_truncate(&expand.valuelist, 0);
pl_truncate(&expand.cclist, 0);
} else {
valuelist2 = expand.valuelist;
cclist2 = expand.cclist;
pl_init(&expand.valuelist);
pl_init(&expand.cclist);
}
/* field splitting (valuelist2 -> valuelist) */
fieldsplit(pl_toary(&valuelist2), pl_toary(&cclist2),
&expand.valuelist, &expand.cclist);
assert(expand.valuelist.length == expand.cclist.length);
/* pathname expansion (and quote removal) */
glob_all(&expand, list);
return true;
}
/* Expands a word to (possibly any number of) fields.
* The operation includes the four expansions and quote removal. Unlike
* `expand_multiple', this function does not perform brace expansion, field
* splitting, or pathname expansion.
* If successful, the return value is a plist_T containing newly malloced wide
* strings. In most cases, the plist_T contains one string. If the word contains
* "$@", however, it may contain any number of strings.
* On error, the return value is a plist_T with `contents' being NULL. */
plist_T expand_word(const wordunit_T *w)
{
/* four expansions */
struct expand_four_T expand = expand_four(w, TT_NONE, Q_WORD, CC_LITERAL);
if (expand.valuelist.contents == NULL)
return expand.valuelist;
/* quote removal */
for (size_t i = 0; i < expand.valuelist.length; i++)
expand.valuelist.contents[i] = quote_removal_free(
expand.valuelist.contents[i], expand.cclist.contents[i], ES_NONE);
pl_destroy(&expand.cclist);
return expand.valuelist;
}
/* Expands a word to a single field.
* If successful, the result is a pair of newly malloced strings.
* On error, an error message is printed and a NULL pair is returned.
* On error in a non-interactive shell, the shell exits. */
/* This function first expands the word into (possibly many) fields and then
* concatenates into one field. */
struct cc_word_T expand_single_cc(
const wordunit_T *w, tildetype_T tilde, quoting_T quoting)
{
struct expand_four_T e = expand_four(w, tilde, quoting, CC_LITERAL);
if (e.valuelist.contents == NULL) {
maybe_exit_on_error();
return (struct cc_word_T) { NULL, NULL };
}
const wchar_t *ifs = getvar(L VAR_IFS);
wchar_t separator = ifs != NULL ? ifs[0] : L' ';
size_t totallength;
if (e.valuelist.length == 0)
totallength = 0;
else {
totallength = e.valuelist.length - 1;
for (size_t i = 0; i < e.valuelist.length; i++)
totallength = add(totallength, wcslen(e.valuelist.contents[i]));
}
xwcsbuf_T valuebuf;
xstrbuf_T ccbuf;
wb_initwithmax(&valuebuf, totallength);
sb_initwithmax(&ccbuf, totallength);
for (size_t i = 0; i < e.valuelist.length; i++) {
if (i > 0 && separator != L'\0') {
wb_wccat(&valuebuf, separator);
sb_ccat(&ccbuf, CC_SOFT_EXPANSION);
}
wb_catfree(&valuebuf, e.valuelist.contents[i]);
sb_ncat_force(
&ccbuf, e.cclist.contents[i], valuebuf.length - ccbuf.length);
free(e.cclist.contents[i]);
}
pl_destroy(&e.valuelist);
pl_destroy(&e.cclist);
return (struct cc_word_T) { wb_towcs(&valuebuf), sb_tostr(&ccbuf) };
}
/* Expands a single word: the four expansions and quote removal.
* This function doesn't perform brace expansion, field splitting, or globbing.
* If successful, the resulting word is returned as a newly malloced string.
* On error, an error message is printed and NULL is returned.
* On error in a non-interactive shell, the shell exits. */
wchar_t *expand_single(const wordunit_T *w,
tildetype_T tilde, quoting_T quoting, escaping_T escaping)
{
cc_word_T e = expand_single_cc(w, tilde, quoting);
if (e.value == NULL)
return NULL;
return quote_removal_free(e.value, e.cc, escaping);
}
/* Expands a single word: the four expansions, pathname expansion, and quote
* removal.
* This function doesn't perform brace expansion or field splitting.
* If the result of pathname expansion is more than one word, this function
* - returns the original pattern string if in the POSIXly correct mode
* - treats it as an error otherwise.
* If the "glob" shell option is off, pathname expansion is not performed.
* The "nullglob" shell option is ignored.
* If successful, the resulting word is returned as a newly malloced string.
* On error, an error message is printed and NULL is returned.
* On error in a non-interactive shell, the shell exits. */
char *expand_single_with_glob(const wordunit_T *arg)
{
cc_word_T e = expand_single_cc(arg, TT_SINGLE, Q_WORD);
if (e.value == NULL)
goto return_null;
if (!shopt_glob)
goto quote_removal;
wchar_t *pattern = quote_removal(e.value, e.cc, ES_QUOTED_HARD);
if (!is_pathname_matching_pattern(pattern)) {
free(pattern);
goto quote_removal;
}
plist_T globresults;
bool ok;
/* perform pathname expansion */
pl_init(&globresults);
set_interruptible_by_sigint(true);
ok = wglob(pattern, get_wglobflags(), &globresults);
set_interruptible_by_sigint(false);
free(pattern);
if (!ok) {
plfree(pl_toary(&globresults), free);
xerror(EINTR, Ngt("redirection"));
goto return_null;
}
/* examine the expansion results */
wchar_t *wresult;
if (globresults.length == 1) {
wresult = globresults.contents[0];
pl_destroy(&globresults);
} else {
plfree(pl_toary(&globresults), free);
if (!posixly_correct) {
wchar_t *word = quote_removal(e.value, e.cc, ES_NONE);
xerror(0, Ngt("filename `%ls' matches more than one file"), word);
free(word);
goto return_null;
}
quote_removal:
wresult = quote_removal(e.value, e.cc, ES_NONE);
}
char *mbresult = realloc_wcstombs(wresult);
if (mbresult == NULL)
xerror(EILSEQ, Ngt("redirection"));
free(e.value);
free(e.cc);
return mbresult;
return_null:
free(e.value);
free(e.cc);
return NULL;
}
/********** Four Expansions **********/
/* Performs the four expansions, i.e., tilde expansion, parameter expansion,
* command substitution, and arithmetic expansion.
* If successful, `valuelist' in the return value is the list of the resultant
* fields, which are newly malloced wide strings, and `cclist' is the list of
* the corresponding charcategory_T strings, which are also newly malloced.
* Usually this function produces one or more fields, but it may produce zero
* fields if "$@" is expanded with no positional parameters.
* If unsuccessful, `valuelist' and `cclist' are empty and have NULL `contents'.
*/
struct expand_four_T expand_four(const wordunit_T *restrict w,
tildetype_T tilde, quoting_T quoting, charcategory_T defaultcc)
{
/* lists to insert the final results into */
struct expand_four_T e;
pl_init(&e.valuelist);
pl_init(&e.cclist);
/* intermediate value of the currently expanded word */
xwcsbuf_T valuebuf;
wb_init(&valuebuf);
/* charcategory_T string corresponding to `valuebuf' */
xstrbuf_T ccbuf;
sb_init(&ccbuf);
bool indq = false; /* in a double quote? */
bool first = true; /* is the first word unit? */
const wchar_t *ss;
wchar_t *s;
/* When there are no positional parameters, expansion of ${@} contained in
* double-quotes is very special: The result is no fields. To handle this
* correctly, we do the following:
* 1. Remove the surrounding double-quotes if a parameter expansion inside
* them happens to expand to no fields.
* 2. Remove the empty field so that the final result is no fields rather
* than one empty field.
* `removedq' is for step 1 and `removeempty' for step 2. */
bool removedq = false, removeempty = false;
for (; w != NULL; w = w->next, first = false) {
switch (w->wu_type) {
case WT_STRING:
ss = w->wu_string;
if (first && (tilde == TT_SINGLE || tilde == TT_MULTI)) {
s = expand_tilde(&ss, w->next != NULL, tilde == TT_MULTI);
if (s != NULL) {
wb_catfree(&valuebuf, s);
fill_ccbuf(&valuebuf, &ccbuf,
CC_HARD_EXPANSION | (defaultcc & CC_QUOTED));
}
}
while (*ss != L'\0') {
switch (*ss) {
case L'"':
switch (quoting) {
case Q_WORD: case Q_DQPARAM:
break;
case Q_INDQ: case Q_LITERAL:
goto default_;
}
if (!indq) {
indq = true; /* entering a quotation */
removedq = false;
} else {
indq = false; /* leaving a quotation */
if (removedq && e.valuelist.length == 0 &&
wcscmp(valuebuf.contents, L"\"") == 0 &&
(ccbuf.contents[0] & CC_QUOTATION)) {
/* remove the corresponding opening double-quote */
wb_clear(&valuebuf);
sb_clear(&ccbuf);
removeempty = true;
break; /* and ignore the closing double-quote */
}
}
wb_wccat(&valuebuf, L'"');
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
break;
case L'\'':
if (quoting != Q_WORD || indq)
goto default_;
wb_wccat(&valuebuf, L'\'');
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
add_sq(&ss, &valuebuf, false);
assert(*ss == L'\'');
fill_ccbuf(&valuebuf, &ccbuf, defaultcc | CC_QUOTED);
wb_wccat(&valuebuf, L'\'');
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
break;
case L'$':
// Check for dollar-single-quotes.
if (quoting != Q_WORD || indq || ss[1] != '\'')
goto default_;
wb_wccat(&valuebuf, L'$');
wb_wccat(&valuebuf, L'\'');
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
wb_catfree(&valuebuf, interpret_dsq(&ss));
assert(*ss == L'\'');
fill_ccbuf(&valuebuf, &ccbuf, defaultcc | CC_QUOTED);
wb_wccat(&valuebuf, L'\'');
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
break;
case L'\\':
switch (quoting) {
case Q_WORD:
if (indq && wcschr(CHARS_ESCAPABLE, ss[1]) == NULL)
goto default_;
break;
case Q_DQPARAM:
if (wcschr(CHARS_ESCAPABLE "}", ss[1]) == NULL)
goto default_;
break;
case Q_INDQ:
if (wcschr(L"$`\\", ss[1]) == NULL)
goto default_;
break;
case Q_LITERAL:
goto default_;
}
wb_wccat(&valuebuf, L'\\');
sb_ccat(&ccbuf, defaultcc | CC_QUOTATION);
ss++;
if (*ss != L'\0') {
wb_wccat(&valuebuf, *ss++);
sb_ccat(&ccbuf, defaultcc | CC_QUOTED);
}
continue;
case L':':
if (indq || tilde != TT_MULTI)
goto default_;
/* perform tilde expansion after the colon */
goto tilde;
case L'=':
if (indq || tilde != TT_ASSIGN)
goto default_;
tilde = TT_MULTI;
/* perform tilde expansion after the equal */
tilde:
wb_wccat(&valuebuf, *ss);
sb_ccat(&ccbuf, defaultcc);
ss++;
s = expand_tilde(&ss, w->next != NULL, true);
if (s != NULL) {
wb_catfree(&valuebuf, s);
fill_ccbuf(&valuebuf, &ccbuf,
CC_HARD_EXPANSION | (defaultcc & CC_QUOTED));
}
continue;
default_:
default:
wb_wccat(&valuebuf, *ss);
sb_ccat(&ccbuf, defaultcc | (indq * CC_QUOTED));
break;
}
ss++;
}
break;
case WT_PARAM:;
struct expand_four_T e2 = expand_param(w->wu_param,
indq || quoting == Q_LITERAL || (defaultcc & CC_QUOTED));
if (e2.valuelist.contents == NULL)
goto failure;
if (e2.valuelist.length == 0) {
if (indq)
removedq = true;
else
removeempty = true;
}
merge_expand_four(&e2, &e, &valuebuf, &ccbuf);
break;
case WT_CMDSUB:
s = exec_command_substitution(&w->wu_cmdsub);
goto cat_s;
case WT_ARITH:
s = expand_single(w->wu_arith, TT_NONE, Q_INDQ, ES_NONE);
if (s != NULL)
s = evaluate_arithmetic(s);
cat_s:
if (s == NULL)
goto failure;
wb_catfree(&valuebuf, s);
fill_ccbuf(&valuebuf, &ccbuf, CC_SOFT_EXPANSION |
(indq * CC_QUOTED) | (defaultcc & CC_QUOTED));
break;
}
}
/* empty field removal */
if (removeempty && e.valuelist.length == 0 && valuebuf.length == 0) {
wb_destroy(&valuebuf);
sb_destroy(&ccbuf);
} else {
pl_add(&e.valuelist, wb_towcs(&valuebuf));
pl_add(&e.cclist, sb_tostr(&ccbuf));
}
return e;
failure:
sb_destroy(&ccbuf);
wb_destroy(&valuebuf);
plfree(pl_toary(&e.cclist), free);
plfree(pl_toary(&e.valuelist), free);
e.valuelist.contents = e.cclist.contents = NULL;
return e;
}
/* Appends to `e->ccbuf' as many `c's as needed to match the length with
* `e->valuebuf'. */
void fill_ccbuf(const xwcsbuf_T *restrict valuebuf, xstrbuf_T *restrict ccbuf,
charcategory_T c)
{
sb_ccat_repeat(ccbuf, c, valuebuf->length - ccbuf->length);
}
/* Performs tilde expansion.
* `ss' is a pointer to a pointer to the tilde character. The pointer is
* increased so that it points to the character right after the expanded string.
* The string pointed by the pointer pointed by `ss' should be contents of a
* word unit of type WT_STRING. Iff there is a next word unit, `hasnextwordunit'
* must be true.
* If `**ss' is not L'~' or expansion fails, this function has no side effects
* and returns NULL. If successful, `*ss' is incremented and the result is
* returned as a newly malloced string. */
wchar_t *expand_tilde(
const wchar_t **ss, bool hasnextwordunit, bool stopatcolon)
{
const wchar_t *s = *ss;
if (*s != L'~')
return NULL;
s++;
const wchar_t *end = wcspbrk(s, stopatcolon ? L"/:" : L"/");
wchar_t *username;
const wchar_t *home;
size_t usernamelen;
if (end != NULL) {
usernamelen = end - s;
} else {
if (hasnextwordunit)
return NULL;
usernamelen = wcslen(s);
}
username = xwcsndup(s, usernamelen);
if (username[0] == L'\0') {
/* empty user name: use $HOME */
home = getvar(L VAR_HOME);
goto finish;
} else if (wcspbrk(username, L"\"'\\") != 0) {
/* don't expand if the user name is quoted */
free(username);
return NULL;
}
if (!posixly_correct) {
if (username[0] == L'+' && username[1] == L'\0') {
home = getvar(L VAR_PWD);
goto finish;
}
if (username[0] == L'-' && username[1] == L'\0') {
home = getvar(L VAR_OLDPWD);
goto finish;
}
#if YASH_ENABLE_DIRSTACK
if (username[0] == L'+' || username[0] == L'-') {
size_t index;
if (parse_dirstack_index(username, &index, &home, false)
&& index != SIZE_MAX) {
goto finish;
}
}
#endif
}
home = get_home_directory(username, false);
finish:
free(username);
if (home == NULL)
return NULL;
*ss = s + usernamelen;
return xwcsdup(home);
}
/* Performs parameter expansion.
* If successful, the return value contains valid lists of pointers to newly
* malloced strings. Note that the lists may contain no strings.
* If unsuccessful, the lists have NULL `contents'. */
struct expand_four_T expand_param(const paramexp_T *p, bool indq)
{
/* parse indices first */
ssize_t startindex, endindex;
enum indextype_T indextype;
if (p->pe_start == NULL) {
startindex = 0, endindex = SSIZE_MAX, indextype = IDX_NONE;
} else {
wchar_t *start = expand_single(p->pe_start, TT_NONE, Q_WORD, ES_NONE);
if (start == NULL)
goto failure1;
indextype = parse_indextype(start);
if (indextype != IDX_NONE) {
startindex = 0, endindex = SSIZE_MAX;
free(start);
if (p->pe_end != NULL) {
xerror(0, Ngt("the parameter index is invalid"));
goto failure1;
}
} else if (!evaluate_index(start, &startindex)) {
goto failure1;
} else {
if (p->pe_end == NULL) {
endindex = (startindex == -1) ? SSIZE_MAX : startindex;
} else {
wchar_t *end = expand_single(
p->pe_end, TT_NONE, Q_WORD, ES_NONE);
if (end == NULL || !evaluate_index(end, &endindex))
goto failure1;
}
if (startindex == 0)
startindex = SSIZE_MAX;
else if (startindex >= 0)
startindex--;
}
}
/* Here, `startindex' and `endindex' are zero-based. `startindex' is
* included in the range but `endindex' is not. A negative index will be
* wrapped around the length. */
/* get the value of parameter or nested expansion */
struct get_variable_T v;
bool unset; /* parameter is not set? */
if (p->pe_type & PT_NEST) {
plist_T plist = expand_word(p->pe_nest);
if (plist.contents == NULL)
goto failure1;
v.type = (plist.length == 1) ? GV_SCALAR : GV_ARRAY;
v.count = plist.length;
v.values = pl_toary(&plist);
v.freevalues = true;
unset = false;
} else {
v = get_variable(p->pe_name);
if (v.type == GV_NOTFOUND) {
/* if the variable is not set, return empty string */
v.type = GV_SCALAR;
v.count = 1;
v.values = xmallocn(2, sizeof *v.values);
v.values[0] = xwcsdup(L"");
v.values[1] = NULL;
v.freevalues = true;
unset = true;
} else {
unset = false;
}
}
/* here, the contents of `v.values' are not escaped by backslashes. */
/* modify the elements of `v.values' according to the indices */
void **values; /* the result */
bool concat; /* concatenate array elements? */
switch (v.type) {
case GV_SCALAR:
assert(v.values != NULL && v.count == 1);
save_get_variable_values(&v);
if (indextype != IDX_NUMBER) {
trim_wstring(v.values[0], startindex, endindex);
} else {
size_t len = wcslen(v.values[0]);
free(v.values[0]);
v.values[0] = malloc_wprintf(L"%zu", len);
}
values = v.values, concat = false;
break;
case GV_ARRAY:
concat = false;
goto treat_array;
case GV_ARRAY_CONCAT:
concat = true;
treat_array:
switch (indextype) {
case IDX_CONCAT:
concat = true;
/* falls thru! */
case IDX_NONE:
case IDX_ALL:
if (startindex >= 0) {
#if SIZE_MAX >= SSIZE_MAX
if ((size_t) startindex > v.count)
#else
if (startindex > (ssize_t) v.count)
#endif
startindex = v.count;
} else {
startindex += v.count;
if (startindex < 0)
startindex = 0;
}
if (endindex < 0)
endindex += v.count + 1;
if (endindex < startindex)
endindex = startindex;
#if SSIZE_MAX > SIZE_MAX
else if (endindex > (ssize_t) SIZE_MAX)
endindex = SIZE_MAX;
#endif
assert(0 <= startindex && startindex <= endindex);
values = v.freevalues
? trim_array(v.values, startindex, endindex)
: plndup(v.values + startindex,
endindex - startindex, copyaswcs);
break;
case IDX_NUMBER:
if (v.freevalues)
plfree(v.values, free);
values = xmallocn(2, sizeof *values);
values[0] = malloc_wprintf(L"%zu", v.count);
values[1] = NULL;
concat = false;
break;
default:
assert(false);
}
break;
default:
assert(false);
}
/* if `PT_COLON' is true, empty string is treated as unset */
if (p->pe_type & PT_COLON)
if (values[0] == NULL ||
(((wchar_t *) values[0])[0] == L'\0' && values[1] == NULL))
unset = true;
/* PT_PLUS, PT_MINUS, PT_ASSIGN, PT_ERROR */
quoting_T substq = indq ? Q_DQPARAM : Q_WORD;
wchar_t *subst;
switch (p->pe_type & PT_MASK) {
case PT_PLUS:
if (!unset)
goto subst;
unset = false;
break;
case PT_MINUS:
if (unset) {
subst:
plfree(values, free);
return expand_four(p->pe_subst, TT_SINGLE, substq,
CC_SOFT_EXPANSION | (indq * CC_QUOTED));
}
break;
case PT_ASSIGN:
if (unset) {
plfree(values, free);
if (p->pe_type & PT_NEST) {
xerror(0,
Ngt("a nested parameter expansion cannot be assigned"));
goto failure1;
} else if (!is_name(p->pe_name)) {
xerror(0, Ngt("cannot assign to parameter `%ls' "
"in parameter expansion"),
p->pe_name);
goto failure1;
} else if ((v.type == GV_ARRAY_CONCAT)
|| (v.type == GV_ARRAY && startindex + 1 != endindex)) {
xerror(0, Ngt("the specified index does not support assignment "
"in the parameter expansion of array `%ls'"),
p->pe_name);
goto failure1;
}
subst = expand_single(p->pe_subst, TT_SINGLE, substq, ES_NONE);
if (subst == NULL)
goto failure1;
if (v.type != GV_ARRAY) {
assert(v.type == GV_NOTFOUND || v.type == GV_SCALAR);
if (!set_variable(
p->pe_name, xwcsdup(subst), SCOPE_GLOBAL, false)) {
free(subst);
goto failure1;
}
} else {
assert(0 <= startindex && (size_t) startindex <= v.count);
if (!set_array_element(p->pe_name, startindex, xwcsdup(subst))){
free(subst);
goto failure1;
}
}
values = xmallocn(2, sizeof *values);
values[0] = subst;
values[1] = NULL;
unset = false;
}
break;
case PT_ERROR:
if (unset) {
print_subst_as_error(p, substq);
goto failure2;
}
break;
}
if (unset && !shopt_unset) {
xerror(0, Ngt("parameter `%ls' is not set"), p->pe_name);
goto failure2;
}
/* PT_MATCH, PT_SUBST */
wchar_t *match;
switch (p->pe_type & PT_MASK) {
case PT_MATCH:
match = expand_single(p->pe_match, TT_SINGLE, Q_WORD, ES_QUOTED);
if (match == NULL)
goto failure2;
match_each(values, match, p->pe_type);
free(match);
break;
case PT_SUBST:
match = expand_single(p->pe_match, TT_SINGLE, Q_WORD, ES_QUOTED);
if (match == NULL)
goto failure2;
subst = expand_single(p->pe_subst, TT_SINGLE, Q_WORD, ES_NONE);
if (subst == NULL) {
free(match);
goto failure2;
}
subst_each(values, match, subst, p->pe_type);
free(match);
free(subst);
break;
}
/* concatenate the elements of `values' */
if (concat && indq)
values = concatenate_values_into_array(values, false);
/* PT_NUMBER */
if (p->pe_type & PT_NUMBER)
subst_length_each(values);
struct expand_four_T e;
pl_initwith(&e.valuelist, values, plcount(values));
pl_initwithmax(&e.cclist, e.valuelist.length);
/* create `e.cclist' contents */
charcategory_T cc = CC_SOFT_EXPANSION | (indq * CC_QUOTED);
for (size_t i = 0; i < e.valuelist.length; i++) {
xwcsbuf_T sbuf;
wb_initwith(&sbuf, e.valuelist.contents[i]);
size_t n = sbuf.length;
xstrbuf_T ccbuf;
sb_initwithmax(&ccbuf, n + 1);
sb_ccat_repeat(&ccbuf, cc, n);
if (indq && e.valuelist.length > 1) {
// keep the field from empty field removal by adding a dummy quote
wb_wccat(&sbuf, L'"');
sb_ccat(&ccbuf, cc | CC_QUOTATION);
}
e.valuelist.contents[i] = wb_towcs(&sbuf);
pl_add(&e.cclist, sb_tostr(&ccbuf));
}
return e;
failure2:
plfree(values, free);
failure1:
e.valuelist.contents = e.cclist.contents = NULL;
return e;
}
/* Returns IDX_ALL, IDX_CONCAT, IDX_NUMBER if `indexstr' is L"@", L"*",
* L"#" respectively. Otherwise returns IDX_NONE. */
enum indextype_T parse_indextype(const wchar_t *indexstr)
{
if (indexstr[0] != L'\0' && indexstr[1] == L'\0') {
switch (indexstr[0]) {
case L'@': return IDX_ALL;
case L'*': return IDX_CONCAT;
case L'#': return IDX_NUMBER;
}
}
return IDX_NONE;
}
/* Trims some leading and trailing characters of the wide string.
* Characters in the range [`startindex', `endindex') remain.
* Returns the string `s'. */
wchar_t *trim_wstring(wchar_t *s, ssize_t startindex, ssize_t endindex)
{
if (startindex == 0 && endindex == SSIZE_MAX)
return s;