Process.cpp 150 KB

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