Process.cpp 157 KB

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