Process.cpp 150 KB

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