Subversion Repositories SvarDOS

Rev

Rev 526 | Rev 538 | 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
 *
4
 * Copyright (C) 2021 Mateusz Viste
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
 
31
#include <process.h>
32
 
352 mateuszvis 33
#include "cmd.h"
505 mateuszvis 34
#include "doserr.h"
366 mateuszvis 35
#include "env.h"
352 mateuszvis 36
#include "helpers.h"
402 mateuszvis 37
#include "redir.h"
351 mateuszvis 38
#include "rmodinit.h"
448 mateuszvis 39
#include "sayonara.h"
349 mateuszvis 40
 
479 mateuszvis 41
#include "rmodcore.h" /* rmod binary inside a BUFFER array */
443 mateuszvis 42
 
349 mateuszvis 43
struct config {
449 mateuszvis 44
  unsigned char flags; /* command.com flags, as defined in rmodinit.h */
443 mateuszvis 45
  char *execcmd;
410 mateuszvis 46
  unsigned short envsiz;
443 mateuszvis 47
};
349 mateuszvis 48
 
490 mateuszvis 49
/* max length of the cmdline storage (bytes) - includes also max length of
50
 * line loaded from a BAT file (no more than 255 bytes!) */
51
#define CMDLINE_MAXLEN 255
349 mateuszvis 52
 
490 mateuszvis 53
 
54
/* sets guard values at a few places in memory for later detection of
55
 * overflows via memguard_check() */
500 mateuszvis 56
static void memguard_set(char *cmdlinebuf) {
490 mateuszvis 57
  BUFFER[sizeof(BUFFER) - 1] = 0xC7;
500 mateuszvis 58
  cmdlinebuf[CMDLINE_MAXLEN] = 0xC7;
490 mateuszvis 59
}
60
 
61
 
62
/* checks for valguards at specific memory locations, returns 0 on success */
500 mateuszvis 63
static int memguard_check(unsigned short rmodseg, char *cmdlinebuf) {
490 mateuszvis 64
  /* check RMOD signature (would be overwritten in case of stack overflow */
65
  static char msg[] = "!! MEMORY CORRUPTION ## DETECTED !!";
66
  unsigned short far *rmodsig = MK_FP(rmodseg, 0x100 + 6);
67
  if (*rmodsig != 0x2019) {
68
    msg[22] = '1';
69
    outputnl(msg);
70
    printf("rmodseg = %04X ; *rmodsig = %04X\r\n", rmodseg, *rmodsig);
71
    return(1);
72
  }
500 mateuszvis 73
  /* check last BUFFER byte */
490 mateuszvis 74
  if (BUFFER[sizeof(BUFFER) - 1] != 0xC7) {
75
    msg[22] = '2';
76
    outputnl(msg);
77
    return(2);
78
  }
500 mateuszvis 79
  /* check last cmdlinebuf byte */
80
  if (cmdlinebuf[CMDLINE_MAXLEN] != 0xC7) {
490 mateuszvis 81
    msg[22] = '3';
82
    outputnl(msg);
83
    return(3);
84
  }
85
  /* all good */
86
  return(0);
87
}
88
 
89
 
