Subversion Repositories SvarDOS

Rev

Rev 517 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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