Process.cpp 148 KB

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