Process.cpp 148 KB

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