Process.cpp 145 KB

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