Process.cpp 144 KB

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