Process.cpp 136 KB

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