Process.cpp 147 KB

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