Process.cpp 157 KB

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