Subversion Repositories SvarDOS

Rev

Rev 1857 | Details | Compare with Previous | Last modification | View Log | RSS feed

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