Process.cpp 155 KB

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