Process.cpp 125 KB

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