Process.cpp 146 KB

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