443 mateuszvis 90
/* parses command line the hard way (directly from PSP) */
91
static void parse_argv(struct config *cfg) {
491 mateuszvis 92
  const unsigned char *cmdlinelen = (void *)0x80;
93
  char *cmdline = (void *)0x81;
443 mateuszvis 94
 
349 mateuszvis 95
  memset(cfg, 0, sizeof(*cfg));
350 mateuszvis 96
 
443 mateuszvis 97
  /* set a NULL terminator on cmdline */
98
  cmdline[*cmdlinelen] = 0;
99
 
491 mateuszvis 100
  while (*cmdline != 0) {
443 mateuszvis 101
 
102
    /* skip over any leading spaces */
491 mateuszvis 103
    if (*cmdline == ' ') {
104
      cmdline++;
105
      continue;
349 mateuszvis 106
    }
443 mateuszvis 107
 
491 mateuszvis 108
    if (*cmdline != '/') {
443 mateuszvis 109
      output("Invalid parameter: ");
491 mateuszvis 110
      outputnl(cmdline);
111
      goto SKIP_TO_NEXT_ARG;
112
    }
443 mateuszvis 113
 
491 mateuszvis 114
    /* got a slash */
115
    cmdline++;  /* skip the slash */
116
    switch (*cmdline) {
117
      case 'c': /* /C = execute command and quit */
118
      case 'C':
119
        cfg->flags |= FLAG_EXEC_AND_QUIT;
120
        /* FALLTHRU */
121
      case 'k': /* /K = execute command and keep running */
122
      case 'K':
123
        cfg->execcmd = cmdline + 1;
124
        return;
443 mateuszvis 125
 
494 mateuszvis 126
      case 'd': /* /D = skip autoexec.bat processing */
127
      case 'D':
128
        cfg->flags |= FLAG_SKIP_AUTOEXEC;
129
        break;
130
 
491 mateuszvis 131
      case 'e': /* preset the initial size of the environment block */
132
      case 'E':
133
        cmdline++;
134
        if (*cmdline == ':') cmdline++; /* could be /E:size */
135
        atous(&(cfg->envsiz), cmdline);
136
        if (cfg->envsiz < 64) cfg->envsiz = 0;
137
        break;
449 mateuszvis 138
 
491 mateuszvis 139
      case 'p': /* permanent shell (can't exit + run autoexec.bat) */
140
      case 'P':
141
        cfg->flags |= FLAG_PERMANENT;
142
        break;
444 mateuszvis 143
 
491 mateuszvis 144
      case '?':
145
        outputnl("Starts the SvarCOM command interpreter");
146
        outputnl("");
494 mateuszvis 147
        outputnl("COMMAND /E:nnn [/[C|K] [/P] [/D] command]");
491 mateuszvis 148
        outputnl("");
494 mateuszvis 149
        outputnl("/D      Skip AUTOEXEC.BAT processing (makes sense only with /P)");
150
        outputnl("/E:nnn  Sets the environment size to nnn bytes");
151
        outputnl("/P      Makes the new command interpreter permanent and run AUTOEXEC.BAT");
152
        outputnl("/C      Executes the specified command and returns");
153
        outputnl("/K      Executes the specified command and continues running");
491 mateuszvis 154
        exit(1);
155
        break;
156
 
157
      default:
494 mateuszvis 158
        output("Invalid switch: /");
491 mateuszvis 159
        outputnl(cmdline);
160
        break;
350 mateuszvis 161
    }
443 mateuszvis 162
 
163
    /* move to next argument or quit processing if end of cmdline */
491 mateuszvis 164
    SKIP_TO_NEXT_ARG:
165
    while ((*cmdline != 0) && (*cmdline != ' ') && (*cmdline != '/')) cmdline++;
349 mateuszvis 166
  }
167
}
168
 
169
 
474 mateuszvis 170
/* builds the prompt string and displays it. buff is filled with a zero-terminated copy of the prompt. */
171
static void build_and_display_prompt(char *buff, unsigned short envseg) {
172
  char *s = buff;
370 mateuszvis 173
  /* locate the prompt variable or use the default pattern */
438 mateuszvis 174
  const char far *fmt = env_lookup_val(envseg, "PROMPT");
370 mateuszvis 175
  if ((fmt == NULL) || (*fmt == 0)) fmt = "$p$g"; /* fallback to default if empty */
176
  /* build the prompt string based on pattern */
354 mateuszvis 177
  for (; *fmt != 0; fmt++) {
178
    if (*fmt != '$') {
179
      *s = *fmt;
180
      s++;
181
      continue;
182
    }
183
    /* escape code ($P, etc) */
184
    fmt++;
185
    switch (*fmt) {
186
      case 'Q':  /* $Q = = (equal sign) */
187
      case 'q':
188
        *s = '=';
189
        s++;
190
        break;
191
      case '$':  /* $$ = $ (dollar sign) */
192
        *s = '$';
193
        s++;
194
        break;
195
      case 'T':  /* $t = current time */
196
      case 't':
197
        s += sprintf(s, "00:00"); /* TODO */
198
        break;
199
      case 'D':  /* $D = current date */
200
      case 'd':
201
        s += sprintf(s, "1985-07-29"); /* TODO */
202
        break;
203
      case 'P':  /* $P = current drive and path */
204
      case 'p':
205
        _asm {
206
          mov ah, 0x19    /* DOS 1+ - GET CURRENT DRIVE */
207
          int 0x21
208
          mov bx, s
209
          mov [bx], al  /* AL = drive (00 = A:, 01 = B:, etc */
210
        }
211
        *s += 'A';
212
        s++;
213
        *s = ':';
214
        s++;
215
        *s = '\\';
216
        s++;
217
        _asm {
218
          mov ah, 0x47    /* DOS 2+ - CWD - GET CURRENT DIRECTORY */
219
          xor dl,dl       /* DL = drive number (00h = default, 01h = A:, etc) */
220
          mov si, s       /* DS:SI -> 64-byte buffer for ASCIZ pathname */
221
          int 0x21
526 mateuszvis 222
          jc DONE         /* leave path empty on error */
223
          /* move s ptr forward to end (0-termintor) of pathname */
224
          NEXTBYTE:
225
          mov si, s
226
          cmp byte ptr [si], 0
227
          je DONE
228
          inc s
229
          jmp NEXTBYTE
230
          DONE:
354 mateuszvis 231
        }
232
        break;
233
      case 'V':  /* $V = DOS version number */
234
      case 'v':
235
        s += sprintf(s, "VER"); /* TODO */
236
        break;
237
      case 'N':  /* $N = current drive */
238
      case 'n':
239
        _asm {
240
          mov ah, 0x19    /* DOS 1+ - GET CURRENT DRIVE */
241
          int 0x21
242
          mov bx, s
243
          mov [bx], al  /* AL = drive (00 = A:, 01 = B:, etc */
244
        }
245
        *s += 'A';
246
        s++;
247
        break;
248
      case 'G':  /* $G = > (greater-than sign) */
249
      case 'g':
250
        *s = '>';
251
        s++;
252
        break;
253
      case 'L':  /* $L = < (less-than sign) */
254
      case 'l':
255
        *s = '<';
256
        s++;
257
        break;
258
      case 'B':  /* $B = | (pipe) */
259
      case 'b':
260
        *s = '|';
261
        s++;
262
        break;
263
      case 'H':  /* $H = backspace (erases previous character) */
264
      case 'h':
265
        *s = '\b';
266
        s++;
267
        break;
268
      case 'E':  /* $E = Escape code (ASCII 27) */
269
      case 'e':
270
        *s = 27;
271
        s++;
272
        break;
273
      case '_':  /* $_ = CR+LF */
274
        *s = '\r';
275
        s++;
276
        *s = '\n';
277
        s++;
278
        break;
279
    }
280
  }
474 mateuszvis 281
  *s = 0;
282
  output(buff);
354 mateuszvis 283
}
349 mateuszvis 284
 
