Process.cpp 144 KB

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