Subversion Repositories SvarDOS

Rev

Rev 1823 | Rev 1839 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
421 mateuszvis 1
/* This file is part of the SvarCOM project and is published under the terms
2
 * of the MIT license.
3
 *
1714 mateusz.vi 4
 * Copyright (C) 2021-2024 Mateusz Viste
421 mateuszvis 5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a
7
 * copy of this software and associated documentation files (the "Software"),
8
 * to deal in the Software without restriction, including without limitation
9
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
 * and/or sell copies of the Software, and to permit persons to whom the
11
 * Software is furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
 * DEALINGS IN THE SOFTWARE.
23
 */
24
 
349 mateuszvis 25
#include <i86.h>
26
#include <dos.h>
27
#include <stdio.h>
350 mateuszvis 28
#include <stdlib.h>
349 mateuszvis 29
#include <string.h>
30
 
1001 mateusz.vi 31
#include "svarlang.lib/svarlang.h"
349 mateuszvis 32
 
352 mateuszvis 33
#include "cmd.h"
366 mateuszvis 34
#include "env.h"
352 mateuszvis 35
#include "helpers.h"
402 mateuszvis 36
#include "redir.h"
351 mateuszvis 37
#include "rmodinit.h"
448 mateuszvis 38
#include "sayonara.h"
1822 mateusz.vi 39
#include "version.h"
349 mateuszvis 40
 
479 mateuszvis 41
#include "rmodcore.h" /* rmod binary inside a BUFFER array */
443 mateuszvis 42
 
572 mateuszvis 43
/* this version byte is used to tag RMOD so I can easily make sure that
44
 * the RMOD struct I find in memory is one that I know. Should the version
45
 * mismatch, then it would likely mean that SvarCOM has been upgraded and
46
 * RMOD should not be accessed as its structure might no longer be in sync
47
 * with what I think it is.
1715 mateusz.vi 48
 *          *** INCREMENT THIS AT EACH NEW SVARCOM RELEASE! ***
49
 *            (or at least whenever RMOD's struct is changed)            */
1730 mateusz.vi 50
#define BYTE_VERSION 5
572 mateuszvis 51
 
52
 
349 mateuszvis 53
struct config {
449 mateuszvis 54
  unsigned char flags; /* command.com flags, as defined in rmodinit.h */
443 mateuszvis 55
  char *execcmd;
410 mateuszvis 56
  unsigned short envsiz;
443 mateuszvis 57
};
349 mateuszvis 58
 
490 mateuszvis 59
/* max length of the cmdline storage (bytes) - includes also max length of
60
 * line loaded from a BAT file (no more than 255 bytes!) */
61
#define CMDLINE_MAXLEN 255
349 mateuszvis 62
 
490 mateuszvis 63
 
64
/* sets guard values at a few places in memory for later detection of
65
 * overflows via memguard_check() */
500 mateuszvis 66
static void memguard_set(char *cmdlinebuf) {
490 mateuszvis 67
  BUFFER[sizeof(BUFFER) - 1] = 0xC7;
500 mateuszvis 68
  cmdlinebuf[CMDLINE_MAXLEN] = 0xC7;
490 mateuszvis 69
}
70
 
71
 
72
/* checks for valguards at specific memory locations, returns 0 on success */
500 mateuszvis 73
static int memguard_check(unsigned short rmodseg, char *cmdlinebuf) {
490 mateuszvis 74
  /* check RMOD signature (would be overwritten in case of stack overflow */
75
  static char msg[] = "!! MEMORY CORRUPTION ## DETECTED !!";
76
  unsigned short far *rmodsig = MK_FP(rmodseg, 0x100 + 6);
548 mateuszvis 77
  unsigned char far *rmod = MK_FP(rmodseg, 0);
78
 
490 mateuszvis 79
  if (*rmodsig != 0x2019) {
80
    msg[22] = '1';
548 mateuszvis 81
    goto FAIL;
490 mateuszvis 82
  }
548 mateuszvis 83
 
500 mateuszvis 84
  /* check last BUFFER byte */
490 mateuszvis 85
  if (BUFFER[sizeof(BUFFER) - 1] != 0xC7) {
86
    msg[22] = '2';
548 mateuszvis 87
    goto FAIL;
490 mateuszvis 88
  }
548 mateuszvis 89
 
500 mateuszvis 90
  /* check last cmdlinebuf byte */
91
  if (cmdlinebuf[CMDLINE_MAXLEN] != 0xC7) {
490 mateuszvis 92
    msg[22] = '3';
548 mateuszvis 93
    goto FAIL;
490 mateuszvis 94
  }
548 mateuszvis 95
 
96
  /* check rmod exec buf */
97
  if (rmod[RMOD_OFFSET_EXECPROG + 127] != 0) {
98
    msg[22] = '4';
99
    goto FAIL;
100
  }
101
 
102
  /* check rmod exec stdin buf */
103
  if (rmod[RMOD_OFFSET_STDINFILE + 127] != 0) {
104
    msg[22] = '5';
105
    goto FAIL;
106
  }
107
 
108
  /* check rmod exec stdout buf */
109
  if (rmod[RMOD_OFFSET_STDOUTFILE + 127] != 0) {
110
    msg[22] = '6';
111
    goto FAIL;
112
  }
113
 
114
  /* else all good */
490 mateuszvis 115
  return(0);
548 mateuszvis 116
 
117
  /* error handling */
118
  FAIL:
119
  outputnl(msg);
120
  return(1);
490 mateuszvis 121
}
122
 
123
 
