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. description->set_rw_mode(options);
  1659. description->set_file_flags(options);
  1660. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1661. m_fds[fd].set(move(description), fd_flags);
  1662. return fd;
  1663. }
  1664. int Process::alloc_fd(int first_candidate_fd)
  1665. {
  1666. int fd = -EMFILE;
  1667. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1668. if (!m_fds[i]) {
  1669. fd = i;
  1670. break;
  1671. }
  1672. }
  1673. return fd;
  1674. }
  1675. int Process::sys$pipe(int pipefd[2], int flags)
  1676. {
  1677. REQUIRE_PROMISE(stdio);
  1678. if (!validate_write_typed(pipefd))
  1679. return -EFAULT;
  1680. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1681. return -EMFILE;
  1682. // Reject flags other than O_CLOEXEC.
  1683. if ((flags & O_CLOEXEC) != flags)
  1684. return -EINVAL;
  1685. u32 fd_flags = (flags & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1686. auto fifo = FIFO::create(m_uid);
  1687. int reader_fd = alloc_fd();
  1688. m_fds[reader_fd].set(fifo->open_direction(FIFO::Direction::Reader), fd_flags);
  1689. m_fds[reader_fd].description->set_readable(true);
  1690. copy_to_user(&pipefd[0], &reader_fd, sizeof(reader_fd));
  1691. int writer_fd = alloc_fd();
  1692. m_fds[writer_fd].set(fifo->open_direction(FIFO::Direction::Writer), fd_flags);
  1693. m_fds[writer_fd].description->set_writable(true);
  1694. copy_to_user(&pipefd[1], &writer_fd, sizeof(writer_fd));
  1695. return 0;
  1696. }
  1697. int Process::sys$killpg(int pgrp, int signum)
  1698. {
  1699. REQUIRE_PROMISE(proc);
  1700. if (signum < 1 || signum >= 32)
  1701. return -EINVAL;
  1702. if (pgrp < 0)
  1703. return -EINVAL;
  1704. InterruptDisabler disabler;
  1705. return do_killpg(pgrp, signum);
  1706. }
  1707. int Process::sys$setuid(uid_t uid)
  1708. {
  1709. REQUIRE_PROMISE(id);
  1710. if (uid != m_uid && !is_superuser())
  1711. return -EPERM;
  1712. m_uid = uid;
  1713. m_euid = uid;
  1714. return 0;
  1715. }
  1716. int Process::sys$setgid(gid_t gid)
  1717. {
  1718. REQUIRE_PROMISE(id);
  1719. if (gid != m_gid && !is_superuser())
  1720. return -EPERM;
  1721. m_gid = gid;
  1722. m_egid = gid;
  1723. return 0;
  1724. }
  1725. unsigned Process::sys$alarm(unsigned seconds)
  1726. {
  1727. REQUIRE_PROMISE(stdio);
  1728. unsigned previous_alarm_remaining = 0;
  1729. if (m_alarm_deadline && m_alarm_deadline > g_uptime) {
  1730. previous_alarm_remaining = (m_alarm_deadline - g_uptime) / TICKS_PER_SECOND;
  1731. }
  1732. if (!seconds) {
  1733. m_alarm_deadline = 0;
  1734. return previous_alarm_remaining;
  1735. }
  1736. m_alarm_deadline = g_uptime + seconds * TICKS_PER_SECOND;
  1737. return previous_alarm_remaining;
  1738. }
  1739. int Process::sys$uname(utsname* buf)
  1740. {
  1741. REQUIRE_PROMISE(stdio);
  1742. if (!validate_write_typed(buf))
  1743. return -EFAULT;
  1744. LOCKER(*s_hostname_lock);
  1745. if (s_hostname->length() + 1 > sizeof(utsname::nodename))
  1746. return -ENAMETOOLONG;
  1747. copy_to_user(buf->sysname, "SerenityOS", 11);
  1748. copy_to_user(buf->release, "1.0-dev", 8);
  1749. copy_to_user(buf->version, "FIXME", 6);
  1750. copy_to_user(buf->machine, "i686", 5);
  1751. copy_to_user(buf->nodename, s_hostname->characters(), s_hostname->length() + 1);
  1752. return 0;
  1753. }
  1754. KResult Process::do_kill(Process& process, int signal)
  1755. {
  1756. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1757. // FIXME: Should setuid processes have some special treatment here?
  1758. if (!is_superuser() && m_euid != process.m_uid && m_uid != process.m_uid)
  1759. return KResult(-EPERM);
  1760. if (process.is_ring0() && signal == SIGKILL) {
  1761. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, process.name().characters(), process.pid());
  1762. return KResult(-EPERM);
  1763. }
  1764. if (signal != 0)
  1765. process.send_signal(signal, this);
  1766. return KSuccess;
  1767. }
  1768. KResult Process::do_killpg(pid_t pgrp, int signal)
  1769. {
  1770. ASSERT(pgrp >= 0);
  1771. // Send the signal to all processes in the given group.
  1772. if (pgrp == 0) {
  1773. // Send the signal to our own pgrp.
  1774. pgrp = pgid();
  1775. }
  1776. bool group_was_empty = true;
  1777. bool any_succeeded = false;
  1778. KResult error = KSuccess;
  1779. Process::for_each_in_pgrp(pgrp, [&](auto& process) {
  1780. group_was_empty = false;
  1781. KResult res = do_kill(process, signal);
  1782. if (res.is_success())
  1783. any_succeeded = true;
  1784. else
  1785. error = res;
  1786. return IterationDecision::Continue;
  1787. });
  1788. if (group_was_empty)
  1789. return KResult(-ESRCH);
  1790. if (any_succeeded)
  1791. return KSuccess;
  1792. return error;
  1793. }
  1794. int Process::sys$kill(pid_t pid, int signal)
  1795. {
  1796. REQUIRE_PROMISE(proc);
  1797. if (signal < 0 || signal >= 32)
  1798. return -EINVAL;
  1799. if (pid <= 0)
  1800. return do_killpg(-pid, signal);
  1801. if (pid == -1) {
  1802. // FIXME: Send to all processes.
  1803. return -ENOTIMPL;
  1804. }
  1805. if (pid == m_pid) {
  1806. if (signal == 0)
  1807. return 0;
  1808. if (!current->should_ignore_signal(signal)) {
  1809. current->send_signal(signal, this);
  1810. (void)current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal);
  1811. }
  1812. return 0;
  1813. }
  1814. InterruptDisabler disabler;
  1815. auto* peer = Process::from_pid(pid);
  1816. if (!peer)
  1817. return -ESRCH;
  1818. return do_kill(*peer, signal);
  1819. }
  1820. int Process::sys$usleep(useconds_t usec)
  1821. {
  1822. REQUIRE_PROMISE(stdio);
  1823. if (!usec)
  1824. return 0;
  1825. u64 wakeup_time = current->sleep(usec / 1000);
  1826. if (wakeup_time > g_uptime)
  1827. return -EINTR;
  1828. return 0;
  1829. }
  1830. int Process::sys$sleep(unsigned seconds)
  1831. {
  1832. REQUIRE_PROMISE(stdio);
  1833. if (!seconds)
  1834. return 0;
  1835. u64 wakeup_time = current->sleep(seconds * TICKS_PER_SECOND);
  1836. if (wakeup_time > g_uptime) {
  1837. u32 ticks_left_until_original_wakeup_time = wakeup_time - g_uptime;
  1838. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1839. }
  1840. return 0;
  1841. }
  1842. timeval kgettimeofday()
  1843. {
  1844. return const_cast<const timeval&>(((KernelInfoPage*)s_info_page_address_for_kernel.as_ptr())->now);
  1845. }
  1846. void kgettimeofday(timeval& tv)
  1847. {
  1848. tv = kgettimeofday();
  1849. }
  1850. int Process::sys$gettimeofday(timeval* tv)
  1851. {
  1852. REQUIRE_PROMISE(stdio);
  1853. if (!validate_write_typed(tv))
  1854. return -EFAULT;
  1855. *tv = kgettimeofday();
  1856. return 0;
  1857. }
  1858. uid_t Process::sys$getuid()
  1859. {
  1860. REQUIRE_PROMISE(stdio);
  1861. return m_uid;
  1862. }
  1863. gid_t Process::sys$getgid()
  1864. {
  1865. REQUIRE_PROMISE(stdio);
  1866. return m_gid;
  1867. }
  1868. uid_t Process::sys$geteuid()
  1869. {
  1870. REQUIRE_PROMISE(stdio);
  1871. return m_euid;
  1872. }
  1873. gid_t Process::sys$getegid()
  1874. {
  1875. REQUIRE_PROMISE(stdio);
  1876. return m_egid;
  1877. }
  1878. pid_t Process::sys$getpid()
  1879. {
  1880. REQUIRE_PROMISE(stdio);
  1881. return m_pid;
  1882. }
  1883. pid_t Process::sys$getppid()
  1884. {
  1885. REQUIRE_PROMISE(stdio);
  1886. return m_ppid;
  1887. }
  1888. mode_t Process::sys$umask(mode_t mask)
  1889. {
  1890. REQUIRE_PROMISE(stdio);
  1891. auto old_mask = m_umask;
  1892. m_umask = mask & 0777;
  1893. return old_mask;
  1894. }
  1895. int Process::reap(Process& process)
  1896. {
  1897. int exit_status;
  1898. {
  1899. InterruptDisabler disabler;
  1900. exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1901. if (process.ppid()) {
  1902. auto* parent = Process::from_pid(process.ppid());
  1903. if (parent) {
  1904. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1905. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1906. }
  1907. }
  1908. dbgprintf("reap: %s(%u)\n", process.name().characters(), process.pid());
  1909. ASSERT(process.is_dead());
  1910. g_processes->remove(&process);
  1911. }
  1912. delete &process;
  1913. return exit_status;
  1914. }
  1915. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1916. {
  1917. REQUIRE_PROMISE(stdio);
  1918. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1919. if (!options) {
  1920. // FIXME: This can't be right.. can it? Figure out how this should actually work.
  1921. options = WEXITED;
  1922. }
  1923. if (wstatus && !validate_write_typed(wstatus))
  1924. return -EFAULT;
  1925. int exit_status = 0;
  1926. {
  1927. InterruptDisabler disabler;
  1928. if (waitee != -1 && !Process::from_pid(waitee))
  1929. return -ECHILD;
  1930. }
  1931. if (options & WNOHANG) {
  1932. // FIXME: Figure out what WNOHANG should do with stopped children.
  1933. if (waitee == -1) {
  1934. pid_t reaped_pid = 0;
  1935. InterruptDisabler disabler;
  1936. for_each_child([&reaped_pid, &exit_status](Process& process) {
  1937. if (process.is_dead()) {
  1938. reaped_pid = process.pid();
  1939. exit_status = reap(process);
  1940. }
  1941. return IterationDecision::Continue;
  1942. });
  1943. return reaped_pid;
  1944. } else {
  1945. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1946. InterruptDisabler disabler;
  1947. auto* waitee_process = Process::from_pid(waitee);
  1948. if (!waitee_process)
  1949. return -ECHILD;
  1950. if (waitee_process->is_dead()) {
  1951. exit_status = reap(*waitee_process);
  1952. return waitee;
  1953. }
  1954. return 0;
  1955. }
  1956. }
  1957. pid_t waitee_pid = waitee;
  1958. if (current->block<Thread::WaitBlocker>(options, waitee_pid) != Thread::BlockResult::WokeNormally)
  1959. return -EINTR;
  1960. InterruptDisabler disabler;
  1961. // NOTE: If waitee was -1, m_waitee_pid will have been filled in by the scheduler.
  1962. Process* waitee_process = Process::from_pid(waitee_pid);
  1963. if (!waitee_process)
  1964. return -ECHILD;
  1965. ASSERT(waitee_process);
  1966. if (waitee_process->is_dead()) {
  1967. exit_status = reap(*waitee_process);
  1968. } else {
  1969. ASSERT(waitee_process->any_thread().state() == Thread::State::Stopped);
  1970. exit_status = 0x7f;
  1971. }
  1972. if (wstatus)
  1973. copy_to_user(wstatus, &exit_status, sizeof(exit_status));
  1974. return waitee_pid;
  1975. }
  1976. bool Process::validate_read_from_kernel(VirtualAddress vaddr, ssize_t size) const
  1977. {
  1978. if (vaddr.is_null())
  1979. return false;
  1980. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1981. // This code allows access outside of the known used address ranges to get caught.
  1982. if (is_kmalloc_address(vaddr.as_ptr()))
  1983. return true;
  1984. return MM.validate_kernel_read(*this, vaddr, size);
  1985. }
  1986. bool Process::validate_read(const void* address, ssize_t size) const
  1987. {
  1988. ASSERT(size >= 0);
  1989. VirtualAddress first_address((u32)address);
  1990. if (is_ring0()) {
  1991. if (is_kmalloc_address(address))
  1992. return true;
  1993. }
  1994. if (!size)
  1995. return false;
  1996. return MM.validate_user_read(*this, first_address, size);
  1997. }
  1998. bool Process::validate_write(void* address, ssize_t size) const
  1999. {
  2000. ASSERT(size >= 0);
  2001. VirtualAddress first_address((u32)address);
  2002. if (is_ring0()) {
  2003. if (is_kmalloc_address(address))
  2004. return true;
  2005. }
  2006. if (!size)
  2007. return false;
  2008. return MM.validate_user_write(*this, first_address, size);
  2009. }
  2010. pid_t Process::sys$getsid(pid_t pid)
  2011. {
  2012. REQUIRE_PROMISE(stdio);
  2013. if (pid == 0)
  2014. return m_sid;
  2015. InterruptDisabler disabler;
  2016. auto* process = Process::from_pid(pid);
  2017. if (!process)
  2018. return -ESRCH;
  2019. if (m_sid != process->m_sid)
  2020. return -EPERM;
  2021. return process->m_sid;
  2022. }
  2023. pid_t Process::sys$setsid()
  2024. {
  2025. REQUIRE_PROMISE(proc);
  2026. InterruptDisabler disabler;
  2027. bool found_process_with_same_pgid_as_my_pid = false;
  2028. Process::for_each_in_pgrp(pid(), [&](auto&) {
  2029. found_process_with_same_pgid_as_my_pid = true;
  2030. return IterationDecision::Break;
  2031. });
  2032. if (found_process_with_same_pgid_as_my_pid)
  2033. return -EPERM;
  2034. m_sid = m_pid;
  2035. m_pgid = m_pid;
  2036. return m_sid;
  2037. }
  2038. pid_t Process::sys$getpgid(pid_t pid)
  2039. {
  2040. REQUIRE_PROMISE(stdio);
  2041. if (pid == 0)
  2042. return m_pgid;
  2043. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  2044. auto* process = Process::from_pid(pid);
  2045. if (!process)
  2046. return -ESRCH;
  2047. return process->m_pgid;
  2048. }
  2049. pid_t Process::sys$getpgrp()
  2050. {
  2051. REQUIRE_PROMISE(stdio);
  2052. return m_pgid;
  2053. }
  2054. static pid_t get_sid_from_pgid(pid_t pgid)
  2055. {
  2056. InterruptDisabler disabler;
  2057. auto* group_leader = Process::from_pid(pgid);
  2058. if (!group_leader)
  2059. return -1;
  2060. return group_leader->sid();
  2061. }
  2062. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  2063. {
  2064. REQUIRE_PROMISE(proc);
  2065. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  2066. pid_t pid = specified_pid ? specified_pid : m_pid;
  2067. if (specified_pgid < 0) {
  2068. // The value of the pgid argument is less than 0, or is not a value supported by the implementation.
  2069. return -EINVAL;
  2070. }
  2071. auto* process = Process::from_pid(pid);
  2072. if (!process)
  2073. return -ESRCH;
  2074. if (process != this && process->ppid() != m_pid) {
  2075. // The value of the pid argument does not match the process ID
  2076. // of the calling process or of a child process of the calling process.
  2077. return -ESRCH;
  2078. }
  2079. if (process->pid() == process->sid()) {
  2080. // The process indicated by the pid argument is a session leader.
  2081. return -EPERM;
  2082. }
  2083. if (process->ppid() == m_pid && process->sid() != sid()) {
  2084. // The value of the pid argument matches the process ID of a child
  2085. // process of the calling process and the child process is not in
  2086. // the same session as the calling process.
  2087. return -EPERM;
  2088. }
  2089. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  2090. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  2091. pid_t new_sid = get_sid_from_pgid(new_pgid);
  2092. if (current_sid != new_sid) {
  2093. // Can't move a process between sessions.
  2094. return -EPERM;
  2095. }
  2096. // FIXME: There are more EPERM conditions to check for here..
  2097. process->m_pgid = new_pgid;
  2098. return 0;
  2099. }
  2100. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  2101. {
  2102. auto description = file_description(fd);
  2103. if (!description)
  2104. return -EBADF;
  2105. SmapDisabler disabler;
  2106. return description->file().ioctl(*description, request, arg);
  2107. }
  2108. int Process::sys$getdtablesize()
  2109. {
  2110. REQUIRE_PROMISE(stdio);
  2111. return m_max_open_file_descriptors;
  2112. }
  2113. int Process::sys$dup(int old_fd)
  2114. {
  2115. REQUIRE_PROMISE(stdio);
  2116. auto description = file_description(old_fd);
  2117. if (!description)
  2118. return -EBADF;
  2119. int new_fd = alloc_fd(0);
  2120. if (new_fd < 0)
  2121. return new_fd;
  2122. m_fds[new_fd].set(*description);
  2123. return new_fd;
  2124. }
  2125. int Process::sys$dup2(int old_fd, int new_fd)
  2126. {
  2127. REQUIRE_PROMISE(stdio);
  2128. auto description = file_description(old_fd);
  2129. if (!description)
  2130. return -EBADF;
  2131. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  2132. return -EINVAL;
  2133. m_fds[new_fd].set(*description);
  2134. return new_fd;
  2135. }
  2136. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  2137. {
  2138. REQUIRE_PROMISE(stdio);
  2139. if (old_set) {
  2140. if (!validate_write_typed(old_set))
  2141. return -EFAULT;
  2142. copy_to_user(old_set, &current->m_signal_mask, sizeof(current->m_signal_mask));
  2143. }
  2144. if (set) {
  2145. if (!validate_read_typed(set))
  2146. return -EFAULT;
  2147. sigset_t set_value;
  2148. copy_from_user(&set_value, set);
  2149. switch (how) {
  2150. case SIG_BLOCK:
  2151. current->m_signal_mask &= ~set_value;
  2152. break;
  2153. case SIG_UNBLOCK:
  2154. current->m_signal_mask |= set_value;
  2155. break;
  2156. case SIG_SETMASK:
  2157. current->m_signal_mask = set_value;
  2158. break;
  2159. default:
  2160. return -EINVAL;
  2161. }
  2162. }
  2163. return 0;
  2164. }
  2165. int Process::sys$sigpending(sigset_t* set)
  2166. {
  2167. REQUIRE_PROMISE(stdio);
  2168. if (!validate_write_typed(set))
  2169. return -EFAULT;
  2170. copy_to_user(set, &current->m_pending_signals, sizeof(current->m_pending_signals));
  2171. return 0;
  2172. }
  2173. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  2174. {
  2175. REQUIRE_PROMISE(stdio);
  2176. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  2177. return -EINVAL;
  2178. if (!validate_read_typed(act))
  2179. return -EFAULT;
  2180. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  2181. auto& action = current->m_signal_action_data[signum];
  2182. if (old_act) {
  2183. if (!validate_write_typed(old_act))
  2184. return -EFAULT;
  2185. copy_to_user(&old_act->sa_flags, &action.flags, sizeof(action.flags));
  2186. copy_to_user(&old_act->sa_sigaction, &action.handler_or_sigaction, sizeof(action.handler_or_sigaction));
  2187. }
  2188. copy_from_user(&action.flags, &act->sa_flags);
  2189. copy_from_user(&action.handler_or_sigaction, &act->sa_sigaction, sizeof(action.flags));
  2190. return 0;
  2191. }
  2192. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  2193. {
  2194. REQUIRE_PROMISE(stdio);
  2195. if (count < 0)
  2196. return -EINVAL;
  2197. if (!count)
  2198. return m_extra_gids.size();
  2199. if (count != (int)m_extra_gids.size())
  2200. return -EINVAL;
  2201. if (!validate_write_typed(gids, m_extra_gids.size()))
  2202. return -EFAULT;
  2203. size_t i = 0;
  2204. SmapDisabler disabler;
  2205. for (auto gid : m_extra_gids)
  2206. gids[i++] = gid;
  2207. return 0;
  2208. }
  2209. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  2210. {
  2211. REQUIRE_PROMISE(id);
  2212. if (count < 0)
  2213. return -EINVAL;
  2214. if (!is_superuser())
  2215. return -EPERM;
  2216. if (count && !validate_read(gids, count))
  2217. return -EFAULT;
  2218. m_extra_gids.clear();
  2219. SmapDisabler disabler;
  2220. for (int i = 0; i < count; ++i) {
  2221. if (gids[i] == m_gid)
  2222. continue;
  2223. m_extra_gids.set(gids[i]);
  2224. }
  2225. return 0;
  2226. }
  2227. int Process::sys$mkdir(const char* user_path, size_t path_length, mode_t mode)
  2228. {
  2229. REQUIRE_PROMISE(cpath);
  2230. auto path = get_syscall_path_argument(user_path, path_length);
  2231. if (path.is_error())
  2232. return path.error();
  2233. return VFS::the().mkdir(path.value(), mode & ~umask(), current_directory());
  2234. }
  2235. int Process::sys$realpath(const Syscall::SC_realpath_params* user_params)
  2236. {
  2237. REQUIRE_PROMISE(rpath);
  2238. Syscall::SC_realpath_params params;
  2239. if (!validate_read_and_copy_typed(&params, user_params))
  2240. return -EFAULT;
  2241. if (!validate_write(params.buffer.data, params.buffer.size))
  2242. return -EFAULT;
  2243. auto path = get_syscall_path_argument(params.path);
  2244. if (path.is_error())
  2245. return path.error();
  2246. auto custody_or_error = VFS::the().resolve_path(path.value(), current_directory());
  2247. if (custody_or_error.is_error())
  2248. return custody_or_error.error();
  2249. auto& custody = custody_or_error.value();
  2250. // FIXME: Once resolve_path is fixed to deal with .. and . , remove the use of FileSystemPath::canonical_path.
  2251. FileSystemPath canonical_path(custody->absolute_path());
  2252. if (!canonical_path.is_valid()) {
  2253. dbg() << "FileSystemPath failed to canonicalize " << custody->absolute_path();
  2254. ASSERT_NOT_REACHED();
  2255. }
  2256. if (canonical_path.string().length() + 1 > params.buffer.size)
  2257. return -ENAMETOOLONG;
  2258. copy_to_user(params.buffer.data, canonical_path.string().characters(), canonical_path.string().length() + 1);
  2259. return 0;
  2260. };
  2261. clock_t Process::sys$times(tms* times)
  2262. {
  2263. REQUIRE_PROMISE(stdio);
  2264. if (!validate_write_typed(times))
  2265. return -EFAULT;
  2266. copy_to_user(&times->tms_utime, &m_ticks_in_user, sizeof(m_ticks_in_user));
  2267. copy_to_user(&times->tms_stime, &m_ticks_in_kernel, sizeof(m_ticks_in_kernel));
  2268. copy_to_user(&times->tms_cutime, &m_ticks_in_user_for_dead_children, sizeof(m_ticks_in_user_for_dead_children));
  2269. copy_to_user(&times->tms_cstime, &m_ticks_in_kernel_for_dead_children, sizeof(m_ticks_in_kernel_for_dead_children));
  2270. return g_uptime & 0x7fffffff;
  2271. }
  2272. int Process::sys$select(const Syscall::SC_select_params* params)
  2273. {
  2274. REQUIRE_PROMISE(stdio);
  2275. // FIXME: Return -EINVAL if timeout is invalid.
  2276. if (!validate_read_typed(params))
  2277. return -EFAULT;
  2278. SmapDisabler disabler;
  2279. int nfds = params->nfds;
  2280. fd_set* readfds = params->readfds;
  2281. fd_set* writefds = params->writefds;
  2282. fd_set* exceptfds = params->exceptfds;
  2283. timeval* timeout = params->timeout;
  2284. if (writefds && !validate_write_typed(writefds))
  2285. return -EFAULT;
  2286. if (readfds && !validate_write_typed(readfds))
  2287. return -EFAULT;
  2288. if (exceptfds && !validate_write_typed(exceptfds))
  2289. return -EFAULT;
  2290. if (timeout && !validate_read_typed(timeout))
  2291. return -EFAULT;
  2292. if (nfds < 0)
  2293. return -EINVAL;
  2294. timeval computed_timeout;
  2295. bool select_has_timeout = false;
  2296. if (timeout && (timeout->tv_sec || timeout->tv_usec)) {
  2297. timeval_add(kgettimeofday(), *timeout, computed_timeout);
  2298. select_has_timeout = true;
  2299. }
  2300. Thread::SelectBlocker::FDVector rfds;
  2301. Thread::SelectBlocker::FDVector wfds;
  2302. Thread::SelectBlocker::FDVector efds;
  2303. auto transfer_fds = [&](auto* fds, auto& vector) -> int {
  2304. vector.clear_with_capacity();
  2305. if (!fds)
  2306. return 0;
  2307. for (int fd = 0; fd < nfds; ++fd) {
  2308. if (FD_ISSET(fd, fds)) {
  2309. if (!file_description(fd)) {
  2310. dbg() << *current << " sys$select: Bad fd number " << fd;
  2311. return -EBADF;
  2312. }
  2313. vector.append(fd);
  2314. }
  2315. }
  2316. return 0;
  2317. };
  2318. if (int error = transfer_fds(writefds, wfds))
  2319. return error;
  2320. if (int error = transfer_fds(readfds, rfds))
  2321. return error;
  2322. if (int error = transfer_fds(exceptfds, efds))
  2323. return error;
  2324. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  2325. dbgprintf("%s<%u> selecting on (read:%u, write:%u), timeout=%p\n", name().characters(), pid(), rfds.size(), wfds.size(), timeout);
  2326. #endif
  2327. if (!timeout || select_has_timeout) {
  2328. if (current->block<Thread::SelectBlocker>(computed_timeout, select_has_timeout, rfds, wfds, efds) != Thread::BlockResult::WokeNormally)
  2329. return -EINTR;
  2330. }
  2331. int marked_fd_count = 0;
  2332. auto mark_fds = [&](auto* fds, auto& vector, auto should_mark) {
  2333. if (!fds)
  2334. return;
  2335. FD_ZERO(fds);
  2336. for (int fd : vector) {
  2337. if (auto description = file_description(fd); description && should_mark(*description)) {
  2338. FD_SET(fd, fds);
  2339. ++marked_fd_count;
  2340. }
  2341. }
  2342. };
  2343. mark_fds(readfds, rfds, [](auto& description) { return description.can_read(); });
  2344. mark_fds(writefds, wfds, [](auto& description) { return description.can_write(); });
  2345. // FIXME: We should also mark exceptfds as appropriate.
  2346. return marked_fd_count;
  2347. }
  2348. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  2349. {
  2350. REQUIRE_PROMISE(stdio);
  2351. if (!validate_read_typed(fds))
  2352. return -EFAULT;
  2353. SmapDisabler disabler;
  2354. Thread::SelectBlocker::FDVector rfds;
  2355. Thread::SelectBlocker::FDVector wfds;
  2356. for (int i = 0; i < nfds; ++i) {
  2357. if (fds[i].events & POLLIN)
  2358. rfds.append(fds[i].fd);
  2359. if (fds[i].events & POLLOUT)
  2360. wfds.append(fds[i].fd);
  2361. }
  2362. timeval actual_timeout;
  2363. bool has_timeout = false;
  2364. if (timeout >= 0) {
  2365. // poll is in ms, we want s/us.
  2366. struct timeval tvtimeout;
  2367. tvtimeout.tv_sec = 0;
  2368. while (timeout >= 1000) {
  2369. tvtimeout.tv_sec += 1;
  2370. timeout -= 1000;
  2371. }
  2372. tvtimeout.tv_usec = timeout * 1000;
  2373. timeval_add(kgettimeofday(), tvtimeout, actual_timeout);
  2374. has_timeout = true;
  2375. }
  2376. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  2377. dbgprintf("%s<%u> polling on (read:%u, write:%u), timeout=%d\n", name().characters(), pid(), rfds.size(), wfds.size(), timeout);
  2378. #endif
  2379. if (has_timeout || timeout < 0) {
  2380. if (current->block<Thread::SelectBlocker>(actual_timeout, has_timeout, rfds, wfds, Thread::SelectBlocker::FDVector()) != Thread::BlockResult::WokeNormally)
  2381. return -EINTR;
  2382. }
  2383. int fds_with_revents = 0;
  2384. for (int i = 0; i < nfds; ++i) {
  2385. auto description = file_description(fds[i].fd);
  2386. if (!description) {
  2387. fds[i].revents = POLLNVAL;
  2388. continue;
  2389. }
  2390. fds[i].revents = 0;
  2391. if (fds[i].events & POLLIN && description->can_read())
  2392. fds[i].revents |= POLLIN;
  2393. if (fds[i].events & POLLOUT && description->can_write())
  2394. fds[i].revents |= POLLOUT;
  2395. if (fds[i].revents)
  2396. ++fds_with_revents;
  2397. }
  2398. return fds_with_revents;
  2399. }
  2400. Custody& Process::current_directory()
  2401. {
  2402. if (!m_cwd)
  2403. m_cwd = VFS::the().root_custody();
  2404. return *m_cwd;
  2405. }
  2406. int Process::sys$link(const Syscall::SC_link_params* user_params)
  2407. {
  2408. REQUIRE_PROMISE(cpath);
  2409. Syscall::SC_link_params params;
  2410. if (!validate_read_and_copy_typed(&params, user_params))
  2411. return -EFAULT;
  2412. auto old_path = validate_and_copy_string_from_user(params.old_path);
  2413. auto new_path = validate_and_copy_string_from_user(params.new_path);
  2414. if (old_path.is_null() || new_path.is_null())
  2415. return -EFAULT;
  2416. return VFS::the().link(old_path, new_path, current_directory());
  2417. }
  2418. int Process::sys$unlink(const char* user_path, size_t path_length)
  2419. {
  2420. REQUIRE_PROMISE(cpath);
  2421. if (!validate_read(user_path, path_length))
  2422. return -EFAULT;
  2423. auto path = get_syscall_path_argument(user_path, path_length);
  2424. if (path.is_error())
  2425. return path.error();
  2426. return VFS::the().unlink(path.value(), current_directory());
  2427. }
  2428. int Process::sys$symlink(const Syscall::SC_symlink_params* user_params)
  2429. {
  2430. REQUIRE_PROMISE(cpath);
  2431. Syscall::SC_symlink_params params;
  2432. if (!validate_read_and_copy_typed(&params, user_params))
  2433. return -EFAULT;
  2434. auto target = get_syscall_path_argument(params.target);
  2435. if (target.is_error())
  2436. return target.error();
  2437. auto linkpath = get_syscall_path_argument(params.linkpath);
  2438. if (linkpath.is_error())
  2439. return linkpath.error();
  2440. return VFS::the().symlink(target.value(), linkpath.value(), current_directory());
  2441. }
  2442. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  2443. {
  2444. if (path_length == 0)
  2445. return KResult(-EINVAL);
  2446. if (path_length > PATH_MAX)
  2447. return KResult(-ENAMETOOLONG);
  2448. if (!validate_read(user_path, path_length))
  2449. return KResult(-EFAULT);
  2450. return copy_string_from_user(user_path, path_length);
  2451. }
  2452. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  2453. {
  2454. return get_syscall_path_argument(path.characters, path.length);
  2455. }
  2456. int Process::sys$rmdir(const char* user_path, size_t path_length)
  2457. {
  2458. REQUIRE_PROMISE(cpath);
  2459. auto path = get_syscall_path_argument(user_path, path_length);
  2460. if (path.is_error())
  2461. return path.error();
  2462. return VFS::the().rmdir(path.value(), current_directory());
  2463. }
  2464. int Process::sys$chmod(const char* user_path, size_t path_length, mode_t mode)
  2465. {
  2466. REQUIRE_PROMISE(fattr);
  2467. auto path = get_syscall_path_argument(user_path, path_length);
  2468. if (path.is_error())
  2469. return path.error();
  2470. return VFS::the().chmod(path.value(), mode, current_directory());
  2471. }
  2472. int Process::sys$fchmod(int fd, mode_t mode)
  2473. {
  2474. REQUIRE_PROMISE(fattr);
  2475. auto description = file_description(fd);
  2476. if (!description)
  2477. return -EBADF;
  2478. return description->chmod(mode);
  2479. }
  2480. int Process::sys$fchown(int fd, uid_t uid, gid_t gid)
  2481. {
  2482. REQUIRE_PROMISE(chown);
  2483. auto description = file_description(fd);
  2484. if (!description)
  2485. return -EBADF;
  2486. return description->chown(uid, gid);
  2487. }
  2488. int Process::sys$chown(const Syscall::SC_chown_params* user_params)
  2489. {
  2490. REQUIRE_PROMISE(chown);
  2491. Syscall::SC_chown_params params;
  2492. if (!validate_read_and_copy_typed(&params, user_params))
  2493. return -EFAULT;
  2494. auto path = get_syscall_path_argument(params.path);
  2495. if (path.is_error())
  2496. return path.error();
  2497. return VFS::the().chown(path.value(), params.uid, params.gid, current_directory());
  2498. }
  2499. void Process::finalize()
  2500. {
  2501. ASSERT(current == g_finalizer);
  2502. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  2503. m_fds.clear();
  2504. m_tty = nullptr;
  2505. m_executable = nullptr;
  2506. m_cwd = nullptr;
  2507. m_root_directory = nullptr;
  2508. m_root_directory_relative_to_global_root = nullptr;
  2509. m_elf_loader = nullptr;
  2510. disown_all_shared_buffers();
  2511. {
  2512. InterruptDisabler disabler;
  2513. if (auto* parent_thread = Thread::from_tid(m_ppid)) {
  2514. if (parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  2515. // NOTE: If the parent doesn't care about this process, let it go.
  2516. m_ppid = 0;
  2517. } else {
  2518. parent_thread->send_signal(SIGCHLD, this);
  2519. }
  2520. }
  2521. }
  2522. m_dead = true;
  2523. }
  2524. void Process::die()
  2525. {
  2526. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  2527. // getting an EOF when the last process using the slave PTY dies.
  2528. // If the master PTY owner relies on an EOF to know when to wait() on a
  2529. // slave owner, we have to allow the PTY pair to be torn down.
  2530. m_tty = nullptr;
  2531. if (m_tracer)
  2532. m_tracer->set_dead();
  2533. {
  2534. // Tell the threads to unwind and die.
  2535. InterruptDisabler disabler;
  2536. for_each_thread([](Thread& thread) {
  2537. thread.set_should_die();
  2538. return IterationDecision::Continue;
  2539. });
  2540. }
  2541. }
  2542. size_t Process::amount_dirty_private() const
  2543. {
  2544. // FIXME: This gets a bit more complicated for Regions sharing the same underlying VMObject.
  2545. // The main issue I'm thinking of is when the VMObject has physical pages that none of the Regions are mapping.
  2546. // That's probably a situation that needs to be looked at in general.
  2547. size_t amount = 0;
  2548. for (auto& region : m_regions) {
  2549. if (!region.is_shared())
  2550. amount += region.amount_dirty();
  2551. }
  2552. return amount;
  2553. }
  2554. size_t Process::amount_clean_inode() const
  2555. {
  2556. HashTable<const InodeVMObject*> vmobjects;
  2557. for (auto& region : m_regions) {
  2558. if (region.vmobject().is_inode())
  2559. vmobjects.set(&static_cast<const InodeVMObject&>(region.vmobject()));
  2560. }
  2561. size_t amount = 0;
  2562. for (auto& vmobject : vmobjects)
  2563. amount += vmobject->amount_clean();
  2564. return amount;
  2565. }
  2566. size_t Process::amount_virtual() const
  2567. {
  2568. size_t amount = 0;
  2569. for (auto& region : m_regions) {
  2570. amount += region.size();
  2571. }
  2572. return amount;
  2573. }
  2574. size_t Process::amount_resident() const
  2575. {
  2576. // FIXME: This will double count if multiple regions use the same physical page.
  2577. size_t amount = 0;
  2578. for (auto& region : m_regions) {
  2579. amount += region.amount_resident();
  2580. }
  2581. return amount;
  2582. }
  2583. size_t Process::amount_shared() const
  2584. {
  2585. // FIXME: This will double count if multiple regions use the same physical page.
  2586. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  2587. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  2588. // so that every Region contributes +1 ref to each of its PhysicalPages.
  2589. size_t amount = 0;
  2590. for (auto& region : m_regions) {
  2591. amount += region.amount_shared();
  2592. }
  2593. return amount;
  2594. }
  2595. size_t Process::amount_purgeable_volatile() const
  2596. {
  2597. size_t amount = 0;
  2598. for (auto& region : m_regions) {
  2599. if (region.vmobject().is_purgeable() && static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  2600. amount += region.amount_resident();
  2601. }
  2602. return amount;
  2603. }
  2604. size_t Process::amount_purgeable_nonvolatile() const
  2605. {
  2606. size_t amount = 0;
  2607. for (auto& region : m_regions) {
  2608. if (region.vmobject().is_purgeable() && !static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  2609. amount += region.amount_resident();
  2610. }
  2611. return amount;
  2612. }
  2613. #define REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(domain) \
  2614. do { \
  2615. if (domain == AF_INET) \
  2616. REQUIRE_PROMISE(inet); \
  2617. else if (domain == AF_LOCAL) \
  2618. REQUIRE_PROMISE(unix); \
  2619. } while (0)
  2620. int Process::sys$socket(int domain, int type, int protocol)
  2621. {
  2622. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(domain);
  2623. if ((type & SOCK_TYPE_MASK) == SOCK_RAW && !is_superuser())
  2624. return -EACCES;
  2625. int fd = alloc_fd();
  2626. if (fd < 0)
  2627. return fd;
  2628. auto result = Socket::create(domain, type, protocol);
  2629. if (result.is_error())
  2630. return result.error();
  2631. auto description = FileDescription::create(*result.value());
  2632. description->set_readable(true);
  2633. description->set_writable(true);
  2634. unsigned flags = 0;
  2635. if (type & SOCK_CLOEXEC)
  2636. flags |= FD_CLOEXEC;
  2637. if (type & SOCK_NONBLOCK)
  2638. description->set_blocking(false);
  2639. m_fds[fd].set(move(description), flags);
  2640. return fd;
  2641. }
  2642. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2643. {
  2644. if (!validate_read(address, address_length))
  2645. return -EFAULT;
  2646. auto description = file_description(sockfd);
  2647. if (!description)
  2648. return -EBADF;
  2649. if (!description->is_socket())
  2650. return -ENOTSOCK;
  2651. auto& socket = *description->socket();
  2652. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2653. return socket.bind(address, address_length);
  2654. }
  2655. int Process::sys$listen(int sockfd, int backlog)
  2656. {
  2657. auto description = file_description(sockfd);
  2658. if (!description)
  2659. return -EBADF;
  2660. if (!description->is_socket())
  2661. return -ENOTSOCK;
  2662. auto& socket = *description->socket();
  2663. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2664. if (socket.is_connected())
  2665. return -EINVAL;
  2666. return socket.listen(backlog);
  2667. }
  2668. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  2669. {
  2670. REQUIRE_PROMISE(accept);
  2671. if (!validate_write_typed(address_size))
  2672. return -EFAULT;
  2673. SmapDisabler disabler;
  2674. if (!validate_write(address, *address_size))
  2675. return -EFAULT;
  2676. int accepted_socket_fd = alloc_fd();
  2677. if (accepted_socket_fd < 0)
  2678. return accepted_socket_fd;
  2679. auto accepting_socket_description = file_description(accepting_socket_fd);
  2680. if (!accepting_socket_description)
  2681. return -EBADF;
  2682. if (!accepting_socket_description->is_socket())
  2683. return -ENOTSOCK;
  2684. auto& socket = *accepting_socket_description->socket();
  2685. if (!socket.can_accept()) {
  2686. if (accepting_socket_description->is_blocking()) {
  2687. if (current->block<Thread::AcceptBlocker>(*accepting_socket_description) != Thread::BlockResult::WokeNormally)
  2688. return -EINTR;
  2689. } else {
  2690. return -EAGAIN;
  2691. }
  2692. }
  2693. auto accepted_socket = socket.accept();
  2694. ASSERT(accepted_socket);
  2695. bool success = accepted_socket->get_peer_address(address, address_size);
  2696. ASSERT(success);
  2697. auto accepted_socket_description = FileDescription::create(*accepted_socket);
  2698. accepted_socket_description->set_readable(true);
  2699. accepted_socket_description->set_writable(true);
  2700. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2701. // I'm not sure if this matches other systems but it makes sense to me.
  2702. accepted_socket_description->set_blocking(accepting_socket_description->is_blocking());
  2703. m_fds[accepted_socket_fd].set(move(accepted_socket_description), m_fds[accepting_socket_fd].flags);
  2704. // NOTE: Moving this state to Completed is what causes connect() to unblock on the client side.
  2705. accepted_socket->set_setup_state(Socket::SetupState::Completed);
  2706. return accepted_socket_fd;
  2707. }
  2708. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2709. {
  2710. if (!validate_read(address, address_size))
  2711. return -EFAULT;
  2712. int fd = alloc_fd();
  2713. if (fd < 0)
  2714. return fd;
  2715. auto description = file_description(sockfd);
  2716. if (!description)
  2717. return -EBADF;
  2718. if (!description->is_socket())
  2719. return -ENOTSOCK;
  2720. auto& socket = *description->socket();
  2721. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2722. SmapDisabler disabler;
  2723. return socket.connect(*description, address, address_size, description->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  2724. }
  2725. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* user_params)
  2726. {
  2727. REQUIRE_PROMISE(stdio);
  2728. Syscall::SC_sendto_params params;
  2729. if (!validate_read_and_copy_typed(&params, user_params))
  2730. return -EFAULT;
  2731. int flags = params.flags;
  2732. const sockaddr* addr = params.addr;
  2733. socklen_t addr_length = params.addr_length;
  2734. if (!validate(params.data))
  2735. return -EFAULT;
  2736. if (addr && !validate_read(addr, addr_length))
  2737. return -EFAULT;
  2738. auto description = file_description(params.sockfd);
  2739. if (!description)
  2740. return -EBADF;
  2741. if (!description->is_socket())
  2742. return -ENOTSOCK;
  2743. SmapDisabler disabler;
  2744. auto& socket = *description->socket();
  2745. return socket.sendto(*description, params.data.data, params.data.size, flags, addr, addr_length);
  2746. }
  2747. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* user_params)
  2748. {
  2749. REQUIRE_PROMISE(stdio);
  2750. Syscall::SC_recvfrom_params params;
  2751. if (!validate_read_and_copy_typed(&params, user_params))
  2752. return -EFAULT;
  2753. int flags = params.flags;
  2754. sockaddr* addr = params.addr;
  2755. socklen_t* addr_length = params.addr_length;
  2756. SmapDisabler disabler;
  2757. if (!validate(params.buffer))
  2758. return -EFAULT;
  2759. if (addr_length) {
  2760. if (!validate_write_typed(addr_length))
  2761. return -EFAULT;
  2762. if (!validate_write(addr, *addr_length))
  2763. return -EFAULT;
  2764. } else if (addr) {
  2765. return -EINVAL;
  2766. }
  2767. auto description = file_description(params.sockfd);
  2768. if (!description)
  2769. return -EBADF;
  2770. if (!description->is_socket())
  2771. return -ENOTSOCK;
  2772. auto& socket = *description->socket();
  2773. bool original_blocking = description->is_blocking();
  2774. if (flags & MSG_DONTWAIT)
  2775. description->set_blocking(false);
  2776. auto nrecv = socket.recvfrom(*description, params.buffer.data, params.buffer.size, flags, addr, addr_length);
  2777. if (flags & MSG_DONTWAIT)
  2778. description->set_blocking(original_blocking);
  2779. return nrecv;
  2780. }
  2781. int Process::sys$getsockname(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2782. {
  2783. if (!validate_read_typed(addrlen))
  2784. return -EFAULT;
  2785. SmapDisabler disabler;
  2786. if (*addrlen <= 0)
  2787. return -EINVAL;
  2788. if (!validate_write(addr, *addrlen))
  2789. return -EFAULT;
  2790. auto description = file_description(sockfd);
  2791. if (!description)
  2792. return -EBADF;
  2793. if (!description->is_socket())
  2794. return -ENOTSOCK;
  2795. auto& socket = *description->socket();
  2796. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2797. if (!socket.get_local_address(addr, addrlen))
  2798. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2799. return 0;
  2800. }
  2801. int Process::sys$getpeername(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2802. {
  2803. if (!validate_read_typed(addrlen))
  2804. return -EFAULT;
  2805. SmapDisabler disabler;
  2806. if (*addrlen <= 0)
  2807. return -EINVAL;
  2808. if (!validate_write(addr, *addrlen))
  2809. return -EFAULT;
  2810. auto description = file_description(sockfd);
  2811. if (!description)
  2812. return -EBADF;
  2813. if (!description->is_socket())
  2814. return -ENOTSOCK;
  2815. auto& socket = *description->socket();
  2816. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2817. if (socket.setup_state() != Socket::SetupState::Completed)
  2818. return -ENOTCONN;
  2819. if (!socket.get_peer_address(addr, addrlen))
  2820. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2821. return 0;
  2822. }
  2823. int Process::sys$sched_setparam(pid_t pid, const struct sched_param* param)
  2824. {
  2825. REQUIRE_PROMISE(proc);
  2826. if (!validate_read_typed(param))
  2827. return -EFAULT;
  2828. int desired_priority;
  2829. copy_from_user(&desired_priority, &param->sched_priority, sizeof(desired_priority));
  2830. InterruptDisabler disabler;
  2831. auto* peer = this;
  2832. if (pid != 0)
  2833. peer = Process::from_pid(pid);
  2834. if (!peer)
  2835. return -ESRCH;
  2836. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2837. return -EPERM;
  2838. if (desired_priority < THREAD_PRIORITY_MIN || desired_priority > THREAD_PRIORITY_MAX)
  2839. return -EINVAL;
  2840. peer->any_thread().set_priority((u32)desired_priority);
  2841. return 0;
  2842. }
  2843. int Process::sys$sched_getparam(pid_t pid, struct sched_param* param)
  2844. {
  2845. REQUIRE_PROMISE(proc);
  2846. if (!validate_write_typed(param))
  2847. return -EFAULT;
  2848. InterruptDisabler disabler;
  2849. auto* peer = this;
  2850. if (pid != 0)
  2851. peer = Process::from_pid(pid);
  2852. if (!peer)
  2853. return -ESRCH;
  2854. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2855. return -EPERM;
  2856. // FIXME: This doesn't seem like the way to get the right thread!
  2857. int priority = peer->any_thread().priority();
  2858. copy_to_user(&param->sched_priority, &priority, sizeof(priority));
  2859. return 0;
  2860. }
  2861. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  2862. {
  2863. if (!validate_read_typed(params))
  2864. return -EFAULT;
  2865. SmapDisabler disabler;
  2866. int sockfd = params->sockfd;
  2867. int level = params->level;
  2868. int option = params->option;
  2869. void* value = params->value;
  2870. socklen_t* value_size = params->value_size;
  2871. if (!validate_write_typed(value_size))
  2872. return -EFAULT;
  2873. if (!validate_write(value, *value_size))
  2874. return -EFAULT;
  2875. auto description = file_description(sockfd);
  2876. if (!description)
  2877. return -EBADF;
  2878. if (!description->is_socket())
  2879. return -ENOTSOCK;
  2880. auto& socket = *description->socket();
  2881. if (has_promised(Pledge::accept) && socket.is_local() && level == SOL_SOCKET && option == SO_PEERCRED) {
  2882. // We make an exception for SOL_SOCKET::SO_PEERCRED on local sockets if you've pledged "accept"
  2883. } else {
  2884. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2885. }
  2886. return socket.getsockopt(*description, level, option, value, value_size);
  2887. }
  2888. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  2889. {
  2890. if (!validate_read_typed(params))
  2891. return -EFAULT;
  2892. SmapDisabler disabler;
  2893. int sockfd = params->sockfd;
  2894. int level = params->level;
  2895. int option = params->option;
  2896. const void* value = params->value;
  2897. socklen_t value_size = params->value_size;
  2898. if (!validate_read(value, value_size))
  2899. return -EFAULT;
  2900. auto description = file_description(sockfd);
  2901. if (!description)
  2902. return -EBADF;
  2903. if (!description->is_socket())
  2904. return -ENOTSOCK;
  2905. auto& socket = *description->socket();
  2906. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2907. return socket.setsockopt(level, option, value, value_size);
  2908. }
  2909. void Process::disown_all_shared_buffers()
  2910. {
  2911. LOCKER(shared_buffers().lock());
  2912. Vector<SharedBuffer*, 32> buffers_to_disown;
  2913. for (auto& it : shared_buffers().resource())
  2914. buffers_to_disown.append(it.value.ptr());
  2915. for (auto* shared_buffer : buffers_to_disown)
  2916. shared_buffer->disown(m_pid);
  2917. }
  2918. int Process::sys$create_shared_buffer(int size, void** buffer)
  2919. {
  2920. REQUIRE_PROMISE(shared_buffer);
  2921. if (!size || size < 0)
  2922. return -EINVAL;
  2923. size = PAGE_ROUND_UP(size);
  2924. if (!validate_write_typed(buffer))
  2925. return -EFAULT;
  2926. LOCKER(shared_buffers().lock());
  2927. static int s_next_shared_buffer_id;
  2928. int shared_buffer_id = ++s_next_shared_buffer_id;
  2929. auto shared_buffer = make<SharedBuffer>(shared_buffer_id, size);
  2930. shared_buffer->share_with(m_pid);
  2931. void* address = shared_buffer->ref_for_process_and_get_address(*this);
  2932. {
  2933. SmapDisabler disabler;
  2934. *buffer = address;
  2935. }
  2936. ASSERT((int)shared_buffer->size() >= size);
  2937. #ifdef SHARED_BUFFER_DEBUG
  2938. 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());
  2939. #endif
  2940. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2941. return shared_buffer_id;
  2942. }
  2943. int Process::sys$share_buffer_with(int shared_buffer_id, pid_t peer_pid)
  2944. {
  2945. REQUIRE_PROMISE(shared_buffer);
  2946. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2947. return -EINVAL;
  2948. LOCKER(shared_buffers().lock());
  2949. auto it = shared_buffers().resource().find(shared_buffer_id);
  2950. if (it == shared_buffers().resource().end())
  2951. return -EINVAL;
  2952. auto& shared_buffer = *(*it).value;
  2953. if (!shared_buffer.is_shared_with(m_pid))
  2954. return -EPERM;
  2955. {
  2956. InterruptDisabler disabler;
  2957. auto* peer = Process::from_pid(peer_pid);
  2958. if (!peer)
  2959. return -ESRCH;
  2960. }
  2961. shared_buffer.share_with(peer_pid);
  2962. return 0;
  2963. }
  2964. int Process::sys$share_buffer_globally(int shared_buffer_id)
  2965. {
  2966. REQUIRE_PROMISE(shared_buffer);
  2967. LOCKER(shared_buffers().lock());
  2968. auto it = shared_buffers().resource().find(shared_buffer_id);
  2969. if (it == shared_buffers().resource().end())
  2970. return -EINVAL;
  2971. auto& shared_buffer = *(*it).value;
  2972. if (!shared_buffer.is_shared_with(m_pid))
  2973. return -EPERM;
  2974. shared_buffer.share_globally();
  2975. return 0;
  2976. }
  2977. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2978. {
  2979. REQUIRE_PROMISE(shared_buffer);
  2980. LOCKER(shared_buffers().lock());
  2981. auto it = shared_buffers().resource().find(shared_buffer_id);
  2982. if (it == shared_buffers().resource().end())
  2983. return -EINVAL;
  2984. auto& shared_buffer = *(*it).value;
  2985. if (!shared_buffer.is_shared_with(m_pid))
  2986. return -EPERM;
  2987. #ifdef SHARED_BUFFER_DEBUG
  2988. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2989. #endif
  2990. shared_buffer.deref_for_process(*this);
  2991. return 0;
  2992. }
  2993. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2994. {
  2995. REQUIRE_PROMISE(shared_buffer);
  2996. LOCKER(shared_buffers().lock());
  2997. auto it = shared_buffers().resource().find(shared_buffer_id);
  2998. if (it == shared_buffers().resource().end())
  2999. return (void*)-EINVAL;
  3000. auto& shared_buffer = *(*it).value;
  3001. if (!shared_buffer.is_shared_with(m_pid))
  3002. return (void*)-EPERM;
  3003. #ifdef SHARED_BUFFER_DEBUG
  3004. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  3005. #endif
  3006. return shared_buffer.ref_for_process_and_get_address(*this);
  3007. }
  3008. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  3009. {
  3010. REQUIRE_PROMISE(shared_buffer);
  3011. LOCKER(shared_buffers().lock());
  3012. auto it = shared_buffers().resource().find(shared_buffer_id);
  3013. if (it == shared_buffers().resource().end())
  3014. return -EINVAL;
  3015. auto& shared_buffer = *(*it).value;
  3016. if (!shared_buffer.is_shared_with(m_pid))
  3017. return -EPERM;
  3018. #ifdef SHARED_BUFFER_DEBUG
  3019. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  3020. #endif
  3021. shared_buffer.seal();
  3022. return 0;
  3023. }
  3024. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  3025. {
  3026. REQUIRE_PROMISE(shared_buffer);
  3027. LOCKER(shared_buffers().lock());
  3028. auto it = shared_buffers().resource().find(shared_buffer_id);
  3029. if (it == shared_buffers().resource().end())
  3030. return -EINVAL;
  3031. auto& shared_buffer = *(*it).value;
  3032. if (!shared_buffer.is_shared_with(m_pid))
  3033. return -EPERM;
  3034. #ifdef SHARED_BUFFER_DEBUG
  3035. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  3036. #endif
  3037. return shared_buffer.size();
  3038. }
  3039. int Process::sys$set_shared_buffer_volatile(int shared_buffer_id, bool state)
  3040. {
  3041. REQUIRE_PROMISE(shared_buffer);
  3042. LOCKER(shared_buffers().lock());
  3043. auto it = shared_buffers().resource().find(shared_buffer_id);
  3044. if (it == shared_buffers().resource().end())
  3045. return -EINVAL;
  3046. auto& shared_buffer = *(*it).value;
  3047. if (!shared_buffer.is_shared_with(m_pid))
  3048. return -EPERM;
  3049. #ifdef SHARED_BUFFER_DEBUG
  3050. kprintf("%s(%u): Set shared buffer %d volatile: %u\n", name().characters(), pid(), shared_buffer_id, state);
  3051. #endif
  3052. if (!state) {
  3053. bool was_purged = shared_buffer.vmobject().was_purged();
  3054. shared_buffer.vmobject().set_volatile(state);
  3055. shared_buffer.vmobject().set_was_purged(false);
  3056. return was_purged ? 1 : 0;
  3057. }
  3058. shared_buffer.vmobject().set_volatile(true);
  3059. return 0;
  3060. }
  3061. void Process::terminate_due_to_signal(u8 signal)
  3062. {
  3063. ASSERT_INTERRUPTS_DISABLED();
  3064. ASSERT(signal < 32);
  3065. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  3066. m_termination_status = 0;
  3067. m_termination_signal = signal;
  3068. die();
  3069. }
  3070. void Process::send_signal(u8 signal, Process* sender)
  3071. {
  3072. InterruptDisabler disabler;
  3073. auto* thread = Thread::from_tid(m_pid);
  3074. if (!thread)
  3075. thread = &any_thread();
  3076. thread->send_signal(signal, sender);
  3077. }
  3078. int Process::sys$create_thread(void* (*entry)(void*), void* argument, const Syscall::SC_create_thread_params* user_params)
  3079. {
  3080. REQUIRE_PROMISE(thread);
  3081. if (!validate_read((const void*)entry, sizeof(void*)))
  3082. return -EFAULT;
  3083. Syscall::SC_create_thread_params params;
  3084. if (!validate_read_and_copy_typed(&params, user_params))
  3085. return -EFAULT;
  3086. unsigned detach_state = params.m_detach_state;
  3087. int schedule_priority = params.m_schedule_priority;
  3088. void* stack_location = params.m_stack_location;
  3089. unsigned stack_size = params.m_stack_size;
  3090. if (!validate_write(stack_location, stack_size))
  3091. return -EFAULT;
  3092. u32 user_stack_address = reinterpret_cast<u32>(stack_location) + stack_size;
  3093. if (!MM.validate_user_stack(*this, VirtualAddress(user_stack_address - 4)))
  3094. return -EFAULT;
  3095. // FIXME: return EAGAIN if Thread::all_threads().size() is greater than PTHREAD_THREADS_MAX
  3096. int requested_thread_priority = schedule_priority;
  3097. if (requested_thread_priority < THREAD_PRIORITY_MIN || requested_thread_priority > THREAD_PRIORITY_MAX)
  3098. return -EINVAL;
  3099. bool is_thread_joinable = (0 == detach_state);
  3100. // FIXME: Do something with guard pages?
  3101. auto* thread = new Thread(*this);
  3102. // We know this thread is not the main_thread,
  3103. // So give it a unique name until the user calls $set_thread_name on it
  3104. // length + 4 to give space for our extra junk at the end
  3105. StringBuilder builder(m_name.length() + 4);
  3106. builder.append(m_name);
  3107. builder.appendf("[%d]", thread->tid());
  3108. thread->set_name(builder.to_string());
  3109. thread->set_priority(requested_thread_priority);
  3110. thread->set_joinable(is_thread_joinable);
  3111. auto& tss = thread->tss();
  3112. tss.eip = (u32)entry;
  3113. tss.eflags = 0x0202;
  3114. tss.cr3 = page_directory().cr3();
  3115. tss.esp = user_stack_address;
  3116. // NOTE: The stack needs to be 16-byte aligned.
  3117. thread->push_value_on_stack((u32)argument);
  3118. thread->push_value_on_stack(0);
  3119. thread->make_thread_specific_region({});
  3120. thread->set_state(Thread::State::Runnable);
  3121. return thread->tid();
  3122. }
  3123. void Process::sys$exit_thread(void* exit_value)
  3124. {
  3125. REQUIRE_PROMISE(thread);
  3126. cli();
  3127. current->m_exit_value = exit_value;
  3128. current->set_should_die();
  3129. big_lock().force_unlock_if_locked();
  3130. current->die_if_needed();
  3131. ASSERT_NOT_REACHED();
  3132. }
  3133. int Process::sys$detach_thread(int tid)
  3134. {
  3135. REQUIRE_PROMISE(thread);
  3136. auto* thread = Thread::from_tid(tid);
  3137. if (!thread || thread->pid() != pid())
  3138. return -ESRCH;
  3139. if (!thread->is_joinable())
  3140. return -EINVAL;
  3141. thread->set_joinable(false);
  3142. return 0;
  3143. }
  3144. int Process::sys$join_thread(int tid, void** exit_value)
  3145. {
  3146. REQUIRE_PROMISE(thread);
  3147. if (exit_value && !validate_write_typed(exit_value))
  3148. return -EFAULT;
  3149. auto* thread = Thread::from_tid(tid);
  3150. if (!thread || thread->pid() != pid())
  3151. return -ESRCH;
  3152. if (thread == current)
  3153. return -EDEADLK;
  3154. if (thread->m_joinee == current)
  3155. return -EDEADLK;
  3156. ASSERT(thread->m_joiner != current);
  3157. if (thread->m_joiner)
  3158. return -EINVAL;
  3159. if (!thread->is_joinable())
  3160. return -EINVAL;
  3161. void* joinee_exit_value = nullptr;
  3162. // NOTE: pthread_join() cannot be interrupted by signals. Only by death.
  3163. for (;;) {
  3164. auto result = current->block<Thread::JoinBlocker>(*thread, joinee_exit_value);
  3165. if (result == Thread::BlockResult::InterruptedByDeath) {
  3166. // NOTE: This cleans things up so that Thread::finalize() won't
  3167. // get confused about a missing joiner when finalizing the joinee.
  3168. InterruptDisabler disabler;
  3169. current->m_joinee->m_joiner = nullptr;
  3170. current->m_joinee = nullptr;
  3171. return 0;
  3172. }
  3173. }
  3174. // NOTE: 'thread' is very possibly deleted at this point. Clear it just to be safe.
  3175. thread = nullptr;
  3176. if (exit_value)
  3177. copy_to_user(exit_value, &joinee_exit_value, sizeof(joinee_exit_value));
  3178. return 0;
  3179. }
  3180. int Process::sys$set_thread_name(int tid, const char* user_name, size_t user_name_length)
  3181. {
  3182. REQUIRE_PROMISE(thread);
  3183. auto name = validate_and_copy_string_from_user(user_name, user_name_length);
  3184. if (name.is_null())
  3185. return -EFAULT;
  3186. const size_t max_thread_name_size = 64;
  3187. if (name.length() > max_thread_name_size)
  3188. return -EINVAL;
  3189. auto* thread = Thread::from_tid(tid);
  3190. if (!thread || thread->pid() != pid())
  3191. return -ESRCH;
  3192. thread->set_name(name);
  3193. return 0;
  3194. }
  3195. int Process::sys$get_thread_name(int tid, char* buffer, size_t buffer_size)
  3196. {
  3197. REQUIRE_PROMISE(thread);
  3198. if (buffer_size == 0)
  3199. return -EINVAL;
  3200. if (!validate_write(buffer, buffer_size))
  3201. return -EFAULT;
  3202. auto* thread = Thread::from_tid(tid);
  3203. if (!thread || thread->pid() != pid())
  3204. return -ESRCH;
  3205. if (thread->name().length() + 1 > (size_t)buffer_size)
  3206. return -ENAMETOOLONG;
  3207. copy_to_user(buffer, thread->name().characters(), thread->name().length() + 1);
  3208. return 0;
  3209. }
  3210. int Process::sys$gettid()
  3211. {
  3212. REQUIRE_PROMISE(stdio);
  3213. return current->tid();
  3214. }
  3215. int Process::sys$donate(int tid)
  3216. {
  3217. REQUIRE_PROMISE(stdio);
  3218. if (tid < 0)
  3219. return -EINVAL;
  3220. InterruptDisabler disabler;
  3221. auto* thread = Thread::from_tid(tid);
  3222. if (!thread || thread->pid() != pid())
  3223. return -ESRCH;
  3224. Scheduler::donate_to(thread, "sys$donate");
  3225. return 0;
  3226. }
  3227. int Process::sys$rename(const Syscall::SC_rename_params* user_params)
  3228. {
  3229. REQUIRE_PROMISE(cpath);
  3230. Syscall::SC_rename_params params;
  3231. if (!validate_read_and_copy_typed(&params, user_params))
  3232. return -EFAULT;
  3233. auto old_path = get_syscall_path_argument(params.old_path);
  3234. if (old_path.is_error())
  3235. return old_path.error();
  3236. auto new_path = get_syscall_path_argument(params.new_path);
  3237. if (new_path.is_error())
  3238. return new_path.error();
  3239. return VFS::the().rename(old_path.value(), new_path.value(), current_directory());
  3240. }
  3241. int Process::sys$ftruncate(int fd, off_t length)
  3242. {
  3243. REQUIRE_PROMISE(stdio);
  3244. if (length < 0)
  3245. return -EINVAL;
  3246. auto description = file_description(fd);
  3247. if (!description)
  3248. return -EBADF;
  3249. if (!description->is_writable())
  3250. return -EBADF;
  3251. return description->truncate(length);
  3252. }
  3253. int Process::sys$watch_file(const char* user_path, size_t path_length)
  3254. {
  3255. REQUIRE_PROMISE(rpath);
  3256. auto path = get_syscall_path_argument(user_path, path_length);
  3257. if (path.is_error())
  3258. return path.error();
  3259. auto custody_or_error = VFS::the().resolve_path(path.value(), current_directory());
  3260. if (custody_or_error.is_error())
  3261. return custody_or_error.error();
  3262. auto& custody = custody_or_error.value();
  3263. auto& inode = custody->inode();
  3264. if (!inode.fs().supports_watchers())
  3265. return -ENOTSUP;
  3266. int fd = alloc_fd();
  3267. if (fd < 0)
  3268. return fd;
  3269. m_fds[fd].set(FileDescription::create(*InodeWatcher::create(inode)));
  3270. m_fds[fd].description->set_readable(true);
  3271. return fd;
  3272. }
  3273. int Process::sys$systrace(pid_t pid)
  3274. {
  3275. REQUIRE_PROMISE(proc);
  3276. InterruptDisabler disabler;
  3277. auto* peer = Process::from_pid(pid);
  3278. if (!peer)
  3279. return -ESRCH;
  3280. if (peer->uid() != m_euid)
  3281. return -EACCES;
  3282. int fd = alloc_fd();
  3283. if (fd < 0)
  3284. return fd;
  3285. auto description = FileDescription::create(peer->ensure_tracer());
  3286. description->set_readable(true);
  3287. m_fds[fd].set(move(description), 0);
  3288. return fd;
  3289. }
  3290. int Process::sys$halt()
  3291. {
  3292. if (!is_superuser())
  3293. return -EPERM;
  3294. REQUIRE_NO_PROMISES;
  3295. dbgprintf("acquiring FS locks...\n");
  3296. FS::lock_all();
  3297. dbgprintf("syncing mounted filesystems...\n");
  3298. FS::sync();
  3299. dbgprintf("attempting system shutdown...\n");
  3300. IO::out16(0x604, 0x2000);
  3301. return ESUCCESS;
  3302. }
  3303. int Process::sys$reboot()
  3304. {
  3305. if (!is_superuser())
  3306. return -EPERM;
  3307. REQUIRE_NO_PROMISES;
  3308. dbgprintf("acquiring FS locks...\n");
  3309. FS::lock_all();
  3310. dbgprintf("syncing mounted filesystems...\n");
  3311. FS::sync();
  3312. dbgprintf("attempting reboot via KB Controller...\n");
  3313. IO::out8(0x64, 0xFE);
  3314. return ESUCCESS;
  3315. }
  3316. int Process::sys$mount(const Syscall::SC_mount_params* user_params)
  3317. {
  3318. if (!is_superuser())
  3319. return -EPERM;
  3320. REQUIRE_NO_PROMISES;
  3321. Syscall::SC_mount_params params;
  3322. if (!validate_read_and_copy_typed(&params, user_params))
  3323. return -EFAULT;
  3324. auto source = validate_and_copy_string_from_user(params.source);
  3325. auto target = validate_and_copy_string_from_user(params.target);
  3326. auto fs_type = validate_and_copy_string_from_user(params.fs_type);
  3327. if (source.is_null() || target.is_null() || fs_type.is_null())
  3328. return -EFAULT;
  3329. dbg() << "mount " << fs_type << ": source " << source << " @ " << target;
  3330. auto custody_or_error = VFS::the().resolve_path(target, current_directory());
  3331. if (custody_or_error.is_error())
  3332. return custody_or_error.error();
  3333. auto& target_custody = custody_or_error.value();
  3334. RefPtr<FS> fs;
  3335. if (params.flags & MS_BIND) {
  3336. // We're doing a bind mount.
  3337. auto source_or_error = VFS::the().resolve_path(source, current_directory());
  3338. if (source_or_error.is_error())
  3339. return source_or_error.error();
  3340. auto& source_custody = source_or_error.value();
  3341. return VFS::the().bind_mount(source_custody, target_custody, params.flags);
  3342. }
  3343. if (fs_type == "ext2" || fs_type == "Ext2FS") {
  3344. auto source_or_error = VFS::the().open(source, O_RDWR, 0, current_directory());
  3345. if (source_or_error.is_error())
  3346. return source_or_error.error();
  3347. auto* device = source_or_error.value()->device();
  3348. if (!device || !device->is_disk_device()) {
  3349. dbg() << "mount: this is not a DiskDevice";
  3350. return -ENODEV;
  3351. }
  3352. auto& disk_device = static_cast<DiskDevice&>(*device);
  3353. dbg() << "mount: attempting to mount " << disk_device.absolute_path() << " on " << target;
  3354. fs = Ext2FS::create(disk_device);
  3355. } else if (fs_type == "proc" || fs_type == "ProcFS") {
  3356. fs = ProcFS::create();
  3357. } else if (fs_type == "devpts" || fs_type == "DevPtsFS") {
  3358. fs = DevPtsFS::create();
  3359. } else if (fs_type == "tmp" || fs_type == "TmpFS") {
  3360. fs = TmpFS::create();
  3361. } else {
  3362. return -ENODEV;
  3363. }
  3364. if (!fs->initialize()) {
  3365. dbg() << "mount: failed to initialize " << fs_type << " filesystem on " << source;
  3366. return -ENODEV;
  3367. }
  3368. auto result = VFS::the().mount(fs.release_nonnull(), target_custody, params.flags);
  3369. dbg() << "mount: successfully mounted " << source << " on " << target;
  3370. return result;
  3371. }
  3372. int Process::sys$umount(const char* user_mountpoint, size_t mountpoint_length)
  3373. {
  3374. if (!is_superuser())
  3375. return -EPERM;
  3376. REQUIRE_NO_PROMISES;
  3377. if (!validate_read(user_mountpoint, mountpoint_length))
  3378. return -EFAULT;
  3379. auto mountpoint = get_syscall_path_argument(user_mountpoint, mountpoint_length);
  3380. if (mountpoint.is_error())
  3381. return mountpoint.error();
  3382. auto metadata_or_error = VFS::the().lookup_metadata(mountpoint.value(), current_directory());
  3383. if (metadata_or_error.is_error())
  3384. return metadata_or_error.error();
  3385. auto guest_inode_id = metadata_or_error.value().inode;
  3386. return VFS::the().unmount(guest_inode_id);
  3387. }
  3388. ProcessTracer& Process::ensure_tracer()
  3389. {
  3390. if (!m_tracer)
  3391. m_tracer = ProcessTracer::create(m_pid);
  3392. return *m_tracer;
  3393. }
  3394. void Process::FileDescriptionAndFlags::clear()
  3395. {
  3396. description = nullptr;
  3397. flags = 0;
  3398. }
  3399. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& d, u32 f)
  3400. {
  3401. description = move(d);
  3402. flags = f;
  3403. }
  3404. int Process::sys$mknod(const Syscall::SC_mknod_params* user_params)
  3405. {
  3406. REQUIRE_PROMISE(dpath);
  3407. Syscall::SC_mknod_params params;
  3408. if (!validate_read_and_copy_typed(&params, user_params))
  3409. return -EFAULT;
  3410. if (!is_superuser() && !is_regular_file(params.mode) && !is_fifo(params.mode) && !is_socket(params.mode))
  3411. return -EPERM;
  3412. auto path = get_syscall_path_argument(params.path);
  3413. if (path.is_error())
  3414. return path.error();
  3415. return VFS::the().mknod(path.value(), params.mode & ~umask(), params.dev, current_directory());
  3416. }
  3417. int Process::sys$dump_backtrace()
  3418. {
  3419. dump_backtrace();
  3420. return 0;
  3421. }
  3422. int Process::sys$dbgputch(u8 ch)
  3423. {
  3424. IO::out8(0xe9, ch);
  3425. return 0;
  3426. }
  3427. int Process::sys$dbgputstr(const u8* characters, int length)
  3428. {
  3429. if (!length)
  3430. return 0;
  3431. if (!validate_read(characters, length))
  3432. return -EFAULT;
  3433. SmapDisabler disabler;
  3434. for (int i = 0; i < length; ++i)
  3435. IO::out8(0xe9, characters[i]);
  3436. return 0;
  3437. }
  3438. KBuffer Process::backtrace(ProcessInspectionHandle& handle) const
  3439. {
  3440. KBufferBuilder builder;
  3441. for_each_thread([&](Thread& thread) {
  3442. builder.appendf("Thread %d (%s):\n", thread.tid(), thread.name().characters());
  3443. builder.append(thread.backtrace(handle));
  3444. return IterationDecision::Continue;
  3445. });
  3446. return builder.build();
  3447. }
  3448. int Process::sys$set_process_icon(int icon_id)
  3449. {
  3450. REQUIRE_PROMISE(shared_buffer);
  3451. LOCKER(shared_buffers().lock());
  3452. auto it = shared_buffers().resource().find(icon_id);
  3453. if (it == shared_buffers().resource().end())
  3454. return -EINVAL;
  3455. auto& shared_buffer = *(*it).value;
  3456. if (!shared_buffer.is_shared_with(m_pid))
  3457. return -EPERM;
  3458. m_icon_id = icon_id;
  3459. return 0;
  3460. }
  3461. int Process::sys$get_process_name(char* buffer, int buffer_size)
  3462. {
  3463. REQUIRE_PROMISE(stdio);
  3464. if (buffer_size <= 0)
  3465. return -EINVAL;
  3466. if (!validate_write(buffer, buffer_size))
  3467. return -EFAULT;
  3468. if (m_name.length() + 1 > (size_t)buffer_size)
  3469. return -ENAMETOOLONG;
  3470. copy_to_user(buffer, m_name.characters(), m_name.length() + 1);
  3471. return 0;
  3472. }
  3473. // We don't use the flag yet, but we could use it for distinguishing
  3474. // random source like Linux, unlike the OpenBSD equivalent. However, if we
  3475. // do, we should be able of the caveats that Linux has dealt with.
  3476. int Process::sys$getrandom(void* buffer, size_t buffer_size, unsigned int flags __attribute__((unused)))
  3477. {
  3478. REQUIRE_PROMISE(stdio);
  3479. if (buffer_size <= 0)
  3480. return -EINVAL;
  3481. if (!validate_write(buffer, buffer_size))
  3482. return -EFAULT;
  3483. SmapDisabler disabler;
  3484. get_good_random_bytes((u8*)buffer, buffer_size);
  3485. return 0;
  3486. }
  3487. int Process::sys$setkeymap(const Syscall::SC_setkeymap_params* user_params)
  3488. {
  3489. if (!is_superuser())
  3490. return -EPERM;
  3491. REQUIRE_NO_PROMISES;
  3492. Syscall::SC_setkeymap_params params;
  3493. if (!validate_read_and_copy_typed(&params, user_params))
  3494. return -EFAULT;
  3495. const char* map = params.map;
  3496. const char* shift_map = params.shift_map;
  3497. const char* alt_map = params.alt_map;
  3498. const char* altgr_map = params.altgr_map;
  3499. if (!validate_read(map, 0x80))
  3500. return -EFAULT;
  3501. if (!validate_read(shift_map, 0x80))
  3502. return -EFAULT;
  3503. if (!validate_read(alt_map, 0x80))
  3504. return -EFAULT;
  3505. if (!validate_read(altgr_map, 0x80))
  3506. return -EFAULT;
  3507. SmapDisabler disabler;
  3508. KeyboardDevice::the().set_maps(map, shift_map, alt_map, altgr_map);
  3509. return 0;
  3510. }
  3511. int Process::sys$clock_gettime(clockid_t clock_id, timespec* ts)
  3512. {
  3513. REQUIRE_PROMISE(stdio);
  3514. if (!validate_write_typed(ts))
  3515. return -EFAULT;
  3516. SmapDisabler disabler;
  3517. switch (clock_id) {
  3518. case CLOCK_MONOTONIC:
  3519. ts->tv_sec = g_uptime / TICKS_PER_SECOND;
  3520. ts->tv_nsec = (g_uptime % TICKS_PER_SECOND) * 1000000;
  3521. break;
  3522. default:
  3523. return -EINVAL;
  3524. }
  3525. return 0;
  3526. }
  3527. int Process::sys$clock_nanosleep(const Syscall::SC_clock_nanosleep_params* user_params)
  3528. {
  3529. REQUIRE_PROMISE(stdio);
  3530. Syscall::SC_clock_nanosleep_params params;
  3531. if (!validate_read_and_copy_typed(&params, user_params))
  3532. return -EFAULT;
  3533. if (params.requested_sleep && !validate_read_typed(params.requested_sleep))
  3534. return -EFAULT;
  3535. timespec requested_sleep;
  3536. copy_from_user(&requested_sleep, params.requested_sleep);
  3537. if (params.remaining_sleep && !validate_write_typed(params.remaining_sleep))
  3538. return -EFAULT;
  3539. bool is_absolute = params.flags & TIMER_ABSTIME;
  3540. switch (params.clock_id) {
  3541. case CLOCK_MONOTONIC: {
  3542. u64 wakeup_time;
  3543. if (is_absolute) {
  3544. u64 time_to_wake = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
  3545. wakeup_time = current->sleep_until(time_to_wake);
  3546. } else {
  3547. u32 ticks_to_sleep = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
  3548. if (!ticks_to_sleep)
  3549. return 0;
  3550. wakeup_time = current->sleep(ticks_to_sleep);
  3551. }
  3552. if (wakeup_time > g_uptime) {
  3553. u32 ticks_left = wakeup_time - g_uptime;
  3554. if (!is_absolute && params.remaining_sleep) {
  3555. timespec remaining_sleep;
  3556. memset(&remaining_sleep, 0, sizeof(timespec));
  3557. remaining_sleep.tv_sec = ticks_left / TICKS_PER_SECOND;
  3558. ticks_left -= remaining_sleep.tv_sec * TICKS_PER_SECOND;
  3559. remaining_sleep.tv_nsec = ticks_left * 1000000;
  3560. copy_to_user(params.remaining_sleep, &remaining_sleep);
  3561. }
  3562. return -EINTR;
  3563. }
  3564. return 0;
  3565. }
  3566. default:
  3567. return -EINVAL;
  3568. }
  3569. }
  3570. int Process::sys$sync()
  3571. {
  3572. REQUIRE_PROMISE(stdio);
  3573. VFS::the().sync();
  3574. return 0;
  3575. }
  3576. int Process::sys$yield()
  3577. {
  3578. REQUIRE_PROMISE(stdio);
  3579. current->yield_without_holding_big_lock();
  3580. return 0;
  3581. }
  3582. int Process::sys$beep()
  3583. {
  3584. PCSpeaker::tone_on(440);
  3585. u64 wakeup_time = current->sleep(100);
  3586. PCSpeaker::tone_off();
  3587. if (wakeup_time > g_uptime)
  3588. return -EINTR;
  3589. return 0;
  3590. }
  3591. int Process::sys$module_load(const char* user_path, size_t path_length)
  3592. {
  3593. if (!is_superuser())
  3594. return -EPERM;
  3595. REQUIRE_NO_PROMISES;
  3596. auto path = get_syscall_path_argument(user_path, path_length);
  3597. if (path.is_error())
  3598. return path.error();
  3599. auto description_or_error = VFS::the().open(path.value(), 0, 0, current_directory());
  3600. if (description_or_error.is_error())
  3601. return description_or_error.error();
  3602. auto& description = description_or_error.value();
  3603. auto payload = description->read_entire_file();
  3604. auto storage = KBuffer::create_with_size(payload.size());
  3605. memcpy(storage.data(), payload.data(), payload.size());
  3606. payload.clear();
  3607. auto elf_image = make<ELFImage>(storage.data(), storage.size());
  3608. if (!elf_image->parse())
  3609. return -ENOEXEC;
  3610. HashMap<String, u8*> section_storage_by_name;
  3611. auto module = make<Module>();
  3612. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) {
  3613. auto section_storage = KBuffer::copy(section.raw_data(), section.size(), Region::Access::Read | Region::Access::Write | Region::Access::Execute);
  3614. section_storage_by_name.set(section.name(), section_storage.data());
  3615. module->sections.append(move(section_storage));
  3616. return IterationDecision::Continue;
  3617. });
  3618. bool missing_symbols = false;
  3619. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) {
  3620. auto* section_storage = section_storage_by_name.get(section.name()).value_or(nullptr);
  3621. ASSERT(section_storage);
  3622. section.relocations().for_each_relocation([&](const ELFImage::Relocation& relocation) {
  3623. auto& patch_ptr = *reinterpret_cast<ptrdiff_t*>(section_storage + relocation.offset());
  3624. switch (relocation.type()) {
  3625. case R_386_PC32: {
  3626. // PC-relative relocation
  3627. dbg() << "PC-relative relocation: " << relocation.symbol().name();
  3628. u32 symbol_address = address_for_kernel_symbol(relocation.symbol().name());
  3629. if (symbol_address == 0)
  3630. missing_symbols = true;
  3631. dbg() << " Symbol address: " << (void*)symbol_address;
  3632. ptrdiff_t relative_offset = (char*)symbol_address - ((char*)&patch_ptr + 4);
  3633. patch_ptr = relative_offset;
  3634. break;
  3635. }
  3636. case R_386_32: // Absolute relocation
  3637. dbg() << "Absolute relocation: '" << relocation.symbol().name() << "' value:" << relocation.symbol().value() << ", index:" << relocation.symbol_index();
  3638. if (relocation.symbol().bind() == STB_LOCAL) {
  3639. auto* section_storage_containing_symbol = section_storage_by_name.get(relocation.symbol().section().name()).value_or(nullptr);
  3640. ASSERT(section_storage_containing_symbol);
  3641. u32 symbol_address = (ptrdiff_t)(section_storage_containing_symbol + relocation.symbol().value());
  3642. if (symbol_address == 0)
  3643. missing_symbols = true;
  3644. dbg() << " Symbol address: " << (void*)symbol_address;
  3645. patch_ptr += symbol_address;
  3646. } else if (relocation.symbol().bind() == STB_GLOBAL) {
  3647. u32 symbol_address = address_for_kernel_symbol(relocation.symbol().name());
  3648. if (symbol_address == 0)
  3649. missing_symbols = true;
  3650. dbg() << " Symbol address: " << (void*)symbol_address;
  3651. patch_ptr += symbol_address;
  3652. } else {
  3653. ASSERT_NOT_REACHED();
  3654. }
  3655. break;
  3656. }
  3657. return IterationDecision::Continue;
  3658. });
  3659. return IterationDecision::Continue;
  3660. });
  3661. if (missing_symbols)
  3662. return -ENOENT;
  3663. auto* text_base = section_storage_by_name.get(".text").value_or(nullptr);
  3664. if (!text_base) {
  3665. dbg() << "No .text section found in module!";
  3666. return -EINVAL;
  3667. }
  3668. elf_image->for_each_symbol([&](const ELFImage::Symbol& symbol) {
  3669. dbg() << " - " << symbol.type() << " '" << symbol.name() << "' @ " << (void*)symbol.value() << ", size=" << symbol.size();
  3670. if (symbol.name() == "module_init") {
  3671. module->module_init = (ModuleInitPtr)(text_base + symbol.value());
  3672. } else if (symbol.name() == "module_fini") {
  3673. module->module_fini = (ModuleFiniPtr)(text_base + symbol.value());
  3674. } else if (symbol.name() == "module_name") {
  3675. const u8* storage = section_storage_by_name.get(symbol.section().name()).value_or(nullptr);
  3676. if (storage)
  3677. module->name = String((const char*)(storage + symbol.value()));
  3678. }
  3679. return IterationDecision::Continue;
  3680. });
  3681. if (!module->module_init)
  3682. return -EINVAL;
  3683. if (g_modules->contains(module->name)) {
  3684. dbg() << "a module with the name " << module->name << " is already loaded; please unload it first";
  3685. return -EEXIST;
  3686. }
  3687. module->module_init();
  3688. auto name = module->name;
  3689. g_modules->set(name, move(module));
  3690. return 0;
  3691. }
  3692. int Process::sys$module_unload(const char* user_name, size_t name_length)
  3693. {
  3694. if (!is_superuser())
  3695. return -EPERM;
  3696. REQUIRE_NO_PROMISES;
  3697. auto module_name = validate_and_copy_string_from_user(user_name, name_length);
  3698. if (module_name.is_null())
  3699. return -EFAULT;
  3700. auto it = g_modules->find(module_name);
  3701. if (it == g_modules->end())
  3702. return -ENOENT;
  3703. if (it->value->module_fini)
  3704. it->value->module_fini();
  3705. g_modules->remove(it);
  3706. return 0;
  3707. }
  3708. int Process::sys$profiling_enable(pid_t pid)
  3709. {
  3710. REQUIRE_NO_PROMISES;
  3711. InterruptDisabler disabler;
  3712. auto* process = Process::from_pid(pid);
  3713. if (!process)
  3714. return -ESRCH;
  3715. if (!is_superuser() && process->uid() != m_uid)
  3716. return -EPERM;
  3717. Profiling::start(*process);
  3718. process->set_profiling(true);
  3719. return 0;
  3720. }
  3721. int Process::sys$profiling_disable(pid_t pid)
  3722. {
  3723. InterruptDisabler disabler;
  3724. auto* process = Process::from_pid(pid);
  3725. if (!process)
  3726. return -ESRCH;
  3727. if (!is_superuser() && process->uid() != m_uid)
  3728. return -EPERM;
  3729. process->set_profiling(false);
  3730. Profiling::stop();
  3731. return 0;
  3732. }
  3733. void* Process::sys$get_kernel_info_page()
  3734. {
  3735. REQUIRE_PROMISE(stdio);
  3736. return s_info_page_address_for_userspace.as_ptr();
  3737. }
  3738. Thread& Process::any_thread()
  3739. {
  3740. Thread* found_thread = nullptr;
  3741. for_each_thread([&](auto& thread) {
  3742. found_thread = &thread;
  3743. return IterationDecision::Break;
  3744. });
  3745. ASSERT(found_thread);
  3746. return *found_thread;
  3747. }
  3748. WaitQueue& Process::futex_queue(i32* userspace_address)
  3749. {
  3750. auto& queue = m_futex_queues.ensure((u32)userspace_address);
  3751. if (!queue)
  3752. queue = make<WaitQueue>();
  3753. return *queue;
  3754. }
  3755. int Process::sys$futex(const Syscall::SC_futex_params* user_params)
  3756. {
  3757. REQUIRE_PROMISE(thread);
  3758. Syscall::SC_futex_params params;
  3759. if (!validate_read_and_copy_typed(&params, user_params))
  3760. return -EFAULT;
  3761. i32* userspace_address = params.userspace_address;
  3762. int futex_op = params.futex_op;
  3763. i32 value = params.val;
  3764. const timespec* user_timeout = params.timeout;
  3765. if (!validate_read_typed(userspace_address))
  3766. return -EFAULT;
  3767. if (user_timeout && !validate_read_typed(user_timeout))
  3768. return -EFAULT;
  3769. timespec timeout { 0, 0 };
  3770. if (user_timeout)
  3771. copy_from_user(&timeout, user_timeout);
  3772. i32 user_value;
  3773. switch (futex_op) {
  3774. case FUTEX_WAIT:
  3775. copy_from_user(&user_value, userspace_address);
  3776. if (user_value != value)
  3777. return -EAGAIN;
  3778. // FIXME: This is supposed to be interruptible by a signal, but right now WaitQueue cannot be interrupted.
  3779. // FIXME: Support timeout!
  3780. current->wait_on(futex_queue(userspace_address));
  3781. break;
  3782. case FUTEX_WAKE:
  3783. if (value == 0)
  3784. return 0;
  3785. if (value == 1) {
  3786. futex_queue(userspace_address).wake_one();
  3787. } else {
  3788. // FIXME: Wake exactly (value) waiters.
  3789. futex_queue(userspace_address).wake_all();
  3790. }
  3791. break;
  3792. }
  3793. return 0;
  3794. }
  3795. int Process::sys$set_thread_boost(int tid, int amount)
  3796. {
  3797. REQUIRE_PROMISE(proc);
  3798. if (amount < 0 || amount > 20)
  3799. return -EINVAL;
  3800. InterruptDisabler disabler;
  3801. auto* thread = Thread::from_tid(tid);
  3802. if (!thread)
  3803. return -ESRCH;
  3804. if (thread->state() == Thread::State::Dead || thread->state() == Thread::State::Dying)
  3805. return -ESRCH;
  3806. if (!is_superuser() && thread->process().uid() != euid())
  3807. return -EPERM;
  3808. thread->set_priority_boost(amount);
  3809. return 0;
  3810. }
  3811. int Process::sys$set_process_boost(pid_t pid, int amount)
  3812. {
  3813. REQUIRE_PROMISE(proc);
  3814. if (amount < 0 || amount > 20)
  3815. return -EINVAL;
  3816. InterruptDisabler disabler;
  3817. auto* process = Process::from_pid(pid);
  3818. if (!process || process->is_dead())
  3819. return -ESRCH;
  3820. if (!is_superuser() && process->uid() != euid())
  3821. return -EPERM;
  3822. process->m_priority_boost = amount;
  3823. return 0;
  3824. }
  3825. int Process::sys$chroot(const char* user_path, size_t path_length, int mount_flags)
  3826. {
  3827. if (!is_superuser())
  3828. return -EPERM;
  3829. REQUIRE_PROMISE(chroot);
  3830. auto path = get_syscall_path_argument(user_path, path_length);
  3831. if (path.is_error())
  3832. return path.error();
  3833. auto directory_or_error = VFS::the().open_directory(path.value(), current_directory());
  3834. if (directory_or_error.is_error())
  3835. return directory_or_error.error();
  3836. auto directory = directory_or_error.value();
  3837. m_root_directory_relative_to_global_root = directory;
  3838. int chroot_mount_flags = mount_flags == -1 ? directory->mount_flags() : mount_flags;
  3839. set_root_directory(Custody::create(nullptr, "", directory->inode(), chroot_mount_flags));
  3840. return 0;
  3841. }
  3842. Custody& Process::root_directory()
  3843. {
  3844. if (!m_root_directory)
  3845. m_root_directory = VFS::the().root_custody();
  3846. return *m_root_directory;
  3847. }
  3848. Custody& Process::root_directory_relative_to_global_root()
  3849. {
  3850. if (!m_root_directory_relative_to_global_root)
  3851. m_root_directory_relative_to_global_root = root_directory();
  3852. return *m_root_directory_relative_to_global_root;
  3853. }
  3854. void Process::set_root_directory(const Custody& root)
  3855. {
  3856. m_root_directory = root;
  3857. }
  3858. int Process::sys$pledge(const Syscall::SC_pledge_params* user_params)
  3859. {
  3860. Syscall::SC_pledge_params params;
  3861. if (!validate_read_and_copy_typed(&params, user_params))
  3862. return -EFAULT;
  3863. if (params.promises.length > 1024 || params.execpromises.length > 1024)
  3864. return -E2BIG;
  3865. String promises;
  3866. if (params.promises.characters) {
  3867. promises = validate_and_copy_string_from_user(params.promises);
  3868. if (promises.is_null())
  3869. return -EFAULT;
  3870. }
  3871. String execpromises;
  3872. if (params.execpromises.characters) {
  3873. execpromises = validate_and_copy_string_from_user(params.execpromises);
  3874. if (execpromises.is_null())
  3875. return -EFAULT;
  3876. }
  3877. auto parse_pledge = [&](auto& pledge_spec, u32& mask) {
  3878. auto parts = pledge_spec.split_view(' ');
  3879. for (auto& part : parts) {
  3880. #define __ENUMERATE_PLEDGE_PROMISE(x) \
  3881. if (part == #x) { \
  3882. mask |= (1u << (u32)Pledge::x); \
  3883. continue; \
  3884. }
  3885. ENUMERATE_PLEDGE_PROMISES
  3886. #undef __ENUMERATE_PLEDGE_PROMISE
  3887. if (part == "dns") {
  3888. // "dns" is an alias for "unix" since DNS queries go via LookupServer
  3889. mask |= (1u << (u32)Pledge::unix);
  3890. continue;
  3891. }
  3892. return false;
  3893. }
  3894. return true;
  3895. };
  3896. if (!promises.is_null()) {
  3897. u32 new_promises = 0;
  3898. if (!parse_pledge(promises, new_promises))
  3899. return -EINVAL;
  3900. if (m_promises && (!new_promises || new_promises & ~m_promises))
  3901. return -EPERM;
  3902. m_promises = new_promises;
  3903. }
  3904. if (!execpromises.is_null()) {
  3905. u32 new_execpromises = 0;
  3906. if (!parse_pledge(execpromises, new_execpromises))
  3907. return -EINVAL;
  3908. if (m_execpromises && (!new_execpromises || new_execpromises & ~m_execpromises))
  3909. return -EPERM;
  3910. m_execpromises = new_execpromises;
  3911. }
  3912. return 0;
  3913. }