Process.cpp 145 KB

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