443 mateuszvis 124
/* parses command line the hard way (directly from PSP) */
125
static void parse_argv(struct config *cfg) {
1715 mateusz.vi 126
  unsigned char *cmdlinelen = (void *)0x80;
491 mateuszvis 127
  char *cmdline = (void *)0x81;
443 mateuszvis 128
 
1715 mateusz.vi 129
  /* The arg tail at [81h] needs some care when being processed.
130
   *
131
   * Its length should be provided in [80h], but it is not always exact:
132
   * https://github.com/SvarDOS/bugz/issues/67
133
   *
134
   * The tail string itself is usually terminated by a CR character. But
135
   * sometimes it might be terminated by a nul. Or by nothing at all.
136
   *
137
   * The cautious approach is therefore to read the tail up until the length
138
   * mentionned at [80h] or to first CR or nul, whichever comes first.
139
   */
140
 
349 mateuszvis 141
  memset(cfg, 0, sizeof(*cfg));
350 mateuszvis 142
 
1715 mateusz.vi 143
  /* Make sure that the advertised cmdline length is no more than 126 bytes
144
   * because the PSP ends at [0xff] and there ought to be at least 1 byte of
145
   * room for the CR-terminator.
146
   * According to Matthias Paul cmdlines longer than 126 (and even longer than
147
   * 127) might happen with some buggy implementations. */
148
  if (*cmdlinelen > 126) *cmdlinelen = 126;
443 mateuszvis 149
 
1715 mateusz.vi 150
  /* trim out any trailing CR garbage (see the issue 67 mentioned above) */
151
  while ((*cmdlinelen > 0) && (cmdline[*cmdlinelen - 1] == '\r')) (*cmdlinelen)--;
152
 
153
  /* normalize the cmd so it is nul-terminated - this is expected later in a
154
   * few places in the codeflow, among others in run_as_external() */
155
  cmdline[*cmdlinelen] = 0;
156
 
157
  /* process the parameters given to COMMAND.COM */
158
  while (*cmdline != 0) {
159
 
443 mateuszvis 160
    /* skip over any leading spaces */
491 mateuszvis 161
    if (*cmdline == ' ') {
162
      cmdline++;
163
      continue;
349 mateuszvis 164
    }
443 mateuszvis 165
 
491 mateuszvis 166
    if (*cmdline != '/') {
989 mateusz.vi 167
      nls_output(0,6); /* "Invalid parameter" */
168
      output(": ");
491 mateuszvis 169
      outputnl(cmdline);
170
      goto SKIP_TO_NEXT_ARG;
171
    }
443 mateuszvis 172
 
491 mateuszvis 173
    /* got a slash */
174
    cmdline++;  /* skip the slash */
175
    switch (*cmdline) {
176
      case 'c': /* /C = execute command and quit */
177
      case 'C':
178
        cfg->flags |= FLAG_EXEC_AND_QUIT;
179
        /* FALLTHRU */
180
      case 'k': /* /K = execute command and keep running */
181
      case 'K':
1001 mateusz.vi 182
        cmdline++;
183
        cfg->execcmd = cmdline;
1715 mateusz.vi 184
        return; /* further arguments are for the executed program, not for me */
443 mateuszvis 185
 
1001 mateusz.vi 186
      case 'y': /* /Y = execute batch file step-by-step (with /P, /K or /C) */
187
      case 'Y':
188
        cfg->flags |= FLAG_STEPBYSTEP;
189
        break;
190
 
494 mateuszvis 191
      case 'd': /* /D = skip autoexec.bat processing */
192
      case 'D':
193
        cfg->flags |= FLAG_SKIP_AUTOEXEC;
194
        break;
195
 
491 mateuszvis 196
      case 'e': /* preset the initial size of the environment block */
197
      case 'E':
198
        cmdline++;
199
        if (*cmdline == ':') cmdline++; /* could be /E:size */
200
        atous(&(cfg->envsiz), cmdline);
201
        if (cfg->envsiz < 64) cfg->envsiz = 0;
202
        break;
449 mateuszvis 203
 
491 mateuszvis 204
      case 'p': /* permanent shell (can't exit + run autoexec.bat) */
205
      case 'P':
206
        cfg->flags |= FLAG_PERMANENT;
207
        break;
444 mateuszvis 208
 
491 mateuszvis 209
      case '?':
989 mateusz.vi 210
        nls_outputnl(1,0); /* "Starts the SvarCOM command interpreter" */
491 mateuszvis 211
        outputnl("");
989 mateusz.vi 212
        nls_outputnl(1,1); /* "COMMAND /E:nnn [/[C|K] [/P] [/D] command]" */
491 mateuszvis 213
        outputnl("");
989 mateusz.vi 214
        nls_outputnl(1,2); /* "/D      Skip AUTOEXEC.BAT processing (makes sense only with /P)" */
215
        nls_outputnl(1,3); /* "/E:nnn  Sets the environment size to nnn bytes" */
216
        nls_outputnl(1,4); /* "/P      Makes the new command interpreter permanent and run AUTOEXEC.BAT" */
217
        nls_outputnl(1,5); /* "/C      Executes the specified command and returns" */
218
        nls_outputnl(1,6); /* "/K      Executes the specified command and continues running" */
1001 mateusz.vi 219
        nls_outputnl(1,7); /* "/Y      Executes the batch program step by step" */
491 mateuszvis 220
        exit(1);
221
        break;
222
 
223
      default:
989 mateusz.vi 224
        nls_output(0,2); /* invalid switch */
225
        output(": /");
491 mateuszvis 226
        outputnl(cmdline);
227
        break;
350 mateuszvis 228
    }
443 mateuszvis 229
 
230
    /* move to next argument or quit processing if end of cmdline */
491 mateuszvis 231
    SKIP_TO_NEXT_ARG:
1715 mateusz.vi 232
    while ((*cmdline != 0) && (*cmdline != ' ') && (*cmdline != '/')) cmdline++;
349 mateuszvis 233
  }
234
}
235
 
236
 
1798 mateusz.vi 237
/* returns current DOS drive (0 = A: ; 1 = B: etc) */
238
static unsigned char _dosgetcurdrive(void);
239
#pragma aux _dosgetcurdrive = \
240
"mov ah, 0x19"    /* DOS 1+ - GET CURRENT DRIVE */ \
241
"int 0x21" \
242
modify [ah] \
243
value [al]
244
 
245
 
246
static void _dosgetcurdir(char near *s);
247
#pragma aux _dosgetcurdir = \
248
"mov ah, 0x47"    /* DOS 2+ - CWD - GET CURRENT DIRECTORY */ \
249
"xor dl, dl"      /* DL = drive number (00h = default, 01h = A:, etc) */ \
250
"int 0x21" \
251
parm [si] \
252
modify [ax dl]
253
 
254
 
474 mateuszvis 255
/* builds the prompt string and displays it. buff is filled with a zero-terminated copy of the prompt. */
256
static void build_and_display_prompt(char *buff, unsigned short envseg) {
257
  char *s = buff;
1823 mateusz.vi 258
 
370 mateuszvis 259
  /* locate the prompt variable or use the default pattern */
438 mateuszvis 260
  const char far *fmt = env_lookup_val(envseg, "PROMPT");
370 mateuszvis 261
  if ((fmt == NULL) || (*fmt == 0)) fmt = "$p$g"; /* fallback to default if empty */
1823 mateusz.vi 262
 
370 mateuszvis 263
  /* build the prompt string based on pattern */
354 mateuszvis 264
  for (; *fmt != 0; fmt++) {
265
    if (*fmt != '$') {
266
      *s = *fmt;
267
      s++;
268
      continue;
269
    }
270
    /* escape code ($P, etc) */
271
    fmt++;
272
    switch (*fmt) {
273
      case 'Q':  /* $Q = = (equal sign) */
274
      case 'q':
275
        *s = '=';
276
        s++;
277
        break;
278
      case '$':  /* $$ = $ (dollar sign) */
279
        *s = '$';
280
        s++;
281
        break;
282
      case 'T':  /* $t = current time */
283
      case 't':
1823 mateusz.vi 284
      {
285
        struct nls_patterns nls;
286
        unsigned char h, m, sec;
287
        if (nls_getpatterns(&nls) != 0) {
288
          s += sprintf(s, "ERR");
289
        } else {
290
          dos_get_time(&h, &m, &sec);
291
          s += nls_format_time(s, h, m, sec, &nls);
292
        }
354 mateuszvis 293
        break;
1823 mateusz.vi 294
      }
354 mateuszvis 295
      case 'D':  /* $D = current date */
296
      case 'd':
1823 mateusz.vi 297
      {
298
        struct nls_patterns nls;
299
        unsigned short y;
300
        unsigned char m, d;
301
        if (nls_getpatterns(&nls) != 0) {
302
          s += sprintf(s, "ERR");
303
        } else {
304
          dos_get_date(&y, &m, &d);
305
          s += nls_format_date(s, y, m, d, &nls);
306
        }
354 mateuszvis 307
        break;
1823 mateusz.vi 308
      }
354 mateuszvis 309
      case 'P':  /* $P = current drive and path */
310
      case 'p':
1798 mateusz.vi 311
        *s = _dosgetcurdrive() + 'A';
354 mateuszvis 312
        s++;
313
        *s = ':';
314
        s++;
315
        *s = '\\';
316
        s++;
1798 mateusz.vi 317
        _dosgetcurdir(s);
318
        /* move s ptr forward to end (0-termintor) of pathname */
319
        while (*s != 0) s++;
354 mateuszvis 320
        break;
1822 mateusz.vi 321
      case 'V':  /* $V = version number */
354 mateuszvis 322
      case 'v':
1822 mateusz.vi 323
        s += sprintf(s, PVER);
354 mateuszvis 324
        break;
325
      case 'N':  /* $N = current drive */
326
      case 'n':
1798 mateusz.vi 327
        *s = _dosgetcurdrive() + 'A';
354 mateuszvis 328
        s++;
329
        break;
330
      case 'G':  /* $G = > (greater-than sign) */
331
      case 'g':
332
        *s = '>';
333
        s++;
334
        break;
335
      case 'L':  /* $L = < (less-than sign) */
336
      case 'l':
337
        *s = '<';
338
        s++;
339
        break;
340
      case 'B':  /* $B = | (pipe) */
341
      case 'b':
342
        *s = '|';
343
        s++;
344
        break;
345
      case 'H':  /* $H = backspace (erases previous character) */
346
      case 'h':
347
        *s = '\b';
348
        s++;
349
        break;
350
      case 'E':  /* $E = Escape code (ASCII 27) */
351
      case 'e':
352
        *s = 27;
353
        s++;
354
        break;
355
      case '_':  /* $_ = CR+LF */
356
        *s = '\r';
357
        s++;
358
        *s = '\n';
359
        s++;
360
        break;
361
    }
362
  }
474 mateuszvis 363
  *s = 0;
364
  output(buff);
354 mateuszvis 365
}
349 mateuszvis 366
 