285
 
506 mateuszvis 286
/* tries locating executable fname in path and fill res with result. returns 0 on success,
458 mateuszvis 287
 * -1 on failed match and -2 on failed match + "don't even try with other paths"
506 mateuszvis 288
 * extptr contains a ptr to the extension in fname (NULL if not found) */
289
static int lookup_cmd(char *res, const char *fname, const char *path, const char **extptr) {
290
  unsigned short lastbslash = 0;
458 mateuszvis 291
  unsigned short i, len;
292
  unsigned char explicitpath = 0;
293
 
506 mateuszvis 294
  /* does the original fname has an explicit path prefix or explicit ext? */
458 mateuszvis 295
  *extptr = NULL;
296
  for (i = 0; fname[i] != 0; i++) {
297
    switch (fname[i]) {
298
      case ':':
299
      case '\\':
300
        explicitpath = 1;
301
        *extptr = NULL; /* extension is the last dot AFTER all path delimiters */
302
        break;
303
      case '.':
304
        *extptr = fname + i + 1;
305
        break;
306
    }
307
  }
308
 
309
  /* normalize filename */
310
  if (file_truename(fname, res) != 0) return(-2);
311
 
312
  /* printf("truename: %s\r\n", res); */
313
 
314
  /* figure out where the command starts and if it has an explicit extension */
315
  for (len = 0; res[len] != 0; len++) {
316
    switch (res[len]) {
317
      case '?':   /* abort on any wildcard character */
318
      case '*':
319
        return(-2);
320
      case '\\':
321
        lastbslash = len;
322
        break;
323
    }
324
  }
325
 
326
  /* printf("lastbslash=%u\r\n", lastbslash); */
327
 
506 mateuszvis 328
  /* if no path prefix was found in fname (no colon or backslash) AND we have
329
   * a path arg, then assemble path+filename */
330
  if ((!explicitpath) && (path != NULL) && (path[0] != 0)) {
331
    i = strlen(path);
332
    if (path[i - 1] != '\\') i++; /* add a byte for inserting a bkslash after path */
333
    /* move the filename at the place where path will end */
458 mateuszvis 334
    memmove(res + i, res + lastbslash + 1, len - lastbslash);
506 mateuszvis 335
    /* copy path in front of the filename and make sure there is a bkslash sep */
336
    memmove(res, path, i);
337
    res[i - 1] = '\\';
458 mateuszvis 338
  }
339
 
340
  /* if no extension was initially provided, try matching COM, EXE, BAT */
341
  if (*extptr == NULL) {
342
    const char *ext[] = {".COM", ".EXE", ".BAT", NULL};
343
    len = strlen(res);
344
    for (i = 0; ext[i] != NULL; i++) {
345
      strcpy(res + len, ext[i]);
346
      /* printf("? '%s'\r\n", res); */
347
      *extptr = ext[i] + 1;
348
      if (file_getattr(res) >= 0) return(0);
349
    }
350
  } else { /* try finding it as-is */
351
    /* printf("? '%s'\r\n", res); */
352
    if (file_getattr(res) >= 0) return(0);
353
  }
354
 
355
  /* not found */
356
  if (explicitpath) return(-2); /* don't bother trying other paths, the caller had its own path preset anyway */
357
  return(-1);
358
}
359
 
360
 
