Process.cpp 143 KB

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