Process.cpp 150 KB

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