Subversion Repositories SvarDOS

Rev

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