367
 
1797 mateusz.vi 368
static void dos_fname2fcb(char far *fcb, const char near *cmd);
369
#pragma aux dos_fname2fcb = \
370
"mov ax, 0x2900"   /* DOS 1+ - parse filename into FCB (DS:SI=fname, ES:DI=FCB) */ \
371
"int 0x21" \
372
parm [es di] [si] \
373
modify [ax si]
1156 mateusz.vi 374
 
375
 
376
/* parses cmdtail and fills fcb1 and fcb2 with first and second arguments,
377
 * respectively. an FCB is 12 bytes long:
378
 * drive (0=default, 1=A, 2=B, etc)
379
 * fname (8 chars, blank-padded)
380
 * fext (3 chars, blank-padded) */
381
static void cmdtail_to_fcb(char far *fcb1, char far *fcb2, const char *cmdtail) {
382
 
383
  /* skip any leading spaces */
384
  while (*cmdtail == ' ') cmdtail++;
385
 
386
  /* convert first arg */
387
  dos_fname2fcb(fcb1, cmdtail);
388
 
389
  /* skip to next arg */
390
  while ((*cmdtail != ' ') && (*cmdtail != 0)) cmdtail++;
391
  while (*cmdtail == ' ') cmdtail++;
392
 
393
  /* convert second arg */
394
  dos_fname2fcb(fcb2, cmdtail);
395
}
396
 
397
 
957 mateusz.vi 398
/* a few internal flags */
399
#define DELETE_STDIN_FILE 1
400
#define CALL_FLAG         2
1730 mateusz.vi 401
#define LOADHIGH_FLAG     4
957 mateusz.vi 402
 
403
static void run_as_external(char *buff, const char *cmdline, unsigned short envseg, struct rmod_props far *rmod, struct redir_data *redir, unsigned char flags) {
472 mateuszvis 404
  char *cmdfile = buff + 512;
458 mateuszvis 405
  const char far *pathptr;
406
  int lookup;
407
  unsigned short i;
408
  const char *ext;
508 mateuszvis 409
  char *cmd = buff + 1024;
479 mateuszvis 410
  const char *cmdtail;
461 mateuszvis 411
  char far *rmod_execprog = MK_FP(rmod->rmodseg, RMOD_OFFSET_EXECPROG);
412
  char far *rmod_cmdtail = MK_FP(rmod->rmodseg, 0x81);
413
  _Packed struct {
414
    unsigned short envseg;
415
    unsigned long cmdtail;
416
    unsigned long fcb1;
417
    unsigned long fcb2;
418
  } far *ExecParam = MK_FP(rmod->rmodseg, RMOD_OFFSET_EXECPARAM);
364 mateuszvis 419
 
472 mateuszvis 420
  /* find cmd and cmdtail */
421
  i = 0;
422
  cmdtail = cmdline;
423
  while (*cmdtail == ' ') cmdtail++; /* skip any leading spaces */
424
  while ((*cmdtail != ' ') && (*cmdtail != '/') && (*cmdtail != '+') && (*cmdtail != 0)) {
425
    cmd[i++] = *cmdtail;
426
    cmdtail++;
427
  }
428
  cmd[i] = 0;
364 mateuszvis 429
 
458 mateuszvis 430
  /* is this a command in curdir? */
472 mateuszvis 431
  lookup = lookup_cmd(cmdfile, cmd, NULL, &ext);
458 mateuszvis 432
  if (lookup == 0) {
433
    /* printf("FOUND LOCAL EXEC FILE: '%s'\r\n", cmdfile); */
434
    goto RUNCMDFILE;
435
  } else if (lookup == -2) {
436
    /* puts("NOT FOUND"); */
437
    return;
438
  }
439
 
440
  /* try matching something in PATH */
441
  pathptr = env_lookup_val(envseg, "PATH");
442
 
443
  /* try each path in %PATH% */
571 mateuszvis 444
  while (pathptr) {
458 mateuszvis 445
    for (i = 0;; i++) {
446
      buff[i] = *pathptr;
447
      if ((buff[i] == 0) || (buff[i] == ';')) break;
448
      pathptr++;
449
    }
450
    buff[i] = 0;
472 mateuszvis 451
    lookup = lookup_cmd(cmdfile, cmd, buff, &ext);
571 mateuszvis 452
    if (lookup == 0) goto RUNCMDFILE;
458 mateuszvis 453
    if (lookup == -2) return;
454
    if (*pathptr == ';') {
455
      pathptr++;
456
    } else {
571 mateuszvis 457
      break;
458 mateuszvis 458
    }
459
  }
460
 
571 mateuszvis 461
  /* last chance: is it an executable link? (trim extension from cmd first) */
462
  for (i = 0; (cmd[i] != 0) && (cmd[i] != '.') && (i < 9); i++) buff[128 + i] = cmd[i];
463
  buff[128 + i] = 0;
464
  if ((i < 9) && (link_computefname(buff, buff + 128, envseg) == 0)) {
465
    /* try opening the link file (if it exists) and read it into buff */
466
    i = 0;
467
    _asm {
468
      push ax
469
      push bx
470
      push cx
471
      push dx
472
 
473
      mov ax, 0x3d00  /* DOS 2+ - OPEN EXISTING FILE, READ-ONLY */
474
      mov dx, buff    /* file name */
475
      int 0x21
476
      jc ERR_FOPEN
477
      /* file handle in AX, read from file now */
478
      mov bx, ax      /* file handle */
479
      mov ah, 0x3f    /* Read from file via handle bx */
480
      mov cx, 128     /* up to 128 bytes */
481
      /* mov dx, buff */ /* dest buffer (already set) */
482
      int 0x21        /* read up to 256 bytes from file and write to buff */
483
      jc ERR_READ
484
      mov i, ax
485
      ERR_READ:
486
      mov ah, 0x3e    /* close file handle in BX */
487
      int 0x21
488
      ERR_FOPEN:
489
 
490
      pop dx
491
      pop cx
492
      pop bx
493
      pop ax
494
    }
495
 
496
    /* did I read anything? */
497
    if (i != 0) {
498
      buff[i] = 0;
499
      /* trim buff at first \n or \r, just in case someone fiddled with the
500
       * link file using a text editor */
501
      for (i = 0; (buff[i] != 0) && (buff[i] != '\r') && (buff[i] != '\n'); i++);
502
      buff[i] = 0;
503
      /* lookup check */
504
      if (buff[0] != 0) {
505
        lookup = lookup_cmd(cmdfile, cmd, buff, &ext);
506
        if (lookup == 0) goto RUNCMDFILE;
507
      }
508
    }
509
  }
510
 
511
  /* all failed (ie. executable file not found) */
512
  return;
513
 
458 mateuszvis 514
  RUNCMDFILE:
515
 
469 mateuszvis 516
  /* special handling of batch files */
517
  if ((ext != NULL) && (imatch(ext, "bat"))) {
957 mateusz.vi 518
    struct batctx far *newbat;
519
 
520
    /* remember the echo flag (in case bat file disables echo, only when starting first bat) */
521
    if (rmod->bat == NULL) {
522
      rmod->flags &= ~FLAG_ECHO_BEFORE_BAT;
523
      if (rmod->flags & FLAG_ECHOFLAG) rmod->flags |= FLAG_ECHO_BEFORE_BAT;
949 mateusz.vi 524
    }
957 mateusz.vi 525
 
526
    /* if bat is not called via a CALL, then free the bat-context linked list */
963 mateusz.vi 527
    if ((flags & CALL_FLAG) == 0) rmod_free_bat_llist(rmod);
528
 
957 mateusz.vi 529
    /* allocate a new bat context */
530
    newbat = rmod_fcalloc(sizeof(struct batctx), rmod->rmodseg, "SVBATCTX");
531
    if (newbat == NULL) {
532
      nls_outputnl_doserr(8); /* insufficient memory */
949 mateusz.vi 533
      return;
534
    }
535
 
957 mateusz.vi 536
    /* fill the newly allocated batctx structure */
537
    _fstrcpy(newbat->fname, cmdfile); /* truename of the BAT file */
1001 mateusz.vi 538
    newbat->flags = flags & FLAG_STEPBYSTEP;
508 mateuszvis 539
    /* explode args of the bat file and store them in rmod buff */
540
    cmd_explode(buff, cmdline, NULL);
957 mateusz.vi 541
    _fmemcpy(newbat->argv, buff, sizeof(newbat->argv));
508 mateuszvis 542
 
957 mateusz.vi 543
    /* push the new bat to the top of rmod's linked list */
544
    newbat->parent = rmod->bat;
545
    rmod->bat = newbat;
546
 
469 mateuszvis 547
    return;
548
  }
549
 
517 mateuszvis 550
  /* copy full filename to execute, along with redirected files (if any) */
548 mateuszvis 551
  _fstrcpy(rmod_execprog, cmdfile);
552
 
553
  /* copy stdin file if a redirection is needed */
517 mateuszvis 554
  if (redir->stdinfile) {
548 mateuszvis 555
    char far *farptr = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDINFILE);
576 mateuszvis 556
    char far *delstdin = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDIN_DEL);
