Process.cpp 124 KB

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