Process.cpp 145 KB

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