Subversion Repositories SvarDOS

Rev

Rev 1987 | Rev 2213 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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