Subversion Repositories SvarDOS

Rev

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