548 mateuszvis 557
    _fstrcpy(farptr, redir->stdinfile);
957 mateusz.vi 558
    if (flags & DELETE_STDIN_FILE) {
576 mateuszvis 559
      *delstdin = redir->stdinfile[0];
560
    } else {
561
      *delstdin = 0;
562
    }
517 mateuszvis 563
  }
548 mateuszvis 564
 
565
  /* same for stdout file */
517 mateuszvis 566
  if (redir->stdoutfile) {
548 mateuszvis 567
    char far *farptr = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDOUTFILE);
568
    unsigned short far *farptr16 = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDOUTAPP);
569
    _fstrcpy(farptr, redir->stdoutfile);
517 mateuszvis 570
    /* openflag */
548 mateuszvis 571
    *farptr16 = redir->stdout_openflag;
517 mateuszvis 572
  }
461 mateuszvis 573
 
574
  /* copy cmdtail to rmod's PSP and compute its len */
575
  for (i = 0; cmdtail[i] != 0; i++) rmod_cmdtail[i] = cmdtail[i];
576
  rmod_cmdtail[i] = '\r';
577
  rmod_cmdtail[-1] = i;
578
 
579
  /* set up rmod to execute the command */
580
 
1730 mateusz.vi 581
  /* loadhigh? */
582
  if (flags & LOADHIGH_FLAG) {
583
    unsigned char far *farptr = MK_FP(rmod->rmodseg, RMOD_OFFSET_EXEC_LH);
584
    *farptr = 1;
585
  }
586
 
464 mateuszvis 587
  ExecParam->envseg = envseg;
461 mateuszvis 588
  ExecParam->cmdtail = (unsigned long)MK_FP(rmod->rmodseg, 0x80); /* farptr, must be in PSP format (lenbyte args \r) */
1156 mateusz.vi 589
  /* far pointers to unopened FCB entries (stored in RMOD's own PSP) */
590
  {
591
    char far *farptr;
592
    /* prep the unopened FCBs */
593
    farptr = MK_FP(rmod->rmodseg, 0x5C);
594
    _fmemset(farptr, 0, 36); /* first FCB is 16 bytes long, second is 20 bytes long */
595
    cmdtail_to_fcb(farptr, farptr + 16, cmdtail);
596
    /* set (far) pointers in the ExecParam block */
597
    ExecParam->fcb1 = (unsigned long)MK_FP(rmod->rmodseg, 0x5C);
598
    ExecParam->fcb2 = (unsigned long)MK_FP(rmod->rmodseg, 0x6C);
599
  }
461 mateuszvis 600
  exit(0); /* let rmod do the job now */
364 mateuszvis 601
}
602
 
603
 
367 mateuszvis 604
static void set_comspec_to_self(unsigned short envseg) {
605
  unsigned short *psp_envseg = (void *)(0x2c); /* pointer to my env segment field in the PSP */
606
  char far *myenv = MK_FP(*psp_envseg, 0);
607
  unsigned short varcount;
608
  char buff[256] = "COMSPEC=";
609
  char *buffptr = buff + 8;
610
  /* who am i? look into my own environment, at the end of it should be my EXEPATH string */
611
  while (*myenv != 0) {
612
    /* consume a NULL-terminated string */
613
    while (*myenv != 0) myenv++;
614
    /* move to next string */
615
    myenv++;
616
  }
617
  /* get next word, if 1 then EXEPATH follows */
618
  myenv++;
619
  varcount = *myenv;
620
  myenv++;
621
  varcount |= (*myenv << 8);
622
  myenv++;
623
  if (varcount != 1) return; /* NO EXEPATH FOUND */
624
  while (*myenv != 0) {
625
    *buffptr = *myenv;
626
    buffptr++;
627
    myenv++;
628
  }
629
  *buffptr = 0;
630
  /* printf("EXEPATH: '%s'\r\n", buff); */
631
  env_setvar(envseg, buff);
632
}
633
 
