Process.cpp 149 KB

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