517 mateuszvis 361
static void run_as_external(char *buff, const char *cmdline, unsigned short envseg, struct rmod_props far *rmod, struct redir_data *redir) {
472 mateuszvis 362
  char *cmdfile = buff + 512;
458 mateuszvis 363
  const char far *pathptr;
364
  int lookup;
365
  unsigned short i;
366
  const char *ext;
508 mateuszvis 367
  char *cmd = buff + 1024;
479 mateuszvis 368
  const char *cmdtail;
461 mateuszvis 369
  char far *rmod_execprog = MK_FP(rmod->rmodseg, RMOD_OFFSET_EXECPROG);
370
  char far *rmod_cmdtail = MK_FP(rmod->rmodseg, 0x81);
371
  _Packed struct {
372
    unsigned short envseg;
373
    unsigned long cmdtail;
374
    unsigned long fcb1;
375
    unsigned long fcb2;
376
  } far *ExecParam = MK_FP(rmod->rmodseg, RMOD_OFFSET_EXECPARAM);
364 mateuszvis 377
 
472 mateuszvis 378
  /* find cmd and cmdtail */
379
  i = 0;
380
  cmdtail = cmdline;
381
  while (*cmdtail == ' ') cmdtail++; /* skip any leading spaces */
382
  while ((*cmdtail != ' ') && (*cmdtail != '/') && (*cmdtail != '+') && (*cmdtail != 0)) {
383
    cmd[i++] = *cmdtail;
384
    cmdtail++;
385
  }
386
  cmd[i] = 0;
364 mateuszvis 387
 
458 mateuszvis 388
  /* is this a command in curdir? */
472 mateuszvis 389
  lookup = lookup_cmd(cmdfile, cmd, NULL, &ext);
458 mateuszvis 390
  if (lookup == 0) {
391
    /* printf("FOUND LOCAL EXEC FILE: '%s'\r\n", cmdfile); */
392
    goto RUNCMDFILE;
393
  } else if (lookup == -2) {
394
    /* puts("NOT FOUND"); */
395
    return;
396
  }
397
 
398
  /* try matching something in PATH */
399
  pathptr = env_lookup_val(envseg, "PATH");
400
  if (pathptr == NULL) return;
401
 
402
  /* try each path in %PATH% */
403
  for (;;) {
404
    for (i = 0;; i++) {
405
      buff[i] = *pathptr;
406
      if ((buff[i] == 0) || (buff[i] == ';')) break;
407
      pathptr++;
408
    }
409
    buff[i] = 0;
472 mateuszvis 410
    lookup = lookup_cmd(cmdfile, cmd, buff, &ext);
458 mateuszvis 411
    if (lookup == 0) break;
412
    if (lookup == -2) return;
413
    if (*pathptr == ';') {
414
      pathptr++;
415
    } else {
416
      return;
417
    }
418
  }
419
 
420
  RUNCMDFILE:
421
 
469 mateuszvis 422
  /* special handling of batch files */
423
  if ((ext != NULL) && (imatch(ext, "bat"))) {
424
    /* copy truename of the bat file to rmod buff */
425
    for (i = 0; cmdfile[i] != 0; i++) rmod->batfile[i] = cmdfile[i];
426
    rmod->batfile[i] = 0;
508 mateuszvis 427
 
428
    /* explode args of the bat file and store them in rmod buff */
429
    cmd_explode(buff, cmdline, NULL);
430
    _fmemcpy(rmod->batargv, buff, sizeof(rmod->batargv));
431
 
469 mateuszvis 432
    /* reset the 'next line to execute' counter */
433
    rmod->batnextline = 0;
474 mateuszvis 434
    /* remember the echo flag (in case bat file disables echo) */
435
    rmod->flags &= ~FLAG_ECHO_BEFORE_BAT;
475 mateuszvis 436
    if (rmod->flags & FLAG_ECHOFLAG) rmod->flags |= FLAG_ECHO_BEFORE_BAT;
469 mateuszvis 437
    return;
438
  }
439
 
517 mateuszvis 440
  /* copy full filename to execute, along with redirected files (if any) */
461 mateuszvis 441
  for (i = 0; cmdfile[i] != 0; i++) rmod_execprog[i] = cmdfile[i];
517 mateuszvis 442
  rmod_execprog[i++] = 0;
443
  if (redir->stdinfile) {
444
    unsigned short far *farptr = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDINFILE);
445
    unsigned short t;
446
    *farptr = i;
447
    for (t = 0;; t++) {
448
      rmod_execprog[i++] = redir->stdinfile[t];
449
      if (redir->stdinfile[t] == 0) break;
450
    }
451
  }
452
  if (redir->stdoutfile) {
453
    unsigned short far *farptr = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDOUTFILE);
454
    unsigned short t;
455
    *farptr = i;
456
    for (t = 0;; t++) {
457
      rmod_execprog[i++] = redir->stdoutfile[t];
458
      if (redir->stdoutfile[t] == 0) break;
459
    }
460
    /* openflag */
461
    farptr = MK_FP(rmod->rmodseg, RMOD_OFFSET_STDOUTAPP);
462
    *farptr = redir->stdout_openflag;
463
  }
461 mateuszvis 464
 
465
  /* copy cmdtail to rmod's PSP and compute its len */
466
  for (i = 0; cmdtail[i] != 0; i++) rmod_cmdtail[i] = cmdtail[i];
467
  rmod_cmdtail[i] = '\r';
468
  rmod_cmdtail[-1] = i;
469
 
470
  /* set up rmod to execute the command */
