diff --git a/developer/debug/test/dos/README.run b/developer/debug/test/dos/README.run new file mode 100644 index 00000000000..71b5545292a --- /dev/null +++ b/developer/debug/test/dos/README.run @@ -0,0 +1,46 @@ +Run redirection regression +========================== + +run_redirection takes an explicit path to a standalone Run executable. +Build it through test-dos-common, or directly with the AROS target compiler. +Build Run.c in standalone form with -nostartfiles -static and an ADATE string. +Do not replace the installed/resident command for this test. + + run_redirection RAM:Run-fixed + +The probe creates a unique directory in RAM:, verifies a successful launch +and exact output for both > and >>, including a pre-existing PREFIX line. +It waits up to 250 ticks for each asynchronous Echo. On success it removes +its files and empty directory; after failure it retains them, without +reusing a possibly still-active background command's output pathname. + +The unmodified Run is expected to fail these output checks on the tested +RAM-handler. Comparing baseline/fixed executables by explicit path avoids +accidentally running a resident command instead of the patched binary. + +Fault injection (host only) +--------------------------- +From this directory: + + cc -std=c99 -Wall -Wextra -Werror -fsanitize=address,undefined \ + run_handle_host.c -o /tmp/run_handle_host + /tmp/run_handle_host + +This compiles the actual production run_handle.h with DOS boundary doubles. +It checks source seek failures and unrepresentable positions, unsupported +seeks, exclusive-to-shared retry, failed OpenFromLock cleanup, failed copy +seek cleanup, and interactive handles. It is not a native handler test or +allocation-failure test of the entire Run command. + +Compatibility limits +-------------------- +The duplication helper uses the existing LONG-based Seek API. Negative +positions other than -1/ERROR_ACTION_NOT_KNOWN are rejected rather than +silently reopening a seekable output at offset zero. Positions above +LONG_MAX are not supported by this path. Only interactive handles and +explicitly unsupported Seek operations are duplicated without a position. + +Exclusive output is changed to SHARED_LOCK only after DupLockFromFH reports +ERROR_OBJECT_IN_USE. That mode change is not rolled back if a later operation +fails. Concurrent append atomicity, other filesystems and allocation-failure +injection across the entire Shell launch are outside this regression. diff --git a/developer/debug/test/dos/mmakefile.src b/developer/debug/test/dos/mmakefile.src index 5976f655d70..3bbf907ceae 100644 --- a/developer/debug/test/dos/mmakefile.src +++ b/developer/debug/test/dos/mmakefile.src @@ -32,6 +32,7 @@ FILES := \ readitem \ readitemloop \ runcommand \ + run_redirection \ rwverify \ scantest \ scanvarstest \ @@ -54,8 +55,8 @@ EXEDIR := $(AROS_TESTS)/dos USER_CFLAGS += -DADATE="\"$(shell date '+%d.%m.%Y')\"" -#MM- test : test-dos test-dos-pure -#MM- test-quick : test-dos-quick test-dos-pure-quick +#MM- test : test-dos test-dos-pure test-dos-runcommandredir +#MM- test-quick : test-dos-quick test-dos-pure-quick test-dos-runcommandredir-quick #MM test-dos : includes linklibs diff --git a/developer/debug/test/dos/run_handle_host.c b/developer/debug/test/dos/run_handle_host.c new file mode 100644 index 00000000000..f169f90a68f --- /dev/null +++ b/developer/debug/test/dos/run_handle_host.c @@ -0,0 +1,84 @@ +/* Copyright (C) 2026, The AROS Development Team. All rights reserved. */ +/* Host-only fault injection around the actual production duplication helper. + cc -std=c99 -Wall -Wextra -Werror run_handle_host.c -o run_handle_host */ +#include +#include +#include +typedef intptr_t BPTR; +typedef int32_t LONG; +struct DosLibrary { int unused; }; +#define BNULL 0 +#define OFFSET_CURRENT 0 +#define OFFSET_BEGINNING -1 +#define CHANGE_FH 1 +#define SHARED_LOCK -2 +#define ERROR_INVALID_LOCK 211 +#define ERROR_OBJECT_IN_USE 202 +#define ERROR_ACTION_NOT_KNOWN 209 +#define ERROR_SEEK_ERROR 219 +static LONG error, position, seek_error; +static int interactive, exclusive, share_ok, open_ok, restore_ok; +static unsigned seeks, duplicates, shares, unlocks, closes; +static LONG get_error(struct DosLibrary *base) { (void)base;return error; } +static void set_error(LONG e,struct DosLibrary *base) { (void)base;error=e; } +static int is_interactive(BPTR f,struct DosLibrary *base) +{ (void)base;assert(f==1);return interactive; } +static LONG seek_file(BPTR f,LONG offset,LONG mode,struct DosLibrary *base) +{ + (void)base;++seeks; + if(f==1) { assert(offset==0 && mode==OFFSET_CURRENT);error=seek_error;return position; } + assert(f==3 && offset==position && mode==OFFSET_BEGINNING); + error=ERROR_SEEK_ERROR;return restore_ok?0:-1; +} +static BPTR duplicate(BPTR f,struct DosLibrary *base) +{ + (void)base;assert(f==1);++duplicates; + if(exclusive && !shares) { error=ERROR_OBJECT_IN_USE;return 0; } + return 2; +} +static int change_mode(LONG type,BPTR f,LONG mode,struct DosLibrary *base) +{ (void)base;assert(type==CHANGE_FH && f==1 && mode==SHARED_LOCK);++shares;error=223;return share_ok; } +static BPTR open_lock(BPTR l,struct DosLibrary *base) +{ (void)base;assert(l==2);error=103;return open_ok?3:0; } +static void unlock(BPTR l,struct DosLibrary *base) +{ (void)base;assert(l==2);++unlocks;error=0; } +static void close_file(BPTR f,struct DosLibrary *base) +{ (void)base;assert(f==3);++closes;error=0; } +#define IoErr() get_error(DOSBase) +#define SetIoErr(e) set_error((e),DOSBase) +#define IsInteractive(f) is_interactive((f),DOSBase) +#define Seek(f,p,m) seek_file((f),(p),(m),DOSBase) +#define DupLockFromFH(f) duplicate((f),DOSBase) +#define ChangeMode(t,f,m) change_mode((t),(f),(m),DOSBase) +#define OpenFromLock(l) open_lock((l),DOSBase) +#define UnLock(l) unlock((l),DOSBase) +#define Close(f) close_file((f),DOSBase) +#include "../../../../workbench/c/shellcommands/run_handle.h" +static void reset(void) +{ + error=seek_error=0;position=7;interactive=exclusive=0; + share_ok=open_ok=restore_ok=1; + seeks=duplicates=shares=unlocks=closes=0; +} +int main(void) +{ + reset();position=-1;seek_error=ERROR_SEEK_ERROR; + assert(DuplicateRunHandle(1,NULL)==0 && error==ERROR_SEEK_ERROR && !duplicates); + reset();position=INT32_MIN; + assert(DuplicateRunHandle(1,NULL)==0 && error==ERROR_SEEK_ERROR && !duplicates); + reset();position=-1;seek_error=ERROR_ACTION_NOT_KNOWN; + assert(DuplicateRunHandle(1,NULL)==3 && seeks==1); + reset();exclusive=1; + assert(DuplicateRunHandle(1,NULL)==3 && shares==1 && duplicates==2 && seeks==2); + reset();exclusive=1;share_ok=0; + assert(DuplicateRunHandle(1,NULL)==0 && error==223 && duplicates==1); + reset();open_ok=0; + assert(DuplicateRunHandle(1,NULL)==0 && error==103 && unlocks==1 && !closes); + reset();restore_ok=0; + assert(DuplicateRunHandle(1,NULL)==0 && error==ERROR_SEEK_ERROR && closes==1 && !unlocks); + reset();interactive=1; + assert(DuplicateRunHandle(1,NULL)==3 && !seeks); + reset();assert(DuplicateRunHandle(0,NULL)==0 && error==ERROR_INVALID_LOCK && !duplicates); + puts("RUN HANDLE PASS: seek failures, range rejection, nonseekable, sharing, ownership"); + return 0; +} diff --git a/developer/debug/test/dos/run_redirection.c b/developer/debug/test/dos/run_redirection.c new file mode 100644 index 00000000000..1348adac677 --- /dev/null +++ b/developer/debug/test/dos/run_redirection.c @@ -0,0 +1,85 @@ +/* Copyright (C) 2026, The AROS Development Team. All rights reserved. */ +/* Run an explicit standalone Run executable; never replace resident Run. */ +#include +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + struct Process *me = (struct Process *)FindTask(NULL); + char directory[120], path[2][160], command[500], data[128]; + const char *expected[2] = {"RUN_REDIRECT_OK\n", "PREFIX\nRUN_REDIRECT_OK\n"}; + BPTR lock, file; + unsigned attempt, round, ticks; + LONG result, count; + int all_ok = 1, matched; + + if (argc != 2 || strlen(argv[1]) > 240 || strpbrk(argv[1], "\"*\r\n")) + { + puts("Usage: run_redirection "); + return RETURN_FAIL; + } + /* CreateDir is the ownership boundary. Never truncate a pre-existing file. */ + for (attempt = 0; attempt < 100; ++attempt) + { + snprintf(directory, sizeof directory, "RAM:run-redirection-%lu-%u", + (unsigned long)me->pr_TaskNum, attempt); + lock = CreateDir((CONST_STRPTR)directory); + if (lock) { UnLock(lock); break; } + if (IoErr() != ERROR_OBJECT_EXISTS) return RETURN_FAIL; + } + if (attempt == 100) return RETURN_FAIL; + snprintf(path[0], sizeof path[0], "%s/overwrite", directory); + snprintf(path[1], sizeof path[1], "%s/append", directory); + + for (round = 0; round < 2; ++round) + { + matched = 0; + if (round) + { + file = Open((CONST_STRPTR)path[round], MODE_NEWFILE); + if (!file) { all_ok = 0; break; } + count = Write(file, "PREFIX\n", 7); + if (!Close(file) || count != 7) { all_ok = 0; break; } + } + snprintf(command, sizeof command, "\"%s\" %s%s Echo RUN_REDIRECT_OK", + argv[1], round ? ">>" : ">", path[round]); + result = SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE); + for (ticks = 0; result == RETURN_OK && ticks < 250; ++ticks) + { + file = Open((CONST_STRPTR)path[round], MODE_OLDFILE); + if (file) + { + count = Read(file, data, sizeof data - 1); + Close(file); + if (count >= 0) + { + data[count] = 0; + if ((size_t)count == strlen(expected[round]) && + !memcmp(data, expected[round], (size_t)count)) + { matched = 1; break; } + } + } + Delay(1); + } + printf("RUN %s %s: launch=%ld exact_output=%d\n", + round ? "APPEND" : "REDIRECT", matched ? "PASS" : "FAIL", + (long)result, matched); + if (!matched) all_ok = 0; + } + if (all_ok) + { + /* A background Echo may still be closing its output after the read. */ + for (round = 0; round < 2; ++round) + { + for (ticks = 0; ticks < 250 && !DeleteFile((CONST_STRPTR)path[round]); ++ticks) Delay(1); + if (ticks == 250) all_ok = 0; + } + if (all_ok && !DeleteFile((CONST_STRPTR)directory)) all_ok = 0; + } + if (!all_ok) printf("Test files retained: %s\n", directory); + puts(all_ok ? "RUN REDIRECTION PASS: launch status, exact bytes, cleanup" : "RUN REDIRECTION FAIL"); + return all_ok ? RETURN_OK : RETURN_FAIL; +} diff --git a/developer/debug/test/dos/runcommandredir/README b/developer/debug/test/dos/runcommandredir/README new file mode 100644 index 00000000000..363a748c590 --- /dev/null +++ b/developer/debug/test/dos/runcommandredir/README @@ -0,0 +1,38 @@ +Run child-command redirection regression +======================================= + +Build with test-dos-runcommandredir or test-dos-runcommandredir-quick. +Both are selected beneath the DOS component's normal and quick test groups. +Run runcommandredir beside runcommandchild, or pass the child's path as its +first argument. Child paths are quoted in every launch case. + +The parent creates an owned directory in RAM:. The child reads its Input(), +writes those exact bytes to Output(), and writes a separate completion file. +This checks that the child really runs, independently of SystemTagList's return +code. Before the fix, RunBack's repeated NIL form returns success without +executing the child; the test fails on the missing completion file. + +Coverage includes RunBack's exact NIL form, distinct outer and child input/output +files, case-insensitive Run with QUIET, a plain Run with child redirections, +quoted child paths, '+' continuation lines, failed outer input, ordinary +duplicate redirections, and subsequent shell usability. Successful runs remove +their temporary files; failed asynchronous launches retain evidence rather than +reuse their paths. + +Expected result: RUN COMMAND REDIR TEST: 0 failures. + +Quoted command regression +------------------------- +Run runquotedcommand beside runcommandchild. It copies the child into its own +RAM: directory under names containing spaces, stars and double quotes, then +checks the child's completion file and redirected output. Its argument and +redirection paths also contain spaces. Coverage includes QUIET, mixed case, +the COMMAND keyword (with and without '='), and outer Run redirections. +An additional check keeps commands entered after Run's '?' help prompt working. +The unchanged Run loses the child filename's quoting and fails the first case. +Expected result: RUN QUOTED TEST: 0 failures. + +For a focused external probe, runcommandredir still accepts a child's path +followed by PLAIN to exercise only the ordinary Run control. + +Copyright (C) 2026, The AROS Development Team. All rights reserved. diff --git a/developer/debug/test/dos/runcommandredir/mmakefile.src b/developer/debug/test/dos/runcommandredir/mmakefile.src new file mode 100644 index 00000000000..27c3cfbbd99 --- /dev/null +++ b/developer/debug/test/dos/runcommandredir/mmakefile.src @@ -0,0 +1,12 @@ +# Copyright (C) 2026, The AROS Development Team. All rights reserved. + +include $(SRCDIR)/config/aros.cfg +USER_LDFLAGS := -static + +#MM test-dos-runcommandredir : includes linklibs + +%build_progs mmake=test-dos-runcommandredir \ + files="runcommandredir runcommandchild runquotedcommand" \ + targetdir=$(AROS_TESTS)/dos/runcommandredir + +%common diff --git a/developer/debug/test/dos/runcommandredir/runcommandchild.c b/developer/debug/test/dos/runcommandredir/runcommandchild.c new file mode 100644 index 00000000000..51a9e713f5b --- /dev/null +++ b/developer/debug/test/dos/runcommandredir/runcommandchild.c @@ -0,0 +1,30 @@ +/* Copyright (C) 2026, The AROS Development Team. All rights reserved. */ +#include + +int main(int argc, char **argv) +{ + char data[64]; + BPTR result; + LONG count; + + if (argc != 2) + return RETURN_FAIL; + count = Read(Input(), data, sizeof data); + if (count < 0 || Write(Output(), data, count) != count) + return RETURN_FAIL; + result = Open((CONST_STRPTR)argv[1], MODE_NEWFILE); + if (!result) + return RETURN_FAIL; + if (!count) + { + data[0] = 'E'; data[1] = 'M'; data[2] = 'P'; + data[3] = 'T'; data[4] = 'Y'; data[5] = '\n'; + count = 6; + } + if (Write(result, data, count) != count) + { + Close(result); + return RETURN_FAIL; + } + return Close(result) ? RETURN_OK : RETURN_FAIL; +} diff --git a/developer/debug/test/dos/runcommandredir/runcommandredir.c b/developer/debug/test/dos/runcommandredir/runcommandredir.c new file mode 100644 index 00000000000..349eab545f5 --- /dev/null +++ b/developer/debug/test/dos/runcommandredir/runcommandredir.c @@ -0,0 +1,191 @@ +/* Copyright (C) 2026, The AROS Development Team. All rights reserved. */ +/* Exercise the shell and resident Run, with different outer/child streams. */ +#include +#include +#include +#include +#include +#include +#include + +static ULONG failures; + +static void check(BOOL okay, CONST_STRPTR label) +{ + if (!okay) + { + bug("RUN COMMAND REDIR FAIL: %s\n", label); + failures++; + } +} + +static BOOL writeFile(CONST_STRPTR path, CONST_STRPTR text) +{ + BPTR file = Open(path, MODE_NEWFILE); + LONG size = strlen(text), count; + BOOL closed; + if (!file) return FALSE; + count = Write(file, text, size); + closed = Close(file); + return count == size && closed; +} + +static BOOL matches(CONST_STRPTR path, CONST_STRPTR expected) +{ + char data[80]; + BPTR file = Open(path, MODE_OLDFILE); + LONG count; + if (!file) return FALSE; + count = Read(file, data, sizeof data); + Close(file); + return count == strlen(expected) && !memcmp(data, expected, count); +} + +static BOOL waitFor(CONST_STRPTR path, CONST_STRPTR expected) +{ + unsigned ticks; + for (ticks = 0; ticks < 100; ticks++) + { + if (matches(path, expected)) return TRUE; + Delay(1); + } + return FALSE; +} + +static BOOL absent(CONST_STRPTR path) +{ + BPTR lock = Lock(path, SHARED_LOCK); + if (!lock) return TRUE; + UnLock(lock); + return FALSE; +} + +int main(int argc, char **argv) +{ + struct Process *me = (struct Process *)FindTask(NULL); + CONST_STRPTR payload = argc > 1 ? argv[1] : "PROGDIR:runcommandchild"; + char directory[100], input[140], childInput[140]; + char outer[140], inner[140], result[140], command[900]; + BPTR lock; + unsigned attempt, mode; + BOOL complete = TRUE; + + if (strlen(payload) > 240 || strchr(payload, '"') || strchr(payload, '*') || + strchr(payload, '\n') || strchr(payload, '\r')) + return RETURN_FAIL; + for (attempt = 0; attempt < 100; attempt++) + { + snprintf(directory, sizeof directory, "RAM:run-command-%lu-%u", + (unsigned long)me->pr_TaskNum, attempt); + lock = CreateDir((CONST_STRPTR)directory); + if (lock) { UnLock(lock); break; } + if (IoErr() != ERROR_OBJECT_EXISTS) return RETURN_FAIL; + } + if (attempt == 100) return RETURN_FAIL; + snprintf(input, sizeof input, "%s/outer-input", directory); + snprintf(childInput, sizeof childInput, "%s/child-input", directory); + if (!writeFile((CONST_STRPTR)input, "OUTER\n") || + !writeFile((CONST_STRPTR)childInput, "INNER\n")) + return RETURN_FAIL; + + /* PLAIN is a diagnostic control for pre-existing Run behavior. */ + for (mode = argc > 2 && !strcmp(argv[2], "PLAIN") ? 3 : 0; mode < 4; mode++) + { + BPTR oldIn = Input(), oldOut = Output(); + LONG rc; + BOOL ran; + snprintf(outer, sizeof outer, "%s/outer-%u", directory, mode); + snprintf(inner, sizeof inner, "%s/child-%u", directory, mode); + snprintf(result, sizeof result, "%s/result-%u", directory, mode); + if (mode == 0) + snprintf(command, sizeof command, + "Run >NIL: NIL:\n", payload, result); + else if (mode == 1) + snprintf(command, sizeof command, + "Run >%s <%s \"%s\" %s <%s >%s\n", + outer, input, payload, result, childInput, inner); + else if (mode == 2) + snprintf(command, sizeof command, + "rUn QUIET >%s <%s \"%s\" %s <%s >%s\n", + outer, input, payload, result, childInput, inner); + else + snprintf(command, sizeof command, + "Run \"%s\" %s <%s >%s\n", payload, result, childInput, inner); + rc = SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE); + ran = waitFor((CONST_STRPTR)result, mode ? "INNER\n" : "EMPTY\n"); + bug("RUN COMMAND REDIR CASE %lu: rc=%ld child=%ld\n", + (unsigned long)mode, (long)rc, (long)ran); + check(rc == RETURN_OK, "Run launch status"); + check(ran, mode ? "child reads its own input" : "RunBack NIL form executes child"); + check(Input() == oldIn && Output() == oldOut, "caller streams remain installed"); + if (mode) + check(waitFor((CONST_STRPTR)inner, "INNER\n"), "child output reaches its own file"); + if (mode == 1 || mode == 2) + check(matches((CONST_STRPTR)outer, ""), "outer output does not receive child bytes"); + if (!ran) { complete = FALSE; break; } + /* The child may still be closing its redirected streams. */ + Delay(2); + check(DeleteFile((CONST_STRPTR)result), "remove child completion file"); + if (mode) check(DeleteFile((CONST_STRPTR)inner), "remove child output"); + if (mode == 1 || mode == 2) + check(DeleteFile((CONST_STRPTR)outer), "remove outer output"); + } + if (complete) + { + BPTR oldIn = Input(), oldOut = Output(); + + /* '+' continuation: every line runs once, in order, reading NIL:. */ + snprintf(result, sizeof result, "%s/continued-1", directory); + snprintf(inner, sizeof inner, "%s/continued-2", directory); + snprintf(outer, sizeof outer, "%s/continued-once", directory); + snprintf(command, sizeof command, + "Run >NIL: \"%s\" %s +\n\"%s\" %s +\nEcho >>%s ONCE\n", + payload, result, payload, inner, outer); + check(SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE) == RETURN_OK, + "continued Run launch status"); + check(waitFor((CONST_STRPTR)result, "EMPTY\n"), "first continued command reads NIL:"); + check(waitFor((CONST_STRPTR)inner, "EMPTY\n"), "second continued command runs"); + check(waitFor((CONST_STRPTR)outer, "ONCE\n"), "last continued command runs"); + Delay(50); + check(matches((CONST_STRPTR)outer, "ONCE\n"), "continued commands run once"); + check(DeleteFile((CONST_STRPTR)result), "remove first continued output"); + check(DeleteFile((CONST_STRPTR)inner), "remove second continued output"); + check(DeleteFile((CONST_STRPTR)outer), "remove last continued output"); + + snprintf(outer, sizeof outer, "%s/failed-outer", directory); + snprintf(inner, sizeof inner, "%s/should-not-exist", directory); + snprintf(result, sizeof result, "%s/should-not-run", directory); + snprintf(command, sizeof command, + "Run >%s <%s/missing \"%s\" %s <%s >%s\n", + outer, directory, payload, result, childInput, inner); + SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE); + Delay(10); + check(absent((CONST_STRPTR)result), "failed outer redirect does not launch child"); + check(absent((CONST_STRPTR)inner), "failed outer redirect does not open child target"); + check(Input() == oldIn && Output() == oldOut, "failure preserves caller streams"); + check(DeleteFile((CONST_STRPTR)outer), "remove failed outer output"); + + snprintf(command, sizeof command, "Echo BAD <%s <%s >%s\n", + input, childInput, inner); + SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE); + check(absent((CONST_STRPTR)inner), "ordinary duplicate input remains rejected"); + snprintf(command, sizeof command, "Echo BAD >%s >%s\n", outer, inner); + SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE); + check(matches((CONST_STRPTR)outer, "") && absent((CONST_STRPTR)inner), + "ordinary duplicate output remains rejected"); + check(DeleteFile((CONST_STRPTR)outer), "remove rejected command output"); + + snprintf(command, sizeof command, "Echo RESTORED >%s\n", result); + check(SystemTags((CONST_STRPTR)command, SYS_Asynch, FALSE, TAG_DONE) == RETURN_OK && + matches((CONST_STRPTR)result, "RESTORED\n"), + "shell remains usable after redirection errors"); + check(DeleteFile((CONST_STRPTR)result), "remove final probe output"); + check(DeleteFile((CONST_STRPTR)input), "remove outer input"); + check(DeleteFile((CONST_STRPTR)childInput), "remove child input"); + check(DeleteFile((CONST_STRPTR)directory), "remove test directory"); + } + else + bug("RUN COMMAND REDIR: evidence retained in %s\n", directory); + bug("RUN COMMAND REDIR TEST: %lu failures\n", (unsigned long)failures); + return failures ? RETURN_FAIL : RETURN_OK; +} diff --git a/developer/debug/test/dos/runcommandredir/runquotedcommand.c b/developer/debug/test/dos/runcommandredir/runquotedcommand.c new file mode 100644 index 00000000000..ac3534d5f90 --- /dev/null +++ b/developer/debug/test/dos/runcommandredir/runquotedcommand.c @@ -0,0 +1,165 @@ +/* Copyright (C) 2026, The AROS Development Team. All rights reserved. */ +/* Launch real children whose executable and argument names require quoting. */ +#include +#include +#include +#include +#include +#include +#include + +static BOOL copyFile(CONST_STRPTR from, CONST_STRPTR to) +{ + char data[512]; + BPTR in = Open(from, MODE_OLDFILE), out; + LONG n; + BOOL okay = TRUE; + if (!in) return FALSE; + out = Open(to, MODE_NEWFILE); + if (!out) { Close(in); return FALSE; } + while ((n = Read(in, data, sizeof data)) > 0) + if (Write(out, data, n) != n) { okay = FALSE; break; } + if (n < 0) okay = FALSE; + if (!Close(out)) okay = FALSE; + Close(in); + return okay; +} + +static BOOL matches(CONST_STRPTR path) +{ + char data[8]; + BPTR file = Open(path, MODE_OLDFILE); + LONG n; + if (!file) return FALSE; + n = Read(file, data, sizeof data); + Close(file); + return n == 6 && !memcmp(data, "INNER\n", 6); +} + +static BOOL waitFor(CONST_STRPTR path) +{ + unsigned ticks; + for (ticks = 0; ticks < 100; ticks++) + { + if (matches(path)) return TRUE; + Delay(1); + } + return FALSE; +} + +/* Quote one AmigaDOS token, retaining literal stars and double quotes. */ +static void quote(char *out, CONST_STRPTR in) +{ + *out++ = '"'; + while (*in) + { + if (*in == '*' || *in == '"') *out++ = '*'; + *out++ = *in++; + } + *out++ = '"'; + *out = 0; +} + +int main(void) +{ + static CONST_STRPTR prefixes[] = { + "Run", "rUn qUiEt", "Run COMMAND", "Run QUIET COMMAND=", + "Run COMMAND =", "Run >NIL: NIL: pr_TaskNum, attempt); + lock = CreateDir(directory); + if (lock) { UnLock(lock); break; } + if (IoErr() != ERROR_OBJECT_EXISTS) return RETURN_FAIL; + } + if (attempt == 100) return RETURN_FAIL; + snprintf(input, sizeof input, "%s/input file", directory); + file = Open(input, MODE_NEWFILE); + if (!file) return RETURN_FAIL; + if (Write(file, "INNER\n", 6) != 6) { Close(file); return RETURN_FAIL; } + if (!Close(file)) return RETURN_FAIL; + quote(qinput, input); + + for (name = 0; name < sizeof names / sizeof names[0]; name++) + { + snprintf(child, sizeof child, "%s/%s", directory, names[name]); + if (!copyFile("PROGDIR:runcommandchild", child)) return RETURN_FAIL; + quote(qchild, child); + for (mode = 0; mode < sizeof prefixes / sizeof prefixes[0]; mode++) + { + LONG rc; + BOOL ran, wrote; + snprintf(output, sizeof output, "%s/output %u-%u", directory, name, mode); + snprintf(result, sizeof result, "%s/result %u-%u", directory, name, mode); + quote(qoutput, output); + quote(qresult, result); + snprintf(command, sizeof command, "%s %s %s <%s >%s\n", + prefixes[mode], qchild, qresult, qinput, qoutput); + rc = SystemTagList(command, NULL); + ran = waitFor(result); + wrote = waitFor(output); + bug("RUN QUOTED CASE %u/%u: rc=%ld child=%ld output=%ld\n", + name, mode, rc, (LONG)ran, (LONG)wrote); + if (rc || !ran || !wrote) + { + failures++; + complete = FALSE; + break; + } + Delay(2); + if (!DeleteFile(result) || !DeleteFile(output)) failures++; + } + if (!complete) break; + if (!DeleteFile(child)) failures++; + } + if (complete) + { + char prompt[140], noise[140]; + BPTR in, out; + LONG rc; + BOOL ran; + + /* Keep Run's existing ReadArgs '?' prompt working. Its replacement + * command comes from Input(), not the original argument string. */ + snprintf(prompt, sizeof prompt, "%s/prompt", directory); + snprintf(noise, sizeof noise, "%s/help", directory); + snprintf(output, sizeof output, "%s/prompt output", directory); + snprintf(result, sizeof result, "%s/prompt result", directory); + quote(qoutput, output); + quote(qresult, result); + snprintf(command, sizeof command, "PROGDIR:runcommandchild %s <%s >%s\n", + qresult, qinput, qoutput); + file = Open(prompt, MODE_NEWFILE); + if (!file) return RETURN_FAIL; + if (Write(file, command, strlen(command)) != strlen(command)) + { Close(file); return RETURN_FAIL; } + if (!Close(file)) return RETURN_FAIL; + in = Open(prompt, MODE_OLDFILE); + out = Open(noise, MODE_NEWFILE); + if (!in || !out) return RETURN_FAIL; + rc = SystemTags("Run ?\n", SYS_Input, in, SYS_Output, out, TAG_DONE); + ran = waitFor(result) && waitFor(output); + bug("RUN QUOTED HELP: rc=%ld child=%ld\n", rc, (LONG)ran); + if (rc || !ran) failures++; + Delay(2); + Close(in); + Close(out); + if (!DeleteFile(prompt) || !DeleteFile(noise) || + !DeleteFile(result) || !DeleteFile(output)) failures++; + if (!DeleteFile(input) || !DeleteFile(directory)) failures++; + } + else + bug("RUN QUOTED: evidence retained in %s\n", directory); + bug("RUN QUOTED TEST: %u failures\n", failures); + return failures ? RETURN_FAIL : RETURN_OK; +} diff --git a/workbench/c/Shell/Shell.c b/workbench/c/Shell/Shell.c index e6a0968a167..672b54fe803 100644 --- a/workbench/c/Shell/Shell.c +++ b/workbench/c/Shell/Shell.c @@ -47,7 +47,7 @@ BOOL setInteractive(struct CommandLineInterface *cli, ShellState *ss) D(bug("Shell %ld: cli_StandardInput = %p\n", ss->cliNumber, cli->cli_StandardInput)); if (!cli->cli_Background && IS_SCRIPT) - cli->cli_Background = DOSTRUE; + cli->cli_Background = DOSTRUE; cli->cli_Interactive = (cli->cli_Background || IS_SCRIPT || IS_SYSTEM) ? DOSFALSE : DOSTRUE; D(bug("Shell %ld: cli_Interactive => %ld\n", ss->cliNumber, @@ -70,89 +70,89 @@ LONG interact(ShellState *ss) /* pre-allocate input buffer */ if ((error = bufferAppend("?", 1, &in, SysBase))) /* FIXME drop when readLine ok */ - return error; + return error; do { - if ((error = Redirection_init(ss)) == 0) - { - cliPrompt(ss); + if ((error = Redirection_init(ss)) == 0) + { + cliPrompt(ss); - bufferReset(&in); /* reuse allocated buffers */ - bufferReset(&out); + bufferReset(&in); /* reuse allocated buffers */ + bufferReset(&out); - D(bug("Shell %ld: Reading in a line of input...\n", + D(bug("Shell %ld: Reading in a line of input...\n", ss->cliNumber)); - error = readLine(ss, cli, &in, &moreLeft); - D(bug("Shell %ld: moreLeft=%d, error=%ld, Line is: " + error = readLine(ss, cli, &in, &moreLeft); + D(bug("Shell %ld: moreLeft=%d, error=%ld, Line is: " "%ld bytes (%s)\n", ss->cliNumber, moreLeft, error, in.len, in.buf)); - if (error == 0 && in.len > 0) - error = checkLine(ss, &in, &out, TRUE); + if (error == 0 && in.len > 0) + error = checkLine(ss, &in, &out, TRUE); /* The command may have modified cli_Background. * C:Execute does that. */ - setInteractive(cli, ss); - - /* As per AmigaMail Vol 2, "II-65: Writing a UserShell" */ - if (IS_SYSTEM && !IS_SCRIPT) - moreLeft = FALSE; - - if (!cli->cli_Interactive) - { - if (cli->cli_ReturnCode >= cli->cli_FailLevel) { - moreLeft = FALSE; - D(bug("Shell: cli_ReturnCode (%ld) >= cli->cli_FailLevel (%ld)\n", cli->cli_ReturnCode, cli->cli_FailLevel)); - } - - if (CheckSignal(SIGBREAKF_CTRL_D)) - { - PrintFault(ERROR_BREAK, "Shell"); - moreLeft = FALSE; - } - } - - Redirection_release(ss); - } - - if (moreLeft) - continue; - - popInterpreterState(ss); - - if (cli->cli_Interactive) - { - Printf("Process %ld ending\n", ss->cliNumber); - Flush(Output()); - break; - } - - if (IS_SCRIPT) { - D(bug("Shell %ld: Closing CLI input 0x%08lx\n", ss->cliNumber, + setInteractive(cli, ss); + + /* As per AmigaMail Vol 2, "II-65: Writing a UserShell" */ + if (IS_SYSTEM && !IS_SCRIPT) + moreLeft = FALSE; + + if (!cli->cli_Interactive) + { + if (cli->cli_ReturnCode >= cli->cli_FailLevel) { + moreLeft = FALSE; + D(bug("Shell: cli_ReturnCode (%ld) >= cli->cli_FailLevel (%ld)\n", cli->cli_ReturnCode, cli->cli_FailLevel)); + } + + if (CheckSignal(SIGBREAKF_CTRL_D)) + { + PrintFault(ERROR_BREAK, "Shell"); + moreLeft = FALSE; + } + } + + Redirection_release(ss); + } + + if (moreLeft) + continue; + + popInterpreterState(ss); + + if (cli->cli_Interactive) + { + Printf("Process %ld ending\n", ss->cliNumber); + Flush(Output()); + break; + } + + if (IS_SCRIPT) { + D(bug("Shell %ld: Closing CLI input 0x%08lx\n", ss->cliNumber, cli->cli_CurrentInput)); - Close(cli->cli_CurrentInput); + Close(cli->cli_CurrentInput); - /* Now that we've closed CurrentInput, we can delete - * the CommandFile. - */ - if (AROS_BSTR_strlen(cli->cli_CommandFile)) - { - DeleteFile(AROS_BSTR_ADDR(cli->cli_CommandFile)); - AROS_BSTR_setstrlen(cli->cli_CommandFile, 0); - } + /* Now that we've closed CurrentInput, we can delete + * the CommandFile. + */ + if (AROS_BSTR_strlen(cli->cli_CommandFile)) + { + DeleteFile(AROS_BSTR_ADDR(cli->cli_CommandFile)); + AROS_BSTR_setstrlen(cli->cli_CommandFile, 0); + } - cli->cli_CurrentInput = cli->cli_StandardInput; - cli->cli_Background = IsInteractive(cli->cli_CurrentInput) ? DOSFALSE : DOSTRUE; + cli->cli_CurrentInput = cli->cli_StandardInput; + cli->cli_Background = IsInteractive(cli->cli_CurrentInput) ? DOSFALSE : DOSTRUE; - setInteractive(cli, ss); - } + setInteractive(cli, ss); + } - /* As per AmigaMail Vol 2, "II-65: Writing a UserShell", - * if we were running a SYSTEM command, we're done now. - */ - moreLeft = cli->cli_Interactive; + /* As per AmigaMail Vol 2, "II-65: Writing a UserShell", + * if we were running a SYSTEM command, we're done now. + */ + moreLeft = cli->cli_Interactive; if (cli->cli_Interactive) { D(bug("Shell %ld: Flushing output 0x%lx, error 0x%lx\n", @@ -174,23 +174,27 @@ LONG checkLine(ShellState *ss, Buffer *in, Buffer *out, BOOL echo) { struct CommandLineInterface *cli = Cli(); BOOL haveCommand = FALSE; + BOOL convertFailed = FALSE; LONG result; result = convertLine(ss, in, out, &haveCommand); + if (result != 0) + convertFailed = TRUE; + if (result == 0) { D(bug("convertLine: haveCommand = %d, out->buf=%s\n", haveCommand, out->buf)); - /* Only a comment or dot command ? */ - if (haveCommand == FALSE) - goto exit; + /* Only a comment or dot command ? */ + if (haveCommand == FALSE) + goto exit; - if (echo) - cliEcho(ss, out->buf); + if (echo) + cliEcho(ss, out->buf); - /* OK, we've got a command. Let's execute it! */ - result = executeLine(ss, out->buf); + /* OK, we've got a command. Let's execute it! */ + result = executeLine(ss, out->buf); } /* If the command changed the cli's definition @@ -207,19 +211,27 @@ LONG checkLine(ShellState *ss, Buffer *in, Buffer *out, BOOL echo) { D(bug("convertLine: error = %ld faillevel=%ld\n", result, cli->cli_FailLevel)); - cli->cli_Result2 = result; + cli->cli_Result2 = result; + + /* + * executeLine() reports its own failures. Everything convertLine() + * rejects, above all a redirection whose file would not open, used to + * reach here and go no further than Result2, so the command simply did + * not run and said nothing about it. + */ + if (convertFailed) + PrintFault(result, NULL); } exit: - /* FIXME error handling is bullshit */ cliVarNum(ss, "RC", cli->cli_ReturnCode); cliVarNum(ss, "Result2", cli->cli_Result2); if (cli->cli_Interactive) { - Flush(ErrorOutput()); - Flush(Output()); + Flush(ErrorOutput()); + Flush(Output()); } return result; @@ -229,39 +241,49 @@ LONG checkLine(ShellState *ss, Buffer *in, Buffer *out, BOOL echo) * * Action: Free the resources held by a (loaded) command. * - * Input: ShellState *ss -- this state - * BPTR commandSeg -- segment of the program to unload - * BOOL homeDirChanged -- home changed flag + * Input: ShellState *ss -- this state + * BPTR commandSeg -- segment of the program to unload + * BOOL homeDirChanged -- home changed flag * * Output: -- */ static void unloadCommand(ShellState *ss, BPTR commandSeg, - BOOL homeDirChanged, BOOL residentCommand) + BOOL homeDirChanged, BOOL residentCommand) { struct CommandLineInterface *cli = Cli(); if (homeDirChanged) - UnLock(SetProgramDir(ss->oldHomeDir)); + UnLock(SetProgramDir(ss->oldHomeDir)); SetProgramName(""); if (!cli->cli_Module) - return; + return; if (residentCommand) { - struct Segment *residentSeg = (struct Segment *)BADDR(commandSeg); + struct Segment *residentSeg = (struct Segment *)BADDR(commandSeg); - Forbid(); + Forbid(); - /* Decrease usecount */ - if (residentSeg->seg_UC > 0) - residentSeg->seg_UC--; + /* Decrease usecount */ + if (residentSeg->seg_UC > 0) + residentSeg->seg_UC--; - Permit(); + Permit(); } else - UnLoadSeg(commandSeg); + { + /* + * Unload what cli_Module holds now, as the Kickstart CLI does, not the + * segment we loaded. Self-decrunching executables (PowerPacker, + * Imploder and similar stubs, common on old disks) unpack into new + * memory, free their own packed hunks and put the new SegList into + * cli_Module for the CLI to unload. Unloading the original segment + * again freed it twice and leaked the unpacked one. + */ + UnLoadSeg(cli->cli_Module); + } cli->cli_Module = BNULL; } @@ -271,15 +293,15 @@ static void unloadCommand(ShellState *ss, BPTR commandSeg, * Action: Load a command, searching the resident lists, paths and C: * * Input: ShellState *ss -- this state - * STRPTR commandName -- the command to load - * BOOL *homeDirChanged -- home changed result - * BPTR *scriptLock -- lock of script if one + * STRPTR commandName -- the command to load + * BOOL *homeDirChanged -- home changed result + * BPTR *scriptLock -- lock of script if one * * Output: BPTR -- segment of the loaded command or NULL if there was an * error */ static BPTR loadCommand(ShellState *ss, STRPTR commandName, BPTR *scriptLock, - BOOL *homeDirChanged, BOOL *residentCommand) + BOOL *homeDirChanged, BOOL *residentCommand) { struct CommandLineInterface *cli = Cli(); BPTR oldCurDir; @@ -293,32 +315,32 @@ static BPTR loadCommand(ShellState *ss, STRPTR commandName, BPTR *scriptLock, /* We check the resident lists only if we do not have an absolute path */ if (!absolutePath) { - Forbid(); - - /* Check regular list first... */ - residentSeg = FindSegment(commandName, NULL, FALSE); - - if (residentSeg == NULL) - { - /* ... then the system list */ - residentSeg = FindSegment(commandName, NULL, TRUE); - } - - if (residentSeg != NULL) - { - /* Can we use this command? */ - if (residentSeg->seg_UC == CMD_INTERNAL || residentSeg->seg_UC >= 0) - { - if (residentSeg->seg_UC >= 0) - residentSeg->seg_UC++; - - Permit(); - *residentCommand = TRUE; - return MKBADDR(residentSeg); - } - } - - Permit(); + Forbid(); + + /* Check regular list first... */ + residentSeg = FindSegment(commandName, NULL, FALSE); + + if (residentSeg == NULL) + { + /* ... then the system list */ + residentSeg = FindSegment(commandName, NULL, TRUE); + } + + if (residentSeg != NULL) + { + /* Can we use this command? */ + if (residentSeg->seg_UC == CMD_INTERNAL || residentSeg->seg_UC >= 0) + { + if (residentSeg->seg_UC >= 0) + residentSeg->seg_UC++; + + Permit(); + *residentCommand = TRUE; + return MKBADDR(residentSeg); + } + } + + Permit(); } oldCurDir = CurrentDir(BNULL); @@ -329,72 +351,72 @@ static BPTR loadCommand(ShellState *ss, STRPTR commandName, BPTR *scriptLock, if (!file) { - if - ( - absolutePath || /* If this was an absolute path, we don't check the paths set by - 'path' or the C: multiassign */ - err == ERROR_OBJECT_IN_USE /* The object might be exclusively locked */ - ) - return BNULL; - - /* Search the command in the path */ - for - ( - paths = (BPTR *)BADDR(cli->cli_CommandDir); - file == BNULL && paths != NULL; - paths = (BPTR *)BADDR(paths[0]) /* Go on with the next path */ - ) - { - CurrentDir(paths[1]); - file = Open(commandName, MODE_OLDFILE); - } - - /* The last resort -- the C: multiassign */ - if (!file) - { - commandName -= 2; - file = Open(commandName, MODE_OLDFILE); - } + if + ( + absolutePath || /* If this was an absolute path, we don't check the paths set by + 'path' or the C: multiassign */ + err == ERROR_OBJECT_IN_USE /* The object might be exclusively locked */ + ) + return BNULL; + + /* Search the command in the path */ + for + ( + paths = (BPTR *)BADDR(cli->cli_CommandDir); + file == BNULL && paths != NULL; + paths = (BPTR *)BADDR(paths[0]) /* Go on with the next path */ + ) + { + CurrentDir(paths[1]); + file = Open(commandName, MODE_OLDFILE); + } + + /* The last resort -- the C: multiassign */ + if (!file) + { + commandName -= 2; + file = Open(commandName, MODE_OLDFILE); + } } if (file) { - commandSeg = LoadSeg(commandName); - err = IoErr(); - - if (commandSeg) - { - BPTR lock = ParentOfFH(file); - - if (lock) - { - ss->oldHomeDir = SetProgramDir(lock); - *homeDirChanged = TRUE; /* TODO merge */ - } - } - /* Do not attempt to execute corrupted executables (BAD_HUNK) - * Do not swallow original error code */ - if (!commandSeg && err == ERROR_NOT_EXECUTABLE) { - struct FileInfoBlock *fib = AllocDosObject(DOS_FIB, NULL); - if (fib && ExamineFH(file, fib) && (fib->fib_Protection & FIBF_SCRIPT)) - { - commandSeg = LoadSeg("C:Execute"); - if (commandSeg) { - *scriptLock = Lock(commandName, SHARED_LOCK); - if (*scriptLock == BNULL) { - UnLoadSeg(commandSeg); - commandSeg = BNULL; - } - } - } - else - err = ERROR_FILE_NOT_OBJECT; - FreeDosObject(DOS_FIB, fib); - } - - Close(file); + commandSeg = LoadSeg(commandName); + err = IoErr(); + + if (commandSeg) + { + BPTR lock = ParentOfFH(file); + + if (lock) + { + ss->oldHomeDir = SetProgramDir(lock); + *homeDirChanged = TRUE; /* TODO merge */ + } + } + /* Do not attempt to execute corrupted executables (BAD_HUNK) + * Do not swallow original error code */ + if (!commandSeg && err == ERROR_NOT_EXECUTABLE) { + struct FileInfoBlock *fib = AllocDosObject(DOS_FIB, NULL); + if (fib && ExamineFH(file, fib) && (fib->fib_Protection & FIBF_SCRIPT)) + { + commandSeg = LoadSeg("C:Execute"); + if (commandSeg) { + *scriptLock = Lock(commandName, SHARED_LOCK); + if (*scriptLock == BNULL) { + UnLoadSeg(commandSeg); + commandSeg = BNULL; + } + } + } + else + err = ERROR_FILE_NOT_OBJECT; + FreeDosObject(DOS_FIB, fib); + } + + Close(file); } else - err = IoErr(); + err = IoErr(); CurrentDir(oldCurDir); SetIoErr(err); @@ -429,7 +451,7 @@ static LONG executeLine(ShellState *ss, STRPTR commandArgs) } module = loadCommand(ss, command, &scriptLock, - &homeDirChanged, &residentCommand); + &homeDirChanged, &residentCommand); /* Set command name even if we couldn't load the command to be able to report errors correctly */ @@ -437,90 +459,90 @@ static LONG executeLine(ShellState *ss, STRPTR commandArgs) if (module) { - struct Process *pr = (struct Process *) FindTask(NULL); - ULONG defaultStack = cli->cli_DefaultStack * CLI_DEFAULTSTACK_UNIT; - STRPTR oldtaskname = pr->pr_Task.tc_Node.ln_Name; - ULONG mem_before = 0; - ULONG sig_before = pr->pr_Task.tc_SigAlloc; - ULONG sig_after; - ULONG sigmask; - BYTE sigbit; - - BPTR seglist = residentCommand ? ((struct Segment *)BADDR(module))->seg_Seg : module; - - STRPTR dst = cmd, src; - LONG len = 0; - - if (scriptLock) - { - *dst++ = '"'; - if (NameFromLock(scriptLock, dst, FILE_MAX) == 0) { - error = IoErr(); /* bad FS handler ? */ - goto errexit; - } - while (*++dst != '\0'); - - *dst++ = '"'; - *dst++ = ' '; - UnLock(scriptLock); - len = dst - cmd; - } - - src = commandArgs; - for (; src && *src != '\0'; ++dst, ++src, ++len) - *dst = *src; - *dst = '\0'; - - D(bug("[Shell] command loaded: len=%ld, args=%s\n", len, cmd)); - SetIoErr(0); /* Clear error before we execute this command */ - SetSignal(0, SIGBREAKF_CTRL_C | SIGBREAKF_CTRL_D); - - cli->cli_Module = seglist; - pr->pr_Task.tc_Node.ln_Name = command; - - mem_before = FindVar("__debug_mem", LV_VAR) ? AvailMem(MEMF_ANY) : 0; - cli->cli_ReturnCode = RunCommand(seglist, defaultStack, cmd, len); - error = (cli->cli_ReturnCode == RETURN_OK) ? 0 : IoErr(); - - /* Update the state of the cli_Interactive field */ - setInteractive(cli, ss); - - /* - Check if running the command has changed signal bits of the Shell - process. If there is a difference the signals will be set or freed - to avoid that the Shell runs out of free signals. - */ - sig_after = pr->pr_Task.tc_SigAlloc; - if (sig_before != sig_after) - { - for (sigbit = 0; sigbit < 32; sigbit++) - { - sigmask = 1L << sigbit; - if ((sig_before & sigmask) && !(sig_after & sigmask)) - { - /* Command has deleted signal => set it */ - Printf("*** '%s' returned with freed signal 0x%lx\n", command, sigmask); - AllocSignal(sigbit); - } - else if (!(sig_before & sigmask) && (sig_after & sigmask)) - { - /* Command has set signal => free it */ - Printf("*** '%s' returned with unfreed signal 0x%lx\n", command, sigmask); - FreeSignal(sigbit); - } - } - } - - if (mem_before) - { - ULONG mem_after = AvailMem(MEMF_ANY); - Printf("Memory leak of %lu bytes\n", mem_before - mem_after); - } - - D(bug("[Shell] returned %ld (%ld): %s\n", cli->cli_ReturnCode, - error, command)); - pr->pr_Task.tc_Node.ln_Name = oldtaskname; - unloadCommand(ss, module, homeDirChanged, residentCommand); + struct Process *pr = (struct Process *) FindTask(NULL); + ULONG defaultStack = cli->cli_DefaultStack * CLI_DEFAULTSTACK_UNIT; + STRPTR oldtaskname = pr->pr_Task.tc_Node.ln_Name; + ULONG mem_before = 0; + ULONG sig_before = pr->pr_Task.tc_SigAlloc; + ULONG sig_after; + ULONG sigmask; + BYTE sigbit; + + BPTR seglist = residentCommand ? ((struct Segment *)BADDR(module))->seg_Seg : module; + + STRPTR dst = cmd, src; + LONG len = 0; + + if (scriptLock) + { + *dst++ = '"'; + if (NameFromLock(scriptLock, dst, FILE_MAX) == 0) { + error = IoErr(); /* bad FS handler ? */ + goto errexit; + } + while (*++dst != '\0'); + + *dst++ = '"'; + *dst++ = ' '; + UnLock(scriptLock); + len = dst - cmd; + } + + src = commandArgs; + for (; src && *src != '\0'; ++dst, ++src, ++len) + *dst = *src; + *dst = '\0'; + + D(bug("[Shell] command loaded: len=%ld, args=%s\n", len, cmd)); + SetIoErr(0); /* Clear error before we execute this command */ + SetSignal(0, SIGBREAKF_CTRL_C | SIGBREAKF_CTRL_D); + + cli->cli_Module = seglist; + pr->pr_Task.tc_Node.ln_Name = command; + + mem_before = FindVar("__debug_mem", LV_VAR) ? AvailMem(MEMF_ANY) : 0; + cli->cli_ReturnCode = RunCommand(seglist, defaultStack, cmd, len); + error = (cli->cli_ReturnCode == RETURN_OK) ? 0 : IoErr(); + + /* Update the state of the cli_Interactive field */ + setInteractive(cli, ss); + + /* + Check if running the command has changed signal bits of the Shell + process. If there is a difference the signals will be set or freed + to avoid that the Shell runs out of free signals. + */ + sig_after = pr->pr_Task.tc_SigAlloc; + if (sig_before != sig_after) + { + for (sigbit = 0; sigbit < 32; sigbit++) + { + sigmask = 1L << sigbit; + if ((sig_before & sigmask) && !(sig_after & sigmask)) + { + /* Command has deleted signal => set it */ + Printf("*** '%s' returned with freed signal 0x%lx\n", command, sigmask); + AllocSignal(sigbit); + } + else if (!(sig_before & sigmask) && (sig_after & sigmask)) + { + /* Command has set signal => free it */ + Printf("*** '%s' returned with unfreed signal 0x%lx\n", command, sigmask); + FreeSignal(sigbit); + } + } + } + + if (mem_before) + { + ULONG mem_after = AvailMem(MEMF_ANY); + Printf("Memory leak of %lu bytes\n", mem_before - mem_after); + } + + D(bug("[Shell] returned %ld (%ld): %s\n", cli->cli_ReturnCode, + error, command)); + pr->pr_Task.tc_Node.ln_Name = oldtaskname; + unloadCommand(ss, module, homeDirChanged, residentCommand); /* If command couldn't be started, explain why */ if (cli->cli_ReturnCode == -1) @@ -528,41 +550,41 @@ static LONG executeLine(ShellState *ss, STRPTR commandArgs) } else { - /* SFS returns ERROR_INVALID_COMPONENT_NAME if you try to open "" */ - error = IoErr(); - - if (error == ERROR_OBJECT_WRONG_TYPE || - error == ERROR_OBJECT_NOT_FOUND || - error == ERROR_INVALID_COMPONENT_NAME) - { - BPTR lock = Lock(command, SHARED_LOCK); - - if (lock) - { - struct FileInfoBlock *fib = AllocDosObject(DOS_FIB, NULL); - - if (fib) - { - if (Examine(lock, fib)) - { - if (fib->fib_DirEntryType > 0) - { - setPath(ss, lock); - lock = CurrentDir(lock); - } - else - SetIoErr(ERROR_OBJECT_WRONG_TYPE); - } - - FreeDosObject(DOS_FIB, fib); - } - - error = IoErr(); - - /* UnLock the old currentdir */ - UnLock(lock); - } - } + /* SFS returns ERROR_INVALID_COMPONENT_NAME if you try to open "" */ + error = IoErr(); + + if (error == ERROR_OBJECT_WRONG_TYPE || + error == ERROR_OBJECT_NOT_FOUND || + error == ERROR_INVALID_COMPONENT_NAME) + { + BPTR lock = Lock(command, SHARED_LOCK); + + if (lock) + { + struct FileInfoBlock *fib = AllocDosObject(DOS_FIB, NULL); + + if (fib) + { + if (Examine(lock, fib)) + { + if (fib->fib_DirEntryType > 0) + { + setPath(ss, lock); + lock = CurrentDir(lock); + } + else + SetIoErr(ERROR_OBJECT_WRONG_TYPE); + } + + FreeDosObject(DOS_FIB, fib); + } + + error = IoErr(); + + /* UnLock the old currentdir */ + UnLock(lock); + } + } PrintFault(error, command); } errexit: @@ -577,30 +599,30 @@ void setPath(ShellState *ss, BPTR lock) ULONG i = 0; if (lock) - dir = lock; + dir = lock; else - dir = CurrentDir(BNULL); + dir = CurrentDir(BNULL); do { i += 256; - buf = AllocVec(i, MEMF_ANY); + buf = AllocVec(i, MEMF_ANY); - if (buf == NULL) - break; + if (buf == NULL) + break; - if (NameFromLock(dir, buf, i)) - { - SetCurrentDirName(buf); - FreeVec(buf); - break; - } + if (NameFromLock(dir, buf, i)) + { + SetCurrentDirName(buf); + FreeVec(buf); + break; + } - FreeVec(buf); + FreeVec(buf); } while (IoErr() == ERROR_LINE_TOO_LONG); if (lock == BNULL) - CurrentDir(dir); + CurrentDir(dir); } #undef SysBase @@ -622,9 +644,9 @@ __startup AROS_CLI(ShellStart) D(bug("[Shell] executing\n")); ss = AllocMem(sizeof(ShellState), MEMF_CLEAR); if (!ss) { - SetIoErr(ERROR_NO_FREE_STORE); - CloseLibrary(DOSBase); - return RETURN_FAIL; + SetIoErr(ERROR_NO_FREE_STORE); + CloseLibrary(DOSBase); + return RETURN_FAIL; } ss->ss_DOSBase = DOSBase; diff --git a/workbench/c/Shell/Shell.h b/workbench/c/Shell/Shell.h index 60dde638e36..e99fd57aea7 100644 --- a/workbench/c/Shell/Shell.h +++ b/workbench/c/Shell/Shell.h @@ -7,7 +7,7 @@ #define SHELL_H 1 #include -#include /* for BPTR */ +#include /* for BPTR */ #include "buffer.h" @@ -30,7 +30,7 @@ struct SArg { - TEXT name[MAXARGLEN]; + TEXT name[MAXARGLEN + 1]; LONG namelen; LONG len; IPTR def; @@ -40,28 +40,28 @@ struct SArg typedef struct _ShellState { - BPTR newIn; - BPTR newOut; - BPTR oldIn; - BPTR oldOut; + BPTR newIn; + BPTR newOut; + BPTR oldIn; + BPTR oldOut; - TEXT command[FILE_MAX + 2]; /* command buffer */ + TEXT command[FILE_MAX + 2]; /* command buffer */ - BPTR oldHomeDir; /* shared lock on program file's directory */ + BPTR oldHomeDir; /* shared lock on program file's directory */ - LONG cliNumber; + LONG cliNumber; - LONG argcount; /* script args count */ - struct SArg args[MAXARGS]; /* args definitions */ - IPTR arg[MAXARGS]; /* args values */ - struct RDArgs *arg_rd; /* Current RDArgs return state */ + LONG argcount; /* script args count */ + struct SArg args[MAXARGS]; /* args definitions */ + IPTR arg[MAXARGS]; /* args values */ + struct RDArgs *arg_rd; /* Current RDArgs return state */ - TEXT bra, ket, dollar, dot; + TEXT bra, ket, dollar, dot; TEXT mchar0, pchar0; struct _ShellState *stack; - ULONG flags; /* DOS/CliInit*() flags cache */ + ULONG flags; /* DOS/CliInit*() flags cache */ APTR ss_DOSBase; APTR ss_SysBase; @@ -76,10 +76,10 @@ typedef struct _ShellState * redirections, incorporating embedded commands, taking care of * variable references and aliases. * - * Input: ShellState *ss -- this state - * Buffer *in -- input string - * Buffer *out -- output command string - * BOOL *haveCommand -- true if line have command + * Input: ShellState *ss -- this state + * Buffer *in -- input string + * Buffer *out -- output command string + * BOOL *haveCommand -- true if line have command * * Output: LONG -- error code or 0 if everything went OK */ @@ -107,10 +107,10 @@ LONG readLine(ShellState *ss, struct CommandLineInterface *cli, Buffer *out, BOO * * Action: Parse a command line and do consistency checks * - * Input: ShellState *ss -- this state - * Buffer *in -- the input buffer - * Buffer *out -- the result will be stored here - * BOOL echo -- true if command echoed + * Input: ShellState *ss -- this state + * Buffer *in -- the input buffer + * Buffer *out -- the result will be stored here + * BOOL echo -- true if command echoed * * Output: LONG -- DOS error code */ @@ -121,7 +121,7 @@ LONG checkLine(ShellState *ss, Buffer *in, Buffer *out, BOOL echo); * Action: Deallocate file resources used for redirecion and reinstall * standard input and output streams. * - * Input: ShellState *ss -- this state + * Input: ShellState *ss -- this state * * Output: -- */ @@ -132,7 +132,7 @@ void releaseFiles(ShellState *ss); * Action: Execute a commandfile and then perform standard shell user * interaction. * - * Input: ShellState *is -- this state + * Input: ShellState *is -- this state * * Output: LONG -- error code */ @@ -143,7 +143,7 @@ LONG interact(ShellState *ss); * * Action: Release resources allocated in the state * - * Input: ShellState *ss -- this state + * Input: ShellState *ss -- this state * * Output: -- */ @@ -153,7 +153,7 @@ void Redirection_release(ShellState *ss); * * Action: Initialize a state structure * - * Input: ShellState *ss -- this state + * Input: ShellState *ss -- this state * * Output: LONG -- DOS error code */ @@ -176,7 +176,7 @@ void setPath(ShellState *ss, BPTR lock); * * Action: Print the prompt to indicate that user input is viable. * - * Input: ShellState *ss -- this state + * Input: ShellState *ss -- this state * * Output: -- */ diff --git a/workbench/c/Shell/buffer.c b/workbench/c/Shell/buffer.c index d1b2c544a94..e00952e196e 100644 --- a/workbench/c/Shell/buffer.c +++ b/workbench/c/Shell/buffer.c @@ -18,23 +18,23 @@ static BOOL bufferExpand(Buffer *out, LONG size, APTR SysBase) if (newLength > out->mem) { - ULONG newSize = BUF_SIZE; - STRPTR tmp; + ULONG newSize = BUF_SIZE; + STRPTR tmp; - while (newSize < newLength) - newSize += BUF_SIZE; + while (newSize < newLength) + newSize += BUF_SIZE; - if ((tmp = AllocMem(newSize + 1, MEMF_ANY)) == NULL) - return FALSE; + if ((tmp = AllocMem(newSize + 1, MEMF_ANY)) == NULL) + return FALSE; - if (out->len > 0) - CopyMem(out->buf, tmp, out->len); + if (out->len > 0) + CopyMem(out->buf, tmp, out->len); - if (out->mem > 0) - FreeMem(out->buf, out->mem); + if (out->mem > 0) + FreeMem(out->buf, out->mem + 1); - out->buf = tmp; - out->mem = newSize; + out->buf = tmp; + out->mem = newSize; } return TRUE; } @@ -79,7 +79,7 @@ LONG bufferCopy(Buffer *in, Buffer *out, ULONG size, APTR SysBase) void bufferFree(Buffer *b, APTR SysBase) { if (b->mem <= 0) - return; + return; FreeMem(b->buf, b->mem + 1); @@ -104,8 +104,8 @@ LONG bufferReadItem(STRPTR buf, ULONG size, Buffer *in, APTR DOSBase) */ if (in->cur == in->len - 1) { - D(bug("[bufferReadItem] Getting last character\n")); - in->cur++; + D(bug("[bufferReadItem] Getting last character\n")); + in->cur++; } return ret; @@ -114,7 +114,7 @@ LONG bufferReadItem(STRPTR buf, ULONG size, Buffer *in, APTR DOSBase) void bufferReset(Buffer *b) { if (b->mem > 0) - b->buf[0] = '\0'; + b->buf[0] = '\0'; b->len = 0; b->cur = 0; diff --git a/workbench/c/Shell/cliEcho.c b/workbench/c/Shell/cliEcho.c index ca78ee94f6d..0a8ad57845a 100644 --- a/workbench/c/Shell/cliEcho.c +++ b/workbench/c/Shell/cliEcho.c @@ -15,23 +15,23 @@ void cliEcho(ShellState *ss, CONST_STRPTR args) that begins with "on" in order to trigger commands echoing on, it doesn't really have to be set to just "on". */ if ((lv = FindVar("echo", LV_VAR)) == NULL) - return; + return; switch (lv->lv_Value[0]) { case 'o': case 'O': - switch (lv->lv_Value[1]) - { - case 'n': - case 'N': - break; - default: - return; - } - break; + switch (lv->lv_Value[1]) + { + case 'n': + case 'N': + break; + default: + return; + } + break; default: - return; + return; } /* Ok, commands echoing is on. */ @@ -45,8 +45,8 @@ void cliEcho(ShellState *ss, CONST_STRPTR args) if (args) { - FPutC(echoOut, ' '); - FPuts(echoOut, args); + FPutC(echoOut, ' '); + FPuts(echoOut, args); } FPutC(echoOut, '\n'); diff --git a/workbench/c/Shell/cliLen.c b/workbench/c/Shell/cliLen.c index 298d385f84d..8be01450d2d 100644 --- a/workbench/c/Shell/cliLen.c +++ b/workbench/c/Shell/cliLen.c @@ -10,7 +10,7 @@ LONG cliLen(CONST_STRPTR s) LONG i; for (i = 0; *s != '\0'; ++i) - ++s; + ++s; return i; } diff --git a/workbench/c/Shell/cliNan.c b/workbench/c/Shell/cliNan.c index e437606c2d6..ab0043c425a 100644 --- a/workbench/c/Shell/cliNan.c +++ b/workbench/c/Shell/cliNan.c @@ -1,15 +1,21 @@ /* - Copyright (C) 1995-2010, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ #include "Shell.h" BOOL cliNan(CONST_STRPTR s) { + if (*s == '+' || *s == '-') + { + ++s; + if (*s == '\0') + return TRUE; + } + for (; *s != '\0'; ++s) - if (*s < '0' || *s > '9') - return TRUE; + if (*s < '0' || *s > '9') + return TRUE; return FALSE; } diff --git a/workbench/c/Shell/cliPrompt.c b/workbench/c/Shell/cliPrompt.c index c8cb8c29199..649d641a623 100644 --- a/workbench/c/Shell/cliPrompt.c +++ b/workbench/c/Shell/cliPrompt.c @@ -18,34 +18,34 @@ void cliPrompt(ShellState *ss) ULONG i; if (cli->cli_Background) - return; + return; for (i = 0; i < length; i++) { - if (AROS_BSTR_getchar(prompt, i) == '%') - { - if (++i == length) - break; - - switch (AROS_BSTR_getchar(prompt, i)) - { - case 'N': case 'n': - Printf("%ld", ss->cliNumber); - break; - case 'R': case 'r': - Printf("%ld", cli->cli_ReturnCode); - break; - case 'S': case 's': - FPuts(output, AROS_BSTR_ADDR(cli->cli_SetName)); - break; - default: - FPutC(output, '%'); - FPutC(output, AROS_BSTR_getchar(prompt, i)); - break; - } - } - else - FPutC(output, AROS_BSTR_getchar(prompt, i)); + if (AROS_BSTR_getchar(prompt, i) == '%') + { + if (++i == length) + break; + + switch (AROS_BSTR_getchar(prompt, i)) + { + case 'N': case 'n': + Printf("%ld", ss->cliNumber); + break; + case 'R': case 'r': + Printf("%ld", cli->cli_ReturnCode); + break; + case 'S': case 's': + FPuts(output, AROS_BSTR_ADDR(cli->cli_SetName)); + break; + default: + FPutC(output, '%'); + FPutC(output, AROS_BSTR_getchar(prompt, i)); + break; + } + } + else + FPutC(output, AROS_BSTR_getchar(prompt, i)); } Flush(output); diff --git a/workbench/c/Shell/cliVarNum.c b/workbench/c/Shell/cliVarNum.c index c766379656d..ba70e12c90d 100644 --- a/workbench/c/Shell/cliVarNum.c +++ b/workbench/c/Shell/cliVarNum.c @@ -13,18 +13,18 @@ LONG l2a(LONG x, STRPTR buf) /* long to ascii */ TEXT tmp[32]; do { - tmp[i] = '0' + (a % 10); - ++len; + tmp[i] = '0' + (a % 10); + ++len; } while (i-- && (a /= 10)); if (x < 0) { - tmp[i--] = '-'; - ++len; + tmp[i--] = '-'; + ++len; } for (j = 0; j < len; ++j) - buf[j] = tmp[++i]; + buf[j] = tmp[++i]; buf[j] = '\0'; return len; diff --git a/workbench/c/Shell/convertArg.c b/workbench/c/Shell/convertArg.c index c4c72de9d8f..ba0ade85181 100644 --- a/workbench/c/Shell/convertArg.c +++ b/workbench/c/Shell/convertArg.c @@ -25,7 +25,7 @@ LONG convertArg(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) } if (!*quoted && *p == '<' && *q == '>') /* Run <>NIL: ... */ - return convertRedir(ss, in, out); + return bufferCopy(in, out, 1, SysBase); /* Defer I/O to the redirection pass. */ for (; *q != ss->ket && *q != ss->dollar && *q != '\0'; ++q) { @@ -35,7 +35,7 @@ LONG convertArg(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) case '"': case ' ': if (*p == '<') /* input redirection */ - return convertRedir(ss, in, out); + return bufferCopy(in, out, 1, SysBase); bufferAppend(s, q - s, out, SysBase); return 0; diff --git a/workbench/c/Shell/convertBackTicks.c b/workbench/c/Shell/convertBackTicks.c index f10b5268475..9d496fe6b94 100644 --- a/workbench/c/Shell/convertBackTicks.c +++ b/workbench/c/Shell/convertBackTicks.c @@ -26,37 +26,40 @@ LONG convertBackTicks(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) { Buffer embedIn = {0}, embedOut = {0}; /* TODO pre-alloc */ LONG c = 0, error = 0, n = in->len, p = 0; - TEXT buf[512] = SHELL_EMBED; + TEXT buf[512]; + TEXT tempName[sizeof(SHELL_EMBED) + 11] = SHELL_EMBED; + BOOL tempCreated = FALSE; ShellState ess = {0}; ess.ss_DOSBase = DOSBase; ess.ss_SysBase = SysBase; + ess.cliNumber = ss->cliNumber; for (++in->cur; in->cur < n; p = c) { - c = in->buf[in->cur]; - - if (p == '*') - { - c = 0; - bufferCopy(in, &embedIn, 1, SysBase); - } - else if (c == '`') - break; - else - bufferCopy(in, &embedIn, 1, SysBase); + c = in->buf[in->cur]; + + if (p == '*') + { + c = 0; + bufferCopy(in, &embedIn, 1, SysBase); + } + else if (c == '`') + break; + else + bufferCopy(in, &embedIn, 1, SysBase); } if (c != '`') { - bufferCopy(&embedIn, out, embedIn.len, SysBase); - goto freebufs; + bufferCopy(&embedIn, out, embedIn.len, SysBase); + goto freebufs; } ++in->cur; /* last backtick */ if (embedIn.len <= 0) /* `` empty command, no output */ - goto freebufs; + goto freebufs; initDefaultInterpreterState(&ess); @@ -69,17 +72,18 @@ LONG convertBackTicks(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) * but this seems to be rather much work for little gain. */ if ((error = Redirection_init(&ess))) - goto cleanup; + goto cleanup; /* Construct temporary output filename */ - l2a(ss->cliNumber, buf + sizeof(SHELL_EMBED) - 1); + l2a(ss->cliNumber, tempName + sizeof(SHELL_EMBED) - 1); - if (!(ess.newOut = Open(buf, MODE_NEWFILE))) + if (!(ess.newOut = Open(tempName, MODE_NEWFILE))) { - error = IoErr(); - goto cleanup; + error = IoErr(); + goto cleanup; } + tempCreated = TRUE; ess.oldOut = SelectOutput(ess.newOut); /* Embedded command isn't echo'ed, but its result will be integrated @@ -87,33 +91,37 @@ LONG convertBackTicks(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) D(bug("[Shell] embedded command: %s\n", embedIn.buf)); if ((error = checkLine(&ess, &embedIn, &embedOut, FALSE)) == 0) { - LONG i, len = -1, size; + LONG i, len = -1, size; - /* copy result to output */ - if ((size = Seek(ess.newOut, 0, OFFSET_BEGINNING)) >= 0) - { - while ((len = Read(ess.newOut, buf, 512)) > 0) - { - for (i = 0; i < len - 1; ++i) /* replace all \n but last */ - if (buf[i] == '\n') - buf[i] = ' '; + /* copy result to output */ + if ((size = Seek(ess.newOut, 0, OFFSET_BEGINNING)) >= 0) + { + while ((len = Read(ess.newOut, buf, 512)) > 0) + { + for (i = 0; i < len - 1; ++i) /* replace all \n but last */ + if (buf[i] == '\n') + buf[i] = ' '; - size -= len; + size -= len; - if (size <= 0 && buf[i] == '\n') - --len; + if (size <= 0 && buf[i] == '\n') + --len; - bufferAppend(buf, len, out, SysBase); - } - } + bufferAppend(buf, len, out, SysBase); + } + } - if (len == -1) - error = IoErr(); + if (len == -1) + error = IoErr(); } cleanup: Redirection_release(&ess); - /* TODO: delete generated file */ + if (tempCreated) + DeleteFile(tempName); + while (ess.stack) + popInterpreterState(&ess); + popInterpreterState(&ess); freebufs: bufferFree(&embedIn, SysBase); bufferFree(&embedOut, SysBase); diff --git a/workbench/c/Shell/convertLine.c b/workbench/c/Shell/convertLine.c index 6d03b4248ea..64655d85d59 100644 --- a/workbench/c/Shell/convertLine.c +++ b/workbench/c/Shell/convertLine.c @@ -54,10 +54,12 @@ static LONG convertLoop(LONG (*convertItem)(ShellState *, Buffer *, Buffer *, BO return 0; } -static LONG convertLoopRedir(ShellState *ss, Buffer *in, Buffer *out) +static LONG convertLoopRedir(ShellState *ss, Buffer *in, Buffer *out, + BOOL runCommand) { LONG c, p = 0, error, n = in->len; BOOL quoted = FALSE; + BOOL quietSwitch = FALSE; bufferReset(out); @@ -66,6 +68,25 @@ static LONG convertLoopRedir(ShellState *ss, Buffer *in, Buffer *out) DB2(bug("[convertLoopRedir] cur %u (%c)\n", in->cur, in->buf[in->cur])); c = in->buf[in->cur]; + /* Run's leading redirections apply to Run itself. From the child + * command onward, retain the text for the background CLI to parse. + * QUIET is Run's optional switch, not the child command's name. */ + if (runCommand && !quoted && c != ' ' && c != '\t' && + c != '\r' && c != '\n' && c != '<' && c != '>') + { + if (!quietSwitch && n - in->cur >= 5 && + strncasecmp(in->buf + in->cur, "QUIET", 5) == 0 && + (n - in->cur == 5 || + strchr(" \t\r\n", in->buf[in->cur + 5]) != NULL)) + { + bufferCopy(in, out, 5, SysBase); + quietSwitch = TRUE; + c = 0; + continue; + } + return bufferCopy(in, out, n - in->cur, SysBase); + } + if (p == '*') { c = 0; @@ -209,7 +230,8 @@ static LONG readCommand(ShellState *ss, Buffer *in, Buffer *out) file. The first item of the command line is the command to be executed. This may be an alias, that is there is a Local LV_ALIAS variable that should be substituted for the command text. Aliasing only applies to - commands and not to options, for instance. Variables (set by SetEnv or Set) + commands and not to options, for instance. Run retains redirections after + its child command for the background CLI. Variables (set by SetEnv or Set) may be referenced by prepending a '$' to the variable name. */ LONG convertLine(ShellState *ss, Buffer *in, Buffer *out, BOOL *haveCommand) { @@ -275,7 +297,8 @@ LONG convertLine(ShellState *ss, Buffer *in, Buffer *out, BOOL *haveCommand) /* PASS 5: redirections */ D(bug("[convertLine] Pass 5: cur %d len %d (%s)\n", in->cur, in->len, in->buf)); - error = convertLoopRedir(ss, in, out); + error = convertLoopRedir(ss, in, out, + strcasecmp(FilePart(ss->command + 2), "Run") == 0); if (error) { D(bug("[convertLine] Pass 5: Error %lu parsing redirect\n", error)); diff --git a/workbench/c/Shell/convertLineDot.c b/workbench/c/Shell/convertLineDot.c index aa8055cc55c..3d6375c6926 100644 --- a/workbench/c/Shell/convertLineDot.c +++ b/workbench/c/Shell/convertLineDot.c @@ -16,16 +16,19 @@ static LONG getArgumentIdx(ShellState *ss, STRPTR name, LONG len) struct SArg *a; LONG i; + if (len > MAXARGLEN) + return -1; + for (i = 0; i < ss->argcount; ++i) { - a = ss->args + i; + a = ss->args + i; - if (strncmp(a->name, name, len) == 0) - return i; + if (a->namelen == len && strncmp(a->name, name, len) == 0) + return i; } if (ss->argcount >= MAXARGS) - return -1; + return -1; ss->argcount++; a = ss->args + i; @@ -47,34 +50,37 @@ static LONG dotDef(ShellState *ss, STRPTR szz, Buffer *in, LONG len) if ((result = bufferReadItem(buf, sizeof(buf), in, DOSBase)) == ITEM_UNQUOTED) { - len = in->cur - i; - - i = getArgumentIdx(ss, buf, len); - if (i < 0) - return ERROR_TOO_MANY_ARGS; - - a = ss->args + i; - i = ++in->cur; - - switch (bufferReadItem(buf, sizeof(buf), in, DOSBase)) - { - case ITEM_QUOTED: - case ITEM_UNQUOTED: - break; - default: - return ERROR_REQUIRED_ARG_MISSING; - } - - len = in->cur - i; - - if (a->def) - FreeMem((APTR) a->def, a->deflen + 1); - - a->def = (IPTR) AllocMem(len + 1, MEMF_LOCAL); - CopyMem(buf, (APTR) a->def, len); - ((STRPTR) a->def)[len] = '\0'; - a->deflen = len; - return 0; + len = in->cur - i; + + if (len > MAXARGLEN) + return ERROR_LINE_TOO_LONG; + + i = getArgumentIdx(ss, buf, len); + if (i < 0) + return ERROR_TOO_MANY_ARGS; + + a = ss->args + i; + i = ++in->cur; + + switch (bufferReadItem(buf, sizeof(buf), in, DOSBase)) + { + case ITEM_QUOTED: + case ITEM_UNQUOTED: + break; + default: + return ERROR_REQUIRED_ARG_MISSING; + } + + len = in->cur - i; + + if (a->def) + FreeMem((APTR) a->def, a->deflen + 1); + + a->def = (IPTR) AllocMem(len + 1, MEMF_LOCAL); + CopyMem(buf, (APTR) a->def, len); + ((STRPTR) a->def)[len] = '\0'; + a->deflen = len; + return 0; } return ERROR_REQUIRED_ARG_MISSING; @@ -89,14 +95,14 @@ static LONG dotKey(ShellState *ss, STRPTR s, Buffer *in) /* modify the template to read numbers as strings! */ for (i = 0, j = 0; s[j] != '\0' && s[j] != '\n' && i < sizeof(t); ++j) { - if (s[j] == '/' && s[j + 1] == 'N') - ++j; - else - t[i++] = s[j]; + if (s[j] == '/' && s[j + 1] == 'N') + ++j; + else + t[i++] = s[j]; } if (i >= sizeof(t)) - return ERROR_LINE_TOO_LONG; + return ERROR_LINE_TOO_LONG; t[i] = '\0'; @@ -112,51 +118,57 @@ static LONG dotKey(ShellState *ss, STRPTR s, Buffer *in) for (i = 0; i < MAXARGS; ++i) { - STRPTR arg; - - for (len = 0; *s != '/' && *s != ',' && *s != '\n' && *s != '\0'; ++s) - ++len; - - j = getArgumentIdx(ss, s - len, len); - arg = (STRPTR) ss->arg[j]; - a = ss->args + j; - - while (*s == '/') - { - switch (*++s) - { - case 'a': case 'A': a->type |= REQUIRED; break; - case 'f': case 'F': a->type |= REST; break; - case 'k': case 'K': a->type |= KEYWORD; break; - case 'm': case 'M': a->type |= MULTIPLE; break; - case 'n': case 'N': a->type |= NUMERIC; break; - case 's': case 'S': a->type |= SWITCH; break; - case 't': case 'T': a->type |= TOGGLE; break; - default: - return ERROR_BAD_TEMPLATE; - } - ++s; - } - - if (arg && !(a->type & (SWITCH | TOGGLE))) - a->len = cliLen(arg); - - if (arg && a->type & NUMERIC) /* verify numbers' validity */ - { - if (a->type & MULTIPLE) - { - STRPTR *m = (STRPTR *) arg; - - while (*m) - if (cliNan(*m++)) - return ERROR_BAD_NUMBER; - } - else if (cliNan(arg)) - return ERROR_BAD_NUMBER; - } - - if (*s++ != ',') - break; + STRPTR arg; + + for (len = 0; *s != '/' && *s != ',' && *s != '\n' && *s != '\0'; ++s) + ++len; + + if (len > MAXARGLEN) + return ERROR_LINE_TOO_LONG; + + j = getArgumentIdx(ss, s - len, len); + if (j < 0) + return ERROR_TOO_MANY_ARGS; + + arg = (STRPTR) ss->arg[j]; + a = ss->args + j; + + while (*s == '/') + { + switch (*++s) + { + case 'a': case 'A': a->type |= REQUIRED; break; + case 'f': case 'F': a->type |= REST; break; + case 'k': case 'K': a->type |= KEYWORD; break; + case 'm': case 'M': a->type |= MULTIPLE; break; + case 'n': case 'N': a->type |= NUMERIC; break; + case 's': case 'S': a->type |= SWITCH; break; + case 't': case 'T': a->type |= TOGGLE; break; + default: + return ERROR_BAD_TEMPLATE; + } + ++s; + } + + if (arg && !(a->type & (SWITCH | TOGGLE))) + a->len = cliLen(arg); + + if (arg && a->type & NUMERIC) /* verify numbers' validity */ + { + if (a->type & MULTIPLE) + { + STRPTR *m = (STRPTR *) arg; + + while (*m) + if (cliNan(*m++)) + return ERROR_BAD_NUMBER; + } + else if (cliNan(arg)) + return ERROR_BAD_NUMBER; + } + + if (*s++ != ',') + break; } in->cur = in->len; @@ -170,134 +182,141 @@ LONG convertLineDot(ShellState *ss, Buffer *in) #if 0 /* version using libc */ if (*++s == ' ') /* dot comment */ - res = s; + res = s; else if (strncasecmp(s, "bra ", 4) == 0) { - res = &ss->bra; - s += 4; + res = &ss->bra; + s += 4; } else if (strncasecmp(s, "ket ", 4) == 0) { - res = &ss->ket; - s += 4; + res = &ss->ket; + s += 4; } else if (strncasecmp(s, "key ", 4) == 0) - return dotKey(ss, s + 4, in); + return dotKey(ss, s + 4, in); else if (strncasecmp(s, "k ", 2) == 0) - return dotKey(ss, s + 2, in); + return dotKey(ss, s + 2, in); else if (strncasecmp(s, "def ", 4) == 0) - return dotDef(ss, s + 4, in, 5); + return dotDef(ss, s + 4, in, 5); else if (strncasecmp(s, "default ", 8) == 0) - return dotDef(ss, s + 4, in, 9); + return dotDef(ss, s + 4, in, 9); else if (strncasecmp(s, "dol ", 4) == 0) { - res = &ss->dollar; - s += 4; + res = &ss->dollar; + s += 4; } else if (strncasecmp(s, "dollar ", 7) == 0) { - res = &ss->dollar; - s += 7; + res = &ss->dollar; + s += 7; } else if (strncasecmp(s, "dot ", 4) == 0) { - res = &ss->dot; - s += 4; + res = &ss->dot; + s += 4; } else if (strncasecmp(s, "popis", 5) == 0) { - popInterpreterState(ss); - res = s; + popInterpreterState(ss); + res = s; } else if (strncasecmp(s, "pushis", 6) == 0) { - pushInterpreterState(ss); - res = s; + pushInterpreterState(ss); + res = s; } #else /* this ugly version is 424 bytes smaller on x64 */ if (*++s == ' ') /* dot comment */ - res = s; + res = s; else if (*s == 'b' || *s == 'B') /* .bra */ { - if (*++s == 'r' || *s == 'R') - if (*++s == 'a' || *s == 'A') - if (*++s == ' ') - res = &ss->bra; + if (*++s == 'r' || *s == 'R') + if (*++s == 'a' || *s == 'A') + if (*++s == ' ') + res = &ss->bra; } else if (*s == 'k' || *s == 'K') { - if (*++s == ' ') /* .k */ - return dotKey(ss, ++s, in); - - if (*s == 'e' || *s == 'E') - { - if (*++s == 'y' || *s == 'Y') /* .key */ - { - if (*++s == ' ') - return dotKey(ss, ++s, in); - } - else if (*s == 't' || *s == 'T') /* .ket */ - if (*++s == ' ') - res = &ss->ket; - } + if (*++s == ' ') /* .k */ + return dotKey(ss, ++s, in); + + if (*s == 'e' || *s == 'E') + { + if (*++s == 'y' || *s == 'Y') /* .key */ + { + if (*++s == ' ') + return dotKey(ss, ++s, in); + } + else if (*s == 't' || *s == 'T') /* .ket */ + if (*++s == ' ') + res = &ss->ket; + } } else if (*s == 'd' || *s == 'D') { - if (*++s == 'e' || *s == 'E') - { - if (*++s == 'f' || *s == 'F') - { - if (*++s == ' ') /* .def */ - return dotDef(ss, ++s, in, 5); - - if (*s == 'a' || *s == 'A') - if (*++s == 'u' || *s == 'U') - if (*++s == 'l' || *s == 'L') - if (*++s == 't' || *s == 'T') - if (*++s == ' ') /* .default */ - return dotDef(ss, ++s, in, 9); - } - } - else if (*s == 'o' || *s == 'O') - { - if (*++s == 'l' || *s == 'L') - { - if (*++s == ' ') /* .dol */ - res = &ss->dollar; - else if (*s == 'l' || *s == 'L') - if (*++s == 'a' || *s == 'A') - if (*++s == 'r' || *s == 'R') - if (*++s == ' ') /* .dollar */ - res = &ss->dollar; - } - else if (*s == 't' || *s == 'T') - if (*++s == ' ') /* .dot */ - res = &ss->dot; - } + if (*++s == 'e' || *s == 'E') + { + if (*++s == 'f' || *s == 'F') + { + if (*++s == ' ') /* .def */ + return dotDef(ss, ++s, in, 5); + + if (*s == 'a' || *s == 'A') + if (*++s == 'u' || *s == 'U') + if (*++s == 'l' || *s == 'L') + if (*++s == 't' || *s == 'T') + if (*++s == ' ') /* .default */ + return dotDef(ss, ++s, in, 9); + } + } + else if (*s == 'o' || *s == 'O') + { + if (*++s == 'l' || *s == 'L') + { + if (*++s == ' ') /* .dol */ + res = &ss->dollar; + else if (*s == 'l' || *s == 'L') + if (*++s == 'a' || *s == 'A') + if (*++s == 'r' || *s == 'R') + if (*++s == ' ') /* .dollar */ + res = &ss->dollar; + } + else if (*s == 't' || *s == 'T') + if (*++s == ' ') /* .dot */ + res = &ss->dot; + } } - else if (*s == 'p') + else if (*s == 'p' || *s == 'P') { - if (*++s == 'o' && s[1] == 'p') /* .popis */ - { - popInterpreterState(ss); - res = s; - } - else if (*s == 'u' && s[1] == 's' && s[2] == 'h') /* .pushis */ - { - pushInterpreterState(ss); - res = s; - } + if ((*++s == 'o' || *s == 'O') && + (s[1] == 'p' || s[1] == 'P') && + (s[2] == 'i' || s[2] == 'I') && + (s[3] == 's' || s[3] == 'S')) /* .popis */ + { + popInterpreterState(ss); + res = s; + } + else if ((*s == 'u' || *s == 'U') && + (s[1] == 's' || s[1] == 'S') && + (s[2] == 'h' || s[2] == 'H') && + (s[3] == 'i' || s[3] == 'I') && + (s[4] == 's' || s[4] == 'S')) /* .pushis */ + { + pushInterpreterState(ss); + res = s; + } } #endif if (res) { - if (*s == '\0') - return ERROR_REQUIRED_ARG_MISSING; + if (*s == '\0') + return ERROR_REQUIRED_ARG_MISSING; - *res = s[1]; /* FIXME skip spaces */ - in->cur = in->len; - return 0; + *res = s[1]; /* FIXME skip spaces */ + in->cur = in->len; + return 0; } return ERROR_ACTION_NOT_KNOWN; diff --git a/workbench/c/Shell/convertRedir.c b/workbench/c/Shell/convertRedir.c index 5f0d15d843f..a902814e8c0 100644 --- a/workbench/c/Shell/convertRedir.c +++ b/workbench/c/Shell/convertRedir.c @@ -17,25 +17,25 @@ LONG convertRedir(ShellState *ss, Buffer *in, Buffer *out) if (*s == '<') { - if (ss->newIn) /* multiple < not allowed */ - return ERROR_TOO_MANY_LEVELS; + if (ss->newIn) /* multiple < not allowed */ + return ERROR_TOO_MANY_LEVELS; - newIn = TRUE; /* new input */ - ++s; + newIn = TRUE; /* new input */ + ++s; } if (*s == '>') { - if (ss->newOut) /* multiple > or >> not allowed */ - return ERROR_TOO_MANY_LEVELS; + if (ss->newOut) /* multiple > or >> not allowed */ + return ERROR_TOO_MANY_LEVELS; - if (*++s == '>') - { - append = TRUE; - ++s; - } + if (*++s == '>') + { + append = TRUE; + ++s; + } - newOut = TRUE; /* new output */ + newOut = TRUE; /* new output */ } in->cur = s - in->buf; @@ -44,30 +44,30 @@ LONG convertRedir(ShellState *ss, Buffer *in, Buffer *out) { case ITEM_QUOTED: case ITEM_UNQUOTED: - break; + break; default: - return ERROR_LINE_TOO_LONG; + return ERROR_LINE_TOO_LONG; } if (newIn) { - if (!(ss->newIn = Open(file, MODE_OLDFILE))) - return IoErr(); + if (!(ss->newIn = Open(file, MODE_OLDFILE))) + return IoErr(); - ss->oldIn = SelectInput(ss->newIn); + ss->oldIn = SelectInput(ss->newIn); } if (newOut) { - LONG mode = append ? MODE_READWRITE : MODE_NEWFILE; + LONG mode = append ? MODE_READWRITE : MODE_NEWFILE; - if (!(ss->newOut = Open(file, mode))) - return IoErr(); + if (!(ss->newOut = Open(file, mode))) + return IoErr(); - if (append && Seek(ss->newOut, 0, OFFSET_END) == -1) - return IoErr(); + if (append && Seek(ss->newOut, 0, OFFSET_END) == -1) + return IoErr(); - ss->oldOut = SelectOutput(ss->newOut); + ss->oldOut = SelectOutput(ss->newOut); } return 0; diff --git a/workbench/c/Shell/convertVar.c b/workbench/c/Shell/convertVar.c index 0bb30119a0e..525927b6fc7 100644 --- a/workbench/c/Shell/convertVar.c +++ b/workbench/c/Shell/convertVar.c @@ -24,26 +24,26 @@ LONG convertVar(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) APTR orig_WindowPtr; if (bra) - ++s; + ++s; for (i = 0; i < 256; ++i) { - if (bra) + if (bra) { - if (*s == '\0' || *s == '}') - break; + if (*s == '\0' || *s == '}') + break; } else { if (!isalnum(*s)) - break; - } + break; + } - varName[i] = *s++; + varName[i] = *s++; } if (i >= 256) /* FIXME setup a VAR_MAX constant */ - return ERROR_LINE_TOO_LONG; + return ERROR_LINE_TOO_LONG; varName[i] = '\0'; @@ -66,13 +66,13 @@ LONG convertVar(ShellState *ss, Buffer *in, Buffer *out, BOOL *quoted) if ((bra != 1) && (i > 0) && ((len = GetVar(varName, varValue, 256, LV_VAR)) != -1)) { - D(bug("[Shell] found var: %s = %s\n", varName, varValue)); - bufferAppend(varValue, len, out, SysBase); + D(bug("[Shell] found var: %s = %s\n", varName, varValue)); + bufferAppend(varValue, len, out, SysBase); } else { - D(bug("[Shell] var not found: %s\n", varName)); - bufferAppend(p, ++i + bra, out, SysBase); + D(bug("[Shell] var not found: %s\n", varName)); + bufferAppend(p, ++i + bra, out, SysBase); } /* Restore original pr_WindowPtr */ diff --git a/workbench/c/Shell/interpreter.c b/workbench/c/Shell/interpreter.c index 5dfc5fd9b41..afc7f78ab0b 100644 --- a/workbench/c/Shell/interpreter.c +++ b/workbench/c/Shell/interpreter.c @@ -3,6 +3,7 @@ $Id$ */ +#include #include #include "Shell.h" @@ -19,18 +20,20 @@ void initDefaultInterpreterState(ShellState *ss) for (i = 0; i < MAXARGS; ++i) { - struct SArg *a = ss->args + i; + struct SArg *a = ss->args + i; - a->namelen = 0; - a->name[0] = '\0'; - a->len = 0; - a->def = 0; - a->deflen = 0; - a->type = NORMAL; + a->namelen = 0; + a->name[0] = '\0'; + a->len = 0; + a->def = 0; + a->deflen = 0; + a->type = NORMAL; - ss->arg[i] = 0; + ss->arg[i] = 0; } + ss->arg_rd = NULL; + ss->bra = '<'; ss->ket = '>'; ss->dollar = '$'; @@ -45,10 +48,10 @@ LONG pushInterpreterState(ShellState *ss) if (tmp_ss) { - *tmp_ss = *ss; - initDefaultInterpreterState(ss); - ss->stack = tmp_ss; - return 0; + *tmp_ss = *ss; + initDefaultInterpreterState(ss); + ss->stack = tmp_ss; + return 0; } return ERROR_NO_FREE_STORE; @@ -62,17 +65,20 @@ void popInterpreterState(ShellState *ss) for (i = 0; i < ss->argcount; ++i) { - a = ss->args + i; + a = ss->args + i; - if (a->def) - FreeMem((APTR) a->def, a->deflen + 1); + if (a->def) + FreeMem((APTR) a->def, a->deflen + 1); } + if (ss->arg_rd) + FreeDosObject(DOS_RDARGS, ss->arg_rd); + if (tmp_ss) { - *ss = *tmp_ss; - FreeMem(tmp_ss, sizeof(*ss)); + *ss = *tmp_ss; + FreeMem(tmp_ss, sizeof(*ss)); } else - initDefaultInterpreterState(ss); + initDefaultInterpreterState(ss); } diff --git a/workbench/c/Shell/readLine.c b/workbench/c/Shell/readLine.c index e116ce47c1a..dfe3d18a649 100644 --- a/workbench/c/Shell/readLine.c +++ b/workbench/c/Shell/readLine.c @@ -1,5 +1,5 @@ /* - Copyright (C) 1995-2011, The AROS Development Team. All rights reserved. + Copyright (C) 1995-2020, The AROS Development Team. All rights reserved. $Id$ */ @@ -17,16 +17,22 @@ static BOOL checkPipe(STRPTR pchar, STRPTR mchar, STRPTR in, LONG inlen) { LONG c, n; BOOL quoted = FALSE; + BOOL escaped = FALSE; int mcharn = strlen(mchar), pcharn = strlen(pchar); for (n = 0; n < inlen; n++) { c = in[n]; - if (c == '"') + if (c == '"' && !escaped) { quoted = !quoted; } + if (c == '*' && !escaped) + escaped = TRUE; + else + escaped = FALSE; + if (quoted) continue; @@ -45,6 +51,7 @@ LONG readLine(ShellState *ss, struct CommandLineInterface *cli, Buffer *out, WOR STRPTR buf = out->buf; /* pre-allocated by caller */ BOOL comment = FALSE; BOOL quoted = FALSE; + BOOL escaped = FALSE; LONG c, i, j, len; TEXT pchar[3], mchar[3]; @@ -62,41 +69,47 @@ LONG readLine(ShellState *ss, struct CommandLineInterface *cli, Buffer *out, WOR for (i = 0, j = 0; i < LINE_MAX; ++i) { - c = FGetC(fh); + c = FGetC(fh); - if (c == ENDSTREAMCH) - break; + if (c == ENDSTREAMCH) + break; - if (c == '"') + if (c == '"' && !escaped) quoted = !quoted; + if (c == '*' && !escaped) + escaped = TRUE; + else + escaped = FALSE; + if (!quoted && c == ';' && c != mchar[0] ) /* comment line */ - { - comment = TRUE; - continue; - } - else if (c == '\n') /* end of line */ - { - comment = FALSE; - - /* '+' continuation */ - if (j > 0 && buf[j-1]=='+') { - buf[j-1]=c; - continue; + { + comment = TRUE; + continue; + } + else if (c == '\n') /* end of line */ + { + comment = FALSE; + + /* '+' continuation */ + /* requires "+", validated with AmigaOS 3.1/2.1 Shell */ + if (j > 1 && buf[j-1] == '+' && buf[j-2] == ' ') { + buf[j-1] = c; + continue; } - } - else if (comment) - continue; + } + else if (comment) + continue; - buf[j++] = c; + buf[j++] = c; - if (c == '\n') /* end of line */ - break; + if (c == '\n') /* end of line */ + break; } if (i >= LINE_MAX) { D(bug("[Shell] ERROR_LINE_TOO_LONG\n")); - return ERROR_LINE_TOO_LONG; + return ERROR_LINE_TOO_LONG; } buf[j] = '\0'; @@ -110,4 +123,3 @@ LONG readLine(ShellState *ss, struct CommandLineInterface *cli, Buffer *out, WOR D(bug("[Shell] readLine %d%s: %s", j, *moreLeft ? "" : "'", buf)); return 0; } - diff --git a/workbench/c/Shell/redirection.c b/workbench/c/Shell/redirection.c index ee096c1684b..a5cf35b6043 100644 --- a/workbench/c/Shell/redirection.c +++ b/workbench/c/Shell/redirection.c @@ -18,16 +18,16 @@ void Redirection_release(ShellState *ss) /* Close redirection files and install regular input and output streams */ if (ss->newIn) { - D(bug("[Shell] Closing redirected input 0x%p, old 0x%p\n", ss->newIn, ss->oldIn)); - SelectInput(ss->oldIn); - Close(ss->newIn); + D(bug("[Shell] Closing redirected input 0x%p, old 0x%p\n", ss->newIn, ss->oldIn)); + SelectInput(ss->oldIn); + Close(ss->newIn); } if (ss->newOut) { - D(bug("[Shell] Closing redirected output 0x%p, old 0x%p\n", ss->newOut, ss->oldOut)); - SelectOutput(ss->oldOut); - Close(ss->newOut); + D(bug("[Shell] Closing redirected output 0x%p, old 0x%p\n", ss->newOut, ss->oldOut)); + SelectOutput(ss->oldOut); + Close(ss->newOut); } ss->newIn = BNULL; diff --git a/workbench/c/Shell/shell.conf b/workbench/c/Shell/shell.conf index 9c589721387..c9f77984924 100644 --- a/workbench/c/Shell/shell.conf +++ b/workbench/c/Shell/shell.conf @@ -1,5 +1,5 @@ ##begin config -version 41.4 +version 41.5 libbase Shell residentpri -123 options noexpunge diff --git a/workbench/c/Shell/shell_init.c b/workbench/c/Shell/shell_init.c index e71c03a678f..5f8942fd5ab 100644 --- a/workbench/c/Shell/shell_init.c +++ b/workbench/c/Shell/shell_init.c @@ -66,17 +66,17 @@ static int GM_UNIQUENAME(Init)(LIBBASETYPEPTR LIBBASE) DOSBase = OpenLibrary("dos.library", 0); if ( DOSBase == NULL ) { - D(bug("[Shell] What? No dos.library?\n")); - return FALSE; + D(bug("[Shell] What? No dos.library?\n")); + return FALSE; } seg = CreateSegList(ShellStart); if (seg != BNULL) { - AddSegment("shell", seg, CMD_SYSTEM); + AddSegment("shell", seg, CMD_SYSTEM); #ifdef __mc68000 - AddSegment("CLI", MKBADDR(Shell_CLISeg), CMD_SYSTEM); + AddSegment("CLI", MKBADDR(Shell_CLISeg), CMD_SYSTEM); #else - AddSegment("CLI", seg, CMD_SYSTEM); + AddSegment("CLI", seg, CMD_SYSTEM); #endif } diff --git a/workbench/c/shellcommands/Run.c b/workbench/c/shellcommands/Run.c index 7a82c18967e..b92880fcca4 100644 --- a/workbench/c/shellcommands/Run.c +++ b/workbench/c/shellcommands/Run.c @@ -1,9 +1,7 @@ /* - Copyright © 1995-2011, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. Desc: - Lang: English */ /****************************************************************************** @@ -27,7 +25,7 @@ INPUTS - QUIET -- avoids printing of the background CLI's number + QUIET -- avoids printing of the background CLI's number COMMAND -- the program to run together with its arguments @@ -50,6 +48,9 @@ HISTORY + 41.4: Preserve quoting and escapes in the child command line. + 41.5: Run every '+' continuation line, once. + ******************************************************************************/ #include @@ -58,6 +59,7 @@ #include #include #include +#include #include #include #include @@ -67,7 +69,12 @@ #include -AROS_SH2H(Run, 41.3, "Start a program as a background process\n", +#include +#include + +#include "run_handle.h" + +AROS_SH2H(Run, 41.5, "Start a program as a background process\n", AROS_SHAH(BOOL , ,QUIET ,/S,FALSE,"\tDon't print the background CLI's number"), AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (arguments allowed)\n") ) { @@ -75,17 +82,56 @@ AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (argume struct CommandLineInterface *cli = Cli(); struct Process *me = (struct Process *)FindTask(NULL); - BPTR cis = BNULL, cos = BNULL, ces = BNULL; + BPTR cis = BNULL, sis = BNULL, cos = BNULL, ces = BNULL; struct FileHandle *fh; LONG argsize; CONST_STRPTR argbuff; STRPTR command = (STRPTR)SHArg(COMMAND); LONG cmdsize = 0; + STRPTR nl; - if (!command) + if (command) + { + struct CSource source = { (STRPTR)SHArgLine(), strlen(SHArgLine()), 0 }; + BOOL quiet = SHArg(QUIET), keyword = TRUE, equal = FALSE; + char item[8]; + LONG start, type; + + /* ReadArgs /F removes the first item's quotes and escapes. The child + * CLI needs the original text. Skip only Run's own parsed options. */ + for (;;) + { + start = source.CS_CurChr; + type = ReadItem(item, sizeof item, &source); + if (type == ITEM_UNQUOTED && quiet && !strcasecmp(item, "QUIET")) + { + quiet = FALSE; + continue; + } + if (type == ITEM_UNQUOTED && keyword && !strcasecmp(item, "COMMAND")) + { + keyword = FALSE; + equal = TRUE; + continue; + } + if (type == ITEM_EQUAL && equal) + { + equal = FALSE; + continue; + } + /* A help prompt reads a new line; the original '?' is stale. */ + if (type == ITEM_UNQUOTED && !strcmp(item, "?")) + break; + command = source.CS_Buffer + start; + break; + } + } + else command = ""; cis = Open("NIL:", MODE_OLDFILE); + if (!cis) + goto error; /* To support '+' style continuation, we're * going to need to be a little tricky. We @@ -98,6 +144,13 @@ AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (argume fh = BADDR(Input()); argsize = (fh->fh_End > 0 && fh->fh_Pos > 0) ? (fh->fh_End - fh->fh_Pos) : 0; + /* The Shell joins the continuation lines into the argument line, which + * the command already holds then. + */ + nl = strchr(command, '\n'); + if (nl && nl[1]) + argsize = 0; + /* Good, there's some buffered input for us. * Append it to the command. */ @@ -109,8 +162,8 @@ AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (argume tmp = AllocMem(cmdsize+1+argsize+1, MEMF_ANY); if (tmp) { + CopyMem(command, tmp, cmdsize); command = tmp; - CopyMem(SHArg(COMMAND), command, cmdsize); command[cmdsize++]='\n'; CopyMem(argbuff, &command[cmdsize], argsize); cmdsize += argsize; @@ -120,11 +173,28 @@ AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (argume } } - cos = OpenFromLock(DupLockFromFH(Output())); + /* The background CLI reads the command lines from cis. Each command it + * runs gets its arguments injected into Input(), which is flushed after + * the command, so with '+' continuation lines a shared handle loses the + * lines not yet read. Give the commands their own input then. + */ + nl = strchr(command, '\n'); + if (nl && nl[1]) + { + sis = Open("NIL:", MODE_OLDFILE); + if (!sis) + goto error; + } + else + sis = cis; + + cos = DuplicateRunHandle(Output(), DOSBase); + if (!cos) + goto error; /* All the 'noise' goes to cli_StandardError */ - if (!SHArg(QUIET)) { + if (!SHArg(QUIET) && IsInteractive(Output())) { if (cli) { ces = cli->cli_StandardError; @@ -136,34 +206,35 @@ AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (argume /* Use a duplicate of the CES lock */ if (ces) - ces = OpenFromLock(DupLockFromFH(ces)); + ces = DuplicateRunHandle(ces, DOSBase); else ces = Open("NIL:", MODE_OLDFILE); + if (!ces) + goto error; if ( command[0] != 0) { struct TagItem tags[] = { - { SYS_ScriptInput, (IPTR)cis }, - { SYS_Input, (IPTR)cis }, - { SYS_Output, (IPTR)cos }, - { SYS_Error, (IPTR)ces }, - { SYS_CliType, (IPTR)CLI_RUN }, - { TAG_DONE, 0 } + { SYS_ScriptInput, (IPTR)cis }, + { SYS_Input, (IPTR)sis }, + { SYS_Output, (IPTR)cos }, + { SYS_Error, (IPTR)ces }, + { SYS_CliType, (IPTR)CLI_RUN }, + { TAG_DONE, 0 } }; if ( SystemTagList((CONST_STRPTR)command, tags ) == -1 ) - { - PrintFault(IoErr(), "Run"); - Close(cis); - Close(cos); - Close(ces); - if (cmdsize > 0) - FreeMem(command, cmdsize); - - return RETURN_FAIL; - } + goto error; + } + else + { + if (sis != cis) + Close(sis); + Close(cis); + Close(cos); + Close(ces); } if (cmdsize > 0) @@ -171,5 +242,18 @@ AROS_SHAH(STRPTR, ,COMMAND,/F,NULL , "The program (resp. script) to run (argume return RETURN_OK; +error: + { + LONG error = IoErr(); + PrintFault(error, "Run"); + if (sis && sis != cis) Close(sis); + if (cis) Close(cis); + if (cos) Close(cos); + if (ces) Close(ces); + if (cmdsize > 0) FreeMem(command, cmdsize); + SetIoErr(error); + } + return RETURN_FAIL; + AROS_SHCOMMAND_EXIT } diff --git a/workbench/c/shellcommands/run_handle.h b/workbench/c/shellcommands/run_handle.h new file mode 100644 index 00000000000..0d0242da164 --- /dev/null +++ b/workbench/c/shellcommands/run_handle.h @@ -0,0 +1,61 @@ +/* Copyright (C) 2026, The AROS Development Team. All rights reserved. */ +#ifndef SHELL_RUN_HANDLE_H +#define SHELL_RUN_HANDLE_H +/* Run needs its own handle: the parent Shell closes redirections on return. + * MODE_NEWFILE may hold an exclusive lock, which cannot be duplicated until + * explicitly shared. Preserve a seekable stream's position (notably >>). */ +static BPTR DuplicateRunHandle(BPTR source, struct DosLibrary *DOSBase) +{ + BPTR lock, copy; + LONG position = -1, error; + + if (!source) + { + SetIoErr(ERROR_INVALID_LOCK); + return BNULL; + } + if (!IsInteractive(source)) + { + position = Seek(source, 0, OFFSET_CURRENT); + if (position < 0) + { + error = IoErr(); + /* Only an explicitly unsupported seek permits positionless + * duplication. Never turn an I/O error into an append at zero. + * This LONG-based path cannot preserve positions above LONG_MAX. */ + if (position != -1 || error != ERROR_ACTION_NOT_KNOWN) + { + SetIoErr(position == -1 && error ? error : ERROR_SEEK_ERROR); + return BNULL; + } + } + } + + lock = DupLockFromFH(source); + if (!lock && IoErr() == ERROR_OBJECT_IN_USE) + { + if (!ChangeMode(CHANGE_FH, source, SHARED_LOCK)) + return BNULL; + lock = DupLockFromFH(source); + } + if (!lock) + return BNULL; + + copy = OpenFromLock(lock); + if (!copy) + { + error = IoErr(); + UnLock(lock); /* OpenFromLock consumes the lock only on success. */ + SetIoErr(error); + return BNULL; + } + if (position >= 0 && Seek(copy, position, OFFSET_BEGINNING) == -1) + { + error = IoErr(); + Close(copy); + SetIoErr(error); + return BNULL; + } + return copy; +} +#endif diff --git a/workbench/c/shellcommands/shellcommands.conf b/workbench/c/shellcommands/shellcommands.conf index eb469475637..ba745e5a21e 100644 --- a/workbench/c/shellcommands/shellcommands.conf +++ b/workbench/c/shellcommands/shellcommands.conf @@ -1,5 +1,5 @@ ##begin config -version 41.1 +version 41.2 libbase ShellCommandsBase libbasetype struct ShellCommandsBase seglist_field sc_SegList