Process.cpp 109 KB

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