Subversion Repositories SvarDOS

Rev

Rev 538 | Rev 548 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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