Commit 9863abfa authored by jan.koester's avatar jan.koester
Browse files

sh: a quoted '>' or '<' is a word, not a redirection

tokenizeShellArgs() returned the operator ">" and the quoted word '>' as
the same string, so extractRedirections() redirected on both: `echo x '>'
dir` (rust's run_rustc Makefile: echo [CARGO] ... '>' $(OUTDIR)build-std2)
created a file "dir" instead of printing, and cargo then failed on the
directory of that name. Same for ">", \>, '>>', '<'.

The tokenizer now marks the operators it splits off itself (a \x01 prefix,
opt-in via tokenizeShellArgs(..., true)), and extractRedirections(...,
true) only takes marked tokens as operators. The pipeline/subshell/brace
group stages and the compound-command trailing redirection use it; the
other tokenizeShellArgs() users are unchanged.

Checked in the RC5 chroot: the quoted forms print, while >, >>, 2>, <,
2>&1, "{ ...; } > f", "( ... ) > f" and $(...) behave as before.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent b7c8c974
Loading
Loading
Loading
Loading
+45 −28
Changes for src/shell.cpp: 45 added lines, 28 removed lines.
Original line number Diff line number Diff line
@@ -435,7 +435,14 @@ static void flushToken(std::vector<std::string> &tokens,std::string &current,
    }
}