471
 
464 mateuszvis 472
  ExecParam->envseg = envseg;
461 mateuszvis 473
  ExecParam->cmdtail = (unsigned long)MK_FP(rmod->rmodseg, 0x80); /* farptr, must be in PSP format (lenbyte args \r) */
474
  ExecParam->fcb1 = 0; /* TODO farptr */
475
  ExecParam->fcb2 = 0; /* TODO farptr */
476
  exit(0); /* let rmod do the job now */
364 mateuszvis 477
}
478
 
479
 
367 mateuszvis 480
static void set_comspec_to_self(unsigned short envseg) {
481
  unsigned short *psp_envseg = (void *)(0x2c); /* pointer to my env segment field in the PSP */
482
  char far *myenv = MK_FP(*psp_envseg, 0);
483
  unsigned short varcount;
484
  char buff[256] = "COMSPEC=";
485
  char *buffptr = buff + 8;
486
  /* who am i? look into my own environment, at the end of it should be my EXEPATH string */
487
  while (*myenv != 0) {
488
    /* consume a NULL-terminated string */
489
    while (*myenv != 0) myenv++;
490
    /* move to next string */
491
    myenv++;
492
  }
493
  /* get next word, if 1 then EXEPATH follows */
494
  myenv++;
495
  varcount = *myenv;
496
  myenv++;
497
  varcount |= (*myenv << 8);
498
  myenv++;
499
  if (varcount != 1) return; /* NO EXEPATH FOUND */
500
  while (*myenv != 0) {
501
    *buffptr = *myenv;
502
    buffptr++;
503
    myenv++;
504
  }
505
  *buffptr = 0;
506
  /* printf("EXEPATH: '%s'\r\n", buff); */
507
  env_setvar(envseg, buff);
508
}
509
 
510
 
450 mateuszvis 511
/* wait for user input */
512
static void cmdline_getinput(unsigned short inpseg, unsigned short inpoff) {
513
  _asm {
514
    push ax
515
    push bx
516
    push cx
517
    push dx
518
    push ds
519
 
520
    /* is DOSKEY support present? (INT 2Fh, AX=4800h, returns non-zero in AL if present) */
521
    mov ax, 0x4800
522
    int 0x2f
523
    mov bl, al /* save doskey status in BL */
524
 
525
    /* set up buffered input to inpseg:inpoff */
526
    mov ax, inpseg
527
    push ax
528
    pop ds
529
    mov dx, inpoff
530
 
531
    /* execute either DOS input or DOSKEY */
532
    test bl, bl /* zf set if no DOSKEY present */
533
    jnz DOSKEY
534
 
535
    mov ah, 0x0a
536
    int 0x21
537
    jmp short DONE
538
 
539
    DOSKEY:
540
    mov ax, 0x4810
541
    int 0x2f
542
 
543
    DONE:
544
    /* terminate command with a CR/LF */
545
    mov ah, 0x02 /* display character in dl */
546
    mov dl, 0x0d
547
    int 0x21
548
    mov dl, 0x0a
549
    int 0x21
550
 
551
    pop ds
552
    pop dx
553
    pop cx
554
    pop bx
555
    pop ax
556
  }
557
}
558
 
559
 
479 mateuszvis 560
/* fetches a line from batch file and write it to buff (NULL-terminated),
561
 * increments rmod counter and returns 0 on success. */
