-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordexp.c
1527 lines (1337 loc) · 34.3 KB
/
wordexp.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
/*
*@Author: Huzaifa Naseer
*/
/* required macro definition for popen() and pclose() */
#define _POSIX_C_SOURCE 200809L
#include "executor.h"
#include "shell.h"
#include "symtab/symtab.h"
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
/* special value to represent an invalid variable */
#define INVALID_VAR ((char *)-1)
/*
* convert the string *word to a cmd_token struct, so it can be passed to
* functions such as word_expand().
*
* returns the malloc'd cmd_token struct, or NULL if insufficient memory.
*/
struct word_s *make_word(char *str) {
/* alloc struct memory */
struct word_s *word = malloc(sizeof(struct word_s));
if (!word) {
return NULL;
}
/* alloc string memory */
size_t len = strlen(str);
char *data = malloc(len + 1);
if (!data) {
free(word);
return NULL;
}
/* copy string */
strcpy(data, str);
word->data = data;
word->len = len;
word->next = NULL;
/* return struct */
return word;
}
/*
* free the memory used by a list of words.
*/
void free_all_words(struct word_s *first) {
while (first) {
struct word_s *del = first;
first = first->next;
if (del->data) {
/* free the word text */
free(del->data);
}
/* free the word */
free(del);
}
}
/*
* convert a tree of tokens into a command string (i.e. re-create the original
* command line from the token tree.
*
* returns the malloc'd command string, or NULL if there is an error.
*/
char *wordlist_to_str(struct word_s *word) {
if (!word) {
return NULL;
}
size_t len = 0;
struct word_s *w = word;
while (w) {
len += w->len + 1;
w = w->next;
}
char *str = malloc(len + 1);
if (!str) {
return NULL;
}
char *str2 = str;
w = word;
while (w) {
sprintf(str2, "%s ", w->data);
str2 += w->len + 1;
w = w->next;
}
/* remove the last separator */
str2[-1] = '\0';
return str;
}
/*
* delete the character at the given index in the given str.
*/
void delete_char_at(char *str, size_t index) {
char *p1 = str + index;
char *p2 = p1 + 1;
while ((*p1++ = *p2++)) {
;
}
}
/*
* check if the given str is a valid name.. POSIX says a names can consist of
* alphanumeric chars and underscores, and start with an alphabetic char or
* underscore.
*
* returns 1 if str is a valid name, 0 otherwise.
*/
int is_name(char *str) {
/* names start with alpha char or an underscore... */
if (!isalpha(*str) && *str != '_') {
return 0;
}
/* ...and contain alphanumeric chars and/or underscores */
while (*++str) {
if (!isalnum(*str) && *str != '_') {
return 0;
}
}
return 1;
}
/*
* find the closing quote that matches the opening quote, which is the first
* char of the data string.
* sq_nesting is a flag telling us if we should allow single quote nesting
* (prohibited by POSIX, but allowed in ANSI-C strings).
*
* returns the zero-based index of the closing quote.. a return value of 0
* means we didn't find the closing quote.
*/
size_t find_closing_quote(char *data) {
/* check the type of quote we have */
char quote = data[0];
if (quote != '\'' && quote != '"' && quote != '`') {
return 0;
}
/* find the matching closing quote */
size_t i = 0, len = strlen(data);
while (++i < len) {
if (data[i] == quote) {
if (data[i - 1] == '\\') {
if (quote != '\'') {
continue;
}
}
return i;
}
}
return 0;
}
/*
* find the closing brace that matches the opening brace, which is the first
* char of the data string.
*
* returns the zero-based index of the closing brace.. a return value of 0
* means we didn't find the closing brace.
*/
size_t find_closing_brace(char *data) {
/* check the type of opening brace we have */
char opening_brace = data[0], closing_brace;
if (opening_brace != '{' && opening_brace != '(') {
return 0;
}
/* determine the closing brace according to the opening brace */
if (opening_brace == '{') {
closing_brace = '}';
} else {
closing_brace = ')';
}
/* find the matching closing brace */
size_t ob_count = 1, cb_count = 0;
size_t i = 0, len = strlen(data);
while (++i < len) {
if ((data[i] == '"') || (data[i] == '\'') || (data[i] == '`')) {
/* skip escaped quotes */
if (data[i - 1] == '\\') {
continue;
}
/* skip quoted substrings */
char quote = data[i];
while (++i < len) {
if (data[i] == quote && data[i - 1] != '\\') {
break;
}
}
if (i == len) {
return 0;
}
continue;
}
/* keep the count of opening and closing braces */
if (data[i - 1] != '\\') {
if (data[i] == opening_brace) {
ob_count++;
} else if (data[i] == closing_brace) {
cb_count++;
}
}
/* break when we have a matching number of opening and closing braces */
if (ob_count == cb_count) {
break;
}
}
if (ob_count != cb_count) {
return 0;
}
return i;
}
/*
* substitute the substring of s1, from character start to character end,
* with the s2 string.
*
* start should point to the first char to be deleted from s1.
* end should point to the last char to be deleted from s, NOT the
* char coming after it.
*
* returns the malloc'd new string, or NULL on error.
*/
char *substitute_str(char *s1, char *s2, size_t start, size_t end) {
/* get the prefix (the part before start) */
char before[start + 1];
strncpy(before, s1, start);
before[start] = '\0';
/* get the postfix (the part after end) */
size_t afterlen = strlen(s1) - end + 1;
char after[afterlen];
strcpy(after, s1 + end + 1);
/* alloc memory for the new string */
size_t totallen = start + afterlen + strlen(s2);
char *final = malloc(totallen + 1);
if (!final) {
fprintf(stderr,
"error: insufficient memory to perform variable substitution\n");
return NULL;
}
if (!totallen) /* empty string */
{
final[0] = '\0';
} else /* concatenate the three parts into one string */
{
strcpy(final, before);
strcat(final, s2);
strcat(final, after);
}
/* return the new string */
return final;
}
int substitute_word(char **pstart, char **p, size_t len, char *(func)(char *),
int add_quotes) {
/* extract the word to be substituted */
char *tmp = malloc(len + 1);
if (!tmp) {
(*p) += len;
return 0;
}
strncpy(tmp, *p, len);
tmp[len--] = '\0';
/* and expand it */
char *tmp2;
if (func) {
tmp2 = func(tmp);
if (tmp2 == INVALID_VAR) {
tmp2 = NULL;
}
if (tmp2) {
free(tmp);
}
} else {
tmp2 = tmp;
}
/* error expanding the string. keep the original string as-is */
if (!tmp2) {
(*p) += len;
free(tmp);
return 0;
}
/* save our current position in the word */
size_t i = (*p) - (*pstart);
/* substitute the expanded word */
tmp = quote_val(tmp2, add_quotes);
free(tmp2);
if (tmp) {
/* substitute the expanded word */
if ((tmp2 = substitute_str(*pstart, tmp, i, i + len))) {
/* adjust our pointer to point to the new string */
free(*pstart);
(*pstart) = tmp2;
len = strlen(tmp);
}
free(tmp);
}
/* adjust our pointer to point to the new string */
(*p) = (*pstart) + i + len - 1;
return 1;
}
/*
* perform word expansion on a single word, pointed to by orig_word.
*
* returns the head of the linked list of the expanded fields and stores the
* last field in the tail pointer.
*/
struct word_s *word_expand(char *orig_word) {
if (!orig_word) {
return NULL;
}
if (!*orig_word) {
return make_word(orig_word);
}
char *pstart = malloc(strlen(orig_word) + 1);
if (!pstart) {
return NULL;
}
strcpy(pstart, orig_word);
char *p = pstart, *p2;
char *tmp;
char c;
size_t i = 0;
size_t len;
int in_double_quotes = 0;
int in_var_assign = 0;
int var_assign_eq = 0;
int expanded = 0;
char *(*func)(char *);
do {
switch (*p) {
case '~':
/* don't perform tilde expansion inside double quotes */
if (in_double_quotes) {
break;
}
/* expand a tilde prefix only if:
* - it is the first unquoted char in the string.
* - it is part of a variable assignment, and is preceded by the first
* equals sign or a colon.
*/
if (p == pstart ||
(in_var_assign &&
(p[-1] == ':' || (p[-1] == '=' && var_assign_eq == 1)))) {
/* find the end of the tilde prefix */
int tilde_quoted = 0;
int endme = 0;
p2 = p + 1;
while (*p2) {
switch (*p2) {
case '\\':
tilde_quoted = 1;
p2++;
break;
case '"':
case '\'':
i = find_closing_quote(p2);
if (i) {
tilde_quoted = 1;
p2 += i;
}
break;
case '/':
endme = 1;
break;
case ':':
if (in_var_assign) {
endme = 1;
}
break;
}
if (endme) {
break;
}
p2++;
}
/* if any part of the prefix is quoted, no expansion is done */
if (tilde_quoted) {
/* just skip the tilde prefix */
p = p2;
break;
}
/* otherwise, extract the prefix */
len = p2 - p;
substitute_word(&pstart, &p, len, tilde_expand, !in_double_quotes);
expanded = 1;
}
break;
case '"':
/* toggle quote mode */
in_double_quotes = !in_double_quotes;
break;
case '=':
/* skip it if inside double quotes */
if (in_double_quotes) {
break;
}
/* check the previous string is a valid var name */
len = p - pstart;
tmp = malloc(len + 1);
if (!tmp) {
fprintf(stderr, "error: insufficient memory for internal buffers\n");
break;
}
strncpy(tmp, pstart, len);
tmp[len] = '\0';
/*
* if the string before '=' is a valid var name, we have a variable
* assignment.. we set in_var_assign to indicate that, and we set
* var_assign_eq which indicates this is the first equals sign (we use
* this when performing tilde expansion -- see code above).
*/
if (is_name(tmp)) {
in_var_assign = 1;
var_assign_eq++;
}
free(tmp);
break;
case '\\':
/* skip backslash (we'll remove it later on) */
p++;
break;
case '\'':
/* if inside double quotes, treat the single quote as a normal char */
if (in_double_quotes) {
break;
}
/* skip everything, up to the closing single quote */
p += find_closing_quote(p);
break;
case '`':
/* find the closing back quote */
if ((len = find_closing_quote(p)) == 0) {
/* not found. bail out */
break;
}
/* otherwise, extract the command and substitute its output */
substitute_word(&pstart, &p, len + 1, command_substitute, 0);
expanded = 1;
break;
/*
* the $ sign might introduce:
* - parameter expansions: ${var} or $var
* - command substitutions: $()
* - arithmetic expansions: $(())
*/
case '$':
c = p[1];
switch (c) {
case '{':
/* find the closing quote */
if ((len = find_closing_brace(p + 1)) == 0) {
/* not found. bail out */
break;
}
/*
* calling var_expand() might return an INVALID_VAR result which
* makes the following call fail.
*/
if (!substitute_word(&pstart, &p, len + 2, var_expand, 0)) {
free(pstart);
return NULL;
}
expanded = 1;
break;
/*
* arithmetic expansion $(()) or command substitution $().
*/
case '(':
/* check if we have one or two opening braces */
i = 0;
if (p[2] == '(') {
i++;
}
/* find the closing quote */
if ((len = find_closing_brace(p + 1)) == 0) {
/* not found. bail out */
break;
}
/*
* otherwise, extract the expression and substitute its value.
* if we have one brace (i == 0), we'll perform command substitution.
* otherwise, arithmetic expansion.
*/
func = i ? arithm_expand : command_substitute;
substitute_word(&pstart, &p, len + 2, func, 0);
expanded = 1;
break;
default:
/* var names must start with an alphabetic char or _ */
if (!isalpha(p[1]) && p[1] != '_') {
break;
}
p2 = p + 1;
/* get the end of the var name */
while (*p2) {
if (!isalnum(*p2) && *p2 != '_') {
break;
}
p2++;
}
/* empty name */
if (p2 == p + 1) {
break;
}
/* perform variable expansion */
substitute_word(&pstart, &p, p2 - p, var_expand, 0);
expanded = 1;
break;
}
break;
default:
if (isspace(*p) && !in_double_quotes) {
expanded = 1;
}
break;
}
} while (*(++p));
/* if we performed word expansion, do field splitting */
struct word_s *words = NULL;
if (expanded) {
words = field_split(pstart);
}
/* no expansion done, or no field splitting done */
if (!words) {
words = make_word(pstart);
/* error making word struct */
if (!words) {
fprintf(stderr, "error: insufficient memory\n");
free(pstart);
return NULL;
}
}
free(pstart);
/* perform pathname expansion and quote removal */
words = pathnames_expand(words);
remove_quotes(words);
/* return the expanded list */
return words;
}
/*
* perform tilde expansion.
*
* returns the malloc'd expansion of the tilde prefix, NULL if expansion failed.
*/
char *tilde_expand(char *s) {
char *home = NULL;
size_t len = strlen(s);
char *s2 = NULL;
struct symtab_entry_s *entry;
/* null tilde prefix. substitute with the value of home */
if (len == 1) {
entry = get_symtab_entry("HOME");
if (entry && entry->val) {
home = entry->val;
} else {
/*
* POSIX doesn't say what to do if $HOME is null/unset.. we follow
* what bash does, which is searching our home directory in the password
* database.
*/
struct passwd *pass;
pass = getpwuid(getuid());
if (pass) {
/* get the value of home */
home = pass->pw_dir;
}
}
} else {
/* we have a login name */
struct passwd *pass;
pass = getpwnam(s + 1);
if (pass) {
home = pass->pw_dir;
}
}
/* we have a NULL value */
if (!home) {
return NULL;
}
/* return the home dir we've found */
s2 = malloc(strlen(home) + 1);
if (!s2) {
return NULL;
}
strcpy(s2, home);
return s2;
}
/*
* perform variable (parameter) expansion.
* our options are:
* syntax POSIX description var defined var undefined
* ====== ================= =========== =============
* $var Substitute var nothing
* ${var} Substitute var nothing
* ${var:-thing} Use Deflt Values var thing (var unchanged)
* ${var:=thing} Assgn Deflt Values var thing (var set to thing)
* ${var:?message} Error if NULL/Unset var print message and exit
* shell, (if message is empty, print "var: parameter not set")
* ${var:+thing} Use Alt. Value thing nothing
* ${#var} Calculate String Length
*
* Using the same options in the table above, but without the colon, results in
* a test for a parameter that is unset. using the colon results in a test for a
* parameter that is unset or null.
*
* TODO: we should test our implementation of the following string processing
* functions (see section 2.6.2 - Parameter Expansion in POSIX):
*
* ${parameter%[word]} Remove Smallest Suffix Pattern
* ${parameter%%[word]} Remove Largest Suffix Pattern
* ${parameter#[word]} Remove Smallest Prefix Pattern
* ${parameter##[word]} Remove Largest Prefix Pattern
*/
/*
* perform variable (parameter) expansion.
*
* returns an malloc'd string of the expanded variable value, or NULL if the
* variable is not defined or the expansion failed.
*
* this function should not be called directly by any function outside of this
* module (hence the double underscores that prefix the function name).
*/
char *var_expand(char *orig_var_name) {
/* sanity check */
if (!orig_var_name) {
return NULL;
}
/*
* if the var substitution is in the $var format, remove the $.
* if it's in the ${var} format, remove the ${}.
*/
/* skip the $ */
orig_var_name++;
size_t len = strlen(orig_var_name);
if (*orig_var_name == '{') {
/* remove the } */
orig_var_name[len - 1] = '\0';
orig_var_name++;
}
/* check we don't have an empty varname */
if (!*orig_var_name) {
return NULL;
}
int get_length = 0;
/* if varname starts with #, we need to get the string length */
if (*orig_var_name == '#') {
/* use of '#' should come with omission of ':' */
if (strchr(orig_var_name, ':')) {
fprintf(stderr, "error: invalid variable substitution: %s\n",
orig_var_name);
return INVALID_VAR;
}
get_length = 1;
orig_var_name++;
}
/* check we don't have an empty varname */
if (!*orig_var_name) {
return NULL;
}
/*
* search for a colon, which we use to separate the variable name from the
* value or substitution we are going to perform on the variable.
*/
char *sub = strchr(orig_var_name, ':');
if (!sub) /* we have a substitution without a colon */
{
/* search for the char that indicates what type of substitution we need to
* do */
sub = strchr_any(orig_var_name, "-=?+%#");
}
/* get the length of the variable name (without the substitution part) */
len = sub ? (size_t)(sub - orig_var_name) : strlen(orig_var_name);
/* if we have a colon+substitution, skip the colon */
if (sub && *sub == ':') {
sub++;
}
/* copy the varname to a buffer */
char var_name[len + 1];
strncpy(var_name, orig_var_name, len);
var_name[len] = '\0';
/*
* commence variable substitution.
*/
char *empty_val = "";
char *tmp = NULL;
char setme = 0;
struct symtab_entry_s *entry = get_symtab_entry(var_name);
tmp = (entry && entry->val && entry->val[0]) ? entry->val : empty_val;
/*
* first case: variable is unset or empty.
*/
if (!tmp || tmp == empty_val) {
/* do we have a substitution clause? */
if (sub && *sub) {
/* check the substitution operation we need to perform */
switch (sub[0]) {
case '-': /* use default value */
tmp = sub + 1;
break;
case '=': /* assign the variable a value */
/*
* NOTE: only variables, not positional or special parameters can be
* assigned this way (we'll fix this later).
*/
tmp = sub + 1;
/*
* assign the EXPANSION OF tmp, not tmp
* itself, to var_name (we'll set the value below).
*/
setme = 1;
break;
case '?': /* print error msg if variable is null/unset */
if (sub[1] == '\0') {
fprintf(stderr, "error: %s: parameter not set\n", var_name);
} else {
fprintf(stderr, "error: %s: %s\n", var_name, sub + 1);
}
return INVALID_VAR;
/* use alternative value (we don't have alt. value here) */
case '+':
return NULL;
/*
* pattern matching notation. can't match anything
* if the variable is not defined, now can we?
*/
case '#':
case '%':
break;
default: /* unknown operator */
return INVALID_VAR;
}
}
/* no substitution clause. return NULL as the variable is unset/null */
else {
tmp = empty_val;
}
}
/*
* second case: variable is set/not empty.
*/
else {
/* do we have a substitution clause? */
if (sub && *sub) {
/* check the substitution operation we need to perform */
switch (sub[0]) {
case '-': /* use default value */
case '=': /* assign the variable a value */
case '?': /* print error msg if variable is null/unset */
break;
/* use alternative value */
case '+':
tmp = sub + 1;
break;
/*
* for the prefix and suffix matching routines (below).
* bash expands the pattern part, but ksh doesn't seem to do
* the same (as far as the manpage is concerned). we follow ksh.
*/
case '%': /* match suffix */
sub++;
/* perform word expansion on the value */
char *p = word_expand_to_str(tmp);
/* word expansion failed */
if (!p) {
return INVALID_VAR;
}
int longest = 0;
/* match the longest or shortest suffix */
if (*sub == '%') {
longest = 1, sub++;
}
/* perform the match */
if ((len = match_suffix(sub, p, longest)) == 0) {
return p;
}
/* return the match */
char *p2 = malloc(len + 1);
if (p2) {
strncpy(p2, p, len);
p2[len] = '\0';
}
free(p);
return p2;
case '#': /* match prefix */
sub++;
/* perform word expansion on the value */
p = word_expand_to_str(tmp);
/* word expansion failed */
if (!p) {
return INVALID_VAR;
}
longest = 0;
/* match the longest or shortest suffix */
if (*sub == '#') {
longest = 1, sub++;
}
/* perform the match */
if ((len = match_prefix(sub, p, longest)) == 0) {
return p;
}
/* return the match */
p2 = malloc(strlen(p) - len + 1);
if (p2) {
strcpy(p2, p + len);
}
free(p);
return p2;
default: /* unknown operator */
return INVALID_VAR;
}
}
/* no substitution clause. return the variable's original value */
}
/*
* we have substituted the variable's value. now go POSIX style on it.
*/
int expanded = 0;
if (tmp) {
if ((tmp = word_expand_to_str(tmp))) {
expanded = 1;
}
}
/* do we need to set new value to the variable? */
if (setme) {
/* if variable not defined, add it now */
if (!entry) {
entry = add_to_symtab(var_name);
}
/* and set its value */
if (entry) {
symtab_entry_setval(entry, tmp);
}
}
char buf[32];
char *p = NULL;
if (get_length) {
if (!tmp) {
sprintf(buf, "0");
} else {
sprintf(buf, "%lu", strlen(tmp));
}
/* get a copy of the buffer */
p = malloc(strlen(buf) + 1);
if (p) {
strcpy(p, buf);
}
} else {
/* "normal" variable value */
p = malloc(strlen(tmp) + 1);
if (p) {
strcpy(p, tmp);
}
}
/* free the expanded word list */
if (expanded) {
free(tmp);
}
/* return the result */
return p ?: INVALID_VAR;
}
/*
* perform command substitutions.
* the backquoted flag tells if we are called from a backquoted command
* substitution:
*
* `command`
*
* or a regular one:
*
* $(command)
*/
char *command_substitute(char *orig_cmd) {
char b[1024];
size_t bufsz = 0;
char *buf = NULL;
char *p = NULL;
int i = 0;
int backquoted = (*orig_cmd == '`');
/*
* fix cmd in the backquoted version.. we skip the first char (if using the
* old, backquoted version), or the first two chars (if using the POSIX
* version).
*/
char *cmd = malloc(strlen(orig_cmd + 1));
if (!cmd) {
fprintf(stderr,
"error: insufficient memory to perform command substitution\n");
return NULL;
}
strcpy(cmd, orig_cmd + (backquoted ? 1 : 2));
char *cmd2 = cmd;
size_t cmdlen = strlen(cmd);
if (backquoted) {
/* remove the last back quote */
if (cmd[cmdlen - 1] == '`') {
cmd[cmdlen - 1] = '\0';
}
/* fix the backslash-escaped chars */
char *p1 = cmd;
do {
if (*p1 == '\\' && (p1[1] == '$' || p1[1] == '`' || p1[1] == '\\')) {
char *p2 = p1, *p3 = p1 + 1;
while ((*p2++ = *p3++)) {
;