Process.cpp 156 KB

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