Process.cpp 150 KB

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