Process.cpp 148 KB

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