Subversion Repositories SvarDOS

Rev

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