Process.cpp 156 KB

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