634
 
450 mateuszvis 635
/* wait for user input */
1797 mateusz.vi 636
static void cmdline_getinput(unsigned short inpseg, unsigned short inpoff);
637
#pragma aux cmdline_getinput = \
638
"push ds" \
639
/* set up buffered input to inpseg:inpoff */ \
640
"push ax" \
641
"pop ds" \
642
\
643
/* is DOSKEY support present? (INT 2Fh, AX=4800h, returns non-zero in AL if present) */ \
644
"mov ax, 0x4800" \
645
"int 0x2f" \
646
\
647
/* execute either DOS input or DOSKEY */ \
648
"test al, al" /* al=0 if no DOSKEY present */ \
649
"jnz DOSKEY" \
650
\
651
/* buffered string input */ \
652
"mov ah, 0x0a" \
653
"int 0x21" \
654
"jmp short DONE" \
655
\
656
"DOSKEY:" \
657
"mov ax, 0x4810" \
658
"int 0x2f" \
659
\
660
"DONE:" \
661
/* terminate command with a CR/LF */ \
662
"mov ah, 0x02" /* display character in dl */ \
663
"mov dl, 0x0d" \
664
"int 0x21" \
665
"mov dl, 0x0a" \
666
"int 0x21" \
667
"pop ds" \
668
parm [ax] [dx] \
669
modify [ax dl]
450 mateuszvis 670
 
671
 
479 mateuszvis 672
/* fetches a line from batch file and write it to buff (NULL-terminated),
673
 * increments rmod counter and returns 0 on success. */
484 mateuszvis 674
static int getbatcmd(char *buff, unsigned char buffmaxlen, struct rmod_props far *rmod) {
469 mateuszvis 675
  unsigned short i;
949 mateusz.vi 676
  unsigned short batname_seg = FP_SEG(rmod->bat->fname);
677
  unsigned short batname_off = FP_OFF(rmod->bat->fname);
678
  unsigned short filepos_cx = rmod->bat->nextline >> 16;
679
  unsigned short filepos_dx = rmod->bat->nextline & 0xffff;
474 mateuszvis 680
  unsigned char blen = 0;
505 mateuszvis 681
  unsigned short errv = 0;
474 mateuszvis 682
 
683
  /* open file, jump to offset filpos, and read data into buff.
684
   * result in blen (unchanged if EOF or failure). */
685
  _asm {
686
    push ax
687
    push bx
688
    push cx
689
    push dx
690
 
691
    /* open file (read-only) */
505 mateuszvis 692
    mov bx, 0xffff        /* preset BX to 0xffff to detect error conditions */
474 mateuszvis 693
    mov dx, batname_off
694
    mov ax, batname_seg
695
    push ds     /* save DS */
696
    mov ds, ax
697
    mov ax, 0x3d00
698
    int 0x21    /* handle in ax on success */
699
    pop ds      /* restore DS */
505 mateuszvis 700
    jc ERR
474 mateuszvis 701
    mov bx, ax  /* save handle to bx */
702
 
703
    /* jump to file offset CX:DX */
704
    mov ax, 0x4200
705
    mov cx, filepos_cx
706
    mov dx, filepos_dx
707
    int 0x21  /* CF clear on success, DX:AX set to cur pos */
505 mateuszvis 708
    jc ERR
474 mateuszvis 709
 
710
    /* read the line into buff */
711
    mov ah, 0x3f
484 mateuszvis 712
    xor ch, ch
713
    mov cl, buffmaxlen
474 mateuszvis 714
    mov dx, buff
715
    int 0x21 /* CF clear on success, AX=number of bytes read */
505 mateuszvis 716
    jc ERR
474 mateuszvis 717
    mov blen, al
505 mateuszvis 718
    jmp CLOSEANDQUIT
474 mateuszvis 719
 
505 mateuszvis 720
    ERR:
721
    mov errv, ax
722
 
474 mateuszvis 723
    CLOSEANDQUIT:
505 mateuszvis 724
    /* close file (if bx contains a handle) */
725
    cmp bx, 0xffff
726
    je DONE
474 mateuszvis 727
    mov ah, 0x3e
728
    int 0x21
729
 
730
    DONE:
731
    pop dx
732
    pop cx
733
    pop bx
734
    pop ax
469 mateuszvis 735
  }
470 mateuszvis 736
 
474 mateuszvis 737
  /* printf("blen=%u filepos_cx=%u filepos_dx=%u\r\n", blen, filepos_cx, filepos_dx); */
470 mateuszvis 738
 
538 mateuszvis 739
  if (errv != 0) nls_outputnl_doserr(errv);
505 mateuszvis 740
 
474 mateuszvis 741
  /* on EOF - abort processing the bat file */
742
  if (blen == 0) goto OOPS;
743
 
744
  /* find nearest \n to inc batch offset and replace \r by NULL terminator
745
   * I support all CR/LF, CR- and LF-terminated batch files */
746
  for (i = 0; i < blen; i++) {
747
    if ((buff[i] == '\r') || (buff[i] == '\n')) {
949 mateusz.vi 748
      if ((buff[i] == '\r') && ((i+1) < blen) && (buff[i+1] == '\n')) rmod->bat->nextline += 1;
474 mateuszvis 749
      break;
750
    }
751
  }
752
  buff[i] = 0;
949 mateusz.vi 753
  rmod->bat->nextline += i + 1;
474 mateuszvis 754
 
755
  return(0);
756
 
757
  OOPS:
949 mateusz.vi 758
  rmod->bat->fname[0] = 0;
759
  rmod->bat->nextline = 0;
474 mateuszvis 760
  return(-1);
469 mateuszvis 761
}
762
 
763
 
507 mateuszvis 764
/* replaces %-variables in a BAT line with resolved values:
765
 * %PATH%       -> replaced by the contend of the PATH env variable
766
 * %UNDEFINED%  -> undefined variables are replaced by nothing ("")
767
 * %NOTCLOSED   -> NOTCLOSED
768
 * %1           -> first argument of the batch file (or nothing if no arg) */
