Process.cpp 164 KB

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