Process.cpp 123 KB

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