Process.cpp 116 KB

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