std::vector<std::string> fresh::tokenizeShellArgs(const std::string &segment){
// Prefix of a redirection operator token split off by the tokenizer
// (tokenizeShellArgs(..., true)); a control character no shell word has.
static const char REDIR_OP_MARK='\x01';

std::vector<std::string> fresh::tokenizeShellArgs(const std::string &segment,bool markOperators){
    auto opTok=[markOperators](const std::string &op){
        return markOperators ? std::string(1,REDIR_OP_MARK)+op : op;
    };
    std::vector<std::string> tokens;
    // Fully resolved (expanded where appropriate, literal where not) text
    // for the token currently being built.
@@ -577,19 +584,19 @@ std::vector<std::string> fresh::tokenizeShellArgs(const std::string &segment){
            if(j<n && (segment[j]=='>' || segment[j]=='<')){
                std::string fdprefix=segment.substr(i,j-i);
                if(segment[j]=='<'){
                    tokens.push_back(fdprefix+"<");
                    tokens.push_back(opTok(fdprefix+"<"));
                    i=j+1;
                }else if(j+1<n && segment[j+1]=='>'){
                    tokens.push_back(fdprefix+">>");
                    tokens.push_back(opTok(fdprefix+">>"));
                    i=j+2;
                }else if(j+2<n && segment[j+1]=='&' && isdigit((unsigned char)segment[j+2])){
                    size_t k=j+2;
                    while(k<n && isdigit((unsigned char)segment[k]))
                        ++k;
                    tokens.push_back(fdprefix+">&"+segment.substr(j+2,k-(j+2)));
                    tokens.push_back(opTok(fdprefix+">&"+segment.substr(j+2,k-(j+2))));
                    i=k;
                }else{
                    tokens.push_back(fdprefix+">");
                    tokens.push_back(opTok(fdprefix+">"));
                    i=j+1;
                }
                continue;
@@ -611,15 +618,15 @@ std::vector<std::string> fresh::tokenizeShellArgs(const std::string &segment){
                size_t k=i+2;
                while(k<n && isdigit((unsigned char)segment[k]))
                    ++k;
                tokens.push_back("1>&"+segment.substr(i+2,k-(i+2)));
                tokens.push_back(opTok("1>&"+segment.substr(i+2,k-(i+2))));
                i=k;
                continue;
            }
            if(c=='>' && i+1<n && segment[i+1]=='>'){
                tokens.push_back(">>");
                tokens.push_back(opTok(">>"));
                i+=2;
            }else{
                tokens.push_back(std::string(1,c));
                tokens.push_back(opTok(std::string(1,c)));
                ++i;
            }
            continue;
@@ -2753,40 +2760,50 @@ bool fresh::needsMoreInput(const std::string &text){
}

std::vector<std::string> fresh::extractRedirections(const std::vector<std::string> &tokens,
                                                      fresh::Redirection &redir){
                                                      fresh::Redirection &redir,bool marked){
    std::vector<std::string> cleaned;

    // With `marked`, only tokens the tokenizer split off as operators are
    // (REDIR_OP_MARK prefix): a quoted '>' is an ordinary word
    auto word=[marked](const std::string &t){
        return (marked && !t.empty() && t[0]==REDIR_OP_MARK) ? t.substr(1) : t;
    };
    for(size_t i=0; i<tokens.size(); ++i){
        if((tokens[i]==">" || tokens[i]==">>" || tokens[i]=="1>" || tokens[i]=="1>>") &&
           i+1<tokens.size()){
        bool isop=!marked || (!tokens[i].empty() && tokens[i][0]==REDIR_OP_MARK);
        std::string t=word(tokens[i]);
        if(!isop){
            cleaned.push_back(t);
            continue;
        }
        if((t==">" || t==">>" || t=="1>" || t=="1>>") && i+1<tokens.size()){
            redir.hasStdout=true;
            redir.append=(tokens[i]==">>" || tokens[i]=="1>>");
            redir.stdoutFile=tokens[i+1];
            redir.append=(t==">>" || t=="1>>");
            redir.stdoutFile=word(tokens[i+1]);
            ++i;
            continue;
        }
        if((tokens[i]=="<" || tokens[i]=="0<") && i+1<tokens.size()){
        if((t=="<" || t=="0<") && i+1<tokens.size()){
            redir.hasStdin=true;
            redir.stdinFile=tokens[i+1];
            redir.stdinFile=word(tokens[i+1]);
            ++i;
            continue;
        }
        if(tokens[i]=="2>&1"){
        if(t=="2>&1"){
            redir.stderrToStdout=true;
            continue;
        }
        if(tokens[i]=="1>&2"){
        if(t=="1>&2"){
            redir.stdoutToStderr=true;
            continue;
        }
        if((tokens[i]=="2>" || tokens[i]=="2>>") && i+1<tokens.size()){
        if((t=="2>" || t=="2>>") && i+1<tokens.size()){
            redir.hasStderr=true;
            redir.stderrAppend=(tokens[i]=="2>>");
            redir.stderrFile=tokens[i+1];
            redir.stderrAppend=(t=="2>>");
            redir.stderrFile=word(tokens[i+1]);
            ++i;
            continue;
        }
        cleaned.push_back(tokens[i]);
        cleaned.push_back(t);
    }

    return cleaned;
@@ -2882,7 +2899,7 @@ bool fresh::CompoundRedirect::apply(const std::string &trailing,std::string &res
    HeredocSpec heredoc;
    bool hasHeredoc=extractHeredocSpec(text,heredoc);
    Redirection r;
    if(!extractRedirections(tokenizeShellArgs(text),r).empty())
    if(!extractRedirections(tokenizeShellArgs(text,true),r,true).empty())
        return true;  // not (only) redirections: leave it all to the caller, as before

    // what was printed so far goes where it was meant to
@@ -3071,8 +3088,8 @@ int fresh::Shell::runSimple(const std::string &segment){
        std::string subshellBody,suffix;
        if(extractSubshellBody(rawstages[i],subshellBody,suffix)){
            stageSubshellBody.push_back(subshellBody);
            std::vector<std::string> tokens=tokenizeShellArgs(suffix);
            stageTokens.push_back(extractRedirections(tokens,redir));
            std::vector<std::string> tokens=tokenizeShellArgs(suffix,true);
            stageTokens.push_back(extractRedirections(tokens,redir,true));
            stageRedirs.push_back(redir);
            continue;
        }
@@ -3087,8 +3104,8 @@ int fresh::Shell::runSimple(const std::string &segment){
        // group opener at all).
        if(extractBraceGroupBody(rawstages[i],subshellBody,suffix)){
            stageSubshellBody.push_back(subshellBody);
            std::vector<std::string> tokens=tokenizeShellArgs(suffix);
            stageTokens.push_back(extractRedirections(tokens,redir));
            std::vector<std::string> tokens=tokenizeShellArgs(suffix,true);
            stageTokens.push_back(extractRedirections(tokens,redir,true));
            stageRedirs.push_back(redir);
            continue;
        }
@@ -3110,8 +3127,8 @@ int fresh::Shell::runSimple(const std::string &segment){
        }
        stageSubshellBody.push_back("");

        std::vector<std::string> tokens=tokenizeShellArgs(rawstages[i]);
        stageTokens.push_back(extractRedirections(tokens,redir));
        std::vector<std::string> tokens=tokenizeShellArgs(rawstages[i],true);
        stageTokens.push_back(extractRedirections(tokens,redir,true));
        stageRedirs.push_back(redir);

        // See the "!_running" check just below the loop: a fatal
+8 −2
Changes for src/shell.h: 8 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -98,7 +98,11 @@ namespace fresh {
    // becomes two items), matching plain-word POSIX field splitting closely
    // enough for scripting use. Exposed (not file-local to shell.cpp) so
    // the for-loop builtin can reuse it for its item list.
    std::vector<std::string> tokenizeShellArgs(const std::string &segment);
    // markOperators: redirection operators the tokenizer itself split off
    // come back prefixed with REDIR_OP_MARK, so extractRedirections(...,
    // true) can tell them from a quoted word that merely reads ">" (make's
    // `echo [CARGO] x '>' dir` must print, not create the file "dir")
    std::vector<std::string> tokenizeShellArgs(const std::string &segment,bool markOperators=false);

    // Scans words[from..to) tracking if/for/while ... fi/done nesting depth
    // and returns the index of the first word equal to keyword seen at
@@ -261,8 +265,10 @@ namespace fresh {
    // for the file forms, the filename token right after) out of an
    // already-tokenized argv, filling redir and returning the remaining
    // tokens (the real argv).
    // marked: the tokens come from tokenizeShellArgs(..., true) -- only
    // REDIR_OP_MARK-prefixed tokens are operators
    std::vector<std::string> extractRedirections(const std::vector<std::string> &tokens,
                                                   Redirection &redir);
                                                   Redirection &redir,bool marked=false);

    // A "<<WORD" (or "<<-WORD"/"<<'WORD'"/"<<\"WORD\"") here-doc operator
    // found by extractHeredocSpec() in a stage's raw text. quoted (delimiter