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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
|
/*
* Expansion - quoting, separation, substitution, globbing
*/
#include <ctype.h>
#include <glob.h>
#include "sh.h"
#include <pwd.h>
#include "ksh_dir.h"
#include "ksh_stat.h"
/*
* string expansion
*
* first pass: quoting, IFS separation, ~, ${}, $() and $(()) substitution.
* second pass: alternation ({,}), filename expansion (*?[]).
*/
/* expansion generator state */
typedef struct Expand {
/* int type; */ /* see expand() */
const char *str; /* string */
union {
const char **strv;/* string[] */
struct shf *shf; /* file */
} u; /* source */
struct tbl *var; /* variable in ${var..} */
short split; /* split "$@" / call waitlast $() */
} Expand;
#define XBASE 0 /* scanning original */
#define XSUB 1 /* expanding ${} string */
#define XARGSEP 2 /* ifs0 between "$*" */
#define XARG 3 /* expanding $*, $@ */
#define XCOM 4 /* expanding $() */
#define XNULLSUB 5 /* "$@" when $# is 0 (don't generate word) */
#define XSUBMID 6 /* middle of expanding ${} */
/* States used for field splitting */
#define IFS_WORD 0 /* word has chars (or quotes) */
#define IFS_WS 1 /* have seen IFS white-space */
#define IFS_NWS 2 /* have seen IFS non-white-space */
static int varsub(Expand *, const char *, const char *, int *, int *);
static int comsub(Expand *, const char *);
static char *trimsub(char *, char *, int);
static void tmpglob(char *, XPtrV *, int);
static void globit(XString *, char **, char *, XPtrV *, int);
static const char *maybe_expand_tilde(const char *, XString *, char **, int);
static char *tilde(char *);
static char *homedir(char *);
#ifdef BRACE_EXPAND
static void alt_expand(XPtrV *, char *, char *, char *, int));
#endif
/* compile and expand word */
char *
substitute(const char *cp, int f)
{
struct source *s, *sold;
sold = source;
s = pushs(SWSTR, ATEMP);
s->start = s->str = cp;
source = s;
if (yylex(ONEWORD) != LWORD)
internal_errorf(1, "substitute");
source = sold;
afree(s, ATEMP);
return evalstr(yylval.cp, f);
}
/*
* expand arg-list
*/
char **
eval(const char **ap, int f)
{
XPtrV w;
if (*ap == NULL) {
union mksh_ccphack vap;
vap.ro = ap;
return (vap.rw);
}
XPinit(w, 32);
XPput(w, NULL); /* space for shell name */
#ifdef SHARPBANG
XPput(w, NULL); /* and space for one arg */
#endif
while (*ap != NULL)
expand(*ap++, &w, f);
XPput(w, NULL);
#ifdef SHARPBANG
return (char **) XPclose(w) + 2;
#else
return (char **) XPclose(w) + 1;
#endif
}
/*
* expand string
*/
char *
evalstr(const char *cp, int f)
{
XPtrV w;
char *dp = null;
XPinit(w, 1);
expand(cp, &w, f);
if (XPsize(w))
dp = *XPptrv(w);
XPfree(w);
return (dp);
}
/*
* expand string - return only one component
* used from iosetup to expand redirection files
*/
char *
evalonestr(const char *cp, int f)
{
XPtrV w;
char *rv;
XPinit(w, 1);
expand(cp, &w, f);
switch (XPsize(w)) {
case 0:
rv = null;
break;
case 1:
rv = (char *) *XPptrv(w);
break;
default:
rv = evalstr(cp, f&~DOGLOB);
break;
}
XPfree(w);
return (rv);
}
/* for nested substitution: ${var:=$var2} */
typedef struct SubType {
short stype; /* [=+-?%#] action after expanded word */
short base; /* begin position of expanded word */
short f; /* saved value of f (DOPAT, etc) */
struct tbl *var; /* variable for ${var..} */
short quote; /* saved value of quote (for ${..[%#]..}) */
struct SubType *prev; /* old type */
struct SubType *next; /* poped type (to avoid re-allocating) */
} SubType;
void
expand(const char *cp, /* input word */
XPtrV *wp, /* output words */
int f) /* DO* flags */
{
int UNINITIALIZED(c);
int type; /* expansion type */
int quote = 0; /* quoted */
XString ds; /* destination string */
char *dp; /* destination */
const char *sp; /* source */
int fdo, word; /* second pass flags; have word */
int doblank; /* field splitting of parameter/command subst */
Expand x = { /* expansion variables */
NULL, { NULL }, NULL, 0
};
SubType st_head, *st;
int UNINITIALIZED(newlines); /* For trailing newlines in COMSUB */
int saw_eq, tilde_ok;
int make_magic;
size_t len;
if (cp == NULL)
internal_errorf(1, "expand(NULL)");
/* for alias, readonly, set, typeset commands */
if ((f & DOVACHECK) && is_wdvarassign(cp)) {
f &= ~(DOVACHECK|DOBLANK|DOGLOB|DOTILDE);
f |= DOASNTILDE;
}
if (Flag(FNOGLOB))
f &= ~DOGLOB;
#ifdef BRACE_EXPAND
if (Flag(FBRACEEXPAND) && (f & DOGLOB))
f |= DOBRACE_;
#endif /* BRACE_EXPAND */
Xinit(ds, dp, 128, ATEMP); /* init dest. string */
type = XBASE;
sp = cp;
fdo = 0;
saw_eq = 0;
tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0; /* must be 1/0 */
doblank = 0;
make_magic = 0;
word = (f&DOBLANK) ? IFS_WS : IFS_WORD;
st_head.next = NULL;
st_head.quote = 0;
st = &st_head;
while (1) {
Xcheck(ds, dp);
switch (type) {
case XBASE: /* original prefixed string */
c = *sp++;
switch (c) {
case EOS:
c = 0;
break;
case CHAR:
c = *sp++;
break;
case QCHAR:
quote |= 2; /* temporary quote */
c = *sp++;
break;
case OQUOTE:
word = IFS_WORD;
tilde_ok = 0;
quote = 1;
continue;
case CQUOTE:
quote = st->quote; /* XXX correct? */
continue;
case COMSUB:
tilde_ok = 0;
if (f & DONTRUNCOMMAND) {
word = IFS_WORD;
*dp++ = '$'; *dp++ = '(';
while (*sp != '\0') {
Xcheck(ds, dp);
*dp++ = *sp++;
}
*dp++ = ')';
} else {
type = comsub(&x, sp);
if (type == XCOM && (f&DOBLANK))
doblank++;
sp = strchr(sp, 0) + 1;
newlines = 0;
}
continue;
case EXPRSUB:
word = IFS_WORD;
tilde_ok = 0;
if (f & DONTRUNCOMMAND) {
*dp++ = '$'; *dp++ = '('; *dp++ = '(';
while (*sp != '\0') {
Xcheck(ds, dp);
*dp++ = *sp++;
}
*dp++ = ')'; *dp++ = ')';
} else {
struct tbl v;
char *p;
v.flag = DEFINED|ISSET|INTEGER;
v.type = 10; /* not default */
v.name[0] = '\0';
v_evaluate(&v, substitute(sp, 0),
KSH_UNWIND_ERROR);
sp = strchr(sp, 0) + 1;
for (p = str_val(&v); *p; ) {
Xcheck(ds, dp);
*dp++ = *p++;
}
}
continue;
case OSUBST: /* ${{#}var{:}[=+-?#%]word} */
/* format is:
* OSUBST [{x] plain-variable-part \0
* compiled-word-part CSUBST [}x]
* This is where all syntax checking gets done...
*/
{
const char *varname = ++sp; /* skip the { or x (}) */
int stype;
int slen = 0;
sp = ((const char *)strchr(sp, '\0')) + 1; /* skip variable */
type = varsub(&x, varname, sp, &stype, &slen);
if (type < 0) {
char *beg, *end, *str;
unwind_substsyn:
sp = varname - 2; /* restore sp */
end = (beg = wdcopy(sp, ATEMP)) +
(wdscan(sp, CSUBST) - sp);
/* ({) the } or x is already skipped */
if (end < wdscan(beg, EOS))
*end = EOS;
str = snptreef(NULL, 64, "%S", beg);
afree(beg, ATEMP);
errorf("%s: bad substitution", str);
}
if (f & DOBLANK)
doblank++;
tilde_ok = 0;
if (type == XBASE) { /* expand? */
if (!st->next) {
SubType *newst;
newst = (SubType *) alloc(
sizeof(SubType), ATEMP);
newst->next = NULL;
newst->prev = st;
st->next = newst;
}
st = st->next;
st->stype = stype;
st->base = Xsavepos(ds, dp);
st->f = f;
st->var = x.var;
st->quote = quote;
/* skip qualifier(s) */
if (stype)
sp += slen;
switch (stype & 0x7f) {
case '#':
case '%':
/* ! DOBLANK,DOBRACE_,DOTILDE */
f = DOPAT | (f&DONTRUNCOMMAND)
| DOTEMP_;
quote = 0;
/* Prepend open pattern (so |
* in a trim will work as
* expected)
*/
/* *dp++ = MAGIC;
*dp++ = '@' + 0x80; */
break;
case '=':
/* Enabling tilde expansion
* after :'s here is
* non-standard ksh, but is
* consistent with rules for
* other assignments. Not
* sure what POSIX thinks of
* this.
* Not doing tilde expansion
* for integer variables is a
* non-POSIX thing - makes
* sense though, since ~ is
* a arithmetic operator.
*/
if (!(x.var->flag & INTEGER))
f |= DOASNTILDE|DOTILDE;
f |= DOTEMP_;
/* These will be done after the
* value has been assigned.
*/
f &= ~(DOBLANK|DOGLOB|DOBRACE_);
tilde_ok = 1;
break;
case '?':
f &= ~DOBLANK;
f |= DOTEMP_;
/* fall through */
default:
/* Enable tilde expansion */
tilde_ok = 1;
f |= DOTILDE;
}
} else
/* skip word */
sp = (char *) wdscan(sp, CSUBST);
continue;
}
case CSUBST: /* only get here if expanding word */
sp++; /* ({) skip the } or x */
tilde_ok = 0; /* in case of ${unset:-} */
*dp = '\0';
quote = st->quote;
f = st->f;
if (f&DOBLANK)
doblank--;
switch (st->stype&0x7f) {
case '#':
case '%':
/* Append end-pattern */
/* *dp++ = MAGIC; *dp++ = ')'; */ *dp = '\0';
dp = Xrestpos(ds, dp, st->base);
/* Must use st->var since calling
* global would break things
* like x[i+=1].
*/
x.str = trimsub(str_val(st->var),
dp, st->stype);
type = XSUB;
if (f&DOBLANK)
doblank++;
st = st->prev;
continue;
case '=':
/* Restore our position and substitute
* the value of st->var (may not be
* the assigned value in the presence
* of integer/right-adj/etc attributes).
*/
dp = Xrestpos(ds, dp, st->base);
/* Must use st->var since calling
* global would cause with things
* like x[i+=1] to be evaluated twice.
*/
/* Note: not exported by FEXPORT
* in at&t ksh.
*/
/* XXX POSIX says readonly is only
* fatal for special builtins (setstr
* does readonly check).
*/
len = strlen(dp) + 1;
setstr(st->var,
debunk((char *) alloc(len, ATEMP),
dp, len), KSH_UNWIND_ERROR);
x.str = str_val(st->var);
type = XSUB;
if (f&DOBLANK)
doblank++;
st = st->prev;
continue;
case '?':
{
char *s = Xrestpos(ds, dp, st->base);
errorf("%s: %s", st->var->name,
dp == s ?
"parameter null or not set" :
(debunk(s, s, strlen(s) + 1), s));
}
}
st = st->prev;
type = XBASE;
continue;
case OPAT: /* open pattern: *(foo|bar) */
/* Next char is the type of pattern */
make_magic = 1;
c = *sp++ + 0x80;
break;
case SPAT: /* pattern separator (|) */
make_magic = 1;
c = '|';
break;
case CPAT: /* close pattern */
make_magic = 1;
c = /*(*/ ')';
break;
}
break;
case XNULLSUB:
/* Special case for "$@" (and "${foo[@]}") - no
* word is generated if $# is 0 (unless there is
* other stuff inside the quotes).
*/
type = XBASE;
if (f&DOBLANK) {
doblank--;
/* not really correct: x=; "$x$@" should
* generate a null argument and
* set A; "${@:+}" shouldn't.
*/
if (dp == Xstring(ds, dp))
word = IFS_WS;
}
continue;
case XSUB:
case XSUBMID:
if ((c = *x.str++) == 0) {
type = XBASE;
if (f&DOBLANK)
doblank--;
continue;
}
break;
case XARGSEP:
type = XARG;
quote = 1;
case XARG:
if ((c = *x.str++) == '\0') {
/* force null words to be created so
* set -- '' 2 ''; foo "$@" will do
* the right thing
*/
if (quote && x.split)
word = IFS_WORD;
if ((x.str = *x.u.strv++) == NULL) {
type = XBASE;
if (f&DOBLANK)
doblank--;
continue;
}
c = ifs0;
if (c == 0) {
if (quote && !x.split)
continue;
c = ' ';
}
if (quote && x.split) {
/* terminate word for "$@" */
type = XARGSEP;
quote = 0;
}
}
break;
case XCOM:
if (newlines) { /* Spit out saved nl's */
c = '\n';
--newlines;
} else {
while ((c = shf_getc(x.u.shf)) == 0 || c == '\n')
if (c == '\n')
newlines++; /* Save newlines */
if (newlines && c != EOF) {
shf_ungetc(c, x.u.shf);
c = '\n';
--newlines;
}
}
if (c == EOF) {
newlines = 0;
shf_close(x.u.shf);
if (x.split)
subst_exstat = waitlast();
type = XBASE;
if (f&DOBLANK)
doblank--;
continue;
}
break;
}
/* check for end of word or IFS separation */
if (c == 0 || (!quote && (f & DOBLANK) && doblank &&
!make_magic && ctype(c, C_IFS))) {
/* How words are broken up:
* | value of c
* word | ws nws 0
* -----------------------------------
* IFS_WORD w/WS w/NWS w
* IFS_WS -/WS w/NWS -
* IFS_NWS -/NWS w/NWS w
* (w means generate a word)
* Note that IFS_NWS/0 generates a word (at&t ksh
* doesn't do this, but POSIX does).
*/
if (word == IFS_WORD ||
(!ctype(c, C_IFSWS) && c && word == IFS_NWS)) {
char *p;
*dp++ = '\0';
p = Xclose(ds, dp);
#ifdef BRACE_EXPAND
if (fdo & DOBRACE_)
/* also does globbing */
alt_expand(wp, p, p,
p + Xlength(ds, (dp - 1)),
fdo | (f & DOMARKDIRS));
else
#endif /* BRACE_EXPAND */
if (fdo & DOGLOB)
tmpglob(p, wp, f & DOMARKDIRS);
else if ((f & DOPAT) || !(fdo & DOMAGIC_))
XPput(*wp, p);
else
XPput(*wp, debunk(p, p, strlen(p) + 1));
fdo = 0;
saw_eq = 0;
tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0;
if (c != 0)
Xinit(ds, dp, 128, ATEMP);
}
if (c == 0)
return;
if (word != IFS_NWS)
word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
} else {
if (type == XSUB) {
if (word == IFS_NWS &&
Xlength(ds, dp) == 0) {
char *p;
*(p = alloc(1, ATEMP)) = '\0';
XPput(*wp, p);
}
type = XSUBMID;
}
/* age tilde_ok info - ~ code tests second bit */
tilde_ok <<= 1;
/* mark any special second pass chars */
if (!quote)
switch (c) {
case '[':
case NOT:
case '-':
case ']':
/* For character classes - doesn't hurt
* to have magic !,-,]'s outside of
* [...] expressions.
*/
if (f & (DOPAT | DOGLOB)) {
fdo |= DOMAGIC_;
if (c == '[')
fdo |= f & DOGLOB;
*dp++ = MAGIC;
}
break;
case '*':
case '?':
if (f & (DOPAT | DOGLOB)) {
fdo |= DOMAGIC_ | (f & DOGLOB);
*dp++ = MAGIC;
}
break;
#ifdef BRACE_EXPAND
case OBRACE:
case ',':
case CBRACE:
if ((f & DOBRACE_) && (c == OBRACE
|| (fdo & DOBRACE_)))
{
fdo |= DOBRACE_|DOMAGIC_;
*dp++ = MAGIC;
}
break;
#endif /* BRACE_EXPAND */
case '=':
/* Note first unquoted = for ~ */
if (!(f & DOTEMP_) && !saw_eq && (f & DOASNTILDE)) {
saw_eq = 1;
tilde_ok = 1;
}
break;
case PATHSEP: /* : */
/* Note unquoted : for ~ */
if (!(f & DOTEMP_) && (f & DOASNTILDE))
tilde_ok = 1;
break;
case '~':
/* tilde_ok is reset whenever
* any of ' " $( $(( ${ } are seen.
* Note that tilde_ok must be preserved
* through the sequence ${A=a=}~
*/
if (type == XBASE
&& (f & (DOTILDE|DOASNTILDE))
&& (tilde_ok & 2))
{
const char *p;
char *dp_x;
dp_x = dp;
p = maybe_expand_tilde(sp,
&ds, &dp_x,
f & DOASNTILDE);
if (p) {
if (dp != dp_x)
word = IFS_WORD;
dp = dp_x;
sp = p;
continue;
}
}
break;
}
else
quote &= ~2; /* undo temporary */
if (make_magic) {
make_magic = 0;
fdo |= DOMAGIC_ | (f & DOGLOB);
*dp++ = MAGIC;
} else if (ISMAGIC(c)) {
fdo |= DOMAGIC_;
*dp++ = MAGIC;
}
*dp++ = c; /* save output char */
word = IFS_WORD;
}
}
}
/*
* Prepare to generate the string returned by ${} substitution.
*/
static int
varsub(xp, sp, word, stypep, slenp)
Expand *xp;
const char *sp;
const char *word;
int *stypep; /* becomes qualifier type */
int *slenp; /* " " len (=, :=, etc.) valid iff *stypep != 0 */
{
int c;
int state; /* next state: XBASE, XARG, XSUB, XNULLSUB */
int stype; /* substitution type */
int slen;
const char *p;
char q[20];
struct tbl *vp;
if (sp[0] == '\0') /* Bad variable name */
return -1;
xp->var = (struct tbl *) 0;
/* ${#var}, string length or array size */
if (sp[0] == '#' && (c = sp[1]) != '\0') {
int zero_ok = 0;
/* Can't have any modifiers for ${#...} */
if (*word != CSUBST)
return -1;
sp++;
/* Check for size of array */
if ((p=strchr(sp,'[')) && (p[1]=='*'||p[1]=='@') && p[2]==']') {
int n = 0;
int max = 0;
vp = global(arrayname(sp));
if (vp->flag & (ISSET|ARRAY))
zero_ok = 1;
for (; vp; vp = vp->u.array)
if (vp->flag & ISSET) {
max = vp->index + 1;
n++;
}
c = n; /* ksh88/ksh93 go for number, not max index */
} else if (c == '*' || c == '@')
c = e->loc->argc;
else {
p = str_val(global(sp));
zero_ok = p != null;
c = strlen(p);
}
if (Flag(FNOUNSET) && c == 0 && !zero_ok)
errorf("%s: parameter not set", sp);
*stypep = 0; /* unqualified variable/string substitution */
snprintf((char *)&q,19,"%ld",(unsigned long)c);
xp->str = str_save(q, ATEMP);
return XSUB;
}
/* Check for qualifiers in word part */
stype = 0;
c = word[slen = 0] == CHAR ? word[1] : 0;
if (c == ':') {
slen += 2;
stype = 0x80;
c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
}
if (ctype(c, C_SUBOP1)) {
slen += 2;
stype |= c;
} else if (stype) /* : is not ok */
return -1;
else if (ctype(c, C_SUBOP2)) {
slen += 2;
stype = c;
if (word[slen + 0] == CHAR && c == word[slen + 1]) {
stype |= 0x80;
slen += 2;
}
}
if (!stype && *word != CSUBST)
return -1;
*stypep = stype;
*slenp = slen;
c = sp[0];
if (c == '*' || c == '@') {
switch (stype & 0x7f) {
case '=': /* can't assign to a vector */
case '%': /* can't trim a vector (yet) */
case '#':
return -1;
}
if (e->loc->argc == 0) {
xp->str = null;
state = c == '@' ? XNULLSUB : XSUB;
} else {
xp->u.strv = (const char **) e->loc->argv + 1;
xp->str = *xp->u.strv++;
xp->split = c == '@'; /* $@ */
state = XARG;
}
} else {
if ((p=strchr(sp,'[')) && (p[1]=='*'||p[1]=='@') && p[2]==']') {
XPtrV wv;
switch (stype & 0x7f) {
case '=': /* can't assign to a vector */
case '%': /* can't trim a vector (yet) */
case '#':
return -1;
}
XPinit(wv, 32);
vp = global(arrayname(sp));
for (; vp; vp = vp->u.array) {
if (!(vp->flag&ISSET))
continue;
XPput(wv, str_val(vp));
}
if (XPsize(wv) == 0) {
xp->str = null;
state = p[1] == '@' ? XNULLSUB : XSUB;
XPfree(wv);
} else {
XPput(wv, 0);
xp->u.strv = (const char **) XPptrv(wv);
xp->str = *xp->u.strv++;
xp->split = p[1] == '@'; /* ${foo[@]} */
state = XARG;
}
} else {
/* Can't assign things like $! or $1 */
if ((stype & 0x7f) == '='
&& (ctype(*sp, C_VAR1) || isdigit(*sp)))
return -1;
xp->var = global(sp);
xp->str = str_val(xp->var);
state = XSUB;
}
}
c = stype&0x7f;
/* test the compiler's code generator */
if (ctype(c, C_SUBOP2) ||
(((stype&0x80) ? *xp->str=='\0' : xp->str==null) ? /* undef? */
c == '=' || c == '-' || c == '?' : c == '+'))
state = XBASE; /* expand word instead of variable value */
if (Flag(FNOUNSET) && xp->str == null
&& (ctype(c, C_SUBOP2) || (state != XBASE && c != '+')))
errorf("%s: parameter not set", sp);
return state;
}
/*
* Run the command in $(...) and read its output.
*/
static int
comsub(Expand *xp, const char *cp)
{
Source *s, *sold;
struct op *t;
struct shf *shf;
s = pushs(SSTRING, ATEMP);
s->start = s->str = cp;
sold = source;
t = compile(s);
source = sold;
if (t == NULL)
return XBASE;
int ofd1, pv[2];
openpipe(pv);
shf = shf_fdopen(pv[0], SHF_RD, (struct shf *) 0);
ofd1 = savefd(1, 0); /* fd 1 may be closed... */
ksh_dup2(pv[1], 1, FALSE);
close(pv[1]);
execute(t, XFORK | XXCOM | XPIPEO, NULL);
restfd(1, ofd1);
startlast();
xp->split = 1; /* waitlast() */
xp->u.shf = shf;
return XCOM;
}
/*
* perform #pattern and %pattern substitution in ${}
*/
static char *
trimsub(char *str, char *pat, int how)
{
char *end = strchr(str, 0);
char *p, c;
switch (how&0xff) { /* UCHAR_MAX maybe? */
case '#': /* shortest at begining */
for (p = str; p <= end; p++) {
c = *p; *p = '\0';
if (gmatchx(str, pat, FALSE)) {
*p = c;
return p;
}
*p = c;
}
break;
case '#'|0x80: /* longest match at begining */
for (p = end; p >= str; p--) {
c = *p; *p = '\0';
if (gmatchx(str, pat, FALSE)) {
*p = c;
return p;
}
*p = c;
}
break;
case '%': /* shortest match at end */
for (p = end; p >= str; p--) {
if (gmatchx(p, pat, FALSE))
return str_nsave(str, p - str, ATEMP);
}
break;
case '%'|0x80: /* longest match at end */
for (p = str; p <= end; p++) {
if (gmatchx(p, pat, FALSE))
return str_nsave(str, p - str, ATEMP);
}
break;
}
return str; /* no match, return string */
}
/*
* glob
* Name derived from V6's /etc/glob, the program that expanded filenames.
*/
/* XXX cp not const 'cause slashes are temporarily replaced with nulls... */
static void
tmpglob(char *cp, XPtrV *wp, int markdirs)
{
int oldsize = XPsize(*wp);
if (glob_str(cp, wp, markdirs) == 0)
XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
else
qsort(XPptrv(*wp) + oldsize, XPsize(*wp) - oldsize,
sizeof (void *), xstrcmp);
}
#define GF_NONE 0
#define GF_EXCHECK BIT(0) /* do existence check on file */
#define GF_GLOBBED BIT(1) /* some globbing has been done */
#define GF_MARKDIR BIT(2) /* add trailing / to directories */
/* Apply file globbing to cp and store the matching files in wp. Returns
* the number of matches found.
*/
int
glob_str(char *cp, XPtrV *wp, int markdirs)
{
int oldsize = XPsize(*wp);
XString xs;
char *xp;
Xinit(xs, xp, 256, ATEMP);
globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
Xfree(xs, xp);
return XPsize(*wp) - oldsize;
}
static void
globit(XString *xs, /* dest string */
char **xpp, /* ptr to dest end */
char *sp, /* source path */
XPtrV *wp, /* output list */
int check) /* GF_* flags */
{
char *np; /* next source component */
char *xp = *xpp;
char *se;
char odirsep;
/* This to allow long expansions to be interrupted */
intrcheck();
if (sp == NULL) { /* end of source path */
/* We only need to check if the file exists if a pattern
* is followed by a non-pattern (eg, foo*x/bar; no check
* is needed for foo* since the match must exist) or if
* any patterns were expanded and the markdirs option is set.
* Symlinks make things a bit tricky...
*/
if ((check & GF_EXCHECK) ||
((check & GF_MARKDIR) && (check & GF_GLOBBED))) {
#define stat_check() (stat_done ? stat_done : \
(stat_done = stat(Xstring(*xs, xp), &statb) < 0 \
? -1 : 1))
struct stat lstatb, statb;
int stat_done = 0; /* -1: failed, 1 ok */
if (lstat(Xstring(*xs, xp), &lstatb) < 0)
return;
/* special case for systems which strip trailing
* slashes from regular files (eg, /etc/passwd/).
* SunOS 4.1.3 does this...
*/
if ((check & GF_EXCHECK) && xp > Xstring(*xs, xp) &&
xp[-1] == '/' && !S_ISDIR(lstatb.st_mode) &&
(!S_ISLNK(lstatb.st_mode) ||
stat_check() < 0 || !S_ISDIR(statb.st_mode)))
return;
/* Possibly tack on a trailing / if there isn't already
* one and if the file is a directory or a symlink to a
* directory
*/
if (((check & GF_MARKDIR) && (check & GF_GLOBBED)) &&
xp > Xstring(*xs, xp) && xp[-1] != '/' &&
(S_ISDIR(lstatb.st_mode) ||
(S_ISLNK(lstatb.st_mode) && stat_check() > 0 &&
S_ISDIR(statb.st_mode)))) {
*xp++ = '/';
*xp = '\0';
}
}
XPput(*wp, str_nsave(Xstring(*xs, xp), Xlength(*xs, xp), ATEMP));
return;
}
if (xp > Xstring(*xs, xp))
*xp++ = '/';
while (*sp == '/') {
Xcheck(*xs, xp);
*xp++ = *sp++;
}
np = strchr(sp, '/');
if (np != NULL) {
se = np;
odirsep = *np; /* don't assume '/', can be multiple kinds */
*np++ = '\0';
} else {
odirsep = '\0'; /* keep gcc quiet */
se = sp + strlen(sp);
}
/* Check if sp needs globbing - done to avoid pattern checks for strings
* containing MAGIC characters, open [s without the matching close ],
* etc. (otherwise opendir() will be called which may fail because the
* directory isn't readable - if no globbing is needed, only execute
* permission should be required (as per POSIX)).
*/
if (!has_globbing(sp, se)) {
XcheckN(*xs, xp, se - sp + 1);
debunk(xp, sp, Xnleft(*xs, xp));
xp += strlen(xp);
*xpp = xp;
globit(xs, xpp, np, wp, check);
} else {
DIR *dirp;
struct dirent *d;
char *name;
int len;
int prefix_len;
/* xp = *xpp; copy_non_glob() may have re-alloc'd xs */
*xp = '\0';
prefix_len = Xlength(*xs, xp);
dirp = opendir(prefix_len ? Xstring(*xs, xp) : ".");
if (dirp == NULL)
goto Nodir;
while ((d = readdir(dirp)) != NULL) {
name = d->d_name;
if (name[0] == '.' &&
(name[1] == 0 || (name[1] == '.' && name[2] == 0)))
continue; /* always ignore . and .. */
if ((*name == '.' && *sp != '.')
|| !gmatchx(name, sp, TRUE))
continue;
len = strlen(d->d_name) + 1;
XcheckN(*xs, xp, len);
memcpy(xp, name, len);
*xpp = xp + len - 1;
globit(xs, xpp, np, wp,
(check & GF_MARKDIR) | GF_GLOBBED
| (np ? GF_EXCHECK : GF_NONE));
xp = Xstring(*xs, xp) + prefix_len;
}
closedir(dirp);
Nodir:
;
}
if (np != NULL)
*--np = odirsep;
}
/* remove MAGIC from string */
char *
debunk(char *dp, const char *sp, size_t dlen)
{
char *d;
const char *s;
if ((s = ((const char *)strchr(sp, MAGIC)))) {
if (s - sp >= (ssize_t)dlen)
return dp;
memmove(dp, sp, s - sp);
for (d = dp + (s - sp); *s && (d - dp < (ssize_t)dlen); s++)
if (!ISMAGIC(*s) || !(*++s & 0x80) ||
!strchr("*+?@! ", *s & 0x7f))
*d++ = *s;
else {
/* extended pattern operators: *+?@! */
if ((*s & 0x7f) != ' ')
*d++ = *s & 0x7f;
if (d - dp < (ssize_t)dlen)
*d++ = '(';
}
*d = '\0';
} else if (dp != sp)
strcpy(dp, sp);
return dp;
}
/* Check if p is an unquoted name, possibly followed by a / or :. If so
* puts the expanded version in *dcp,dp and returns a pointer in p just
* past the name, otherwise returns 0.
*/
static const char *
maybe_expand_tilde(const char *p, XString *dsp, char **dpp, int isassign)
{
XString ts;
char *dp = *dpp;
char *tp;
const char *r;
Xinit(ts, tp, 16, ATEMP);
/* : only for DOASNTILDE form */
while (p[0] == CHAR && !ISDIRSEP(p[1])
&& (!isassign || p[1] != PATHSEP))
{
Xcheck(ts, tp);
*tp++ = p[1];
p += 2;
}
*tp = '\0';
r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ? tilde(Xstring(ts, tp)) : (char *) 0;
Xfree(ts, tp);
if (r) {
while (*r) {
Xcheck(*dsp, dp);
if (ISMAGIC(*r))
*dp++ = MAGIC;
*dp++ = *r++;
}
*dpp = dp;
r = p;
}
return r;
}
/*
* tilde expansion
*
* based on a version by Arnold Robbins
*/
static char *
tilde(char *cp)
{
char *dp;
if (cp[0] == '\0')
dp = str_val(global("HOME"));
else
dp = homedir(cp);
/* If HOME, PWD or OLDPWD are not set, don't expand ~ */
if (dp == null)
dp = (char *) 0;
return dp;
}
/*
* map userid to user's home directory.
* note that 4.3's getpw adds more than 6K to the shell,
* and the YP version probably adds much more.
* we might consider our own version of getpwnam() to keep the size down.
*/
static char *
homedir(char *name)
{
/* this used to cache results */
struct passwd *pw;
pw = getpwnam(name);
if(pw == NULL)
return NULL;
return pw->pw_dir;
}
#ifdef BRACE_EXPAND
static void
alt_expand(wp, start, exp_start, end, fdo)
XPtrV *wp;
char *start, *exp_start;
char *end;
int fdo;
{
int UNINITIALIZED(count);
char *brace_start, *brace_end, *UNINITIALIZED(comma);
char *field_start;
char *p;
/* search for open brace */
for (p = exp_start; (p = strchr(p, MAGIC)) && p[1] != OBRACE; p += 2)
;
brace_start = p;
/* find matching close brace, if any */
if (p) {
comma = (char *) 0;
count = 1;
for (p += 2; *p && count; p++) {
if (ISMAGIC(*p)) {
if (*++p == OBRACE)
count++;
else if (*p == CBRACE)
--count;
else if (*p == ',' && count == 1)
comma = p;
}
}
}
/* no valid expansions... */
if (!p || count != 0) {
/* Note that given a{{b,c} we do not expand anything (this is
* what at&t ksh does. This may be changed to do the {b,c}
* expansion. }
*/
if (fdo & DOGLOB)
tmpglob(start, wp, fdo & DOMARKDIRS);
else
XPput(*wp, debunk(start, start));
return;
}
brace_end = p;
if (!comma) {
alt_expand(wp, start, brace_end, end, fdo);
return;
}
/* expand expression */
field_start = brace_start + 2;
count = 1;
for (p = brace_start + 2; p != brace_end; p++) {
if (ISMAGIC(*p)) {
if (*++p == OBRACE)
count++;
else if ((*p == CBRACE && --count == 0)
|| (*p == ',' && count == 1))
{
char *new;
int l1, l2, l3;
l1 = brace_start - start;
l2 = (p - 1) - field_start;
l3 = end - brace_end;
new = (char *) alloc(l1 + l2 + l3 + 1, ATEMP);
memcpy(new, start, l1);
memcpy(new + l1, field_start, l2);
memcpy(new + l1 + l2, brace_end, l3);
new[l1 + l2 + l3] = '\0';
alt_expand(wp, new, new + l1,
new + l1 + l2 + l3, fdo);
field_start = p + 1;
}
}
}
return;
}
#endif /* BRACE_EXPAND */
|