Process.cpp 157 KB

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