Process.cpp 135 KB

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