home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 6 / FreshFish_September1994.bin / bbs / gnu / gawk-2.15.5-src.lha / GNU / src / amiga / gawk-2.15.5 / vms / vms_args.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-01-05  |  15.0 KB  |  413 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-1993 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 2 of the License, or
  15.  * (at your option) 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, Inc., 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.  *   Oct'91, gawk 2.13.3
  74.  *    Open '<' with full sharing allowed, so that we can  read batch logs
  75.  *    and other open files.  Create record-format output ('>$') with read
  76.  *    sharing permited,  so that others can read our output file to check
  77.  *    progess.  For stream  output ('>' or  '>>'), sharing is  disallowed
  78.  *    (for performance reasons).
  79.  */
  80.  
  81. #include "awk.h"    /* really "../awk.h" */
  82. #include "vms.h"
  83. #include <lnmdef.h>
  84.  
  85.        void   v_add_arg(int, const char *);
  86. static char  *skipblanks(const char *);
  87. static void   vms_expand_wildcards(const char *);
  88. static u_long vms_define(const char *, const char *);
  89. static char  *t_strstr(const char *, const char *);
  90. #define strstr t_strstr        /* strstr() missing from vaxcrtl for V4.x */
  91.  
  92. static    int    v_argc,  v_argz = 0;
  93. static    char  **v_argv;
  94.  
  95. /* vms_arg_fixup() - scan argv[] for i/o redirection and wildcards and also */
  96. /*            rebuild it with those removed or expanded, respectively */
  97. void
  98. vms_arg_fixup( int *pargc, char ***pargv )
  99. {
  100.     const char *f_in, *f_out, *f_err,
  101.     *out_mode, *rms_rfm, *rms_shr, *rms_mrs;
  102.     char **argv = *pargv;
  103.     int i, argc = *pargc;
  104.     int err_to_out_redirect = 0, out_to_err_redirect = 0;
  105.  
  106. #ifdef CHECK_DECSHELL        /* don't define this if linking with DECC$SHR */
  107.     if (shell$is_shell())
  108.     return;            /* don't do anything if we're running DEC/Shell */
  109. #endif
  110. #ifndef NO_DCL_CMD
  111.     for (i = 1; i < argc ; i++)     /* check for dash or other non-VMS args */
  112.     if (strchr("->\\|", *argv[i]))    break;        /* found => (i < argc) */
  113.     if (i >= argc && (v_argc = vms_gawk()) > 0) {   /* vms_gawk => dcl_parse */
  114.     /* if we successfully parsed the command, replace original argv[] */
  115.     argc = v_argc,    argv = v_argv;
  116.     v_argz = v_argc = 0,  v_argv = NULL;
  117.     }
  118. #endif
  119.     v_add_arg(v_argc = 0, argv[0]);    /* store arg #0 (image name) */
  120.  
  121.     f_in = f_out = f_err = NULL;    /* stdio setup (no filenames yet) */
  122.     out_mode = "w";            /* default access for stdout */
  123.     rms_rfm = "rfm=stmlf";        /* stream_LF format */
  124.     rms_shr = "shr=nil";        /* no sharing (for '>' output file) */
  125.     rms_mrs = "mrs=0";            /* no maximum record size */
  126.  
  127.     for (i = 1; i < argc; i++) {
  128.     char *p, *fn;
  129.     int  is_arg;
  130.  
  131.     is_arg = 0;        /* current arg does not begin with dash */
  132.     p = argv[i];        /* current arg */
  133.     switch (*p) {
  134.       case '<':        /* stdin */
  135.           /*[should try to determine whether this is really a directory
  136.          spec using <>; for now, force user to quote them with '\<']*/
  137.         if ( f_in ) {
  138.             fatal("multiple specification of '<' for stdin");
  139.         } else if (*++p == '<') {   /* '<<' is not supported */
  140.             fatal("'<<' not available for stdin");
  141.         } else {
  142.             p = skipblanks(p);
  143.             fn = (*p ? p : argv[++i]);    /* use next arg if necessary */
  144.             if (i >= argc || *fn == '-')
  145.             fatal("invalid i/o redirection, null filespec after '<'");
  146.             else
  147.             f_in = fn;        /* save filename for stdin */
  148.         }
  149.         break;
  150.       case '>':   {        /* stdout or stderr */
  151.           /*[vms-specific kludge '>$' added to force stdout to be created
  152.          as record-oriented text file instead of in stream-lf format]*/
  153.         int is_out = 1;            /* assume stdout */
  154.         if (*++p == '>')    /* '>>' => append */
  155.             out_mode = "a",  p++;
  156.         else if (*p == '&')    /* '>&' => stderr */
  157.             is_out = 0,  p++;
  158.         else if (*p == '$')    /* '>$' => kludge for record format */
  159.             rms_rfm = "rfm=var",  rms_shr = "shr=get,upi",
  160.             rms_mrs = "mrs=32767",  p++;
  161.         else            /* '>'    => create */
  162.             {}        /* use default values initialized prior to loop */
  163.         p = skipblanks(p);
  164.         fn = (*p ? p : argv[++i]);    /* use next arg if necessary */
  165.         if (i >= argc || *fn == '-') {
  166.             fatal("invalid i/o redirection, null filespec after '>'");
  167.         } else if (is_out) {
  168.             if (out_to_err_redirect)
  169.             fatal("conflicting specifications for stdout");
  170.             else if (f_out)
  171.             fatal("multiple specification of '>' for stdout");
  172.             else
  173.             f_out = fn;        /* save filename for stdout */
  174.         } else {
  175.             if (err_to_out_redirect)
  176.             fatal("conflicting specifications for stderr");
  177.             else if (f_err)
  178.             fatal("multiple specification of '>&' for stderr");
  179.             else
  180.             f_err = fn;        /* save filename for stderr */
  181.         }
  182.         }    break;
  183.       case '2':        /* check for ``2>&1'' special case'' */
  184.         if (strcmp(p, "2>&1") != 0)
  185.             goto ordinary_arg;
  186.         else if (f_err || out_to_err_redirect)
  187.             fatal("conflicting specifications for stderr");
  188.         else {
  189.             err_to_out_redirect = 1;
  190.             f_err = "SYS$OUTPUT:";
  191.         }  break;
  192.       case '1':        /* check for ``1>&2'' special case'' */
  193.         if (strcmp(p, "1>&2") != 0)
  194.             goto ordinary_arg;
  195.         else if (f_out || err_to_out_redirect)
  196.             fatal("conflicting specifications for stdout");
  197.         else {
  198.             out_to_err_redirect = 1;
  199.             f_out = "SYS$ERROR:";
  200.         }  break;
  201.       case '|':        /* pipe */
  202.           /* command pipelines are not supported */
  203.         fatal("command pipes not available ('|' encountered)");
  204.         break;
  205.       case '&':        /* background */
  206.           /*[we could probably spawn or fork ourself--maybe someday]*/
  207.         if (*(p+1) == '\0' && i == argc - 1) {
  208.             fatal("background tasks not available ('&' encountered)");
  209.             break;
  210.         } else {    /* fall through */
  211.             ;    /*NOBREAK*/
  212.         }
  213.       case '-':        /* argument */
  214.         is_arg = 1;        /*(=> skip wildcard check)*/
  215.       default:        /* other (filespec assumed) */
  216. ordinary_arg:
  217.           /* process escape sequences or expand wildcards */
  218.         v_add_arg(++v_argc, p);        /* include this arg */
  219.         p = strchr(p, '\\');        /* look for backslash */
  220.         if (p != NULL) {    /* does it have escape sequence(s)? */
  221. #if 0    /* disable escape parsing; it's now done elsewhere within gawk */
  222.             register int c;
  223.             char *q = v_argv[v_argc] + (p - argv[i]);
  224.             do {
  225.             c = *p++;
  226.             if (c == '\\')
  227.                 c = parse_escape(&p);
  228.             *q++ = (c >= 0 ? (char)c : '\\');
  229.             } while (*p != '\0');
  230.             *q = '\0';
  231. #endif    /*0*/
  232.         } else if (!is_arg && strchr(v_argv[v_argc], '=') == NULL) {
  233.             vms_expand_wildcards(v_argv[v_argc]);
  234.         }
  235.         break;
  236.     } /* end switch */
  237.     } /* loop */
  238.  
  239.     /*
  240.      * Now process any/all I/O options encountered above.
  241.      */
  242.  
  243.     /* must do stderr first, or vaxcrtl init might not see it */
  244.     /*[ catch 22:  we'll also redirect errors encountered doing <in or >out ]*/
  245.     if (f_err) {    /* define logical name but don't open file */
  246.     int len = strlen(f_err);
  247.     if (strncasecmp(f_err, "SYS$OUTPUT", len) == 0
  248.      && (f_err[len] == ':' || f_err[len] == '\0'))
  249.         err_to_out_redirect = 1;
  250.     else
  251.         (void) vms_define("SYS$ERROR", f_err);
  252.     }
  253.     /* do stdin before stdout, so if we bomb we won't make empty output file */
  254.     if (f_in) {        /* [re]open file and define logical name */
  255.     stdin = freopen(f_in, "r", stdin,
  256.             "ctx=rec", "shr=get,put,del,upd",
  257.             "mrs=32767", "mbc=32", "mbf=2");
  258.     if (stdin != NULL)
  259.         (void) vms_define("SYS$INPUT", f_in);
  260.     else
  261.         fatal("<%s (%s)", f_in, strerror(errno));
  262.     }
  263.     if (f_out) {
  264.     stdout = freopen(f_out, out_mode, stdout,
  265.              rms_rfm, rms_shr, rms_mrs,
  266.              "rat=cr", "mbc=32", "mbf=2");
  267.     if (stdout != NULL)
  268.         (void) vms_define("SYS$OUTPUT", f_out);
  269.     else
  270.         fatal(">%s%s (%s)", (*out_mode == 'a' ? ">" : ""),
  271.           f_out, strerror(errno));
  272.     }
  273.     if (err_to_out_redirect) {    /* special case for ``2>&1'' construct */
  274.     (void) fclose(stderr);
  275.     (void) dup2(1, 2);    /* make file 2 (stderr) share file 1 (stdout) */
  276.     stderr = stdout;
  277.     (void) vms_define("SYS$ERROR", "SYS$OUTPUT:");
  278.     } else if (out_to_err_redirect) {    /* ``1>&2'' */
  279.     (void) fclose(stdout);
  280.     (void) dup2(2, 1);    /* make file 1 (stdout) share file 2 (stderr) */
  281.     stdout = stderr;
  282.     (void) vms_define("SYS$OUTPUT", "SYS$ERROR:");
  283.     }
  284.  
  285. #ifndef NO_DCL_CMD
  286.     /* if we replaced argv[] with our own, we can release it now */
  287.     if (argv != *pargv)
  288.     free((void *)argv),  argv = NULL;
  289. #endif
  290.     *pargc = ++v_argc;        /* increment to account for argv[0] */
  291.     *pargv = v_argv;
  292.     return;
  293. }
  294.  
  295. /* vms_expand_wildcards() - check a string for wildcard punctuation; */
  296. /*               if it has any, attempt a directory lookup */
  297. /*               and store resulting name(s) in argv array */
  298. static void
  299. vms_expand_wildcards( const char *prospective_filespec )
  300. {
  301.     char *p, spec_buf[255+1], res_buf[255+1], *strstr();
  302.     Dsc   spec, result;
  303.     void *context;
  304.     register int len = strlen(prospective_filespec);
  305.  
  306.     if (len >= sizeof spec_buf)
  307.     return;        /* can't be valid--or at least we can't handle it */
  308.     strcpy(spec_buf, prospective_filespec);    /* copy the arg */
  309.     p = strchr(spec_buf, '?');
  310.     if (p != NULL)    /* change '?' single-char wildcard to '%' */
  311.     do  *p++ = '%',  p = strchr(p, '?');
  312.         while (p != NULL);
  313.     else if (strchr(spec_buf, '*') == strchr(spec_buf, '%')  /* => both NULL */
  314.       && strstr(spec_buf, "...") == NULL)
  315.     return;        /* no wildcards present; don't attempt file lookup */
  316.     spec.len = len,  spec.adr = spec_buf;
  317.     result.len = sizeof res_buf - 1,  result.adr = res_buf;
  318.  
  319.     /* The filespec is already in v_argv[v_argc]; if we fail to match anything,
  320.        we'll just leave it there (unlike most shells, where it would evaporate).
  321.      */
  322.     len = -1;            /* overload 'len' with flag value */
  323.     context = NULL;        /* init */
  324.     while (vmswork(LIB$FIND_FILE(&spec, &result, &context))) {
  325.     for (len = sizeof(res_buf)-1; len > 0 && res_buf[len-1] == ' '; len--) ;
  326.     res_buf[len] = '\0';    /* terminate after discarding trailing blanks */
  327.     v_add_arg(v_argc++, strdup(res_buf));        /* store result */
  328.     }
  329.     (void)LIB$FIND_FILE_END(&context);
  330.     if (len >= 0)        /* (still -1 => never entered loop) */
  331.     --v_argc;        /* undo final post-increment */
  332.     return;
  333. }
  334.  
  335. /* v_add_arg() - store string pointer in v_argv[]; expand array if necessary */
  336. void
  337. v_add_arg( int idx, const char *val )
  338. {
  339. #ifdef DEBUG_VMS
  340.     fprintf(stderr, "v_add_arg: v_argv[%d] ", idx);
  341. #endif
  342.     if (idx + 1 >= v_argz) {    /* 'v_argz' is the current size of v_argv[] */
  343.     int old_size = v_argz;
  344.  
  345.     v_argz = idx + 10;    /* increment by arbitrary amount */
  346.     if (old_size == 0)
  347.         v_argv = (char **)malloc((unsigned)(v_argz * sizeof(char **)));
  348.     else
  349.         v_argv = (char **)realloc((char *)v_argv,
  350.                      (unsigned)(v_argz * sizeof(char **)));
  351.     if (v_argv == NULL) {    /* error */
  352.         fatal("%s: %s: can't allocate memory (%s)", "vms_args",
  353.           "v_argv", strerror(errno));
  354.     } else {
  355.         while (old_size < v_argz)  v_argv[old_size++] = NULL;
  356.     }
  357.     }
  358.     v_argv[idx] = (char *)val;
  359. #ifdef DEBUG_VMS
  360.     fprintf(stderr, "= \"%s\"\n", val);
  361. #endif
  362. }
  363.  
  364. /* skipblanks() - return a pointer to the first non-blank in the string */
  365. static char *
  366. skipblanks( const char *ptr )
  367. {
  368.     if (ptr)
  369.     while (*ptr == ' ' || *ptr == '\t')
  370.         ptr++;
  371.     return (char *)ptr;
  372. }
  373.  
  374. /* vms_define() - assign a value to a logical name [define/process/user_mode] */
  375. static u_long
  376. vms_define( const char *log_name, const char *trans_val )
  377. {
  378.     Dsc log_dsc;
  379.     static Descrip(lnmtable,"LNM$PROCESS_TABLE");
  380.     static u_long attr = LNM$M_CONFINE;
  381.     static Itm itemlist[] = { {0,LNM$_STRING,0,0}, {0,0} };
  382.     static unsigned char acmode = PSL$C_USER;
  383.     unsigned len = strlen(log_name);
  384.  
  385.     /* avoid "define SYS$OUTPUT sys$output:" for redundant ">sys$output:" */
  386.     if (strncasecmp(log_name, trans_val, len) == 0
  387.      && (trans_val[len] == '\0' || trans_val[len] == ':'))
  388.     return 0;
  389.  
  390.     log_dsc.adr = (char *)log_name;
  391.     log_dsc.len = len;
  392.     itemlist[0].buffer = (char *)trans_val;
  393.     itemlist[0].len = strlen(trans_val);
  394.     return SYS$CRELNM(&attr, &lnmtable, &log_dsc, &acmode, itemlist);
  395. }
  396.  
  397. /* t_strstr -- strstr() substitute; search 'str' for 'sub' */
  398. static char *t_strstr ( const char *str, const char *sub )
  399. {
  400.     register const char *s0, *s1, *s2;
  401.  
  402.     /* special case: empty substring */
  403.     if (!*sub)    return (char *)str;
  404.  
  405.     /* brute force method */
  406.     for (s0 = s1 = str; *s1; s1 = ++s0) {
  407.     s2 = sub;
  408.     while (*s1++ == *s2++)
  409.         if (!*s2)  return (char *)s0;    /* full match */
  410.     }
  411.     return (char *)0;    /* not found */
  412. }
  413.