home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / gawk213s.lzh / GAWK213S / VMS_ARGS.C < prev    next >
C/C++ Source or Header  |  1993-07-29  |  15KB  |  399 lines

  1. /*
  2.  * vms_args.c -- command line parsing, to emulate shell i/o redirection.
  3.  *        [ Escape sequence parsing now suppressed. ]
  4.  */
  5.  
  6. /*
  7.  * Copyright (C) 1991 the Free Software Foundation, Inc.
  8.  *
  9.  * This file is part of GAWK, the GNU implementation of the
  10.  * AWK Progamming Language.
  11.  *
  12.  * GAWK is free software; you can redistribute it and/or modify
  13.  * it under the terms of the GNU General Public License as published by
  14.  * the Free Software Foundation; either version 1, or (at your option)
  15.  * any later version.
  16.  *
  17.  * GAWK is distributed in the hope that it will be useful,
  18.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  20.  * GNU General Public License for more details.
  21.  *
  22.  * You should have received a copy of the GNU General Public License
  23.  * along with GAWK; see the file COPYING.  If not, write to
  24.  * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  25.  */
  26.  
  27. /*
  28.  * [.vms]vms_arg_fixup - emulate shell's command line processing: handle
  29.  *        stdio redirection, backslash escape sequences, and file wildcard
  30.  *        expansion.    Should be called immediately upon image startup.
  31.  *
  32.  *                              Pat Rankin, Nov'89
  33.  *                            rankin@eql.Caltech.EDU
  34.  *
  35.  *    <ifile        - open 'ifile' (readonly) as 'stdin'
  36.  *    >nfile        - create 'nfile' as 'stdout' (stream-lf format)
  37.  *    >>ofile     - append to 'ofile' for 'stdout'; create it if necessary
  38.  *    >&efile     - point 'stderr' (SYS$ERROR) at 'efile', but don't open
  39.  *    >$vfile     - create 'vfile' as 'stdout', using rms attributes
  40.  *              appropriate for a standard text file (variable length
  41.  *              records with implied carriage control)
  42.  *    2>&1        - special case: direct error messages into output file
  43.  *    1>&2        - special case: direct output data to error destination
  44.  *    <<sentinal  - error; reading stdin until 'sentinal' not supported
  45.  *    <-, >-        - error: stdin/stdout closure not implemented
  46.  *    | anything  - error; pipes not implemented
  47.  *    & <end-of-line> - error; background execution not implemented
  48.  *
  49.  *    any\Xany    - convert 'X' as appropriate; \000 will not work as
  50.  *              intended since subsequent processing will misinterpret
  51.  *
  52.  *    any*any     - perform wildcard directory lookup to find file(s)
  53.  *    any%any     -     "       "    ('%' is vms wildcard for '?' [ie, /./])
  54.  *    any?any     - treat like 'any%any' unless no files match
  55.  *    *, %, ?     - if no file(s) match, leave original value in arg list
  56.  *
  57.  *
  58.  * Notes:  a redirection operator  can have optional white space between it
  59.  *    and its filename; the  operator itself *must* be preceded by  white
  60.  *    space  so that it starts  a  separate  argument.  '<' is  ambiguous
  61.  *    since "<dir>file" is a valid VMS file specification; leading '<' is
  62.  *    assumed  to be    stdin--use "\<dir>file" to override.  '>$' is local
  63.  *    kludge to force  stdout to be created with text file RMS attributes
  64.  *    instead of  stream  format;  file  sharing is disabled    for  stdout
  65.  *    regardless.  Multiple  instances of  stdin  or stdout or stderr are
  66.  *    treated as fatal errors  rather than using the first or last.  If a
  67.  *    wildcard file specification is detected, it is expanded into a list
  68.  *    of  filenames  which match; if there  are no  matches, the original
  69.  *    file-spec is left in the argument list rather than having it expand
  70.  *    into thin  air.   No  attempt is made to identify  and    make $(var)
  71.  *    environment substitutions--must draw the line somewhere!
  72.  */
  73.  
  74. #include "awk.h"    /* really "../awk.h" */
  75. #include "vms.h"
  76.  
  77.        void   v_add_arg(int, const char *);
  78. static char  *skipblanks(const char *);
  79. static void   vms_expand_wildcards(const char *);
  80. static u_long vms_define(const char *, const char *);
  81. static char  *t_strstr(const char *, const char *);
  82. #define strstr t_strstr        /* strstr() missing from vaxcrtl for V4.x */
  83.  
  84. static    int    v_argc,  v_argz = 0;
  85. static    char  **v_argv;
  86.  
  87. /* vms_arg_fixup() - scan argv[] for i/o redirection and wildcards and also */
  88. /*            rebuild it with those removed or expanded, respectively */
  89. void
  90. vms_arg_fixup( int *pargc, char ***pargv )
  91. {
  92.     char *f_in, *f_out, *f_err,
  93.     *out_mode, *rms_opt1, *rms_opt2;
  94.     char **argv = *pargv;
  95.     int i, argc = *pargc;
  96.     int err_to_out_redirect = 0, out_to_err_redirect = 0;
  97.  
  98. #ifndef NO_CHECK_SHELL
  99.     if (shell$is_shell())
  100.     return;            /* don't do anything if we're running DECshell */
  101. #endif
  102. #ifndef NO_DCL_CMD
  103.     for (i = 1; i < argc ; i++)     /* check for dash or other non-VMS args */
  104.     if (strchr("->\\|", *argv[i]))    break;        /* found => (i < argc) */
  105.     if (i >= argc && (v_argc = vms_gawk()) > 0) {   /* vms_gawk => dcl_parse */
  106.     /* if we successfully parsed the command, replace original argv[] */
  107.     argc = v_argc,    argv = v_argv;
  108.     v_argz = v_argc = 0,  v_argv = NULL;
  109.     }
  110. #endif
  111.     v_add_arg(v_argc = 0, basename(argv[0]));    /* store arg #0 (image name) */
  112.  
  113.     f_in = f_out = f_err = NULL;    /* stdio setup (no filenames yet) */
  114.     out_mode = "w";            /* default access for stdout */
  115.     rms_opt1 = rms_opt2 = "ctx=stm";    /* ("context = stream") == no-opt */
  116.  
  117.     for (i = 1; i < argc; i++) {
  118.     char *p, *fn;
  119.     int  is_arg;
  120.  
  121.     is_arg = 0;        /* current arg does not begin with dash */
  122.     p = argv[i];        /* current arg */
  123.     switch (*p) {
  124.       case '<':        /* stdin */
  125.           /*[should try to determine whether this is really a directory
  126.          spec using <>; for now, force user to quote them with '\<']*/
  127.         if ( f_in ) {
  128.             fatal("multiple specification of '<' for stdin");
  129.         } else if (*++p == '<') {   /* '<<' is not supported */
  130.             fatal("'<<' not available for stdin");
  131.         } else {
  132.             p = skipblanks(p);
  133.             fn = (*p ? p : argv[++i]);    /* use next arg if necessary */
  134.             if (i >= argc || *fn == '-')
  135.             fatal("invalid i/o redirection, null filespec after '<'");
  136.             else
  137.             f_in = fn;        /* save filename for stdin */
  138.         }
  139.         break;
  140.       case '>':   {        /* stdout or stderr */
  141.           /*[vms-specific kludge '>$' added to force stdout to be created
  142.          as record-oriented text file instead of in stream-lf format]*/
  143.         int is_out = 1;            /* assume stdout */
  144.         if (*++p == '>')    /* '>>' => append */
  145.             out_mode = "a",  p++;
  146.         else if (*p == '&')    /* '>&' => stderr */
  147.             is_out = 0,  p++;
  148.         else if (*p == '$')    /* '>$' => kludge for record format */
  149.             rms_opt1 = "rfm=var",  rms_opt2 = "rat=cr",  p++;
  150.         else            /* '>'    => create */
  151.             ;        /* use default values initialized prior to loop */
  152.         p = skipblanks(p);
  153.         fn = (*p ? p : argv[++i]);    /* use next arg if necessary */
  154.         if (i >= argc || *fn == '-') {
  155.             fatal("invalid i/o redirection, null filespec after '>'");
  156.         } else if (is_out) {
  157.             if (out_to_err_redirect)
  158.             fatal("conflicting specifications for stdout");
  159.             else if (f_out)
  160.             fatal("multiple specification of '>' for stdout");
  161.             else
  162.             f_out = fn;        /* save filename for stdout */
  163.         } else {
  164.             if (err_to_out_redirect)
  165.             fatal("conflicting specifications for stderr");
  166.             else if (f_err)
  167.             fatal("multiple specification of '>&' for stderr");
  168.             else
  169.             f_err = fn;        /* save filename for stderr */
  170.         }
  171.         }    break;
  172.       case '2':        /* check for ``2>&1'' special case'' */
  173.         if (strcmp(p, "2>&1") != 0)
  174.             goto ordinary_arg;
  175.         else if (f_err || out_to_err_redirect)
  176.             fatal("conflicting specifications for stderr");
  177.         else {
  178.             err_to_out_redirect = 1;
  179.             f_err = "SYS$OUTPUT:";
  180.         }  break;
  181.       case '1':        /* check for ``1>&2'' special case'' */
  182.         if (strcmp(p, "1>&2") != 0)
  183.             goto ordinary_arg;
  184.         else if (f_out || err_to_out_redirect)
  185.             fatal("conflicting specifications for stdout");
  186.         else {
  187.             out_to_err_redirect = 1;
  188.             f_out = "SYS$ERROR:";
  189.         }  break;
  190.       case '|':        /* pipe */
  191.           /* command pipelines are not supported */
  192.         fatal("command pipes not available ('|' encountered)");
  193.         break;
  194.       case '&':        /* background */
  195.           /*[we could probably spawn or fork ourself--maybe someday]*/
  196.         if (*(p+1) == '\0' && i == argc - 1) {
  197.             fatal("background tasks not available ('&' encountered)");
  198.             break;
  199.         } else        /* fall through */
  200.             ;    /*NOBREAK*/
  201.       case '-':        /* argument */
  202.         is_arg = 1;        /*(=> skip wildcard check)*/
  203.       default:        /* other (filespec assumed) */
  204. ordinary_arg:
  205.           /* process escape sequences or expand wildcards */
  206.         v_add_arg(++v_argc, p);        /* include this arg */
  207.         p = strchr(p, '\\');        /* look for backslash */
  208.         if (p != NULL) {    /* does it have escape sequence(s)? */
  209. #if 0    /* disable escape parsing; it's now done elsewhere within gawk */
  210.             register int c;
  211.             char *q = v_argv[v_argc] + (p - argv[i]);
  212.             do {
  213.             c = *p++;
  214.             if (c == '\\')
  215.                 c = parse_escape(&p);
  216.             *q++ = (c >= 0 ? (char)c : '\\');
  217.             } while (*p != '\0');
  218.             *q = '\0';
  219. #endif    /*0*/
  220.         } else if (!is_arg && strchr(v_argv[v_argc], '=') == NULL) {
  221.             vms_expand_wildcards(v_argv[v_argc]);
  222.         }
  223.         break;
  224.     } /* end switch */
  225.     } /* loop */
  226.  
  227.     /*
  228.      * Now process any/all I/O options encountered above.
  229.      */
  230.  
  231.     /* must do stderr first, or vaxcrtl init might not see it */
  232.     /*[ catch 22:  we'll also redirect errors encountered doing <in or >out ]*/
  233.     if (f_err) {    /* define logical name but don't open file */
  234.     int len = strlen(f_err);
  235.     if (strncasecmp(f_err, "SYS$OUTPUT", len) == 0
  236.      && (f_err[len] == ':' || f_err[len] == '\0'))
  237.         err_to_out_redirect = 1;
  238.     else
  239.         vms_define("SYS$ERROR", f_err);
  240.     }
  241.     /* do stdin before stdout, so we bomb we won't create empty output file */
  242.     if (f_in) {        /* [re]open file and define logical name */
  243.     stdin = freopen(f_in, "r", stdin, "mbf=2");
  244.     if (stdin != NULL)
  245.         vms_define("SYS$INPUT", f_in);
  246.     else
  247.         fatal("<%s (%s)", f_in, strerror(errno));
  248.     }
  249.     if (f_out) {    /* disallow file sharing to reduce overhead */
  250.     stdout = freopen(f_out, out_mode, stdout,
  251.              rms_opt1, rms_opt2, "shr=nil", "mbf=2");   /*VAXCRTL*/
  252.     if (stdout != NULL) {
  253. #ifdef crtl_bug  /* eof sometimes doesn't get set properly for stm_lf file */
  254. # define BIGBUF 8*BUFSIZ    /* maximum record size: 4096 instead of 512 */
  255.         setvbuf(stdout, malloc(BIGBUF), _IOFBF, BIGBUF);
  256. #endif
  257.         vms_define("SYS$OUTPUT", f_out);
  258.     } else
  259.         fatal(">%s%s (%s)", (*out_mode == 'a' ? ">" : ""),
  260.           f_out, strerror(errno));
  261.     }
  262.     if (err_to_out_redirect) {    /* special case for ``2>&1'' construct */
  263.     fclose(stderr);
  264.     dup(1, 2);    /* make file 2 (stderr) share file 1 (stdout) */
  265.     stderr = stdout;
  266.     vms_define("SYS$ERROR", "SYS$OUTPUT:");
  267.     } else if (out_to_err_redirect) {    /* ``1>&2'' */
  268.     fclose(stdout);
  269.     dup(2, 1);    /* make file 1 (stdout) share file 2 (stderr) */
  270.     stdout = stderr;
  271.     vms_define("SYS$OUTPUT", "SYS$ERROR:");
  272.     }
  273.  
  274. #ifndef NO_DCL_CMD
  275.     /* if we replaced argv[] with our own, we can release it now */
  276.     if (argv != *pargv)
  277.     free((void *)argv),  argv = NULL;
  278. #endif
  279.     *pargc = ++v_argc;        /* increment to account for argv[0] */
  280.     *pargv = v_argv;
  281.     return;
  282. }
  283.  
  284. /* vms_expand_wildcards() - check a string for wildcard punctuation; */
  285. /*               if it has any, attempt a directory lookup */
  286. /*               and store resulting name(s) in argv array */
  287. static void
  288. vms_expand_wildcards( const char *prospective_filespec )
  289. {
  290.     char *p, spec_buf[255+1], res_buf[255+1], *strstr();
  291.     Dsc   spec, result;
  292.     void *context;
  293.     register int len = strlen(prospective_filespec);
  294.  
  295.     if (len >= sizeof spec_buf)
  296.     return;        /* can't be valid--or at least we can't handle it */
  297.     strcpy(spec_buf, prospective_filespec);    /* copy the arg */
  298.     p = strchr(spec_buf, '?');
  299.     if (p != NULL)    /* change '?' single-char wildcard to '%' */
  300.     do  *p++ = '%',  p = strchr(p, '?');
  301.         while (p != NULL);
  302.     else if (strchr(spec_buf, '*') == strchr(spec_buf, '%')  /* => both NULL */
  303.       && strstr(spec_buf, "...") == NULL)
  304.     return;        /* no wildcards present; don't attempt file lookup */
  305.     spec.len = len,  spec.adr = spec_buf;
  306.     result.len = sizeof res_buf - 1,  result.adr = res_buf;
  307.  
  308.     /* The filespec is already in v_argv[v_argc]; if we fail to match anything,
  309.        we'll just leave it there (unlike most shells, where it would evaporate).
  310.      */
  311.     len = -1;            /* overload 'len' with flag value */
  312.     context = NULL;        /* init */
  313.     while (vmswork(LIB$FIND_FILE(&spec, &result, &context))) {
  314.     for (len = sizeof(res_buf)-1; len > 0 && res_buf[len-1] == ' '; len--) ;
  315.     res_buf[len] = '\0';    /* terminate after discarding trailing blanks */
  316.     v_add_arg(v_argc++, strdup(res_buf));        /* store result */
  317.     }
  318.     (void)LIB$FIND_FILE_END(&context);
  319.     if (len >= 0)        /* (still -1 => never entered loop) */
  320.     --v_argc;        /* undo final post-increment */
  321.     return;
  322. }
  323.  
  324. /* v_add_arg() - store string pointer in v_argv[]; expand array if necessary */
  325. void
  326. v_add_arg( int idx, const char *val )
  327. {
  328. #ifdef DEBUG_VMS
  329.     fprintf(stderr, "v_add_arg: v_argv[%d] ", idx);
  330. #endif
  331.     if (idx + 1 >= v_argz) {    /* 'v_argz' is the current size of v_argv[] */
  332.     int old_size = v_argz;
  333.  
  334.     v_argz = idx + 10;    /* increment by arbitrary amount */
  335.     if (old_size == 0)
  336.         v_argv = (char **)malloc((unsigned)(v_argz * sizeof(char **)));
  337.     else
  338.         v_argv = (char **)realloc((char *)v_argv,
  339.                      (unsigned)(v_argz * sizeof(char **)));
  340.     if (v_argv == NULL) {    /* error */
  341.         fatal("%s: %s: can't allocate memory (%s)", "vms_args",
  342.           "v_argv", strerror(errno));
  343.     } else {
  344.         memmsg((oldsize == 0 ? "v_argv" : "re: v_argv"), v_argz,
  345.            "vms_args", v_argv);
  346.         while (old_size < v_argz)  v_argv[old_size++] = NULL;
  347.     }
  348.     }
  349.     v_argv[idx] = (char *)val;
  350. #ifdef DEBUG_VMS
  351.     fprintf(stderr, "= \"%s\"\n", val);
  352. #endif
  353. }
  354.  
  355. /* skipblanks() - return a pointer to the first non-blank in the string */
  356. static char *
  357. skipblanks( const char *ptr )
  358. {
  359.     if (ptr)
  360.     while (*ptr == ' ' || *ptr == '\t')
  361.         ptr++;
  362.     return (char *)ptr;
  363. }
  364.  
  365. /* vms_define() - assign a value to a logical name [define/process/user_mode] */
  366. static u_long
  367. vms_define( const char *log_name, const char *trans_val )
  368. {
  369.     Dsc log_dsc, trn_dsc;
  370. # define LOG_PROCESS_TABLE 2        /* <obsolete> */
  371. # define LOG_USERMODE 3            /* PSL$C_USER */
  372.     extern u_long SYS$CRELOG();        /* <superceded by $CRELNM> */
  373.  
  374.     /* avoid "define SYS$OUTPUT sys$output:" for redundant ">sys$output:" */
  375.     if (strncasecmp(log_name, trans_val, strlen(log_name)) == 0)
  376.     return 0;
  377.  
  378.     log_dsc.len = strlen(log_dsc.adr = (char *)log_name);
  379.     trn_dsc.len = strlen(trn_dsc.adr = (char *)trans_val);
  380.     return SYS$CRELOG(LOG_PROCESS_TABLE, &log_dsc, &trn_dsc, LOG_USERMODE);
  381. }
  382.  
  383. /* t_strstr -- strstr() substitute; search 'str' for 'sub' */
  384. static char *t_strstr ( const char *str, const char *sub )
  385. {
  386.     register const char *s0, *s1, *s2;
  387.  
  388.     /* special case: empty substring */
  389.     if (!*sub)    return (char *)str;
  390.  
  391.     /* brute force method */
  392.     for (s0 = s1 = str; *s1; s1 = ++s0) {
  393.     s2 = sub;
  394.     while (*s1++ == *s2++)
  395.         if (!*s2)  return (char *)s0;    /* full match */
  396.     }
  397.     return (char *)0;    /* not found */
  398. }
  399.