Process.cpp 164 KB

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