Process.cpp 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Demangle.h>
  27. #include <AK/RefPtr.h>
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/Time.h>
  32. #include <AK/Types.h>
  33. #include <Kernel/ACPI/Parser.h>
  34. #include <Kernel/Arch/i386/CPU.h>
  35. #include <Kernel/Console.h>
  36. #include <Kernel/Devices/BlockDevice.h>
  37. #include <Kernel/Devices/KeyboardDevice.h>
  38. #include <Kernel/Devices/NullDevice.h>
  39. #include <Kernel/Devices/PCSpeaker.h>
  40. #include <Kernel/Devices/RandomDevice.h>
  41. #include <Kernel/FileSystem/Custody.h>
  42. #include <Kernel/FileSystem/DevPtsFS.h>
  43. #include <Kernel/FileSystem/Ext2FileSystem.h>
  44. #include <Kernel/FileSystem/FIFO.h>
  45. #include <Kernel/FileSystem/FileDescription.h>
  46. #include <Kernel/FileSystem/InodeWatcher.h>
  47. #include <Kernel/FileSystem/ProcFS.h>
  48. #include <Kernel/FileSystem/TmpFS.h>
  49. #include <Kernel/FileSystem/VirtualFileSystem.h>
  50. #include <Kernel/Heap/kmalloc.h>
  51. #include <Kernel/IO.h>
  52. #include <Kernel/KBufferBuilder.h>
  53. #include <Kernel/KSyms.h>
  54. #include <Kernel/Module.h>
  55. #include <Kernel/Multiboot.h>
  56. #include <Kernel/Net/Socket.h>
  57. #include <Kernel/PerformanceEventBuffer.h>
  58. #include <Kernel/Process.h>
  59. #include <Kernel/Profiling.h>
  60. #include <Kernel/Ptrace.h>
  61. #include <Kernel/RTC.h>
  62. #include <Kernel/Random.h>
  63. #include <Kernel/Scheduler.h>
  64. #include <Kernel/SharedBuffer.h>
  65. #include <Kernel/StdLib.h>
  66. #include <Kernel/Syscall.h>
  67. #include <Kernel/TTY/MasterPTY.h>
  68. #include <Kernel/TTY/TTY.h>
  69. #include <Kernel/Thread.h>
  70. #include <Kernel/ThreadTracer.h>
  71. #include <Kernel/Time/TimeManagement.h>
  72. #include <Kernel/VM/PageDirectory.h>
  73. #include <Kernel/VM/PrivateInodeVMObject.h>
  74. #include <Kernel/VM/ProcessPagingScope.h>
  75. #include <Kernel/VM/PurgeableVMObject.h>
  76. #include <Kernel/VM/SharedInodeVMObject.h>
  77. #include <LibC/errno_numbers.h>
  78. #include <LibC/limits.h>
  79. #include <LibC/signal_numbers.h>
  80. #include <LibELF/Loader.h>
  81. #include <LibELF/Validation.h>
  82. //#define PROCESS_DEBUG
  83. //#define DEBUG_POLL_SELECT
  84. //#define DEBUG_IO
  85. //#define TASK_DEBUG
  86. //#define FORK_DEBUG
  87. //#define EXEC_DEBUG
  88. //#define SIGNAL_DEBUG
  89. //#define SHARED_BUFFER_DEBUG
  90. namespace Kernel {
  91. static void create_signal_trampolines();
  92. Process* Process::current;
  93. static pid_t next_pid;
  94. InlineLinkedList<Process>* g_processes;
  95. static String* s_hostname;
  96. static Lock* s_hostname_lock;
  97. VirtualAddress g_return_to_ring3_from_signal_trampoline;
  98. HashMap<String, OwnPtr<Module>>* g_modules;
  99. pid_t Process::allocate_pid()
  100. {
  101. InterruptDisabler disabler;
  102. return next_pid++;
  103. }
  104. void Process::initialize()
  105. {
  106. g_modules = new HashMap<String, OwnPtr<Module>>;
  107. next_pid = 0;
  108. g_processes = new InlineLinkedList<Process>;
  109. s_hostname = new String("courage");
  110. s_hostname_lock = new Lock;
  111. create_signal_trampolines();
  112. }
  113. Vector<pid_t> Process::all_pids()
  114. {
  115. Vector<pid_t> pids;
  116. InterruptDisabler disabler;
  117. pids.ensure_capacity((int)g_processes->size_slow());
  118. for (auto& process : *g_processes)
  119. pids.append(process.pid());
  120. return pids;
  121. }
  122. Vector<Process*> Process::all_processes()
  123. {
  124. Vector<Process*> processes;
  125. InterruptDisabler disabler;
  126. processes.ensure_capacity((int)g_processes->size_slow());
  127. for (auto& process : *g_processes)
  128. processes.append(&process);
  129. return processes;
  130. }
  131. bool Process::in_group(gid_t gid) const
  132. {
  133. return m_gid == gid || m_extra_gids.contains(gid);
  134. }
  135. Range Process::allocate_range(VirtualAddress vaddr, size_t size, size_t alignment)
  136. {
  137. vaddr.mask(PAGE_MASK);
  138. size = PAGE_ROUND_UP(size);
  139. if (vaddr.is_null())
  140. return page_directory().range_allocator().allocate_anywhere(size, alignment);
  141. return page_directory().range_allocator().allocate_specific(vaddr, size);
  142. }
  143. static unsigned prot_to_region_access_flags(int prot)
  144. {
  145. unsigned access = 0;
  146. if (prot & PROT_READ)
  147. access |= Region::Access::Read;
  148. if (prot & PROT_WRITE)
  149. access |= Region::Access::Write;
  150. if (prot & PROT_EXEC)
  151. access |= Region::Access::Execute;
  152. return access;
  153. }
  154. Region& Process::allocate_split_region(const Region& source_region, const Range& range, size_t offset_in_vmobject)
  155. {
  156. auto& region = add_region(Region::create_user_accessible(range, source_region.vmobject(), offset_in_vmobject, source_region.name(), source_region.access()));
  157. region.set_mmap(source_region.is_mmap());
  158. region.set_stack(source_region.is_stack());
  159. size_t page_offset_in_source_region = (offset_in_vmobject - source_region.offset_in_vmobject()) / PAGE_SIZE;
  160. for (size_t i = 0; i < region.page_count(); ++i) {
  161. if (source_region.should_cow(page_offset_in_source_region + i))
  162. region.set_should_cow(i, true);
  163. }
  164. return region;
  165. }
  166. Region* Process::allocate_region(const Range& range, const String& name, int prot, bool should_commit)
  167. {
  168. ASSERT(range.is_valid());
  169. auto vmobject = AnonymousVMObject::create_with_size(range.size());
  170. auto region = Region::create_user_accessible(range, vmobject, 0, name, prot_to_region_access_flags(prot));
  171. region->map(page_directory());
  172. if (should_commit && !region->commit())
  173. return nullptr;
  174. return &add_region(move(region));
  175. }
  176. Region* Process::allocate_region(VirtualAddress vaddr, size_t size, const String& name, int prot, bool should_commit)
  177. {
  178. auto range = allocate_range(vaddr, size);
  179. if (!range.is_valid())
  180. return nullptr;
  181. return allocate_region(range, name, prot, should_commit);
  182. }
  183. Region* Process::allocate_region_with_vmobject(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, int prot)
  184. {
  185. ASSERT(range.is_valid());
  186. size_t end_in_vmobject = offset_in_vmobject + range.size();
  187. if (end_in_vmobject <= offset_in_vmobject) {
  188. dbg() << "allocate_region_with_vmobject: Overflow (offset + size)";
  189. return nullptr;
  190. }
  191. if (offset_in_vmobject >= vmobject->size()) {
  192. dbg() << "allocate_region_with_vmobject: Attempt to allocate a region with an offset past the end of its VMObject.";
  193. return nullptr;
  194. }
  195. if (end_in_vmobject > vmobject->size()) {
  196. dbg() << "allocate_region_with_vmobject: Attempt to allocate a region with an end past the end of its VMObject.";
  197. return nullptr;
  198. }
  199. offset_in_vmobject &= PAGE_MASK;
  200. auto& region = add_region(Region::create_user_accessible(range, move(vmobject), offset_in_vmobject, name, prot_to_region_access_flags(prot)));
  201. region.map(page_directory());
  202. return &region;
  203. }
  204. Region* Process::allocate_region_with_vmobject(VirtualAddress vaddr, size_t size, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, int prot)
  205. {
  206. auto range = allocate_range(vaddr, size);
  207. if (!range.is_valid())
  208. return nullptr;
  209. return allocate_region_with_vmobject(range, move(vmobject), offset_in_vmobject, name, prot);
  210. }
  211. bool Process::deallocate_region(Region& region)
  212. {
  213. InterruptDisabler disabler;
  214. if (m_region_lookup_cache.region == &region)
  215. m_region_lookup_cache.region = nullptr;
  216. for (size_t i = 0; i < m_regions.size(); ++i) {
  217. if (&m_regions[i] == &region) {
  218. m_regions.unstable_remove(i);
  219. return true;
  220. }
  221. }
  222. return false;
  223. }
  224. Region* Process::region_from_range(const Range& range)
  225. {
  226. if (m_region_lookup_cache.range == range && m_region_lookup_cache.region)
  227. return m_region_lookup_cache.region;
  228. size_t size = PAGE_ROUND_UP(range.size());
  229. for (auto& region : m_regions) {
  230. if (region.vaddr() == range.base() && region.size() == size) {
  231. m_region_lookup_cache.range = range;
  232. m_region_lookup_cache.region = region.make_weak_ptr();
  233. return &region;
  234. }
  235. }
  236. return nullptr;
  237. }
  238. Region* Process::region_containing(const Range& range)
  239. {
  240. for (auto& region : m_regions) {
  241. if (region.contains(range))
  242. return &region;
  243. }
  244. return nullptr;
  245. }
  246. int Process::sys$set_mmap_name(const Syscall::SC_set_mmap_name_params* user_params)
  247. {
  248. REQUIRE_PROMISE(stdio);
  249. Syscall::SC_set_mmap_name_params params;
  250. if (!validate_read_and_copy_typed(&params, user_params))
  251. return -EFAULT;
  252. if (params.name.length > PATH_MAX)
  253. return -ENAMETOOLONG;
  254. auto name = validate_and_copy_string_from_user(params.name);
  255. if (name.is_null())
  256. return -EFAULT;
  257. auto* region = region_from_range({ VirtualAddress(params.addr), params.size });
  258. if (!region)
  259. return -EINVAL;
  260. if (!region->is_mmap())
  261. return -EPERM;
  262. region->set_name(name);
  263. return 0;
  264. }
  265. static bool validate_mmap_prot(int prot, bool map_stack)
  266. {
  267. bool readable = prot & PROT_READ;
  268. bool writable = prot & PROT_WRITE;
  269. bool executable = prot & PROT_EXEC;
  270. if (writable && executable)
  271. return false;
  272. if (map_stack) {
  273. if (executable)
  274. return false;
  275. if (!readable || !writable)
  276. return false;
  277. }
  278. return true;
  279. }
  280. static bool validate_inode_mmap_prot(const Process& process, int prot, const Inode& inode, bool map_shared)
  281. {
  282. auto metadata = inode.metadata();
  283. if ((prot & PROT_READ) && !metadata.may_read(process))
  284. return false;
  285. if (map_shared) {
  286. // FIXME: What about readonly filesystem mounts? We cannot make a
  287. // decision here without knowing the mount flags, so we would need to
  288. // keep a Custody or something from mmap time.
  289. if ((prot & PROT_WRITE) && !metadata.may_write(process))
  290. return false;
  291. InterruptDisabler disabler;
  292. if (inode.shared_vmobject()) {
  293. if ((prot & PROT_EXEC) && inode.shared_vmobject()->writable_mappings())
  294. return false;
  295. if ((prot & PROT_WRITE) && inode.shared_vmobject()->executable_mappings())
  296. return false;
  297. }
  298. }
  299. return true;
  300. }
  301. // Carve out a virtual address range from a region and return the two regions on either side
  302. Vector<Region*, 2> Process::split_region_around_range(const Region& source_region, const Range& desired_range)
  303. {
  304. Range old_region_range = source_region.range();
  305. auto remaining_ranges_after_unmap = old_region_range.carve(desired_range);
  306. ASSERT(!remaining_ranges_after_unmap.is_empty());
  307. auto make_replacement_region = [&](const Range& new_range) -> Region& {
  308. ASSERT(old_region_range.contains(new_range));
  309. size_t new_range_offset_in_vmobject = source_region.offset_in_vmobject() + (new_range.base().get() - old_region_range.base().get());
  310. return allocate_split_region(source_region, new_range, new_range_offset_in_vmobject);
  311. };
  312. Vector<Region*, 2> new_regions;
  313. for (auto& new_range : remaining_ranges_after_unmap) {
  314. new_regions.unchecked_append(&make_replacement_region(new_range));
  315. }
  316. return new_regions;
  317. }
  318. void* Process::sys$mmap(const Syscall::SC_mmap_params* user_params)
  319. {
  320. REQUIRE_PROMISE(stdio);
  321. Syscall::SC_mmap_params params;
  322. if (!validate_read_and_copy_typed(&params, user_params))
  323. return (void*)-EFAULT;
  324. void* addr = (void*)params.addr;
  325. size_t size = params.size;
  326. size_t alignment = params.alignment;
  327. int prot = params.prot;
  328. int flags = params.flags;
  329. int fd = params.fd;
  330. int offset = params.offset;
  331. if (alignment & ~PAGE_MASK)
  332. return (void*)-EINVAL;
  333. if (!is_user_range(VirtualAddress(addr), size))
  334. return (void*)-EFAULT;
  335. String name;
  336. if (params.name.characters) {
  337. if (params.name.length > PATH_MAX)
  338. return (void*)-ENAMETOOLONG;
  339. name = validate_and_copy_string_from_user(params.name);
  340. if (name.is_null())
  341. return (void*)-EFAULT;
  342. }
  343. if (size == 0)
  344. return (void*)-EINVAL;
  345. if ((FlatPtr)addr & ~PAGE_MASK)
  346. return (void*)-EINVAL;
  347. bool map_shared = flags & MAP_SHARED;
  348. bool map_anonymous = flags & MAP_ANONYMOUS;
  349. bool map_purgeable = flags & MAP_PURGEABLE;
  350. bool map_private = flags & MAP_PRIVATE;
  351. bool map_stack = flags & MAP_STACK;
  352. bool map_fixed = flags & MAP_FIXED;
  353. if (map_shared && map_private)
  354. return (void*)-EINVAL;
  355. if (!map_shared && !map_private)
  356. return (void*)-EINVAL;
  357. if (!validate_mmap_prot(prot, map_stack))
  358. return (void*)-EINVAL;
  359. if (map_stack && (!map_private || !map_anonymous))
  360. return (void*)-EINVAL;
  361. Region* region = nullptr;
  362. auto range = allocate_range(VirtualAddress(addr), size, alignment);
  363. if (!range.is_valid())
  364. return (void*)-ENOMEM;
  365. if (map_purgeable) {
  366. auto vmobject = PurgeableVMObject::create_with_size(size);
  367. region = allocate_region_with_vmobject(range, vmobject, 0, !name.is_null() ? name : "mmap (purgeable)", prot);
  368. if (!region && (!map_fixed && addr != 0))
  369. region = allocate_region_with_vmobject({}, size, vmobject, 0, !name.is_null() ? name : "mmap (purgeable)", prot);
  370. } else if (map_anonymous) {
  371. region = allocate_region(range, !name.is_null() ? name : "mmap", prot, false);
  372. if (!region && (!map_fixed && addr != 0))
  373. region = allocate_region(allocate_range({}, size), !name.is_null() ? name : "mmap", prot, false);
  374. } else {
  375. if (offset < 0)
  376. return (void*)-EINVAL;
  377. if (static_cast<size_t>(offset) & ~PAGE_MASK)
  378. return (void*)-EINVAL;
  379. auto description = file_description(fd);
  380. if (!description)
  381. return (void*)-EBADF;
  382. if (description->is_directory())
  383. return (void*)-ENODEV;
  384. // Require read access even when read protection is not requested.
  385. if (!description->is_readable())
  386. return (void*)-EACCES;
  387. if (map_shared) {
  388. if ((prot & PROT_WRITE) && !description->is_writable())
  389. return (void*)-EACCES;
  390. }
  391. if (description->inode()) {
  392. if (!validate_inode_mmap_prot(*this, prot, *description->inode(), map_shared))
  393. return (void*)-EACCES;
  394. }
  395. auto region_or_error = description->mmap(*this, VirtualAddress(addr), static_cast<size_t>(offset), size, prot, map_shared);
  396. if (region_or_error.is_error()) {
  397. // Fail if MAP_FIXED or address is 0, retry otherwise
  398. if (map_fixed || addr == 0)
  399. return (void*)(int)region_or_error.error();
  400. region_or_error = description->mmap(*this, {}, static_cast<size_t>(offset), size, prot, map_shared);
  401. }
  402. if (region_or_error.is_error())
  403. return (void*)(int)region_or_error.error();
  404. region = region_or_error.value();
  405. }
  406. if (!region)
  407. return (void*)-ENOMEM;
  408. region->set_mmap(true);
  409. if (map_shared)
  410. region->set_shared(true);
  411. if (map_stack)
  412. region->set_stack(true);
  413. if (!name.is_null())
  414. region->set_name(name);
  415. return region->vaddr().as_ptr();
  416. }
  417. int Process::sys$munmap(void* addr, size_t size)
  418. {
  419. REQUIRE_PROMISE(stdio);
  420. if (!size)
  421. return -EINVAL;
  422. if (!is_user_range(VirtualAddress(addr), size))
  423. return -EFAULT;
  424. Range range_to_unmap { VirtualAddress(addr), size };
  425. if (auto* whole_region = region_from_range(range_to_unmap)) {
  426. if (!whole_region->is_mmap())
  427. return -EPERM;
  428. bool success = deallocate_region(*whole_region);
  429. ASSERT(success);
  430. return 0;
  431. }
  432. if (auto* old_region = region_containing(range_to_unmap)) {
  433. if (!old_region->is_mmap())
  434. return -EPERM;
  435. auto new_regions = split_region_around_range(*old_region, range_to_unmap);
  436. // We manually unmap the old region here, specifying that we *don't* want the VM deallocated.
  437. old_region->unmap(Region::ShouldDeallocateVirtualMemoryRange::No);
  438. deallocate_region(*old_region);
  439. // Instead we give back the unwanted VM manually.
  440. page_directory().range_allocator().deallocate(range_to_unmap);
  441. // And finally we map the new region(s) using our page directory (they were just allocated and don't have one).
  442. for (auto* new_region : new_regions) {
  443. new_region->map(page_directory());
  444. }
  445. return 0;
  446. }
  447. // FIXME: We should also support munmap() across multiple regions. (#175)
  448. return -EINVAL;
  449. }
  450. int Process::sys$mprotect(void* addr, size_t size, int prot)
  451. {
  452. REQUIRE_PROMISE(stdio);
  453. if (!size)
  454. return -EINVAL;
  455. if (!is_user_range(VirtualAddress(addr), size))
  456. return -EFAULT;
  457. Range range_to_mprotect = { VirtualAddress(addr), size };
  458. if (auto* whole_region = region_from_range(range_to_mprotect)) {
  459. if (!whole_region->is_mmap())
  460. return -EPERM;
  461. if (!validate_mmap_prot(prot, whole_region->is_stack()))
  462. return -EINVAL;
  463. if (whole_region->access() == prot_to_region_access_flags(prot))
  464. return 0;
  465. if (whole_region->vmobject().is_inode()
  466. && !validate_inode_mmap_prot(*this, prot, static_cast<const InodeVMObject&>(whole_region->vmobject()).inode(), whole_region->is_shared())) {
  467. return -EACCES;
  468. }
  469. whole_region->set_readable(prot & PROT_READ);
  470. whole_region->set_writable(prot & PROT_WRITE);
  471. whole_region->set_executable(prot & PROT_EXEC);
  472. whole_region->remap();
  473. return 0;
  474. }
  475. // Check if we can carve out the desired range from an existing region
  476. if (auto* old_region = region_containing(range_to_mprotect)) {
  477. if (!old_region->is_mmap())
  478. return -EPERM;
  479. if (!validate_mmap_prot(prot, old_region->is_stack()))
  480. return -EINVAL;
  481. if (old_region->access() == prot_to_region_access_flags(prot))
  482. return 0;
  483. if (old_region->vmobject().is_inode()
  484. && !validate_inode_mmap_prot(*this, prot, static_cast<const InodeVMObject&>(old_region->vmobject()).inode(), old_region->is_shared())) {
  485. return -EACCES;
  486. }
  487. // This vector is the region(s) adjacent to our range.
  488. // We need to allocate a new region for the range we wanted to change permission bits on.
  489. auto adjacent_regions = split_region_around_range(*old_region, range_to_mprotect);
  490. size_t new_range_offset_in_vmobject = old_region->offset_in_vmobject() + (range_to_mprotect.base().get() - old_region->range().base().get());
  491. auto& new_region = allocate_split_region(*old_region, range_to_mprotect, new_range_offset_in_vmobject);
  492. new_region.set_readable(prot & PROT_READ);
  493. new_region.set_writable(prot & PROT_WRITE);
  494. new_region.set_executable(prot & PROT_EXEC);
  495. // Unmap the old region here, specifying that we *don't* want the VM deallocated.
  496. old_region->unmap(Region::ShouldDeallocateVirtualMemoryRange::No);
  497. deallocate_region(*old_region);
  498. // Map the new regions using our page directory (they were just allocated and don't have one).
  499. for (auto* adjacent_region : adjacent_regions) {
  500. adjacent_region->map(page_directory());
  501. }
  502. new_region.map(page_directory());
  503. return 0;
  504. }
  505. // FIXME: We should also support mprotect() across multiple regions. (#175) (#964)
  506. return -EINVAL;
  507. }
  508. int Process::sys$madvise(void* address, size_t size, int advice)
  509. {
  510. REQUIRE_PROMISE(stdio);
  511. if (!size)
  512. return -EINVAL;
  513. if (!is_user_range(VirtualAddress(address), size))
  514. return -EFAULT;
  515. auto* region = region_from_range({ VirtualAddress(address), size });
  516. if (!region)
  517. return -EINVAL;
  518. if (!region->is_mmap())
  519. return -EPERM;
  520. if ((advice & MADV_SET_VOLATILE) && (advice & MADV_SET_NONVOLATILE))
  521. return -EINVAL;
  522. if (advice & MADV_SET_VOLATILE) {
  523. if (!region->vmobject().is_purgeable())
  524. return -EPERM;
  525. auto& vmobject = static_cast<PurgeableVMObject&>(region->vmobject());
  526. vmobject.set_volatile(true);
  527. return 0;
  528. }
  529. if (advice & MADV_SET_NONVOLATILE) {
  530. if (!region->vmobject().is_purgeable())
  531. return -EPERM;
  532. auto& vmobject = static_cast<PurgeableVMObject&>(region->vmobject());
  533. if (!vmobject.is_volatile())
  534. return 0;
  535. vmobject.set_volatile(false);
  536. bool was_purged = vmobject.was_purged();
  537. vmobject.set_was_purged(false);
  538. return was_purged ? 1 : 0;
  539. }
  540. if (advice & MADV_GET_VOLATILE) {
  541. if (!region->vmobject().is_purgeable())
  542. return -EPERM;
  543. auto& vmobject = static_cast<PurgeableVMObject&>(region->vmobject());
  544. return vmobject.is_volatile() ? 0 : 1;
  545. }
  546. return -EINVAL;
  547. }
  548. int Process::sys$minherit(void* address, size_t size, int inherit)
  549. {
  550. REQUIRE_PROMISE(stdio);
  551. auto* region = region_from_range({ VirtualAddress(address), size });
  552. if (!region)
  553. return -EINVAL;
  554. if (!region->is_mmap())
  555. return -EINVAL;
  556. if (region->is_shared())
  557. return -EINVAL;
  558. if (!region->vmobject().is_anonymous())
  559. return -EINVAL;
  560. switch (inherit) {
  561. case MAP_INHERIT_ZERO:
  562. region->set_inherit_mode(Region::InheritMode::ZeroedOnFork);
  563. return 0;
  564. }
  565. return -EINVAL;
  566. }
  567. int Process::sys$purge(int mode)
  568. {
  569. REQUIRE_NO_PROMISES;
  570. if (!is_superuser())
  571. return -EPERM;
  572. int purged_page_count = 0;
  573. if (mode & PURGE_ALL_VOLATILE) {
  574. NonnullRefPtrVector<PurgeableVMObject> vmobjects;
  575. {
  576. InterruptDisabler disabler;
  577. MM.for_each_vmobject_of_type<PurgeableVMObject>([&](auto& vmobject) {
  578. vmobjects.append(vmobject);
  579. return IterationDecision::Continue;
  580. });
  581. }
  582. for (auto& vmobject : vmobjects) {
  583. purged_page_count += vmobject.purge();
  584. }
  585. }
  586. if (mode & PURGE_ALL_CLEAN_INODE) {
  587. NonnullRefPtrVector<InodeVMObject> vmobjects;
  588. {
  589. InterruptDisabler disabler;
  590. MM.for_each_vmobject_of_type<InodeVMObject>([&](auto& vmobject) {
  591. vmobjects.append(vmobject);
  592. return IterationDecision::Continue;
  593. });
  594. }
  595. for (auto& vmobject : vmobjects) {
  596. purged_page_count += vmobject.release_all_clean_pages();
  597. }
  598. }
  599. return purged_page_count;
  600. }
  601. int Process::sys$gethostname(char* buffer, ssize_t size)
  602. {
  603. REQUIRE_PROMISE(stdio);
  604. if (size < 0)
  605. return -EINVAL;
  606. if (!validate_write(buffer, size))
  607. return -EFAULT;
  608. LOCKER(*s_hostname_lock, Lock::Mode::Shared);
  609. if ((size_t)size < (s_hostname->length() + 1))
  610. return -ENAMETOOLONG;
  611. copy_to_user(buffer, s_hostname->characters(), s_hostname->length() + 1);
  612. return 0;
  613. }
  614. int Process::sys$sethostname(const char* hostname, ssize_t length)
  615. {
  616. REQUIRE_NO_PROMISES;
  617. if (!is_superuser())
  618. return -EPERM;
  619. if (length < 0)
  620. return -EINVAL;
  621. LOCKER(*s_hostname_lock, Lock::Mode::Exclusive);
  622. if (length > 64)
  623. return -ENAMETOOLONG;
  624. *s_hostname = validate_and_copy_string_from_user(hostname, length);
  625. return 0;
  626. }
  627. pid_t Process::sys$fork(RegisterState& regs)
  628. {
  629. REQUIRE_PROMISE(proc);
  630. Thread* child_first_thread = nullptr;
  631. auto* child = new Process(child_first_thread, m_name, m_uid, m_gid, m_pid, m_ring, m_cwd, m_executable, m_tty, this);
  632. child->m_root_directory = m_root_directory;
  633. child->m_root_directory_relative_to_global_root = m_root_directory_relative_to_global_root;
  634. child->m_promises = m_promises;
  635. child->m_execpromises = m_execpromises;
  636. child->m_veil_state = m_veil_state;
  637. child->m_unveiled_paths = m_unveiled_paths;
  638. child->m_fds = m_fds;
  639. child->m_sid = m_sid;
  640. child->m_pgid = m_pgid;
  641. child->m_umask = m_umask;
  642. #ifdef FORK_DEBUG
  643. dbg() << "fork: child=" << child;
  644. #endif
  645. for (auto& region : m_regions) {
  646. #ifdef FORK_DEBUG
  647. dbg() << "fork: cloning Region{" << &region << "} '" << region.name() << "' @ " << region.vaddr();
  648. #endif
  649. auto& child_region = child->add_region(region.clone());
  650. child_region.map(child->page_directory());
  651. if (&region == m_master_tls_region)
  652. child->m_master_tls_region = child_region.make_weak_ptr();
  653. }
  654. child->m_extra_gids = m_extra_gids;
  655. auto& child_tss = child_first_thread->m_tss;
  656. child_tss.eax = 0; // fork() returns 0 in the child :^)
  657. child_tss.ebx = regs.ebx;
  658. child_tss.ecx = regs.ecx;
  659. child_tss.edx = regs.edx;
  660. child_tss.ebp = regs.ebp;
  661. child_tss.esp = regs.userspace_esp;
  662. child_tss.esi = regs.esi;
  663. child_tss.edi = regs.edi;
  664. child_tss.eflags = regs.eflags;
  665. child_tss.eip = regs.eip;
  666. child_tss.cs = regs.cs;
  667. child_tss.ds = regs.ds;
  668. child_tss.es = regs.es;
  669. child_tss.fs = regs.fs;
  670. child_tss.gs = regs.gs;
  671. child_tss.ss = regs.userspace_ss;
  672. #ifdef FORK_DEBUG
  673. dbg() << "fork: child will begin executing at " << String::format("%w", child_tss.cs) << ":" << String::format("%x", child_tss.eip) << " with stack " << String::format("%w", child_tss.ss) << ":" << String::format("%x", child_tss.esp) << ", kstack " << String::format("%w", child_tss.ss0) << ":" << String::format("%x", child_tss.esp0);
  674. #endif
  675. {
  676. InterruptDisabler disabler;
  677. g_processes->prepend(child);
  678. }
  679. #ifdef TASK_DEBUG
  680. klog() << "Process " << child->pid() << " (" << child->name().characters() << ") forked from " << m_pid << " @ " << String::format("%p", child_tss.eip);
  681. #endif
  682. child_first_thread->set_state(Thread::State::Skip1SchedulerPass);
  683. return child->pid();
  684. }
  685. void Process::kill_threads_except_self()
  686. {
  687. InterruptDisabler disabler;
  688. if (m_thread_count <= 1)
  689. return;
  690. for_each_thread([&](Thread& thread) {
  691. if (&thread == Thread::current
  692. || thread.state() == Thread::State::Dead
  693. || thread.state() == Thread::State::Dying)
  694. return IterationDecision::Continue;
  695. // At this point, we have no joiner anymore
  696. thread.m_joiner = nullptr;
  697. thread.set_should_die();
  698. if (thread.state() != Thread::State::Dead)
  699. thread.set_state(Thread::State::Dying);
  700. return IterationDecision::Continue;
  701. });
  702. big_lock().clear_waiters();
  703. }
  704. void Process::kill_all_threads()
  705. {
  706. for_each_thread([&](Thread& thread) {
  707. thread.set_should_die();
  708. return IterationDecision::Continue;
  709. });
  710. }
  711. int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Vector<String> arguments, Vector<String> environment, RefPtr<FileDescription> interpreter_description)
  712. {
  713. ASSERT(is_ring3());
  714. auto path = main_program_description->absolute_path();
  715. dbg() << "do_exec(" << path << ")";
  716. size_t total_blob_size = 0;
  717. for (auto& a : arguments)
  718. total_blob_size += a.length() + 1;
  719. for (auto& e : environment)
  720. total_blob_size += e.length() + 1;
  721. size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1);
  722. // FIXME: How much stack space does process startup need?
  723. if ((total_blob_size + total_meta_size) >= Thread::default_userspace_stack_size)
  724. return -E2BIG;
  725. auto parts = path.split('/');
  726. if (parts.is_empty())
  727. return -ENOENT;
  728. auto& inode = interpreter_description ? *interpreter_description->inode() : *main_program_description->inode();
  729. auto vmobject = SharedInodeVMObject::create_with_inode(inode);
  730. if (static_cast<const SharedInodeVMObject&>(*vmobject).writable_mappings()) {
  731. dbg() << "Refusing to execute a write-mapped program";
  732. return -ETXTBSY;
  733. }
  734. // Disable profiling temporarily in case it's running on this process.
  735. bool was_profiling = is_profiling();
  736. TemporaryChange profiling_disabler(m_profiling, false);
  737. // Mark this thread as the current thread that does exec
  738. // No other thread from this process will be scheduled to run
  739. m_exec_tid = Thread::current->tid();
  740. auto old_page_directory = move(m_page_directory);
  741. auto old_regions = move(m_regions);
  742. m_page_directory = PageDirectory::create_for_userspace(*this);
  743. #ifdef MM_DEBUG
  744. dbg() << "Process " << pid() << " exec: PD=" << m_page_directory.ptr() << " created";
  745. #endif
  746. InodeMetadata loader_metadata;
  747. // FIXME: Hoooo boy this is a hack if I ever saw one.
  748. // This is the 'random' offset we're giving to our ET_DYN exectuables to start as.
  749. // It also happens to be the static Virtual Addresss offset every static exectuable gets :)
  750. // Without this, some assumptions by the ELF loading hooks below are severely broken.
  751. // 0x08000000 is a verified random number chosen by random dice roll https://xkcd.com/221/
  752. u32 totally_random_offset = interpreter_description ? 0x08000000 : 0;
  753. // FIXME: We should be able to load both the PT_INTERP interpreter and the main program... once the RTLD is smart enough
  754. if (interpreter_description) {
  755. loader_metadata = interpreter_description->metadata();
  756. // we don't need the interpreter file desciption after we've loaded (or not) it into memory
  757. interpreter_description = nullptr;
  758. } else {
  759. loader_metadata = main_program_description->metadata();
  760. }
  761. auto region = MM.allocate_kernel_region_with_vmobject(*vmobject, PAGE_ROUND_UP(loader_metadata.size), "ELF loading", Region::Access::Read);
  762. if (!region)
  763. return -ENOMEM;
  764. Region* master_tls_region { nullptr };
  765. size_t master_tls_size = 0;
  766. size_t master_tls_alignment = 0;
  767. u32 entry_eip = 0;
  768. MM.enter_process_paging_scope(*this);
  769. RefPtr<ELF::Loader> loader;
  770. {
  771. ArmedScopeGuard rollback_regions_guard([&]() {
  772. ASSERT(Process::current == this);
  773. m_page_directory = move(old_page_directory);
  774. m_regions = move(old_regions);
  775. MM.enter_process_paging_scope(*this);
  776. });
  777. loader = ELF::Loader::create(region->vaddr().as_ptr(), loader_metadata.size);
  778. // Load the correct executable -- either interp or main program.
  779. // FIXME: Once we actually load both interp and main, we'll need to be more clever about this.
  780. // In that case, both will be ET_DYN objects, so they'll both be completely relocatable.
  781. // That means, we can put them literally anywhere in User VM space (ASLR anyone?).
  782. // ALSO FIXME: Reminder to really really fix that 'totally random offset' business.
  783. loader->map_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable, bool is_executable, const String& name) -> u8* {
  784. ASSERT(size);
  785. ASSERT(alignment == PAGE_SIZE);
  786. int prot = 0;
  787. if (is_readable)
  788. prot |= PROT_READ;
  789. if (is_writable)
  790. prot |= PROT_WRITE;
  791. if (is_executable)
  792. prot |= PROT_EXEC;
  793. if (auto* region = allocate_region_with_vmobject(vaddr.offset(totally_random_offset), size, *vmobject, offset_in_image, String(name), prot)) {
  794. region->set_shared(true);
  795. return region->vaddr().as_ptr();
  796. }
  797. return nullptr;
  798. };
  799. loader->alloc_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) -> u8* {
  800. ASSERT(size);
  801. ASSERT(alignment == PAGE_SIZE);
  802. int prot = 0;
  803. if (is_readable)
  804. prot |= PROT_READ;
  805. if (is_writable)
  806. prot |= PROT_WRITE;
  807. if (auto* region = allocate_region(vaddr.offset(totally_random_offset), size, String(name), prot))
  808. return region->vaddr().as_ptr();
  809. return nullptr;
  810. };
  811. // FIXME: Move TLS region allocation to userspace: LibC and the dynamic loader.
  812. // LibC if we end up with a statically linked executable, and the
  813. // dynamic loader so that it can create new TLS blocks for each shared libarary
  814. // that gets loaded as part of DT_NEEDED processing, and via dlopen()
  815. // If that doesn't happen quickly, at least pass the location of the TLS region
  816. // some ELF Auxilliary Vector so the loader can use it/create new ones as necessary.
  817. loader->tls_section_hook = [&](size_t size, size_t alignment) {
  818. ASSERT(size);
  819. master_tls_region = allocate_region({}, size, String(), PROT_READ | PROT_WRITE);
  820. master_tls_size = size;
  821. master_tls_alignment = alignment;
  822. return master_tls_region->vaddr().as_ptr();
  823. };
  824. bool success = loader->load();
  825. if (!success) {
  826. klog() << "do_exec: Failure loading " << path.characters();
  827. return -ENOEXEC;
  828. }
  829. // FIXME: Validate that this virtual address is within executable region,
  830. // instead of just non-null. You could totally have a DSO with entry point of
  831. // the beginning of the text segement.
  832. if (!loader->entry().offset(totally_random_offset).get()) {
  833. klog() << "do_exec: Failure loading " << path.characters() << ", entry pointer is invalid! (" << loader->entry().offset(totally_random_offset) << ")";
  834. return -ENOEXEC;
  835. }
  836. rollback_regions_guard.disarm();
  837. // NOTE: At this point, we've committed to the new executable.
  838. entry_eip = loader->entry().offset(totally_random_offset).get();
  839. kill_threads_except_self();
  840. #ifdef EXEC_DEBUG
  841. klog() << "Memory layout after ELF load:";
  842. dump_regions();
  843. #endif
  844. }
  845. m_executable = main_program_description->custody();
  846. m_promises = m_execpromises;
  847. m_veil_state = VeilState::None;
  848. m_unveiled_paths.clear();
  849. // Copy of the master TLS region that we will clone for new threads
  850. m_master_tls_region = master_tls_region->make_weak_ptr();
  851. auto main_program_metadata = main_program_description->metadata();
  852. if (!(main_program_description->custody()->mount_flags() & MS_NOSUID)) {
  853. if (main_program_metadata.is_setuid())
  854. m_euid = main_program_metadata.uid;
  855. if (main_program_metadata.is_setgid())
  856. m_egid = main_program_metadata.gid;
  857. }
  858. Thread::current->set_default_signal_dispositions();
  859. Thread::current->m_signal_mask = 0;
  860. Thread::current->m_pending_signals = 0;
  861. m_futex_queues.clear();
  862. m_region_lookup_cache = {};
  863. disown_all_shared_buffers();
  864. for (size_t i = 0; i < m_fds.size(); ++i) {
  865. auto& daf = m_fds[i];
  866. if (daf.description && daf.flags & FD_CLOEXEC) {
  867. daf.description->close();
  868. daf = {};
  869. }
  870. }
  871. Thread* new_main_thread = nullptr;
  872. if (Process::current == this) {
  873. new_main_thread = Thread::current;
  874. } else {
  875. for_each_thread([&](auto& thread) {
  876. new_main_thread = &thread;
  877. return IterationDecision::Break;
  878. });
  879. }
  880. ASSERT(new_main_thread);
  881. // NOTE: We create the new stack before disabling interrupts since it will zero-fault
  882. // and we don't want to deal with faults after this point.
  883. u32 new_userspace_esp = new_main_thread->make_userspace_stack_for_main_thread(move(arguments), move(environment));
  884. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  885. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  886. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  887. if (Process::current == this)
  888. cli();
  889. // NOTE: Be careful to not trigger any page faults below!
  890. Scheduler::prepare_to_modify_tss(*new_main_thread);
  891. m_name = parts.take_last();
  892. new_main_thread->set_name(m_name);
  893. auto& tss = new_main_thread->m_tss;
  894. u32 old_esp0 = tss.esp0;
  895. m_master_tls_size = master_tls_size;
  896. m_master_tls_alignment = master_tls_alignment;
  897. m_pid = new_main_thread->tid();
  898. new_main_thread->make_thread_specific_region({});
  899. new_main_thread->reset_fpu_state();
  900. memset(&tss, 0, sizeof(TSS32));
  901. tss.iomapbase = sizeof(TSS32);
  902. tss.eflags = 0x0202;
  903. tss.eip = entry_eip;
  904. tss.cs = 0x1b;
  905. tss.ds = 0x23;
  906. tss.es = 0x23;
  907. tss.fs = 0x23;
  908. tss.gs = thread_specific_selector() | 3;
  909. tss.ss = 0x23;
  910. tss.cr3 = page_directory().cr3();
  911. tss.esp = new_userspace_esp;
  912. tss.ss0 = 0x10;
  913. tss.esp0 = old_esp0;
  914. tss.ss2 = m_pid;
  915. #ifdef TASK_DEBUG
  916. klog() << "Process exec'd " << path.characters() << " @ " << String::format("%p", tss.eip);
  917. #endif
  918. if (was_profiling)
  919. Profiling::did_exec(path);
  920. new_main_thread->set_state(Thread::State::Skip1SchedulerPass);
  921. big_lock().force_unlock_if_locked();
  922. return 0;
  923. }
  924. static KResultOr<Vector<String>> find_shebang_interpreter_for_executable(const char first_page[], int nread)
  925. {
  926. int word_start = 2;
  927. int word_length = 0;
  928. if (nread > 2 && first_page[0] == '#' && first_page[1] == '!') {
  929. Vector<String> interpreter_words;
  930. for (int i = 2; i < nread; ++i) {
  931. if (first_page[i] == '\n') {
  932. break;
  933. }
  934. if (first_page[i] != ' ') {
  935. ++word_length;
  936. }
  937. if (first_page[i] == ' ') {
  938. if (word_length > 0) {
  939. interpreter_words.append(String(&first_page[word_start], word_length));
  940. }
  941. word_length = 0;
  942. word_start = i + 1;
  943. }
  944. }
  945. if (word_length > 0)
  946. interpreter_words.append(String(&first_page[word_start], word_length));
  947. if (!interpreter_words.is_empty())
  948. return interpreter_words;
  949. }
  950. return KResult(-ENOEXEC);
  951. }
  952. KResultOr<NonnullRefPtr<FileDescription>> Process::find_elf_interpreter_for_executable(const String& path, char (&first_page)[PAGE_SIZE], int nread, size_t file_size)
  953. {
  954. if (nread < (int)sizeof(Elf32_Ehdr))
  955. return KResult(-ENOEXEC);
  956. auto elf_header = (Elf32_Ehdr*)first_page;
  957. if (!ELF::validate_elf_header(*elf_header, file_size)) {
  958. dbg() << "exec(" << path << "): File has invalid ELF header";
  959. return KResult(-ENOEXEC);
  960. }
  961. // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD
  962. String interpreter_path;
  963. if (!ELF::validate_program_headers(*elf_header, file_size, (u8*)first_page, nread, interpreter_path)) {
  964. dbg() << "exec(" << path << "): File has invalid ELF Program headers";
  965. return KResult(-ENOEXEC);
  966. }
  967. if (!interpreter_path.is_empty()) {
  968. // Programs with an interpreter better be relocatable executables or we don't know what to do...
  969. if (elf_header->e_type != ET_DYN)
  970. return KResult(-ENOEXEC);
  971. dbg() << "exec(" << path << "): Using program interpreter " << interpreter_path;
  972. auto interp_result = VFS::the().open(interpreter_path, O_EXEC, 0, current_directory());
  973. if (interp_result.is_error()) {
  974. dbg() << "exec(" << path << "): Unable to open program interpreter " << interpreter_path;
  975. return interp_result.error();
  976. }
  977. auto interpreter_description = interp_result.value();
  978. auto interp_metadata = interpreter_description->metadata();
  979. ASSERT(interpreter_description->inode());
  980. // Validate the program interpreter as a valid elf binary.
  981. // If your program interpreter is a #! file or something, it's time to stop playing games :)
  982. if (interp_metadata.size < (int)sizeof(Elf32_Ehdr))
  983. return KResult(-ENOEXEC);
  984. memset(first_page, 0, sizeof(first_page));
  985. nread = interpreter_description->read((u8*)&first_page, sizeof(first_page));
  986. if (nread < (int)sizeof(Elf32_Ehdr))
  987. return KResult(-ENOEXEC);
  988. elf_header = (Elf32_Ehdr*)first_page;
  989. if (!ELF::validate_elf_header(*elf_header, interp_metadata.size)) {
  990. dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has invalid ELF header";
  991. return KResult(-ENOEXEC);
  992. }
  993. // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD
  994. String interpreter_interpreter_path;
  995. if (!ELF::validate_program_headers(*elf_header, interp_metadata.size, (u8*)first_page, nread, interpreter_interpreter_path)) {
  996. dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has invalid ELF Program headers";
  997. return KResult(-ENOEXEC);
  998. }
  999. if (!interpreter_interpreter_path.is_empty()) {
  1000. dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has its own interpreter (" << interpreter_interpreter_path << ")! No thank you!";
  1001. return KResult(-ELOOP);
  1002. }
  1003. return interpreter_description;
  1004. }
  1005. if (elf_header->e_type != ET_EXEC) {
  1006. // We can't exec an ET_REL, that's just an object file from the compiler
  1007. // If it's ET_DYN with no PT_INTERP, then we can't load it properly either
  1008. return KResult(-ENOEXEC);
  1009. }
  1010. // No interpreter, but, path refers to a valid elf image
  1011. return KResult(KSuccess);
  1012. }
  1013. int Process::exec(String path, Vector<String> arguments, Vector<String> environment, int recursion_depth)
  1014. {
  1015. if (recursion_depth > 2) {
  1016. dbg() << "exec(" << path << "): SHENANIGANS! recursed too far trying to find #! interpreter";
  1017. return -ELOOP;
  1018. }
  1019. // Open the file to check what kind of binary format it is
  1020. // Currently supported formats:
  1021. // - #! interpreted file
  1022. // - ELF32
  1023. // * ET_EXEC binary that just gets loaded
  1024. // * ET_DYN binary that requires a program interpreter
  1025. //
  1026. auto result = VFS::the().open(path, O_EXEC, 0, current_directory());
  1027. if (result.is_error())
  1028. return result.error();
  1029. auto description = result.value();
  1030. auto metadata = description->metadata();
  1031. // Always gonna need at least 3 bytes. these are for #!X
  1032. if (metadata.size < 3)
  1033. return -ENOEXEC;
  1034. ASSERT(description->inode());
  1035. // Read the first page of the program into memory so we can validate the binfmt of it
  1036. char first_page[PAGE_SIZE];
  1037. int nread = description->read((u8*)&first_page, sizeof(first_page));
  1038. // 1) #! interpreted file
  1039. auto shebang_result = find_shebang_interpreter_for_executable(first_page, nread);
  1040. if (!shebang_result.is_error()) {
  1041. Vector<String> new_arguments(shebang_result.value());
  1042. new_arguments.append(path);
  1043. arguments.remove(0);
  1044. new_arguments.append(move(arguments));
  1045. return exec(shebang_result.value().first(), move(new_arguments), move(environment), ++recursion_depth);
  1046. }
  1047. // #2) ELF32 for i386
  1048. auto elf_result = find_elf_interpreter_for_executable(path, first_page, nread, metadata.size);
  1049. RefPtr<FileDescription> interpreter_description;
  1050. // We're getting either an interpreter, an error, or KSuccess (i.e. no interpreter but file checks out)
  1051. if (!elf_result.is_error())
  1052. interpreter_description = elf_result.value();
  1053. else if (elf_result.error().is_error())
  1054. return elf_result.error();
  1055. // The bulk of exec() is done by do_exec(), which ensures that all locals
  1056. // are cleaned up by the time we yield-teleport below.
  1057. int rc = do_exec(move(description), move(arguments), move(environment), move(interpreter_description));
  1058. m_exec_tid = 0;
  1059. if (rc < 0)
  1060. return rc;
  1061. if (m_wait_for_tracer_at_next_execve) {
  1062. ASSERT(Thread::current->state() == Thread::State::Skip1SchedulerPass);
  1063. // State::Skip1SchedulerPass is irrelevant since we block the thread
  1064. Thread::current->set_state(Thread::State::Running);
  1065. Thread::current->send_urgent_signal_to_self(SIGSTOP);
  1066. }
  1067. if (Process::current == this) {
  1068. Scheduler::yield();
  1069. ASSERT_NOT_REACHED();
  1070. }
  1071. return 0;
  1072. }
  1073. int Process::sys$execve(const Syscall::SC_execve_params* user_params)
  1074. {
  1075. REQUIRE_PROMISE(exec);
  1076. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  1077. // On success, the kernel stack will be lost.
  1078. Syscall::SC_execve_params params;
  1079. if (!validate_read_and_copy_typed(&params, user_params))
  1080. return -EFAULT;
  1081. if (params.arguments.length > ARG_MAX || params.environment.length > ARG_MAX)
  1082. return -E2BIG;
  1083. if (m_wait_for_tracer_at_next_execve)
  1084. Thread::current->send_urgent_signal_to_self(SIGSTOP);
  1085. String path;
  1086. {
  1087. auto path_arg = get_syscall_path_argument(params.path);
  1088. if (path_arg.is_error())
  1089. return path_arg.error();
  1090. path = path_arg.value();
  1091. }
  1092. auto copy_user_strings = [&](const auto& list, auto& output) {
  1093. if (!list.length)
  1094. return true;
  1095. if (!validate_read_typed(list.strings, list.length))
  1096. return false;
  1097. Vector<Syscall::StringArgument, 32> strings;
  1098. strings.resize(list.length);
  1099. copy_from_user(strings.data(), list.strings, list.length * sizeof(Syscall::StringArgument));
  1100. for (size_t i = 0; i < list.length; ++i) {
  1101. auto string = validate_and_copy_string_from_user(strings[i]);
  1102. if (string.is_null())
  1103. return false;
  1104. output.append(move(string));
  1105. }
  1106. return true;
  1107. };
  1108. Vector<String> arguments;
  1109. if (!copy_user_strings(params.arguments, arguments))
  1110. return -EFAULT;
  1111. Vector<String> environment;
  1112. if (!copy_user_strings(params.environment, environment))
  1113. return -EFAULT;
  1114. int rc = exec(move(path), move(arguments), move(environment));
  1115. ASSERT(rc < 0); // We should never continue after a successful exec!
  1116. return rc;
  1117. }
  1118. Process* Process::create_user_process(Thread*& first_thread, const String& path, uid_t uid, gid_t gid, pid_t parent_pid, int& error, Vector<String>&& arguments, Vector<String>&& environment, TTY* tty)
  1119. {
  1120. auto parts = path.split('/');
  1121. if (arguments.is_empty()) {
  1122. arguments.append(parts.last());
  1123. }
  1124. RefPtr<Custody> cwd;
  1125. RefPtr<Custody> root;
  1126. {
  1127. InterruptDisabler disabler;
  1128. if (auto* parent = Process::from_pid(parent_pid)) {
  1129. cwd = parent->m_cwd;
  1130. root = parent->m_root_directory;
  1131. }
  1132. }
  1133. if (!cwd)
  1134. cwd = VFS::the().root_custody();
  1135. if (!root)
  1136. root = VFS::the().root_custody();
  1137. auto* process = new Process(first_thread, parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  1138. process->m_fds.resize(m_max_open_file_descriptors);
  1139. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  1140. auto description = device_to_use_as_tty.open(O_RDWR).value();
  1141. process->m_fds[0].set(*description);
  1142. process->m_fds[1].set(*description);
  1143. process->m_fds[2].set(*description);
  1144. error = process->exec(path, move(arguments), move(environment));
  1145. if (error != 0) {
  1146. dbg() << "Failed to exec " << path << ": " << error;
  1147. delete first_thread;
  1148. delete process;
  1149. return nullptr;
  1150. }
  1151. {
  1152. InterruptDisabler disabler;
  1153. g_processes->prepend(process);
  1154. }
  1155. #ifdef TASK_DEBUG
  1156. klog() << "Process " << process->pid() << " (" << process->name().characters() << ") spawned @ " << String::format("%p", first_thread->tss().eip);
  1157. #endif
  1158. error = 0;
  1159. return process;
  1160. }
  1161. Process* Process::create_kernel_process(Thread*& first_thread, String&& name, void (*e)())
  1162. {
  1163. auto* process = new Process(first_thread, move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  1164. first_thread->tss().eip = (FlatPtr)e;
  1165. if (process->pid() != 0) {
  1166. InterruptDisabler disabler;
  1167. g_processes->prepend(process);
  1168. #ifdef TASK_DEBUG
  1169. klog() << "Kernel process " << process->pid() << " (" << process->name().characters() << ") spawned @ " << String::format("%p", first_thread->tss().eip);
  1170. #endif
  1171. }
  1172. first_thread->set_state(Thread::State::Runnable);
  1173. return process;
  1174. }
  1175. Process::Process(Thread*& first_thread, const String& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RefPtr<Custody> cwd, RefPtr<Custody> executable, TTY* tty, Process* fork_parent)
  1176. : m_name(move(name))
  1177. , m_pid(allocate_pid())
  1178. , m_uid(uid)
  1179. , m_gid(gid)
  1180. , m_euid(uid)
  1181. , m_egid(gid)
  1182. , m_ring(ring)
  1183. , m_executable(move(executable))
  1184. , m_cwd(move(cwd))
  1185. , m_tty(tty)
  1186. , m_ppid(ppid)
  1187. {
  1188. #ifdef PROCESS_DEBUG
  1189. dbg() << "Created new process " << m_name << "(" << m_pid << ")";
  1190. #endif
  1191. m_page_directory = PageDirectory::create_for_userspace(*this, fork_parent ? &fork_parent->page_directory().range_allocator() : nullptr);
  1192. #ifdef MM_DEBUG
  1193. dbg() << "Process " << pid() << " ctor: PD=" << m_page_directory.ptr() << " created";
  1194. #endif
  1195. if (fork_parent) {
  1196. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the only thread in the new process.
  1197. first_thread = Thread::current->clone(*this);
  1198. } else {
  1199. // NOTE: This non-forked code path is only taken when the kernel creates a process "manually" (at boot.)
  1200. first_thread = new Thread(*this);
  1201. }
  1202. }
  1203. Process::~Process()
  1204. {
  1205. ASSERT(thread_count() == 0);
  1206. }
  1207. void Process::dump_regions()
  1208. {
  1209. klog() << "Process regions:";
  1210. klog() << "BEGIN END SIZE ACCESS NAME";
  1211. for (auto& region : m_regions) {
  1212. klog() << String::format("%08x", region.vaddr().get()) << " -- " << String::format("%08x", region.vaddr().offset(region.size() - 1).get()) << " " << String::format("%08x", region.size()) << " " << (region.is_readable() ? 'R' : ' ') << (region.is_writable() ? 'W' : ' ') << (region.is_executable() ? 'X' : ' ') << (region.is_shared() ? 'S' : ' ') << (region.is_stack() ? 'T' : ' ') << (region.vmobject().is_purgeable() ? 'P' : ' ') << " " << region.name().characters();
  1213. }
  1214. MM.dump_kernel_regions();
  1215. }
  1216. void Process::sys$exit(int status)
  1217. {
  1218. cli();
  1219. #ifdef TASK_DEBUG
  1220. klog() << "sys$exit: exit with status " << status;
  1221. #endif
  1222. if (status != 0)
  1223. dump_backtrace();
  1224. m_termination_status = status;
  1225. m_termination_signal = 0;
  1226. die();
  1227. Thread::current->die_if_needed();
  1228. ASSERT_NOT_REACHED();
  1229. }
  1230. void signal_trampoline_dummy(void)
  1231. {
  1232. // The trampoline preserves the current eax, pushes the signal code and
  1233. // then calls the signal handler. We do this because, when interrupting a
  1234. // blocking syscall, that syscall may return some special error code in eax;
  1235. // This error code would likely be overwritten by the signal handler, so it's
  1236. // neccessary to preserve it here.
  1237. asm(
  1238. ".intel_syntax noprefix\n"
  1239. "asm_signal_trampoline:\n"
  1240. "push ebp\n"
  1241. "mov ebp, esp\n"
  1242. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  1243. "sub esp, 4\n" // align the stack to 16 bytes
  1244. "mov eax, [ebp+12]\n" // push the signal code
  1245. "push eax\n"
  1246. "call [ebp+8]\n" // call the signal handler
  1247. "add esp, 8\n"
  1248. "mov eax, %P0\n"
  1249. "int 0x82\n" // sigreturn syscall
  1250. "asm_signal_trampoline_end:\n"
  1251. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  1252. }
  1253. extern "C" void asm_signal_trampoline(void);
  1254. extern "C" void asm_signal_trampoline_end(void);
  1255. void create_signal_trampolines()
  1256. {
  1257. InterruptDisabler disabler;
  1258. // NOTE: We leak this region.
  1259. auto* trampoline_region = MM.allocate_user_accessible_kernel_region(PAGE_SIZE, "Signal trampolines", Region::Access::Read | Region::Access::Write | Region::Access::Execute, false).leak_ptr();
  1260. g_return_to_ring3_from_signal_trampoline = trampoline_region->vaddr();
  1261. u8* trampoline = (u8*)asm_signal_trampoline;
  1262. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  1263. size_t trampoline_size = trampoline_end - trampoline;
  1264. {
  1265. SmapDisabler disabler;
  1266. u8* code_ptr = (u8*)trampoline_region->vaddr().as_ptr();
  1267. memcpy(code_ptr, trampoline, trampoline_size);
  1268. }
  1269. trampoline_region->set_writable(false);
  1270. trampoline_region->remap();
  1271. }
  1272. int Process::sys$sigreturn(RegisterState& registers)
  1273. {
  1274. REQUIRE_PROMISE(stdio);
  1275. SmapDisabler disabler;
  1276. //Here, we restore the state pushed by dispatch signal and asm_signal_trampoline.
  1277. u32* stack_ptr = (u32*)registers.userspace_esp;
  1278. u32 smuggled_eax = *stack_ptr;
  1279. //pop the stored eax, ebp, return address, handler and signal code
  1280. stack_ptr += 5;
  1281. Thread::current->m_signal_mask = *stack_ptr;
  1282. stack_ptr++;
  1283. //pop edi, esi, ebp, esp, ebx, edx, ecx and eax
  1284. memcpy(&registers.edi, stack_ptr, 8 * sizeof(FlatPtr));
  1285. stack_ptr += 8;
  1286. registers.eip = *stack_ptr;
  1287. stack_ptr++;
  1288. registers.eflags = *stack_ptr;
  1289. stack_ptr++;
  1290. registers.userspace_esp = registers.esp;
  1291. return smuggled_eax;
  1292. }
  1293. void Process::crash(int signal, u32 eip, bool out_of_memory)
  1294. {
  1295. ASSERT_INTERRUPTS_DISABLED();
  1296. ASSERT(!is_dead());
  1297. ASSERT(Process::current == this);
  1298. if (out_of_memory) {
  1299. dbg() << "\033[31;1mOut of memory\033[m, killing: " << *this;
  1300. } else {
  1301. if (eip >= 0xc0000000 && g_kernel_symbols_available) {
  1302. auto* symbol = symbolicate_kernel_address(eip);
  1303. dbg() << "\033[31;1m" << String::format("%p", eip) << " " << (symbol ? demangle(symbol->name) : "(k?)") << " +" << (symbol ? eip - symbol->address : 0) << "\033[0m\n";
  1304. } else if (auto elf_bundle = this->elf_bundle()) {
  1305. dbg() << "\033[31;1m" << String::format("%p", eip) << " " << elf_bundle->elf_loader->symbolicate(eip) << "\033[0m\n";
  1306. } else {
  1307. dbg() << "\033[31;1m" << String::format("%p", eip) << " (?)\033[0m\n";
  1308. }
  1309. dump_backtrace();
  1310. }
  1311. m_termination_signal = signal;
  1312. dump_regions();
  1313. ASSERT(is_ring3());
  1314. die();
  1315. // We can not return from here, as there is nowhere
  1316. // to unwind to, so die right away.
  1317. Thread::current->die_if_needed();
  1318. ASSERT_NOT_REACHED();
  1319. }
  1320. Process* Process::from_pid(pid_t pid)
  1321. {
  1322. ASSERT_INTERRUPTS_DISABLED();
  1323. for (auto& process : *g_processes) {
  1324. if (process.pid() == pid)
  1325. return &process;
  1326. }
  1327. return nullptr;
  1328. }
  1329. RefPtr<FileDescription> Process::file_description(int fd) const
  1330. {
  1331. if (fd < 0)
  1332. return nullptr;
  1333. if (static_cast<size_t>(fd) < m_fds.size())
  1334. return m_fds[fd].description.ptr();
  1335. return nullptr;
  1336. }
  1337. int Process::fd_flags(int fd) const
  1338. {
  1339. if (fd < 0)
  1340. return -1;
  1341. if (static_cast<size_t>(fd) < m_fds.size())
  1342. return m_fds[fd].flags;
  1343. return -1;
  1344. }
  1345. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, ssize_t size)
  1346. {
  1347. REQUIRE_PROMISE(stdio);
  1348. if (size < 0)
  1349. return -EINVAL;
  1350. if (!validate_write(buffer, size))
  1351. return -EFAULT;
  1352. auto description = file_description(fd);
  1353. if (!description)
  1354. return -EBADF;
  1355. return description->get_dir_entries((u8*)buffer, size);
  1356. }
  1357. int Process::sys$lseek(int fd, off_t offset, int whence)
  1358. {
  1359. REQUIRE_PROMISE(stdio);
  1360. auto description = file_description(fd);
  1361. if (!description)
  1362. return -EBADF;
  1363. return description->seek(offset, whence);
  1364. }
  1365. int Process::sys$ttyname_r(int fd, char* buffer, ssize_t size)
  1366. {
  1367. REQUIRE_PROMISE(tty);
  1368. if (size < 0)
  1369. return -EINVAL;
  1370. if (!validate_write(buffer, size))
  1371. return -EFAULT;
  1372. auto description = file_description(fd);
  1373. if (!description)
  1374. return -EBADF;
  1375. if (!description->is_tty())
  1376. return -ENOTTY;
  1377. String tty_name = description->tty()->tty_name();
  1378. if ((size_t)size < tty_name.length() + 1)
  1379. return -ERANGE;
  1380. copy_to_user(buffer, tty_name.characters(), tty_name.length() + 1);
  1381. return 0;
  1382. }
  1383. int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size)
  1384. {
  1385. REQUIRE_PROMISE(tty);
  1386. if (size < 0)
  1387. return -EINVAL;
  1388. if (!validate_write(buffer, size))
  1389. return -EFAULT;
  1390. auto description = file_description(fd);
  1391. if (!description)
  1392. return -EBADF;
  1393. auto* master_pty = description->master_pty();
  1394. if (!master_pty)
  1395. return -ENOTTY;
  1396. auto pts_name = master_pty->pts_name();
  1397. if ((size_t)size < pts_name.length() + 1)
  1398. return -ERANGE;
  1399. copy_to_user(buffer, pts_name.characters(), pts_name.length() + 1);
  1400. return 0;
  1401. }
  1402. ssize_t Process::sys$writev(int fd, const struct iovec* iov, int iov_count)
  1403. {
  1404. REQUIRE_PROMISE(stdio);
  1405. if (iov_count < 0)
  1406. return -EINVAL;
  1407. if (!validate_read_typed(iov, iov_count))
  1408. return -EFAULT;
  1409. u64 total_length = 0;
  1410. Vector<iovec, 32> vecs;
  1411. vecs.resize(iov_count);
  1412. copy_from_user(vecs.data(), iov, iov_count * sizeof(iovec));
  1413. for (auto& vec : vecs) {
  1414. if (!validate_read(vec.iov_base, vec.iov_len))
  1415. return -EFAULT;
  1416. total_length += vec.iov_len;
  1417. if (total_length > INT32_MAX)
  1418. return -EINVAL;
  1419. }
  1420. auto description = file_description(fd);
  1421. if (!description)
  1422. return -EBADF;
  1423. if (!description->is_writable())
  1424. return -EBADF;
  1425. int nwritten = 0;
  1426. for (auto& vec : vecs) {
  1427. int rc = do_write(*description, (const u8*)vec.iov_base, vec.iov_len);
  1428. if (rc < 0) {
  1429. if (nwritten == 0)
  1430. return rc;
  1431. return nwritten;
  1432. }
  1433. nwritten += rc;
  1434. }
  1435. return nwritten;
  1436. }
  1437. ssize_t Process::do_write(FileDescription& description, const u8* data, int data_size)
  1438. {
  1439. ssize_t nwritten = 0;
  1440. if (!description.is_blocking()) {
  1441. if (!description.can_write())
  1442. return -EAGAIN;
  1443. }
  1444. if (description.should_append()) {
  1445. #ifdef IO_DEBUG
  1446. dbg() << "seeking to end (O_APPEND)";
  1447. #endif
  1448. description.seek(0, SEEK_END);
  1449. }
  1450. while (nwritten < data_size) {
  1451. #ifdef IO_DEBUG
  1452. dbg() << "while " << nwritten << " < " << size;
  1453. #endif
  1454. if (!description.can_write()) {
  1455. #ifdef IO_DEBUG
  1456. dbg() << "block write on " << description.absolute_path();
  1457. #endif
  1458. if (Thread::current->block<Thread::WriteBlocker>(description) != Thread::BlockResult::WokeNormally) {
  1459. if (nwritten == 0)
  1460. return -EINTR;
  1461. }
  1462. }
  1463. ssize_t rc = description.write(data + nwritten, data_size - nwritten);
  1464. #ifdef IO_DEBUG
  1465. dbg() << " -> write returned " << rc;
  1466. #endif
  1467. if (rc < 0) {
  1468. if (nwritten)
  1469. return nwritten;
  1470. return rc;
  1471. }
  1472. if (rc == 0)
  1473. break;
  1474. nwritten += rc;
  1475. }
  1476. return nwritten;
  1477. }
  1478. ssize_t Process::sys$write(int fd, const u8* data, ssize_t size)
  1479. {
  1480. REQUIRE_PROMISE(stdio);
  1481. if (size < 0)
  1482. return -EINVAL;
  1483. if (size == 0)
  1484. return 0;
  1485. if (!validate_read(data, size))
  1486. return -EFAULT;
  1487. #ifdef DEBUG_IO
  1488. dbg() << "sys$write(" << fd << ", " << (const void*)(data) << ", " << size << ")";
  1489. #endif
  1490. auto description = file_description(fd);
  1491. if (!description)
  1492. return -EBADF;
  1493. if (!description->is_writable())
  1494. return -EBADF;
  1495. return do_write(*description, data, size);
  1496. }
  1497. ssize_t Process::sys$read(int fd, u8* buffer, ssize_t size)
  1498. {
  1499. REQUIRE_PROMISE(stdio);
  1500. if (size < 0)
  1501. return -EINVAL;
  1502. if (size == 0)
  1503. return 0;
  1504. if (!validate_write(buffer, size))
  1505. return -EFAULT;
  1506. #ifdef DEBUG_IO
  1507. dbg() << "sys$read(" << fd << ", " << (const void*)buffer << ", " << size << ")";
  1508. #endif
  1509. auto description = file_description(fd);
  1510. if (!description)
  1511. return -EBADF;
  1512. if (!description->is_readable())
  1513. return -EBADF;
  1514. if (description->is_directory())
  1515. return -EISDIR;
  1516. if (description->is_blocking()) {
  1517. if (!description->can_read()) {
  1518. if (Thread::current->block<Thread::ReadBlocker>(*description) != Thread::BlockResult::WokeNormally)
  1519. return -EINTR;
  1520. if (!description->can_read())
  1521. return -EAGAIN;
  1522. }
  1523. }
  1524. return description->read(buffer, size);
  1525. }
  1526. int Process::sys$close(int fd)
  1527. {
  1528. REQUIRE_PROMISE(stdio);
  1529. auto description = file_description(fd);
  1530. #ifdef DEBUG_IO
  1531. dbg() << "sys$close(" << fd << ") " << description.ptr();
  1532. #endif
  1533. if (!description)
  1534. return -EBADF;
  1535. int rc = description->close();
  1536. m_fds[fd] = {};
  1537. return rc;
  1538. }
  1539. int Process::sys$utime(const char* user_path, size_t path_length, const utimbuf* user_buf)
  1540. {
  1541. REQUIRE_PROMISE(fattr);
  1542. if (user_buf && !validate_read_typed(user_buf))
  1543. return -EFAULT;
  1544. auto path = get_syscall_path_argument(user_path, path_length);
  1545. if (path.is_error())
  1546. return path.error();
  1547. utimbuf buf;
  1548. if (user_buf) {
  1549. copy_from_user(&buf, user_buf);
  1550. } else {
  1551. auto now = kgettimeofday();
  1552. buf = { now.tv_sec, now.tv_sec };
  1553. }
  1554. return VFS::the().utime(path.value(), current_directory(), buf.actime, buf.modtime);
  1555. }
  1556. int Process::sys$access(const char* user_path, size_t path_length, int mode)
  1557. {
  1558. REQUIRE_PROMISE(rpath);
  1559. auto path = get_syscall_path_argument(user_path, path_length);
  1560. if (path.is_error())
  1561. return path.error();
  1562. return VFS::the().access(path.value(), mode, current_directory());
  1563. }
  1564. int Process::sys$fcntl(int fd, int cmd, u32 arg)
  1565. {
  1566. REQUIRE_PROMISE(stdio);
  1567. #ifdef DEBUG_IO
  1568. dbg() << "sys$fcntl: fd=" << fd << ", cmd=" << cmd << ", arg=" << arg;
  1569. #endif
  1570. auto description = file_description(fd);
  1571. if (!description)
  1572. return -EBADF;
  1573. // NOTE: The FD flags are not shared between FileDescription objects.
  1574. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1575. switch (cmd) {
  1576. case F_DUPFD: {
  1577. int arg_fd = (int)arg;
  1578. if (arg_fd < 0)
  1579. return -EINVAL;
  1580. int new_fd = alloc_fd(arg_fd);
  1581. if (new_fd < 0)
  1582. return new_fd;
  1583. m_fds[new_fd].set(*description);
  1584. return new_fd;
  1585. }
  1586. case F_GETFD:
  1587. return m_fds[fd].flags;
  1588. case F_SETFD:
  1589. m_fds[fd].flags = arg;
  1590. break;
  1591. case F_GETFL:
  1592. return description->file_flags();
  1593. case F_SETFL:
  1594. description->set_file_flags(arg);
  1595. break;
  1596. case F_ISTTY:
  1597. return description->is_tty();
  1598. default:
  1599. return -EINVAL;
  1600. }
  1601. return 0;
  1602. }
  1603. int Process::sys$fstat(int fd, stat* user_statbuf)
  1604. {
  1605. REQUIRE_PROMISE(stdio);
  1606. if (!validate_write_typed(user_statbuf))
  1607. return -EFAULT;
  1608. auto description = file_description(fd);
  1609. if (!description)
  1610. return -EBADF;
  1611. stat buffer;
  1612. memset(&buffer, 0, sizeof(buffer));
  1613. int rc = description->fstat(buffer);
  1614. copy_to_user(user_statbuf, &buffer);
  1615. return rc;
  1616. }
  1617. int Process::sys$stat(const Syscall::SC_stat_params* user_params)
  1618. {
  1619. REQUIRE_PROMISE(rpath);
  1620. Syscall::SC_stat_params params;
  1621. if (!validate_read_and_copy_typed(&params, user_params))
  1622. return -EFAULT;
  1623. if (!validate_write_typed(params.statbuf))
  1624. return -EFAULT;
  1625. auto path = get_syscall_path_argument(params.path);
  1626. if (path.is_error())
  1627. return path.error();
  1628. auto metadata_or_error = VFS::the().lookup_metadata(path.value(), current_directory(), params.follow_symlinks ? 0 : O_NOFOLLOW_NOERROR);
  1629. if (metadata_or_error.is_error())
  1630. return metadata_or_error.error();
  1631. stat statbuf;
  1632. auto result = metadata_or_error.value().stat(statbuf);
  1633. if (result.is_error())
  1634. return result;
  1635. copy_to_user(params.statbuf, &statbuf);
  1636. return 0;
  1637. }
  1638. template<typename DataType, typename SizeType>
  1639. bool Process::validate(const Syscall::MutableBufferArgument<DataType, SizeType>& buffer)
  1640. {
  1641. return validate_write(buffer.data, buffer.size);
  1642. }
  1643. template<typename DataType, typename SizeType>
  1644. bool Process::validate(const Syscall::ImmutableBufferArgument<DataType, SizeType>& buffer)
  1645. {
  1646. return validate_read(buffer.data, buffer.size);
  1647. }
  1648. String Process::validate_and_copy_string_from_user(const char* user_characters, size_t user_length) const
  1649. {
  1650. if (user_length == 0)
  1651. return String::empty();
  1652. if (!user_characters)
  1653. return {};
  1654. if (!validate_read(user_characters, user_length))
  1655. return {};
  1656. SmapDisabler disabler;
  1657. size_t measured_length = strnlen(user_characters, user_length);
  1658. return String(user_characters, measured_length);
  1659. }
  1660. String Process::validate_and_copy_string_from_user(const Syscall::StringArgument& string) const
  1661. {
  1662. return validate_and_copy_string_from_user(string.characters, string.length);
  1663. }
  1664. int Process::sys$readlink(const Syscall::SC_readlink_params* user_params)
  1665. {
  1666. REQUIRE_PROMISE(rpath);
  1667. Syscall::SC_readlink_params params;
  1668. if (!validate_read_and_copy_typed(&params, user_params))
  1669. return -EFAULT;
  1670. if (!validate(params.buffer))
  1671. return -EFAULT;
  1672. auto path = get_syscall_path_argument(params.path);
  1673. if (path.is_error())
  1674. return path.error();
  1675. auto result = VFS::the().open(path.value(), O_RDONLY | O_NOFOLLOW_NOERROR, 0, current_directory());
  1676. if (result.is_error())
  1677. return result.error();
  1678. auto description = result.value();
  1679. if (!description->metadata().is_symlink())
  1680. return -EINVAL;
  1681. auto contents = description->read_entire_file();
  1682. if (contents.is_error())
  1683. return contents.error();
  1684. auto link_target = String::copy(contents.value());
  1685. if (link_target.length() > params.buffer.size)
  1686. return -ENAMETOOLONG;
  1687. copy_to_user(params.buffer.data, link_target.characters(), link_target.length());
  1688. return link_target.length();
  1689. }
  1690. int Process::sys$chdir(const char* user_path, size_t path_length)
  1691. {
  1692. REQUIRE_PROMISE(rpath);
  1693. auto path = get_syscall_path_argument(user_path, path_length);
  1694. if (path.is_error())
  1695. return path.error();
  1696. auto directory_or_error = VFS::the().open_directory(path.value(), current_directory());
  1697. if (directory_or_error.is_error())
  1698. return directory_or_error.error();
  1699. m_cwd = *directory_or_error.value();
  1700. return 0;
  1701. }
  1702. int Process::sys$fchdir(int fd)
  1703. {
  1704. REQUIRE_PROMISE(stdio);
  1705. auto description = file_description(fd);
  1706. if (!description)
  1707. return -EBADF;
  1708. if (!description->is_directory())
  1709. return -ENOTDIR;
  1710. if (!description->metadata().may_execute(*this))
  1711. return -EACCES;
  1712. m_cwd = description->custody();
  1713. return 0;
  1714. }
  1715. int Process::sys$getcwd(char* buffer, ssize_t size)
  1716. {
  1717. REQUIRE_PROMISE(rpath);
  1718. if (size < 0)
  1719. return -EINVAL;
  1720. if (!validate_write(buffer, size))
  1721. return -EFAULT;
  1722. auto path = current_directory().absolute_path();
  1723. if ((size_t)size < path.length() + 1)
  1724. return -ERANGE;
  1725. copy_to_user(buffer, path.characters(), path.length() + 1);
  1726. return 0;
  1727. }
  1728. int Process::number_of_open_file_descriptors() const
  1729. {
  1730. int count = 0;
  1731. for (auto& description : m_fds) {
  1732. if (description)
  1733. ++count;
  1734. }
  1735. return count;
  1736. }
  1737. int Process::sys$open(const Syscall::SC_open_params* user_params)
  1738. {
  1739. Syscall::SC_open_params params;
  1740. if (!validate_read_and_copy_typed(&params, user_params))
  1741. return -EFAULT;
  1742. int dirfd = params.dirfd;
  1743. int options = params.options;
  1744. u16 mode = params.mode;
  1745. if (options & O_NOFOLLOW_NOERROR)
  1746. return -EINVAL;
  1747. if (options & O_UNLINK_INTERNAL)
  1748. return -EINVAL;
  1749. if (options & O_WRONLY)
  1750. REQUIRE_PROMISE(wpath);
  1751. else if (options & O_RDONLY)
  1752. REQUIRE_PROMISE(rpath);
  1753. if (options & O_CREAT)
  1754. REQUIRE_PROMISE(cpath);
  1755. // Ignore everything except permission bits.
  1756. mode &= 04777;
  1757. auto path = get_syscall_path_argument(params.path);
  1758. if (path.is_error())
  1759. return path.error();
  1760. #ifdef DEBUG_IO
  1761. dbg() << "sys$open(dirfd=" << dirfd << ", path=\"" << path.value() << "\", options=" << options << ", mode=" << mode << ")";
  1762. #endif
  1763. int fd = alloc_fd();
  1764. if (fd < 0)
  1765. return fd;
  1766. RefPtr<Custody> base;
  1767. if (dirfd == AT_FDCWD) {
  1768. base = current_directory();
  1769. } else {
  1770. auto base_description = file_description(dirfd);
  1771. if (!base_description)
  1772. return -EBADF;
  1773. if (!base_description->is_directory())
  1774. return -ENOTDIR;
  1775. if (!base_description->custody())
  1776. return -EINVAL;
  1777. base = base_description->custody();
  1778. }
  1779. auto result = VFS::the().open(path.value(), options, mode & ~umask(), *base);
  1780. if (result.is_error())
  1781. return result.error();
  1782. auto description = result.value();
  1783. if (description->inode() && description->inode()->socket())
  1784. return -ENXIO;
  1785. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1786. m_fds[fd].set(move(description), fd_flags);
  1787. return fd;
  1788. }
  1789. int Process::alloc_fd(int first_candidate_fd)
  1790. {
  1791. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1792. if (!m_fds[i])
  1793. return i;
  1794. }
  1795. return -EMFILE;
  1796. }
  1797. int Process::sys$pipe(int pipefd[2], int flags)
  1798. {
  1799. REQUIRE_PROMISE(stdio);
  1800. if (!validate_write_typed(pipefd))
  1801. return -EFAULT;
  1802. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1803. return -EMFILE;
  1804. // Reject flags other than O_CLOEXEC.
  1805. if ((flags & O_CLOEXEC) != flags)
  1806. return -EINVAL;
  1807. u32 fd_flags = (flags & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1808. auto fifo = FIFO::create(m_uid);
  1809. int reader_fd = alloc_fd();
  1810. m_fds[reader_fd].set(fifo->open_direction(FIFO::Direction::Reader), fd_flags);
  1811. m_fds[reader_fd].description->set_readable(true);
  1812. copy_to_user(&pipefd[0], &reader_fd);
  1813. int writer_fd = alloc_fd();
  1814. m_fds[writer_fd].set(fifo->open_direction(FIFO::Direction::Writer), fd_flags);
  1815. m_fds[writer_fd].description->set_writable(true);
  1816. copy_to_user(&pipefd[1], &writer_fd);
  1817. return 0;
  1818. }
  1819. int Process::sys$killpg(int pgrp, int signum)
  1820. {
  1821. REQUIRE_PROMISE(proc);
  1822. if (signum < 1 || signum >= 32)
  1823. return -EINVAL;
  1824. if (pgrp < 0)
  1825. return -EINVAL;
  1826. return do_killpg(pgrp, signum);
  1827. }
  1828. int Process::sys$setuid(uid_t uid)
  1829. {
  1830. REQUIRE_PROMISE(id);
  1831. if (uid != m_uid && !is_superuser())
  1832. return -EPERM;
  1833. m_uid = uid;
  1834. m_euid = uid;
  1835. return 0;
  1836. }
  1837. int Process::sys$setgid(gid_t gid)
  1838. {
  1839. REQUIRE_PROMISE(id);
  1840. if (gid != m_gid && !is_superuser())
  1841. return -EPERM;
  1842. m_gid = gid;
  1843. m_egid = gid;
  1844. return 0;
  1845. }
  1846. unsigned Process::sys$alarm(unsigned seconds)
  1847. {
  1848. REQUIRE_PROMISE(stdio);
  1849. unsigned previous_alarm_remaining = 0;
  1850. if (m_alarm_deadline && m_alarm_deadline > g_uptime) {
  1851. previous_alarm_remaining = (m_alarm_deadline - g_uptime) / TimeManagement::the().ticks_per_second();
  1852. }
  1853. if (!seconds) {
  1854. m_alarm_deadline = 0;
  1855. return previous_alarm_remaining;
  1856. }
  1857. m_alarm_deadline = g_uptime + seconds * TimeManagement::the().ticks_per_second();
  1858. return previous_alarm_remaining;
  1859. }
  1860. int Process::sys$uname(utsname* buf)
  1861. {
  1862. REQUIRE_PROMISE(stdio);
  1863. if (!validate_write_typed(buf))
  1864. return -EFAULT;
  1865. LOCKER(*s_hostname_lock, Lock::Mode::Shared);
  1866. if (s_hostname->length() + 1 > sizeof(utsname::nodename))
  1867. return -ENAMETOOLONG;
  1868. copy_to_user(buf->sysname, "SerenityOS", 11);
  1869. copy_to_user(buf->release, "1.0-dev", 8);
  1870. copy_to_user(buf->version, "FIXME", 6);
  1871. copy_to_user(buf->machine, "i686", 5);
  1872. copy_to_user(buf->nodename, s_hostname->characters(), s_hostname->length() + 1);
  1873. return 0;
  1874. }
  1875. KResult Process::do_kill(Process& process, int signal)
  1876. {
  1877. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1878. // FIXME: Should setuid processes have some special treatment here?
  1879. if (!is_superuser() && m_euid != process.m_uid && m_uid != process.m_uid)
  1880. return KResult(-EPERM);
  1881. if (process.is_ring0() && signal == SIGKILL) {
  1882. klog() << "attempted to send SIGKILL to ring 0 process " << process.name().characters() << "(" << process.pid() << ")";
  1883. return KResult(-EPERM);
  1884. }
  1885. if (signal != 0)
  1886. return process.send_signal(signal, this);
  1887. return KSuccess;
  1888. }
  1889. KResult Process::do_killpg(pid_t pgrp, int signal)
  1890. {
  1891. InterruptDisabler disabler;
  1892. ASSERT(pgrp >= 0);
  1893. // Send the signal to all processes in the given group.
  1894. if (pgrp == 0) {
  1895. // Send the signal to our own pgrp.
  1896. pgrp = pgid();
  1897. }
  1898. bool group_was_empty = true;
  1899. bool any_succeeded = false;
  1900. KResult error = KSuccess;
  1901. Process::for_each_in_pgrp(pgrp, [&](auto& process) {
  1902. group_was_empty = false;
  1903. KResult res = do_kill(process, signal);
  1904. if (res.is_success())
  1905. any_succeeded = true;
  1906. else
  1907. error = res;
  1908. return IterationDecision::Continue;
  1909. });
  1910. if (group_was_empty)
  1911. return KResult(-ESRCH);
  1912. if (any_succeeded)
  1913. return KSuccess;
  1914. return error;
  1915. }
  1916. KResult Process::do_killall(int signal)
  1917. {
  1918. InterruptDisabler disabler;
  1919. bool any_succeeded = false;
  1920. KResult error = KSuccess;
  1921. // Send the signal to all processes we have access to for.
  1922. for (auto& process : *g_processes) {
  1923. KResult res = KSuccess;
  1924. if (process.pid() == m_pid)
  1925. res = do_killself(signal);
  1926. else
  1927. res = do_kill(process, signal);
  1928. if (res.is_success())
  1929. any_succeeded = true;
  1930. else
  1931. error = res;
  1932. }
  1933. if (any_succeeded)
  1934. return KSuccess;
  1935. return error;
  1936. }
  1937. KResult Process::do_killself(int signal)
  1938. {
  1939. if (signal == 0)
  1940. return KSuccess;
  1941. if (!Thread::current->should_ignore_signal(signal)) {
  1942. Thread::current->send_signal(signal, this);
  1943. (void)Thread::current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal);
  1944. }
  1945. return KSuccess;
  1946. }
  1947. int Process::sys$kill(pid_t pid, int signal)
  1948. {
  1949. if (pid == m_pid)
  1950. REQUIRE_PROMISE(stdio);
  1951. else
  1952. REQUIRE_PROMISE(proc);
  1953. if (signal < 0 || signal >= 32)
  1954. return -EINVAL;
  1955. if (pid < -1) {
  1956. if (pid == INT32_MIN)
  1957. return -EINVAL;
  1958. return do_killpg(-pid, signal);
  1959. }
  1960. if (pid == -1)
  1961. return do_killall(signal);
  1962. if (pid == m_pid) {
  1963. return do_killself(signal);
  1964. }
  1965. InterruptDisabler disabler;
  1966. auto* peer = Process::from_pid(pid);
  1967. if (!peer)
  1968. return -ESRCH;
  1969. return do_kill(*peer, signal);
  1970. }
  1971. int Process::sys$usleep(useconds_t usec)
  1972. {
  1973. REQUIRE_PROMISE(stdio);
  1974. if (!usec)
  1975. return 0;
  1976. u64 wakeup_time = Thread::current->sleep(usec / 1000);
  1977. if (wakeup_time > g_uptime)
  1978. return -EINTR;
  1979. return 0;
  1980. }
  1981. int Process::sys$sleep(unsigned seconds)
  1982. {
  1983. REQUIRE_PROMISE(stdio);
  1984. if (!seconds)
  1985. return 0;
  1986. u64 wakeup_time = Thread::current->sleep(seconds * TimeManagement::the().ticks_per_second());
  1987. if (wakeup_time > g_uptime) {
  1988. u32 ticks_left_until_original_wakeup_time = wakeup_time - g_uptime;
  1989. return ticks_left_until_original_wakeup_time / TimeManagement::the().ticks_per_second();
  1990. }
  1991. return 0;
  1992. }
  1993. timeval kgettimeofday()
  1994. {
  1995. return g_timeofday;
  1996. }
  1997. void compute_relative_timeout_from_absolute(const timeval& absolute_time, timeval& relative_time)
  1998. {
  1999. // Convert absolute time to relative time of day.
  2000. timeval_sub(absolute_time, kgettimeofday(), relative_time);
  2001. }
  2002. void compute_relative_timeout_from_absolute(const timespec& absolute_time, timeval& relative_time)
  2003. {
  2004. timeval tv_absolute_time;
  2005. timespec_to_timeval(absolute_time, tv_absolute_time);
  2006. compute_relative_timeout_from_absolute(tv_absolute_time, relative_time);
  2007. }
  2008. void kgettimeofday(timeval& tv)
  2009. {
  2010. tv = kgettimeofday();
  2011. }
  2012. int Process::sys$gettimeofday(timeval* user_tv)
  2013. {
  2014. REQUIRE_PROMISE(stdio);
  2015. if (!validate_write_typed(user_tv))
  2016. return -EFAULT;
  2017. auto tv = kgettimeofday();
  2018. copy_to_user(user_tv, &tv);
  2019. return 0;
  2020. }
  2021. uid_t Process::sys$getuid()
  2022. {
  2023. REQUIRE_PROMISE(stdio);
  2024. return m_uid;
  2025. }
  2026. gid_t Process::sys$getgid()
  2027. {
  2028. REQUIRE_PROMISE(stdio);
  2029. return m_gid;
  2030. }
  2031. uid_t Process::sys$geteuid()
  2032. {
  2033. REQUIRE_PROMISE(stdio);
  2034. return m_euid;
  2035. }
  2036. gid_t Process::sys$getegid()
  2037. {
  2038. REQUIRE_PROMISE(stdio);
  2039. return m_egid;
  2040. }
  2041. pid_t Process::sys$getpid()
  2042. {
  2043. REQUIRE_PROMISE(stdio);
  2044. return m_pid;
  2045. }
  2046. pid_t Process::sys$getppid()
  2047. {
  2048. REQUIRE_PROMISE(stdio);
  2049. return m_ppid;
  2050. }
  2051. mode_t Process::sys$umask(mode_t mask)
  2052. {
  2053. REQUIRE_PROMISE(stdio);
  2054. auto old_mask = m_umask;
  2055. m_umask = mask & 0777;
  2056. return old_mask;
  2057. }
  2058. siginfo_t Process::reap(Process& process)
  2059. {
  2060. siginfo_t siginfo;
  2061. memset(&siginfo, 0, sizeof(siginfo));
  2062. siginfo.si_signo = SIGCHLD;
  2063. siginfo.si_pid = process.pid();
  2064. siginfo.si_uid = process.uid();
  2065. if (process.m_termination_signal) {
  2066. siginfo.si_status = process.m_termination_signal;
  2067. siginfo.si_code = CLD_KILLED;
  2068. } else {
  2069. siginfo.si_status = process.m_termination_status;
  2070. siginfo.si_code = CLD_EXITED;
  2071. }
  2072. {
  2073. InterruptDisabler disabler;
  2074. if (process.ppid()) {
  2075. auto* parent = Process::from_pid(process.ppid());
  2076. if (parent) {
  2077. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  2078. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  2079. }
  2080. }
  2081. #ifdef PROCESS_DEBUG
  2082. dbg() << "Reaping process " << process;
  2083. #endif
  2084. ASSERT(process.is_dead());
  2085. g_processes->remove(&process);
  2086. }
  2087. delete &process;
  2088. return siginfo;
  2089. }
  2090. KResultOr<siginfo_t> Process::do_waitid(idtype_t idtype, int id, int options)
  2091. {
  2092. if (idtype == P_PID) {
  2093. InterruptDisabler disabler;
  2094. if (idtype == P_PID && !Process::from_pid(id))
  2095. return KResult(-ECHILD);
  2096. }
  2097. pid_t waitee_pid;
  2098. // FIXME: WaitBlocker should support idtype/id specs directly.
  2099. if (idtype == P_ALL) {
  2100. waitee_pid = -1;
  2101. } else if (idtype == P_PID) {
  2102. waitee_pid = id;
  2103. } else {
  2104. // FIXME: Implement other PID specs.
  2105. return KResult(-EINVAL);
  2106. }
  2107. if (Thread::current->block<Thread::WaitBlocker>(options, waitee_pid) != Thread::BlockResult::WokeNormally)
  2108. return KResult(-EINTR);
  2109. InterruptDisabler disabler;
  2110. // NOTE: If waitee was -1, m_waitee_pid will have been filled in by the scheduler.
  2111. Process* waitee_process = Process::from_pid(waitee_pid);
  2112. if (!waitee_process)
  2113. return KResult(-ECHILD);
  2114. ASSERT(waitee_process);
  2115. if (waitee_process->is_dead()) {
  2116. return reap(*waitee_process);
  2117. } else {
  2118. auto* waitee_thread = Thread::from_tid(waitee_pid);
  2119. if (!waitee_thread)
  2120. return KResult(-ECHILD);
  2121. ASSERT((options & WNOHANG) || waitee_thread->state() == Thread::State::Stopped);
  2122. siginfo_t siginfo;
  2123. memset(&siginfo, 0, sizeof(siginfo));
  2124. siginfo.si_signo = SIGCHLD;
  2125. siginfo.si_pid = waitee_process->pid();
  2126. siginfo.si_uid = waitee_process->uid();
  2127. switch (waitee_thread->state()) {
  2128. case Thread::State::Stopped:
  2129. siginfo.si_code = CLD_STOPPED;
  2130. break;
  2131. case Thread::State::Running:
  2132. case Thread::State::Runnable:
  2133. case Thread::State::Blocked:
  2134. case Thread::State::Dying:
  2135. case Thread::State::Queued:
  2136. siginfo.si_code = CLD_CONTINUED;
  2137. break;
  2138. default:
  2139. ASSERT_NOT_REACHED();
  2140. break;
  2141. }
  2142. siginfo.si_status = waitee_thread->m_stop_signal;
  2143. return siginfo;
  2144. }
  2145. }
  2146. pid_t Process::sys$waitid(const Syscall::SC_waitid_params* user_params)
  2147. {
  2148. REQUIRE_PROMISE(proc);
  2149. Syscall::SC_waitid_params params;
  2150. if (!validate_read_and_copy_typed(&params, user_params))
  2151. return -EFAULT;
  2152. if (!validate_write_typed(params.infop))
  2153. return -EFAULT;
  2154. #ifdef PROCESS_DEBUG
  2155. dbg() << "sys$waitid(" << params.idtype << ", " << params.id << ", " << params.infop << ", " << params.options << ")";
  2156. #endif
  2157. auto siginfo_or_error = do_waitid(static_cast<idtype_t>(params.idtype), params.id, params.options);
  2158. if (siginfo_or_error.is_error())
  2159. return siginfo_or_error.error();
  2160. // While we waited, the process lock was dropped. This gave other threads
  2161. // the opportunity to mess with the memory. For example, it could free the
  2162. // region, and map it to a region to which it has no write permissions.
  2163. // Therefore, we need to re-validate the pointer.
  2164. if (!validate_write_typed(params.infop))
  2165. return -EFAULT;
  2166. copy_to_user(params.infop, &siginfo_or_error.value());
  2167. return 0;
  2168. }
  2169. bool Process::validate_read_from_kernel(VirtualAddress vaddr, size_t size) const
  2170. {
  2171. if (vaddr.is_null())
  2172. return false;
  2173. return MM.validate_kernel_read(*this, vaddr, size);
  2174. }
  2175. bool Process::validate_read(const void* address, size_t size) const
  2176. {
  2177. if (!size)
  2178. return false;
  2179. return MM.validate_user_read(*this, VirtualAddress(address), size);
  2180. }
  2181. bool Process::validate_write(void* address, size_t size) const
  2182. {
  2183. if (!size)
  2184. return false;
  2185. return MM.validate_user_write(*this, VirtualAddress(address), size);
  2186. }
  2187. pid_t Process::sys$getsid(pid_t pid)
  2188. {
  2189. REQUIRE_PROMISE(proc);
  2190. if (pid == 0)
  2191. return m_sid;
  2192. InterruptDisabler disabler;
  2193. auto* process = Process::from_pid(pid);
  2194. if (!process)
  2195. return -ESRCH;
  2196. if (m_sid != process->m_sid)
  2197. return -EPERM;
  2198. return process->m_sid;
  2199. }
  2200. pid_t Process::sys$setsid()
  2201. {
  2202. REQUIRE_PROMISE(proc);
  2203. InterruptDisabler disabler;
  2204. bool found_process_with_same_pgid_as_my_pid = false;
  2205. Process::for_each_in_pgrp(pid(), [&](auto&) {
  2206. found_process_with_same_pgid_as_my_pid = true;
  2207. return IterationDecision::Break;
  2208. });
  2209. if (found_process_with_same_pgid_as_my_pid)
  2210. return -EPERM;
  2211. m_sid = m_pid;
  2212. m_pgid = m_pid;
  2213. m_tty = nullptr;
  2214. return m_sid;
  2215. }
  2216. pid_t Process::sys$getpgid(pid_t pid)
  2217. {
  2218. REQUIRE_PROMISE(proc);
  2219. if (pid == 0)
  2220. return m_pgid;
  2221. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  2222. auto* process = Process::from_pid(pid);
  2223. if (!process)
  2224. return -ESRCH;
  2225. return process->m_pgid;
  2226. }
  2227. pid_t Process::sys$getpgrp()
  2228. {
  2229. REQUIRE_PROMISE(stdio);
  2230. return m_pgid;
  2231. }
  2232. static pid_t get_sid_from_pgid(pid_t pgid)
  2233. {
  2234. InterruptDisabler disabler;
  2235. auto* group_leader = Process::from_pid(pgid);
  2236. if (!group_leader)
  2237. return -1;
  2238. return group_leader->sid();
  2239. }
  2240. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  2241. {
  2242. REQUIRE_PROMISE(proc);
  2243. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  2244. pid_t pid = specified_pid ? specified_pid : m_pid;
  2245. if (specified_pgid < 0) {
  2246. // The value of the pgid argument is less than 0, or is not a value supported by the implementation.
  2247. return -EINVAL;
  2248. }
  2249. auto* process = Process::from_pid(pid);
  2250. if (!process)
  2251. return -ESRCH;
  2252. if (process != this && process->ppid() != m_pid) {
  2253. // The value of the pid argument does not match the process ID
  2254. // of the calling process or of a child process of the calling process.
  2255. return -ESRCH;
  2256. }
  2257. if (process->pid() == process->sid()) {
  2258. // The process indicated by the pid argument is a session leader.
  2259. return -EPERM;
  2260. }
  2261. if (process->ppid() == m_pid && process->sid() != sid()) {
  2262. // The value of the pid argument matches the process ID of a child
  2263. // process of the calling process and the child process is not in
  2264. // the same session as the calling process.
  2265. return -EPERM;
  2266. }
  2267. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  2268. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  2269. pid_t new_sid = get_sid_from_pgid(new_pgid);
  2270. if (current_sid != new_sid) {
  2271. // Can't move a process between sessions.
  2272. return -EPERM;
  2273. }
  2274. // FIXME: There are more EPERM conditions to check for here..
  2275. process->m_pgid = new_pgid;
  2276. return 0;
  2277. }
  2278. int Process::sys$ioctl(int fd, unsigned request, FlatPtr arg)
  2279. {
  2280. auto description = file_description(fd);
  2281. if (!description)
  2282. return -EBADF;
  2283. SmapDisabler disabler;
  2284. return description->file().ioctl(*description, request, arg);
  2285. }
  2286. int Process::sys$dup(int old_fd)
  2287. {
  2288. REQUIRE_PROMISE(stdio);
  2289. auto description = file_description(old_fd);
  2290. if (!description)
  2291. return -EBADF;
  2292. int new_fd = alloc_fd();
  2293. if (new_fd < 0)
  2294. return new_fd;
  2295. m_fds[new_fd].set(*description);
  2296. return new_fd;
  2297. }
  2298. int Process::sys$dup2(int old_fd, int new_fd)
  2299. {
  2300. REQUIRE_PROMISE(stdio);
  2301. auto description = file_description(old_fd);
  2302. if (!description)
  2303. return -EBADF;
  2304. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  2305. return -EINVAL;
  2306. m_fds[new_fd].set(*description);
  2307. return new_fd;
  2308. }
  2309. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  2310. {
  2311. REQUIRE_PROMISE(sigaction);
  2312. if (old_set) {
  2313. if (!validate_write_typed(old_set))
  2314. return -EFAULT;
  2315. copy_to_user(old_set, &Thread::current->m_signal_mask);
  2316. }
  2317. if (set) {
  2318. if (!validate_read_typed(set))
  2319. return -EFAULT;
  2320. sigset_t set_value;
  2321. copy_from_user(&set_value, set);
  2322. switch (how) {
  2323. case SIG_BLOCK:
  2324. Thread::current->m_signal_mask &= ~set_value;
  2325. break;
  2326. case SIG_UNBLOCK:
  2327. Thread::current->m_signal_mask |= set_value;
  2328. break;
  2329. case SIG_SETMASK:
  2330. Thread::current->m_signal_mask = set_value;
  2331. break;
  2332. default:
  2333. return -EINVAL;
  2334. }
  2335. }
  2336. return 0;
  2337. }
  2338. int Process::sys$sigpending(sigset_t* set)
  2339. {
  2340. REQUIRE_PROMISE(stdio);
  2341. if (!validate_write_typed(set))
  2342. return -EFAULT;
  2343. copy_to_user(set, &Thread::current->m_pending_signals);
  2344. return 0;
  2345. }
  2346. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  2347. {
  2348. REQUIRE_PROMISE(sigaction);
  2349. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  2350. return -EINVAL;
  2351. if (!validate_read_typed(act))
  2352. return -EFAULT;
  2353. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  2354. auto& action = Thread::current->m_signal_action_data[signum];
  2355. if (old_act) {
  2356. if (!validate_write_typed(old_act))
  2357. return -EFAULT;
  2358. copy_to_user(&old_act->sa_flags, &action.flags);
  2359. copy_to_user(&old_act->sa_sigaction, &action.handler_or_sigaction, sizeof(action.handler_or_sigaction));
  2360. }
  2361. copy_from_user(&action.flags, &act->sa_flags);
  2362. copy_from_user(&action.handler_or_sigaction, &act->sa_sigaction, sizeof(action.handler_or_sigaction));
  2363. return 0;
  2364. }
  2365. int Process::sys$getgroups(ssize_t count, gid_t* user_gids)
  2366. {
  2367. REQUIRE_PROMISE(stdio);
  2368. if (count < 0)
  2369. return -EINVAL;
  2370. if (!count)
  2371. return m_extra_gids.size();
  2372. if (count != (int)m_extra_gids.size())
  2373. return -EINVAL;
  2374. if (!validate_write_typed(user_gids, m_extra_gids.size()))
  2375. return -EFAULT;
  2376. Vector<gid_t> gids;
  2377. for (auto gid : m_extra_gids)
  2378. gids.append(gid);
  2379. copy_to_user(user_gids, gids.data(), sizeof(gid_t) * count);
  2380. return 0;
  2381. }
  2382. int Process::sys$setgroups(ssize_t count, const gid_t* user_gids)
  2383. {
  2384. REQUIRE_PROMISE(id);
  2385. if (count < 0)
  2386. return -EINVAL;
  2387. if (!is_superuser())
  2388. return -EPERM;
  2389. if (count && !validate_read(user_gids, count))
  2390. return -EFAULT;
  2391. if (!count) {
  2392. m_extra_gids.clear();
  2393. return 0;
  2394. }
  2395. Vector<gid_t> gids;
  2396. gids.resize(count);
  2397. copy_from_user(gids.data(), user_gids, sizeof(gid_t) * count);
  2398. HashTable<gid_t> unique_extra_gids;
  2399. for (auto& gid : gids) {
  2400. if (gid != m_gid)
  2401. unique_extra_gids.set(gid);
  2402. }
  2403. m_extra_gids.resize(unique_extra_gids.size());
  2404. size_t i = 0;
  2405. for (auto& gid : unique_extra_gids) {
  2406. if (gid == m_gid)
  2407. continue;
  2408. m_extra_gids[i++] = gid;
  2409. }
  2410. return 0;
  2411. }
  2412. int Process::sys$mkdir(const char* user_path, size_t path_length, mode_t mode)
  2413. {
  2414. REQUIRE_PROMISE(cpath);
  2415. auto path = get_syscall_path_argument(user_path, path_length);
  2416. if (path.is_error())
  2417. return path.error();
  2418. return VFS::the().mkdir(path.value(), mode & ~umask(), current_directory());
  2419. }
  2420. int Process::sys$realpath(const Syscall::SC_realpath_params* user_params)
  2421. {
  2422. REQUIRE_PROMISE(rpath);
  2423. Syscall::SC_realpath_params params;
  2424. if (!validate_read_and_copy_typed(&params, user_params))
  2425. return -EFAULT;
  2426. if (!validate_write(params.buffer.data, params.buffer.size))
  2427. return -EFAULT;
  2428. auto path = get_syscall_path_argument(params.path);
  2429. if (path.is_error())
  2430. return path.error();
  2431. auto custody_or_error = VFS::the().resolve_path(path.value(), current_directory());
  2432. if (custody_or_error.is_error())
  2433. return custody_or_error.error();
  2434. auto& custody = custody_or_error.value();
  2435. auto absolute_path = custody->absolute_path();
  2436. if (absolute_path.length() + 1 > params.buffer.size)
  2437. return -ENAMETOOLONG;
  2438. copy_to_user(params.buffer.data, absolute_path.characters(), absolute_path.length() + 1);
  2439. return 0;
  2440. };
  2441. clock_t Process::sys$times(tms* times)
  2442. {
  2443. REQUIRE_PROMISE(stdio);
  2444. if (!validate_write_typed(times))
  2445. return -EFAULT;
  2446. copy_to_user(&times->tms_utime, &m_ticks_in_user);
  2447. copy_to_user(&times->tms_stime, &m_ticks_in_kernel);
  2448. copy_to_user(&times->tms_cutime, &m_ticks_in_user_for_dead_children);
  2449. copy_to_user(&times->tms_cstime, &m_ticks_in_kernel_for_dead_children);
  2450. return g_uptime & 0x7fffffff;
  2451. }
  2452. int Process::sys$select(const Syscall::SC_select_params* params)
  2453. {
  2454. REQUIRE_PROMISE(stdio);
  2455. // FIXME: Return -EINVAL if timeout is invalid.
  2456. if (!validate_read_typed(params))
  2457. return -EFAULT;
  2458. SmapDisabler disabler;
  2459. int nfds = params->nfds;
  2460. fd_set* readfds = params->readfds;
  2461. fd_set* writefds = params->writefds;
  2462. fd_set* exceptfds = params->exceptfds;
  2463. timeval* timeout = params->timeout;
  2464. if (writefds && !validate_write_typed(writefds))
  2465. return -EFAULT;
  2466. if (readfds && !validate_write_typed(readfds))
  2467. return -EFAULT;
  2468. if (exceptfds && !validate_write_typed(exceptfds))
  2469. return -EFAULT;
  2470. if (timeout && !validate_read_typed(timeout))
  2471. return -EFAULT;
  2472. if (nfds < 0)
  2473. return -EINVAL;
  2474. timeval computed_timeout;
  2475. bool select_has_timeout = false;
  2476. if (timeout && (timeout->tv_sec || timeout->tv_usec)) {
  2477. timeval_add(Scheduler::time_since_boot(), *timeout, computed_timeout);
  2478. select_has_timeout = true;
  2479. }
  2480. Thread::SelectBlocker::FDVector rfds;
  2481. Thread::SelectBlocker::FDVector wfds;
  2482. Thread::SelectBlocker::FDVector efds;
  2483. auto transfer_fds = [&](auto* fds, auto& vector) -> int {
  2484. vector.clear_with_capacity();
  2485. if (!fds)
  2486. return 0;
  2487. for (int fd = 0; fd < nfds; ++fd) {
  2488. if (FD_ISSET(fd, fds)) {
  2489. if (!file_description(fd)) {
  2490. dbg() << "sys$select: Bad fd number " << fd;
  2491. return -EBADF;
  2492. }
  2493. vector.append(fd);
  2494. }
  2495. }
  2496. return 0;
  2497. };
  2498. if (int error = transfer_fds(writefds, wfds))
  2499. return error;
  2500. if (int error = transfer_fds(readfds, rfds))
  2501. return error;
  2502. if (int error = transfer_fds(exceptfds, efds))
  2503. return error;
  2504. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  2505. dbg() << "selecting on (read:" << rfds.size() << ", write:" << wfds.size() << "), timeout=" << timeout;
  2506. #endif
  2507. if (!timeout || select_has_timeout) {
  2508. if (Thread::current->block<Thread::SelectBlocker>(computed_timeout, select_has_timeout, rfds, wfds, efds) != Thread::BlockResult::WokeNormally)
  2509. return -EINTR;
  2510. // While we blocked, the process lock was dropped. This gave other threads
  2511. // the opportunity to mess with the memory. For example, it could free the
  2512. // region, and map it to a region to which it has no write permissions.
  2513. // Therefore, we need to re-validate all pointers.
  2514. if (writefds && !validate_write_typed(writefds))
  2515. return -EFAULT;
  2516. if (readfds && !validate_write_typed(readfds))
  2517. return -EFAULT;
  2518. // See the fixme below.
  2519. if (exceptfds && !validate_write_typed(exceptfds))
  2520. return -EFAULT;
  2521. }
  2522. int marked_fd_count = 0;
  2523. auto mark_fds = [&](auto* fds, auto& vector, auto should_mark) {
  2524. if (!fds)
  2525. return;
  2526. FD_ZERO(fds);
  2527. for (int fd : vector) {
  2528. if (auto description = file_description(fd); description && should_mark(*description)) {
  2529. FD_SET(fd, fds);
  2530. ++marked_fd_count;
  2531. }
  2532. }
  2533. };
  2534. mark_fds(readfds, rfds, [](auto& description) { return description.can_read(); });
  2535. mark_fds(writefds, wfds, [](auto& description) { return description.can_write(); });
  2536. // FIXME: We should also mark exceptfds as appropriate.
  2537. return marked_fd_count;
  2538. }
  2539. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  2540. {
  2541. REQUIRE_PROMISE(stdio);
  2542. if (!validate_read_typed(fds))
  2543. return -EFAULT;
  2544. SmapDisabler disabler;
  2545. Thread::SelectBlocker::FDVector rfds;
  2546. Thread::SelectBlocker::FDVector wfds;
  2547. for (int i = 0; i < nfds; ++i) {
  2548. if (fds[i].events & POLLIN)
  2549. rfds.append(fds[i].fd);
  2550. if (fds[i].events & POLLOUT)
  2551. wfds.append(fds[i].fd);
  2552. }
  2553. timeval actual_timeout;
  2554. bool has_timeout = false;
  2555. if (timeout >= 0) {
  2556. // poll is in ms, we want s/us.
  2557. struct timeval tvtimeout;
  2558. tvtimeout.tv_sec = 0;
  2559. while (timeout >= 1000) {
  2560. tvtimeout.tv_sec += 1;
  2561. timeout -= 1000;
  2562. }
  2563. tvtimeout.tv_usec = timeout * 1000;
  2564. timeval_add(Scheduler::time_since_boot(), tvtimeout, actual_timeout);
  2565. has_timeout = true;
  2566. }
  2567. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  2568. dbg() << "polling on (read:" << rfds.size() << ", write:" << wfds.size() << "), timeout=" << timeout;
  2569. #endif
  2570. if (has_timeout || timeout < 0) {
  2571. if (Thread::current->block<Thread::SelectBlocker>(actual_timeout, has_timeout, rfds, wfds, Thread::SelectBlocker::FDVector()) != Thread::BlockResult::WokeNormally)
  2572. return -EINTR;
  2573. }
  2574. int fds_with_revents = 0;
  2575. for (int i = 0; i < nfds; ++i) {
  2576. auto description = file_description(fds[i].fd);
  2577. if (!description) {
  2578. fds[i].revents = POLLNVAL;
  2579. continue;
  2580. }
  2581. fds[i].revents = 0;
  2582. if (fds[i].events & POLLIN && description->can_read())
  2583. fds[i].revents |= POLLIN;
  2584. if (fds[i].events & POLLOUT && description->can_write())
  2585. fds[i].revents |= POLLOUT;
  2586. if (fds[i].revents)
  2587. ++fds_with_revents;
  2588. }
  2589. return fds_with_revents;
  2590. }
  2591. Custody& Process::current_directory()
  2592. {
  2593. if (!m_cwd)
  2594. m_cwd = VFS::the().root_custody();
  2595. return *m_cwd;
  2596. }
  2597. int Process::sys$link(const Syscall::SC_link_params* user_params)
  2598. {
  2599. REQUIRE_PROMISE(cpath);
  2600. Syscall::SC_link_params params;
  2601. if (!validate_read_and_copy_typed(&params, user_params))
  2602. return -EFAULT;
  2603. auto old_path = validate_and_copy_string_from_user(params.old_path);
  2604. auto new_path = validate_and_copy_string_from_user(params.new_path);
  2605. if (old_path.is_null() || new_path.is_null())
  2606. return -EFAULT;
  2607. return VFS::the().link(old_path, new_path, current_directory());
  2608. }
  2609. int Process::sys$unlink(const char* user_path, size_t path_length)
  2610. {
  2611. REQUIRE_PROMISE(cpath);
  2612. if (!validate_read(user_path, path_length))
  2613. return -EFAULT;
  2614. auto path = get_syscall_path_argument(user_path, path_length);
  2615. if (path.is_error())
  2616. return path.error();
  2617. return VFS::the().unlink(path.value(), current_directory());
  2618. }
  2619. int Process::sys$symlink(const Syscall::SC_symlink_params* user_params)
  2620. {
  2621. REQUIRE_PROMISE(cpath);
  2622. Syscall::SC_symlink_params params;
  2623. if (!validate_read_and_copy_typed(&params, user_params))
  2624. return -EFAULT;
  2625. auto target = get_syscall_path_argument(params.target);
  2626. if (target.is_error())
  2627. return target.error();
  2628. auto linkpath = get_syscall_path_argument(params.linkpath);
  2629. if (linkpath.is_error())
  2630. return linkpath.error();
  2631. return VFS::the().symlink(target.value(), linkpath.value(), current_directory());
  2632. }
  2633. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  2634. {
  2635. if (path_length == 0)
  2636. return KResult(-EINVAL);
  2637. if (path_length > PATH_MAX)
  2638. return KResult(-ENAMETOOLONG);
  2639. if (!validate_read(user_path, path_length))
  2640. return KResult(-EFAULT);
  2641. return copy_string_from_user(user_path, path_length);
  2642. }
  2643. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  2644. {
  2645. return get_syscall_path_argument(path.characters, path.length);
  2646. }
  2647. int Process::sys$rmdir(const char* user_path, size_t path_length)
  2648. {
  2649. REQUIRE_PROMISE(cpath);
  2650. auto path = get_syscall_path_argument(user_path, path_length);
  2651. if (path.is_error())
  2652. return path.error();
  2653. return VFS::the().rmdir(path.value(), current_directory());
  2654. }
  2655. int Process::sys$chmod(const char* user_path, size_t path_length, mode_t mode)
  2656. {
  2657. REQUIRE_PROMISE(fattr);
  2658. auto path = get_syscall_path_argument(user_path, path_length);
  2659. if (path.is_error())
  2660. return path.error();
  2661. return VFS::the().chmod(path.value(), mode, current_directory());
  2662. }
  2663. int Process::sys$fchmod(int fd, mode_t mode)
  2664. {
  2665. REQUIRE_PROMISE(fattr);
  2666. auto description = file_description(fd);
  2667. if (!description)
  2668. return -EBADF;
  2669. return description->chmod(mode);
  2670. }
  2671. int Process::sys$fchown(int fd, uid_t uid, gid_t gid)
  2672. {
  2673. REQUIRE_PROMISE(chown);
  2674. auto description = file_description(fd);
  2675. if (!description)
  2676. return -EBADF;
  2677. return description->chown(uid, gid);
  2678. }
  2679. int Process::sys$chown(const Syscall::SC_chown_params* user_params)
  2680. {
  2681. REQUIRE_PROMISE(chown);
  2682. Syscall::SC_chown_params params;
  2683. if (!validate_read_and_copy_typed(&params, user_params))
  2684. return -EFAULT;
  2685. auto path = get_syscall_path_argument(params.path);
  2686. if (path.is_error())
  2687. return path.error();
  2688. return VFS::the().chown(path.value(), params.uid, params.gid, current_directory());
  2689. }
  2690. void Process::finalize()
  2691. {
  2692. ASSERT(Thread::current == g_finalizer);
  2693. #ifdef PROCESS_DEBUG
  2694. dbg() << "Finalizing process " << *this;
  2695. #endif
  2696. if (m_perf_event_buffer) {
  2697. auto description_or_error = VFS::the().open(String::format("perfcore.%d", m_pid), O_CREAT | O_EXCL, 0400, current_directory(), UidAndGid { m_uid, m_gid });
  2698. if (!description_or_error.is_error()) {
  2699. auto& description = description_or_error.value();
  2700. auto json = m_perf_event_buffer->to_json(m_pid, m_executable ? m_executable->absolute_path() : "");
  2701. description->write(json.data(), json.size());
  2702. }
  2703. }
  2704. m_fds.clear();
  2705. m_tty = nullptr;
  2706. m_executable = nullptr;
  2707. m_cwd = nullptr;
  2708. m_root_directory = nullptr;
  2709. m_root_directory_relative_to_global_root = nullptr;
  2710. disown_all_shared_buffers();
  2711. {
  2712. InterruptDisabler disabler;
  2713. if (auto* parent_thread = Thread::from_tid(m_ppid)) {
  2714. if (parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  2715. // NOTE: If the parent doesn't care about this process, let it go.
  2716. m_ppid = 0;
  2717. } else {
  2718. parent_thread->send_signal(SIGCHLD, this);
  2719. }
  2720. }
  2721. }
  2722. m_regions.clear();
  2723. m_dead = true;
  2724. }
  2725. void Process::die()
  2726. {
  2727. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  2728. // getting an EOF when the last process using the slave PTY dies.
  2729. // If the master PTY owner relies on an EOF to know when to wait() on a
  2730. // slave owner, we have to allow the PTY pair to be torn down.
  2731. m_tty = nullptr;
  2732. kill_all_threads();
  2733. }
  2734. size_t Process::amount_dirty_private() const
  2735. {
  2736. // FIXME: This gets a bit more complicated for Regions sharing the same underlying VMObject.
  2737. // The main issue I'm thinking of is when the VMObject has physical pages that none of the Regions are mapping.
  2738. // That's probably a situation that needs to be looked at in general.
  2739. size_t amount = 0;
  2740. for (auto& region : m_regions) {
  2741. if (!region.is_shared())
  2742. amount += region.amount_dirty();
  2743. }
  2744. return amount;
  2745. }
  2746. size_t Process::amount_clean_inode() const
  2747. {
  2748. HashTable<const InodeVMObject*> vmobjects;
  2749. for (auto& region : m_regions) {
  2750. if (region.vmobject().is_inode())
  2751. vmobjects.set(&static_cast<const InodeVMObject&>(region.vmobject()));
  2752. }
  2753. size_t amount = 0;
  2754. for (auto& vmobject : vmobjects)
  2755. amount += vmobject->amount_clean();
  2756. return amount;
  2757. }
  2758. size_t Process::amount_virtual() const
  2759. {
  2760. size_t amount = 0;
  2761. for (auto& region : m_regions) {
  2762. amount += region.size();
  2763. }
  2764. return amount;
  2765. }
  2766. size_t Process::amount_resident() const
  2767. {
  2768. // FIXME: This will double count if multiple regions use the same physical page.
  2769. size_t amount = 0;
  2770. for (auto& region : m_regions) {
  2771. amount += region.amount_resident();
  2772. }
  2773. return amount;
  2774. }
  2775. size_t Process::amount_shared() const
  2776. {
  2777. // FIXME: This will double count if multiple regions use the same physical page.
  2778. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  2779. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  2780. // so that every Region contributes +1 ref to each of its PhysicalPages.
  2781. size_t amount = 0;
  2782. for (auto& region : m_regions) {
  2783. amount += region.amount_shared();
  2784. }
  2785. return amount;
  2786. }
  2787. size_t Process::amount_purgeable_volatile() const
  2788. {
  2789. size_t amount = 0;
  2790. for (auto& region : m_regions) {
  2791. if (region.vmobject().is_purgeable() && static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  2792. amount += region.amount_resident();
  2793. }
  2794. return amount;
  2795. }
  2796. size_t Process::amount_purgeable_nonvolatile() const
  2797. {
  2798. size_t amount = 0;
  2799. for (auto& region : m_regions) {
  2800. if (region.vmobject().is_purgeable() && !static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  2801. amount += region.amount_resident();
  2802. }
  2803. return amount;
  2804. }
  2805. #define REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(domain) \
  2806. do { \
  2807. if (domain == AF_INET) \
  2808. REQUIRE_PROMISE(inet); \
  2809. else if (domain == AF_LOCAL) \
  2810. REQUIRE_PROMISE(unix); \
  2811. } while (0)
  2812. int Process::sys$socket(int domain, int type, int protocol)
  2813. {
  2814. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(domain);
  2815. if ((type & SOCK_TYPE_MASK) == SOCK_RAW && !is_superuser())
  2816. return -EACCES;
  2817. int fd = alloc_fd();
  2818. if (fd < 0)
  2819. return fd;
  2820. auto result = Socket::create(domain, type, protocol);
  2821. if (result.is_error())
  2822. return result.error();
  2823. auto description = FileDescription::create(*result.value());
  2824. description->set_readable(true);
  2825. description->set_writable(true);
  2826. unsigned flags = 0;
  2827. if (type & SOCK_CLOEXEC)
  2828. flags |= FD_CLOEXEC;
  2829. if (type & SOCK_NONBLOCK)
  2830. description->set_blocking(false);
  2831. m_fds[fd].set(move(description), flags);
  2832. return fd;
  2833. }
  2834. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2835. {
  2836. if (!validate_read(address, address_length))
  2837. return -EFAULT;
  2838. auto description = file_description(sockfd);
  2839. if (!description)
  2840. return -EBADF;
  2841. if (!description->is_socket())
  2842. return -ENOTSOCK;
  2843. auto& socket = *description->socket();
  2844. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2845. return socket.bind(address, address_length);
  2846. }
  2847. int Process::sys$listen(int sockfd, int backlog)
  2848. {
  2849. if (backlog < 0)
  2850. return -EINVAL;
  2851. auto description = file_description(sockfd);
  2852. if (!description)
  2853. return -EBADF;
  2854. if (!description->is_socket())
  2855. return -ENOTSOCK;
  2856. auto& socket = *description->socket();
  2857. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2858. if (socket.is_connected())
  2859. return -EINVAL;
  2860. return socket.listen(backlog);
  2861. }
  2862. int Process::sys$accept(int accepting_socket_fd, sockaddr* user_address, socklen_t* user_address_size)
  2863. {
  2864. REQUIRE_PROMISE(accept);
  2865. if (!validate_write_typed(user_address_size))
  2866. return -EFAULT;
  2867. socklen_t address_size = 0;
  2868. copy_from_user(&address_size, user_address_size);
  2869. if (!validate_write(user_address, address_size))
  2870. return -EFAULT;
  2871. int accepted_socket_fd = alloc_fd();
  2872. if (accepted_socket_fd < 0)
  2873. return accepted_socket_fd;
  2874. auto accepting_socket_description = file_description(accepting_socket_fd);
  2875. if (!accepting_socket_description)
  2876. return -EBADF;
  2877. if (!accepting_socket_description->is_socket())
  2878. return -ENOTSOCK;
  2879. auto& socket = *accepting_socket_description->socket();
  2880. if (!socket.can_accept()) {
  2881. if (accepting_socket_description->is_blocking()) {
  2882. if (Thread::current->block<Thread::AcceptBlocker>(*accepting_socket_description) != Thread::BlockResult::WokeNormally)
  2883. return -EINTR;
  2884. } else {
  2885. return -EAGAIN;
  2886. }
  2887. }
  2888. auto accepted_socket = socket.accept();
  2889. ASSERT(accepted_socket);
  2890. u8 address_buffer[sizeof(sockaddr_un)];
  2891. address_size = min(sizeof(sockaddr_un), static_cast<size_t>(address_size));
  2892. accepted_socket->get_peer_address((sockaddr*)address_buffer, &address_size);
  2893. copy_to_user(user_address, address_buffer, address_size);
  2894. copy_to_user(user_address_size, &address_size);
  2895. auto accepted_socket_description = FileDescription::create(*accepted_socket);
  2896. accepted_socket_description->set_readable(true);
  2897. accepted_socket_description->set_writable(true);
  2898. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2899. // I'm not sure if this matches other systems but it makes sense to me.
  2900. accepted_socket_description->set_blocking(accepting_socket_description->is_blocking());
  2901. m_fds[accepted_socket_fd].set(move(accepted_socket_description), m_fds[accepting_socket_fd].flags);
  2902. // NOTE: Moving this state to Completed is what causes connect() to unblock on the client side.
  2903. accepted_socket->set_setup_state(Socket::SetupState::Completed);
  2904. return accepted_socket_fd;
  2905. }
  2906. int Process::sys$connect(int sockfd, const sockaddr* user_address, socklen_t user_address_size)
  2907. {
  2908. if (!validate_read(user_address, user_address_size))
  2909. return -EFAULT;
  2910. int fd = alloc_fd();
  2911. if (fd < 0)
  2912. return fd;
  2913. auto description = file_description(sockfd);
  2914. if (!description)
  2915. return -EBADF;
  2916. if (!description->is_socket())
  2917. return -ENOTSOCK;
  2918. auto& socket = *description->socket();
  2919. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2920. u8 address[sizeof(sockaddr_un)];
  2921. size_t address_size = min(sizeof(address), static_cast<size_t>(user_address_size));
  2922. copy_from_user(address, user_address, address_size);
  2923. return socket.connect(*description, (const sockaddr*)address, address_size, description->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  2924. }
  2925. int Process::sys$shutdown(int sockfd, int how)
  2926. {
  2927. REQUIRE_PROMISE(stdio);
  2928. if (how & ~SHUT_RDWR)
  2929. return -EINVAL;
  2930. auto description = file_description(sockfd);
  2931. if (!description)
  2932. return -EBADF;
  2933. if (!description->is_socket())
  2934. return -ENOTSOCK;
  2935. auto& socket = *description->socket();
  2936. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2937. return socket.shutdown(how);
  2938. }
  2939. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* user_params)
  2940. {
  2941. REQUIRE_PROMISE(stdio);
  2942. Syscall::SC_sendto_params params;
  2943. if (!validate_read_and_copy_typed(&params, user_params))
  2944. return -EFAULT;
  2945. int flags = params.flags;
  2946. const sockaddr* addr = params.addr;
  2947. socklen_t addr_length = params.addr_length;
  2948. if (!validate(params.data))
  2949. return -EFAULT;
  2950. if (addr && !validate_read(addr, addr_length))
  2951. return -EFAULT;
  2952. auto description = file_description(params.sockfd);
  2953. if (!description)
  2954. return -EBADF;
  2955. if (!description->is_socket())
  2956. return -ENOTSOCK;
  2957. auto& socket = *description->socket();
  2958. if (socket.is_shut_down_for_writing())
  2959. return -EPIPE;
  2960. SmapDisabler disabler;
  2961. return socket.sendto(*description, params.data.data, params.data.size, flags, addr, addr_length);
  2962. }
  2963. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* user_params)
  2964. {
  2965. REQUIRE_PROMISE(stdio);
  2966. Syscall::SC_recvfrom_params params;
  2967. if (!validate_read_and_copy_typed(&params, user_params))
  2968. return -EFAULT;
  2969. int flags = params.flags;
  2970. sockaddr* addr = params.addr;
  2971. socklen_t* addr_length = params.addr_length;
  2972. SmapDisabler disabler;
  2973. if (!validate(params.buffer))
  2974. return -EFAULT;
  2975. if (addr_length) {
  2976. if (!validate_write_typed(addr_length))
  2977. return -EFAULT;
  2978. if (!validate_write(addr, *addr_length))
  2979. return -EFAULT;
  2980. } else if (addr) {
  2981. return -EINVAL;
  2982. }
  2983. auto description = file_description(params.sockfd);
  2984. if (!description)
  2985. return -EBADF;
  2986. if (!description->is_socket())
  2987. return -ENOTSOCK;
  2988. auto& socket = *description->socket();
  2989. if (socket.is_shut_down_for_reading())
  2990. return 0;
  2991. bool original_blocking = description->is_blocking();
  2992. if (flags & MSG_DONTWAIT)
  2993. description->set_blocking(false);
  2994. auto nrecv = socket.recvfrom(*description, params.buffer.data, params.buffer.size, flags, addr, addr_length);
  2995. if (flags & MSG_DONTWAIT)
  2996. description->set_blocking(original_blocking);
  2997. return nrecv;
  2998. }
  2999. template<bool sockname, typename Params>
  3000. int Process::get_sock_or_peer_name(const Params& params)
  3001. {
  3002. socklen_t addrlen_value;
  3003. if (!validate_read_and_copy_typed(&addrlen_value, params.addrlen))
  3004. return -EFAULT;
  3005. if (addrlen_value <= 0)
  3006. return -EINVAL;
  3007. if (!validate_write(params.addr, addrlen_value))
  3008. return -EFAULT;
  3009. if (!validate_write_typed(params.addrlen))
  3010. return -EFAULT;
  3011. auto description = file_description(params.sockfd);
  3012. if (!description)
  3013. return -EBADF;
  3014. if (!description->is_socket())
  3015. return -ENOTSOCK;
  3016. auto& socket = *description->socket();
  3017. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  3018. u8 address_buffer[sizeof(sockaddr_un)];
  3019. addrlen_value = min(sizeof(sockaddr_un), static_cast<size_t>(addrlen_value));
  3020. if constexpr (sockname)
  3021. socket.get_local_address((sockaddr*)address_buffer, &addrlen_value);
  3022. else
  3023. socket.get_peer_address((sockaddr*)address_buffer, &addrlen_value);
  3024. copy_to_user(params.addr, address_buffer, addrlen_value);
  3025. copy_to_user(params.addrlen, &addrlen_value);
  3026. return 0;
  3027. }
  3028. int Process::sys$getsockname(const Syscall::SC_getsockname_params* user_params)
  3029. {
  3030. Syscall::SC_getsockname_params params;
  3031. if (!validate_read_and_copy_typed(&params, user_params))
  3032. return -EFAULT;
  3033. return get_sock_or_peer_name<true>(params);
  3034. }
  3035. int Process::sys$getpeername(const Syscall::SC_getpeername_params* user_params)
  3036. {
  3037. Syscall::SC_getpeername_params params;
  3038. if (!validate_read_and_copy_typed(&params, user_params))
  3039. return -EFAULT;
  3040. return get_sock_or_peer_name<false>(params);
  3041. }
  3042. int Process::sys$sched_setparam(int tid, const struct sched_param* param)
  3043. {
  3044. REQUIRE_PROMISE(proc);
  3045. if (!validate_read_typed(param))
  3046. return -EFAULT;
  3047. int desired_priority;
  3048. copy_from_user(&desired_priority, &param->sched_priority);
  3049. InterruptDisabler disabler;
  3050. auto* peer = Thread::current;
  3051. if (tid != 0)
  3052. peer = Thread::from_tid(tid);
  3053. if (!peer)
  3054. return -ESRCH;
  3055. if (!is_superuser() && m_euid != peer->process().m_uid && m_uid != peer->process().m_uid)
  3056. return -EPERM;
  3057. if (desired_priority < THREAD_PRIORITY_MIN || desired_priority > THREAD_PRIORITY_MAX)
  3058. return -EINVAL;
  3059. peer->set_priority((u32)desired_priority);
  3060. return 0;
  3061. }
  3062. int Process::sys$sched_getparam(pid_t pid, struct sched_param* param)
  3063. {
  3064. REQUIRE_PROMISE(proc);
  3065. if (!validate_write_typed(param))
  3066. return -EFAULT;
  3067. InterruptDisabler disabler;
  3068. auto* peer = Thread::current;
  3069. if (pid != 0)
  3070. peer = Thread::from_tid(pid);
  3071. if (!peer)
  3072. return -ESRCH;
  3073. if (!is_superuser() && m_euid != peer->process().m_uid && m_uid != peer->process().m_uid)
  3074. return -EPERM;
  3075. int priority = peer->priority();
  3076. copy_to_user(&param->sched_priority, &priority);
  3077. return 0;
  3078. }
  3079. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  3080. {
  3081. if (!validate_read_typed(params))
  3082. return -EFAULT;
  3083. SmapDisabler disabler;
  3084. int sockfd = params->sockfd;
  3085. int level = params->level;
  3086. int option = params->option;
  3087. void* value = params->value;
  3088. socklen_t* value_size = params->value_size;
  3089. if (!validate_write_typed(value_size))
  3090. return -EFAULT;
  3091. if (!validate_write(value, *value_size))
  3092. return -EFAULT;
  3093. auto description = file_description(sockfd);
  3094. if (!description)
  3095. return -EBADF;
  3096. if (!description->is_socket())
  3097. return -ENOTSOCK;
  3098. auto& socket = *description->socket();
  3099. if (has_promised(Pledge::accept) && socket.is_local() && level == SOL_SOCKET && option == SO_PEERCRED) {
  3100. // We make an exception for SOL_SOCKET::SO_PEERCRED on local sockets if you've pledged "accept"
  3101. } else {
  3102. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  3103. }
  3104. return socket.getsockopt(*description, level, option, value, value_size);
  3105. }
  3106. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  3107. {
  3108. if (!validate_read_typed(params))
  3109. return -EFAULT;
  3110. SmapDisabler disabler;
  3111. int sockfd = params->sockfd;
  3112. int level = params->level;
  3113. int option = params->option;
  3114. const void* value = params->value;
  3115. socklen_t value_size = params->value_size;
  3116. if (!validate_read(value, value_size))
  3117. return -EFAULT;
  3118. auto description = file_description(sockfd);
  3119. if (!description)
  3120. return -EBADF;
  3121. if (!description->is_socket())
  3122. return -ENOTSOCK;
  3123. auto& socket = *description->socket();
  3124. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  3125. return socket.setsockopt(level, option, value, value_size);
  3126. }
  3127. void Process::disown_all_shared_buffers()
  3128. {
  3129. LOCKER(shared_buffers().lock());
  3130. Vector<SharedBuffer*, 32> buffers_to_disown;
  3131. for (auto& it : shared_buffers().resource())
  3132. buffers_to_disown.append(it.value.ptr());
  3133. for (auto* shared_buffer : buffers_to_disown)
  3134. shared_buffer->disown(m_pid);
  3135. }
  3136. int Process::sys$shbuf_create(int size, void** buffer)
  3137. {
  3138. REQUIRE_PROMISE(shared_buffer);
  3139. if (!size || size < 0)
  3140. return -EINVAL;
  3141. size = PAGE_ROUND_UP(size);
  3142. if (!validate_write_typed(buffer))
  3143. return -EFAULT;
  3144. LOCKER(shared_buffers().lock());
  3145. static int s_next_shbuf_id;
  3146. int shbuf_id = ++s_next_shbuf_id;
  3147. auto shared_buffer = make<SharedBuffer>(shbuf_id, size);
  3148. shared_buffer->share_with(m_pid);
  3149. void* address = shared_buffer->ref_for_process_and_get_address(*this);
  3150. copy_to_user(buffer, &address);
  3151. ASSERT((int)shared_buffer->size() >= size);
  3152. #ifdef SHARED_BUFFER_DEBUG
  3153. klog() << "Created shared buffer " << shbuf_id << " @ " << buffer << " (" << size << " bytes, vmobject is " << shared_buffer->size() << ")";
  3154. #endif
  3155. shared_buffers().resource().set(shbuf_id, move(shared_buffer));
  3156. return shbuf_id;
  3157. }
  3158. int Process::sys$shbuf_allow_pid(int shbuf_id, pid_t peer_pid)
  3159. {
  3160. REQUIRE_PROMISE(shared_buffer);
  3161. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  3162. return -EINVAL;
  3163. LOCKER(shared_buffers().lock());
  3164. auto it = shared_buffers().resource().find(shbuf_id);
  3165. if (it == shared_buffers().resource().end())
  3166. return -EINVAL;
  3167. auto& shared_buffer = *(*it).value;
  3168. if (!shared_buffer.is_shared_with(m_pid))
  3169. return -EPERM;
  3170. {
  3171. InterruptDisabler disabler;
  3172. auto* peer = Process::from_pid(peer_pid);
  3173. if (!peer)
  3174. return -ESRCH;
  3175. }
  3176. shared_buffer.share_with(peer_pid);
  3177. return 0;
  3178. }
  3179. int Process::sys$shbuf_allow_all(int shbuf_id)
  3180. {
  3181. REQUIRE_PROMISE(shared_buffer);
  3182. LOCKER(shared_buffers().lock());
  3183. auto it = shared_buffers().resource().find(shbuf_id);
  3184. if (it == shared_buffers().resource().end())
  3185. return -EINVAL;
  3186. auto& shared_buffer = *(*it).value;
  3187. if (!shared_buffer.is_shared_with(m_pid))
  3188. return -EPERM;
  3189. shared_buffer.share_globally();
  3190. return 0;
  3191. }
  3192. int Process::sys$shbuf_release(int shbuf_id)
  3193. {
  3194. REQUIRE_PROMISE(shared_buffer);
  3195. LOCKER(shared_buffers().lock());
  3196. auto it = shared_buffers().resource().find(shbuf_id);
  3197. if (it == shared_buffers().resource().end())
  3198. return -EINVAL;
  3199. auto& shared_buffer = *(*it).value;
  3200. if (!shared_buffer.is_shared_with(m_pid))
  3201. return -EPERM;
  3202. #ifdef SHARED_BUFFER_DEBUG
  3203. klog() << "Releasing shared buffer " << shbuf_id << ", buffer count: " << shared_buffers().resource().size();
  3204. #endif
  3205. shared_buffer.deref_for_process(*this);
  3206. return 0;
  3207. }
  3208. void* Process::sys$shbuf_get(int shbuf_id, size_t* user_size)
  3209. {
  3210. REQUIRE_PROMISE(shared_buffer);
  3211. if (user_size && !validate_write_typed(user_size))
  3212. return (void*)-EFAULT;
  3213. LOCKER(shared_buffers().lock());
  3214. auto it = shared_buffers().resource().find(shbuf_id);
  3215. if (it == shared_buffers().resource().end())
  3216. return (void*)-EINVAL;
  3217. auto& shared_buffer = *(*it).value;
  3218. if (!shared_buffer.is_shared_with(m_pid))
  3219. return (void*)-EPERM;
  3220. #ifdef SHARED_BUFFER_DEBUG
  3221. klog() << "Retaining shared buffer " << shbuf_id << ", buffer count: " << shared_buffers().resource().size();
  3222. #endif
  3223. if (user_size) {
  3224. size_t size = shared_buffer.size();
  3225. copy_to_user(user_size, &size);
  3226. }
  3227. return shared_buffer.ref_for_process_and_get_address(*this);
  3228. }
  3229. int Process::sys$shbuf_seal(int shbuf_id)
  3230. {
  3231. REQUIRE_PROMISE(shared_buffer);
  3232. LOCKER(shared_buffers().lock());
  3233. auto it = shared_buffers().resource().find(shbuf_id);
  3234. if (it == shared_buffers().resource().end())
  3235. return -EINVAL;
  3236. auto& shared_buffer = *(*it).value;
  3237. if (!shared_buffer.is_shared_with(m_pid))
  3238. return -EPERM;
  3239. #ifdef SHARED_BUFFER_DEBUG
  3240. klog() << "Sealing shared buffer " << shbuf_id;
  3241. #endif
  3242. shared_buffer.seal();
  3243. return 0;
  3244. }
  3245. int Process::sys$shbuf_set_volatile(int shbuf_id, bool state)
  3246. {
  3247. REQUIRE_PROMISE(shared_buffer);
  3248. LOCKER(shared_buffers().lock());
  3249. auto it = shared_buffers().resource().find(shbuf_id);
  3250. if (it == shared_buffers().resource().end())
  3251. return -EINVAL;
  3252. auto& shared_buffer = *(*it).value;
  3253. if (!shared_buffer.is_shared_with(m_pid))
  3254. return -EPERM;
  3255. #ifdef SHARED_BUFFER_DEBUG
  3256. klog() << "Set shared buffer " << shbuf_id << " volatile: " << state;
  3257. #endif
  3258. if (!state) {
  3259. bool was_purged = shared_buffer.vmobject().was_purged();
  3260. shared_buffer.vmobject().set_volatile(state);
  3261. shared_buffer.vmobject().set_was_purged(false);
  3262. return was_purged ? 1 : 0;
  3263. }
  3264. shared_buffer.vmobject().set_volatile(true);
  3265. return 0;
  3266. }
  3267. void Process::terminate_due_to_signal(u8 signal)
  3268. {
  3269. ASSERT_INTERRUPTS_DISABLED();
  3270. ASSERT(signal < 32);
  3271. dbg() << "Terminating due to signal " << signal;
  3272. m_termination_status = 0;
  3273. m_termination_signal = signal;
  3274. die();
  3275. }
  3276. KResult Process::send_signal(u8 signal, Process* sender)
  3277. {
  3278. InterruptDisabler disabler;
  3279. if (auto* thread = Thread::from_tid(m_pid)) {
  3280. thread->send_signal(signal, sender);
  3281. return KSuccess;
  3282. }
  3283. return KResult(-ESRCH);
  3284. }
  3285. int Process::sys$create_thread(void* (*entry)(void*), const Syscall::SC_create_thread_params* user_params)
  3286. {
  3287. REQUIRE_PROMISE(thread);
  3288. if (!validate_read((const void*)entry, sizeof(void*)))
  3289. return -EFAULT;
  3290. Syscall::SC_create_thread_params params;
  3291. if (!validate_read_and_copy_typed(&params, user_params))
  3292. return -EFAULT;
  3293. unsigned detach_state = params.m_detach_state;
  3294. int schedule_priority = params.m_schedule_priority;
  3295. void* stack_location = params.m_stack_location;
  3296. unsigned stack_size = params.m_stack_size;
  3297. if (!validate_write(stack_location, stack_size))
  3298. return -EFAULT;
  3299. u32 user_stack_address = reinterpret_cast<u32>(stack_location) + stack_size;
  3300. if (!MM.validate_user_stack(*this, VirtualAddress(user_stack_address - 4)))
  3301. return -EFAULT;
  3302. // FIXME: return EAGAIN if Thread::all_threads().size() is greater than PTHREAD_THREADS_MAX
  3303. int requested_thread_priority = schedule_priority;
  3304. if (requested_thread_priority < THREAD_PRIORITY_MIN || requested_thread_priority > THREAD_PRIORITY_MAX)
  3305. return -EINVAL;
  3306. bool is_thread_joinable = (0 == detach_state);
  3307. // FIXME: Do something with guard pages?
  3308. auto* thread = new Thread(*this);
  3309. // We know this thread is not the main_thread,
  3310. // So give it a unique name until the user calls $set_thread_name on it
  3311. // length + 4 to give space for our extra junk at the end
  3312. StringBuilder builder(m_name.length() + 4);
  3313. builder.append(m_name);
  3314. builder.appendf("[%d]", thread->tid());
  3315. thread->set_name(builder.to_string());
  3316. thread->set_priority(requested_thread_priority);
  3317. thread->set_joinable(is_thread_joinable);
  3318. auto& tss = thread->tss();
  3319. tss.eip = (FlatPtr)entry;
  3320. tss.eflags = 0x0202;
  3321. tss.cr3 = page_directory().cr3();
  3322. tss.esp = user_stack_address;
  3323. thread->make_thread_specific_region({});
  3324. thread->set_state(Thread::State::Runnable);
  3325. return thread->tid();
  3326. }
  3327. void Process::sys$exit_thread(void* exit_value)
  3328. {
  3329. REQUIRE_PROMISE(thread);
  3330. cli();
  3331. Thread::current->m_exit_value = exit_value;
  3332. Thread::current->set_should_die();
  3333. big_lock().force_unlock_if_locked();
  3334. Thread::current->die_if_needed();
  3335. ASSERT_NOT_REACHED();
  3336. }
  3337. int Process::sys$detach_thread(int tid)
  3338. {
  3339. REQUIRE_PROMISE(thread);
  3340. InterruptDisabler disabler;
  3341. auto* thread = Thread::from_tid(tid);
  3342. if (!thread || thread->pid() != pid())
  3343. return -ESRCH;
  3344. if (!thread->is_joinable())
  3345. return -EINVAL;
  3346. thread->set_joinable(false);
  3347. return 0;
  3348. }
  3349. int Process::sys$join_thread(int tid, void** exit_value)
  3350. {
  3351. REQUIRE_PROMISE(thread);
  3352. if (exit_value && !validate_write_typed(exit_value))
  3353. return -EFAULT;
  3354. InterruptDisabler disabler;
  3355. auto* thread = Thread::from_tid(tid);
  3356. if (!thread || thread->pid() != pid())
  3357. return -ESRCH;
  3358. if (thread == Thread::current)
  3359. return -EDEADLK;
  3360. if (thread->m_joinee == Thread::current)
  3361. return -EDEADLK;
  3362. ASSERT(thread->m_joiner != Thread::current);
  3363. if (thread->m_joiner)
  3364. return -EINVAL;
  3365. if (!thread->is_joinable())
  3366. return -EINVAL;
  3367. void* joinee_exit_value = nullptr;
  3368. // NOTE: pthread_join() cannot be interrupted by signals. Only by death.
  3369. for (;;) {
  3370. auto result = Thread::current->block<Thread::JoinBlocker>(*thread, joinee_exit_value);
  3371. if (result == Thread::BlockResult::InterruptedByDeath) {
  3372. // NOTE: This cleans things up so that Thread::finalize() won't
  3373. // get confused about a missing joiner when finalizing the joinee.
  3374. InterruptDisabler disabler_t;
  3375. if (Thread::current->m_joinee) {
  3376. Thread::current->m_joinee->m_joiner = nullptr;
  3377. Thread::current->m_joinee = nullptr;
  3378. }
  3379. break;
  3380. }
  3381. }
  3382. // NOTE: 'thread' is very possibly deleted at this point. Clear it just to be safe.
  3383. thread = nullptr;
  3384. if (exit_value)
  3385. copy_to_user(exit_value, &joinee_exit_value);
  3386. return 0;
  3387. }
  3388. int Process::sys$set_thread_name(int tid, const char* user_name, size_t user_name_length)
  3389. {
  3390. REQUIRE_PROMISE(thread);
  3391. auto name = validate_and_copy_string_from_user(user_name, user_name_length);
  3392. if (name.is_null())
  3393. return -EFAULT;
  3394. const size_t max_thread_name_size = 64;
  3395. if (name.length() > max_thread_name_size)
  3396. return -EINVAL;
  3397. InterruptDisabler disabler;
  3398. auto* thread = Thread::from_tid(tid);
  3399. if (!thread || thread->pid() != pid())
  3400. return -ESRCH;
  3401. thread->set_name(name);
  3402. return 0;
  3403. }
  3404. int Process::sys$get_thread_name(int tid, char* buffer, size_t buffer_size)
  3405. {
  3406. REQUIRE_PROMISE(thread);
  3407. if (buffer_size == 0)
  3408. return -EINVAL;
  3409. if (!validate_write(buffer, buffer_size))
  3410. return -EFAULT;
  3411. InterruptDisabler disabler;
  3412. auto* thread = Thread::from_tid(tid);
  3413. if (!thread || thread->pid() != pid())
  3414. return -ESRCH;
  3415. if (thread->name().length() + 1 > (size_t)buffer_size)
  3416. return -ENAMETOOLONG;
  3417. copy_to_user(buffer, thread->name().characters(), thread->name().length() + 1);
  3418. return 0;
  3419. }
  3420. int Process::sys$gettid()
  3421. {
  3422. REQUIRE_PROMISE(stdio);
  3423. return Thread::current->tid();
  3424. }
  3425. int Process::sys$donate(int tid)
  3426. {
  3427. REQUIRE_PROMISE(stdio);
  3428. if (tid < 0)
  3429. return -EINVAL;
  3430. InterruptDisabler disabler;
  3431. auto* thread = Thread::from_tid(tid);
  3432. if (!thread || thread->pid() != pid())
  3433. return -ESRCH;
  3434. Scheduler::donate_to(thread, "sys$donate");
  3435. return 0;
  3436. }
  3437. int Process::sys$rename(const Syscall::SC_rename_params* user_params)
  3438. {
  3439. REQUIRE_PROMISE(cpath);
  3440. Syscall::SC_rename_params params;
  3441. if (!validate_read_and_copy_typed(&params, user_params))
  3442. return -EFAULT;
  3443. auto old_path = get_syscall_path_argument(params.old_path);
  3444. if (old_path.is_error())
  3445. return old_path.error();
  3446. auto new_path = get_syscall_path_argument(params.new_path);
  3447. if (new_path.is_error())
  3448. return new_path.error();
  3449. return VFS::the().rename(old_path.value(), new_path.value(), current_directory());
  3450. }
  3451. int Process::sys$ftruncate(int fd, off_t length)
  3452. {
  3453. REQUIRE_PROMISE(stdio);
  3454. if (length < 0)
  3455. return -EINVAL;
  3456. auto description = file_description(fd);
  3457. if (!description)
  3458. return -EBADF;
  3459. if (!description->is_writable())
  3460. return -EBADF;
  3461. return description->truncate(static_cast<u64>(length));
  3462. }
  3463. int Process::sys$watch_file(const char* user_path, size_t path_length)
  3464. {
  3465. REQUIRE_PROMISE(rpath);
  3466. auto path = get_syscall_path_argument(user_path, path_length);
  3467. if (path.is_error())
  3468. return path.error();
  3469. auto custody_or_error = VFS::the().resolve_path(path.value(), current_directory());
  3470. if (custody_or_error.is_error())
  3471. return custody_or_error.error();
  3472. auto& custody = custody_or_error.value();
  3473. auto& inode = custody->inode();
  3474. if (!inode.fs().supports_watchers())
  3475. return -ENOTSUP;
  3476. int fd = alloc_fd();
  3477. if (fd < 0)
  3478. return fd;
  3479. m_fds[fd].set(FileDescription::create(*InodeWatcher::create(inode)));
  3480. m_fds[fd].description->set_readable(true);
  3481. return fd;
  3482. }
  3483. int Process::sys$halt()
  3484. {
  3485. if (!is_superuser())
  3486. return -EPERM;
  3487. REQUIRE_NO_PROMISES;
  3488. dbg() << "acquiring FS locks...";
  3489. FS::lock_all();
  3490. dbg() << "syncing mounted filesystems...";
  3491. FS::sync();
  3492. dbg() << "attempting system shutdown...";
  3493. IO::out16(0x604, 0x2000);
  3494. return 0;
  3495. }
  3496. int Process::sys$reboot()
  3497. {
  3498. if (!is_superuser())
  3499. return -EPERM;
  3500. REQUIRE_NO_PROMISES;
  3501. dbg() << "acquiring FS locks...";
  3502. FS::lock_all();
  3503. dbg() << "syncing mounted filesystems...";
  3504. FS::sync();
  3505. dbg() << "attempting reboot via ACPI";
  3506. if (ACPI::is_enabled())
  3507. ACPI::Parser::the()->try_acpi_reboot();
  3508. dbg() << "attempting reboot via KB Controller...";
  3509. IO::out8(0x64, 0xFE);
  3510. return 0;
  3511. }
  3512. int Process::sys$mount(const Syscall::SC_mount_params* user_params)
  3513. {
  3514. if (!is_superuser())
  3515. return -EPERM;
  3516. REQUIRE_NO_PROMISES;
  3517. Syscall::SC_mount_params params;
  3518. if (!validate_read_and_copy_typed(&params, user_params))
  3519. return -EFAULT;
  3520. auto source_fd = params.source_fd;
  3521. auto target = validate_and_copy_string_from_user(params.target);
  3522. auto fs_type = validate_and_copy_string_from_user(params.fs_type);
  3523. if (target.is_null())
  3524. return -EFAULT;
  3525. auto description = file_description(source_fd);
  3526. if (!description.is_null())
  3527. dbg() << "mount " << fs_type << ": source fd " << source_fd << " @ " << target;
  3528. else
  3529. dbg() << "mount " << fs_type << " @ " << target;
  3530. auto custody_or_error = VFS::the().resolve_path(target, current_directory());
  3531. if (custody_or_error.is_error())
  3532. return custody_or_error.error();
  3533. auto& target_custody = custody_or_error.value();
  3534. if (params.flags & MS_REMOUNT) {
  3535. // We're not creating a new mount, we're updating an existing one!
  3536. return VFS::the().remount(target_custody, params.flags & ~MS_REMOUNT);
  3537. }
  3538. if (params.flags & MS_BIND) {
  3539. // We're doing a bind mount.
  3540. if (description.is_null())
  3541. return -EBADF;
  3542. if (!description->custody()) {
  3543. // We only support bind-mounting inodes, not arbitrary files.
  3544. return -ENODEV;
  3545. }
  3546. return VFS::the().bind_mount(*description->custody(), target_custody, params.flags);
  3547. }
  3548. RefPtr<FS> fs;
  3549. if (fs_type == "ext2" || fs_type == "Ext2FS") {
  3550. if (description.is_null())
  3551. return -EBADF;
  3552. if (!description->file().is_seekable()) {
  3553. dbg() << "mount: this is not a seekable file";
  3554. return -ENODEV;
  3555. }
  3556. dbg() << "mount: attempting to mount " << description->absolute_path() << " on " << target;
  3557. fs = Ext2FS::create(*description);
  3558. } else if (fs_type == "proc" || fs_type == "ProcFS") {
  3559. fs = ProcFS::create();
  3560. } else if (fs_type == "devpts" || fs_type == "DevPtsFS") {
  3561. fs = DevPtsFS::create();
  3562. } else if (fs_type == "tmp" || fs_type == "TmpFS") {
  3563. fs = TmpFS::create();
  3564. } else {
  3565. return -ENODEV;
  3566. }
  3567. if (!fs->initialize()) {
  3568. dbg() << "mount: failed to initialize " << fs_type << " filesystem, fd - " << source_fd;
  3569. return -ENODEV;
  3570. }
  3571. auto result = VFS::the().mount(fs.release_nonnull(), target_custody, params.flags);
  3572. if (!description.is_null())
  3573. dbg() << "mount: successfully mounted " << description->absolute_path() << " on " << target;
  3574. else
  3575. dbg() << "mount: successfully mounted " << target;
  3576. return result;
  3577. }
  3578. int Process::sys$umount(const char* user_mountpoint, size_t mountpoint_length)
  3579. {
  3580. if (!is_superuser())
  3581. return -EPERM;
  3582. REQUIRE_NO_PROMISES;
  3583. if (!validate_read(user_mountpoint, mountpoint_length))
  3584. return -EFAULT;
  3585. auto mountpoint = get_syscall_path_argument(user_mountpoint, mountpoint_length);
  3586. if (mountpoint.is_error())
  3587. return mountpoint.error();
  3588. auto metadata_or_error = VFS::the().lookup_metadata(mountpoint.value(), current_directory());
  3589. if (metadata_or_error.is_error())
  3590. return metadata_or_error.error();
  3591. auto guest_inode_id = metadata_or_error.value().inode;
  3592. return VFS::the().unmount(guest_inode_id);
  3593. }
  3594. void Process::FileDescriptionAndFlags::clear()
  3595. {
  3596. description = nullptr;
  3597. flags = 0;
  3598. }
  3599. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& d, u32 f)
  3600. {
  3601. description = move(d);
  3602. flags = f;
  3603. }
  3604. int Process::sys$mknod(const Syscall::SC_mknod_params* user_params)
  3605. {
  3606. REQUIRE_PROMISE(dpath);
  3607. Syscall::SC_mknod_params params;
  3608. if (!validate_read_and_copy_typed(&params, user_params))
  3609. return -EFAULT;
  3610. if (!is_superuser() && !is_regular_file(params.mode) && !is_fifo(params.mode) && !is_socket(params.mode))
  3611. return -EPERM;
  3612. auto path = get_syscall_path_argument(params.path);
  3613. if (path.is_error())
  3614. return path.error();
  3615. return VFS::the().mknod(path.value(), params.mode & ~umask(), params.dev, current_directory());
  3616. }
  3617. int Process::sys$dump_backtrace()
  3618. {
  3619. dump_backtrace();
  3620. return 0;
  3621. }
  3622. int Process::sys$dbgputch(u8 ch)
  3623. {
  3624. IO::out8(0xe9, ch);
  3625. return 0;
  3626. }
  3627. int Process::sys$dbgputstr(const u8* characters, int length)
  3628. {
  3629. if (!length)
  3630. return 0;
  3631. if (!validate_read(characters, length))
  3632. return -EFAULT;
  3633. SmapDisabler disabler;
  3634. for (int i = 0; i < length; ++i)
  3635. IO::out8(0xe9, characters[i]);
  3636. return 0;
  3637. }
  3638. KBuffer Process::backtrace(ProcessInspectionHandle& handle) const
  3639. {
  3640. KBufferBuilder builder;
  3641. for_each_thread([&](Thread& thread) {
  3642. builder.appendf("Thread %d (%s):\n", thread.tid(), thread.name().characters());
  3643. builder.append(thread.backtrace(handle));
  3644. return IterationDecision::Continue;
  3645. });
  3646. return builder.build();
  3647. }
  3648. int Process::sys$set_process_icon(int icon_id)
  3649. {
  3650. REQUIRE_PROMISE(shared_buffer);
  3651. LOCKER(shared_buffers().lock());
  3652. auto it = shared_buffers().resource().find(icon_id);
  3653. if (it == shared_buffers().resource().end())
  3654. return -EINVAL;
  3655. auto& shared_buffer = *(*it).value;
  3656. if (!shared_buffer.is_shared_with(m_pid))
  3657. return -EPERM;
  3658. m_icon_id = icon_id;
  3659. return 0;
  3660. }
  3661. int Process::sys$get_process_name(char* buffer, int buffer_size)
  3662. {
  3663. REQUIRE_PROMISE(stdio);
  3664. if (buffer_size <= 0)
  3665. return -EINVAL;
  3666. if (!validate_write(buffer, buffer_size))
  3667. return -EFAULT;
  3668. if (m_name.length() + 1 > (size_t)buffer_size)
  3669. return -ENAMETOOLONG;
  3670. copy_to_user(buffer, m_name.characters(), m_name.length() + 1);
  3671. return 0;
  3672. }
  3673. // We don't use the flag yet, but we could use it for distinguishing
  3674. // random source like Linux, unlike the OpenBSD equivalent. However, if we
  3675. // do, we should be able of the caveats that Linux has dealt with.
  3676. ssize_t Process::sys$getrandom(void* buffer, size_t buffer_size, unsigned int flags __attribute__((unused)))
  3677. {
  3678. REQUIRE_PROMISE(stdio);
  3679. if (buffer_size <= 0)
  3680. return -EINVAL;
  3681. if (!validate_write(buffer, buffer_size))
  3682. return -EFAULT;
  3683. SmapDisabler disabler;
  3684. get_good_random_bytes((u8*)buffer, buffer_size);
  3685. return 0;
  3686. }
  3687. int Process::sys$setkeymap(const Syscall::SC_setkeymap_params* user_params)
  3688. {
  3689. if (!is_superuser())
  3690. return -EPERM;
  3691. REQUIRE_NO_PROMISES;
  3692. Syscall::SC_setkeymap_params params;
  3693. if (!validate_read_and_copy_typed(&params, user_params))
  3694. return -EFAULT;
  3695. const char* map = params.map;
  3696. const char* shift_map = params.shift_map;
  3697. const char* alt_map = params.alt_map;
  3698. const char* altgr_map = params.altgr_map;
  3699. if (!validate_read(map, 0x80))
  3700. return -EFAULT;
  3701. if (!validate_read(shift_map, 0x80))
  3702. return -EFAULT;
  3703. if (!validate_read(alt_map, 0x80))
  3704. return -EFAULT;
  3705. if (!validate_read(altgr_map, 0x80))
  3706. return -EFAULT;
  3707. SmapDisabler disabler;
  3708. KeyboardDevice::the().set_maps(map, shift_map, alt_map, altgr_map);
  3709. return 0;
  3710. }
  3711. int Process::sys$clock_gettime(clockid_t clock_id, timespec* user_ts)
  3712. {
  3713. REQUIRE_PROMISE(stdio);
  3714. if (!validate_write_typed(user_ts))
  3715. return -EFAULT;
  3716. timespec ts;
  3717. memset(&ts, 0, sizeof(ts));
  3718. switch (clock_id) {
  3719. case CLOCK_MONOTONIC:
  3720. ts.tv_sec = TimeManagement::the().seconds_since_boot();
  3721. ts.tv_nsec = TimeManagement::the().ticks_this_second() * 1000000;
  3722. break;
  3723. case CLOCK_REALTIME:
  3724. ts.tv_sec = TimeManagement::the().epoch_time();
  3725. ts.tv_nsec = TimeManagement::the().ticks_this_second() * 1000000;
  3726. break;
  3727. default:
  3728. return -EINVAL;
  3729. }
  3730. copy_to_user(user_ts, &ts);
  3731. return 0;
  3732. }
  3733. int Process::sys$clock_settime(clockid_t clock_id, timespec* user_ts)
  3734. {
  3735. REQUIRE_PROMISE(settime);
  3736. if (!is_superuser())
  3737. return -EPERM;
  3738. timespec ts;
  3739. if (!validate_read_and_copy_typed(&ts, user_ts))
  3740. return -EFAULT;
  3741. switch (clock_id) {
  3742. case CLOCK_REALTIME:
  3743. TimeManagement::the().set_epoch_time(ts.tv_sec);
  3744. break;
  3745. default:
  3746. return -EINVAL;
  3747. }
  3748. return 0;
  3749. }
  3750. int Process::sys$clock_nanosleep(const Syscall::SC_clock_nanosleep_params* user_params)
  3751. {
  3752. REQUIRE_PROMISE(stdio);
  3753. Syscall::SC_clock_nanosleep_params params;
  3754. if (!validate_read_and_copy_typed(&params, user_params))
  3755. return -EFAULT;
  3756. if (params.requested_sleep && !validate_read_typed(params.requested_sleep))
  3757. return -EFAULT;
  3758. timespec requested_sleep;
  3759. copy_from_user(&requested_sleep, params.requested_sleep);
  3760. if (params.remaining_sleep && !validate_write_typed(params.remaining_sleep))
  3761. return -EFAULT;
  3762. bool is_absolute = params.flags & TIMER_ABSTIME;
  3763. switch (params.clock_id) {
  3764. case CLOCK_MONOTONIC: {
  3765. u64 wakeup_time;
  3766. if (is_absolute) {
  3767. u64 time_to_wake = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
  3768. wakeup_time = Thread::current->sleep_until(time_to_wake);
  3769. } else {
  3770. u32 ticks_to_sleep = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
  3771. if (!ticks_to_sleep)
  3772. return 0;
  3773. wakeup_time = Thread::current->sleep(ticks_to_sleep);
  3774. }
  3775. if (wakeup_time > g_uptime) {
  3776. u32 ticks_left = wakeup_time - g_uptime;
  3777. if (!is_absolute && params.remaining_sleep) {
  3778. if (!validate_write_typed(params.remaining_sleep)) {
  3779. // This can happen because the lock is dropped while
  3780. // sleeping, thus giving other threads the opportunity
  3781. // to make the region unwritable.
  3782. return -EFAULT;
  3783. }
  3784. timespec remaining_sleep;
  3785. memset(&remaining_sleep, 0, sizeof(timespec));
  3786. remaining_sleep.tv_sec = ticks_left / TimeManagement::the().ticks_per_second();
  3787. ticks_left -= remaining_sleep.tv_sec * TimeManagement::the().ticks_per_second();
  3788. remaining_sleep.tv_nsec = ticks_left * 1000000;
  3789. copy_to_user(params.remaining_sleep, &remaining_sleep);
  3790. }
  3791. return -EINTR;
  3792. }
  3793. return 0;
  3794. }
  3795. default:
  3796. return -EINVAL;
  3797. }
  3798. }
  3799. int Process::sys$sync()
  3800. {
  3801. REQUIRE_PROMISE(stdio);
  3802. VFS::the().sync();
  3803. return 0;
  3804. }
  3805. int Process::sys$yield()
  3806. {
  3807. REQUIRE_PROMISE(stdio);
  3808. Thread::current->yield_without_holding_big_lock();
  3809. return 0;
  3810. }
  3811. int Process::sys$beep()
  3812. {
  3813. PCSpeaker::tone_on(440);
  3814. u64 wakeup_time = Thread::current->sleep(100);
  3815. PCSpeaker::tone_off();
  3816. if (wakeup_time > g_uptime)
  3817. return -EINTR;
  3818. return 0;
  3819. }
  3820. int Process::sys$module_load(const char* user_path, size_t path_length)
  3821. {
  3822. if (!is_superuser())
  3823. return -EPERM;
  3824. REQUIRE_NO_PROMISES;
  3825. auto path = get_syscall_path_argument(user_path, path_length);
  3826. if (path.is_error())
  3827. return path.error();
  3828. auto description_or_error = VFS::the().open(path.value(), O_RDONLY, 0, current_directory());
  3829. if (description_or_error.is_error())
  3830. return description_or_error.error();
  3831. auto& description = description_or_error.value();
  3832. auto payload_or_error = description->read_entire_file();
  3833. if (payload_or_error.is_error())
  3834. return payload_or_error.error();
  3835. auto payload = payload_or_error.value();
  3836. auto storage = KBuffer::create_with_size(payload.size());
  3837. memcpy(storage.data(), payload.data(), payload.size());
  3838. payload.clear();
  3839. auto elf_image = make<ELF::Image>(storage.data(), storage.size());
  3840. if (!elf_image->parse())
  3841. return -ENOEXEC;
  3842. HashMap<String, u8*> section_storage_by_name;
  3843. auto module = make<Module>();
  3844. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELF::Image::Section& section) {
  3845. if (!section.size())
  3846. return IterationDecision::Continue;
  3847. auto section_storage = KBuffer::copy(section.raw_data(), section.size(), Region::Access::Read | Region::Access::Write | Region::Access::Execute);
  3848. section_storage_by_name.set(section.name(), section_storage.data());
  3849. module->sections.append(move(section_storage));
  3850. return IterationDecision::Continue;
  3851. });
  3852. bool missing_symbols = false;
  3853. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELF::Image::Section& section) {
  3854. if (!section.size())
  3855. return IterationDecision::Continue;
  3856. auto* section_storage = section_storage_by_name.get(section.name()).value_or(nullptr);
  3857. ASSERT(section_storage);
  3858. section.relocations().for_each_relocation([&](const ELF::Image::Relocation& relocation) {
  3859. auto& patch_ptr = *reinterpret_cast<ptrdiff_t*>(section_storage + relocation.offset());
  3860. switch (relocation.type()) {
  3861. case R_386_PC32: {
  3862. // PC-relative relocation
  3863. dbg() << "PC-relative relocation: " << relocation.symbol().name();
  3864. u32 symbol_address = address_for_kernel_symbol(relocation.symbol().name());
  3865. if (symbol_address == 0)
  3866. missing_symbols = true;
  3867. dbg() << " Symbol address: " << (void*)symbol_address;
  3868. ptrdiff_t relative_offset = (char*)symbol_address - ((char*)&patch_ptr + 4);
  3869. patch_ptr = relative_offset;
  3870. break;
  3871. }
  3872. case R_386_32: // Absolute relocation
  3873. dbg() << "Absolute relocation: '" << relocation.symbol().name() << "' value:" << relocation.symbol().value() << ", index:" << relocation.symbol_index();
  3874. if (relocation.symbol().bind() == STB_LOCAL) {
  3875. auto* section_storage_containing_symbol = section_storage_by_name.get(relocation.symbol().section().name()).value_or(nullptr);
  3876. ASSERT(section_storage_containing_symbol);
  3877. u32 symbol_address = (ptrdiff_t)(section_storage_containing_symbol + relocation.symbol().value());
  3878. if (symbol_address == 0)
  3879. missing_symbols = true;
  3880. dbg() << " Symbol address: " << (void*)symbol_address;
  3881. patch_ptr += symbol_address;
  3882. } else if (relocation.symbol().bind() == STB_GLOBAL) {
  3883. u32 symbol_address = address_for_kernel_symbol(relocation.symbol().name());
  3884. if (symbol_address == 0)
  3885. missing_symbols = true;
  3886. dbg() << " Symbol address: " << (void*)symbol_address;
  3887. patch_ptr += symbol_address;
  3888. } else {
  3889. ASSERT_NOT_REACHED();
  3890. }
  3891. break;
  3892. }
  3893. return IterationDecision::Continue;
  3894. });
  3895. return IterationDecision::Continue;
  3896. });
  3897. if (missing_symbols)
  3898. return -EINVAL;
  3899. auto* text_base = section_storage_by_name.get(".text").value_or(nullptr);
  3900. if (!text_base) {
  3901. dbg() << "No .text section found in module!";
  3902. return -EINVAL;
  3903. }
  3904. elf_image->for_each_symbol([&](const ELF::Image::Symbol& symbol) {
  3905. dbg() << " - " << symbol.type() << " '" << symbol.name() << "' @ " << (void*)symbol.value() << ", size=" << symbol.size();
  3906. if (symbol.name() == "module_init") {
  3907. module->module_init = (ModuleInitPtr)(text_base + symbol.value());
  3908. } else if (symbol.name() == "module_fini") {
  3909. module->module_fini = (ModuleFiniPtr)(text_base + symbol.value());
  3910. } else if (symbol.name() == "module_name") {
  3911. const u8* storage = section_storage_by_name.get(symbol.section().name()).value_or(nullptr);
  3912. if (storage)
  3913. module->name = String((const char*)(storage + symbol.value()));
  3914. }
  3915. return IterationDecision::Continue;
  3916. });
  3917. if (!module->module_init)
  3918. return -EINVAL;
  3919. if (g_modules->contains(module->name)) {
  3920. dbg() << "a module with the name " << module->name << " is already loaded; please unload it first";
  3921. return -EEXIST;
  3922. }
  3923. module->module_init();
  3924. auto name = module->name;
  3925. g_modules->set(name, move(module));
  3926. return 0;
  3927. }
  3928. int Process::sys$module_unload(const char* user_name, size_t name_length)
  3929. {
  3930. if (!is_superuser())
  3931. return -EPERM;
  3932. REQUIRE_NO_PROMISES;
  3933. auto module_name = validate_and_copy_string_from_user(user_name, name_length);
  3934. if (module_name.is_null())
  3935. return -EFAULT;
  3936. auto it = g_modules->find(module_name);
  3937. if (it == g_modules->end())
  3938. return -ENOENT;
  3939. if (it->value->module_fini)
  3940. it->value->module_fini();
  3941. g_modules->remove(it);
  3942. return 0;
  3943. }
  3944. int Process::sys$profiling_enable(pid_t pid)
  3945. {
  3946. REQUIRE_NO_PROMISES;
  3947. InterruptDisabler disabler;
  3948. auto* process = Process::from_pid(pid);
  3949. if (!process)
  3950. return -ESRCH;
  3951. if (process->is_dead())
  3952. return -ESRCH;
  3953. if (!is_superuser() && process->uid() != m_uid)
  3954. return -EPERM;
  3955. Profiling::start(*process);
  3956. process->set_profiling(true);
  3957. return 0;
  3958. }
  3959. int Process::sys$profiling_disable(pid_t pid)
  3960. {
  3961. InterruptDisabler disabler;
  3962. auto* process = Process::from_pid(pid);
  3963. if (!process)
  3964. return -ESRCH;
  3965. if (!is_superuser() && process->uid() != m_uid)
  3966. return -EPERM;
  3967. process->set_profiling(false);
  3968. Profiling::stop();
  3969. return 0;
  3970. }
  3971. WaitQueue& Process::futex_queue(i32* userspace_address)
  3972. {
  3973. auto& queue = m_futex_queues.ensure((FlatPtr)userspace_address);
  3974. if (!queue)
  3975. queue = make<WaitQueue>();
  3976. return *queue;
  3977. }
  3978. int Process::sys$futex(const Syscall::SC_futex_params* user_params)
  3979. {
  3980. REQUIRE_PROMISE(thread);
  3981. Syscall::SC_futex_params params;
  3982. if (!validate_read_and_copy_typed(&params, user_params))
  3983. return -EFAULT;
  3984. i32* userspace_address = params.userspace_address;
  3985. int futex_op = params.futex_op;
  3986. i32 value = params.val;
  3987. const timespec* user_timeout = params.timeout;
  3988. if (!validate_read_typed(userspace_address))
  3989. return -EFAULT;
  3990. if (user_timeout && !validate_read_typed(user_timeout))
  3991. return -EFAULT;
  3992. switch (futex_op) {
  3993. case FUTEX_WAIT: {
  3994. i32 user_value;
  3995. copy_from_user(&user_value, userspace_address);
  3996. if (user_value != value)
  3997. return -EAGAIN;
  3998. timespec ts_abstimeout { 0, 0 };
  3999. if (user_timeout && !validate_read_and_copy_typed(&ts_abstimeout, user_timeout))
  4000. return -EFAULT;
  4001. WaitQueue& wait_queue = futex_queue(userspace_address);
  4002. timeval* optional_timeout = nullptr;
  4003. timeval relative_timeout { 0, 0 };
  4004. if (user_timeout) {
  4005. compute_relative_timeout_from_absolute(ts_abstimeout, relative_timeout);
  4006. optional_timeout = &relative_timeout;
  4007. }
  4008. // FIXME: This is supposed to be interruptible by a signal, but right now WaitQueue cannot be interrupted.
  4009. Thread::BlockResult result = Thread::current->wait_on(wait_queue, optional_timeout);
  4010. if (result == Thread::BlockResult::InterruptedByTimeout) {
  4011. return -ETIMEDOUT;
  4012. }
  4013. break;
  4014. }
  4015. case FUTEX_WAKE:
  4016. if (value == 0)
  4017. return 0;
  4018. if (value == 1) {
  4019. futex_queue(userspace_address).wake_one();
  4020. } else {
  4021. futex_queue(userspace_address).wake_n(value);
  4022. }
  4023. break;
  4024. }
  4025. return 0;
  4026. }
  4027. int Process::sys$set_thread_boost(int tid, int amount)
  4028. {
  4029. REQUIRE_PROMISE(proc);
  4030. if (amount < 0 || amount > 20)
  4031. return -EINVAL;
  4032. InterruptDisabler disabler;
  4033. auto* thread = Thread::from_tid(tid);
  4034. if (!thread)
  4035. return -ESRCH;
  4036. if (thread->state() == Thread::State::Dead || thread->state() == Thread::State::Dying)
  4037. return -ESRCH;
  4038. if (!is_superuser() && thread->process().uid() != euid())
  4039. return -EPERM;
  4040. thread->set_priority_boost(amount);
  4041. return 0;
  4042. }
  4043. int Process::sys$set_process_boost(pid_t pid, int amount)
  4044. {
  4045. REQUIRE_PROMISE(proc);
  4046. if (amount < 0 || amount > 20)
  4047. return -EINVAL;
  4048. InterruptDisabler disabler;
  4049. auto* process = Process::from_pid(pid);
  4050. if (!process || process->is_dead())
  4051. return -ESRCH;
  4052. if (!is_superuser() && process->uid() != euid())
  4053. return -EPERM;
  4054. process->m_priority_boost = amount;
  4055. return 0;
  4056. }
  4057. int Process::sys$chroot(const char* user_path, size_t path_length, int mount_flags)
  4058. {
  4059. if (!is_superuser())
  4060. return -EPERM;
  4061. REQUIRE_PROMISE(chroot);
  4062. auto path = get_syscall_path_argument(user_path, path_length);
  4063. if (path.is_error())
  4064. return path.error();
  4065. auto directory_or_error = VFS::the().open_directory(path.value(), current_directory());
  4066. if (directory_or_error.is_error())
  4067. return directory_or_error.error();
  4068. auto directory = directory_or_error.value();
  4069. m_root_directory_relative_to_global_root = directory;
  4070. int chroot_mount_flags = mount_flags == -1 ? directory->mount_flags() : mount_flags;
  4071. set_root_directory(Custody::create(nullptr, "", directory->inode(), chroot_mount_flags));
  4072. return 0;
  4073. }
  4074. Custody& Process::root_directory()
  4075. {
  4076. if (!m_root_directory)
  4077. m_root_directory = VFS::the().root_custody();
  4078. return *m_root_directory;
  4079. }
  4080. Custody& Process::root_directory_relative_to_global_root()
  4081. {
  4082. if (!m_root_directory_relative_to_global_root)
  4083. m_root_directory_relative_to_global_root = root_directory();
  4084. return *m_root_directory_relative_to_global_root;
  4085. }
  4086. void Process::set_root_directory(const Custody& root)
  4087. {
  4088. m_root_directory = root;
  4089. }
  4090. int Process::sys$pledge(const Syscall::SC_pledge_params* user_params)
  4091. {
  4092. Syscall::SC_pledge_params params;
  4093. if (!validate_read_and_copy_typed(&params, user_params))
  4094. return -EFAULT;
  4095. if (params.promises.length > 1024 || params.execpromises.length > 1024)
  4096. return -E2BIG;
  4097. String promises;
  4098. if (params.promises.characters) {
  4099. promises = validate_and_copy_string_from_user(params.promises);
  4100. if (promises.is_null())
  4101. return -EFAULT;
  4102. }
  4103. String execpromises;
  4104. if (params.execpromises.characters) {
  4105. execpromises = validate_and_copy_string_from_user(params.execpromises);
  4106. if (execpromises.is_null())
  4107. return -EFAULT;
  4108. }
  4109. auto parse_pledge = [&](auto& pledge_spec, u32& mask) {
  4110. auto parts = pledge_spec.split_view(' ');
  4111. for (auto& part : parts) {
  4112. #define __ENUMERATE_PLEDGE_PROMISE(x) \
  4113. if (part == #x) { \
  4114. mask |= (1u << (u32)Pledge::x); \
  4115. continue; \
  4116. }
  4117. ENUMERATE_PLEDGE_PROMISES
  4118. #undef __ENUMERATE_PLEDGE_PROMISE
  4119. if (part == "dns") {
  4120. // "dns" is an alias for "unix" since DNS queries go via LookupServer
  4121. mask |= (1u << (u32)Pledge::unix);
  4122. continue;
  4123. }
  4124. return false;
  4125. }
  4126. return true;
  4127. };
  4128. u32 new_promises;
  4129. u32 new_execpromises;
  4130. if (!promises.is_null()) {
  4131. new_promises = 0;
  4132. if (!parse_pledge(promises, new_promises))
  4133. return -EINVAL;
  4134. if (m_promises && (!new_promises || new_promises & ~m_promises))
  4135. return -EPERM;
  4136. } else {
  4137. new_promises = m_promises;
  4138. }
  4139. if (!execpromises.is_null()) {
  4140. new_execpromises = 0;
  4141. if (!parse_pledge(execpromises, new_execpromises))
  4142. return -EINVAL;
  4143. if (m_execpromises && (!new_execpromises || new_execpromises & ~m_execpromises))
  4144. return -EPERM;
  4145. } else {
  4146. new_execpromises = m_execpromises;
  4147. }
  4148. m_promises = new_promises;
  4149. m_execpromises = new_execpromises;
  4150. return 0;
  4151. }
  4152. Region& Process::add_region(NonnullOwnPtr<Region> region)
  4153. {
  4154. auto* ptr = region.ptr();
  4155. m_regions.append(move(region));
  4156. return *ptr;
  4157. }
  4158. int Process::sys$unveil(const Syscall::SC_unveil_params* user_params)
  4159. {
  4160. Syscall::SC_unveil_params params;
  4161. if (!validate_read_and_copy_typed(&params, user_params))
  4162. return -EFAULT;
  4163. if (!params.path.characters && !params.permissions.characters) {
  4164. m_veil_state = VeilState::Locked;
  4165. return 0;
  4166. }
  4167. if (m_veil_state == VeilState::Locked)
  4168. return -EPERM;
  4169. if (!params.path.characters || !params.permissions.characters)
  4170. return -EINVAL;
  4171. if (params.permissions.length > 4)
  4172. return -EINVAL;
  4173. auto path = get_syscall_path_argument(params.path);
  4174. if (path.is_error())
  4175. return path.error();
  4176. if (path.value().is_empty() || path.value().characters()[0] != '/')
  4177. return -EINVAL;
  4178. auto custody_or_error = VFS::the().resolve_path_without_veil(path.value(), root_directory());
  4179. if (custody_or_error.is_error())
  4180. // FIXME Should this be EINVAL?
  4181. return custody_or_error.error();
  4182. auto& custody = custody_or_error.value();
  4183. auto new_unveiled_path = custody->absolute_path();
  4184. auto permissions = validate_and_copy_string_from_user(params.permissions);
  4185. if (permissions.is_null())
  4186. return -EFAULT;
  4187. unsigned new_permissions = 0;
  4188. for (size_t i = 0; i < permissions.length(); ++i) {
  4189. switch (permissions[i]) {
  4190. case 'r':
  4191. new_permissions |= UnveiledPath::Access::Read;
  4192. break;
  4193. case 'w':
  4194. new_permissions |= UnveiledPath::Access::Write;
  4195. break;
  4196. case 'x':
  4197. new_permissions |= UnveiledPath::Access::Execute;
  4198. break;
  4199. case 'c':
  4200. new_permissions |= UnveiledPath::Access::CreateOrRemove;
  4201. break;
  4202. default:
  4203. return -EINVAL;
  4204. }
  4205. }
  4206. for (size_t i = 0; i < m_unveiled_paths.size(); ++i) {
  4207. auto& unveiled_path = m_unveiled_paths[i];
  4208. if (unveiled_path.path == new_unveiled_path) {
  4209. if (new_permissions & ~unveiled_path.permissions)
  4210. return -EPERM;
  4211. unveiled_path.permissions = new_permissions;
  4212. return 0;
  4213. }
  4214. }
  4215. m_unveiled_paths.append({ new_unveiled_path, new_permissions });
  4216. ASSERT(m_veil_state != VeilState::Locked);
  4217. m_veil_state = VeilState::Dropped;
  4218. return 0;
  4219. }
  4220. int Process::sys$perf_event(int type, FlatPtr arg1, FlatPtr arg2)
  4221. {
  4222. if (!m_perf_event_buffer)
  4223. m_perf_event_buffer = make<PerformanceEventBuffer>();
  4224. return m_perf_event_buffer->append(type, arg1, arg2);
  4225. }
  4226. void Process::set_tty(TTY* tty)
  4227. {
  4228. m_tty = tty;
  4229. }
  4230. OwnPtr<Process::ELFBundle> Process::elf_bundle() const
  4231. {
  4232. if (!m_executable)
  4233. return nullptr;
  4234. auto bundle = make<ELFBundle>();
  4235. if (!m_executable->inode().shared_vmobject()) {
  4236. return nullptr;
  4237. }
  4238. ASSERT(m_executable->inode().shared_vmobject());
  4239. auto& vmobject = *m_executable->inode().shared_vmobject();
  4240. bundle->region = MM.allocate_kernel_region_with_vmobject(const_cast<SharedInodeVMObject&>(vmobject), vmobject.size(), "ELF bundle", Region::Access::Read);
  4241. if (!bundle->region)
  4242. return nullptr;
  4243. bundle->elf_loader = ELF::Loader::create(bundle->region->vaddr().as_ptr(), bundle->region->size());
  4244. return bundle;
  4245. }
  4246. int Process::sys$get_stack_bounds(FlatPtr* user_stack_base, size_t* user_stack_size)
  4247. {
  4248. if (!validate_write_typed(user_stack_base))
  4249. return -EFAULT;
  4250. if (!validate_write_typed(user_stack_size))
  4251. return -EFAULT;
  4252. FlatPtr stack_pointer = Thread::current->get_register_dump_from_stack().userspace_esp;
  4253. auto* stack_region = MM.region_from_vaddr(*this, VirtualAddress(stack_pointer));
  4254. if (!stack_region) {
  4255. ASSERT_NOT_REACHED();
  4256. return -EINVAL;
  4257. }
  4258. FlatPtr stack_base = stack_region->range().base().get();
  4259. size_t stack_size = stack_region->size();
  4260. copy_to_user(user_stack_base, &stack_base);
  4261. copy_to_user(user_stack_size, &stack_size);
  4262. return 0;
  4263. }
  4264. int Process::sys$ptrace(const Syscall::SC_ptrace_params* user_params)
  4265. {
  4266. REQUIRE_PROMISE(proc);
  4267. Syscall::SC_ptrace_params params;
  4268. if (!validate_read_and_copy_typed(&params, user_params))
  4269. return -EFAULT;
  4270. auto result = Ptrace::handle_syscall(params, *this);
  4271. return result.is_error() ? result.error() : result.value();
  4272. }
  4273. bool Process::has_tracee_thread(int tracer_pid) const
  4274. {
  4275. bool has_tracee = false;
  4276. for_each_thread([&](Thread& t) {
  4277. if (t.tracer() && t.tracer()->tracer_pid() == tracer_pid) {
  4278. has_tracee = true;
  4279. return IterationDecision::Break;
  4280. }
  4281. return IterationDecision::Continue;
  4282. });
  4283. return has_tracee;
  4284. }
  4285. KResultOr<u32> Process::peek_user_data(u32* address)
  4286. {
  4287. if (!MM.validate_user_read(*this, VirtualAddress(address), sizeof(u32))) {
  4288. dbg() << "Invalid address for peek_user_data: " << address;
  4289. return KResult(-EFAULT);
  4290. }
  4291. uint32_t result;
  4292. // This function can be called from the context of another
  4293. // process that called PT_PEEK
  4294. ProcessPagingScope scope(*this);
  4295. copy_from_user(&result, address);
  4296. return result;
  4297. }
  4298. KResult Process::poke_user_data(u32* address, u32 data)
  4299. {
  4300. // We validate for read (rather than write) because PT_POKE can write to readonly pages.
  4301. // So we effectively only care that the poke operation is trying to write to user pages.
  4302. if (!MM.validate_user_read(*this, VirtualAddress(address), sizeof(u32))) {
  4303. dbg() << "Invalid address for poke_user_data: " << address;
  4304. return KResult(-EFAULT);
  4305. }
  4306. ProcessPagingScope scope(*this);
  4307. Range range = { VirtualAddress(address), sizeof(u32) };
  4308. auto* region = region_containing(range);
  4309. ASSERT(region != nullptr);
  4310. if (region->is_shared()) {
  4311. // If the region is shared, we change its vmobject to a PrivateInodeVMObject
  4312. // to prevent the write operation from chaning any shared inode data
  4313. ASSERT(region->vmobject().is_shared_inode());
  4314. region->set_vmobject(PrivateInodeVMObject::create_with_inode(static_cast<SharedInodeVMObject&>(region->vmobject()).inode()));
  4315. region->set_shared(false);
  4316. }
  4317. const bool was_writable = region->is_writable();
  4318. if (!was_writable) //TODO refactor into scopeguard
  4319. {
  4320. region->set_writable(true);
  4321. region->remap();
  4322. }
  4323. copy_to_user(address, &data);
  4324. if (!was_writable) {
  4325. region->set_writable(false);
  4326. region->remap();
  4327. }
  4328. return KResult(KSuccess);
  4329. }
  4330. }