Subversion Repositories SvarDOS

Rev

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