769
static void batpercrepl(char *res, unsigned short ressz, const char *line, const struct rmod_props far *rmod, unsigned short envseg) {
770
  unsigned short lastperc = 0xffff;
771
  unsigned short reslen = 0;
772
 
773
  if (ressz == 0) return;
774
  ressz--; /* reserve one byte for the NULL terminator */
775
 
776
  for (; (reslen < ressz) && (*line != 0); line++) {
777
    /* if not a percent, I don't care */
778
    if (*line != '%') {
779
      res[reslen++] = *line;
780
      continue;
781
    }
782
 
783
    /* *** perc char handling *** */
784
 
785
    /* closing perc? */
786
    if (lastperc != 0xffff) {
787
      /* %% is '%' */
788
      if (lastperc == reslen) {
789
        res[reslen++] = '%';
790
      } else {   /* otherwise variable name */
791
        const char far *ptr;
792
        res[reslen] = 0;
793
        reslen = lastperc;
1139 mateusz.vi 794
        nls_strtoup(res + reslen); /* turn varname uppercase before lookup */
507 mateuszvis 795
        ptr = env_lookup_val(envseg, res + reslen);
796
        if (ptr != NULL) {
797
          while ((*ptr != 0) && (reslen < ressz)) {
798
            res[reslen++] = *ptr;
799
            ptr++;
800
          }
801
        }
802
      }
803
      lastperc = 0xffff;
804
      continue;
805
    }
806
 
807
    /* digit? (bat arg) */
808
    if ((line[1] >= '0') && (line[1] <= '9')) {
508 mateuszvis 809
      unsigned short argid = line[1] - '0';
810
      unsigned short i;
949 mateusz.vi 811
      const char far *argv = "";
812
      if ((rmod != NULL) && (rmod->bat != NULL)) argv = rmod->bat->argv;
508 mateuszvis 813
 
814
      /* locate the proper arg */
815
      for (i = 0; i != argid; i++) {
816
        /* if string is 0, then end of list reached */
817
        if (*argv == 0) break;
818
        /* jump to next arg */
819
        while (*argv != 0) argv++;
820
        argv++;
821
      }
822
 
823
      /* copy the arg to result */
824
      for (i = 0; (argv[i] != 0) && (reslen < ressz); i++) {
825
        res[reslen++] = argv[i];
826
      }
507 mateuszvis 827
      line++;  /* skip the digit */
828
      continue;
829
    }
830
 
831
    /* opening perc */
832
    lastperc = reslen;
833
 
834
  }
835
 
836
  res[reslen] = 0;
837
}
838
 
839
 
1024 mateusz.vi 840
/* process the ongoing forloop, returns 0 on success, non-zero otherwise (no
841
   more things to process) */
842
static int forloop_process(char *res, struct forctx far *forloop) {
843
  unsigned short i, t;
844
  struct DTA *dta = (void *)0x80; /* default DTA at 80h in PSP */
1055 mateusz.vi 845
  char *fnameptr = dta->fname;
1070 mateusz.vi 846
  char *pathprefix = BUFFER + 256;
957 mateusz.vi 847
 
1070 mateusz.vi 848
  *pathprefix = 0;
849
 
1024 mateusz.vi 850
  TRYAGAIN:
851
 
852
  /* dta_inited: FindFirst() or FindNext()? */
853
  if (forloop->dta_inited == 0) {
854
 
1065 bttr 855
    /* copy next awaiting pattern to BUFFER (and skip all delimiters until
1054 mateusz.vi 856
     * next pattern or end of list) */
857
    t = 0;
1024 mateusz.vi 858
    for (i = 0;; i++) {
859
      BUFFER[i] = forloop->cmd[forloop->nextpat + i];
1070 mateusz.vi 860
      /* is this a delimiter? (all delimiters are already normalized to a space here) */
861
      if (BUFFER[i] == ' ') {
862
        BUFFER[i] = 0;
863
        t = 1;
864
      } else if (BUFFER[i] == 0) {
865
        /* end of patterns list */
866
        break;
867
      } else {
868
        /* quit if I got a pattern already */
869
        if (t == 1) break;
1024 mateusz.vi 870
      }
871
    }
872
 
873
    if (i == 0) return(-1);
874
 
875
    /* remember position of current pattern */
876
    forloop->curpat = forloop->nextpat;
877
 
878
    /* move nextpat forward to next pattern */
879
    i += forloop->nextpat;
880
    forloop->nextpat = i;
881
 
1055 mateusz.vi 882
    /* if this is a string and not a pattern, skip all the FindFirst business
883
     * a file pattern has a wildcard (* or ?), a message doesn't */
884
    for (i = 0; (BUFFER[i] != 0) && (BUFFER[i] != '?') && (BUFFER[i] != '*'); i++);
885
    if (BUFFER[i] == 0) {
886
      fnameptr = BUFFER;
887
      goto SKIP_DTA;
888
    }
889
 
1024 mateusz.vi 890
    /* FOR in MSDOS 6 includes hidden and system files, but not directories nor volumes */
891
    if (findfirst(dta, BUFFER, DOS_ATTR_RO | DOS_ATTR_HID | DOS_ATTR_SYS | DOS_ATTR_ARC) != 0) {
892
      goto TRYAGAIN;
893
    }
894
    forloop->dta_inited = 1;
895
  } else { /* dta in progress */
896
 
897
    /* copy forloop DTA to my local copy */
898
    _fmemcpy(dta, &(forloop->dta), sizeof(*dta));
899
 
900
    /* findnext() call */
901
    if (findnext(dta) != 0) {
902
      forloop->dta_inited = 0;
903
      goto TRYAGAIN;
904
    }
905
  }
906
 
907
  /* copy updated DTA to rmod */
908
  _fmemcpy(&(forloop->dta), dta, sizeof(*dta));
909
 
1070 mateusz.vi 910
  /* prefill pathprefix with the prefix (path) of the files */
911
  {
912
    short lastbk = -1;
913
    char far *c = forloop->cmd + forloop->curpat;
914
    for (i = 0;; i++) {
915
      pathprefix[i] = c[i];
916
      if (pathprefix[i] == '\\') lastbk = i;
917
      if ((pathprefix[i] == ' ') || (pathprefix[i] == 0)) break;
918
    }
919
    pathprefix[lastbk+1] = 0;
920
  }
921
 
1055 mateusz.vi 922
  SKIP_DTA:
923
 
1024 mateusz.vi 924
  /* fill res with command, replacing varname by actual filename */
925
  /* full filename is to be built with path of curpat and fname from dta */
926
  t = 0;
927
  i = 0;
928
  for (;;) {
929
    if ((forloop->cmd[forloop->exec + t] == '%') && (forloop->cmd[forloop->exec + t + 1] == forloop->varname)) {
1070 mateusz.vi 930
      strcpy(res + i, pathprefix);
931
      strcat(res + i, fnameptr);
932
      for (; res[i] != 0; i++);
1024 mateusz.vi 933
      t += 2;
934
    } else {
935
      res[i] = forloop->cmd[forloop->exec + t];
936
      t++;
937
      if (res[i++] == 0) break;
938
    }
939
  }
940
 
941
  return(0);
942
}
943
 
944
 
