Commit def8bd9f authored by jan.koester's avatar jan.koester
Browse files

sh: read/builtins with redirections, heredocs in groups, expr ':'

Found while building git with fresh as /bin/sh:
- builtins that change shell state (read, cd, export, eval, ., ...) and
  shell functions run in-process when they carry redirections, so
  "read A B <<EOF" and "read x <file" keep their variables
- a heredoc body inside "{ ... }" is data: a "};" line no longer closes
  the group
- "} >file" / '} >"$OUT"' (glued) redirect the group
- unquoted heredoc bodies run $(...) and `...`
- "${line#$cmd - }": the word stays whole (its '}' no longer closes an
  enclosing function) and the pattern is expanded
- $PWD is set at startup
- expr: "STRING : REGEX", match, length, substr, index

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 3dd28f4e
Loading
Loading
Loading
Loading
+73 −7
Changes for commands/text/expr.cpp: 73 added lines, 7 removed lines.
Original line number Diff line number Diff line
@@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
#include <cstdlib>
#include <regex.h>

#include "shell.h"

@@ -47,11 +48,12 @@ namespace fresh { namespace cmd {
    // 1"-style counters). Precedence low-to-high: "|" (first non-null/
    // non-zero operand, else second), "&" (first operand if both are
    // non-null/non-zero, else 0), relational (= != < <= > >=, numeric if
    // both sides parse as integers, else lexical), "+ -", "* / %". No
    // "length"/"substr"/"index"/"match"/regex operators, and no ":" match
    // operator -- covers the arithmetic/comparison core real scripts
    // actually reach for over "$((...))" (mainly for POSIX sh portability
    // and its own exit-status-as-truth-value convention).
    // both sides parse as integers, else lexical), "+ -", "* / %", and
    // POSIX's "STRING : REGEX" (a basic regex anchored at the start of
    // STRING: the text of its first \(...\) group, or else the number of
    // characters matched -- git's GIT-VERSION-GEN: expr "$VN" : v*'\(.*\)').
    // GNU's prefix forms "match STRING REGEX", "length STRING", "substr
    // STRING POS LEN" and "index STRING CHARS" work too.
    class ExprCommand : public ShellCommand {
    public:
        ExprCommand():ShellCommand("expr"){}
@@ -82,11 +84,44 @@ namespace fresh { namespace cmd {
            return !s.empty() && s!="0";
        }

        std::string parseMul(){
        // "STRING : REGEX"
        static std::string match(const std::string &str,std::string pat){
            if(!pat.empty() && pat[0]=='^')
                pat.erase(0,1);
            regex_t re;
            int rc=regcomp(&re,("^"+pat).c_str(),0);
            if(rc!=0){
                char msg[256];
                regerror(rc,&re,msg,sizeof(msg));
                throw ExprError{std::string("invalid regex: ")+msg};
            }
            regmatch_t m[2];
            bool hit=regexec(&re,str.c_str(),2,m,0)==0;
            bool group=re.re_nsub>0;
            regfree(&re);
            if(group){
                if(!hit || m[1].rm_so<0)
                    return "";
                return str.substr(m[1].rm_so,m[1].rm_eo-m[1].rm_so);
            }
            return std::to_string(hit ? (long long)(m[0].rm_eo-m[0].rm_so) : 0LL);
        }

        std::string parseMatch(){
            std::string left=parseUnary();
            while(!atEnd() && peek()==":"){
                next();
                std::string right=parseUnary();
                left=match(left,right);
            }
            return left;
        }

        std::string parseMul(){
            std::string left=parseMatch();
            while(!atEnd() && (peek()=="*" || peek()=="/" || peek()=="%")){
                std::string op=next();
                std::string right=parseUnary();
                std::string right=parseMatch();
                long long a,b;
                if(!isInt(left,a) || !isInt(right,b))
                    throw ExprError{"non-numeric argument"};
@@ -171,6 +206,37 @@ namespace fresh { namespace cmd {
                    throw ExprError{"syntax error (expected ')')"};
                return v;
            }
            // GNU prefix operators (only with enough operands following,
            // so a lone "length" is still a plain string)
            if(peek()=="match" && pos+2<toks.size()){
                next();
                std::string str=parseUnary();
                std::string pat=parseUnary();
                return match(str,pat);
            }
            if(peek()=="length" && pos+1<toks.size()){
                next();
                return std::to_string((long long)parseUnary().size());
            }
            if(peek()=="substr" && pos+3<toks.size()){
                next();
                std::string str=parseUnary();
                long long p,l;
                std::string ps=parseUnary();
                std::string ls=parseUnary();
                if(!isInt(ps,p) || !isInt(ls,l))
                    throw ExprError{"non-numeric argument"};
                if(p<1 || l<1 || (size_t)p>str.size())
                    return "";
                return str.substr((size_t)p-1,(size_t)l);
            }
            if(peek()=="index" && pos+2<toks.size()){
                next();
                std::string str=parseUnary();
                std::string chars=parseUnary();
                size_t at=str.find_first_of(chars);
                return std::to_string(at==std::string::npos ? 0LL : (long long)at+1);
            }
            return next();
        }

+26 −4
Changes for src/envoirment.cpp: 26 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -33,6 +33,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>

#include <unistd.h>
#include <sys/stat.h>

#include "envoirment.h"
#include "shell.h"
@@ -231,6 +232,24 @@ fresh::Environment::Environment(){
    // through the environment is replaced, and it is not exported
    _variables["PPID"]=std::to_string(getppid());
    _exported.erase("PPID");
    // $PWD (POSIX): set at startup to the current directory unless the
    // inherited value already names it (keeps a symlinked path the parent
    // was in); exported, so programs started from here see it as well
    {
        char cwd[4096];
        if(getcwd(cwd,sizeof(cwd))){
            std::map<std::string,std::string>::const_iterator w=_variables.find("PWD");
            struct stat a,b;
            bool keep=w!=_variables.end() && !w->second.empty() && w->second[0]=='/' &&
                      stat(w->second.c_str(),&a)==0 && stat(cwd,&b)==0 &&
                      a.st_dev==b.st_dev && a.st_ino==b.st_ino;
            if(!keep){
                _variables["PWD"]=cwd;
                setenv("PWD",cwd,1);
            }
            _exported["PWD"]=true;
        }
    }
    // An applet run directly (/usr/bin/env -> fresh, "#!/usr/bin/env
    // python3") returns before load() ever fills _path from config.yaml, so
    // runExternal() searched an empty list and every "env CMD" was "command
@@ -649,10 +668,9 @@ std::string fresh::Environment::expand(const std::string &token){
        // "$var#foo" is just the value of var followed by the literal text
        // "#foo", exactly like the plain-braced case below already treats
        // anything past the name that isn't an immediate '}'). The pattern
        // itself is taken as literal text up to the matching '}' -- not
        // re-expanded for nested "$"/"${...}" of its own, the same
        // "not full parity" scope limit already documented elsewhere in
        // this codebase (e.g. tokenizeShellArgs()'s "$(...)" handling).
        // itself is the text up to the matching '}', expanded when it
        // holds a "$"/"`" of its own (quotes in it are not treated
        // specially).
        if(braced && next<token.length() && (token[next]=='#' || token[next]=='%')){
            char opChar=token[next];
            bool fromStart=(opChar=='#');
@@ -675,6 +693,10 @@ std::string fresh::Environment::expand(const std::string &token){
                next=opStart; // unterminated -- fall back, treat '#'/'%' as literal below

            if(next!=opStart){
                // POSIX expands the pattern first: "${line#$cmd - }" (git's
                // generate-cmdlist.sh) strips "<value of cmd> - "
                if(pattern.find_first_of("$`")!=std::string::npos)
                    pattern=expand(pattern);
                result+=stripMatch(value,pattern,fromStart,longest);
                i=next-1;
                continue;
+3 −0
Changes for src/envoirment.h: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -52,6 +52,9 @@ namespace fresh {
    // back to a literal '$' unconditionally and never treats it as
    // starting an expansion.
    constexpr char kLiteralDollarMarker='\x01';
    // an escaped \` in an unquoted heredoc body: a literal backtick, not
    // the start of a command substitution
    constexpr char kLiteralBacktickMarker='\x02';

    // Shell variable store plus config.yaml (PATH/MOTD) loading. Deliberately
    // hand-rolled: config.yaml here only ever holds a short, fixed-shape
+247 −2
Changes for src/shell.cpp: 247 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -1243,6 +1243,41 @@ std::vector<fresh::ShellWord> fresh::tokenizeShellWords(const std::string &input
        size_t start=i;
        while(i<n && input[i]!=' ' && input[i]!='\t' && input[i]!='\r' &&
              input[i]!='\n' && input[i]!=';'){
            // "${line#$cmd - }": a parameter expansion is one word even
            // with blanks in its pattern/word -- split at them, its own
            // '}' became a word of its own and closed an enclosing
            // function body/brace group early (git's generate-cmdlist.sh)
            if(input[i]=='$' && i+1<n && input[i+1]=='{'){
                int depth=1;
                i+=2;
                while(i<n && depth>0){
                    char c=input[i];
                    if(c=='\\' && i+1<n){ i+=2; continue; }
                    if(c=='\''){
                        size_t e=input.find('\'',i+1);
                        i=(e==std::string::npos) ? n : e+1;
                        continue;
                    }
                    if(c=='"'){
                        ++i;
                        while(i<n && input[i]!='"'){
                            if(input[i]=='\\' && i+1<n) ++i;
                            ++i;
                        }
                        if(i<n) ++i;
                        continue;
                    }
                    if(c=='$' && i+1<n && input[i+1]=='{'){ ++depth; i+=2; continue; }
                    if(c=='$' && i+1<n && input[i+1]=='('){
                        size_t close=cmdSubstClose(input,i+2);
                        i=(close<n) ? close+1 : n;
                        continue;
                    }
                    if(c=='}') --depth;
                    ++i;
                }
                continue;
            }
            if(input[i]=='('){
                // "(cmds)" subshell group: ';'/newline/space *inside* it
                // (e.g. "(x=inner; echo "$x")") are not statement
@@ -3179,7 +3214,11 @@ std::string fresh::Shell::unescapeHeredocLine(const std::string &line,bool &cont
        if(next=='$'){
            out+=kLiteralDollarMarker;
            ++i;
        }else if(next=='`' || next=='\\'){
        }else if(next=='`'){
            // kept literal through expandHeredocText()'s `...` scan
            out+=kLiteralBacktickMarker;
            ++i;
        }else if(next=='\\'){
            out+=next;
            ++i;
        }else{
@@ -3189,6 +3228,48 @@ std::string fresh::Shell::unescapeHeredocLine(const std::string &line,bool &cont
    return out;
}

// An unquoted heredoc body line: "$(cmd)" and `cmd` run like in a word
// (git's GIT-VERSION-GEN: "read MAJOR MINOR ... <<EOF\n$(echo ... | tr
// ...)\nEOF"), their output inserted verbatim minus trailing newlines; the
// text around them gets the usual $-expansion.
static std::string expandHeredocText(const std::string &piece){
    std::string out,lit;
    size_t n=piece.size(),i=0;
    auto flush=[&](){
        if(!lit.empty()){
            out+=fresh::Environment::instance().expand(lit);
            lit.clear();
        }
    };
    auto trim=[](std::string r)->std::string{
        while(!r.empty() && r.back()=='\n') r.pop_back();
        return r;
    };
    while(i<n){
        if(piece[i]=='$' && i+1<n && piece[i+1]=='(' && !(i+2<n && piece[i+2]=='(')){
            size_t c=cmdSubstClose(piece,i+2);
            flush();
            out+=trim(fresh::Shell::instance().runCaptured(piece.substr(i+2,c-(i+2))));
            i=(c<n) ? c+1 : n;
            continue;
        }
        if(piece[i]=='`'){
            size_t e=piece.find('`',i+1);
            if(e==std::string::npos) e=n;
            flush();
            out+=trim(fresh::Shell::instance().runCaptured(piece.substr(i+1,e-i-1)));
            i=(e<n) ? e+1 : n;
            continue;
        }
        lit+=piece[i++];
    }
    flush();
    for(size_t k=0; k<out.size(); ++k)
        if(out[k]==fresh::kLiteralBacktickMarker)
            out[k]='`';
    return out;
}

std::string fresh::Shell::readHeredocBodyLines(std::istream &in,const fresh::HeredocSpec &spec){
    std::string body;
    std::string line;
@@ -3221,7 +3302,7 @@ std::string fresh::Shell::readHeredocBodyLines(std::istream &in,const fresh::Her
        std::string piece=unescapeHeredocLine(logical,continues);
        while(continues && std::getline(in,logical))
            piece += unescapeHeredocLine(logical,continues);
        body += Environment::instance().expand(piece);
        body += expandHeredocText(piece);
        body += "\n";
    }
    return body;
@@ -3453,6 +3534,117 @@ int fresh::Shell::runSimple(const std::string &segment){
        return rc;
    }

    // A single command with redirections whose effect must stay in THIS
    // shell -- "read VAR <file", "read A B <<EOF", "eval ... >log", ". f
    // <in", a shell function call "f <file" -- runs in-process with its
    // redirections applied around it and undone afterwards (POSIX 2.9.1:
    // only external commands get a child). runPipeline() forks every stage,
    // so the variables "read" set there used to die with the child (git's
    // GIT-VERSION-GEN: "read MAJOR MINOR ... <<EOF"). External commands and
    // fresh's own multicall tools (sed, awk, ...) still fork as before.
    if(stageTokens.size()==1 && !anySubshell && anyRedirection && !stageTokens[0].empty()){
        static const char *inProcess[]={"read","cd","export","unset","set","eval",".",
                                        "source","shift","local","trap","umask",
                                        "readonly","getopts","alias","unalias",nullptr};
        std::vector<std::string> tokens=stageTokens[0];
        std::vector<std::pair<std::string,std::string> > assignments=
            extractLeadingAssignments(tokens);
        bool runHere=false;
        if(!tokens.empty()){
            for(size_t k=0; inProcess[k]; ++k)
                if(tokens[0]==inProcess[k] && find(tokens[0]))
                    runHere=true;
            if(!runHere && !find(tokens[0]) && hasFunction(tokens[0]))
                runHere=true;
        }
        if(runHere){
            const Redirection &redir=stageRedirs[0];
            // buffered output written before the redirection belongs to
            // the old fd 1/2
            std::cout.flush();
            std::cerr.flush();

            int savedStdin=-1,savedStdout=-1,savedStderr=-1;
            bool openFailed=false;
            std::string openFailMsg;
            int openErrno=0;
            if(redir.hasStdin){
                int fd=open(redir.stdinFile.c_str(),O_RDONLY);
                if(fd<0){ openFailed=true; openFailMsg=redir.stdinFile; openErrno=errno; }
                else{ savedStdin=dup(0); dup2(fd,0); close(fd); }
            }
            if(!openFailed && redir.hasStdout){
                int flags=O_WRONLY|O_CREAT|(redir.append ? O_APPEND : O_TRUNC);
                int fd=open(redir.stdoutFile.c_str(),flags,0644);
                if(fd<0){ openFailed=true; openFailMsg=redir.stdoutFile; openErrno=errno; }
                else{ savedStdout=dup(1); dup2(fd,1); close(fd); }
            }
            if(!openFailed && redir.hasStderr){
                int flags=O_WRONLY|O_CREAT|(redir.stderrAppend ? O_APPEND : O_TRUNC);
                int fd=open(redir.stderrFile.c_str(),flags,0644);
                if(fd<0){ openFailed=true; openFailMsg=redir.stderrFile; openErrno=errno; }
                else{ savedStderr=dup(2); dup2(fd,2); close(fd); }
            }
            if(!openFailed && redir.stderrToStdout){
                if(savedStderr<0) savedStderr=dup(2);
                dup2(1,2);
            }
            if(!openFailed && redir.stdoutToStderr){
                if(savedStdout<0) savedStdout=dup(1);
                dup2(2,1);
            }
            std::vector<std::pair<int,int> > dupSaved;
            bool dupFailed=!openFailed && !applyFdDups(redir.dups,&dupSaved);

            int rc;
            if(openFailed){
                std::cerr << "fresh: " << openFailMsg << ": " << strerror(openErrno) << std::endl;
                rc=1;
            }else if(dupFailed){
                rc=1;
            }else{
                // "FOO=bar cmd <file": FOO only for this command, as in
                // the fast path above
                std::vector<std::pair<std::string,bool> > hadOld;
                std::vector<std::string> oldValues;
                for(size_t k=0; k<assignments.size(); ++k){
                    const char *old=getenv(assignments[k].first.c_str());
                    hadOld.push_back(std::make_pair(assignments[k].first,old!=nullptr));
                    oldValues.push_back(old ? old : "");
                    setenv(assignments[k].first.c_str(),assignments[k].second.c_str(),1);
                }
                ShellCommand *cmd=find(tokens[0]);
                if(cmd){
                    std::vector<const char*> cargs(tokens.size()+1,nullptr);
                    for(size_t k=0; k<tokens.size(); ++k)
                        cargs[k]=tokens[k].c_str();
                    rc=cmd->runCommand((int)tokens.size(),cargs.data());
                }else{
                    std::vector<std::string> fnargs(tokens.begin()+1,tokens.end());
                    rc=callFunction(tokens[0],fnargs);
                }
                for(size_t k=0; k<hadOld.size(); ++k){
                    if(hadOld[k].second)
                        setenv(hadOld[k].first.c_str(),oldValues[k].c_str(),1);
                    else
                        unsetenv(hadOld[k].first.c_str());
                }
            }

            // see the "{ ...; } >file" group's own flush-before-restore note
            std::cout.flush();
            std::cerr.flush();
            restoreFdDups(dupSaved);
            if(savedStdin>=0){ dup2(savedStdin,0); close(savedStdin); }
            if(savedStdout>=0){ dup2(savedStdout,1); close(savedStdout); }
            if(savedStderr>=0){ dup2(savedStderr,2); close(savedStderr); }

            for(size_t i=0; i<heredocTempFiles.size(); ++i)
                unlink(heredocTempFiles[i].c_str());
            return rc;
        }
    }

    int result=runPipeline(stageTokens,stageRedirs,stageSubshellBody);

    for(size_t i=0; i<heredocTempFiles.size(); ++i)
@@ -3708,8 +3900,26 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
    // each compound stage as a body of its own
    if(first=="if" || first=="for" || first=="while" || first=="until" || first=="case" || first=="{"){
        int d=0;
        bool inDoc=false;
        std::string docDelim;
        for(size_t i=from;i<to;++i){
            const std::string &w=words[i].text;
            // heredoc body lines are data (a "};" or "done" in one is no
            // keyword), same skip as parse()'s own per-statement scan
            if(inDoc){
                if(w==docDelim) inDoc=false;
                continue;
            }
            {
                size_t used=1;
                std::string dl=heredocMarkerDelim(words,i,used);
                if(!dl.empty()){
                    inDoc=true;
                    docDelim=dl;
                    i+=used-1;
                    continue;
                }
            }
            bool stmtStart=(i==from || words[i-1].text==";" || words[i-1].text=="&&" ||
                            words[i-1].text=="||" || words[i-1].text=="|" || words[i-1].text=="do" ||
                            words[i-1].text=="then" || words[i-1].text=="else" ||
@@ -3742,7 +3952,26 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
    if(first=="{"){
        int depth=1;
        size_t closeIdx=to;
        bool inDoc=false;
        std::string docDelim;
        for(size_t i=from+1;i<to;++i){
            // A heredoc body inside the group is data: its lines (e.g. the
            // "};" closing a C array in git's generate-hooklist.sh) must
            // not count as the group's closing '}'.
            if(inDoc){
                if(words[i].text==docDelim) inDoc=false;
                continue;
            }
            {
                size_t used=1;
                std::string dl=heredocMarkerDelim(words,i,used);
                if(!dl.empty()){
                    inDoc=true;
                    docDelim=dl;
                    i+=used-1;
                    continue;
                }
            }
            // Only at a statement-start position (right after ';'/'&&'/
            // '||', or immediately after the opening '{'/keyword itself)
            // does a bare "{"/"}" count as real compound-command syntax
@@ -3823,7 +4052,23 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
                redirTokens.push_back(t);
                redirEnd+=1;
            }else{
                // glued form: '} >"$OUTPUT"', '} >file', '} 2>>log' (git's
                // generate-hooklist.sh / generate-cmdlist.sh)
                static const char *ops[]={"1>>","2>>",">>","1>","2>","0<",">","<",nullptr};
                std::string op;
                for(size_t k=0; ops[k]; ++k){
                    size_t l=strlen(ops[k]);
                    if(t.size()>l && t.compare(0,l,ops[k])==0){
                        op=ops[k];
                        break;
                    }
                }
                if(op.empty())
                    break;
                redirTokens.push_back(op);
                std::vector<std::string> target=tokenizeShellArgs(t.substr(op.size()));
                redirTokens.push_back(target.empty() ? std::string() : target[0]);
                redirEnd+=1;
            }
        }