484 mateuszvis 562
static int getbatcmd(char *buff, unsigned char buffmaxlen, struct rmod_props far *rmod) {
469 mateuszvis 563
  unsigned short i;
474 mateuszvis 564
  unsigned short batname_seg = FP_SEG(rmod->batfile);
565
  unsigned short batname_off = FP_OFF(rmod->batfile);
566
  unsigned short filepos_cx = rmod->batnextline >> 16;
567
  unsigned short filepos_dx = rmod->batnextline & 0xffff;
568
  unsigned char blen = 0;
505 mateuszvis 569
  unsigned short errv = 0;
474 mateuszvis 570
 
571
  /* open file, jump to offset filpos, and read data into buff.
572
   * result in blen (unchanged if EOF or failure). */
573
  _asm {
574
    push ax
575
    push bx
576
    push cx
577
    push dx
578
 
579
    /* open file (read-only) */
505 mateuszvis 580
    mov bx, 0xffff        /* preset BX to 0xffff to detect error conditions */
474 mateuszvis 581
    mov dx, batname_off
582
    mov ax, batname_seg
583
    push ds     /* save DS */
584
    mov ds, ax
585
    mov ax, 0x3d00
586
    int 0x21    /* handle in ax on success */
587
    pop ds      /* restore DS */
505 mateuszvis 588
    jc ERR
474 mateuszvis 589
    mov bx, ax  /* save handle to bx */
590
 
591
    /* jump to file offset CX:DX */
592
    mov ax, 0x4200
593
    mov cx, filepos_cx
594
    mov dx, filepos_dx
595
    int 0x21  /* CF clear on success, DX:AX set to cur pos */
505 mateuszvis 596
    jc ERR
474 mateuszvis 597
 
598
    /* read the line into buff */
599
    mov ah, 0x3f
484 mateuszvis 600
    xor ch, ch
601
    mov cl, buffmaxlen
474 mateuszvis 602
    mov dx, buff
603
    int 0x21 /* CF clear on success, AX=number of bytes read */
505 mateuszvis 604
    jc ERR
474 mateuszvis 605
    mov blen, al
505 mateuszvis 606
    jmp CLOSEANDQUIT
474 mateuszvis 607
 
505 mateuszvis 608
    ERR:
609
    mov errv, ax
610
 
474 mateuszvis 611
    CLOSEANDQUIT:
505 mateuszvis 612
    /* close file (if bx contains a handle) */
613
    cmp bx, 0xffff
614
    je DONE
474 mateuszvis 615
    mov ah, 0x3e
616
    int 0x21
617
 
618
    DONE:
619
    pop dx
620
    pop cx
621
    pop bx
622
    pop ax
469 mateuszvis 623
  }
470 mateuszvis 624
 
474 mateuszvis 625
  /* printf("blen=%u filepos_cx=%u filepos_dx=%u\r\n", blen, filepos_cx, filepos_dx); */
470 mateuszvis 626
 
505 mateuszvis 627
  if (errv != 0) outputnl(doserr(errv));
628
 
474 mateuszvis 629
  /* on EOF - abort processing the bat file */
630
  if (blen == 0) goto OOPS;
631
 
632
  /* find nearest \n to inc batch offset and replace \r by NULL terminator
633
   * I support all CR/LF, CR- and LF-terminated batch files */
634
  for (i = 0; i < blen; i++) {
635
    if ((buff[i] == '\r') || (buff[i] == '\n')) {
636
      if ((buff[i] == '\r') && ((i+1) < blen) && (buff[i+1] == '\n')) rmod->batnextline += 1;
637
      break;
638
    }
639
  }
640
  buff[i] = 0;
641
  rmod->batnextline += i + 1;
642
 
643
  return(0);
644
 
645
  OOPS:
646
  rmod->batfile[0] = 0;
647
  rmod->batnextline = 0;
648
  return(-1);
469 mateuszvis 649
}
650
 
651
 
507 mateuszvis 652
/* replaces %-variables in a BAT line with resolved values:
653
 * %PATH%       -> replaced by the contend of the PATH env variable
654
 * %UNDEFINED%  -> undefined variables are replaced by nothing ("")
655
 * %NOTCLOSED   -> NOTCLOSED
656
 * %1           -> first argument of the batch file (or nothing if no arg) */
657
static void batpercrepl(char *res, unsigned short ressz, const char *line, const struct rmod_props far *rmod, unsigned short envseg) {
658
  unsigned short lastperc = 0xffff;
659
  unsigned short reslen = 0;
660
 
661
  if (ressz == 0) return;
662
  ressz--; /* reserve one byte for the NULL terminator */
663
 
664
  for (; (reslen < ressz) && (*line != 0); line++) {
665
    /* if not a percent, I don't care */
666
    if (*line != '%') {
667
      res[reslen++] = *line;
668
      continue;
669
    }
670
 
671
    /* *** perc char handling *** */
672
 
673
    /* closing perc? */
674
    if (lastperc != 0xffff) {
675
      /* %% is '%' */
676
      if (lastperc == reslen) {
677
        res[reslen++] = '%';
678
      } else {   /* otherwise variable name */
679
        const char far *ptr;
680
        res[reslen] = 0;
681
        reslen = lastperc;
682
        ptr = env_lookup_val(envseg, res + reslen);
683
        if (ptr != NULL) {
684
          while ((*ptr != 0) && (reslen < ressz)) {
685
            res[reslen++] = *ptr;
686
            ptr++;
687
          }
688
        }
689
      }
690
      lastperc = 0xffff;
691
      continue;
692
    }
693
 
694
    /* digit? (bat arg) */
695
    if ((line[1] >= '0') && (line[1] <= '9')) {
508 mateuszvis 696
      unsigned short argid = line[1] - '0';
697
      unsigned short i;
698
      const char far *argv = rmod->batargv;
699
 
700
      /* locate the proper arg */
701
      for (i = 0; i != argid; i++) {
702
        /* if string is 0, then end of list reached */
703
        if (*argv == 0) break;
704
        /* jump to next arg */
705
        while (*argv != 0) argv++;
706
        argv++;
707
      }
708
 
709
      /* copy the arg to result */
710
      for (i = 0; (argv[i] != 0) && (reslen < ressz); i++) {
711
        res[reslen++] = argv[i];
712
      }
507 mateuszvis 713
      line++;  /* skip the digit */
714
      continue;
715
    }
716
 
717
    /* opening perc */
718
    lastperc = reslen;
719
 
720
  }
721
 
722
  res[reslen] = 0;
723
}
724
 
725
 
