sh.c 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431
  1. /* sh.c - toybox shell
  2. *
  3. * Copyright 2006 Rob Landley <rob@landley.net>
  4. *
  5. * This shell aims for bash compatibility. The bash man page is at:
  6. * http://man7.org/linux/man-pages/man1/bash.1.html
  7. *
  8. * The POSIX-2008/SUSv4 shell spec is at:
  9. * http://opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  10. * and http://opengroup.org/onlinepubs/9699919799/utilities/sh.html
  11. *
  12. * deviations from posix: don't care about $LANG or $LC_ALL
  13. * builtins: alias bg command fc fg getopts jobs newgrp read umask unalias wait
  14. * disown suspend source pushd popd dirs logout times trap cd hash exit
  15. * unset local export readonly set : . let history declare ulimit type
  16. * "special" builtins: break continue eval exec return shift
  17. * external with extra shell behavior: kill pwd time test
  18. * * ? [ # ~ = % [[ ]] function select exit label:
  19. * TODO: case, wildcard +(*|?), job control (find_plus_minus), ${x//}, $(())
  20. * TODO: support case in $() because $(case a in a) ;; ; esac) stops at first )
  21. * TODO: test exit from "trap EXIT" doesn't recurse
  22. * TODO: ! history expansion
  23. * TODO: getuid() vs geteuid()
  24. * TODO: test that $PS1 color changes work without stupid \[ \] hack
  25. * TODO: Handle embedded NUL bytes in the command line? (When/how?)
  26. * TODO: set -e -u -o pipefail, shopt -s nullglob
  27. *
  28. * bash man page:
  29. * control operators || & && ; ;; ;& ;;& ( ) | |& <newline>
  30. * reserved words
  31. * ! case coproc do done elif else esac fi for function if in select
  32. * then until while { } time [[ ]]
  33. *
  34. * Flow control statements:
  35. *
  36. * if/then/elif/else/fi, for select while until/do/done, case/esac,
  37. * {/}, [[/]], (/), function assignment
  38. USE_SH(NEWTOY(cd, ">1LP[-LP]", TOYFLAG_NOFORK))
  39. USE_SH(NEWTOY(declare, "pAailunxr", TOYFLAG_NOFORK))
  40. // TODO tpgfF
  41. USE_SH(NEWTOY(eval, 0, TOYFLAG_NOFORK))
  42. USE_SH(NEWTOY(exec, "^cla:", TOYFLAG_NOFORK))
  43. USE_SH(NEWTOY(exit, 0, TOYFLAG_NOFORK))
  44. USE_SH(NEWTOY(export, "np", TOYFLAG_NOFORK))
  45. USE_SH(NEWTOY(jobs, "lnprs", TOYFLAG_NOFORK))
  46. USE_SH(NEWTOY(set, 0, TOYFLAG_NOFORK))
  47. USE_SH(NEWTOY(shift, ">1", TOYFLAG_NOFORK))
  48. USE_SH(NEWTOY(source, "<1", TOYFLAG_NOFORK))
  49. USE_SH(OLDTOY(., source, TOYFLAG_NOFORK))
  50. USE_SH(NEWTOY(unset, "fvn[!fv]", TOYFLAG_NOFORK))
  51. USE_SH(NEWTOY(wait, "n", TOYFLAG_NOFORK))
  52. USE_SH(NEWTOY(sh, "0(noediting)(noprofile)(norc)sc:i", TOYFLAG_BIN))
  53. USE_SH(OLDTOY(toysh, sh, TOYFLAG_BIN))
  54. USE_SH(OLDTOY(bash, sh, TOYFLAG_BIN))
  55. // Login lies in argv[0], so add some aliases to catch that
  56. USE_SH(OLDTOY(-sh, sh, 0))
  57. USE_SH(OLDTOY(-toysh, sh, 0))
  58. USE_SH(OLDTOY(-bash, sh, 0))
  59. config SH
  60. bool "sh (toysh)"
  61. default n
  62. help
  63. usage: sh [-c command] [script]
  64. Command shell. Runs a shell script, or reads input interactively
  65. and responds to it.
  66. -c command line to execute
  67. -i interactive mode (default when STDIN is a tty)
  68. # These are here for the help text, they're not selectable and control nothing
  69. config CD
  70. bool
  71. default n
  72. depends on SH
  73. help
  74. usage: cd [-PL] [-] [path]
  75. Change current directory. With no arguments, go $HOME. Sets $OLDPWD to
  76. previous directory: cd - to return to $OLDPWD.
  77. -P Physical path: resolve symlinks in path
  78. -L Local path: .. trims directories off $PWD (default)
  79. config DECLARE
  80. bool
  81. default n
  82. depends on SH
  83. help
  84. usage: declare [-pAailunxr] [NAME...]
  85. Set or print variable attributes and values.
  86. -p Print variables instead of setting
  87. -A Associative array
  88. -a Indexed array
  89. -i Integer
  90. -l Lower case
  91. -n Name reference (symlink)
  92. -r Readonly
  93. -u Uppercase
  94. -x Export
  95. config EXIT
  96. bool
  97. default n
  98. depends on SH
  99. help
  100. usage: exit [status]
  101. Exit shell. If no return value supplied on command line, use value
  102. of most recent command, or 0 if none.
  103. config SET
  104. bool
  105. default n
  106. depends on SH
  107. help
  108. usage: set [+a] [+o OPTION] [VAR...]
  109. Set variables and shell attributes. Use + to disable and - to enable.
  110. NAME=VALUE arguments assign to the variable, any leftovers set $1, $2...
  111. With no arguments, prints current variables.
  112. -f NAME is a function
  113. -v NAME is a variable
  114. -n don't follow name reference
  115. OPTIONs:
  116. history - enable command history
  117. config UNSET
  118. bool
  119. default n
  120. depends on SH
  121. help
  122. usage: unset [-fvn] NAME...
  123. -f NAME is a function
  124. -v NAME is a variable
  125. -n dereference NAME and unset that
  126. config EVAL
  127. bool
  128. default n
  129. depends on SH
  130. help
  131. usage: eval COMMAND...
  132. Execute (combined) arguments as a shell command.
  133. config EXEC
  134. bool
  135. default n
  136. depends on SH
  137. help
  138. usage: exec [-cl] [-a NAME] COMMAND...
  139. -a set argv[0] to NAME
  140. -c clear environment
  141. -l prepend - to argv[0]
  142. config EXPORT
  143. bool
  144. default n
  145. depends on SH
  146. help
  147. usage: export [-n] [NAME[=VALUE]...]
  148. Make variables available to child processes. NAME exports existing local
  149. variable(s), NAME=VALUE sets and exports.
  150. -n Unexport. Turn listed variable(s) into local variables.
  151. With no arguments list exported variables/attributes as "declare" statements.
  152. config JOBS
  153. bool
  154. default n
  155. depends on SH
  156. help
  157. usage: jobs [-lnprs] [%JOB | -x COMMAND...]
  158. List running/stopped background jobs.
  159. -l Include process ID in list
  160. -n Show only new/changed processes
  161. -p Show process IDs only
  162. -r Show running processes
  163. -s Show stopped processes
  164. config LOCAL
  165. bool
  166. default n
  167. depends on SH
  168. help
  169. usage: local [NAME[=VALUE]...]
  170. Create a local variable that lasts until return from this function.
  171. With no arguments lists local variables in current function context.
  172. TODO: implement "declare" options.
  173. config SHIFT
  174. bool
  175. default n
  176. depends on SH
  177. help
  178. usage: shift [N]
  179. Skip N (default 1) positional parameters, moving $1 and friends along the list.
  180. Does not affect $0.
  181. config SOURCE
  182. bool
  183. default n
  184. depends on SH
  185. help
  186. usage: source FILE [ARGS...]
  187. Read FILE and execute commands. Any ARGS become positional parameters.
  188. config WAIT
  189. bool
  190. default n
  191. depends on SH
  192. help
  193. usage: wait [-n] [ID...]
  194. Wait for background processes to exit, returning its exit code.
  195. ID can be PID or job, with no IDs waits for all backgrounded processes.
  196. -n Wait for next process to exit
  197. */
  198. #define FOR_sh
  199. #include "toys.h"
  200. GLOBALS(
  201. union {
  202. struct {
  203. char *c;
  204. } sh;
  205. struct {
  206. char *a;
  207. } exec;
  208. };
  209. // keep SECONDS here: used to work around compiler limitation in run_command()
  210. long long SECONDS;
  211. char *isexec, *wcpat;
  212. unsigned options, jobcnt, LINENO;
  213. int hfd, pid, bangpid, varslen, srclvl, recursion;
  214. // Callable function array
  215. struct sh_function {
  216. char *name;
  217. struct sh_pipeline { // pipeline segments: linked list of arg w/metadata
  218. struct sh_pipeline *next, *prev, *end;
  219. int count, here, type, lineno;
  220. struct sh_arg {
  221. char **v;
  222. int c;
  223. } arg[1];
  224. } *pipeline;
  225. unsigned long refcount;
  226. } **functions;
  227. long funcslen;
  228. // runtime function call stack
  229. struct sh_fcall {
  230. struct sh_fcall *next, *prev;
  231. // This dlist in reverse order: TT.ff current function, TT.ff->prev globals
  232. struct sh_vars {
  233. long flags;
  234. char *str;
  235. } *vars;
  236. long varslen, shift;
  237. struct sh_function *func; // TODO wire this up
  238. struct sh_pipeline *pl;
  239. char *ifs;
  240. struct sh_arg arg;
  241. struct arg_list *delete;
  242. // Runtime stack of nested if/else/fi and for/do/done contexts.
  243. struct sh_blockstack {
  244. struct sh_blockstack *next;
  245. struct sh_pipeline *start, *middle;
  246. struct sh_process *pp; // list of processes piping in to us
  247. int run, loop, *urd, pout, pipe;
  248. struct sh_arg farg; // for/select arg stack, case wildcard deck
  249. struct arg_list *fdelete; // farg's cleanup list
  250. char *fvar; // for/select's iteration variable name
  251. } *blk;
  252. } *ff;
  253. // TODO ctrl-Z suspend should stop script
  254. struct sh_process {
  255. struct sh_process *next, *prev; // | && ||
  256. struct arg_list *delete; // expanded strings
  257. // undo redirects, a=b at start, child PID, exit status, has !, job #
  258. int *urd, envlen, pid, exit, flags, job, dash;
  259. long long when; // when job backgrounded/suspended
  260. struct sh_arg *raw, arg;
  261. } *pp; // currently running process
  262. // job list, command line for $*, scratch space for do_wildcard_files()
  263. struct sh_arg jobs, *wcdeck;
  264. )
  265. // Prototype because $($($(blah))) nests, leading to run->parse->run loop
  266. int do_source(char *name, FILE *ff);
  267. // ordered for greedy matching, so >&; becomes >& ; not > &;
  268. // making these const means I need to typecast the const away later to
  269. // avoid endless warnings.
  270. static const char *redirectors[] = {"<<<", "<<-", "<<", "<&", "<>", "<", ">>",
  271. ">&", ">|", ">", "&>>", "&>", 0};
  272. // The order of these has to match the string in set_main()
  273. #define OPT_B 0x100
  274. #define OPT_C 0x200
  275. #define OPT_x 0x400
  276. // only export $PWD and $OLDPWD on first cd
  277. #define OPT_cd 0x80000000
  278. // struct sh_process->flags
  279. #define PFLAG_NOT 1
  280. static void syntax_err(char *s)
  281. {
  282. error_msg("syntax error: %s", s);
  283. toys.exitval = 2;
  284. if (!(TT.options&FLAG_i)) xexit();
  285. }
  286. void debug_show_fds()
  287. {
  288. int x = 0, fd = open("/proc/self/fd", O_RDONLY);
  289. DIR *X = fdopendir(fd);
  290. struct dirent *DE;
  291. char *s, *ss = 0, buf[4096], *sss = buf;
  292. if (!X) return;
  293. for (; (DE = readdir(X));) {
  294. if (atoi(DE->d_name) == fd) continue;
  295. s = xreadlink(ss = xmprintf("/proc/self/fd/%s", DE->d_name));
  296. if (s && *s != '.') sss += sprintf(sss, ", %s=%s"+2*!x++, DE->d_name, s);
  297. free(s); free(ss);
  298. }
  299. *sss = 0;
  300. dprintf(2, "%d fd:%s\n", getpid(), buf);
  301. closedir(X);
  302. }
  303. // append to array with null terminator and realloc as necessary
  304. static void arg_add(struct sh_arg *arg, char *data)
  305. {
  306. // expand with stride 32. Micro-optimization: don't realloc empty stack
  307. if (!(arg->c&31) && (arg->c || !arg->v))
  308. arg->v = xrealloc(arg->v, sizeof(char *)*(arg->c+33));
  309. arg->v[arg->c++] = data;
  310. arg->v[arg->c] = 0;
  311. }
  312. // add argument to an arg_list
  313. static void *push_arg(struct arg_list **list, void *arg)
  314. {
  315. struct arg_list *al;
  316. if (list) {
  317. al = xmalloc(sizeof(struct arg_list));
  318. al->next = *list;
  319. al->arg = arg;
  320. *list = al;
  321. }
  322. return arg;
  323. }
  324. static void arg_add_del(struct sh_arg *arg, char *data,struct arg_list **delete)
  325. {
  326. arg_add(arg, push_arg(delete, data));
  327. }
  328. // Assign one variable from malloced key=val string, returns var struct
  329. // TODO implement remaining types
  330. #define VAR_NOFREE (1<<10)
  331. #define VAR_WHITEOUT (1<<9)
  332. #define VAR_DICT (1<<8)
  333. #define VAR_ARRAY (1<<7)
  334. #define VAR_INT (1<<6)
  335. #define VAR_TOLOWER (1<<5)
  336. #define VAR_TOUPPER (1<<4)
  337. #define VAR_NAMEREF (1<<3)
  338. #define VAR_EXPORT (1<<2)
  339. #define VAR_READONLY (1<<1)
  340. #define VAR_MAGIC (1<<0)
  341. // return length of valid variable name
  342. static char *varend(char *s)
  343. {
  344. if (isdigit(*s)) return s;
  345. while (*s>' ' && (*s=='_' || !ispunct(*s))) s++;
  346. return s;
  347. }
  348. // TODO: this has to handle VAR_NAMEREF, but return dangling symlink
  349. // Also, unset -n, also "local ISLINK" to parent var.
  350. // Return sh_vars * or 0 if not found.
  351. // Sets *pff to function (only if found), only returns whiteouts if pff not NULL
  352. static struct sh_vars *findvar(char *name, struct sh_fcall **pff)
  353. {
  354. int len = varend(name)-name;
  355. struct sh_fcall *ff = TT.ff;
  356. // advance through locals to global context, ignoring whiteouts
  357. if (len) do {
  358. struct sh_vars *var = ff->vars+ff->varslen;
  359. if (var) while (var--!=ff->vars) {
  360. if (strncmp(var->str, name, len) || var->str[len]!='=') continue;
  361. if (pff) *pff = ff;
  362. else if (var->flags&VAR_WHITEOUT) return 0;
  363. return var;
  364. }
  365. } while ((ff = ff->next)!=TT.ff);
  366. return 0;
  367. }
  368. // Append variable to ff->vars, returning *struct. Does not check duplicates.
  369. static struct sh_vars *addvar(char *s, struct sh_fcall *ff)
  370. {
  371. if (!(ff->varslen&31))
  372. ff->vars = xrealloc(ff->vars, (ff->varslen+32)*sizeof(*ff->vars));
  373. if (!s) return ff->vars;
  374. ff->vars[ff->varslen].flags = 0;
  375. ff->vars[ff->varslen].str = s;
  376. return ff->vars+ff->varslen++;
  377. }
  378. static char **nospace(char **ss)
  379. {
  380. while (isspace(**ss)) ++*ss;
  381. return ss;
  382. }
  383. /*
  384. 15L ( [ . -> ++ --
  385. 14R (all prefix operators)
  386. ++ -- + - ! ~ (typecast) * & sizeof
  387. 13L * / %
  388. 12L + -
  389. 11L << >>
  390. 10L < <= > >=
  391. 9L == !=
  392. 8L & (bitwise)
  393. 7L ^ (xor)
  394. 6L |
  395. 5L &&
  396. 4L ||
  397. 3R ? :
  398. 2R (assignments) = += -= *= /= %= &= ^= |= <<= >>=
  399. 1L ,
  400. */
  401. // Recursively calculate string into dd, returns 0 if failed, ss = error point
  402. static int recalculate(long long *dd, char **ss, int lvl)
  403. {
  404. long long ee, ff;
  405. char cc = **nospace(ss);
  406. // TODO: assignable (variable)
  407. // Always start handling unary prefixes, parenthetical blocks, and constants
  408. if (cc=='+' || cc=='-') {
  409. ++*ss;
  410. if (!recalculate(dd, ss, 1)) return 0;
  411. if (cc=='-') *dd = -*dd;
  412. } else if (cc=='(') {
  413. ++*ss;
  414. if (!recalculate(dd, ss, 1)) return 0;
  415. if (**ss!=')') return 0;
  416. else ++*ss;
  417. } else if (isdigit(cc)) *dd = strtoll(*ss, ss, 0); //TODO overflow?
  418. else if (!lvl && (!cc || cc==')')) {
  419. *dd = 0;
  420. return 1;
  421. } else return 0;
  422. // x^y binds first
  423. if (lvl<4) while (strstart(nospace(ss), "**")) {
  424. if (!recalculate(&ee, ss, 4)) return 0;
  425. if (ee<0) perror_msg("** < 0");
  426. for (ff = *dd, *dd = 1; ee; ee--) *dd *= ff;
  427. }
  428. // w*x/y%z bind next
  429. if (lvl<3) while ((cc = **nospace(ss))) {
  430. if (cc=='*' || cc=='/' || cc=='%') {
  431. ++*ss;
  432. if (!recalculate(&ee, ss, 3)) return 0;
  433. if (cc=='*') *dd *= ee;
  434. else if (cc=='%') *dd %= ee;
  435. else if (!ee) {
  436. perror_msg("/0");
  437. return 0;
  438. } else *dd /= ee;
  439. } else break;
  440. }
  441. // x+y-z
  442. if (lvl<2) while ((cc = **nospace(ss))) {
  443. if (cc=='+' || cc=='-') {
  444. ++*ss;
  445. if (!recalculate(&ee, ss, 2)) return 0;
  446. if (cc=='+') *dd += ee;
  447. else *dd -= ee;
  448. } else break;
  449. }
  450. nospace(ss);
  451. return 1;
  452. }
  453. static int calculate(long long *ll, char *equation)
  454. {
  455. char *ss = equation;
  456. // TODO: error_msg->sherror_msg() with LINENO for scripts
  457. if (!recalculate(ll, &ss, 0) || *ss) {
  458. perror_msg("bad math: %s @ %d", equation, (int)(ss-equation));
  459. return 0;
  460. }
  461. return 1;
  462. }
  463. // Return length of utf8 char @s fitting in len, writing value into *cc
  464. int getutf8(char *s, int len, int *cc)
  465. {
  466. unsigned wc;
  467. if (len<0) wc = len = 0;
  468. else if (1>(len = utf8towc(&wc, s, len))) wc = *s, len = 1;
  469. if (cc) *cc = wc;
  470. return len;
  471. }
  472. // get value of variable starting at s.
  473. static char *getvar(char *s)
  474. {
  475. struct sh_vars *var = findvar(s, 0);
  476. if (!var) return 0;
  477. if (var->flags & VAR_MAGIC) {
  478. char c = *var->str;
  479. if (c == 'S') sprintf(toybuf, "%lld", (millitime()-TT.SECONDS)/1000);
  480. else if (c == 'R') sprintf(toybuf, "%ld", random()&((1<<16)-1));
  481. else if (c == 'L') sprintf(toybuf, "%u", TT.ff->pl->lineno);
  482. else if (c == 'G') sprintf(toybuf, "TODO: GROUPS");
  483. else if (c == 'B') sprintf(toybuf, "%d", getpid());
  484. else if (c == 'E') {
  485. struct timespec ts;
  486. clock_gettime(CLOCK_REALTIME, &ts);
  487. sprintf(toybuf, "%lld%c%06ld", (long long)ts.tv_sec, (s[5]=='R')*'.',
  488. ts.tv_nsec/1000);
  489. }
  490. return toybuf;
  491. }
  492. return varend(var->str)+1;
  493. }
  494. // Update $IFS cache in function call stack after variable assignment
  495. static void cache_ifs(char *s, struct sh_fcall *ff)
  496. {
  497. if (!strncmp(s, "IFS=", 4))
  498. do ff->ifs = s+4; while ((ff = ff->next) != TT.ff->prev);
  499. }
  500. // declare -aAilnrux
  501. // ft
  502. // TODO VAR_ARRAY VAR_DICT
  503. // Assign new name=value string for existing variable. s takes x=y or x+=y
  504. static struct sh_vars *setvar_found(char *s, int freeable, struct sh_vars *var)
  505. {
  506. char *ss, *sss, *sd, buf[24];
  507. long ii, jj, kk, flags = var->flags&~VAR_WHITEOUT;
  508. long long ll;
  509. int cc, vlen = varend(s)-s;
  510. if (flags&VAR_READONLY) {
  511. error_msg("%.*s: read only", vlen, s);
  512. goto bad;
  513. }
  514. // If += has no old value (addvar placeholder or empty old var) yank the +
  515. if (s[vlen]=='+' && (var->str==s || !strchr(var->str, '=')[1])) {
  516. ss = xmprintf("%.*s%s", vlen, s, s+vlen+1);
  517. if (var->str==s) {
  518. if (!freeable++) var->flags |= VAR_NOFREE;
  519. } else if (freeable++) free(s);
  520. s = ss;
  521. }
  522. // Handle VAR_NAMEREF mismatch by replacing name
  523. if (strncmp(var->str, s, vlen)) {
  524. ss = s+vlen+(s[vlen]=='+')+1;
  525. ss = xmprintf("%.*s%s", (vlen = varend(var->str)-var->str)+1, var->str, ss);
  526. if (freeable++) free(s);
  527. s = ss;
  528. }
  529. // utf8 aware case conversion, two pass (measure, allocate, convert) because
  530. // unicode IS stupid enough for upper/lower case to be different utf8 byte
  531. // lengths, for example lowercase of U+023a (c8 ba) is U+2c65 (e2 b1 a5)
  532. if (flags&(VAR_TOUPPER|VAR_TOLOWER)) {
  533. for (jj = kk = 0, sss = 0; jj<2; jj++, sss = sd = xmalloc(vlen+kk+2)) {
  534. sd = jj ? stpncpy(sss, s, vlen+1) : (void *)&sss;
  535. for (ss = s+vlen+1; (ii = getutf8(ss, 4, &cc)); ss += ii) {
  536. kk += wctoutf8(sd, (flags&VAR_TOUPPER) ? towupper(cc) : towlower(cc));
  537. if (jj) {
  538. sd += kk;
  539. kk = 0;
  540. }
  541. }
  542. }
  543. *sd = 0;
  544. if (freeable++) free(s);
  545. s = sss;
  546. }
  547. // integer variables treat += differently
  548. ss = s+vlen+(s[vlen]=='+')+1;
  549. if (flags&VAR_INT) {
  550. if (!calculate(&ll, ss)) goto bad;
  551. sprintf(buf, "%lld", ll);
  552. if (flags&VAR_MAGIC) {
  553. if (*s == 'S') {
  554. ll *= 1000;
  555. TT.SECONDS = (s[vlen]=='+') ? TT.SECONDS+ll : millitime()-ll;
  556. } else if (*s == 'R') srandom(ll);
  557. if (freeable) free(s);
  558. // magic can't be whiteout or nofree, and keeps old string
  559. return var;
  560. } else if (s[vlen]=='+' || strcmp(buf, ss)) {
  561. if (s[vlen]=='+') ll += atoll(strchr(var->str, '=')+1);
  562. ss = xmprintf("%.*s=%lld", vlen, s, ll);
  563. if (freeable++) free(s);
  564. s = ss;
  565. }
  566. } else if (s[vlen]=='+' && !(flags&VAR_MAGIC)) {
  567. ss = xmprintf("%s%s", var->str, ss);
  568. if (freeable++) free(s);
  569. s = ss;
  570. }
  571. // Replace old string with new one, adjusting nofree status
  572. if (flags&VAR_NOFREE) flags ^= VAR_NOFREE;
  573. else free(var->str);
  574. if (!freeable) flags |= VAR_NOFREE;
  575. var->str = s;
  576. var->flags = flags;
  577. return var;
  578. bad:
  579. if (freeable) free(s);
  580. return 0;
  581. }
  582. // Creates new variables (local or global) and handles +=
  583. // returns 0 on error, else sh_vars of new entry.
  584. static struct sh_vars *setvar_long(char *s, int freeable, struct sh_fcall *ff)
  585. {
  586. struct sh_vars *vv = 0, *was;
  587. char *ss;
  588. if (!s) return 0;
  589. ss = varend(s);
  590. if (ss[*ss=='+']!='=') {
  591. error_msg("bad setvar %s\n", s);
  592. if (freeable) free(s);
  593. return 0;
  594. }
  595. // Add if necessary, set value, and remove again if we added but set failed
  596. if (!(was = vv = findvar(s, &ff))) (vv = addvar(s, ff))->flags = VAR_NOFREE;
  597. if (!(vv = setvar_found(s, freeable, vv))) {
  598. int ii = vv-ff->vars;
  599. if (!was) memmove(ff->vars+ii, ff->vars+ii+1, (ff->varslen--)-ii);
  600. } else cache_ifs(vv->str, ff);
  601. return vv;
  602. }
  603. // Set variable via a malloced "name=value" (or "name+=value") string.
  604. // Returns sh_vars * or 0 for failure (readonly, etc)
  605. static struct sh_vars *setvar(char *str)
  606. {
  607. return setvar_long(str, 0, TT.ff->prev);
  608. }
  609. // returns whether variable found (whiteout doesn't count)
  610. static int unsetvar(char *name)
  611. {
  612. struct sh_fcall *ff;
  613. struct sh_vars *var = findvar(name, &ff);
  614. int ii = var-ff->vars, len = varend(name)-name;
  615. if (!var || (var->flags&VAR_WHITEOUT)) return 0;
  616. if (var->flags&VAR_READONLY) error_msg("readonly %.*s", len, name);
  617. else {
  618. // turn local into whiteout
  619. if (ff != TT.ff->prev) {
  620. var->flags = VAR_WHITEOUT;
  621. if (!(var->flags&VAR_NOFREE))
  622. (var->str = xrealloc(var->str, len+2))[len+1] = 0;
  623. // free from global context
  624. } else {
  625. if (!(var->flags&VAR_NOFREE)) free(var->str);
  626. memmove(ff->vars+ii, ff->vars+ii+1, (ff->varslen--)-ii);
  627. }
  628. if (!strcmp(name, "IFS"))
  629. do ff->ifs = " \t\n"; while ((ff = ff->next) != TT.ff->prev);
  630. }
  631. return 1;
  632. }
  633. static struct sh_vars *setvarval(char *name, char *val)
  634. {
  635. return setvar(xmprintf("%s=%s", name, val));
  636. }
  637. // TODO: keep variable arrays sorted for binary search
  638. // create array of variables visible in current function.
  639. static struct sh_vars **visible_vars(void)
  640. {
  641. struct sh_arg arg;
  642. struct sh_fcall *ff;
  643. struct sh_vars *vv;
  644. unsigned ii, jj, len;
  645. arg.c = 0;
  646. arg.v = 0;
  647. // Find non-duplicate entries: TODO, sort and binary search
  648. for (ff = TT.ff; ; ff = ff->next) {
  649. if (ff->vars) for (ii = ff->varslen; ii--;) {
  650. vv = ff->vars+ii;
  651. len = 1+(varend(vv->str)-vv->str);
  652. for (jj = 0; ;jj++) {
  653. if (jj == arg.c) arg_add(&arg, (void *)vv);
  654. else if (strncmp(arg.v[jj], vv->str, len)) continue;
  655. break;
  656. }
  657. }
  658. if (ff->next == TT.ff) break;
  659. }
  660. return (void *)arg.v;
  661. }
  662. // malloc declare -x "escaped string"
  663. static char *declarep(struct sh_vars *var)
  664. {
  665. char *types = "rxnuliaA", *esc = "$\"\\`", *in, flags[16], *out = flags, *ss;
  666. int len;
  667. for (len = 0; types[len]; len++) if (var->flags&(2<<len)) *out++ = types[len];
  668. if (out==flags) *out++ = '-';
  669. *out = 0;
  670. len = out-flags;
  671. for (in = var->str; *in; in++) len += !!strchr(esc, *in);
  672. len += in-var->str;
  673. ss = xmalloc(len+15);
  674. len = varend(var->str)-var->str;
  675. out = ss + sprintf(ss, "declare -%s %.*s", flags, len, var->str);
  676. if (var->flags != VAR_MAGIC) {
  677. out = stpcpy(out, "=\"");
  678. for (in = var->str+len+1; *in; *out++ = *in++)
  679. if (strchr(esc, *in)) *out++ = '\\';
  680. *out++ = '"';
  681. }
  682. *out = 0;
  683. return ss;
  684. }
  685. // return length of match found at this point (try is null terminated array)
  686. static int anystart(char *s, char **try)
  687. {
  688. char *ss = s;
  689. while (*try) if (strstart(&s, *try++)) return s-ss;
  690. return 0;
  691. }
  692. // does this entire string match one of the strings in try[]
  693. static int anystr(char *s, char **try)
  694. {
  695. while (*try) if (!strcmp(s, *try++)) return 1;
  696. return 0;
  697. }
  698. // return length of valid prefix that could go before redirect
  699. static int redir_prefix(char *word)
  700. {
  701. char *s = word;
  702. if (*s == '{') {
  703. if (*(s = varend(s+1)) == '}' && s != word+1) s++;
  704. else s = word;
  705. } else while (isdigit(*s)) s++;
  706. return s-word;
  707. }
  708. // parse next word from command line. Returns end, or 0 if need continuation
  709. // caller eats leading spaces. early = skip one quote block (or return start)
  710. // quote is depth of existing quote stack in toybuf (usually 0)
  711. static char *parse_word(char *start, int early, int quote)
  712. {
  713. int ii, qq, qc = 0;
  714. char *end = start, *ss;
  715. // Handle redirections, <(), (( )) that only count at the start of word
  716. ss = end + redir_prefix(end); // 123<<file- parses as 2 args: "123<<" "file-"
  717. if (strstart(&ss, "<(") || strstart(&ss, ">(")) {
  718. toybuf[quote++]=')';
  719. end = ss;
  720. } else if ((ii = anystart(ss, (void *)redirectors))) return ss+ii;
  721. if (strstart(&end, "((")) toybuf[quote++] = 254;
  722. // Loop to find end of this word
  723. while (*end) {
  724. // If we're stopping early and already handled a symbol...
  725. if (early && end!=start && !quote) break;
  726. // barf if we're near overloading quote stack (nesting ridiculously deep)
  727. if (quote>4000) {
  728. syntax_err("bad quote depth");
  729. return (void *)1;
  730. }
  731. // Are we in a quote context?
  732. if ((qq = quote ? toybuf[quote-1] : 0)) {
  733. ii = *end++;
  734. if ((qq==')' || qq>=254) && (ii=='(' || ii==')')) { // parentheses nest
  735. if (ii=='(') qc++;
  736. else if (qc) qc--;
  737. else if (qq>=254) {
  738. // (( can end with )) or retroactively become two (( if we hit one )
  739. if (ii==')' && *end==')') quote--, end++;
  740. else if (qq==254) return start+1;
  741. else if (qq==255) toybuf[quote-1] = ')';
  742. } else if (ii==')') quote--;
  743. } else if (ii==qq) quote--; // matching end quote
  744. else if (qq!='\'') end--, ii = 0; // single quote claims everything
  745. if (ii) continue; // fall through for other quote types
  746. // space and flow control chars only end word when not quoted in any way
  747. } else {
  748. if (isspace(*end)) break;
  749. ss = end + anystart(end, (char *[]){";;&", ";;", ";&", ";", "||",
  750. "|&", "|", "&&", "&", "(", ")", 0});
  751. if (ss!=end) return (end==start) ? ss : end;
  752. }
  753. // start new quote context? (' not special within ")
  754. if (strchr("'\"`"+(qq=='"'), ii = *end++)) toybuf[quote++] = ii;
  755. // \? $() ${} $[] ?() *() +() @() !()
  756. else {
  757. if (ii=='\\') { // TODO why end[1] here? sh -c $'abc\\\ndef' Add test.
  758. if (!*end || (*end=='\n' && !end[1])) return early ? end : 0;
  759. } else if (ii=='$' && -1!=(qq = stridx("({[", *end))) {
  760. if (strstart(&end, "((")) {
  761. end--;
  762. toybuf[quote++] = 255;
  763. } else toybuf[quote++] = ")}]"[qq];
  764. } else if (*end=='(' && strchr("?*+@!", ii)) toybuf[quote++] = ')';
  765. else {
  766. end--;
  767. if (early && !quote) return end;
  768. }
  769. end++;
  770. }
  771. }
  772. return (quote && !early) ? 0 : end;
  773. }
  774. // Return next available high (>=10) file descriptor
  775. static int next_hfd()
  776. {
  777. int hfd;
  778. for (; TT.hfd<=99999; TT.hfd++) if (-1 == fcntl(TT.hfd, F_GETFL)) break;
  779. hfd = TT.hfd;
  780. if (TT.hfd>99999) {
  781. hfd = -1;
  782. if (!errno) errno = EMFILE;
  783. }
  784. return hfd;
  785. }
  786. // Perform a redirect, saving displaced filehandle to a high (>10) fd
  787. // rd is an int array: [0] = count, followed by from/to pairs to restore later.
  788. // If from >= 0 dup from->to after saving to. If from == -1 just save to.
  789. // if from == -2 schedule "to" to be closed by unredirect.
  790. static int save_redirect(int **rd, int from, int to)
  791. {
  792. int cnt, hfd, *rr;
  793. //dprintf(2, "%d redir %d to %d\n", getpid(), from, to);
  794. if (from == to) return 0;
  795. // save displaced to, copying to high (>=10) file descriptor to undo later
  796. // except if we're saving to environment variable instead (don't undo that)
  797. if (from>-2) {
  798. if ((hfd = next_hfd())==-1) return 1;
  799. if (hfd != dup2(to, hfd)) hfd = -1;
  800. else fcntl(hfd, F_SETFD, FD_CLOEXEC);
  801. // dup "to"
  802. if (from >= 0 && to != dup2(from, to)) {
  803. if (hfd >= 0) close(hfd);
  804. return 1;
  805. }
  806. } else {
  807. hfd = to;
  808. to = -1;
  809. }
  810. // Append undo information to redirect list so we can restore saved hfd later.
  811. if (!((cnt = *rd ? **rd : 0)&31)) *rd = xrealloc(*rd, (cnt+33)*2*sizeof(int));
  812. *(rr = *rd) = ++cnt;
  813. rr[2*cnt-1] = hfd;
  814. rr[2*cnt] = to;
  815. return 0;
  816. }
  817. // TODO: waitpid(WNOHANG) to clean up zombies and catch background& ending
  818. static void subshell_callback(char **argv)
  819. {
  820. // This depends on environ having been replaced by caller
  821. environ[1] = xmprintf("@%d,%d", getpid(), getppid());
  822. environ[2] = xmprintf("$=%d", TT.pid);
  823. // TODO: test $$ in (nommu)
  824. }
  825. // TODO what happens when you background a function?
  826. // turn a parsed pipeline back into a string.
  827. static char *pl2str(struct sh_pipeline *pl, int one)
  828. {
  829. struct sh_pipeline *end = 0, *pp;
  830. int len QUIET, i;
  831. char *ss;
  832. // Find end of block (or one argument)
  833. if (one) end = pl->next;
  834. else for (end = pl, len = 0; end; end = end->next)
  835. if (end->type == 1) len++;
  836. else if (end->type == 3 && --len<0) break;
  837. // measure, then allocate
  838. for (ss = 0;; ss = xmalloc(len+1)) {
  839. for (pp = pl; pp != end; pp = pp->next) {
  840. if (pp->type == 'F') continue; // TODO fix this
  841. for (i = len = 0; i<=pp->arg->c; i++)
  842. len += snprintf(ss+len, ss ? INT_MAX : 0, " %s"+!i,
  843. pp->arg->v[i] ? : ";"+(pp->next==end));
  844. }
  845. if (ss) return ss;
  846. }
  847. // TODO test output with case and function
  848. // TODO add HERE documents back in
  849. // TODO handle functions
  850. }
  851. // restore displaced filehandles, closing high filehandles they were copied to
  852. static void unredirect(int *urd)
  853. {
  854. int *rr = urd+1, i;
  855. if (!urd) return;
  856. for (i = 0; i<*urd; i++, rr += 2) if (rr[0] != -1) {
  857. // No idea what to do about fd exhaustion here, so Steinbach's Guideline.
  858. dup2(rr[0], rr[1]);
  859. close(rr[0]);
  860. }
  861. free(urd);
  862. }
  863. static struct sh_blockstack *clear_block(struct sh_blockstack *blk)
  864. {
  865. memset(blk, 0, sizeof(*blk));
  866. blk->start = TT.ff->pl;
  867. blk->run = 1;
  868. blk->pout = -1;
  869. return blk;
  870. }
  871. // when ending a block, free, cleanup redirects and pop stack.
  872. static struct sh_pipeline *pop_block(void)
  873. {
  874. struct sh_pipeline *pl = 0;
  875. struct sh_blockstack *blk = TT.ff->blk;
  876. // when ending a block, free, cleanup redirects and pop stack.
  877. if (blk->pout != -1) close(blk->pout);
  878. unredirect(blk->urd);
  879. llist_traverse(blk->fdelete, llist_free_arg);
  880. free(blk->farg.v);
  881. if (TT.ff->blk->next) {
  882. pl = blk->start->end;
  883. free(llist_pop(&TT.ff->blk));
  884. } else clear_block(blk);
  885. return pl;
  886. }
  887. // Push a new empty block to the stack
  888. static void add_block(void)
  889. {
  890. struct sh_blockstack *blk = clear_block(xmalloc(sizeof(*blk)));
  891. blk->next = TT.ff->blk;
  892. TT.ff->blk = blk;
  893. }
  894. // Add entry to runtime function call stack
  895. static void call_function(void)
  896. {
  897. // dlist in reverse order: TT.ff = current function, TT.ff->prev = globals
  898. dlist_add_nomalloc((void *)&TT.ff, xzalloc(sizeof(struct sh_fcall)));
  899. TT.ff = TT.ff->prev;
  900. add_block();
  901. // TODO caller needs to set pl, vars, func
  902. // default $* is to copy previous
  903. TT.ff->arg.v = TT.ff->next->arg.v;
  904. TT.ff->arg.c = TT.ff->next->arg.c;
  905. TT.ff->ifs = TT.ff->next->ifs;
  906. }
  907. // functions contain pipelines contain functions: prototype because loop
  908. static void free_pipeline(void *pipeline);
  909. static void free_function(struct sh_function *funky)
  910. {
  911. if (--funky->refcount) return;
  912. free(funky->name);
  913. llist_traverse(funky->pipeline, free_pipeline);
  914. free(funky);
  915. }
  916. // TODO: old function-vs-source definition is "has variables", but no ff->func?
  917. // returns 0 if source popped, nonzero if function popped
  918. static int end_function(int funconly)
  919. {
  920. struct sh_fcall *ff = TT.ff;
  921. int func = ff->next!=ff && ff->vars;
  922. if (!func && funconly) return 0;
  923. llist_traverse(ff->delete, llist_free_arg);
  924. ff->delete = 0;
  925. while (TT.ff->blk->next) pop_block();
  926. pop_block();
  927. // for a function, free variables and pop context
  928. if (!func) return 0;
  929. while (ff->varslen)
  930. if (!(ff->vars[--ff->varslen].flags&VAR_NOFREE))
  931. free(ff->vars[ff->varslen].str);
  932. free(ff->vars);
  933. free(TT.ff->blk);
  934. if (ff->func) free_function(ff->func);
  935. free(dlist_pop(&TT.ff));
  936. return 1;
  937. }
  938. // TODO check every caller of run_subshell for error, or syntax_error() here
  939. // from pipe() failure
  940. // TODO need CLOFORK? CLOEXEC doesn't help if we don't exec...
  941. // Pass environment and command string to child shell, return PID of child
  942. static int run_subshell(char *str, int len)
  943. {
  944. pid_t pid;
  945. //dprintf(2, "%d run_subshell %.*s\n", getpid(), len, str); debug_show_fds();
  946. // The with-mmu path is significantly faster.
  947. if (CFG_TOYBOX_FORK) {
  948. if ((pid = fork())<0) perror_msg("fork");
  949. else if (!pid) {
  950. call_function();
  951. if (str) {
  952. do_source(0, fmemopen(str, len, "r"));
  953. _exit(toys.exitval);
  954. }
  955. }
  956. // On nommu vfork, exec /proc/self/exe, and pipe state data to ourselves.
  957. } else {
  958. int pipes[2];
  959. unsigned i;
  960. char **oldenv = environ, *ss = str ? : pl2str(TT.ff->pl->next, 0);
  961. struct sh_vars **vv;
  962. // open pipe to child
  963. if (pipe(pipes) || 254 != dup2(pipes[0], 254)) return 1;
  964. close(pipes[0]);
  965. fcntl(pipes[1], F_SETFD, FD_CLOEXEC);
  966. // vfork child with clean environment
  967. environ = xzalloc(4*sizeof(char *));
  968. *environ = getvar("PATH") ? : "PATH=";
  969. pid = xpopen_setup(0, 0, subshell_callback);
  970. // TODO what if pid -1? Handle process exhaustion.
  971. // free entries added to end of environment by callback (shared heap)
  972. free(environ[1]);
  973. free(environ[2]);
  974. free(environ);
  975. environ = oldenv;
  976. // marshall context to child
  977. close(254);
  978. dprintf(pipes[1], "%lld %u %u %u %u\n", TT.SECONDS,
  979. TT.options, TT.LINENO, TT.pid, TT.bangpid);
  980. for (i = 0, vv = visible_vars(); vv[i]; i++)
  981. dprintf(pipes[1], "%u %lu\n%.*s", (unsigned)strlen(vv[i]->str),
  982. vv[i]->flags, (int)strlen(vv[i]->str), vv[i]->str);
  983. free(vv);
  984. // send command
  985. dprintf(pipes[1], "0 0\n%.*s\n", len, ss);
  986. if (!str) free(ss);
  987. close(pipes[1]);
  988. }
  989. return pid;
  990. }
  991. // Call subshell with either stdin/stdout redirected, return other end of pipe
  992. static int pipe_subshell(char *s, int len, int out)
  993. {
  994. int pipes[2], *uu = 0, in = !out;
  995. // Grab subshell data
  996. if (pipe(pipes)) {
  997. perror_msg("%.*s", len, s);
  998. return -1;
  999. }
  1000. // Perform input or output redirect and launch process (ignoring errors)
  1001. save_redirect(&uu, pipes[in], in);
  1002. close(pipes[in]);
  1003. fcntl(pipes[!in], F_SETFD, FD_CLOEXEC);
  1004. run_subshell(s, len);
  1005. fcntl(pipes[!in], F_SETFD, 0);
  1006. unredirect(uu);
  1007. return pipes[out];
  1008. }
  1009. // utf8 strchr: return wide char matched at wc from chrs, or 0 if not matched
  1010. // if len, save length of next wc (whether or not it's in list)
  1011. static int utf8chr(char *wc, char *chrs, int *len)
  1012. {
  1013. unsigned wc1, wc2;
  1014. int ll;
  1015. if (len) *len = 1;
  1016. if (!*wc) return 0;
  1017. if (0<(ll = utf8towc(&wc1, wc, 99))) {
  1018. if (len) *len = ll;
  1019. while (*chrs) {
  1020. if(1>(ll = utf8towc(&wc2, chrs, 99))) chrs++;
  1021. else {
  1022. if (wc1 == wc2) return wc1;
  1023. chrs += ll;
  1024. }
  1025. }
  1026. }
  1027. return 0;
  1028. }
  1029. // grab variable or special param (ala $$) up to len bytes. Return value.
  1030. // set *used to length consumed. Does not handle $* and $@
  1031. char *getvar_special(char *str, int len, int *used, struct arg_list **delete)
  1032. {
  1033. char *s = 0, *ss, cc = *str;
  1034. unsigned uu;
  1035. *used = 1;
  1036. if (cc == '-') {
  1037. s = ss = xmalloc(8);
  1038. if (TT.options&FLAG_i) *ss++ = 'i';
  1039. if (TT.options&OPT_B) *ss++ = 'B';
  1040. if (TT.options&FLAG_s) *ss++ = 's';
  1041. if (TT.options&FLAG_c) *ss++ = 'c';
  1042. *ss = 0;
  1043. } else if (cc == '?') s = xmprintf("%d", toys.exitval);
  1044. else if (cc == '$') s = xmprintf("%d", TT.pid);
  1045. else if (cc == '#') s = xmprintf("%d", TT.ff->arg.c ? TT.ff->arg.c-1 : 0);
  1046. else if (cc == '!') s = xmprintf("%d"+2*!TT.bangpid, TT.bangpid);
  1047. else {
  1048. delete = 0;
  1049. for (*used = uu = 0; *used<len && isdigit(str[*used]); ++*used)
  1050. uu = (10*uu)+str[*used]-'0';
  1051. if (*used) {
  1052. if (uu) uu += TT.ff->shift;
  1053. if (uu<TT.ff->arg.c) s = TT.ff->arg.v[uu];
  1054. } else if ((*used = varend(str)-str)) return getvar(str);
  1055. }
  1056. if (s) push_arg(delete, s);
  1057. return s;
  1058. }
  1059. #define WILD_SHORT 1 // else longest match
  1060. #define WILD_CASE 2 // case insensitive
  1061. #define WILD_ANY 4 // advance through pattern instead of str
  1062. // Returns length of str matched by pattern, or -1 if not all pattern consumed
  1063. static int wildcard_matchlen(char *str, int len, char *pattern, int plen,
  1064. struct sh_arg *deck, int flags)
  1065. {
  1066. struct sh_arg ant = {0}; // stack: of str offsets
  1067. long ss, pp, dd, best = -1;
  1068. int i, j, c, not;
  1069. // Loop through wildcards in pattern.
  1070. for (ss = pp = dd = 0; ;) {
  1071. if ((flags&WILD_ANY) && best!=-1) break;
  1072. // did we consume pattern?
  1073. if (pp==plen) {
  1074. if (ss>best) best = ss;
  1075. if (ss==len || (flags&WILD_SHORT)) break;
  1076. // attempt literal match?
  1077. } else if (dd>=deck->c || pp!=(long)deck->v[dd]) {
  1078. if (ss<len) {
  1079. if (flags&WILD_CASE) {
  1080. ss += getutf8(str+ss, len-ss, &c);
  1081. c = towupper(c);
  1082. pp += getutf8(pattern+pp, pp-plen, &i);
  1083. i = towupper(i);
  1084. } else c = str[ss++], i = pattern[pp++];
  1085. if (c==i) continue;
  1086. }
  1087. // Wildcard chars: |+@!*?()[]
  1088. } else {
  1089. c = pattern[pp++];
  1090. dd++;
  1091. if (c=='?' || ((flags&WILD_ANY) && c=='*')) {
  1092. ss += (i = getutf8(str+ss, len-ss, 0));
  1093. if (i) continue;
  1094. } else if (c=='*') {
  1095. // start with zero length match, don't record consecutive **
  1096. if (dd==1 || pp-2!=(long)deck->v[dd-1] || pattern[pp-2]!='*') {
  1097. arg_add(&ant, (void *)ss);
  1098. arg_add(&ant, 0);
  1099. }
  1100. continue;
  1101. } else if (c == '[') {
  1102. pp += (not = !!strchr("!^", pattern[pp]));
  1103. ss += getutf8(str+ss, len-ss, &c);
  1104. for (i = 0; pp<(long)deck->v[dd]; i = 0) {
  1105. pp += getutf8(pattern+pp, plen-pp, &i);
  1106. if (pattern[pp]=='-') {
  1107. ++pp;
  1108. pp += getutf8(pattern+pp, plen-pp, &j);
  1109. if (not^(i<=c && j>=c)) break;
  1110. } else if (not^(i==c)) break;
  1111. }
  1112. if (i) {
  1113. pp = 1+(long)deck->v[dd++];
  1114. continue;
  1115. }
  1116. // ( preceded by +@!*?
  1117. } else { // TODO ( ) |
  1118. dd++;
  1119. continue;
  1120. }
  1121. }
  1122. // match failure
  1123. if (flags&WILD_ANY) {
  1124. ss = 0;
  1125. if (plen==pp) break;
  1126. continue;
  1127. }
  1128. // pop retry stack or return failure (TODO: seek to next | in paren)
  1129. while (ant.c) {
  1130. if ((c = pattern[(long)deck->v[--dd]])=='*') {
  1131. if (len<(ss = (long)ant.v[ant.c-2]+(long)++ant.v[ant.c-1])) ant.c -= 2;
  1132. else {
  1133. pp = (long)deck->v[dd++]+1;
  1134. break;
  1135. }
  1136. } else if (c == '(') dprintf(2, "TODO: (");
  1137. }
  1138. if (!ant.c) break;
  1139. }
  1140. free (ant.v);
  1141. return best;
  1142. }
  1143. static int wildcard_match(char *s, char *p, struct sh_arg *deck, int flags)
  1144. {
  1145. return wildcard_matchlen(s, strlen(s), p, strlen(p), deck, flags);
  1146. }
  1147. // TODO: test that * matches ""
  1148. // skip to next slash in wildcard path, passing count active ranges.
  1149. // start at pattern[off] and deck[*idx], return pattern pos and update *idx
  1150. char *wildcard_path(char *pattern, int off, struct sh_arg *deck, int *idx,
  1151. int count)
  1152. {
  1153. char *p, *old;
  1154. int i = 0, j = 0;
  1155. // Skip [] and nested () ranges within deck until / or NUL
  1156. for (p = old = pattern+off;; p++) {
  1157. if (!*p) return p;
  1158. while (*p=='/') {
  1159. old = p++;
  1160. if (j && !count) return old;
  1161. j = 0;
  1162. }
  1163. // Got wildcard? Return if start of name if out of count, else skip [] ()
  1164. if (*idx<deck->c && p-pattern == (long)deck->v[*idx]) {
  1165. if (!j++ && !count--) return old;
  1166. ++*idx;
  1167. if (*p=='[') p = pattern+(long)deck->v[(*idx)++];
  1168. else if (*p=='(') while (*++p) if (p-pattern == (long)deck->v[*idx]) {
  1169. ++*idx;
  1170. if (*p == ')') {
  1171. if (!i) break;
  1172. i--;
  1173. } else if (*p == '(') i++;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. // TODO ** means this directory as well as ones below it, shopt -s globstar
  1179. // Filesystem traversal callback
  1180. // pass on: filename, portion of deck, portion of pattern,
  1181. // input: pattern+offset, deck+offset. Need to update offsets.
  1182. int do_wildcard_files(struct dirtree *node)
  1183. {
  1184. struct dirtree *nn;
  1185. char *pattern, *patend;
  1186. int lvl, ll = 0, ii = 0, rc;
  1187. struct sh_arg ant;
  1188. // Top level entry has no pattern in it
  1189. if (!node->parent) return DIRTREE_RECURSE;
  1190. // Find active pattern range
  1191. for (nn = node->parent; nn; nn = nn->parent) if (nn->parent) ii++;
  1192. pattern = wildcard_path(TT.wcpat, 0, TT.wcdeck, &ll, ii);
  1193. while (*pattern=='/') pattern++;
  1194. lvl = ll;
  1195. patend = wildcard_path(TT.wcpat, pattern-TT.wcpat, TT.wcdeck, &ll, 1);
  1196. // Don't include . entries unless explicitly asked for them
  1197. if (*node->name=='.' && *pattern!='.') return 0;
  1198. // Don't descend into non-directory (was called with DIRTREE_SYMFOLLOW)
  1199. if (*patend && !S_ISDIR(node->st.st_mode) && *node->name) return 0;
  1200. // match this filename from pattern to p in deck from lvl to ll
  1201. ant.c = ll-lvl;
  1202. ant.v = TT.wcdeck->v+lvl;
  1203. for (ii = 0; ii<ant.c; ii++) TT.wcdeck->v[lvl+ii] -= pattern-TT.wcpat;
  1204. rc = wildcard_matchlen(node->name, strlen(node->name), pattern,
  1205. patend-pattern, &ant, 0);
  1206. for (ii = 0; ii<ant.c; ii++) TT.wcdeck->v[lvl+ii] += pattern-TT.wcpat;
  1207. // Return failure or save exact match.
  1208. if (rc<0 || node->name[rc]) return 0;
  1209. if (!*patend) return DIRTREE_SAVE;
  1210. // Are there more wildcards to test children against?
  1211. if (TT.wcdeck->c!=ll) return DIRTREE_RECURSE;
  1212. // No more wildcards: check for child and return failure if it isn't there.
  1213. pattern = xmprintf("%s%s", node->name, patend);
  1214. rc = faccessat(dirtree_parentfd(node), pattern, F_OK, AT_SYMLINK_NOFOLLOW);
  1215. free(pattern);
  1216. if (rc) return 0;
  1217. // Save child and self. (Child could be trailing / but only one saved.)
  1218. while (*patend=='/' && patend[1]) patend++;
  1219. node->child = xzalloc(sizeof(struct dirtree)+1+strlen(patend));
  1220. node->child->parent = node;
  1221. strcpy(node->child->name, patend);
  1222. return DIRTREE_SAVE;
  1223. }
  1224. // Record active wildcard chars in output string
  1225. // *new start of string, oo offset into string, deck is found wildcards,
  1226. static void collect_wildcards(char *new, long oo, struct sh_arg *deck)
  1227. {
  1228. long bracket, *vv;
  1229. char cc = new[oo];
  1230. // Record unescaped/unquoted wildcard metadata for later processing
  1231. if (!deck->c) arg_add(deck, 0);
  1232. vv = (long *)deck->v;
  1233. // vv[0] used for paren level (bottom 16 bits) + bracket start offset<<16
  1234. // at end loop backwards through live wildcards to remove pending unmatched (
  1235. if (!cc) {
  1236. long ii = 0, jj = 65535&*vv, kk;
  1237. for (kk = deck->c; jj;) {
  1238. if (')' == (cc = new[vv[--kk]])) ii++;
  1239. else if ('(' == cc) {
  1240. if (ii) ii--;
  1241. else {
  1242. memmove(vv+kk, vv+kk+1, sizeof(long)*(deck->c-- -kk));
  1243. jj--;
  1244. }
  1245. }
  1246. }
  1247. if (deck->c) memmove(vv, vv+1, sizeof(long)*deck->c--);
  1248. return;
  1249. }
  1250. // Start +( range, or remove first char that isn't wildcard without (
  1251. if (deck->c>1 && vv[deck->c-1] == oo-1 && strchr("+@!*?", new[oo-1])) {
  1252. if (cc == '(') {
  1253. vv[deck->c-1] = oo;
  1254. return;
  1255. } else if (!strchr("*?", new[oo-1])) deck->c--;
  1256. }
  1257. // fall through to add wildcard, popping parentheses stack as necessary
  1258. if (strchr("|+@!*?", cc));
  1259. else if (cc == ')' && (65535&*vv)) --*vv;
  1260. // complete [range], discard wildcards within, add [, fall through to add ]
  1261. else if (cc == ']' && (bracket = *vv>>16)) {
  1262. // don't end range yet for [] or [^]
  1263. if (bracket+1 == oo || (bracket+2 == oo && strchr("!^", new[oo-1]))) return;
  1264. while (deck->c>1 && vv[deck->c-1]>=bracket) deck->c--;
  1265. *vv &= 65535;
  1266. arg_add(deck, (void *)bracket);
  1267. // Not a wildcard
  1268. } else {
  1269. // [ is speculative, don't add to deck yet, just record we saw it
  1270. if (cc == '[' && !(*vv>>16)) *vv = (oo<<16)+(65535&*vv);
  1271. return;
  1272. }
  1273. // add active wildcard location
  1274. arg_add(deck, (void *)oo);
  1275. }
  1276. // wildcard expand data against filesystem, and add results to arg list
  1277. // Note: this wildcard deck has extra argument at start (leftover from parsing)
  1278. static void wildcard_add_files(struct sh_arg *arg, char *pattern,
  1279. struct sh_arg *deck, struct arg_list **delete)
  1280. {
  1281. struct dirtree *dt;
  1282. char *pp;
  1283. int ll = 0;
  1284. // fast path: when no wildcards, add pattern verbatim
  1285. collect_wildcards("", 0, deck);
  1286. if (!deck->c) return arg_add(arg, pattern);
  1287. // Traverse starting with leading patternless path.
  1288. pp = wildcard_path(TT.wcpat = pattern, 0, TT.wcdeck = deck, &ll, 0);
  1289. pp = (pp==pattern) ? 0 : xstrndup(pattern, pp-pattern);
  1290. dt = dirtree_flagread(pp, DIRTREE_STATLESS|DIRTREE_SYMFOLLOW,
  1291. do_wildcard_files);
  1292. free(pp);
  1293. deck->c = 0;
  1294. // If no match save pattern, else free tree saving each path found.
  1295. if (!dt) return arg_add(arg, pattern);
  1296. while (dt) {
  1297. while (dt->child) dt = dt->child;
  1298. arg_add(arg, push_arg(delete, dirtree_path(dt, 0)));
  1299. do {
  1300. pp = (void *)dt;
  1301. if ((dt = dt->parent)) dt->child = dt->child->next;
  1302. free(pp);
  1303. } while (dt && !dt->child);
  1304. }
  1305. // TODO: test .*/../
  1306. }
  1307. // Copy string until } including escaped }
  1308. // if deck collect wildcards, and store terminator at deck->v[deck->c]
  1309. char *slashcopy(char *s, char *c, struct sh_arg *deck)
  1310. {
  1311. char *ss;
  1312. long ii, jj;
  1313. for (ii = 0; !strchr(c, s[ii]); ii++) if (s[ii] == '\\') ii++;
  1314. ss = xmalloc(ii+1);
  1315. for (ii = jj = 0; !strchr(c, s[jj]); ii++)
  1316. if ('\\'==(ss[ii] = s[jj++])) ss[ii] = s[jj++];
  1317. else if (deck) collect_wildcards(ss, ii, deck);
  1318. ss[ii] = 0;
  1319. if (deck) {
  1320. arg_add(deck, 0);
  1321. deck->v[--deck->c] = (void *)jj;
  1322. collect_wildcards("", 0, deck);
  1323. }
  1324. return ss;
  1325. }
  1326. #define NO_QUOTE (1<<0) // quote removal
  1327. #define NO_PATH (1<<1) // path expansion (wildcards)
  1328. #define NO_SPLIT (1<<2) // word splitting
  1329. #define NO_BRACE (1<<3) // {brace,expansion}
  1330. #define NO_TILDE (1<<4) // ~username/path
  1331. #define NO_NULL (1<<5) // Expand to "" instead of NULL
  1332. #define SEMI_IFS (1<<6) // Use ' ' instead of IFS to combine $*
  1333. // expand str appending to arg using above flag defines, add mallocs to delete
  1334. // if ant not null, save wildcard deck there instead of expanding vs filesystem
  1335. // returns 0 for success, 1 for error
  1336. static int expand_arg_nobrace(struct sh_arg *arg, char *str, unsigned flags,
  1337. struct arg_list **delete, struct sh_arg *ant)
  1338. {
  1339. char cc, qq = flags&NO_QUOTE, sep[6], *new = str, *s, *ss = ss, *ifs, *slice;
  1340. int ii = 0, oo = 0, xx, yy, dd, jj, kk, ll, mm;
  1341. struct sh_arg deck = {0};
  1342. // Tilde expansion
  1343. if (!(flags&NO_TILDE) && *str == '~') {
  1344. struct passwd *pw = 0;
  1345. ss = 0;
  1346. while (str[ii] && str[ii]!=':' && str[ii]!='/') ii++;
  1347. if (ii==1) {
  1348. if (!(ss = getvar("HOME")) || !*ss) pw = bufgetpwuid(getuid());
  1349. } else {
  1350. // TODO bufgetpwnam
  1351. pw = getpwnam(s = xstrndup(str+1, ii-1));
  1352. free(s);
  1353. }
  1354. if (pw) {
  1355. ss = pw->pw_dir;
  1356. if (!ss || !*ss) ss = "/";
  1357. }
  1358. if (ss) {
  1359. oo = strlen(ss);
  1360. s = xmprintf("%s%s", ss, str+ii);
  1361. if (str != new) free(new);
  1362. new = s;
  1363. }
  1364. }
  1365. // parameter/variable expansion and dequoting
  1366. if (!ant) ant = &deck;
  1367. for (; (cc = str[ii++]); str!=new && (new[oo] = 0)) {
  1368. struct sh_arg aa = {0};
  1369. int nosplit = 0;
  1370. // skip literal chars
  1371. if (!strchr("'\"\\$`"+2*(flags&NO_QUOTE), cc)) {
  1372. if (str != new) new[oo] = cc;
  1373. if (!(flags&NO_PATH) && !(qq&1)) collect_wildcards(new, oo, ant);
  1374. oo++;
  1375. continue;
  1376. }
  1377. // allocate snapshot if we just started modifying
  1378. if (str == new) {
  1379. new = xstrdup(new);
  1380. new[oo] = 0;
  1381. }
  1382. ifs = slice = 0;
  1383. // handle escapes and quoting
  1384. if (cc == '\\') {
  1385. if (!(qq&1) || (str[ii] && strchr("\"\\$`", str[ii])))
  1386. new[oo++] = str[ii] ? str[ii++] : cc;
  1387. } else if (cc == '"') qq++;
  1388. else if (cc == '\'') {
  1389. if (qq&1) new[oo++] = cc;
  1390. else {
  1391. qq += 2;
  1392. while ((cc = str[ii++]) != '\'') new[oo++] = cc;
  1393. }
  1394. // both types of subshell work the same, so do $( here not in '$' below
  1395. // TODO $((echo hello) | cat) ala $(( becomes $( ( retroactively
  1396. } else if (cc == '`' || (cc == '$' && str[ii] && strchr("([", str[ii]))) {
  1397. off_t pp = 0;
  1398. s = str+ii-1;
  1399. kk = parse_word(s, 1, 0)-s;
  1400. if (str[ii] == '[' || *toybuf == 255) {
  1401. struct sh_arg aa = {0};
  1402. long long ll;
  1403. // Expand $VARS in math string
  1404. ss = str+ii+1+(str[ii]=='(');
  1405. push_arg(delete, ss = xstrndup(ss, kk - (3+2*(str[ii]!='['))));
  1406. expand_arg_nobrace(&aa, ss, NO_PATH|NO_SPLIT, delete, 0);
  1407. s = ss = (aa.v && *aa.v) ? *aa.v : "";
  1408. free(aa.v);
  1409. // Recursively calculate result
  1410. if (!recalculate(&ll, &s, 0) || *s) {
  1411. error_msg("bad math: %s @ %ld", ss, (s-ss)+1);
  1412. goto fail;
  1413. }
  1414. ii += kk-1;
  1415. push_arg(delete, ifs = xmprintf("%lld", ll));
  1416. } else {
  1417. // Run subshell and trim trailing newlines
  1418. s += (jj = 1+(cc == '$'));
  1419. ii += --kk;
  1420. kk -= jj;
  1421. // Special case echo $(<input)
  1422. for (ss = s; isspace(*ss); ss++);
  1423. if (*ss != '<') ss = 0;
  1424. else {
  1425. while (isspace(*++ss));
  1426. if (!(ll = parse_word(ss, 0, 0)-ss)) ss = 0;
  1427. else {
  1428. jj = ll+(ss-s);
  1429. while (isspace(s[jj])) jj++;
  1430. if (jj != kk) ss = 0;
  1431. else {
  1432. jj = xcreate_stdio(ss = xstrndup(ss, ll), O_RDONLY|WARN_ONLY, 0);
  1433. free(ss);
  1434. }
  1435. }
  1436. }
  1437. // TODO what does \ in `` mean? What is echo `printf %s \$x` supposed to do?
  1438. // This has to be async so pipe buffer doesn't fill up
  1439. if (!ss) jj = pipe_subshell(s, kk, 0);
  1440. if ((ifs = readfd(jj, 0, &pp)))
  1441. for (kk = strlen(ifs); kk && ifs[kk-1]=='\n'; ifs[--kk] = 0);
  1442. close(jj);
  1443. }
  1444. // $VARIABLE expansions
  1445. } else if (cc == '$') {
  1446. cc = *(ss = str+ii++);
  1447. if (cc=='\'') {
  1448. for (s = str+ii; *s != '\''; oo += wcrtomb(new+oo, unescape2(&s, 0),0));
  1449. ii = s-str+1;
  1450. continue;
  1451. } else if (cc=='"' && !(qq&1)) {
  1452. qq++;
  1453. continue;
  1454. } else if (cc == '{') {
  1455. // Skip escapes to find }, parse_word() guarantees ${} terminates
  1456. for (cc = *++ss; str[ii] != '}'; ii++) if (str[ii]=='\\') ii++;
  1457. ii++;
  1458. if (cc == '}') ifs = (void *)1;
  1459. else if (strchr("#!", cc)) ss++;
  1460. if (!(jj = varend(ss)-ss)) while (isdigit(ss[jj])) jj++;
  1461. if (!jj && strchr("#$_*", *ss)) jj++;
  1462. // parameter or operator? Maybe not a prefix: ${#-} vs ${#-x}
  1463. if (!jj && strchr("-?@", *ss)) if (ss[++jj]!='}' && ss[-1]!='{') ss--;
  1464. slice = ss+jj; // start of :operation
  1465. if (!jj) {
  1466. // literal ${#} or ${!} wasn't a prefix
  1467. if (strchr("#!", cc)) ifs = getvar_special(--ss, 1, &kk, delete);
  1468. else ifs = (void *)1; // unrecognized char ala ${~}
  1469. } else if (ss[-1]=='{'); // not prefix, fall through
  1470. else if (cc == '#') { // TODO ${#x[@]}
  1471. dd = !!strchr("@*", *ss); // For ${#@} or ${#*} do normal ${#}
  1472. ifs = getvar_special(ss-dd, jj, &kk, delete) ? : "";
  1473. if (!dd) push_arg(delete, ifs = xmprintf("%zu", strlen(ifs)));
  1474. // ${!@} ${!@Q} ${!x} ${!x@} ${!x@Q} ${!x#} ${!x[} ${!x[*]}
  1475. } else if (cc == '!') { // TODO: ${var[@]} array
  1476. // special case: normal varname followed by @} or *} = prefix list
  1477. if (ss[jj] == '*' || (ss[jj] == '@' && !isalpha(ss[jj+1]))) {
  1478. struct sh_vars **vv = visible_vars();
  1479. for (slice++, kk = 0; vv[kk]; kk++) {
  1480. if (vv[kk]->flags&VAR_WHITEOUT) continue;
  1481. if (!strncmp(s = vv[kk]->str, ss, jj))
  1482. arg_add(&aa, push_arg(delete, s = xstrndup(s, stridx(s, '='))));
  1483. }
  1484. if (aa.c) push_arg(delete, aa.v);
  1485. free(vv);
  1486. // else dereference to get new varname, discarding if none, check err
  1487. } else {
  1488. // First expansion
  1489. if (strchr("@*", *ss)) { // special case ${!*}/${!@}
  1490. expand_arg_nobrace(&aa, "\"$*\"", NO_PATH|NO_SPLIT, delete, 0);
  1491. ifs = *aa.v;
  1492. free(aa.v);
  1493. memset(&aa, 0, sizeof(aa));
  1494. jj = 1;
  1495. } else ifs = getvar_special(ss, jj, &jj, delete);
  1496. slice = ss+jj;
  1497. // Second expansion
  1498. if (!jj) ifs = (void *)1;
  1499. else if (ifs && *(ss = ifs)) {
  1500. if (strchr("@*", cc)) {
  1501. aa.c = TT.ff->arg.c-1;
  1502. aa.v = TT.ff->arg.v+1;
  1503. jj = 1;
  1504. } else ifs = getvar_special(ifs, strlen(ifs), &jj, delete);
  1505. if (ss && ss[jj]) {
  1506. ifs = (void *)1;
  1507. slice = ss+strlen(ss);
  1508. }
  1509. }
  1510. }
  1511. }
  1512. // Substitution error?
  1513. if (ifs == (void *)1) {
  1514. barf:
  1515. if (!(((unsigned long)ifs)>>1)) ifs = "bad substitution";
  1516. error_msg("%.*s: %s", (int)(slice-ss), ss, ifs);
  1517. goto fail;
  1518. }
  1519. } else jj = 1;
  1520. // Resolve unprefixed variables
  1521. if (strchr("{$", ss[-1])) {
  1522. if (strchr("@*", cc)) {
  1523. aa.c = TT.ff->arg.c-1;
  1524. aa.v = TT.ff->arg.v+1;
  1525. } else {
  1526. ifs = getvar_special(ss, jj, &jj, delete);
  1527. if (!jj) {
  1528. if (ss[-1] == '{') goto barf;
  1529. new[oo++] = '$';
  1530. ii--;
  1531. continue;
  1532. } else if (ss[-1] != '{') ii += jj-1;
  1533. }
  1534. }
  1535. }
  1536. // combine before/ifs/after sections & split words on $IFS in ifs
  1537. // keep oo bytes of str before (already parsed)
  1538. // insert ifs (active for wildcards+splitting)
  1539. // keep str+ii after (still to parse)
  1540. // Fetch separator to glue string back together with
  1541. *sep = 0;
  1542. if (((qq&1) && cc=='*') || (flags&NO_SPLIT)) {
  1543. unsigned wc;
  1544. nosplit++;
  1545. if (flags&SEMI_IFS) strcpy(sep, " ");
  1546. // TODO what if separator is bigger? Need to grab 1 column of combining chars
  1547. else if (0<(dd = utf8towc(&wc, TT.ff->ifs, 4)))
  1548. sprintf(sep, "%.*s", dd, TT.ff->ifs);
  1549. }
  1550. // when aa proceed through entries until NULL, else process ifs once
  1551. mm = yy = 0;
  1552. do {
  1553. // get next argument
  1554. if (aa.c) ifs = aa.v[mm++] ? : "";
  1555. // Are we performing surgery on this argument?
  1556. if (slice && *slice != '}') {
  1557. dd = slice[xx = (*slice == ':')];
  1558. if (!ifs || (xx && !*ifs)) {
  1559. if (strchr("-?=", dd)) { // - use default = assign default ? error
  1560. push_arg(delete, ifs = slashcopy(slice+xx+1, "}", 0));
  1561. if (dd == '?' || (dd == '=' &&
  1562. !(setvar(s = xmprintf("%.*s=%s", (int)(slice-ss), ss, ifs)))))
  1563. goto barf; // TODO ? exits past "source" boundary
  1564. }
  1565. } else if (dd == '-'); // NOP when ifs not empty
  1566. // use alternate value
  1567. else if (dd == '+')
  1568. push_arg(delete, ifs = slashcopy(slice+xx+1, "}", 0));
  1569. else if (xx) { // ${x::}
  1570. long long la = 0, lb = LLONG_MAX, lc = 1;
  1571. ss = ++slice;
  1572. if ((lc = recalculate(&la, &ss, 0)) && *ss == ':') {
  1573. ss++;
  1574. lc = recalculate(&lb, &ss, 0);
  1575. }
  1576. if (!lc || *ss != '}') {
  1577. for (s = ss; *s != '}' && *s != ':'; s++);
  1578. error_msg("bad %.*s @ %ld", (int)(s-slice), slice, ss-slice);
  1579. //TODO fix error message
  1580. goto fail;
  1581. }
  1582. // This isn't quite what bash does, but close enough.
  1583. if (!(lc = aa.c)) lc = strlen(ifs);
  1584. else if (!la && !yy && strchr("@*", *slice)) {
  1585. aa.v--; // ${*:0} shows $0 even though default is 1-indexed
  1586. aa.c++;
  1587. yy++;
  1588. }
  1589. if (la<0 && (la += lc)<0) continue;
  1590. if (lb<0) lb = lc+lb-la;
  1591. if (aa.c) {
  1592. if (mm<la || mm>=la+lb) continue;
  1593. } else if (la>=lc || lb<0) ifs = "";
  1594. else if (la+lb>=lc) ifs += la;
  1595. else if (!*delete || ifs != (*delete)->arg)
  1596. push_arg(delete, ifs = xmprintf("%.*s", (int)lb, ifs+la));
  1597. else {
  1598. for (dd = 0; dd<lb ; dd++) if (!(ifs[dd] = ifs[dd+la])) break;
  1599. ifs[dd] = 0;
  1600. }
  1601. } else if (strchr("#%^,", *slice)) {
  1602. struct sh_arg wild = {0};
  1603. char buf[8];
  1604. s = slashcopy(slice+(xx = slice[1]==*slice)+1, "}", &wild);
  1605. // ${x^pat} ${x^^pat} uppercase ${x,} ${x,,} lowercase (no pat = ?)
  1606. if (strchr("^,", *slice)) {
  1607. for (ss = ifs; *ss; ss += dd) {
  1608. dd = getutf8(ss, 4, &jj);
  1609. if (!*s || 0<wildcard_match(ss, s, &wild, WILD_ANY)) {
  1610. ll = ((*slice=='^') ? towupper : towlower)(jj);
  1611. // Of COURSE unicode case switch can change utf8 encoding length
  1612. // Lower case U+0069 becomes u+0130 in turkish.
  1613. // Greek U+0390 becomes 3 characters TODO test this
  1614. if (ll != jj) {
  1615. yy = ss-ifs;
  1616. if (!*delete || (*delete)->arg!=ifs)
  1617. push_arg(delete, ifs = xstrdup(ifs));
  1618. if (dd != (ll = wctoutf8(buf, ll))) {
  1619. if (dd<ll)
  1620. ifs = (*delete)->arg = xrealloc(ifs, strlen(ifs)+1+dd-ll);
  1621. memmove(ifs+yy+dd-ll, ifs+yy+ll, strlen(ifs+yy+ll)+1);
  1622. }
  1623. memcpy(ss = ifs+yy, buf, dd = ll);
  1624. }
  1625. }
  1626. if (!xx) break;
  1627. }
  1628. // ${x#y} remove shortest prefix ${x##y} remove longest prefix
  1629. } else if (*slice=='#') {
  1630. if (0<(dd = wildcard_match(ifs, s, &wild, WILD_SHORT*!xx)))
  1631. ifs += dd;
  1632. // ${x%y} ${x%%y} suffix
  1633. } else if (*slice=='%') {
  1634. for (ss = ifs+strlen(ifs), yy = -1; ss>=ifs; ss--) {
  1635. if (0<(dd = wildcard_match(ss, s, &wild, WILD_SHORT*xx))&&!ss[dd])
  1636. {
  1637. yy = ss-ifs;
  1638. if (!xx) break;
  1639. }
  1640. }
  1641. if (yy != -1) {
  1642. if (*delete && (*delete)->arg==ifs) ifs[yy] = 0;
  1643. else push_arg(delete, ifs = xstrndup(ifs, yy));
  1644. }
  1645. }
  1646. free(s);
  1647. free(wild.v);
  1648. // ${x/pat/sub} substitute ${x//pat/sub} global ${x/#pat/sub} begin
  1649. // ${x/%pat/sub} end ${x/pat} delete pat (x can be @ or *)
  1650. } else if (*slice=='/') {
  1651. struct sh_arg wild = {0};
  1652. s = slashcopy(ss = slice+(xx = !!strchr("/#%", slice[1]))+1, "/}",
  1653. &wild);
  1654. ss += (long)wild.v[wild.c];
  1655. ss = (*ss == '/') ? slashcopy(ss+1, "}", 0) : 0;
  1656. jj = ss ? strlen(ss) : 0;
  1657. ll = 0;
  1658. for (ll = 0; ifs[ll];) {
  1659. // TODO nocasematch option
  1660. if (0<(dd = wildcard_match(ifs+ll, s, &wild, 0))) {
  1661. char *bird = 0;
  1662. if (slice[1]=='%' && ifs[ll+dd]) {
  1663. ll++;
  1664. continue;
  1665. }
  1666. if (*delete && (*delete)->arg==ifs) {
  1667. if (jj==dd) memcpy(ifs+ll, ss, jj);
  1668. else if (jj<dd) sprintf(ifs+ll, "%s%s", ss, ifs+ll+dd);
  1669. else bird = ifs;
  1670. } else bird = (void *)1;
  1671. if (bird) {
  1672. ifs = xmprintf("%.*s%s%s", ll, ifs, ss ? : "", ifs+ll+dd);
  1673. if (bird != (void *)1) {
  1674. free(bird);
  1675. (*delete)->arg = ifs;
  1676. } else push_arg(delete, ifs);
  1677. }
  1678. if (slice[1]!='/') break;
  1679. } else ll++;
  1680. if (slice[1]=='#') break;
  1681. }
  1682. // ${x@QEPAa} Q=$'blah' E=blah without the $'' wrap, P=expand as $PS1
  1683. // A=declare that recreates var a=attribute flags
  1684. // x can be @*
  1685. // } else if (*slice=='@') {
  1686. // TODO test x can be @ or *
  1687. } else {
  1688. // TODO test ${-abc} as error
  1689. ifs = slice;
  1690. goto barf;
  1691. }
  1692. // TODO: $((a=42)) can change var, affect lifetime
  1693. // must replace ifs AND any previous output arg[] within pointer strlen()
  1694. // also x=;echo $x${x:=4}$x
  1695. }
  1696. // Nothing left to do?
  1697. if (!ifs) break;
  1698. if (!*ifs && !qq) continue;
  1699. // loop within current ifs checking region to split words
  1700. do {
  1701. // find end of (split) word
  1702. if ((qq&1) || nosplit) ss = ifs+strlen(ifs);
  1703. else for (ss = ifs; *ss; ss += kk)
  1704. if (utf8chr(ss, TT.ff->ifs, &kk)) break;
  1705. // when no prefix, not splitting, no suffix: use existing memory
  1706. if (!oo && !*ss && !((mm==aa.c) ? str[ii] : nosplit)) {
  1707. if (qq || ss!=ifs) {
  1708. if (!(flags&NO_PATH))
  1709. for (jj = 0; ifs[jj]; jj++) collect_wildcards(ifs, jj, ant);
  1710. wildcard_add_files(arg, ifs, &deck, delete);
  1711. }
  1712. continue;
  1713. }
  1714. // resize allocation and copy next chunk of IFS-free data
  1715. jj = (mm == aa.c) && !*ss;
  1716. new = xrealloc(new, oo + (ss-ifs) + ((nosplit&!jj) ? strlen(sep) : 0) +
  1717. (jj ? strlen(str+ii) : 0) + 1);
  1718. dd = sprintf(new + oo, "%.*s%s", (int)(ss-ifs), ifs,
  1719. (nosplit&!jj) ? sep : "");
  1720. if (flags&NO_PATH) oo += dd;
  1721. else while (dd--) collect_wildcards(new, oo++, ant);
  1722. if (jj) break;
  1723. // If splitting, keep quoted, non-blank, or non-whitespace separator
  1724. if (!nosplit) {
  1725. if (qq || *new || *ss) {
  1726. push_arg(delete, new = xrealloc(new, strlen(new)+1));
  1727. wildcard_add_files(arg, new, &deck, delete);
  1728. new = xstrdup(str+ii);
  1729. }
  1730. qq &= 1;
  1731. oo = 0;
  1732. }
  1733. // Skip trailing seperator (combining whitespace)
  1734. kk = 0;
  1735. while ((jj = utf8chr(ss, TT.ff->ifs, &ll))) {
  1736. if (!iswspace(jj) && kk++) break;
  1737. ss += ll;
  1738. }
  1739. } while (*(ifs = ss));
  1740. } while (!(mm == aa.c));
  1741. }
  1742. // TODO globbing * ? [] +() happens after variable resolution
  1743. // TODO test word splitting completely eliminating argument when no non-$IFS data left
  1744. // wordexp keeps pattern when no matches
  1745. // TODO test NO_SPLIT cares about IFS, see also trailing \n
  1746. // Record result.
  1747. if (*new || qq) {
  1748. if (str != new) push_arg(delete, new);
  1749. wildcard_add_files(arg, new, &deck, delete);
  1750. new = 0;
  1751. }
  1752. // return success after freeing
  1753. arg = 0;
  1754. fail:
  1755. if (str != new) free(new);
  1756. free(deck.v);
  1757. if (ant!=&deck && ant->v) collect_wildcards("", 0, ant);
  1758. return !!arg;
  1759. }
  1760. struct sh_brace {
  1761. struct sh_brace *next, *prev, *stack;
  1762. int active, cnt, idx, commas[];
  1763. };
  1764. static int brace_end(struct sh_brace *bb)
  1765. {
  1766. return bb->commas[(bb->cnt<0 ? 0 : bb->cnt)+1];
  1767. }
  1768. // expand braces (ala {a,b,c}) and call expand_arg_nobrace() each permutation
  1769. static int expand_arg(struct sh_arg *arg, char *old, unsigned flags,
  1770. struct arg_list **delete)
  1771. {
  1772. struct sh_brace *bb = 0, *blist = 0, *bstk, *bnext;
  1773. int i, j, k, x;
  1774. char *s, *ss;
  1775. // collect brace spans
  1776. if ((TT.options&OPT_B) && !(flags&NO_BRACE)) for (i = 0; ; i++) {
  1777. // skip quoted/escaped text
  1778. while ((s = parse_word(old+i, 1, 0)) != old+i) i += s-(old+i);
  1779. // stop at end of string if we haven't got any more open braces
  1780. if (!bb && !old[i]) break;
  1781. // end a brace?
  1782. if (bb && (!old[i] || old[i] == '}')) {
  1783. bb->active = bb->commas[bb->cnt+1] = i;
  1784. // pop brace from bb into bnext
  1785. for (bnext = bb; bb && bb->active; bb = (bb==blist) ? 0 : bb->prev);
  1786. // Is this a .. span?
  1787. j = 1+*bnext->commas;
  1788. if (old[i] && !bnext->cnt && i-j>=4) {
  1789. // a..z span? Single digit numbers handled here too. TODO: utf8
  1790. if (old[j+1]=='.' && old[j+2]=='.') {
  1791. bnext->commas[2] = old[j];
  1792. bnext->commas[3] = old[j+3];
  1793. k = 0;
  1794. if (old[j+4]=='}' ||
  1795. (sscanf(old+j+4, "..%u}%n", bnext->commas+4, &k) && k))
  1796. bnext->cnt = -1;
  1797. }
  1798. // 3..11 numeric span?
  1799. if (!bnext->cnt) {
  1800. for (k=0, j = 1+*bnext->commas; k<3; k++, j += x)
  1801. if (!sscanf(old+j, "..%u%n"+2*!k, bnext->commas+2+k, &x)) break;
  1802. if (old[j] == '}') bnext->cnt = -2;
  1803. }
  1804. // Increment goes in the right direction by at least 1
  1805. if (bnext->cnt) {
  1806. if (!bnext->commas[4]) bnext->commas[4] = 1;
  1807. if ((bnext->commas[3]-bnext->commas[2]>0) != (bnext->commas[4]>0))
  1808. bnext->commas[4] *= -1;
  1809. }
  1810. }
  1811. // discard unterminated span, or commaless span that wasn't x..y
  1812. if (!old[i] || !bnext->cnt)
  1813. free(dlist_pop((blist == bnext) ? &blist : &bnext));
  1814. // starting brace
  1815. } else if (old[i] == '{') {
  1816. dlist_add_nomalloc((void *)&blist,
  1817. (void *)(bb = xzalloc(sizeof(struct sh_brace)+34*4)));
  1818. bb->commas[0] = i;
  1819. // no active span?
  1820. } else if (!bb) continue;
  1821. // add a comma to current span
  1822. else if (bb && old[i] == ',') {
  1823. if (bb->cnt && !(bb->cnt&31)) {
  1824. dlist_lpop(&blist);
  1825. dlist_add_nomalloc((void *)&blist,
  1826. (void *)(bb = xrealloc(bb, sizeof(struct sh_brace)+(bb->cnt+34)*4)));
  1827. }
  1828. bb->commas[++bb->cnt] = i;
  1829. }
  1830. }
  1831. // TODO NO_SPLIT with braces? (Collate with spaces?)
  1832. // If none, pass on verbatim
  1833. if (!blist) return expand_arg_nobrace(arg, old, flags, delete, 0);
  1834. // enclose entire range in top level brace.
  1835. (bstk = xzalloc(sizeof(struct sh_brace)+8))->commas[1] = strlen(old)+1;
  1836. bstk->commas[0] = -1;
  1837. // loop through each combination
  1838. for (;;) {
  1839. // Brace expansion can't be longer than original string. Keep start to {
  1840. s = ss = xmalloc(bstk->commas[1]);
  1841. // Append output from active braces to string
  1842. for (bb = blist; bb; bb = (bnext == blist) ? 0 : bnext) {
  1843. // If this brace already tip of stack, pop it. (We'll re-add in a moment.)
  1844. if (bstk == bb) bstk = bstk->stack;
  1845. // if bb is within bstk, save prefix text from bstk's "," to bb's "{"
  1846. if (brace_end(bstk)>bb->commas[0]) {
  1847. i = bstk->commas[bstk->idx]+1;
  1848. s = stpncpy(s, old+i, bb->commas[0]-i);
  1849. }
  1850. else bstk = bstk->stack; // bb past bstk so done with old bstk, pop it
  1851. // push self onto stack as active
  1852. bb->stack = bstk;
  1853. bb->active = 1;
  1854. bstk = bnext = bb;
  1855. // Find next active range: skip inactive spans from earlier/later commas
  1856. while ((bnext = (bnext->next==blist) ? 0 : bnext->next)) {
  1857. // past end of this brace (always true for a..b ranges)
  1858. if ((i = bnext->commas[0])>brace_end(bb)) break;
  1859. // in this brace but not this section
  1860. if (i<bb->commas[bb->idx] || i>bb->commas[bb->idx+1]) {
  1861. bnext->active = 0;
  1862. bnext->stack = 0;
  1863. // in this section
  1864. } else break;
  1865. }
  1866. // is next span past this range?
  1867. if (!bnext || bb->cnt<0 || bnext->commas[0]>bb->commas[bb->idx+1]) {
  1868. // output uninterrupted span
  1869. if (bb->cnt<0) {
  1870. k = bb->commas[2]+bb->commas[4]*bb->idx;
  1871. s += sprintf(s, (bb->cnt==-1) ? "\\%c"+!ispunct(k) : "%d", k);
  1872. } else {
  1873. i = bb->commas[bstk->idx]+1;
  1874. s = stpncpy(s, old+i, bb->commas[bb->idx+1]-i);
  1875. }
  1876. // While not sibling, output tail and pop
  1877. while (!bnext || bnext->commas[0]>brace_end(bstk)) {
  1878. if (!(bb = bstk->stack)) break;
  1879. i = brace_end(bstk)+1; // start of span
  1880. j = bb->commas[bb->idx+1]; // enclosing comma span (can't be a..b)
  1881. while (bnext) {
  1882. if (bnext->commas[0]<j) {
  1883. j = bnext->commas[0];// sibling
  1884. break;
  1885. } else if (brace_end(bb)>bnext->commas[0])
  1886. bnext = (bnext->next == blist) ? 0 : bnext->next;
  1887. else break;
  1888. }
  1889. s = stpncpy(s, old+i, j-i);
  1890. // if next is sibling but parent _not_ a sibling, don't pop
  1891. if (bnext && bnext->commas[0]<brace_end(bb)) break;
  1892. bstk = bb;
  1893. }
  1894. }
  1895. }
  1896. // Save result, aborting on expand error
  1897. if (expand_arg_nobrace(arg, push_arg(delete, ss), flags, delete, 0)) {
  1898. llist_traverse(blist, free);
  1899. return 1;
  1900. }
  1901. // increment
  1902. for (bb = blist->prev; bb; bb = (bb == blist) ? 0 : bb->prev) {
  1903. if (!bb->stack) continue;
  1904. else if (bb->cnt<0) {
  1905. if (abs(bb->commas[2]-bb->commas[3]) < abs(++bb->idx*bb->commas[4]))
  1906. bb->idx = 0;
  1907. else break;
  1908. } else if (++bb->idx > bb->cnt) bb->idx = 0;
  1909. else break;
  1910. }
  1911. // if increment went off left edge, done expanding
  1912. if (!bb) break;
  1913. }
  1914. llist_traverse(blist, free);
  1915. return 0;
  1916. }
  1917. // Expand exactly one arg, returning NULL on error.
  1918. static char *expand_one_arg(char *new, unsigned flags, struct arg_list **del)
  1919. {
  1920. struct sh_arg arg = {0};
  1921. char *s = 0;
  1922. if (!expand_arg(&arg, new, flags|NO_PATH|NO_SPLIT, del))
  1923. if (!(s = *arg.v) && (flags&(SEMI_IFS|NO_NULL))) s = "";
  1924. free(arg.v);
  1925. return s;
  1926. }
  1927. // TODO |&
  1928. // Expand arguments and perform redirections. Return new process object with
  1929. // expanded args. This can be called from command or block context.
  1930. static struct sh_process *expand_redir(struct sh_arg *arg, int skip, int *urd)
  1931. {
  1932. struct sh_process *pp;
  1933. char *s = s, *ss, *sss, *cv = 0;
  1934. int j, to, from, here = 0;
  1935. TT.hfd = 10;
  1936. pp = xzalloc(sizeof(struct sh_process));
  1937. pp->urd = urd;
  1938. pp->raw = arg;
  1939. // When we redirect, we copy each displaced filehandle to restore it later.
  1940. // Expand arguments and perform redirections
  1941. for (j = skip; j<arg->c; j++) {
  1942. int saveclose = 0, bad = 0;
  1943. if (!strcmp(s = arg->v[j], "!")) {
  1944. pp->flags ^= PFLAG_NOT;
  1945. continue;
  1946. }
  1947. // Handle <() >() redirectionss
  1948. if ((*s == '<' || *s == '>') && s[1] == '(') {
  1949. int new = pipe_subshell(s+2, strlen(s+2)-1, *s == '>');
  1950. // Grab subshell data
  1951. if (new == -1) {
  1952. pp->exit = 1;
  1953. return pp;
  1954. }
  1955. save_redirect(&pp->urd, -2, new);
  1956. // bash uses /dev/fd/%d which requires /dev/fd to be a symlink to
  1957. // /proc/self/fd so we just produce that directly.
  1958. arg_add_del(&pp->arg, ss = xmprintf("/proc/self/fd/%d", new),&pp->delete);
  1959. continue;
  1960. }
  1961. // Is this a redirect? s = prefix, ss = operator
  1962. ss = s + redir_prefix(arg->v[j]);
  1963. sss = ss + anystart(ss, (void *)redirectors);
  1964. if (ss == sss) {
  1965. // Nope: save/expand argument and loop
  1966. if (expand_arg(&pp->arg, s, 0, &pp->delete)) {
  1967. pp->exit = 1;
  1968. return pp;
  1969. }
  1970. continue;
  1971. } else if (j+1 >= arg->c) {
  1972. // redirect needs one argument
  1973. s = "\\n";
  1974. break;
  1975. }
  1976. sss = arg->v[++j];
  1977. // It's a redirect: for [to]<from s = start of [to], ss = <, sss = from
  1978. if (isdigit(*s) && ss-s>5) break;
  1979. // expand arguments for everything but << and <<-
  1980. if (strncmp(ss, "<<", 2) && ss[2] != '<') {
  1981. struct sh_arg tmp = {0};
  1982. if (!expand_arg(&tmp, sss, 0, &pp->delete) && tmp.c == 1) sss = *tmp.v;
  1983. else {
  1984. if (tmp.c > 1) error_msg("%s: ambiguous redirect", sss);
  1985. s = 0;
  1986. }
  1987. free(tmp.v);
  1988. if (!s) break;
  1989. }
  1990. // Parse the [fd] part of [fd]<name
  1991. to = *ss != '<';
  1992. if (isdigit(*s)) to = atoi(s);
  1993. else if (*s == '{') {
  1994. if (*varend(s+1) != '}') break;
  1995. // when we close a filehandle, we _read_ from {var}, not write to it
  1996. if ((!strcmp(ss, "<&") || !strcmp(ss, ">&")) && !strcmp(sss, "-")) {
  1997. if (!(ss = getvar(s+1))) break;
  1998. to = atoi(ss); // TODO trailing garbage?
  1999. if (save_redirect(&pp->urd, -1, to)) break;
  2000. close(to);
  2001. continue;
  2002. // record high file descriptor in {to}<from environment variable
  2003. } else {
  2004. // we don't save this, it goes in the env var and user can close it.
  2005. if (-1 == (to = next_hfd())) break;
  2006. cv = xmprintf("%.*s=%d", (int)(ss-s-2), s+1, to);
  2007. }
  2008. }
  2009. // HERE documents?
  2010. if (!strcmp(ss, "<<<") || !strcmp(ss, "<<-") || !strcmp(ss, "<<")) {
  2011. char *tmp = getvar("TMPDIR");
  2012. int i, len, zap = (ss[2] == '-'), x = !ss[strcspn(ss, "\"'")];
  2013. // store contents in open-but-deleted /tmp file.
  2014. tmp = xmprintf("%s/sh-XXXXXX", tmp ? tmp : "/tmp");
  2015. if ((from = mkstemp(tmp))>=0) {
  2016. if (unlink(tmp)) bad++;
  2017. // write contents to file (if <<< else <<) then lseek back to start
  2018. else if (ss[2] == '<') {
  2019. if (!(ss = expand_one_arg(sss, 0, 0))) {
  2020. s = 0;
  2021. break;
  2022. }
  2023. len = strlen(ss);
  2024. if (len != writeall(from, ss, len)) bad++;
  2025. if (ss != sss) free(ss);
  2026. } else {
  2027. struct sh_arg *hh = arg+here++;
  2028. for (i = 0; i<hh->c; i++) {
  2029. ss = hh->v[i];
  2030. sss = 0;
  2031. // TODO audit this ala man page
  2032. // expand_parameter, commands, and arithmetic
  2033. if (x && !(ss = sss = expand_one_arg(ss, ~SEMI_IFS, 0))) {
  2034. s = 0;
  2035. break;
  2036. }
  2037. while (zap && *ss == '\t') ss++;
  2038. x = writeall(from, ss, len = strlen(ss));
  2039. free(sss);
  2040. if (len != x) break;
  2041. }
  2042. if (i != hh->c) bad++;
  2043. }
  2044. if (!bad && lseek(from, 0, SEEK_SET)) bad++;
  2045. if (bad) close(from);
  2046. } else bad++;
  2047. free(tmp);
  2048. if (bad) break;
  2049. // from is fd<<2 (new fd to dup2() after vfork()) plus
  2050. // 2 if we should close(from>>2) after dup2(from>>2, to),
  2051. // 1 if we should close but dup for nofork recovery (ala <&2-)
  2052. // Handle file descriptor duplication/close (&> &>> <& >& with number or -)
  2053. // These redirect existing fd so nothing to open()
  2054. } else if (*ss == '&' || ss[1] == '&') {
  2055. // is there an explicit fd?
  2056. for (ss = sss; isdigit(*ss); ss++);
  2057. if (ss-sss>5 || (*ss && (*ss != '-' || ss[1]))) {
  2058. if (*ss=='&') ss++;
  2059. saveclose = 4;
  2060. goto notfd;
  2061. }
  2062. from = (ss==sss) ? to : atoi(sss);
  2063. saveclose = 2-(*ss == '-');
  2064. } else {
  2065. notfd:
  2066. // Permissions to open external file with: < > >> <& >& <> >| &>> &>
  2067. if (!strcmp(ss, "<>")) from = O_CREAT|O_RDWR;
  2068. else if (strstr(ss, ">>")) from = O_CREAT|O_APPEND|O_WRONLY;
  2069. else {
  2070. from = (*ss == '<') ? O_RDONLY : O_CREAT|O_WRONLY|O_TRUNC;
  2071. if (!strcmp(ss, ">") && (TT.options&OPT_C)) {
  2072. struct stat st;
  2073. // Not _just_ O_EXCL: > /dev/null allowed
  2074. if (stat(sss, &st) || !S_ISREG(st.st_mode)) from |= O_EXCL;
  2075. }
  2076. }
  2077. // we expect /dev/fd/# and /dev/{stdin,stdout,stderr} to be in /dev
  2078. // TODO: /dev/{tcp,udp}/host/port
  2079. // Open the file
  2080. if (-1 == (from = xcreate_stdio(sss, from|WARN_ONLY, 0666))) {
  2081. s = 0;
  2082. break;
  2083. }
  2084. }
  2085. // perform redirect, saving displaced "to".
  2086. if (save_redirect(&pp->urd, from, to)) bad++;
  2087. // Do we save displaced "to" in env variable instead of undo list?
  2088. if (cv) {
  2089. --*pp->urd;
  2090. if (!setvar(cv)) bad++;
  2091. cv = 0;
  2092. }
  2093. if ((saveclose&1) && save_redirect(&pp->urd, -1, from)) bad++;
  2094. if ((saveclose&4) && save_redirect(&pp->urd, from, 2)) bad++;
  2095. if (!(saveclose&2)) close(from);
  2096. if (bad) break;
  2097. }
  2098. // didn't parse everything?
  2099. if (j != arg->c) {
  2100. if (s) syntax_err(s);
  2101. if (!pp->exit) pp->exit = 1;
  2102. free(cv);
  2103. }
  2104. return pp;
  2105. }
  2106. // Call binary, or run script via xexec("sh --")
  2107. static void sh_exec(char **argv)
  2108. {
  2109. char *pp = getvar("PATH" ? : _PATH_DEFPATH), *cc = TT.isexec ? : *argv, *ss,
  2110. **sss = 0, **oldenv = environ, **argv2;
  2111. struct string_list *sl;
  2112. if (getpid() != TT.pid) signal(SIGINT, SIG_DFL); // TODO: restore all?
  2113. errno = ENOENT;
  2114. if (strchr(ss = cc, '/')) {
  2115. if (access(ss, X_OK)) ss = 0;
  2116. } else for (sl = find_in_path(pp, cc); sl || (ss = 0); free(llist_pop(&sl)))
  2117. if (!access(ss = sl->str, X_OK)) break;
  2118. if (ss) {
  2119. struct sh_vars **vv = visible_vars();
  2120. struct sh_arg aa;
  2121. unsigned uu, argc;
  2122. // convert vars in-place and use original sh_arg alloc to add one more
  2123. aa.v = environ = (void *)vv;
  2124. for (aa.c = uu = 0; vv[uu]; uu++) {
  2125. if ((vv[uu]->flags&(VAR_WHITEOUT|VAR_EXPORT))==VAR_EXPORT) {
  2126. if (*(pp = vv[uu]->str)=='_' && pp[1]=='=') sss = aa.v+aa.c;
  2127. aa.v[aa.c++] = pp;
  2128. }
  2129. }
  2130. aa.v[aa.c] = 0;
  2131. if (!sss) {
  2132. arg_add(&aa, 0);
  2133. sss = aa.v+aa.c-1;
  2134. }
  2135. *sss = xmprintf("_=%s", ss);
  2136. // exec or source
  2137. execve(ss, argv, environ);
  2138. if (errno == ENOEXEC) {
  2139. for (argc = 0; argv[argc]; argc++);
  2140. argv2 = xmalloc((argc+3)*sizeof(char *));
  2141. memcpy(argv2+3, argv+1, argc*sizeof(char *));
  2142. argv2[0] = "sh";
  2143. argv2[1] = "--";
  2144. argv2[2] = ss;
  2145. xexec(argv2);
  2146. free(argv2);
  2147. }
  2148. environ = oldenv;
  2149. free(*sss);
  2150. free(aa.v);
  2151. }
  2152. perror_msg("%s", *argv);
  2153. if (!TT.isexec) _exit(127);
  2154. llist_traverse(sl, free);
  2155. }
  2156. // Execute a single command at TT.ff->pl
  2157. static struct sh_process *run_command(void)
  2158. {
  2159. char *s, *ss, *sss;
  2160. struct sh_arg *arg = TT.ff->pl->arg;
  2161. int envlen, funk = TT.funcslen, jj = 0, prefix = 0;
  2162. struct sh_process *pp;
  2163. // Count leading variable assignments
  2164. for (envlen = 0; envlen<arg->c; envlen++)
  2165. if ((ss = varend(arg->v[envlen]))==arg->v[envlen] || ss[*ss=='+']!='=')
  2166. break;
  2167. pp = expand_redir(arg, envlen, 0);
  2168. // Are we calling a shell function? TODO binary search
  2169. if (pp->arg.c && !strchr(*pp->arg.v, '/'))
  2170. for (funk = 0; funk<TT.funcslen; funk++)
  2171. if (!strcmp(*pp->arg.v, TT.functions[funk]->name)) break;
  2172. // Create new function context to hold local vars?
  2173. if (funk != TT.funcslen || (envlen && pp->arg.c) || TT.ff->blk->pipe) {
  2174. call_function();
  2175. // TODO function needs to run asynchronously in pipeline
  2176. if (funk != TT.funcslen) {
  2177. TT.ff->delete = pp->delete;
  2178. pp->delete = 0;
  2179. }
  2180. addvar(0, TT.ff); // function context (not source) so end_function deletes
  2181. prefix = 1; // create local variables for function prefix assignment
  2182. }
  2183. // perform any assignments
  2184. if (envlen) for (; jj<envlen && !pp->exit; jj++) {
  2185. struct sh_vars *vv;
  2186. if ((sss = expand_one_arg(ss = arg->v[jj], SEMI_IFS, 0))) {
  2187. if (!prefix && sss==ss) sss = xstrdup(sss);
  2188. if ((vv = setvar_long(sss, sss!=ss, prefix ? TT.ff : TT.ff->prev))) {
  2189. if (prefix) vv->flags |= VAR_EXPORT;
  2190. continue;
  2191. }
  2192. }
  2193. pp->exit = 1;
  2194. break;
  2195. }
  2196. // Do the thing
  2197. if (pp->exit || envlen==arg->c) s = 0; // leave $_ alone
  2198. else if (!pp->arg.c) s = ""; // nothing to do but blank $_
  2199. // TODO: call functions() FUNCTION
  2200. // TODO what about "echo | x=1 | export fruit", must subshell? Test this.
  2201. // Several NOFORK can just NOP in a pipeline? Except ${a?b} still errors
  2202. // call shell function
  2203. else if (funk != TT.funcslen) {
  2204. s = 0; // $_ set on return, not here
  2205. (TT.ff->func = TT.functions[funk])->refcount++;
  2206. TT.ff->pl = TT.ff->func->pipeline;
  2207. TT.ff->arg = pp->arg;
  2208. // TODO: unredirect(pp->urd) called below but haven't traversed function yet
  2209. } else {
  2210. struct toy_list *tl = toy_find(*pp->arg.v);
  2211. jj = tl ? tl->flags : 0;
  2212. TT.pp = pp;
  2213. s = pp->arg.v[pp->arg.c-1];
  2214. sss = pp->arg.v[pp->arg.c];
  2215. //dprintf(2, "%d run command %p %s\n", getpid(), TT.ff, *pp->arg.v); debug_show_fds();
  2216. // TODO handle ((math)): else if (!strcmp(*pp->arg.v, "(("))
  2217. // TODO: figure out when can exec instead of forking, ala sh -c blah
  2218. // Is this command a builtin that should run in this process?
  2219. if ((jj&TOYFLAG_NOFORK) || ((jj&TOYFLAG_MAYFORK) && !prefix)) {
  2220. sigjmp_buf rebound;
  2221. char temp[jj = offsetof(struct toy_context, rebound)];
  2222. // This fakes lots of what toybox_main() does.
  2223. memcpy(&temp, &toys, jj);
  2224. memset(&toys, 0, jj);
  2225. // The compiler complains "declaration does not declare anything" if we
  2226. // name the union in TT, only works WITHOUT name. So we can't
  2227. // sizeof(union) instead offsetof() first thing after union to get size.
  2228. memset(&TT, 0, offsetof(struct sh_data, SECONDS));
  2229. if (!sigsetjmp(rebound, 1)) {
  2230. toys.rebound = &rebound;
  2231. //dprintf(2, "%d builtin", getpid()); for (int xx = 0; xx<=pp->arg.c; xx++) dprintf(2, "{%s}", pp->arg.v[xx]); dprintf(2, "\n");
  2232. toy_singleinit(tl, pp->arg.v);
  2233. tl->toy_main();
  2234. xflush(0);
  2235. }
  2236. toys.rebound = 0;
  2237. pp->exit = toys.exitval;
  2238. if (toys.optargs != toys.argv+1) free(toys.optargs);
  2239. if (toys.old_umask) umask(toys.old_umask);
  2240. memcpy(&toys, &temp, jj);
  2241. } else if (-1==(pp->pid = xpopen_setup(pp->arg.v, 0, sh_exec)))
  2242. perror_msg("%s: vfork", *pp->arg.v);
  2243. }
  2244. // cleanup process
  2245. unredirect(pp->urd);
  2246. pp->urd = 0;
  2247. if (prefix && funk == TT.funcslen) end_function(0);
  2248. if (s) setvarval("_", s);
  2249. return pp;
  2250. }
  2251. static int free_process(struct sh_process *pp)
  2252. {
  2253. int rc;
  2254. if (!pp) return 127;
  2255. rc = pp->exit;
  2256. llist_traverse(pp->delete, llist_free_arg);
  2257. free(pp);
  2258. return rc;
  2259. }
  2260. // if then fi for while until select done done case esac break continue return
  2261. // Free one pipeline segment.
  2262. static void free_pipeline(void *pipeline)
  2263. {
  2264. struct sh_pipeline *pl = pipeline;
  2265. int i, j;
  2266. if (!pl) return;
  2267. // free either function or arguments and HERE doc contents
  2268. if (pl->type == 'F') {
  2269. free_function((void *)*pl->arg->v);
  2270. *pl->arg->v = 0;
  2271. }
  2272. for (j=0; j<=pl->count; j++) {
  2273. if (!pl->arg[j].v) continue;
  2274. for (i = 0; i<=pl->arg[j].c; i++) free(pl->arg[j].v[i]);
  2275. free(pl->arg[j].v);
  2276. }
  2277. free(pl);
  2278. }
  2279. // Append a new pipeline to function, returning pipeline and pipeline's arg
  2280. static struct sh_pipeline *add_pl(struct sh_pipeline **ppl, struct sh_arg **arg)
  2281. {
  2282. struct sh_pipeline *pl = xzalloc(sizeof(struct sh_pipeline));
  2283. if (arg) *arg = pl->arg;
  2284. pl->lineno = TT.LINENO;
  2285. dlist_add_nomalloc((void *)ppl, (void *)pl);
  2286. return pl->end = pl;
  2287. }
  2288. // Add a line of shell script to a shell function. Returns 0 if finished,
  2289. // 1 to request another line of input (> prompt), -1 for syntax err
  2290. static int parse_line(char *line, struct sh_pipeline **ppl,
  2291. struct double_list **expect)
  2292. {
  2293. char *start = line, *delete = 0, *end, *s, *ex, done = 0,
  2294. *tails[] = {"fi", "done", "esac", "}", "]]", ")", 0};
  2295. struct sh_pipeline *pl = *ppl ? (*ppl)->prev : 0, *pl2, *pl3;
  2296. struct sh_arg *arg = 0;
  2297. long i;
  2298. // Resume appending to last statement?
  2299. if (pl) {
  2300. arg = pl->arg;
  2301. // Extend/resume quoted block
  2302. if (arg->c<0) {
  2303. delete = start = xmprintf("%s%s", arg->v[arg->c = (-arg->c)-1], start);
  2304. free(arg->v[arg->c]);
  2305. arg->v[arg->c] = 0;
  2306. // is a HERE document in progress?
  2307. } else if (pl->count != pl->here) {
  2308. arg += 1+pl->here;
  2309. // Match unquoted EOF.
  2310. for (s = line, end = arg->v[arg->c]; *s && *end; s++) {
  2311. s += strspn(s, "\\\"'");
  2312. if (*s != *end) break;
  2313. }
  2314. // Add this line, else EOF hit so end HERE document
  2315. if (!*s && !*end) {
  2316. end = arg->v[arg->c];
  2317. arg_add(arg, xstrdup(line));
  2318. arg->v[arg->c] = end;
  2319. } else {
  2320. arg->v[arg->c] = 0;
  2321. pl->here++;
  2322. }
  2323. start = 0;
  2324. // Nope, new segment if not self-managing type
  2325. } else if (pl->type < 128) pl = 0;
  2326. }
  2327. // Parse words, assemble argv[] pipelines, check flow control and HERE docs
  2328. if (start) for (;;) {
  2329. ex = *expect ? (*expect)->prev->data : 0;
  2330. // Look for << HERE redirections in completed pipeline segment
  2331. if (pl && pl->count == -1) {
  2332. pl->count = 0;
  2333. arg = pl->arg;
  2334. // find arguments of the form [{n}]<<[-] with another one after it
  2335. for (i = 0; i<arg->c; i++) {
  2336. s = arg->v[i] + redir_prefix(arg->v[i]);
  2337. // TODO <<< is funky
  2338. // argc[] entries removed from main list? Can have more than one?
  2339. if (strcmp(s, "<<") && strcmp(s, "<<-") && strcmp(s, "<<<")) continue;
  2340. if (i+1 == arg->c) goto flush;
  2341. // Add another arg[] to the pipeline segment (removing/readding to list
  2342. // because realloc can move pointer)
  2343. dlist_lpop(ppl);
  2344. pl = xrealloc(pl, sizeof(*pl) + ++pl->count*sizeof(struct sh_arg));
  2345. dlist_add_nomalloc((void *)ppl, (void *)pl);
  2346. // queue up HERE EOF so input loop asks for more lines.
  2347. arg[pl->count].v = xzalloc(2*sizeof(void *));
  2348. arg[pl->count].v[0] = arg->v[++i];
  2349. arg[pl->count].v[1] = 0;
  2350. arg[pl->count].c = 0;
  2351. if (s[2] == '<') pl->here++; // <<< doesn't load more data
  2352. }
  2353. // Did we just end a function?
  2354. if (ex == (void *)1) {
  2355. struct sh_function *funky;
  2356. // function must be followed by a compound statement for some reason
  2357. if ((*ppl)->prev->type != 3) {
  2358. s = *(*ppl)->prev->arg->v;
  2359. goto flush;
  2360. }
  2361. // Back up to saved function() statement and create sh_function
  2362. free(dlist_lpop(expect));
  2363. pl = (void *)(*expect)->data;
  2364. funky = xmalloc(sizeof(struct sh_function));
  2365. funky->refcount = 1;
  2366. funky->name = *pl->arg->v;
  2367. *pl->arg->v = (void *)funky;
  2368. // Chop out pipeline segments added since saved function
  2369. funky->pipeline = pl->next;
  2370. pl->next->prev = (*ppl)->prev;
  2371. (*ppl)->prev->next = pl->next;
  2372. pl->next = *ppl;
  2373. (*ppl)->prev = pl;
  2374. dlist_terminate(funky->pipeline = add_pl(&funky->pipeline, 0));
  2375. funky->pipeline->type = 'f';
  2376. // Immature function has matured (meaning cleanup is different)
  2377. pl->type = 'F';
  2378. free(dlist_lpop(expect));
  2379. ex = *expect ? (*expect)->prev->data : 0;
  2380. }
  2381. pl = 0;
  2382. }
  2383. if (done) break;
  2384. s = 0;
  2385. // skip leading whitespace/comment here to know where next word starts
  2386. while (isspace(*start)) ++start;
  2387. if (*start=='#') while (*start && *start != '\n') ++start;
  2388. // Parse next word and detect overflow (too many nested quotes).
  2389. if ((end = parse_word(start, 0, 0)) == (void *)1) goto flush;
  2390. //dprintf(2, "%d %p %s word=%.*s\n", getpid(), pl, (ex != (void *)1) ? ex : "function", (int)(end-start), end ? start : "");
  2391. if (pl && pl->type == 'f' && arg->c == 1 && (end-start!=1 || *start!='(')) {
  2392. funky:
  2393. // end function segment, expect function body
  2394. dlist_add(expect, (void *)pl);
  2395. pl = 0;
  2396. dlist_add(expect, (void *)1);
  2397. dlist_add(expect, 0);
  2398. continue;
  2399. }
  2400. // Is this a new pipeline segment?
  2401. if (!pl) pl = add_pl(ppl, &arg);
  2402. // Do we need to request another line to finish word (find ending quote)?
  2403. if (!end) {
  2404. // Save unparsed bit of this line, we'll need to re-parse it.
  2405. arg_add(arg, xstrndup(start, strlen(start)));
  2406. arg->c = -arg->c;
  2407. free(delete);
  2408. return 1;
  2409. }
  2410. // Ok, we have a word. What does it _mean_?
  2411. // case/esac parsing is weird (unbalanced parentheses!), handle first
  2412. i = (unsigned long)ex>1 && !strcmp(ex, "esac") &&
  2413. ((pl->type && pl->type != 3) || (*start==';' && end-start>1));
  2414. if (i) {
  2415. // Premature EOL in type 1 (case x\nin) or 2 (at start or after ;;) is ok
  2416. if (end == start) {
  2417. if (pl->type==128 && arg->c==2) break; // case x\nin
  2418. if (pl->type==129 && (!arg->c || (arg->c==1 && **arg->v==';'))) break;
  2419. s = "newline";
  2420. goto flush;
  2421. }
  2422. // type 0 means just got ;; so start new type 2
  2423. if (!pl->type) {
  2424. // catch "echo | ;;" errors
  2425. if (arg->v && arg->v[arg->c] && strcmp(arg->v[arg->c], "&")) goto flush;
  2426. if (!arg->c) {
  2427. if (pl->prev->type == 2) {
  2428. // Add a call to "true" between empty ) ;;
  2429. arg_add(arg, xstrdup(":"));
  2430. pl = add_pl(ppl, &arg);
  2431. }
  2432. pl->type = 129;
  2433. } else {
  2434. // check for here documents
  2435. pl->count = -1;
  2436. continue;
  2437. }
  2438. }
  2439. // Did we hit end of line or ) outside a function declaration?
  2440. // ) is only saved at start of a statement, ends current statement
  2441. } else if (end == start || (arg->c && *start == ')' && pl->type!='f')) {
  2442. // function () needs both parentheses or neither
  2443. if (pl->type == 'f' && arg->c != 1 && arg->c != 3) {
  2444. s = "function(";
  2445. goto flush;
  2446. }
  2447. // "for" on its own line is an error.
  2448. if (arg->c == 1 && (unsigned long)ex>1 && !memcmp(ex, "do\0A", 4)) {
  2449. s = "newline";
  2450. goto flush;
  2451. }
  2452. // Stop at EOL. Discard blank pipeline segment, else end segment
  2453. if (end == start) done++;
  2454. if (!pl->type && !arg->c) {
  2455. free_pipeline(dlist_lpop(ppl));
  2456. pl = *ppl ? (*ppl)->prev : 0;
  2457. } else pl->count = -1;
  2458. continue;
  2459. }
  2460. // Save word and check for flow control
  2461. arg_add(arg, s = xstrndup(start, end-start));
  2462. start = end;
  2463. // Second half of case/esac parsing
  2464. if (i) {
  2465. // type 1 (128): case x [\n] in
  2466. if (pl->type==128) {
  2467. if (arg->c==2 && strchr("()|;&", *s)) goto flush;
  2468. if (arg->c==3) {
  2469. if (strcmp(s, "in")) goto flush;
  2470. pl->type = 1;
  2471. (pl = add_pl(ppl, &arg))->type = 129;
  2472. }
  2473. continue;
  2474. // type 2 (129): [;;] [(] pattern [|pattern...] )
  2475. } else {
  2476. // can't start with line break or ";;" or "case ? in ;;" without ")"
  2477. if (*s==';') {
  2478. if (arg->c>1 || (arg->c==1 && pl->prev->type==1)) goto flush;
  2479. } else pl->type = 2;
  2480. i = arg->c - (**arg->v==';' && arg->v[0][1]);
  2481. if (i==1 && !strcmp(s, "esac")) {
  2482. // esac right after "in" or ";;" ends block, fall through
  2483. if (arg->c>1) {
  2484. arg->v[1] = 0;
  2485. pl = add_pl(ppl, &arg);
  2486. arg_add(arg, s);
  2487. } else pl->type = 0;
  2488. } else {
  2489. if (arg->c>1) i -= *arg->v[1]=='(';
  2490. if (i>0 && ((i&1)==!!strchr("|)", *s) || strchr(";(", *s)))
  2491. goto flush;
  2492. if (*s=='&' || !strcmp(s, "||")) goto flush;
  2493. if (*s==')') pl = add_pl(ppl, &arg);
  2494. continue;
  2495. }
  2496. }
  2497. }
  2498. // Are we starting a new [function] name [()] definition
  2499. if (!pl->type || pl->type=='f') {
  2500. if (!pl->type && arg->c==1 && !strcmp(s, "function")) {
  2501. free(arg->v[--arg->c]);
  2502. arg->v[arg->c] = 0;
  2503. pl->type = 'f';
  2504. continue;
  2505. } else if (arg->c==2 && !strcmp(s, "(")) pl->type = 'f';
  2506. }
  2507. // one or both of [function] name[()]
  2508. if (pl->type=='f') {
  2509. if (arg->v[0][strcspn(*arg->v, "\"'`><;|&$")]) {
  2510. s = *arg->v;
  2511. goto flush;
  2512. }
  2513. if (arg->c == 2 && strcmp(s, "(")) goto flush;
  2514. if (arg->c == 3) {
  2515. if (strcmp(s, ")")) goto flush;
  2516. goto funky;
  2517. }
  2518. continue;
  2519. // is it a line break token?
  2520. } else if (strchr(";|&", *s) && strncmp(s, "&>", 2)) {
  2521. arg->c--;
  2522. // treat ; as newline so we don't have to check both elsewhere.
  2523. if (!strcmp(s, ";")) {
  2524. arg->v[arg->c] = 0;
  2525. free(s);
  2526. s = 0;
  2527. // TODO can't have ; between "for i" and in or do. (Newline yes, ; no. Why?)
  2528. if (!arg->c && (unsigned long)ex>1 && !memcmp(ex, "do\0C", 4)) continue;
  2529. // ;; and friends only allowed in case statements
  2530. } else if (*s == ';') goto flush;
  2531. // flow control without a statement is an error
  2532. if (!arg->c) goto flush;
  2533. pl->count = -1;
  2534. continue;
  2535. // a for/select must have at least one additional argument on same line
  2536. } else if ((unsigned long)ex>1 && !memcmp(ex, "do\0A", 4)) {
  2537. // Sanity check and break the segment
  2538. if (strncmp(s, "((", 2) && *varend(s)) goto flush;
  2539. pl->count = -1;
  2540. (*expect)->prev->data = "do\0C";
  2541. continue;
  2542. // flow control is the first word of a pipeline segment
  2543. } else if (arg->c>1) continue;
  2544. // Do we expect something that _must_ come next? (no multiple statements)
  2545. if ((unsigned long)ex>1) {
  2546. // The "test" part of for/select loops can have (at most) one "in" line,
  2547. // for {((;;))|name [in...]} do
  2548. if (!memcmp(ex, "do\0C", 4)) {
  2549. if (strcmp(s, "do")) {
  2550. // can only have one "in" line between for/do, but not with for(())
  2551. if (pl->prev->type == 's') goto flush;
  2552. if (!strncmp(pl->prev->arg->v[1], "((", 2)) goto flush;
  2553. else if (strcmp(s, "in")) goto flush;
  2554. pl->type = 's';
  2555. continue;
  2556. }
  2557. }
  2558. }
  2559. // start of a new block?
  2560. // for/select/case require var name on same line, can't break segment yet
  2561. if (!strcmp(s, "for") || !strcmp(s, "select") || !strcmp(s, "case")) {
  2562. // TODO why !pl->type here
  2563. if (!pl->type) pl->type = (*s == 'c') ? 128 : 1;
  2564. dlist_add(expect, (*s == 'c') ? "esac" : "do\0A");
  2565. continue;
  2566. }
  2567. end = 0;
  2568. if (!strcmp(s, "if")) end = "then";
  2569. else if (!strcmp(s, "while") || !strcmp(s, "until")) end = "do\0B";
  2570. else if (!strcmp(s, "{")) end = "}";
  2571. else if (!strcmp(s, "[[")) end = "]]";
  2572. else if (!strcmp(s, "(")) end = ")";
  2573. // Expecting NULL means a statement: I.E. any otherwise unrecognized word
  2574. if (!ex && *expect) free(dlist_lpop(expect));
  2575. // Did we start a new statement
  2576. if (end) {
  2577. pl->type = 1;
  2578. // Only innermost statement needed in { { { echo ;} ;} ;} and such
  2579. if (*expect && !(*expect)->prev->data) free(dlist_lpop(expect));
  2580. // if can't end a statement here skip next few tests
  2581. } else if ((unsigned long)ex<2);
  2582. // If we got here we expect a specific word to end this block: is this it?
  2583. else if (!strcmp(s, ex)) {
  2584. // can't "if | then" or "while && do", only ; & or newline works
  2585. if (strcmp(pl->prev->arg->v[pl->prev->arg->c] ? : "&", "&")) goto flush;
  2586. // consume word, record block end location in earlier !0 type blocks
  2587. free(dlist_lpop(expect));
  2588. if (3 == (pl->type = anystr(s, tails) ? 3 : 2)) {
  2589. for (i = 0, pl2 = pl3 = pl; (pl2 = pl2->prev);) {
  2590. if (pl2->type == 3) i++;
  2591. else if (pl2->type) {
  2592. if (!i) {
  2593. if (pl2->type == 2) {
  2594. pl2->end = pl3;
  2595. pl3 = pl2;
  2596. } else pl2->end = pl;
  2597. }
  2598. if (pl2->type == 1 && --i<0) break;
  2599. }
  2600. }
  2601. }
  2602. // if it's a multipart block, what comes next?
  2603. if (!strcmp(s, "do")) end = "done";
  2604. else if (!strcmp(s, "then")) end = "fi\0A";
  2605. // fi could have elif, which queues a then.
  2606. } else if (!strcmp(ex, "fi")) {
  2607. if (!strcmp(s, "elif")) {
  2608. free(dlist_lpop(expect));
  2609. end = "then";
  2610. // catch duplicate else while we're here
  2611. } else if (!strcmp(s, "else")) {
  2612. if (ex[3] != 'A') {
  2613. s = "2 else";
  2614. goto flush;
  2615. }
  2616. free(dlist_lpop(expect));
  2617. end = "fi\0B";
  2618. }
  2619. }
  2620. // Queue up the next thing to expect, all preceded by a statement
  2621. if (end) {
  2622. if (!pl->type) pl->type = 2;
  2623. dlist_add(expect, end);
  2624. if (!anystr(end, tails)) dlist_add(expect, 0);
  2625. pl->count = -1;
  2626. }
  2627. // syntax error check: these can't be the first word in an unexpected place
  2628. if (!pl->type && anystr(s, (char *[]){"then", "do", "esac", "}", "]]", ")",
  2629. "done", "fi", "elif", "else", 0})) goto flush;
  2630. }
  2631. free(delete);
  2632. // ignore blank and comment lines
  2633. if (!*ppl) return 0;
  2634. // TODO <<< has no parsing impact, why play with it here at all?
  2635. // advance past <<< arguments (stored as here documents, but no new input)
  2636. pl = (*ppl)->prev;
  2637. while (pl->count<pl->here && pl->arg[pl->count].c<0)
  2638. pl->arg[pl->count++].c = 0;
  2639. // return if HERE document pending or more flow control needed to complete
  2640. if (*expect) return 1;
  2641. if (*ppl && pl->count != pl->here) return 1;
  2642. if (pl->arg->v[pl->arg->c] && strcmp(pl->arg->v[pl->arg->c], "&")) return 1;
  2643. // Don't need more input, can start executing.
  2644. dlist_terminate(*ppl);
  2645. return 0;
  2646. flush:
  2647. if (s) syntax_err(s);
  2648. llist_traverse(*ppl, free_pipeline);
  2649. *ppl = 0;
  2650. llist_traverse(*expect, free);
  2651. *expect = 0;
  2652. return 0-!!s;
  2653. }
  2654. // Find + and - jobs. Returns index of plus, writes minus to *minus
  2655. int find_plus_minus(int *minus)
  2656. {
  2657. long long when, then;
  2658. int i, plus;
  2659. if (minus) *minus = 0;
  2660. for (then = i = plus = 0; i<TT.jobs.c; i++) {
  2661. if ((when = ((struct sh_process *)TT.jobs.v[i])->when) > then) {
  2662. then = when;
  2663. if (minus) *minus = plus;
  2664. plus = i;
  2665. }
  2666. }
  2667. return plus;
  2668. }
  2669. char is_plus_minus(int i, int plus, int minus)
  2670. {
  2671. return (i == plus) ? '+' : (i == minus) ? '-' : ' ';
  2672. }
  2673. // We pass in dash to avoid looping over every job each time
  2674. char *show_job(struct sh_process *pp, char dash)
  2675. {
  2676. char *s = "Run", *buf = 0;
  2677. int i, j, len, len2;
  2678. // TODO Terminated (Exited)
  2679. if (pp->exit<0) s = "Stop";
  2680. else if (pp->exit>126) s = "Kill";
  2681. else if (pp->exit>0) s = "Done";
  2682. for (i = len = len2 = 0;; i++) {
  2683. len += snprintf(buf, len2, "[%d]%c %-6s", pp->job, dash, s);
  2684. for (j = 0; j<pp->raw->c; j++)
  2685. len += snprintf(buf, len2, " %s"+!j, pp->raw->v[j]);
  2686. if (!i) buf = xmalloc(len2 = len+1);
  2687. else break;
  2688. }
  2689. return buf;
  2690. }
  2691. // Wait for pid to exit and remove from jobs table, returning process or 0.
  2692. struct sh_process *wait_job(int pid, int nohang)
  2693. {
  2694. struct sh_process *pp = pp;
  2695. int ii, status, minus, plus;
  2696. if (TT.jobs.c<1) return 0;
  2697. for (;;) {
  2698. errno = 0;
  2699. if (1>(pid = waitpid(pid, &status, nohang ? WNOHANG : 0))) {
  2700. if (!nohang && errno==EINTR && !toys.signal) continue;
  2701. return 0;
  2702. }
  2703. for (ii = 0; ii<TT.jobs.c; ii++) {
  2704. pp = (void *)TT.jobs.v[ii];
  2705. if (pp->pid == pid) break;
  2706. }
  2707. if (ii == TT.jobs.c) continue;
  2708. if (pid<1) return 0;
  2709. if (!WIFSTOPPED(status) && !WIFCONTINUED(status)) break;
  2710. }
  2711. plus = find_plus_minus(&minus);
  2712. memmove(TT.jobs.v+ii, TT.jobs.v+ii+1, (TT.jobs.c--)-ii);
  2713. pp->exit = WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+128;
  2714. pp->dash = is_plus_minus(ii, plus, minus);
  2715. return pp;
  2716. }
  2717. // wait for every process in a pipeline to end
  2718. static int wait_pipeline(struct sh_process *pp)
  2719. {
  2720. int rc = 0;
  2721. for (dlist_terminate(pp); pp; pp = pp->next) {
  2722. if (pp->pid) {
  2723. // TODO job control: not xwait, handle EINTR ourselves and check signals
  2724. pp->exit = xwaitpid(pp->pid);
  2725. pp->pid = 0;
  2726. }
  2727. // TODO handle set -o pipefail here
  2728. rc = (pp->flags&PFLAG_NOT) ? !pp->exit : pp->exit;
  2729. }
  2730. while ((pp = wait_job(-1, 1)) && (TT.options&FLAG_i)) {
  2731. char *s = show_job(pp, pp->dash);
  2732. dprintf(2, "%s\n", s);
  2733. free(s);
  2734. }
  2735. return rc;
  2736. }
  2737. // Print prompt to stderr, parsing escapes
  2738. // Truncated to 4k at the moment, waiting for somebody to complain.
  2739. static void do_prompt(char *prompt)
  2740. {
  2741. char *s, *ss, c, cc, *pp = toybuf;
  2742. int len, ll;
  2743. if (!prompt) return;
  2744. while ((len = sizeof(toybuf)-(pp-toybuf))>0 && *prompt) {
  2745. c = *(prompt++);
  2746. if (c=='!') {
  2747. if (*prompt=='!') prompt++;
  2748. else {
  2749. pp += snprintf(pp, len, "%u", TT.LINENO);
  2750. continue;
  2751. }
  2752. } else if (c=='\\') {
  2753. cc = *(prompt++);
  2754. if (!cc) {
  2755. *pp++ = c;
  2756. break;
  2757. }
  2758. // \nnn \dD{}hHjlstT@AuvVwW!#$
  2759. // Ignore bash's "nonprintable" hack; query our cursor position instead.
  2760. if (cc=='[' || cc==']') continue;
  2761. else if (cc=='$') *pp++ = getuid() ? '$' : '#';
  2762. else if (cc=='h' || cc=='H') {
  2763. *pp = 0;
  2764. gethostname(pp, len);
  2765. pp[len-1] = 0;
  2766. if (cc=='h' && (s = strchr(pp, '.'))) *s = 0;
  2767. pp += strlen(pp);
  2768. } else if (cc=='s') {
  2769. s = getbasename(*toys.argv);
  2770. while (*s && len--) *pp++ = *s++;
  2771. } else if (cc=='w') {
  2772. if ((s = getvar("PWD"))) {
  2773. if ((ss = getvar("HOME")) && strstart(&s, ss)) {
  2774. *pp++ = '~';
  2775. if (--len && *s!='/') *pp++ = '/';
  2776. len--;
  2777. }
  2778. if (len>0) {
  2779. ll = strlen(s);
  2780. pp = stpncpy(pp, s, ll>len ? len : ll);
  2781. }
  2782. }
  2783. } else if (!(c = unescape(cc))) {
  2784. *pp++ = '\\';
  2785. if (--len) *pp++ = c;
  2786. } else *pp++ = c;
  2787. } else *pp++ = c;
  2788. }
  2789. len = pp-toybuf;
  2790. if (len>=sizeof(toybuf)) len = sizeof(toybuf);
  2791. writeall(2, toybuf, len);
  2792. }
  2793. // returns NULL for EOF, 1 for invalid, else null terminated string.
  2794. static char *get_next_line(FILE *ff, int prompt)
  2795. {
  2796. char *new;
  2797. int len, cc;
  2798. if (!ff) {
  2799. char ps[16];
  2800. sprintf(ps, "PS%d", prompt);
  2801. do_prompt(getvar(ps));
  2802. }
  2803. // TODO what should ctrl-C do? (also in "select")
  2804. // TODO line editing/history, should set $COLUMNS $LINES and sigwinch update
  2805. // TODO: after first EINTR returns closed?
  2806. // TODO: ctrl-z during script read having already read partial line,
  2807. // SIGSTOP and SIGTSTP need SA_RESTART, but child proc should stop
  2808. // TODO if (!isspace(*new)) add_to_history(line);
  2809. for (new = 0, len = 0;;) {
  2810. errno = 0;
  2811. if (!(cc = getc(ff ? : stdin))) {
  2812. if (TT.LINENO) continue;
  2813. free(new);
  2814. return (char *)1;
  2815. }
  2816. if (cc<0) {
  2817. if (errno == EINTR) continue;
  2818. break;
  2819. }
  2820. if (!(len&63)) new = xrealloc(new, len+65);
  2821. if (cc == '\n') break;
  2822. new[len++] = cc;
  2823. }
  2824. if (new) new[len] = 0;
  2825. return new;
  2826. }
  2827. /*
  2828. TODO: "echo | read i" is backgroundable with ctrl-Z despite read = builtin.
  2829. probably have to inline run_command here to do that? Implicit ()
  2830. also "X=42 | true; echo $X" doesn't get X.
  2831. I.E. run_subshell() here sometimes? (But when?)
  2832. TODO: bash supports "break &" and "break > file". No idea why.
  2833. TODO If we just started a new pipeline, implicit parentheses (subshell)
  2834. TODO can't free sh_process delete until ready to dispose else no debug output
  2835. TODO: a | b | c needs subshell for builtins?
  2836. - anything that can produce output
  2837. - echo declare dirs
  2838. (a; b; c) like { } but subshell
  2839. when to auto-exec? ps vs sh -c 'ps' vs sh -c '(ps)'
  2840. */
  2841. // run a parsed shell function. Handle flow control blocks and characters,
  2842. // setup pipes and block redirection, break/continue, call builtins, functions,
  2843. // vfork/exec external commands. Return when out of input.
  2844. static void run_lines(void)
  2845. {
  2846. char *ctl, *s, *ss, **vv;
  2847. struct sh_process *pp, *pplist = 0; // processes piping into current level
  2848. long i, j, k;
  2849. // iterate through pipeline segments
  2850. for (;;) {
  2851. if (!TT.ff->pl) {
  2852. if (!end_function(1)) break;
  2853. goto advance;
  2854. }
  2855. ctl = TT.ff->pl->end->arg->v[TT.ff->pl->end->arg->c];
  2856. s = *TT.ff->pl->arg->v;
  2857. ss = TT.ff->pl->arg->v[1];
  2858. //dprintf(2, "%d s=%s ss=%s ctl=%s type=%d pl=%p ff=%p\n", getpid(), (TT.ff->pl->type == 'F') ? ((struct sh_function *)s)->name : s, ss, ctl, TT.ff->pl->type, TT.ff->pl, TT.ff);
  2859. if (!pplist) TT.hfd = 10;
  2860. // Skip disabled blocks, handle pipes and backgrounding
  2861. if (TT.ff->pl->type<2) {
  2862. if (!TT.ff->blk->run) {
  2863. TT.ff->pl = TT.ff->pl->end->next;
  2864. continue;
  2865. }
  2866. if (TT.options&OPT_x) {
  2867. unsigned lineno;
  2868. char *ss, *ps4 = getvar("PS4");
  2869. // duplicate first char of ps4 call depth times
  2870. if (ps4 && *ps4) {
  2871. j = getutf8(ps4, k = strlen(ps4), 0);
  2872. ss = xmalloc(TT.srclvl*j+k+1);
  2873. for (k = 0; k<TT.srclvl; k++) memcpy(ss+k*j, ps4, j);
  2874. strcpy(ss+k*j, ps4+j);
  2875. // show saved line number from function, not next to read
  2876. lineno = TT.LINENO;
  2877. TT.LINENO = TT.ff->pl->lineno;
  2878. do_prompt(ss);
  2879. TT.LINENO = lineno;
  2880. free(ss);
  2881. // TODO resolve variables
  2882. ss = pl2str(TT.ff->pl, 1);
  2883. dprintf(2, "%s\n", ss);
  2884. free(ss);
  2885. }
  2886. }
  2887. // pipe data into and out of this segment, I.E. leading/trailing |
  2888. unredirect(TT.ff->blk->urd);
  2889. TT.ff->blk->urd = 0;
  2890. TT.ff->blk->pipe = 0;
  2891. // Consume pipe from previous segment as stdin.
  2892. if (TT.ff->blk->pout != -1) {
  2893. TT.ff->blk->pipe++;
  2894. if (save_redirect(&TT.ff->blk->urd, TT.ff->blk->pout, 0)) break;
  2895. close(TT.ff->blk->pout);
  2896. TT.ff->blk->pout = -1;
  2897. }
  2898. // Create output pipe and save next process's stdin in pout
  2899. if (ctl && *ctl == '|' && ctl[1] != '|') {
  2900. int pipes[2] = {-1, -1};
  2901. TT.ff->blk->pipe++;
  2902. if (pipe(pipes)) {
  2903. perror_msg("pipe");
  2904. break;
  2905. }
  2906. if (save_redirect(&TT.ff->blk->urd, pipes[1], 1)) {
  2907. close(pipes[0]);
  2908. close(pipes[1]);
  2909. break;
  2910. }
  2911. if (pipes[1] != 1) close(pipes[1]);
  2912. fcntl(TT.ff->blk->pout = *pipes, F_SETFD, FD_CLOEXEC);
  2913. if (ctl[1] == '&') save_redirect(&TT.ff->blk->urd, 1, 2);
  2914. }
  2915. }
  2916. // Is this an executable segment?
  2917. if (!TT.ff->pl->type) {
  2918. // Is it a flow control jump? These aren't handled as normal builtins
  2919. // because they move *pl to other pipeline segments which is local here.
  2920. if (!strcmp(s, "break") || !strcmp(s, "continue")) {
  2921. // How many layers to peel off?
  2922. i = ss ? atol(ss) : 0;
  2923. if (i<1) i = 1;
  2924. if (TT.ff->blk->next && TT.ff->pl->arg->c<3
  2925. && (!ss || !ss[strspn(ss,"0123456789")]))
  2926. {
  2927. while (i && TT.ff->blk->next)
  2928. if (TT.ff->blk->middle && !strcmp(*TT.ff->blk->middle->arg->v, "do")
  2929. && !--i && *s=='c') TT.ff->pl = TT.ff->blk->start;
  2930. else TT.ff->pl = pop_block();
  2931. }
  2932. if (i) {
  2933. syntax_err(s);
  2934. break;
  2935. }
  2936. // Parse and run next command, saving resulting process
  2937. } else if ((pp = run_command()))
  2938. dlist_add_nomalloc((void *)&pplist, (void *)pp);
  2939. // Start of flow control block?
  2940. } else if (TT.ff->pl->type == 1) {
  2941. // TODO test cat | {thingy} is new PID: { is ( for |
  2942. // perform/save trailing redirects
  2943. pp = expand_redir(TT.ff->pl->end->arg, 1, TT.ff->blk->urd);
  2944. TT.ff->blk->urd = pp->urd;
  2945. pp->urd = 0;
  2946. if (pp->arg.c) syntax_err(*pp->arg.v);
  2947. llist_traverse(pp->delete, llist_free_arg);
  2948. pp->delete = 0;
  2949. if (pp->exit || pp->arg.c) {
  2950. free(pp);
  2951. toys.exitval = 1;
  2952. break;
  2953. }
  2954. add_block();
  2955. // TODO test background a block: { abc; } &
  2956. // If we spawn a subshell, pass data off to child process
  2957. if (TT.ff->blk->pipe || !strcmp(s, "(") || (ctl && !strcmp(ctl, "&"))) {
  2958. if (!(pp->pid = run_subshell(0, -1))) {
  2959. // zap forked child's cleanup context and advance to next statement
  2960. pplist = 0;
  2961. while (TT.ff->blk->next) TT.ff->blk = TT.ff->blk->next;
  2962. TT.ff->blk->pout = -1;
  2963. TT.ff->blk->urd = 0;
  2964. TT.ff->pl = TT.ff->next->pl->next;
  2965. continue;
  2966. }
  2967. TT.ff->pl = TT.ff->pl->end;
  2968. pop_block();
  2969. dlist_add_nomalloc((void *)&pplist, (void *)pp);
  2970. // handle start of block in this process
  2971. } else {
  2972. free(pp);
  2973. // What flow control statement is this?
  2974. // {/} if/then/elif/else/fi, while until/do/done - no special handling
  2975. // for/select/do/done: populate blk->farg with expanded args (if any)
  2976. if (!strcmp(s, "for") || !strcmp(s, "select")) {
  2977. if (TT.ff->blk->loop);
  2978. else if (!strncmp(TT.ff->blk->fvar = ss, "((", 2)) {
  2979. TT.ff->blk->loop = 1;
  2980. dprintf(2, "TODO skipped init for((;;)), need math parser\n");
  2981. // in LIST
  2982. } else if (TT.ff->pl->next->type == 's') {
  2983. for (i = 1; i<TT.ff->pl->next->arg->c; i++)
  2984. if (expand_arg(&TT.ff->blk->farg, TT.ff->pl->next->arg->v[i],
  2985. 0, &TT.ff->blk->fdelete)) break;
  2986. if (i != TT.ff->pl->next->arg->c) TT.ff->pl = pop_block();
  2987. // in without LIST. (This expansion can't return error.)
  2988. } else expand_arg(&TT.ff->blk->farg, "\"$@\"", 0,
  2989. &TT.ff->blk->fdelete);
  2990. // TODO: ls -C style output
  2991. if (*s == 's') for (i = 0; i<TT.ff->blk->farg.c; i++)
  2992. dprintf(2, "%ld) %s\n", i+1, TT.ff->blk->farg.v[i]);
  2993. // TODO: bash man page says it performs <(process substituion) here?!?
  2994. } else if (!strcmp(s, "case")) {
  2995. TT.ff->blk->fvar = expand_one_arg(ss, NO_NULL, &TT.ff->blk->fdelete);
  2996. if (!TT.ff->blk->fvar) break;
  2997. }
  2998. // TODO [[/]] ((/)) function/}
  2999. }
  3000. // gearshift from block start to block body (end of flow control test)
  3001. } else if (TT.ff->pl->type == 2) {
  3002. int match, err;
  3003. TT.ff->blk->middle = TT.ff->pl;
  3004. // ;; end, ;& continue through next block, ;;& test next block
  3005. if (!strcmp(*TT.ff->blk->start->arg->v, "case")) {
  3006. if (!strcmp(s, ";;")) {
  3007. while (TT.ff->pl->type!=3) TT.ff->pl = TT.ff->pl->end;
  3008. continue;
  3009. } else if (strcmp(s, ";&")) {
  3010. struct sh_arg arg = {0}, arg2 = {0};
  3011. for (err = 0, vv = 0;;) {
  3012. if (!vv) {
  3013. vv = TT.ff->pl->arg->v + (**TT.ff->pl->arg->v == ';');
  3014. if (!*vv) {
  3015. // TODO syntax err if not type==3, catch above
  3016. TT.ff->pl = TT.ff->pl->next;
  3017. break;
  3018. } else vv += **vv == '(';
  3019. }
  3020. arg.c = arg2.c = 0;
  3021. if ((err = expand_arg_nobrace(&arg, *vv++, NO_SPLIT,
  3022. &TT.ff->blk->fdelete, &arg2))) break;
  3023. s = arg.c ? *arg.v : "";
  3024. match = wildcard_match(TT.ff->blk->fvar, s, &arg2, 0);
  3025. if (match>=0 && !s[match]) break;
  3026. else if (**vv++ == ')') {
  3027. vv = 0;
  3028. if ((TT.ff->pl = TT.ff->pl->end)->type!=2) break;
  3029. }
  3030. }
  3031. free(arg.v);
  3032. free(arg2.v);
  3033. if (err) break;
  3034. if (TT.ff->pl->type==3) continue;
  3035. }
  3036. // Handle if/else/elif statement
  3037. } else if (!strcmp(s, "then"))
  3038. TT.ff->blk->run = TT.ff->blk->run && !toys.exitval;
  3039. else if (!strcmp(s, "else") || !strcmp(s, "elif"))
  3040. TT.ff->blk->run = !TT.ff->blk->run;
  3041. // Loop
  3042. else if (!strcmp(s, "do")) {
  3043. struct sh_blockstack *blk = TT.ff->blk;
  3044. ss = *blk->start->arg->v;
  3045. if (!strcmp(ss, "while")) blk->run = blk->run && !toys.exitval;
  3046. else if (!strcmp(ss, "until")) blk->run = blk->run && toys.exitval;
  3047. else if (!strcmp(ss, "select")) {
  3048. if (!(ss = get_next_line(0, 3)) || ss==(void *)1) {
  3049. TT.ff->pl = pop_block();
  3050. printf("\n");
  3051. } else {
  3052. match = atoi(ss);
  3053. free(ss);
  3054. if (!*ss) {
  3055. TT.ff->pl = blk->start;
  3056. continue;
  3057. } else setvarval(blk->fvar, (match<1 || match>blk->farg.c)
  3058. ? "" : blk->farg.v[match-1]);
  3059. }
  3060. } else if (blk->loop >= blk->farg.c) TT.ff->pl = pop_block();
  3061. else if (!strncmp(blk->fvar, "((", 2)) {
  3062. dprintf(2, "TODO skipped running for((;;)), need math parser\n");
  3063. } else setvarval(blk->fvar, blk->farg.v[blk->loop++]);
  3064. }
  3065. // end of block
  3066. } else if (TT.ff->pl->type == 3) {
  3067. // If we end a block we're not in, exit subshell
  3068. if (!TT.ff->blk->next) xexit();
  3069. // repeating block?
  3070. if (TT.ff->blk->run && !strcmp(s, "done")) {
  3071. TT.ff->pl = TT.ff->blk->middle;
  3072. continue;
  3073. }
  3074. // cleans up after trailing redirections/pipe
  3075. pop_block();
  3076. // declare a shell function
  3077. } else if (TT.ff->pl->type == 'F') {
  3078. struct sh_function *funky = (void *)*TT.ff->pl->arg->v;
  3079. // TODO binary search
  3080. for (i = 0; i<TT.funcslen; i++)
  3081. if (!strcmp(TT.functions[i]->name, funky->name)) break;
  3082. if (i == TT.funcslen) {
  3083. struct sh_arg arg = {(void *)TT.functions, TT.funcslen};
  3084. arg_add(&arg, (void *)funky); // TODO possibly an expand@31 function?
  3085. TT.functions = (void *)arg.v;
  3086. TT.funcslen++;
  3087. } else {
  3088. free_function(TT.functions[i]);
  3089. TT.functions[i] = funky;
  3090. }
  3091. TT.functions[i]->refcount++;
  3092. }
  3093. // Three cases: 1) background & 2) pipeline | 3) last process in pipeline ;
  3094. // If we ran a process and didn't pipe output, background or wait for exit
  3095. if (pplist && TT.ff->blk->pout == -1) {
  3096. if (ctl && !strcmp(ctl, "&")) {
  3097. if (!TT.jobs.c) TT.jobcnt = 0;
  3098. pplist->job = ++TT.jobcnt;
  3099. arg_add(&TT.jobs, (void *)pplist);
  3100. if (TT.options&FLAG_i) dprintf(2, "[%u] %u\n", pplist->job,pplist->pid);
  3101. } else {
  3102. toys.exitval = wait_pipeline(pplist);
  3103. llist_traverse(pplist, (void *)free_process);
  3104. }
  3105. pplist = 0;
  3106. }
  3107. advance:
  3108. // for && and || skip pipeline segment(s) based on return code
  3109. if (!TT.ff->pl->type || TT.ff->pl->type == 3) {
  3110. for (;;) {
  3111. ctl = TT.ff->pl->arg->v[TT.ff->pl->arg->c];
  3112. if (!ctl || strcmp(ctl, toys.exitval ? "&&" : "||")) break;
  3113. if ((TT.ff->pl = TT.ff->pl->next)->type) TT.ff->pl = TT.ff->pl->end;
  3114. }
  3115. }
  3116. TT.ff->pl = TT.ff->pl->next;
  3117. }
  3118. // clean up any unfinished stuff
  3119. if (pplist) {
  3120. toys.exitval = wait_pipeline(pplist);
  3121. llist_traverse(pplist, (void *)free_process);
  3122. }
  3123. // exit source context (and function calls on syntax err)
  3124. while (end_function(0));
  3125. }
  3126. // set variable
  3127. static struct sh_vars *initvar(char *name, char *val)
  3128. {
  3129. return addvar(xmprintf("%s=%s", name, val ? val : ""), TT.ff);
  3130. }
  3131. static struct sh_vars *initvardef(char *name, char *val, char *def)
  3132. {
  3133. return initvar(name, (!val || !*val) ? def : val);
  3134. }
  3135. // export existing "name" or assign/export name=value string (making new copy)
  3136. static void set_varflags(char *str, unsigned set_flags, unsigned unset_flags)
  3137. {
  3138. struct sh_vars *shv = 0;
  3139. struct sh_fcall *ff;
  3140. char *s;
  3141. // Make sure variable exists and is updated
  3142. if (strchr(str, '=')) shv = setvar(xstrdup(str));
  3143. else if (!(shv = findvar(str, &ff))) {
  3144. if (!set_flags) return;
  3145. shv = addvar(str = xmprintf("%s=", str), TT.ff->prev);
  3146. shv->flags = VAR_WHITEOUT;
  3147. } else if (shv->flags&VAR_WHITEOUT) shv->flags |= VAR_EXPORT;
  3148. if (!shv || (shv->flags&VAR_EXPORT)) return;
  3149. // Resolve magic for export (bash bug compatibility, really should be dynamic)
  3150. if (shv->flags&VAR_MAGIC) {
  3151. s = shv->str;
  3152. shv->str = xmprintf("%.*s=%s", (int)(varend(str)-str), str, getvar(str));
  3153. if (!(shv->flags&VAR_NOFREE)) free(s);
  3154. else shv->flags ^= VAR_NOFREE;
  3155. }
  3156. shv->flags |= set_flags;
  3157. shv->flags &= ~unset_flags;
  3158. }
  3159. static void export(char *str)
  3160. {
  3161. set_varflags(str, VAR_EXPORT, 0);
  3162. }
  3163. FILE *fpathopen(char *name)
  3164. {
  3165. struct string_list *sl = 0;
  3166. FILE *f = fopen(name, "r");
  3167. char *pp = getvar("PATH") ? : _PATH_DEFPATH;
  3168. if (!f) {
  3169. for (sl = find_in_path(pp, name); sl; free(llist_pop(&sl)))
  3170. if ((f = fopen(sl->str, "r"))) break;
  3171. if (sl) llist_traverse(sl, free);
  3172. }
  3173. return f;
  3174. }
  3175. // Read script input and execute lines, with or without prompts
  3176. int do_source(char *name, FILE *ff)
  3177. {
  3178. struct sh_pipeline *pl = 0;
  3179. struct double_list *expect = 0;
  3180. unsigned lineno = TT.LINENO, more = 0, wc;
  3181. int cc, ii;
  3182. char *new;
  3183. if (++TT.recursion>(50+200*CFG_TOYBOX_FORK)) {
  3184. error_msg("recursive occlusion");
  3185. goto end;
  3186. }
  3187. // TODO fix/catch NONBLOCK on input?
  3188. // TODO when DO we reset lineno? (!LINENO means \0 returns 1)
  3189. // when do we NOT reset lineno? Inherit but preserve perhaps? newline in $()?
  3190. if (!name) TT.LINENO = 0;
  3191. do {
  3192. if ((void *)1 == (new = get_next_line(ff, more+1))) goto is_binary;
  3193. //dprintf(2, "%d getline from %p %s\n", getpid(), ff, new); debug_show_fds();
  3194. // did we exec an ELF file or something?
  3195. if (!TT.LINENO++ && name && new) {
  3196. // A shell script's first line has no high bytes that aren't valid utf-8.
  3197. for (ii = 0; new[ii] && 0<(cc = utf8towc(&wc, new+ii, 4)); ii += cc);
  3198. if (new[ii]) {
  3199. is_binary:
  3200. if (name) error_msg("'%s' is binary", name); // TODO syntax_err() exit?
  3201. if (new != (void *)1) free(new);
  3202. new = 0;
  3203. }
  3204. }
  3205. // TODO: source <(echo 'echo hello\') vs source <(echo -n 'echo hello\')
  3206. // prints "hello" vs "hello\"
  3207. // returns 0 if line consumed, command if it needs more data
  3208. more = parse_line(new ? : " ", &pl, &expect);
  3209. free(new);
  3210. if (more==1) {
  3211. if (!new) {
  3212. if (!ff) syntax_err("unexpected end of file");
  3213. } else continue;
  3214. } else if (!more && pl) {
  3215. TT.ff->pl = pl;
  3216. run_lines();
  3217. } else more = 0;
  3218. llist_traverse(pl, free_pipeline);
  3219. pl = 0;
  3220. llist_traverse(expect, free);
  3221. expect = 0;
  3222. } while (new);
  3223. if (ff) fclose(ff);
  3224. if (!name) TT.LINENO = lineno;
  3225. end:
  3226. TT.recursion--;
  3227. return more;
  3228. }
  3229. // On nommu we had to exec(), so parent environment is passed via a pipe.
  3230. static void nommu_reentry(void)
  3231. {
  3232. struct stat st;
  3233. int ii, pid, ppid, len;
  3234. unsigned long ll;
  3235. char *s = 0;
  3236. FILE *fp;
  3237. // Sanity check
  3238. if (!fstat(254, &st) && S_ISFIFO(st.st_mode)) {
  3239. for (ii = len = 0; (s = environ[ii]); ii++) {
  3240. if (*s!='@') continue;
  3241. sscanf(s, "@%u,%u%n", &pid, &ppid, &len);
  3242. break;
  3243. }
  3244. }
  3245. if (!s || s[len] || pid!=getpid() || ppid!=getppid()) error_exit(0);
  3246. // TODO signal setup before this so fscanf can't EINTR.
  3247. // TODO marshall TT.jobcnt TT.funcslen: child needs jobs and function list
  3248. // Marshall magics: $SECONDS $- $LINENO $$ $!
  3249. if (5!=fscanf(fp = fdopen(254, "r"), "%lld %u %u %u %u%*[^\n]", &TT.SECONDS,
  3250. &TT.options, &TT.LINENO, &TT.pid, &TT.bangpid)) error_exit(0);
  3251. // Read named variables: type, len, var=value\0
  3252. for (;;) {
  3253. len = ll = 0;
  3254. fscanf(fp, "%u %lu%*[^\n]", &len, &ll);
  3255. fgetc(fp); // Discard the newline fscanf didn't eat.
  3256. if (!len) break;
  3257. (s = xmalloc(len+1))[len] = 0;
  3258. for (ii = 0; ii<len; ii += pid)
  3259. if (1>(pid = fread(s+ii, 1, len-ii, fp))) error_exit(0);
  3260. set_varflags(s, ll, 0);
  3261. }
  3262. // Perform subshell command(s)
  3263. do_source(0, fp);
  3264. xexit();
  3265. }
  3266. // init locals, sanitize environment, handle nommu subshell handoff
  3267. static void subshell_setup(void)
  3268. {
  3269. int ii, from, uid = getuid();
  3270. struct passwd *pw = getpwuid(uid);
  3271. char *s, *ss, *magic[] = {"SECONDS", "RANDOM", "LINENO", "GROUPS", "BASHPID",
  3272. "EPOCHREALTIME", "EPOCHSECONDS"},
  3273. *readonly[] = {xmprintf("EUID=%d", geteuid()), xmprintf("UID=%d", uid),
  3274. xmprintf("PPID=%d", getppid())};
  3275. struct sh_vars *shv;
  3276. struct utsname uu;
  3277. // Initialize magic and read only local variables
  3278. for (ii = 0; ii<ARRAY_LEN(magic) && (s = magic[ii]); ii++)
  3279. initvar(s, "")->flags = VAR_MAGIC+VAR_INT*('G'!=*s)+VAR_READONLY*('B'==*s);
  3280. for (ii = 0; ii<ARRAY_LEN(readonly); ii++)
  3281. addvar(readonly[ii], TT.ff)->flags = VAR_READONLY|VAR_INT;
  3282. // Add local variables that can be overwritten
  3283. initvar("PATH", _PATH_DEFPATH);
  3284. if (!pw) pw = (void *)toybuf; // first use, so still zeroed
  3285. sprintf(toybuf+1024, "%u", uid);
  3286. initvardef("HOME", pw->pw_dir, "/");
  3287. initvardef("SHELL", pw->pw_shell, "/bin/sh");
  3288. initvardef("USER", pw->pw_name, toybuf+1024);
  3289. initvardef("LOGNAME", pw->pw_name, toybuf+1024);
  3290. gethostname(toybuf, sizeof(toybuf)-1);
  3291. initvar("HOSTNAME", toybuf);
  3292. uname(&uu);
  3293. initvar("HOSTTYPE", uu.machine);
  3294. sprintf(toybuf, "%s-unknown-linux", uu.machine);
  3295. initvar("MACHTYPE", toybuf);
  3296. initvar("OSTYPE", uu.sysname);
  3297. // sprintf(toybuf, "%s-toybox", TOYBOX_VERSION);
  3298. // initvar("BASH_VERSION", toybuf); TODO
  3299. initvar("OPTERR", "1"); // TODO: test if already exported?
  3300. if (readlink0("/proc/self/exe", s = toybuf, sizeof(toybuf))||(s=getenv("_")))
  3301. initvar("BASH", s);
  3302. initvar("PS2", "> ");
  3303. initvar("PS3", "#? ");
  3304. initvar("PS4", "+ ");
  3305. // Ensure environ copied and toys.envc set, and clean out illegal entries
  3306. for (from = 0; (s = environ[from]); from++) {
  3307. if (*varend(s) != '=') continue;
  3308. if (!(shv = findvar(s, 0))) addvar(s, TT.ff)->flags = VAR_EXPORT|VAR_NOFREE;
  3309. else if (shv->flags&VAR_READONLY) continue;
  3310. else {
  3311. if (!(shv->flags&VAR_NOFREE)) {
  3312. free(shv->str);
  3313. shv->flags ^= VAR_NOFREE;
  3314. }
  3315. shv->flags |= VAR_EXPORT;
  3316. shv->str = s;
  3317. }
  3318. cache_ifs(s, TT.ff);
  3319. }
  3320. // set/update PWD
  3321. do_source(0, fmemopen("cd .", 4, "r"));
  3322. // set _ to path to this shell
  3323. s = toys.argv[0];
  3324. ss = 0;
  3325. if (!strchr(s, '/')) {
  3326. if ((ss = getcwd(0, 0))) {
  3327. s = xmprintf("%s/%s", ss, s);
  3328. free(ss);
  3329. ss = s;
  3330. } else if (*toybuf) s = toybuf; // from /proc/self/exe
  3331. }
  3332. setvarval("_", s)->flags |= VAR_EXPORT;
  3333. free(ss);
  3334. // TODO: this is in pipe, not environment
  3335. if (!(ss = getvar("SHLVL"))) export("SHLVL=1"); // Bash 5.0
  3336. else {
  3337. char buf[16];
  3338. sprintf(buf, "%u", atoi(ss+6)+1);
  3339. setvarval("SHLVL", buf)->flags |= VAR_EXPORT;
  3340. }
  3341. }
  3342. void sh_main(void)
  3343. {
  3344. char *cc = 0;
  3345. FILE *ff;
  3346. //unsigned uu; dprintf(2, "%d main", getpid()); for (uu = 0; toys.argv[uu]; uu++) dprintf(2, " %s", toys.argv[uu]); dprintf(2, "\n");
  3347. signal(SIGPIPE, SIG_IGN);
  3348. TT.options = OPT_B;
  3349. TT.pid = getpid();
  3350. srandom(TT.SECONDS = millitime());
  3351. // TODO euid stuff?
  3352. // TODO login shell?
  3353. // TODO read profile, read rc
  3354. // if (!FLAG(noprofile)) { }
  3355. // If not reentering, figure out if this is an interactive shell.
  3356. if (toys.stacktop) {
  3357. cc = TT.sh.c;
  3358. if (!FLAG(c)) {
  3359. if (toys.optc==1) toys.optflags |= FLAG_s;
  3360. if (FLAG(s) && isatty(0)) toys.optflags |= FLAG_i;
  3361. }
  3362. if (toys.optc>1) {
  3363. toys.optargs++;
  3364. toys.optc--;
  3365. }
  3366. TT.options |= toys.optflags&0xff;
  3367. }
  3368. // Create initial function context
  3369. call_function();
  3370. TT.ff->arg.v = toys.optargs;
  3371. TT.ff->arg.c = toys.optc;
  3372. TT.ff->ifs = " \t\n";
  3373. // Set up environment variables.
  3374. // Note: can call run_command() which blanks argument sections of TT and this,
  3375. // so parse everything we need from shell command line before here.
  3376. if (CFG_TOYBOX_FORK || toys.stacktop) subshell_setup(); // returns
  3377. else nommu_reentry(); // does not return
  3378. if (TT.options&FLAG_i) {
  3379. if (!getvar("PS1")) setvarval("PS1", getpid() ? "\\$ " : "# ");
  3380. // TODO Set up signal handlers and grab control of this tty.
  3381. // ^C SIGINT ^\ SIGQUIT ^Z SIGTSTP SIGTTIN SIGTTOU SIGCHLD
  3382. // setsid(), setpgid(), tcsetpgrp()...
  3383. xsignal(SIGINT, SIG_IGN);
  3384. }
  3385. if (cc) ff = fmemopen(cc, strlen(cc), "r");
  3386. else if (TT.options&FLAG_s) ff = (TT.options&FLAG_i) ? 0 : stdin;
  3387. else if (!(ff = fpathopen(*toys.optargs))) perror_exit_raw(*toys.optargs);
  3388. // Read and execute lines from file
  3389. if (do_source(cc ? : *toys.optargs, ff))
  3390. error_exit("%u:unfinished line"+3*!TT.LINENO, TT.LINENO);
  3391. }
  3392. // TODO: ./blah.sh one two three: put one two three in scratch.arg
  3393. /********************* shell builtin functions *************************/
  3394. #define FOR_cd
  3395. #include "generated/flags.h"
  3396. void cd_main(void)
  3397. {
  3398. char *from, *to = 0, *dd = *toys.optargs ? : (getvar("HOME") ? : "/"),
  3399. *pwd = FLAG(P) ? 0 : getvar("PWD"), *zap = 0;
  3400. struct stat st1, st2;
  3401. // TODO: CDPATH? Really?
  3402. // For cd - use $OLDPWD as destination directory
  3403. if (!strcmp(dd, "-") && (!(dd = getvar("OLDPWD")) || !*dd))
  3404. return perror_msg("No $OLDPWD");
  3405. if (*dd == '/') pwd = 0;
  3406. // Did $PWD move out from under us?
  3407. if (pwd && !stat(".", &st1))
  3408. if (stat(pwd, &st2) || st1.st_dev!=st2.st_dev || st1.st_ino!=st2.st_ino)
  3409. pwd = 0;
  3410. // Handle logical relative path
  3411. if (pwd) {
  3412. zap = xmprintf("%s/%s", pwd, dd);
  3413. // cancel out . and .. in the string
  3414. for (from = to = zap; *from;) {
  3415. if (*from=='/' && from[1]=='/') from++;
  3416. else if (*from!='/' || from[1]!='.') *to++ = *from++;
  3417. else if (!from[2] || from[2]=='/') from += 2;
  3418. else if (from[2]=='.' && (!from[3] || from[3]=='/')) {
  3419. from += 3;
  3420. while (to>zap && *--to != '/');
  3421. } else *to++ = *from++;
  3422. }
  3423. if (to == zap) to++;
  3424. if (to-zap>1 && to[-1]=='/') to--;
  3425. *to = 0;
  3426. }
  3427. // If logical chdir doesn't work, fall back to physical
  3428. if (!zap || chdir(zap)) {
  3429. free(zap);
  3430. if (chdir(dd)) return perror_msg("%s", dd);
  3431. if (!(dd = getcwd(0, 0))) dd = xstrdup("(nowhere)");
  3432. } else dd = zap;
  3433. if ((pwd = getvar("PWD"))) setvarval("OLDPWD", pwd);
  3434. setvarval("PWD", dd);
  3435. free(dd);
  3436. if (!(TT.options&OPT_cd)) {
  3437. export("OLDPWD");
  3438. export("PWD");
  3439. TT.options |= OPT_cd;
  3440. }
  3441. }
  3442. void exit_main(void)
  3443. {
  3444. exit(*toys.optargs ? atoi(*toys.optargs) : 0);
  3445. }
  3446. // lib/args.c can't +prefix & "+o history" needs space so parse cmdline here
  3447. void set_main(void)
  3448. {
  3449. char *cc, *ostr[] = {"braceexpand", "noclobber", "xtrace"};
  3450. int ii, jj, kk, oo = 0, dd = 0;
  3451. // display visible variables
  3452. if (!*toys.optargs) {
  3453. struct sh_vars **vv = visible_vars();
  3454. // TODO escape properly
  3455. for (ii = 0; vv[ii]; ii++)
  3456. if (!(vv[ii]->flags&VAR_WHITEOUT)) printf("%s\n", vv[ii]->str);
  3457. free(vv);
  3458. return;
  3459. }
  3460. // Handle options
  3461. for (ii = 0;; ii++) {
  3462. if ((cc = toys.optargs[ii]) && !(dd = stridx("-+", *cc)+1) && oo--) {
  3463. for (jj = 0; jj<ARRAY_LEN(ostr); jj++) if (!strcmp(cc, ostr[jj])) break;
  3464. if (jj != ARRAY_LEN(ostr)) {
  3465. if (dd==1) TT.options |= OPT_B<<kk;
  3466. else TT.options &= ~(OPT_B<<kk);
  3467. continue;
  3468. }
  3469. error_exit("bad -o %s", cc);
  3470. }
  3471. if (oo>0) for (jj = 0; jj<ARRAY_LEN(ostr); jj++)
  3472. printf("%s\t%s\n", ostr[jj], TT.options&(OPT_B<<jj) ? "on" : "off");
  3473. oo = 0;
  3474. if (!cc || !dd) break;
  3475. for (jj = 1; cc[jj]; jj++) {
  3476. if (cc[jj] == 'o') oo++;
  3477. else if (-1 != (kk = stridx("BCx", cc[jj]))) {
  3478. if (*cc == '-') TT.options |= OPT_B<<kk;
  3479. else TT.options &= ~(OPT_B<<kk);
  3480. } else error_exit("bad -%c", toys.optargs[ii][1]);
  3481. }
  3482. }
  3483. // handle positional parameters
  3484. if (cc) {
  3485. struct arg_list *al, **head;
  3486. struct sh_arg *arg = &TT.ff->arg;
  3487. // don't free memory that's already scheduled for deletion
  3488. for (al = *(head = &TT.ff->delete); al; al = *(head = &al->next))
  3489. if (al->arg == (void *)arg->v) break;
  3490. // free last set's memory (if any) so it doesn't accumulate in loop
  3491. if (al) for (jj = arg->c+1; jj; jj--) {
  3492. *head = al->next;
  3493. free(al->arg);
  3494. free(al);
  3495. }
  3496. while (toys.optargs[ii])
  3497. arg_add(arg, push_arg(&TT.ff->delete, strdup(toys.optargs[ii++])));
  3498. push_arg(&TT.ff->delete, arg->v);
  3499. }
  3500. }
  3501. // TODO need test: unset clears var first and stops, function only if no var.
  3502. #define FOR_unset
  3503. #include "generated/flags.h"
  3504. void unset_main(void)
  3505. {
  3506. char **arg, *s;
  3507. int ii;
  3508. for (arg = toys.optargs; *arg; arg++) {
  3509. s = varend(*arg);
  3510. if (s == *arg || *s) {
  3511. error_msg("bad '%s'", *arg);
  3512. continue;
  3513. }
  3514. // TODO -n and name reference support
  3515. // unset variable
  3516. if (!FLAG(f) && unsetvar(*arg)) continue;
  3517. // unset function TODO binary search
  3518. for (ii = 0; ii<TT.funcslen; ii++)
  3519. if (!strcmp(*arg, TT.functions[ii]->name)) break;
  3520. if (ii != TT.funcslen) {
  3521. free_function(TT.functions[ii]);
  3522. memmove(TT.functions+ii, TT.functions+ii+1, TT.funcslen+1-ii);
  3523. }
  3524. }
  3525. }
  3526. #define FOR_export
  3527. #include "generated/flags.h"
  3528. void export_main(void)
  3529. {
  3530. char **arg, *eq;
  3531. // list existing variables?
  3532. if (!toys.optc) {
  3533. struct sh_vars **vv = visible_vars();
  3534. unsigned uu;
  3535. for (uu = 0; vv[uu]; uu++) {
  3536. if ((vv[uu]->flags&(VAR_WHITEOUT|VAR_EXPORT))==VAR_EXPORT) {
  3537. xputs(eq = declarep(vv[uu]));
  3538. free(eq);
  3539. }
  3540. }
  3541. free(vv);
  3542. return;
  3543. }
  3544. // set/move variables
  3545. for (arg = toys.optargs; *arg; arg++) {
  3546. eq = varend(*arg);
  3547. if (eq == *arg || (*eq && eq[*eq=='+'] != '=')) {
  3548. error_msg("bad %s", *arg);
  3549. continue;
  3550. }
  3551. if (FLAG(n)) set_varflags(*arg, 0, VAR_EXPORT);
  3552. else export(*arg);
  3553. }
  3554. }
  3555. #define FOR_declare
  3556. #include "generated/flags.h"
  3557. void declare_main(void)
  3558. {
  3559. unsigned uu, fl = toys.optflags&(FLAG(p)-1);
  3560. char *ss, **arg;
  3561. // TODO: need a show_vars() to collate all the visible_vars() loop output
  3562. // TODO: -g support including -gp
  3563. // TODO: dump everything key=value and functions too
  3564. if (!toys.optc) {
  3565. struct sh_vars **vv = visible_vars();
  3566. for (uu = 0; vv[uu]; uu++) {
  3567. if ((vv[uu]->flags&VAR_WHITEOUT) || (fl && !(vv[uu]->flags&fl))) continue;
  3568. xputs(ss = declarep(vv[uu]));
  3569. free(ss);
  3570. }
  3571. free(vv);
  3572. } else if (FLAG(p)) for (arg = toys.optargs; *arg; arg++) {
  3573. struct sh_vars *vv = *varend(ss = *arg) ? 0 : findvar(ss, 0);
  3574. if (!vv) perror_msg("%s: not found", ss);
  3575. else {
  3576. xputs(ss = declarep(vv));
  3577. free(ss);
  3578. }
  3579. } else for (arg = toys.optargs; *arg; arg++) {
  3580. ss = varend(*arg);
  3581. if (ss == *arg || (*ss && ss[*ss=='+'] != '=')) {
  3582. error_msg("bad %s", *arg);
  3583. continue;
  3584. }
  3585. set_varflags(*arg, toys.optflags<<1, 0); // TODO +x unset
  3586. }
  3587. }
  3588. void eval_main(void)
  3589. {
  3590. char *s;
  3591. // borrow the $* expand infrastructure
  3592. call_function();
  3593. TT.ff->arg.v = toys.argv;
  3594. TT.ff->arg.c = toys.optc+1;
  3595. s = expand_one_arg("\"$*\"", SEMI_IFS, 0);
  3596. TT.ff->arg.v = TT.ff->next->arg.v;
  3597. TT.ff->arg.c = TT.ff->next->arg.c;
  3598. do_source(0, fmemopen(s, strlen(s), "r"));
  3599. free(dlist_pop(&TT.ff));
  3600. free(s);
  3601. }
  3602. #define FOR_exec
  3603. #include "generated/flags.h"
  3604. void exec_main(void)
  3605. {
  3606. char *ee[1] = {0}, **old = environ;
  3607. // discard redirects and return if nothing to exec
  3608. free(TT.pp->urd);
  3609. TT.pp->urd = 0;
  3610. if (!toys.optc) return;
  3611. // exec, handling -acl
  3612. TT.isexec = *toys.optargs;
  3613. if (FLAG(c)) environ = ee;
  3614. if (TT.exec.a || FLAG(l))
  3615. *toys.optargs = xmprintf("%s%s", FLAG(l) ? "-" : "", TT.exec.a?:TT.isexec);
  3616. sh_exec(toys.optargs);
  3617. // report error (usually ENOENT) and return
  3618. perror_msg("%s", TT.isexec);
  3619. if (*toys.optargs != TT.isexec) free(*toys.optargs);
  3620. TT.isexec = 0;
  3621. toys.exitval = 127;
  3622. environ = old;
  3623. }
  3624. // Return T.jobs index or -1 from identifier
  3625. // Note, we don't return "ambiguous job spec", we return the first hit or -1.
  3626. // TODO %% %+ %- %?ab
  3627. int find_job(char *s)
  3628. {
  3629. char *ss;
  3630. long ll = strtol(s, &ss, 10);
  3631. int i, j;
  3632. if (!TT.jobs.c) return -1;
  3633. if (!*s || (!s[1] && strchr("%+-", *s))) {
  3634. int minus, plus = find_plus_minus(&minus);
  3635. return (*s == '-') ? minus : plus;
  3636. }
  3637. // Is this a %1 numeric jobspec?
  3638. if (s != ss && !*ss)
  3639. for (i = 0; i<TT.jobs.c; i++)
  3640. if (((struct sh_process *)TT.jobs.v[i])->job == ll) return i;
  3641. // Match start of command or %?abc
  3642. for (i = 0; i<TT.jobs.c; i++) {
  3643. struct sh_process *pp = (void *)TT.jobs.v[i];
  3644. if (strstart(&s, *pp->arg.v)) return i;
  3645. if (*s != '?' || !s[1]) continue;
  3646. for (j = 0; j<pp->arg.c; j++) if (strstr(pp->arg.v[j], s+1)) return i;
  3647. }
  3648. return -1;
  3649. }
  3650. void jobs_main(void)
  3651. {
  3652. int i, j, minus, plus = find_plus_minus(&minus);
  3653. char *s;
  3654. // TODO -lnprs
  3655. for (i = 0;;i++) {
  3656. if (toys.optc) {
  3657. if (!(s = toys.optargs[i])) break;
  3658. if ((j = find_job(s+('%' == *s))) == -1) {
  3659. perror_msg("%s: no such job", s);
  3660. continue;
  3661. }
  3662. } else if ((j = i) >= TT.jobs.c) break;
  3663. s = show_job((void *)TT.jobs.v[i], is_plus_minus(i, plus, minus));
  3664. printf("%s\n", s);
  3665. free(s);
  3666. }
  3667. }
  3668. #define FOR_local
  3669. #include "generated/flags.h"
  3670. void local_main(void)
  3671. {
  3672. struct sh_fcall *ff, *ff2;
  3673. struct sh_vars *var;
  3674. char **arg, *eq;
  3675. // find local variable context
  3676. for (ff = TT.ff;; ff = ff->next) {
  3677. if (ff == TT.ff->prev) return error_msg("not in function");
  3678. if (ff->vars) break;
  3679. }
  3680. // list existing vars (todo:
  3681. if (!toys.optc) {
  3682. for (var = ff->vars; var; var++) xputs(var->str); // TODO escape
  3683. return;
  3684. }
  3685. // set/move variables
  3686. for (arg = toys.optargs; *arg; arg++) {
  3687. if ((eq = varend(*arg)) == *arg || (*eq && *eq != '=')) {
  3688. error_msg("bad %s", *arg);
  3689. continue;
  3690. }
  3691. if ((var = findvar(*arg, &ff2)) && ff == ff2 && !*eq) continue;
  3692. if (var && (var->flags&VAR_READONLY)) {
  3693. error_msg("%.*s: readonly variable", (int)(varend(*arg)-*arg), *arg);
  3694. continue;
  3695. }
  3696. // Add local inheriting global status and setting whiteout if blank.
  3697. if (!var || ff!=ff2) {
  3698. int flags = var ? var->flags&VAR_EXPORT : 0;
  3699. var = addvar(xmprintf("%s%s", *arg, *eq ? "" : "="), ff);
  3700. var->flags = flags|(VAR_WHITEOUT*!*eq);
  3701. }
  3702. // TODO accept declare options to set more flags
  3703. // TODO, integer, uppercase take effect. Setvar?
  3704. }
  3705. }
  3706. void shift_main(void)
  3707. {
  3708. long long by = 1;
  3709. if (toys.optc) by = atolx(*toys.optargs);
  3710. by += TT.ff->shift;
  3711. if (by<0 || by>=TT.ff->arg.c) toys.exitval++;
  3712. else TT.ff->shift = by;
  3713. }
  3714. void source_main(void)
  3715. {
  3716. char *name = *toys.optargs;
  3717. FILE *ff = fpathopen(name);
  3718. if (!ff) return perror_msg_raw(name);
  3719. // $0 is shell name, not source file name while running this
  3720. // TODO add tests: sh -c "source input four five" one two three
  3721. *toys.optargs = *toys.argv;
  3722. ++TT.srclvl;
  3723. call_function();
  3724. TT.ff->arg.v = toys.optargs;
  3725. TT.ff->arg.c = toys.optc;
  3726. do_source(name, ff);
  3727. free(dlist_pop(&TT.ff));
  3728. --TT.srclvl;
  3729. }
  3730. #define FOR_wait
  3731. #include "generated/flags.h"
  3732. void wait_main(void)
  3733. {
  3734. struct sh_process *pp;
  3735. int ii, jj;
  3736. long long ll;
  3737. char *s;
  3738. // TODO does -o pipefail affect return code here
  3739. if (FLAG(n)) toys.exitval = free_process(wait_job(-1, 0));
  3740. else if (!toys.optc) while (TT.jobs.c) {
  3741. if (!(pp = wait_job(-1, 0))) break;
  3742. } else for (ii = 0; ii<toys.optc; ii++) {
  3743. ll = estrtol(toys.optargs[ii], &s, 10);
  3744. if (errno || *s) {
  3745. if (-1 == (jj = find_job(toys.optargs[ii]))) {
  3746. error_msg("%s: bad pid/job", toys.optargs[ii]);
  3747. continue;
  3748. }
  3749. ll = ((struct sh_process *)TT.jobs.v[jj])->pid;
  3750. }
  3751. if (!(pp = wait_job(ll, 0))) {
  3752. if (toys.signal) toys.exitval = 128+toys.signal;
  3753. break;
  3754. }
  3755. toys.exitval = free_process(pp);
  3756. }
  3757. }