Process.cpp 146 KB

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