Process.cpp 104 KB

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