443 mateuszvis 726
int main(void) {
372 mateuszvis 727
  static struct config cfg;
728
  static unsigned short far *rmod_envseg;
729
  static unsigned short far *lastexitcode;
449 mateuszvis 730
  static struct rmod_props far *rmod;
500 mateuszvis 731
  static char cmdlinebuf[CMDLINE_MAXLEN + 2]; /* 1 extra byte for 0-terminator and another for memguard */
479 mateuszvis 732
  static char *cmdline;
517 mateuszvis 733
  static struct redir_data redirprops;
533 mateuszvis 734
  static enum cmd_result cmdres;
349 mateuszvis 735
 
479 mateuszvis 736
  rmod = rmod_find(BUFFER_len);
449 mateuszvis 737
  if (rmod == NULL) {
485 mateuszvis 738
    /* look at command line parameters (in case env size if set there) */
739
    parse_argv(&cfg);
479 mateuszvis 740
    rmod = rmod_install(cfg.envsiz, BUFFER, BUFFER_len);
449 mateuszvis 741
    if (rmod == NULL) {
369 mateuszvis 742
      outputnl("ERROR: rmod_install() failed");
349 mateuszvis 743
      return(1);
744
    }
475 mateuszvis 745
    /* copy flags to rmod's storage (and enable ECHO) */
746
    rmod->flags = cfg.flags | FLAG_ECHOFLAG;
465 mateuszvis 747
    /* printf("rmod installed at %Fp\r\n", rmod); */
349 mateuszvis 748
  } else {
465 mateuszvis 749
    /* printf("rmod found at %Fp\r\n", rmod); */
750
    /* if I was spawned by rmod and FLAG_EXEC_AND_QUIT is set, then I should
751
     * die asap, because the command has been executed already, so I no longer
752
     * have a purpose in life */
469 mateuszvis 753
    if (rmod->flags & FLAG_EXEC_AND_QUIT) sayonara(rmod);
349 mateuszvis 754
  }
755
 
490 mateuszvis 756
  /* install a few guardvals in memory to detect some cases of overflows */
500 mateuszvis 757
  memguard_set(cmdlinebuf);
490 mateuszvis 758
 
465 mateuszvis 759
  rmod_envseg = MK_FP(rmod->rmodseg, RMOD_OFFSET_ENVSEG);
760
  lastexitcode = MK_FP(rmod->rmodseg, RMOD_OFFSET_LEXITCODE);
350 mateuszvis 761
 
367 mateuszvis 762
  /* make COMPSEC point to myself */
763
  set_comspec_to_self(*rmod_envseg);
764
 
369 mateuszvis 765
/*  {
350 mateuszvis 766
    unsigned short envsiz;
767
    unsigned short far *sizptr = MK_FP(*rmod_envseg - 1, 3);
768
    envsiz = *sizptr;
769
    envsiz *= 16;
465 mateuszvis 770
    printf("rmod_inpbuff at %04X:%04X, env_seg at %04X:0000 (env_size = %u bytes)\r\n", rmod->rmodseg, RMOD_OFFSET_INPBUFF, *rmod_envseg, envsiz);
369 mateuszvis 771
  }*/
349 mateuszvis 772
 
494 mateuszvis 773
  /* on /P check for the presence of AUTOEXEC.BAT and execute it if found,
774
   * but skip this check if /D was also passed */
775
  if ((cfg.flags & (FLAG_PERMANENT | FLAG_SKIP_AUTOEXEC)) == FLAG_PERMANENT) {
483 mateuszvis 776
    if (file_getattr("AUTOEXEC.BAT") >= 0) cfg.execcmd = "AUTOEXEC.BAT";
777
  }
778
 
443 mateuszvis 779
  do {
480 mateuszvis 780
    /* terminate previous command with a CR/LF if ECHO ON (but not during BAT processing) */
483 mateuszvis 781
    if ((rmod->flags & FLAG_ECHOFLAG) && (rmod->batfile[0] == 0)) outputnl("");
474 mateuszvis 782
 
783
    SKIP_NEWLINE:
784
 
785
    /* cancel any redirections that may have been set up before */
786
    redir_revert();
787
 
490 mateuszvis 788
    /* memory check */
500 mateuszvis 789
    memguard_check(rmod->rmodseg, cmdlinebuf);
474 mateuszvis 790
 
500 mateuszvis 791
    /* preset cmdline to point at the dedicated buffer */
792
    cmdline = cmdlinebuf;
490 mateuszvis 793
 
437 mateuszvis 794
    /* (re)load translation strings if needed */
795
    nls_langreload(BUFFER, *rmod_envseg);
796
 
443 mateuszvis 797
    /* skip user input if I have a command to exec (/C or /K) */
798
    if (cfg.execcmd != NULL) {
799
      cmdline = cfg.execcmd;
800
      cfg.execcmd = NULL;
801
      goto EXEC_CMDLINE;
802
    }
803
 
469 mateuszvis 804
    /* if batch file is being executed -> fetch next line */
805
    if (rmod->batfile[0] != 0) {
507 mateuszvis 806
      if (getbatcmd(BUFFER, CMDLINE_MAXLEN, rmod) != 0) { /* end of batch */
474 mateuszvis 807
        /* restore echo flag as it was before running the bat file */
475 mateuszvis 808
        rmod->flags &= ~FLAG_ECHOFLAG;
809
        if (rmod->flags & FLAG_ECHO_BEFORE_BAT) rmod->flags |= FLAG_ECHOFLAG;
474 mateuszvis 810
        continue;
811
      }
507 mateuszvis 812
      /* %-decoding of variables (%PATH%, %1, %%...), result in cmdline */
813
      batpercrepl(cmdline, CMDLINE_MAXLEN, BUFFER, rmod, *rmod_envseg);
480 mateuszvis 814
      /* skip any leading spaces */
815
      while (*cmdline == ' ') cmdline++;
474 mateuszvis 816
      /* output prompt and command on screen if echo on and command is not
817
       * inhibiting it with the @ prefix */
479 mateuszvis 818
      if ((rmod->flags & FLAG_ECHOFLAG) && (cmdline[0] != '@')) {
474 mateuszvis 819
        build_and_display_prompt(BUFFER, *rmod_envseg);
479 mateuszvis 820
        outputnl(cmdline);
474 mateuszvis 821
      }
479 mateuszvis 822
      /* skip the @ prefix if present, it is no longer useful */
823
      if (cmdline[0] == '@') cmdline++;
469 mateuszvis 824
    } else {
474 mateuszvis 825
      /* interactive mode: display prompt (if echo enabled) and wait for user
826
       * command line */
475 mateuszvis 827
      if (rmod->flags & FLAG_ECHOFLAG) build_and_display_prompt(BUFFER, *rmod_envseg);
474 mateuszvis 828
      /* collect user input */
469 mateuszvis 829
      cmdline_getinput(FP_SEG(rmod->inputbuf), FP_OFF(rmod->inputbuf));
479 mateuszvis 830
      /* copy it to local cmdline */
831
      if (rmod->inputbuf[1] != 0) _fmemcpy(cmdline, rmod->inputbuf + 2, rmod->inputbuf[1]);
832
      cmdline[(unsigned)(rmod->inputbuf[1])] = 0; /* zero-terminate local buff (oriignal is '\r'-terminated) */
469 mateuszvis 833
    }
349 mateuszvis 834
 
405 mateuszvis 835
    /* if nothing entered, loop again (but without appending an extra CR/LF) */
479 mateuszvis 836
    if (cmdline[0] == 0) goto SKIP_NEWLINE;
349 mateuszvis 837
 
443 mateuszvis 838
    /* I jump here when I need to exec an initial command (/C or /K) */
839
    EXEC_CMDLINE:
840
 
364 mateuszvis 841
    /* move pointer forward to skip over any leading spaces */
842
    while (*cmdline == ' ') cmdline++;
349 mateuszvis 843
 
367 mateuszvis 844
    /* update rmod's ptr to COMPSPEC so it is always up to date */
465 mateuszvis 845
    rmod_updatecomspecptr(rmod->rmodseg, *rmod_envseg);
367 mateuszvis 846
 
402 mateuszvis 847
    /* handle redirections (if any) */
517 mateuszvis 848
    redir_parsecmd(&redirprops, cmdline);
402 mateuszvis 849
 
364 mateuszvis 850
    /* try matching (and executing) an internal command */
533 mateuszvis 851
    cmdres = cmd_process(rmod, *rmod_envseg, cmdline, BUFFER, sizeof(BUFFER), &redirprops);
852
    if ((cmdres == CMD_OK) || (cmdres == CMD_FAIL)) {
443 mateuszvis 853
      /* internal command executed */
854
      continue;
533 mateuszvis 855
    } else if (cmdres == CMD_CHANGED) { /* cmdline changed, needs to be reprocessed */
856
      goto EXEC_CMDLINE;
857
    } else if (cmdres == CMD_NOTFOUND) {
858
      /* this was not an internal command, try matching an external command */
859
      run_as_external(BUFFER, cmdline, *rmod_envseg, rmod, &redirprops);
860
      /* perhaps this is a newly launched BAT file */
861
      if ((rmod->batfile[0] != 0) && (rmod->batnextline == 0)) goto SKIP_NEWLINE;
862
      /* run_as_external() does not return on success, if I am still alive then
863
       * external command failed to execute */
864
      outputnl("Bad command or file name");
865
      continue;
353 mateuszvis 866
    }
352 mateuszvis 867
 
533 mateuszvis 868
    /* I should never ever land here */
869
    outputnl("INTERNAL ERR: INVALID CMDRES");
349 mateuszvis 870
 
449 mateuszvis 871
  } while ((rmod->flags & FLAG_EXEC_AND_QUIT) == 0);
349 mateuszvis 872
 
449 mateuszvis 873
  sayonara(rmod);
349 mateuszvis 874
  return(0);
875
}