Process.cpp 142 KB

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