Process.cpp 145 KB

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