Subversion Repositories SvarDOS

Rev

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