443 mateuszvis 945
int main(void) {
372 mateuszvis 946
  static struct config cfg;
947
  static unsigned short far *rmod_envseg;
948
  static unsigned short far *lastexitcode;
449 mateuszvis 949
  static struct rmod_props far *rmod;
500 mateuszvis 950
  static char cmdlinebuf[CMDLINE_MAXLEN + 2]; /* 1 extra byte for 0-terminator and another for memguard */
479 mateuszvis 951
  static char *cmdline;
517 mateuszvis 952
  static struct redir_data redirprops;
533 mateuszvis 953
  static enum cmd_result cmdres;
543 mateuszvis 954
  static unsigned short i; /* general-purpose variable for short-lived things */
957 mateusz.vi 955
  static unsigned char flags;
349 mateuszvis 956
 
479 mateuszvis 957
  rmod = rmod_find(BUFFER_len);
449 mateuszvis 958
  if (rmod == NULL) {
485 mateuszvis 959
    /* look at command line parameters (in case env size if set there) */
960
    parse_argv(&cfg);
479 mateuszvis 961
    rmod = rmod_install(cfg.envsiz, BUFFER, BUFFER_len);
449 mateuszvis 962
    if (rmod == NULL) {
989 mateusz.vi 963
      nls_outputnl_err(2,1); /* "FATAL ERROR: rmod_install() failed" */
349 mateuszvis 964
      return(1);
965
    }
475 mateuszvis 966
    /* copy flags to rmod's storage (and enable ECHO) */
967
    rmod->flags = cfg.flags | FLAG_ECHOFLAG;
465 mateuszvis 968
    /* printf("rmod installed at %Fp\r\n", rmod); */
572 mateuszvis 969
    rmod->version = BYTE_VERSION;
349 mateuszvis 970
  } else {
465 mateuszvis 971
    /* printf("rmod found at %Fp\r\n", rmod); */
972
    /* if I was spawned by rmod and FLAG_EXEC_AND_QUIT is set, then I should
973
     * die asap, because the command has been executed already, so I no longer
1824 mateusz.vi 974
     * have a purpose in life, UNLESS I still have a batch file to run or
975
     * a FOR loop to execute */
976
    if ((rmod->flags & FLAG_EXEC_AND_QUIT) && (rmod->bat == NULL) && (rmod->forloop == NULL)) {
977
      sayonara(rmod);
978
    }
572 mateuszvis 979
    /* */
980
    if (rmod->version != BYTE_VERSION) {
989 mateusz.vi 981
      nls_outputnl_err(2,0);
572 mateuszvis 982
      _asm {
983
        HALT:
984
        hlt
985
        jmp HALT
986
      }
987
    }
349 mateuszvis 988
  }
989
 
490 mateuszvis 990
  /* install a few guardvals in memory to detect some cases of overflows */
500 mateuszvis 991
  memguard_set(cmdlinebuf);
490 mateuszvis 992
 
465 mateuszvis 993
  rmod_envseg = MK_FP(rmod->rmodseg, RMOD_OFFSET_ENVSEG);
994
  lastexitcode = MK_FP(rmod->rmodseg, RMOD_OFFSET_LEXITCODE);
350 mateuszvis 995
 
1713 bttr 996
  /* make COMSPEC point to myself */
367 mateuszvis 997
  set_comspec_to_self(*rmod_envseg);
998
 
494 mateuszvis 999
  /* on /P check for the presence of AUTOEXEC.BAT and execute it if found,
1000
   * but skip this check if /D was also passed */
1001
  if ((cfg.flags & (FLAG_PERMANENT | FLAG_SKIP_AUTOEXEC)) == FLAG_PERMANENT) {
483 mateuszvis 1002
    if (file_getattr("AUTOEXEC.BAT") >= 0) cfg.execcmd = "AUTOEXEC.BAT";
1003
  }
1004
 
443 mateuszvis 1005
  do {
1023 mateusz.vi 1006
 
480 mateuszvis 1007
    /* terminate previous command with a CR/LF if ECHO ON (but not during BAT processing) */
949 mateusz.vi 1008
    if ((rmod->flags & FLAG_ECHOFLAG) && (rmod->bat == NULL)) outputnl("");
474 mateuszvis 1009
 
1010
    SKIP_NEWLINE:
1011
 
490 mateuszvis 1012
    /* memory check */
500 mateuszvis 1013
    memguard_check(rmod->rmodseg, cmdlinebuf);
474 mateuszvis 1014
 
500 mateuszvis 1015
    /* preset cmdline to point at the dedicated buffer */
1016
    cmdline = cmdlinebuf;
490 mateuszvis 1017
 
437 mateuszvis 1018
    /* (re)load translation strings if needed */
1019
    nls_langreload(BUFFER, *rmod_envseg);
1020
 
1024 mateusz.vi 1021
    /* am I inside a FOR loop? */
1022
    if (rmod->forloop) {
1023
      if (forloop_process(cmdlinebuf, rmod->forloop) != 0) {
1024
        rmod_ffree(rmod->forloop);
1025
        rmod->forloop = NULL;
1824 mateusz.vi 1026
        continue; /* needed so we quit if the FOR loop was ran through COMMAND/C */
1024 mateusz.vi 1027
      } else {
1028
        /* output prompt and command on screen if echo on and command is not
1029
         * inhibiting it with the @ prefix */
1030
        if (rmod->flags & FLAG_ECHOFLAG) {
1031
          build_and_display_prompt(BUFFER, *rmod_envseg);
1032
          outputnl(cmdline);
1033
        }
1034
        /* jump to command processing */
1035
        goto EXEC_CMDLINE;
1036
      }
1037
    }
1038
 
543 mateuszvis 1039
    /* load awaiting command, if any (used to run piped commands) */
1040
    if (rmod->awaitingcmd[0] != 0) {
1041
      _fstrcpy(cmdline, rmod->awaitingcmd);
1042
      rmod->awaitingcmd[0] = 0;
957 mateusz.vi 1043
      flags |= DELETE_STDIN_FILE;
543 mateuszvis 1044
      goto EXEC_CMDLINE;
576 mateuszvis 1045
    } else {
957 mateusz.vi 1046
      flags &= ~DELETE_STDIN_FILE;
543 mateuszvis 1047
    }
1048
 
1001 mateusz.vi 1049
    /* skip user input if I have a command to exec (/C or /K or /P) */
443 mateuszvis 1050
    if (cfg.execcmd != NULL) {
1051
      cmdline = cfg.execcmd;
1052
      cfg.execcmd = NULL;
1001 mateusz.vi 1053
      /* */
1054
      if (cfg.flags & FLAG_STEPBYSTEP) flags |= FLAG_STEPBYSTEP;
443 mateuszvis 1055
      goto EXEC_CMDLINE;
1056
    }
1057
 
469 mateuszvis 1058
    /* if batch file is being executed -> fetch next line */
949 mateusz.vi 1059
    if (rmod->bat != NULL) {
507 mateuszvis 1060
      if (getbatcmd(BUFFER, CMDLINE_MAXLEN, rmod) != 0) { /* end of batch */
949 mateusz.vi 1061
        struct batctx far *victim = rmod->bat;
1062
        rmod->bat = rmod->bat->parent;
1063
        rmod_ffree(victim);
957 mateusz.vi 1064
        /* end of batch? then restore echo flag as it was before running the (first) bat file */
949 mateusz.vi 1065
        if (rmod->bat == NULL) {
1066
          rmod->flags &= ~FLAG_ECHOFLAG;
1067
          if (rmod->flags & FLAG_ECHO_BEFORE_BAT) rmod->flags |= FLAG_ECHOFLAG;
1068
        }
474 mateuszvis 1069
        continue;
1070
      }
507 mateuszvis 1071
      /* %-decoding of variables (%PATH%, %1, %%...), result in cmdline */
1072
      batpercrepl(cmdline, CMDLINE_MAXLEN, BUFFER, rmod, *rmod_envseg);
480 mateuszvis 1073
      /* skip any leading spaces */
1074
      while (*cmdline == ' ') cmdline++;
960 mateusz.vi 1075
      /* skip batch labels */
1076
      if (*cmdline == ':') continue;
1001 mateusz.vi 1077
      /* step-by-step execution? */
1078
      if (rmod->bat->flags & FLAG_STEPBYSTEP) {
1079
        if (*cmdline == 0) continue; /* skip empty lines */
1080
        if (askchoice(cmdline, svarlang_str(0,10)) != 0) continue;
1081
      }
474 mateuszvis 1082
      /* output prompt and command on screen if echo on and command is not
1083
       * inhibiting it with the @ prefix */
479 mateuszvis 1084
      if ((rmod->flags & FLAG_ECHOFLAG) && (cmdline[0] != '@')) {
474 mateuszvis 1085
        build_and_display_prompt(BUFFER, *rmod_envseg);
479 mateuszvis 1086
        outputnl(cmdline);
474 mateuszvis 1087
      }
479 mateuszvis 1088
      /* skip the @ prefix if present, it is no longer useful */
1089
      if (cmdline[0] == '@') cmdline++;
469 mateuszvis 1090
    } else {
983 mateusz.vi 1091
      unsigned char far *rmod_inputbuf = MK_FP(rmod->rmodseg, RMOD_OFFSET_INPUTBUF);
1092
      /* invalidate input history if it appears to be damaged (could occur
1093
       * because of a stack overflow, for example if some stack-hungry TSR is
1094
       * being used) */
987 mateusz.vi 1095
      if ((rmod_inputbuf[0] != 128) || (rmod_inputbuf[rmod_inputbuf[1] + 2] != '\r') || (rmod_inputbuf[rmod_inputbuf[1] + 3] != 0xCA) || (rmod_inputbuf[rmod_inputbuf[1] + 4] != 0xFE)) {
1096
        rmod_inputbuf[0] = 128;  /* max allowed input length */
1097
        rmod_inputbuf[1] = 0;    /* string len stored in buffer */
1098
        rmod_inputbuf[2] = '\r'; /* string terminator */
1099
        rmod_inputbuf[3] = 0xCA; /* trailing signature */
1100
        rmod_inputbuf[4] = 0xFE; /* trailing signature */
989 mateusz.vi 1101
        nls_outputnl_err(2,2); /* "stack overflow detected, command history flushed" */
983 mateusz.vi 1102
      }
474 mateuszvis 1103
      /* interactive mode: display prompt (if echo enabled) and wait for user
1104
       * command line */
475 mateuszvis 1105
      if (rmod->flags & FLAG_ECHOFLAG) build_and_display_prompt(BUFFER, *rmod_envseg);
474 mateuszvis 1106
      /* collect user input */
983 mateusz.vi 1107
      cmdline_getinput(rmod->rmodseg, RMOD_OFFSET_INPUTBUF);
987 mateusz.vi 1108
      /* append stack-overflow detection signature to the end of the input buffer */
1109
      rmod_inputbuf[rmod_inputbuf[1] + 3] = 0xCA; /* trailing signature */
1110
      rmod_inputbuf[rmod_inputbuf[1] + 4] = 0xFE; /* trailing signature */
479 mateuszvis 1111
      /* copy it to local cmdline */
983 mateusz.vi 1112
      if (rmod_inputbuf[1] != 0) _fmemcpy(cmdline, rmod_inputbuf + 2, rmod_inputbuf[1]);
1113
      cmdline[rmod_inputbuf[1]] = 0; /* zero-terminate local buff (original is '\r'-terminated) */
469 mateuszvis 1114
    }
349 mateuszvis 1115
 
405 mateuszvis 1116
    /* if nothing entered, loop again (but without appending an extra CR/LF) */
479 mateuszvis 1117
    if (cmdline[0] == 0) goto SKIP_NEWLINE;
349 mateuszvis 1118
 
443 mateuszvis 1119
    /* I jump here when I need to exec an initial command (/C or /K) */
1120
    EXEC_CMDLINE:
1121
 
364 mateuszvis 1122
    /* move pointer forward to skip over any leading spaces */
1123
    while (*cmdline == ' ') cmdline++;
349 mateuszvis 1124
 
1138 mateusz.vi 1125
    /* sanitize separators into spaces */
1126
    for (i = 0; cmdline[i] != 0; i++) {
1127
      switch (cmdline[i]) {
1128
        case '\t':
1129
          cmdline[i] = ' ';
1130
      }
1131
    }
1132
 
1713 bttr 1133
    /* update rmod's ptr to COMSPEC so it is always up to date */
465 mateuszvis 1134
    rmod_updatecomspecptr(rmod->rmodseg, *rmod_envseg);
367 mateuszvis 1135
 
402 mateuszvis 1136
    /* handle redirections (if any) */
577 mateuszvis 1137
    i = redir_parsecmd(&redirprops, cmdline, rmod->awaitingcmd, *rmod_envseg);
543 mateuszvis 1138
    if (i != 0) {
1139
      nls_outputnl_doserr(i);
1140
      rmod->awaitingcmd[0] = 0;
1141
      continue;
1142
    }
402 mateuszvis 1143
 
364 mateuszvis 1144
    /* try matching (and executing) an internal command */
957 mateusz.vi 1145
    cmdres = cmd_process(rmod, *rmod_envseg, cmdline, BUFFER, sizeof(BUFFER), &redirprops, flags & DELETE_STDIN_FILE);
533 mateuszvis 1146
    if ((cmdres == CMD_OK) || (cmdres == CMD_FAIL)) {
443 mateuszvis 1147
      /* internal command executed */
533 mateuszvis 1148
    } else if (cmdres == CMD_CHANGED) { /* cmdline changed, needs to be reprocessed */
1149
      goto EXEC_CMDLINE;
957 mateusz.vi 1150
    } else if (cmdres == CMD_CHANGED_BY_CALL) { /* cmdline changed *specifically* by CALL */
1151
      /* the distinction is important since it changes the way batch files are processed */
1152
      flags |= CALL_FLAG;
1153
      goto EXEC_CMDLINE;
1730 mateusz.vi 1154
    } else if (cmdres == CMD_CHANGED_BY_LH) { /* cmdline changed *specifically* by LH */
1155
      flags |= LOADHIGH_FLAG;
1156
      goto EXEC_CMDLINE;
533 mateuszvis 1157
    } else if (cmdres == CMD_NOTFOUND) {
1158
      /* this was not an internal command, try matching an external command */
957 mateusz.vi 1159
      run_as_external(BUFFER, cmdline, *rmod_envseg, rmod, &redirprops, flags);
1160
 
1161
      /* is it a newly launched BAT file? */
949 mateusz.vi 1162
      if ((rmod->bat != NULL) && (rmod->bat->nextline == 0)) goto SKIP_NEWLINE;
533 mateuszvis 1163
      /* run_as_external() does not return on success, if I am still alive then
1164
       * external command failed to execute */
989 mateusz.vi 1165
      nls_outputnl(0,5); /* "Bad command or file name" */
1001 mateusz.vi 1166
    } else {
1167
      /* I should never ever land here */
1168
      outputnl("INTERNAL ERR: INVALID CMDRES");
353 mateuszvis 1169
    }
352 mateuszvis 1170
 
1001 mateusz.vi 1171
    /* reset one-time only flags */
1172
    flags &= ~CALL_FLAG;
1173
    flags &= ~FLAG_STEPBYSTEP;
1730 mateusz.vi 1174
    flags &= ~LOADHIGH_FLAG;
349 mateuszvis 1175
 
958 mateusz.vi 1176
    /* repeat unless /C was asked - but always finish running an ongoing batch
1177
     * file (otherwise only first BAT command would be executed with /C) */
1024 mateusz.vi 1178
  } while (((rmod->flags & FLAG_EXEC_AND_QUIT) == 0) || (rmod->bat != NULL) || (rmod->forloop != NULL));
349 mateuszvis 1179
 
449 mateuszvis 1180
  sayonara(rmod);
349 mateuszvis 1181
  return(0);
1182
}