Process.cpp 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498
  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. if (!description)
  1030. return -EBADF;
  1031. int rc = description->close();
  1032. m_fds[fd] = {};
  1033. return rc;
  1034. }
  1035. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  1036. {
  1037. if (!validate_read_str(pathname))
  1038. return -EFAULT;
  1039. if (buf && !validate_read_typed(buf))
  1040. return -EFAULT;
  1041. time_t atime;
  1042. time_t mtime;
  1043. if (buf) {
  1044. atime = buf->actime;
  1045. mtime = buf->modtime;
  1046. } else {
  1047. struct timeval now;
  1048. kgettimeofday(now);
  1049. mtime = now.tv_sec;
  1050. atime = now.tv_sec;
  1051. }
  1052. return VFS::the().utime(StringView(pathname), current_directory(), atime, mtime);
  1053. }
  1054. int Process::sys$access(const char* pathname, int mode)
  1055. {
  1056. if (!validate_read_str(pathname))
  1057. return -EFAULT;
  1058. return VFS::the().access(StringView(pathname), mode, current_directory());
  1059. }
  1060. int Process::sys$fcntl(int fd, int cmd, u32 arg)
  1061. {
  1062. (void)cmd;
  1063. (void)arg;
  1064. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1065. auto* description = file_description(fd);
  1066. if (!description)
  1067. return -EBADF;
  1068. // NOTE: The FD flags are not shared between FileDescription objects.
  1069. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1070. switch (cmd) {
  1071. case F_DUPFD: {
  1072. int arg_fd = (int)arg;
  1073. if (arg_fd < 0)
  1074. return -EINVAL;
  1075. int new_fd = alloc_fd(arg_fd);
  1076. if (new_fd < 0)
  1077. return new_fd;
  1078. m_fds[new_fd].set(*description);
  1079. break;
  1080. }
  1081. case F_GETFD:
  1082. return m_fds[fd].flags;
  1083. case F_SETFD:
  1084. m_fds[fd].flags = arg;
  1085. break;
  1086. case F_GETFL:
  1087. return description->file_flags();
  1088. case F_SETFL:
  1089. description->set_file_flags(arg);
  1090. break;
  1091. default:
  1092. ASSERT_NOT_REACHED();
  1093. }
  1094. return 0;
  1095. }
  1096. int Process::sys$fstat(int fd, stat* statbuf)
  1097. {
  1098. if (!validate_write_typed(statbuf))
  1099. return -EFAULT;
  1100. auto* description = file_description(fd);
  1101. if (!description)
  1102. return -EBADF;
  1103. return description->fstat(*statbuf);
  1104. }
  1105. int Process::sys$lstat(const char* path, stat* statbuf)
  1106. {
  1107. if (!validate_write_typed(statbuf))
  1108. return -EFAULT;
  1109. auto metadata_or_error = VFS::the().lookup_metadata(StringView(path), current_directory(), O_NOFOLLOW_NOERROR);
  1110. if (metadata_or_error.is_error())
  1111. return metadata_or_error.error();
  1112. return metadata_or_error.value().stat(*statbuf);
  1113. }
  1114. int Process::sys$stat(const char* path, stat* statbuf)
  1115. {
  1116. if (!validate_write_typed(statbuf))
  1117. return -EFAULT;
  1118. auto metadata_or_error = VFS::the().lookup_metadata(StringView(path), current_directory());
  1119. if (metadata_or_error.is_error())
  1120. return metadata_or_error.error();
  1121. return metadata_or_error.value().stat(*statbuf);
  1122. }
  1123. int Process::sys$readlink(const char* path, char* buffer, ssize_t size)
  1124. {
  1125. if (size < 0)
  1126. return -EINVAL;
  1127. if (!validate_read_str(path))
  1128. return -EFAULT;
  1129. if (!validate_write(buffer, size))
  1130. return -EFAULT;
  1131. auto result = VFS::the().open(path, O_RDONLY | O_NOFOLLOW_NOERROR, 0, current_directory());
  1132. if (result.is_error())
  1133. return result.error();
  1134. auto description = result.value();
  1135. if (!description->metadata().is_symlink())
  1136. return -EINVAL;
  1137. auto contents = description->read_entire_file();
  1138. if (!contents)
  1139. return -EIO; // FIXME: Get a more detailed error from VFS.
  1140. memcpy(buffer, contents.data(), min(size, (ssize_t)contents.size()));
  1141. if (contents.size() + 1 < size)
  1142. buffer[contents.size()] = '\0';
  1143. return 0;
  1144. }
  1145. int Process::sys$chdir(const char* path)
  1146. {
  1147. if (!validate_read_str(path))
  1148. return -EFAULT;
  1149. auto directory_or_error = VFS::the().open_directory(StringView(path), current_directory());
  1150. if (directory_or_error.is_error())
  1151. return directory_or_error.error();
  1152. m_cwd = *directory_or_error.value();
  1153. return 0;
  1154. }
  1155. int Process::sys$fchdir(int fd)
  1156. {
  1157. auto* description = file_description(fd);
  1158. if (!description)
  1159. return -EBADF;
  1160. if (!description->is_directory())
  1161. return -ENOTDIR;
  1162. if (!description->metadata().may_execute(*this))
  1163. return -EACCES;
  1164. m_cwd = description->custody();
  1165. return 0;
  1166. }
  1167. int Process::sys$getcwd(char* buffer, ssize_t size)
  1168. {
  1169. if (size < 0)
  1170. return -EINVAL;
  1171. if (!validate_write(buffer, size))
  1172. return -EFAULT;
  1173. auto path = current_directory().absolute_path();
  1174. if (size < path.length() + 1)
  1175. return -ERANGE;
  1176. strcpy(buffer, path.characters());
  1177. return 0;
  1178. }
  1179. int Process::number_of_open_file_descriptors() const
  1180. {
  1181. int count = 0;
  1182. for (auto& description : m_fds) {
  1183. if (description)
  1184. ++count;
  1185. }
  1186. return count;
  1187. }
  1188. int Process::sys$open(const Syscall::SC_open_params* params)
  1189. {
  1190. if (!validate_read_typed(params))
  1191. return -EFAULT;
  1192. auto& [path, path_length, options, mode] = *params;
  1193. if (!path_length)
  1194. return -EINVAL;
  1195. if (!validate_read(path, path_length))
  1196. return -EFAULT;
  1197. #ifdef DEBUG_IO
  1198. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1199. #endif
  1200. int fd = alloc_fd();
  1201. if (fd < 0)
  1202. return fd;
  1203. auto result = VFS::the().open(path, options, mode & ~umask(), current_directory());
  1204. if (result.is_error())
  1205. return result.error();
  1206. auto description = result.value();
  1207. if (options & O_DIRECTORY && !description->is_directory())
  1208. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1209. description->set_file_flags(options);
  1210. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1211. m_fds[fd].set(move(description), fd_flags);
  1212. return fd;
  1213. }
  1214. int Process::sys$openat(const Syscall::SC_openat_params* params)
  1215. {
  1216. if (!validate_read_typed(params))
  1217. return -EFAULT;
  1218. auto& [dirfd, path, path_length, options, mode] = *params;
  1219. if (!validate_read(path, path_length))
  1220. return -EFAULT;
  1221. #ifdef DEBUG_IO
  1222. dbgprintf("%s(%u) sys$openat(%d, \"%s\")\n", dirfd, name().characters(), pid(), path);
  1223. #endif
  1224. int fd = alloc_fd();
  1225. if (fd < 0)
  1226. return fd;
  1227. RefPtr<Custody> base;
  1228. if (dirfd == AT_FDCWD) {
  1229. base = current_directory();
  1230. } else {
  1231. auto* base_description = file_description(dirfd);
  1232. if (!base_description)
  1233. return -EBADF;
  1234. if (!base_description->is_directory())
  1235. return -ENOTDIR;
  1236. if (!base_description->custody())
  1237. return -EINVAL;
  1238. base = base_description->custody();
  1239. }
  1240. auto result = VFS::the().open(path, options, mode & ~umask(), *base);
  1241. if (result.is_error())
  1242. return result.error();
  1243. auto description = result.value();
  1244. if (options & O_DIRECTORY && !description->is_directory())
  1245. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1246. description->set_file_flags(options);
  1247. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1248. m_fds[fd].set(move(description), fd_flags);
  1249. return fd;
  1250. }
  1251. int Process::alloc_fd(int first_candidate_fd)
  1252. {
  1253. int fd = -EMFILE;
  1254. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1255. if (!m_fds[i]) {
  1256. fd = i;
  1257. break;
  1258. }
  1259. }
  1260. return fd;
  1261. }
  1262. int Process::sys$pipe(int pipefd[2], int flags)
  1263. {
  1264. if (!validate_write_typed(pipefd))
  1265. return -EFAULT;
  1266. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1267. return -EMFILE;
  1268. // Reject flags other than O_CLOEXEC.
  1269. if ((flags & O_CLOEXEC) != flags)
  1270. return -EINVAL;
  1271. u32 fd_flags = (flags & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1272. auto fifo = FIFO::create(m_uid);
  1273. int reader_fd = alloc_fd();
  1274. m_fds[reader_fd].set(fifo->open_direction(FIFO::Direction::Reader), fd_flags);
  1275. pipefd[0] = reader_fd;
  1276. int writer_fd = alloc_fd();
  1277. m_fds[writer_fd].set(fifo->open_direction(FIFO::Direction::Writer), fd_flags);
  1278. pipefd[1] = writer_fd;
  1279. return 0;
  1280. }
  1281. int Process::sys$killpg(int pgrp, int signum)
  1282. {
  1283. if (signum < 1 || signum >= 32)
  1284. return -EINVAL;
  1285. if (pgrp < 0)
  1286. return -EINVAL;
  1287. InterruptDisabler disabler;
  1288. return do_killpg(pgrp, signum);
  1289. }
  1290. int Process::sys$setuid(uid_t uid)
  1291. {
  1292. if (uid != m_uid && !is_superuser())
  1293. return -EPERM;
  1294. m_uid = uid;
  1295. m_euid = uid;
  1296. return 0;
  1297. }
  1298. int Process::sys$setgid(gid_t gid)
  1299. {
  1300. if (gid != m_gid && !is_superuser())
  1301. return -EPERM;
  1302. m_gid = gid;
  1303. m_egid = gid;
  1304. return 0;
  1305. }
  1306. unsigned Process::sys$alarm(unsigned seconds)
  1307. {
  1308. unsigned previous_alarm_remaining = 0;
  1309. if (m_alarm_deadline && m_alarm_deadline > g_uptime) {
  1310. previous_alarm_remaining = (m_alarm_deadline - g_uptime) / TICKS_PER_SECOND;
  1311. }
  1312. if (!seconds) {
  1313. m_alarm_deadline = 0;
  1314. return previous_alarm_remaining;
  1315. }
  1316. m_alarm_deadline = g_uptime + seconds * TICKS_PER_SECOND;
  1317. return previous_alarm_remaining;
  1318. }
  1319. int Process::sys$uname(utsname* buf)
  1320. {
  1321. if (!validate_write_typed(buf))
  1322. return -EFAULT;
  1323. strcpy(buf->sysname, "Serenity");
  1324. strcpy(buf->release, "1.0-dev");
  1325. strcpy(buf->version, "FIXME");
  1326. strcpy(buf->machine, "i686");
  1327. LOCKER(*s_hostname_lock);
  1328. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1329. return 0;
  1330. }
  1331. KResult Process::do_kill(Process& process, int signal)
  1332. {
  1333. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1334. // FIXME: Should setuid processes have some special treatment here?
  1335. if (!is_superuser() && m_euid != process.m_uid && m_uid != process.m_uid)
  1336. return KResult(-EPERM);
  1337. if (process.is_ring0() && signal == SIGKILL) {
  1338. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, process.name().characters(), process.pid());
  1339. return KResult(-EPERM);
  1340. }
  1341. process.send_signal(signal, this);
  1342. return KSuccess;
  1343. }
  1344. KResult Process::do_killpg(pid_t pgrp, int signal)
  1345. {
  1346. ASSERT(pgrp >= 0);
  1347. // Send the signal to all processes in the given group.
  1348. if (pgrp == 0) {
  1349. // Send the signal to our own pgrp.
  1350. pgrp = pgid();
  1351. }
  1352. bool group_was_empty = true;
  1353. bool any_succeeded = false;
  1354. KResult error = KSuccess;
  1355. Process::for_each_in_pgrp(pgrp, [&](auto& process) {
  1356. group_was_empty = false;
  1357. KResult res = do_kill(process, signal);
  1358. if (res.is_success())
  1359. any_succeeded = true;
  1360. else
  1361. error = res;
  1362. return IterationDecision::Continue;
  1363. });
  1364. if (group_was_empty)
  1365. return KResult(-ESRCH);
  1366. if (any_succeeded)
  1367. return KSuccess;
  1368. return error;
  1369. }
  1370. int Process::sys$kill(pid_t pid, int signal)
  1371. {
  1372. if (signal < 0 || signal >= 32)
  1373. return -EINVAL;
  1374. if (pid <= 0) {
  1375. return do_killpg(-pid, signal);
  1376. }
  1377. if (pid == -1) {
  1378. // FIXME: Send to all processes.
  1379. ASSERT(pid != -1);
  1380. }
  1381. if (pid == m_pid) {
  1382. // FIXME: If we ignore this signal anyway, we don't need to block here, right?
  1383. current->send_signal(signal, this);
  1384. (void)current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal);
  1385. return 0;
  1386. }
  1387. InterruptDisabler disabler;
  1388. auto* peer = Process::from_pid(pid);
  1389. if (!peer)
  1390. return -ESRCH;
  1391. return do_kill(*peer, signal);
  1392. }
  1393. int Process::sys$usleep(useconds_t usec)
  1394. {
  1395. if (!usec)
  1396. return 0;
  1397. u64 wakeup_time = current->sleep(usec / 1000);
  1398. if (wakeup_time > g_uptime)
  1399. return -EINTR;
  1400. return 0;
  1401. }
  1402. int Process::sys$sleep(unsigned seconds)
  1403. {
  1404. if (!seconds)
  1405. return 0;
  1406. u64 wakeup_time = current->sleep(seconds * TICKS_PER_SECOND);
  1407. if (wakeup_time > g_uptime) {
  1408. u32 ticks_left_until_original_wakeup_time = wakeup_time - g_uptime;
  1409. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1410. }
  1411. return 0;
  1412. }
  1413. timeval kgettimeofday()
  1414. {
  1415. timeval tv;
  1416. tv.tv_sec = RTC::boot_time() + PIT::seconds_since_boot();
  1417. tv.tv_usec = PIT::ticks_this_second() * 1000;
  1418. return tv;
  1419. }
  1420. void kgettimeofday(timeval& tv)
  1421. {
  1422. tv = kgettimeofday();
  1423. }
  1424. int Process::sys$gettimeofday(timeval* tv)
  1425. {
  1426. if (!validate_write_typed(tv))
  1427. return -EFAULT;
  1428. kgettimeofday(*tv);
  1429. return 0;
  1430. }
  1431. uid_t Process::sys$getuid()
  1432. {
  1433. return m_uid;
  1434. }
  1435. gid_t Process::sys$getgid()
  1436. {
  1437. return m_gid;
  1438. }
  1439. uid_t Process::sys$geteuid()
  1440. {
  1441. return m_euid;
  1442. }
  1443. gid_t Process::sys$getegid()
  1444. {
  1445. return m_egid;
  1446. }
  1447. pid_t Process::sys$getpid()
  1448. {
  1449. return m_pid;
  1450. }
  1451. pid_t Process::sys$getppid()
  1452. {
  1453. return m_ppid;
  1454. }
  1455. mode_t Process::sys$umask(mode_t mask)
  1456. {
  1457. auto old_mask = m_umask;
  1458. m_umask = mask & 0777;
  1459. return old_mask;
  1460. }
  1461. int Process::reap(Process& process)
  1462. {
  1463. int exit_status;
  1464. {
  1465. InterruptDisabler disabler;
  1466. exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1467. if (process.ppid()) {
  1468. auto* parent = Process::from_pid(process.ppid());
  1469. if (parent) {
  1470. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1471. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1472. }
  1473. }
  1474. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), process.main_thread().state_string());
  1475. ASSERT(process.is_dead());
  1476. g_processes->remove(&process);
  1477. }
  1478. delete &process;
  1479. return exit_status;
  1480. }
  1481. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1482. {
  1483. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1484. if (!options) {
  1485. // FIXME: This can't be right.. can it? Figure out how this should actually work.
  1486. options = WEXITED;
  1487. }
  1488. if (wstatus)
  1489. if (!validate_write_typed(wstatus))
  1490. return -EFAULT;
  1491. int dummy_wstatus;
  1492. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1493. {
  1494. InterruptDisabler disabler;
  1495. if (waitee != -1 && !Process::from_pid(waitee))
  1496. return -ECHILD;
  1497. }
  1498. if (options & WNOHANG) {
  1499. // FIXME: Figure out what WNOHANG should do with stopped children.
  1500. if (waitee == -1) {
  1501. pid_t reaped_pid = 0;
  1502. InterruptDisabler disabler;
  1503. for_each_child([&reaped_pid, &exit_status](Process& process) {
  1504. if (process.is_dead()) {
  1505. reaped_pid = process.pid();
  1506. exit_status = reap(process);
  1507. }
  1508. return IterationDecision::Continue;
  1509. });
  1510. return reaped_pid;
  1511. } else {
  1512. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1513. InterruptDisabler disabler;
  1514. auto* waitee_process = Process::from_pid(waitee);
  1515. if (!waitee_process)
  1516. return -ECHILD;
  1517. if (waitee_process->is_dead()) {
  1518. exit_status = reap(*waitee_process);
  1519. return waitee;
  1520. }
  1521. return 0;
  1522. }
  1523. }
  1524. pid_t waitee_pid = waitee;
  1525. if (current->block<Thread::WaitBlocker>(options, waitee_pid) == Thread::BlockResult::InterruptedBySignal)
  1526. return -EINTR;
  1527. InterruptDisabler disabler;
  1528. // NOTE: If waitee was -1, m_waitee_pid will have been filled in by the scheduler.
  1529. Process* waitee_process = Process::from_pid(waitee_pid);
  1530. if (!waitee_process)
  1531. return -ECHILD;
  1532. ASSERT(waitee_process);
  1533. if (waitee_process->is_dead()) {
  1534. exit_status = reap(*waitee_process);
  1535. } else {
  1536. ASSERT(waitee_process->main_thread().state() == Thread::State::Stopped);
  1537. exit_status = 0x7f;
  1538. }
  1539. return waitee_pid;
  1540. }
  1541. enum class KernelMemoryCheckResult {
  1542. NotInsideKernelMemory,
  1543. AccessGranted,
  1544. AccessDenied
  1545. };
  1546. static KernelMemoryCheckResult check_kernel_memory_access(VirtualAddress vaddr, bool is_write)
  1547. {
  1548. auto& sections = multiboot_info_ptr->u.elf_sec;
  1549. auto* kernel_program_headers = (Elf32_Phdr*)(sections.addr);
  1550. for (unsigned i = 0; i < sections.num; ++i) {
  1551. auto& segment = kernel_program_headers[i];
  1552. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1553. continue;
  1554. if (vaddr.get() < segment.p_vaddr || vaddr.get() > (segment.p_vaddr + segment.p_memsz))
  1555. continue;
  1556. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1557. return KernelMemoryCheckResult::AccessDenied;
  1558. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1559. return KernelMemoryCheckResult::AccessDenied;
  1560. return KernelMemoryCheckResult::AccessGranted;
  1561. }
  1562. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1563. }
  1564. bool Process::validate_read_from_kernel(VirtualAddress vaddr) const
  1565. {
  1566. if (vaddr.is_null())
  1567. return false;
  1568. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1569. // This code allows access outside of the known used address ranges to get caught.
  1570. auto kmc_result = check_kernel_memory_access(vaddr, false);
  1571. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1572. return true;
  1573. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1574. return false;
  1575. if (is_kmalloc_address(vaddr.as_ptr()))
  1576. return true;
  1577. return validate_read(vaddr.as_ptr(), 1);
  1578. }
  1579. bool Process::validate_read_str(const char* str)
  1580. {
  1581. if (!validate_read(str, 1))
  1582. return false;
  1583. return validate_read(str, strlen(str) + 1);
  1584. }
  1585. bool Process::validate_read(const void* address, ssize_t size) const
  1586. {
  1587. ASSERT(size >= 0);
  1588. VirtualAddress first_address((u32)address);
  1589. VirtualAddress last_address = first_address.offset(size - 1);
  1590. if (is_ring0()) {
  1591. auto kmc_result = check_kernel_memory_access(first_address, false);
  1592. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1593. return true;
  1594. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1595. return false;
  1596. if (is_kmalloc_address(address))
  1597. return true;
  1598. }
  1599. ASSERT(size);
  1600. if (!size)
  1601. return false;
  1602. if (first_address.page_base() != last_address.page_base()) {
  1603. if (!MM.validate_user_read(*this, last_address))
  1604. return false;
  1605. }
  1606. return MM.validate_user_read(*this, first_address);
  1607. }
  1608. bool Process::validate_write(void* address, ssize_t size) const
  1609. {
  1610. ASSERT(size >= 0);
  1611. VirtualAddress first_address((u32)address);
  1612. VirtualAddress last_address = first_address.offset(size - 1);
  1613. if (is_ring0()) {
  1614. if (is_kmalloc_address(address))
  1615. return true;
  1616. auto kmc_result = check_kernel_memory_access(first_address, true);
  1617. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1618. return true;
  1619. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1620. return false;
  1621. }
  1622. if (!size)
  1623. return false;
  1624. if (first_address.page_base() != last_address.page_base()) {
  1625. if (!MM.validate_user_write(*this, last_address))
  1626. return false;
  1627. }
  1628. return MM.validate_user_write(*this, last_address);
  1629. }
  1630. pid_t Process::sys$getsid(pid_t pid)
  1631. {
  1632. if (pid == 0)
  1633. return m_sid;
  1634. InterruptDisabler disabler;
  1635. auto* process = Process::from_pid(pid);
  1636. if (!process)
  1637. return -ESRCH;
  1638. if (m_sid != process->m_sid)
  1639. return -EPERM;
  1640. return process->m_sid;
  1641. }
  1642. pid_t Process::sys$setsid()
  1643. {
  1644. InterruptDisabler disabler;
  1645. bool found_process_with_same_pgid_as_my_pid = false;
  1646. Process::for_each_in_pgrp(pid(), [&](auto&) {
  1647. found_process_with_same_pgid_as_my_pid = true;
  1648. return IterationDecision::Break;
  1649. });
  1650. if (found_process_with_same_pgid_as_my_pid)
  1651. return -EPERM;
  1652. m_sid = m_pid;
  1653. m_pgid = m_pid;
  1654. return m_sid;
  1655. }
  1656. pid_t Process::sys$getpgid(pid_t pid)
  1657. {
  1658. if (pid == 0)
  1659. return m_pgid;
  1660. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1661. auto* process = Process::from_pid(pid);
  1662. if (!process)
  1663. return -ESRCH;
  1664. return process->m_pgid;
  1665. }
  1666. pid_t Process::sys$getpgrp()
  1667. {
  1668. return m_pgid;
  1669. }
  1670. static pid_t get_sid_from_pgid(pid_t pgid)
  1671. {
  1672. InterruptDisabler disabler;
  1673. auto* group_leader = Process::from_pid(pgid);
  1674. if (!group_leader)
  1675. return -1;
  1676. return group_leader->sid();
  1677. }
  1678. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1679. {
  1680. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1681. pid_t pid = specified_pid ? specified_pid : m_pid;
  1682. if (specified_pgid < 0)
  1683. return -EINVAL;
  1684. auto* process = Process::from_pid(pid);
  1685. if (!process)
  1686. return -ESRCH;
  1687. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1688. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1689. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1690. if (current_sid != new_sid) {
  1691. // Can't move a process between sessions.
  1692. return -EPERM;
  1693. }
  1694. // FIXME: There are more EPERM conditions to check for here..
  1695. process->m_pgid = new_pgid;
  1696. return 0;
  1697. }
  1698. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1699. {
  1700. auto* description = file_description(fd);
  1701. if (!description)
  1702. return -EBADF;
  1703. return description->file().ioctl(*description, request, arg);
  1704. }
  1705. int Process::sys$getdtablesize()
  1706. {
  1707. return m_max_open_file_descriptors;
  1708. }
  1709. int Process::sys$dup(int old_fd)
  1710. {
  1711. auto* description = file_description(old_fd);
  1712. if (!description)
  1713. return -EBADF;
  1714. int new_fd = alloc_fd(0);
  1715. if (new_fd < 0)
  1716. return new_fd;
  1717. m_fds[new_fd].set(*description);
  1718. return new_fd;
  1719. }
  1720. int Process::sys$dup2(int old_fd, int new_fd)
  1721. {
  1722. auto* description = file_description(old_fd);
  1723. if (!description)
  1724. return -EBADF;
  1725. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  1726. return -EINVAL;
  1727. m_fds[new_fd].set(*description);
  1728. return new_fd;
  1729. }
  1730. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1731. {
  1732. if (old_set) {
  1733. if (!validate_write_typed(old_set))
  1734. return -EFAULT;
  1735. *old_set = current->m_signal_mask;
  1736. }
  1737. if (set) {
  1738. if (!validate_read_typed(set))
  1739. return -EFAULT;
  1740. switch (how) {
  1741. case SIG_BLOCK:
  1742. current->m_signal_mask &= ~(*set);
  1743. break;
  1744. case SIG_UNBLOCK:
  1745. current->m_signal_mask |= *set;
  1746. break;
  1747. case SIG_SETMASK:
  1748. current->m_signal_mask = *set;
  1749. break;
  1750. default:
  1751. return -EINVAL;
  1752. }
  1753. }
  1754. return 0;
  1755. }
  1756. int Process::sys$sigpending(sigset_t* set)
  1757. {
  1758. if (!validate_write_typed(set))
  1759. return -EFAULT;
  1760. *set = current->m_pending_signals;
  1761. return 0;
  1762. }
  1763. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1764. {
  1765. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1766. return -EINVAL;
  1767. if (!validate_read_typed(act))
  1768. return -EFAULT;
  1769. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1770. auto& action = current->m_signal_action_data[signum];
  1771. if (old_act) {
  1772. if (!validate_write_typed(old_act))
  1773. return -EFAULT;
  1774. old_act->sa_flags = action.flags;
  1775. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1776. }
  1777. action.flags = act->sa_flags;
  1778. action.handler_or_sigaction = VirtualAddress((u32)act->sa_sigaction);
  1779. return 0;
  1780. }
  1781. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1782. {
  1783. if (count < 0)
  1784. return -EINVAL;
  1785. if (!count)
  1786. return m_gids.size();
  1787. if (count != (int)m_gids.size())
  1788. return -EINVAL;
  1789. if (!validate_write_typed(gids, m_gids.size()))
  1790. return -EFAULT;
  1791. size_t i = 0;
  1792. for (auto gid : m_gids)
  1793. gids[i++] = gid;
  1794. return 0;
  1795. }
  1796. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1797. {
  1798. if (count < 0)
  1799. return -EINVAL;
  1800. if (!is_superuser())
  1801. return -EPERM;
  1802. if (!validate_read(gids, count))
  1803. return -EFAULT;
  1804. m_gids.clear();
  1805. m_gids.set(m_gid);
  1806. for (int i = 0; i < count; ++i)
  1807. m_gids.set(gids[i]);
  1808. return 0;
  1809. }
  1810. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1811. {
  1812. if (!validate_read_str(pathname))
  1813. return -EFAULT;
  1814. size_t pathname_length = strlen(pathname);
  1815. if (pathname_length == 0)
  1816. return -EINVAL;
  1817. if (pathname_length >= 255)
  1818. return -ENAMETOOLONG;
  1819. return VFS::the().mkdir(StringView(pathname, pathname_length), mode & ~umask(), current_directory());
  1820. }
  1821. int Process::sys$realpath(const char* pathname, char* buffer, size_t size)
  1822. {
  1823. if (!validate_read_str(pathname))
  1824. return -EFAULT;
  1825. size_t pathname_length = strlen(pathname);
  1826. if (pathname_length == 0)
  1827. return -EINVAL;
  1828. if (pathname_length >= size)
  1829. return -ENAMETOOLONG;
  1830. if (!validate_write(buffer, size))
  1831. return -EFAULT;
  1832. auto custody_or_error = VFS::the().resolve_path(pathname, current_directory());
  1833. if (custody_or_error.is_error())
  1834. return custody_or_error.error();
  1835. auto& custody = custody_or_error.value();
  1836. // FIXME: Once resolve_path is fixed to deal with .. and . , remove the use of FileSystemPath::canonical_path.
  1837. FileSystemPath canonical_path(custody->absolute_path());
  1838. if (!canonical_path.is_valid()) {
  1839. dbg() << "FileSystemPath failed to canonicalize " << custody->absolute_path();
  1840. ASSERT_NOT_REACHED();
  1841. }
  1842. strncpy(buffer, canonical_path.string().characters(), size);
  1843. return 0;
  1844. };
  1845. clock_t Process::sys$times(tms* times)
  1846. {
  1847. if (!validate_write_typed(times))
  1848. return -EFAULT;
  1849. times->tms_utime = m_ticks_in_user;
  1850. times->tms_stime = m_ticks_in_kernel;
  1851. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1852. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1853. return g_uptime & 0x7fffffff;
  1854. }
  1855. int Process::sys$select(const Syscall::SC_select_params* params)
  1856. {
  1857. // FIXME: Return -EINVAL if timeout is invalid.
  1858. if (!validate_read_typed(params))
  1859. return -EFAULT;
  1860. auto& [nfds, readfds, writefds, exceptfds, timeout] = *params;
  1861. if (writefds && !validate_write_typed(writefds))
  1862. return -EFAULT;
  1863. if (readfds && !validate_write_typed(readfds))
  1864. return -EFAULT;
  1865. if (exceptfds && !validate_write_typed(exceptfds))
  1866. return -EFAULT;
  1867. if (timeout && !validate_read_typed(timeout))
  1868. return -EFAULT;
  1869. if (nfds < 0)
  1870. return -EINVAL;
  1871. timeval computed_timeout;
  1872. bool select_has_timeout = false;
  1873. if (timeout && (timeout->tv_sec || timeout->tv_usec)) {
  1874. timeval_add(kgettimeofday(), *timeout, computed_timeout);
  1875. select_has_timeout = true;
  1876. }
  1877. Thread::SelectBlocker::FDVector rfds;
  1878. Thread::SelectBlocker::FDVector wfds;
  1879. Thread::SelectBlocker::FDVector efds;
  1880. auto transfer_fds = [&](auto* fds, auto& vector) -> int {
  1881. vector.clear_with_capacity();
  1882. if (!fds)
  1883. return 0;
  1884. for (int fd = 0; fd < params->nfds; ++fd) {
  1885. if (FD_ISSET(fd, fds)) {
  1886. if (!file_description(fd))
  1887. return -EBADF;
  1888. vector.append(fd);
  1889. }
  1890. }
  1891. return 0;
  1892. };
  1893. if (int error = transfer_fds(writefds, wfds))
  1894. return error;
  1895. if (int error = transfer_fds(readfds, rfds))
  1896. return error;
  1897. if (int error = transfer_fds(exceptfds, efds))
  1898. return error;
  1899. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  1900. dbgprintf("%s<%u> selecting on (read:%u, write:%u), timeout=%p\n", name().characters(), pid(), rfds.size(), wfds.size(), timeout);
  1901. #endif
  1902. if (!timeout || select_has_timeout) {
  1903. if (current->block<Thread::SelectBlocker>(computed_timeout, select_has_timeout, rfds, wfds, efds) == Thread::BlockResult::InterruptedBySignal)
  1904. return -EINTR;
  1905. }
  1906. int marked_fd_count = 0;
  1907. auto mark_fds = [&](auto* fds, auto& vector, auto should_mark) {
  1908. if (!fds)
  1909. return;
  1910. FD_ZERO(fds);
  1911. for (int fd : vector) {
  1912. if (auto* description = file_description(fd); description && should_mark(*description)) {
  1913. FD_SET(fd, fds);
  1914. ++marked_fd_count;
  1915. }
  1916. }
  1917. };
  1918. mark_fds(readfds, rfds, [](auto& description) { return description.can_read(); });
  1919. mark_fds(writefds, wfds, [](auto& description) { return description.can_write(); });
  1920. // FIXME: We should also mark exceptfds as appropriate.
  1921. return marked_fd_count;
  1922. }
  1923. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1924. {
  1925. if (!validate_read_typed(fds))
  1926. return -EFAULT;
  1927. Thread::SelectBlocker::FDVector rfds;
  1928. Thread::SelectBlocker::FDVector wfds;
  1929. for (int i = 0; i < nfds; ++i) {
  1930. if (fds[i].events & POLLIN)
  1931. rfds.append(fds[i].fd);
  1932. if (fds[i].events & POLLOUT)
  1933. wfds.append(fds[i].fd);
  1934. }
  1935. timeval actual_timeout;
  1936. bool has_timeout = false;
  1937. if (timeout >= 0) {
  1938. // poll is in ms, we want s/us.
  1939. struct timeval tvtimeout;
  1940. tvtimeout.tv_sec = 0;
  1941. while (timeout >= 1000) {
  1942. tvtimeout.tv_sec += 1;
  1943. timeout -= 1000;
  1944. }
  1945. tvtimeout.tv_usec = timeout * 1000;
  1946. timeval_add(kgettimeofday(), tvtimeout, actual_timeout);
  1947. has_timeout = true;
  1948. }
  1949. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  1950. dbgprintf("%s<%u> polling on (read:%u, write:%u), timeout=%d\n", name().characters(), pid(), rfds.size(), wfds.size(), timeout);
  1951. #endif
  1952. if (has_timeout || timeout < 0) {
  1953. if (current->block<Thread::SelectBlocker>(actual_timeout, has_timeout, rfds, wfds, Thread::SelectBlocker::FDVector()) == Thread::BlockResult::InterruptedBySignal)
  1954. return -EINTR;
  1955. }
  1956. int fds_with_revents = 0;
  1957. for (int i = 0; i < nfds; ++i) {
  1958. auto* description = file_description(fds[i].fd);
  1959. if (!description) {
  1960. fds[i].revents = POLLNVAL;
  1961. continue;
  1962. }
  1963. fds[i].revents = 0;
  1964. if (fds[i].events & POLLIN && description->can_read())
  1965. fds[i].revents |= POLLIN;
  1966. if (fds[i].events & POLLOUT && description->can_write())
  1967. fds[i].revents |= POLLOUT;
  1968. if (fds[i].revents)
  1969. ++fds_with_revents;
  1970. }
  1971. return fds_with_revents;
  1972. }
  1973. Custody& Process::current_directory()
  1974. {
  1975. if (!m_cwd)
  1976. m_cwd = VFS::the().root_custody();
  1977. return *m_cwd;
  1978. }
  1979. int Process::sys$link(const char* old_path, const char* new_path)
  1980. {
  1981. if (!validate_read_str(old_path))
  1982. return -EFAULT;
  1983. if (!validate_read_str(new_path))
  1984. return -EFAULT;
  1985. return VFS::the().link(StringView(old_path), StringView(new_path), current_directory());
  1986. }
  1987. int Process::sys$unlink(const char* pathname)
  1988. {
  1989. if (!validate_read_str(pathname))
  1990. return -EFAULT;
  1991. return VFS::the().unlink(StringView(pathname), current_directory());
  1992. }
  1993. int Process::sys$symlink(const char* target, const char* linkpath)
  1994. {
  1995. if (!validate_read_str(target))
  1996. return -EFAULT;
  1997. if (!validate_read_str(linkpath))
  1998. return -EFAULT;
  1999. return VFS::the().symlink(StringView(target), StringView(linkpath), current_directory());
  2000. }
  2001. int Process::sys$rmdir(const char* pathname)
  2002. {
  2003. if (!validate_read_str(pathname))
  2004. return -EFAULT;
  2005. return VFS::the().rmdir(StringView(pathname), current_directory());
  2006. }
  2007. int Process::sys$read_tsc(u32* lsw, u32* msw)
  2008. {
  2009. if (!validate_write_typed(lsw))
  2010. return -EFAULT;
  2011. if (!validate_write_typed(msw))
  2012. return -EFAULT;
  2013. read_tsc(*lsw, *msw);
  2014. return 0;
  2015. }
  2016. int Process::sys$chmod(const char* pathname, mode_t mode)
  2017. {
  2018. if (!validate_read_str(pathname))
  2019. return -EFAULT;
  2020. return VFS::the().chmod(StringView(pathname), mode, current_directory());
  2021. }
  2022. int Process::sys$fchmod(int fd, mode_t mode)
  2023. {
  2024. auto* description = file_description(fd);
  2025. if (!description)
  2026. return -EBADF;
  2027. return description->fchmod(mode);
  2028. }
  2029. int Process::sys$fchown(int fd, uid_t uid, gid_t gid)
  2030. {
  2031. auto* description = file_description(fd);
  2032. if (!description)
  2033. return -EBADF;
  2034. return description->chown(uid, gid);
  2035. }
  2036. int Process::sys$chown(const char* pathname, uid_t uid, gid_t gid)
  2037. {
  2038. if (!validate_read_str(pathname))
  2039. return -EFAULT;
  2040. return VFS::the().chown(StringView(pathname), uid, gid, current_directory());
  2041. }
  2042. void Process::finalize()
  2043. {
  2044. ASSERT(current == g_finalizer);
  2045. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  2046. m_fds.clear();
  2047. m_tty = nullptr;
  2048. m_executable = nullptr;
  2049. m_cwd = nullptr;
  2050. m_elf_loader = nullptr;
  2051. disown_all_shared_buffers();
  2052. {
  2053. InterruptDisabler disabler;
  2054. if (auto* parent_process = Process::from_pid(m_ppid)) {
  2055. // FIXME(Thread): What should we do here? Should we look at all threads' signal actions?
  2056. if (parent_process->main_thread().m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  2057. // NOTE: If the parent doesn't care about this process, let it go.
  2058. m_ppid = 0;
  2059. } else {
  2060. parent_process->send_signal(SIGCHLD, this);
  2061. }
  2062. }
  2063. }
  2064. m_dead = true;
  2065. }
  2066. void Process::die()
  2067. {
  2068. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  2069. // getting an EOF when the last process using the slave PTY dies.
  2070. // If the master PTY owner relies on an EOF to know when to wait() on a
  2071. // slave owner, we have to allow the PTY pair to be torn down.
  2072. m_tty = nullptr;
  2073. if (m_tracer)
  2074. m_tracer->set_dead();
  2075. {
  2076. // Tell the threads to unwind and die.
  2077. InterruptDisabler disabler;
  2078. for_each_thread([](Thread& thread) {
  2079. thread.set_should_die();
  2080. return IterationDecision::Continue;
  2081. });
  2082. }
  2083. }
  2084. size_t Process::amount_virtual() const
  2085. {
  2086. size_t amount = 0;
  2087. for (auto& region : m_regions) {
  2088. amount += region.size();
  2089. }
  2090. return amount;
  2091. }
  2092. size_t Process::amount_resident() const
  2093. {
  2094. // FIXME: This will double count if multiple regions use the same physical page.
  2095. size_t amount = 0;
  2096. for (auto& region : m_regions) {
  2097. amount += region.amount_resident();
  2098. }
  2099. return amount;
  2100. }
  2101. size_t Process::amount_shared() const
  2102. {
  2103. // FIXME: This will double count if multiple regions use the same physical page.
  2104. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  2105. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  2106. // so that every Region contributes +1 ref to each of its PhysicalPages.
  2107. size_t amount = 0;
  2108. for (auto& region : m_regions) {
  2109. amount += region.amount_shared();
  2110. }
  2111. return amount;
  2112. }
  2113. int Process::sys$socket(int domain, int type, int protocol)
  2114. {
  2115. int fd = alloc_fd();
  2116. if (fd < 0)
  2117. return fd;
  2118. auto result = Socket::create(domain, type, protocol);
  2119. if (result.is_error())
  2120. return result.error();
  2121. auto description = FileDescription::create(*result.value());
  2122. unsigned flags = 0;
  2123. if (type & SOCK_CLOEXEC)
  2124. flags |= FD_CLOEXEC;
  2125. if (type & SOCK_NONBLOCK)
  2126. description->set_blocking(false);
  2127. m_fds[fd].set(move(description), flags);
  2128. return fd;
  2129. }
  2130. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2131. {
  2132. if (!validate_read(address, address_length))
  2133. return -EFAULT;
  2134. auto* description = file_description(sockfd);
  2135. if (!description)
  2136. return -EBADF;
  2137. if (!description->is_socket())
  2138. return -ENOTSOCK;
  2139. auto& socket = *description->socket();
  2140. return socket.bind(address, address_length);
  2141. }
  2142. int Process::sys$listen(int sockfd, int backlog)
  2143. {
  2144. auto* description = file_description(sockfd);
  2145. if (!description)
  2146. return -EBADF;
  2147. if (!description->is_socket())
  2148. return -ENOTSOCK;
  2149. auto& socket = *description->socket();
  2150. if (socket.is_connected())
  2151. return -EINVAL;
  2152. return socket.listen(backlog);
  2153. }
  2154. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  2155. {
  2156. if (!validate_write_typed(address_size))
  2157. return -EFAULT;
  2158. if (!validate_write(address, *address_size))
  2159. return -EFAULT;
  2160. int accepted_socket_fd = alloc_fd();
  2161. if (accepted_socket_fd < 0)
  2162. return accepted_socket_fd;
  2163. auto* accepting_socket_description = file_description(accepting_socket_fd);
  2164. if (!accepting_socket_description)
  2165. return -EBADF;
  2166. if (!accepting_socket_description->is_socket())
  2167. return -ENOTSOCK;
  2168. auto& socket = *accepting_socket_description->socket();
  2169. if (!socket.can_accept()) {
  2170. if (accepting_socket_description->is_blocking()) {
  2171. if (current->block<Thread::AcceptBlocker>(*accepting_socket_description) == Thread::BlockResult::InterruptedBySignal)
  2172. return -EINTR;
  2173. } else {
  2174. return -EAGAIN;
  2175. }
  2176. }
  2177. auto accepted_socket = socket.accept();
  2178. ASSERT(accepted_socket);
  2179. bool success = accepted_socket->get_peer_address(address, address_size);
  2180. ASSERT(success);
  2181. auto accepted_socket_description = FileDescription::create(*accepted_socket);
  2182. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2183. // I'm not sure if this matches other systems but it makes sense to me.
  2184. accepted_socket_description->set_blocking(accepting_socket_description->is_blocking());
  2185. m_fds[accepted_socket_fd].set(move(accepted_socket_description), m_fds[accepting_socket_fd].flags);
  2186. // NOTE: Moving this state to Completed is what causes connect() to unblock on the client side.
  2187. accepted_socket->set_setup_state(Socket::SetupState::Completed);
  2188. return accepted_socket_fd;
  2189. }
  2190. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2191. {
  2192. if (!validate_read(address, address_size))
  2193. return -EFAULT;
  2194. int fd = alloc_fd();
  2195. if (fd < 0)
  2196. return fd;
  2197. auto* description = file_description(sockfd);
  2198. if (!description)
  2199. return -EBADF;
  2200. if (!description->is_socket())
  2201. return -ENOTSOCK;
  2202. auto& socket = *description->socket();
  2203. return socket.connect(*description, address, address_size, description->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  2204. }
  2205. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* params)
  2206. {
  2207. if (!validate_read_typed(params))
  2208. return -EFAULT;
  2209. auto& [sockfd, data, data_length, flags, addr, addr_length] = *params;
  2210. if (!validate_read(data, data_length))
  2211. return -EFAULT;
  2212. if (addr && !validate_read(addr, addr_length))
  2213. return -EFAULT;
  2214. auto* description = file_description(sockfd);
  2215. if (!description)
  2216. return -EBADF;
  2217. if (!description->is_socket())
  2218. return -ENOTSOCK;
  2219. auto& socket = *description->socket();
  2220. kprintf("sendto %p (%u), flags=%u, addr: %p (%u)\n", data, data_length, flags, addr, addr_length);
  2221. return socket.sendto(*description, data, data_length, flags, addr, addr_length);
  2222. }
  2223. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params)
  2224. {
  2225. if (!validate_read_typed(params))
  2226. return -EFAULT;
  2227. auto& [sockfd, buffer, buffer_length, flags, addr, addr_length] = *params;
  2228. if (!validate_write(buffer, buffer_length))
  2229. return -EFAULT;
  2230. if (addr_length) {
  2231. if (!validate_write_typed(addr_length))
  2232. return -EFAULT;
  2233. if (!validate_write(addr, *addr_length))
  2234. return -EFAULT;
  2235. } else if (addr) {
  2236. return -EINVAL;
  2237. }
  2238. auto* description = file_description(sockfd);
  2239. if (!description)
  2240. return -EBADF;
  2241. if (!description->is_socket())
  2242. return -ENOTSOCK;
  2243. auto& socket = *description->socket();
  2244. bool original_blocking = description->is_blocking();
  2245. if (flags & MSG_DONTWAIT)
  2246. description->set_blocking(false);
  2247. auto nrecv = socket.recvfrom(*description, buffer, buffer_length, flags, addr, addr_length);
  2248. if (flags & MSG_DONTWAIT)
  2249. description->set_blocking(original_blocking);
  2250. return nrecv;
  2251. }
  2252. int Process::sys$getsockname(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2253. {
  2254. if (!validate_read_typed(addrlen))
  2255. return -EFAULT;
  2256. if (*addrlen <= 0)
  2257. return -EINVAL;
  2258. if (!validate_write(addr, *addrlen))
  2259. return -EFAULT;
  2260. auto* description = file_description(sockfd);
  2261. if (!description)
  2262. return -EBADF;
  2263. if (!description->is_socket())
  2264. return -ENOTSOCK;
  2265. auto& socket = *description->socket();
  2266. if (!socket.get_local_address(addr, addrlen))
  2267. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2268. return 0;
  2269. }
  2270. int Process::sys$getpeername(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2271. {
  2272. if (!validate_read_typed(addrlen))
  2273. return -EFAULT;
  2274. if (*addrlen <= 0)
  2275. return -EINVAL;
  2276. if (!validate_write(addr, *addrlen))
  2277. return -EFAULT;
  2278. auto* description = file_description(sockfd);
  2279. if (!description)
  2280. return -EBADF;
  2281. if (!description->is_socket())
  2282. return -ENOTSOCK;
  2283. auto& socket = *description->socket();
  2284. if (socket.setup_state() != Socket::SetupState::Completed)
  2285. return -ENOTCONN;
  2286. if (!socket.get_peer_address(addr, addrlen))
  2287. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2288. return 0;
  2289. }
  2290. int Process::sys$sched_setparam(pid_t pid, const struct sched_param* param)
  2291. {
  2292. if (!validate_read_typed(param))
  2293. return -EFAULT;
  2294. InterruptDisabler disabler;
  2295. auto* peer = this;
  2296. if (pid != 0)
  2297. peer = Process::from_pid(pid);
  2298. if (!peer)
  2299. return -ESRCH;
  2300. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2301. return -EPERM;
  2302. if (param->sched_priority < (int)ThreadPriority::First || param->sched_priority > (int)ThreadPriority::Last)
  2303. return -EINVAL;
  2304. peer->main_thread().set_priority((ThreadPriority)param->sched_priority);
  2305. return 0;
  2306. }
  2307. int Process::sys$sched_getparam(pid_t pid, struct sched_param* param)
  2308. {
  2309. if (!validate_read_typed(param))
  2310. return -EFAULT;
  2311. InterruptDisabler disabler;
  2312. auto* peer = this;
  2313. if (pid != 0)
  2314. peer = Process::from_pid(pid);
  2315. if (!peer)
  2316. return -ESRCH;
  2317. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2318. return -EPERM;
  2319. param->sched_priority = (int)peer->main_thread().priority();
  2320. return 0;
  2321. }
  2322. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  2323. {
  2324. if (!validate_read_typed(params))
  2325. return -EFAULT;
  2326. auto& [sockfd, level, option, value, value_size] = *params;
  2327. if (!validate_write_typed(value_size))
  2328. return -EFAULT;
  2329. if (!validate_write(value, *value_size))
  2330. return -EFAULT;
  2331. auto* description = file_description(sockfd);
  2332. if (!description)
  2333. return -EBADF;
  2334. if (!description->is_socket())
  2335. return -ENOTSOCK;
  2336. auto& socket = *description->socket();
  2337. return socket.getsockopt(level, option, value, value_size);
  2338. }
  2339. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  2340. {
  2341. if (!validate_read_typed(params))
  2342. return -EFAULT;
  2343. auto& [sockfd, level, option, value, value_size] = *params;
  2344. if (!validate_read(value, value_size))
  2345. return -EFAULT;
  2346. auto* description = file_description(sockfd);
  2347. if (!description)
  2348. return -EBADF;
  2349. if (!description->is_socket())
  2350. return -ENOTSOCK;
  2351. auto& socket = *description->socket();
  2352. return socket.setsockopt(level, option, value, value_size);
  2353. }
  2354. void Process::disown_all_shared_buffers()
  2355. {
  2356. LOCKER(shared_buffers().lock());
  2357. Vector<SharedBuffer*, 32> buffers_to_disown;
  2358. for (auto& it : shared_buffers().resource())
  2359. buffers_to_disown.append(it.value.ptr());
  2360. for (auto* shared_buffer : buffers_to_disown)
  2361. shared_buffer->disown(m_pid);
  2362. }
  2363. int Process::sys$create_shared_buffer(int size, void** buffer)
  2364. {
  2365. if (!size || size < 0)
  2366. return -EINVAL;
  2367. size = PAGE_ROUND_UP(size);
  2368. if (!validate_write_typed(buffer))
  2369. return -EFAULT;
  2370. LOCKER(shared_buffers().lock());
  2371. static int s_next_shared_buffer_id;
  2372. int shared_buffer_id = ++s_next_shared_buffer_id;
  2373. auto shared_buffer = make<SharedBuffer>(shared_buffer_id, size);
  2374. shared_buffer->share_with(m_pid);
  2375. *buffer = shared_buffer->ref_for_process_and_get_address(*this);
  2376. ASSERT((int)shared_buffer->size() >= size);
  2377. #ifdef SHARED_BUFFER_DEBUG
  2378. 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());
  2379. #endif
  2380. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2381. return shared_buffer_id;
  2382. }
  2383. int Process::sys$share_buffer_with(int shared_buffer_id, pid_t peer_pid)
  2384. {
  2385. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2386. return -EINVAL;
  2387. LOCKER(shared_buffers().lock());
  2388. auto it = shared_buffers().resource().find(shared_buffer_id);
  2389. if (it == shared_buffers().resource().end())
  2390. return -EINVAL;
  2391. auto& shared_buffer = *(*it).value;
  2392. if (!shared_buffer.is_shared_with(m_pid))
  2393. return -EPERM;
  2394. {
  2395. InterruptDisabler disabler;
  2396. auto* peer = Process::from_pid(peer_pid);
  2397. if (!peer)
  2398. return -ESRCH;
  2399. }
  2400. shared_buffer.share_with(peer_pid);
  2401. return 0;
  2402. }
  2403. int Process::sys$share_buffer_globally(int shared_buffer_id)
  2404. {
  2405. LOCKER(shared_buffers().lock());
  2406. auto it = shared_buffers().resource().find(shared_buffer_id);
  2407. if (it == shared_buffers().resource().end())
  2408. return -EINVAL;
  2409. auto& shared_buffer = *(*it).value;
  2410. if (!shared_buffer.is_shared_with(m_pid))
  2411. return -EPERM;
  2412. shared_buffer.share_globally();
  2413. return 0;
  2414. }
  2415. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2416. {
  2417. LOCKER(shared_buffers().lock());
  2418. auto it = shared_buffers().resource().find(shared_buffer_id);
  2419. if (it == shared_buffers().resource().end())
  2420. return -EINVAL;
  2421. auto& shared_buffer = *(*it).value;
  2422. if (!shared_buffer.is_shared_with(m_pid))
  2423. return -EPERM;
  2424. #ifdef SHARED_BUFFER_DEBUG
  2425. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2426. #endif
  2427. shared_buffer.deref_for_process(*this);
  2428. return 0;
  2429. }
  2430. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2431. {
  2432. LOCKER(shared_buffers().lock());
  2433. auto it = shared_buffers().resource().find(shared_buffer_id);
  2434. if (it == shared_buffers().resource().end())
  2435. return (void*)-EINVAL;
  2436. auto& shared_buffer = *(*it).value;
  2437. if (!shared_buffer.is_shared_with(m_pid))
  2438. return (void*)-EPERM;
  2439. #ifdef SHARED_BUFFER_DEBUG
  2440. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2441. #endif
  2442. return shared_buffer.ref_for_process_and_get_address(*this);
  2443. }
  2444. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  2445. {
  2446. LOCKER(shared_buffers().lock());
  2447. auto it = shared_buffers().resource().find(shared_buffer_id);
  2448. if (it == shared_buffers().resource().end())
  2449. return -EINVAL;
  2450. auto& shared_buffer = *(*it).value;
  2451. if (!shared_buffer.is_shared_with(m_pid))
  2452. return -EPERM;
  2453. #ifdef SHARED_BUFFER_DEBUG
  2454. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  2455. #endif
  2456. shared_buffer.seal();
  2457. return 0;
  2458. }
  2459. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  2460. {
  2461. LOCKER(shared_buffers().lock());
  2462. auto it = shared_buffers().resource().find(shared_buffer_id);
  2463. if (it == shared_buffers().resource().end())
  2464. return -EINVAL;
  2465. auto& shared_buffer = *(*it).value;
  2466. if (!shared_buffer.is_shared_with(m_pid))
  2467. return -EPERM;
  2468. #ifdef SHARED_BUFFER_DEBUG
  2469. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2470. #endif
  2471. return shared_buffer.size();
  2472. }
  2473. void Process::terminate_due_to_signal(u8 signal)
  2474. {
  2475. ASSERT_INTERRUPTS_DISABLED();
  2476. ASSERT(signal < 32);
  2477. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  2478. m_termination_status = 0;
  2479. m_termination_signal = signal;
  2480. die();
  2481. }
  2482. void Process::send_signal(u8 signal, Process* sender)
  2483. {
  2484. // FIXME(Thread): Find the appropriate thread to deliver the signal to.
  2485. main_thread().send_signal(signal, sender);
  2486. }
  2487. int Process::thread_count() const
  2488. {
  2489. int count = 0;
  2490. for_each_thread([&count](auto&) {
  2491. ++count;
  2492. return IterationDecision::Continue;
  2493. });
  2494. return count;
  2495. }
  2496. int Process::sys$create_thread(void* (*entry)(void*), void* argument, const Syscall::SC_create_thread_params* params)
  2497. {
  2498. if (!validate_read((const void*)entry, sizeof(void*)))
  2499. return -EFAULT;
  2500. if (!validate_read_typed(params))
  2501. return -EFAULT;
  2502. u32 user_stack_address = reinterpret_cast<u32>(params->m_stack_location) + params->m_stack_size;
  2503. if (!MM.validate_user_stack(*this, VirtualAddress(user_stack_address - 4)))
  2504. return -EFAULT;
  2505. // FIXME: return EAGAIN if Thread::all_threads().size() is greater than PTHREAD_THREADS_MAX
  2506. ThreadPriority requested_thread_priority = static_cast<ThreadPriority>(params->m_schedule_priority);
  2507. if (requested_thread_priority < ThreadPriority::First || requested_thread_priority > ThreadPriority::Last)
  2508. return -EINVAL;
  2509. if (requested_thread_priority != ThreadPriority::Normal && !is_superuser())
  2510. return -EPERM;
  2511. bool is_thread_joinable = (0 == params->m_detach_state);
  2512. // FIXME: Do something with guard pages?
  2513. auto* thread = new Thread(*this);
  2514. thread->set_priority(requested_thread_priority);
  2515. thread->set_joinable(is_thread_joinable);
  2516. auto& tss = thread->tss();
  2517. tss.eip = (u32)entry;
  2518. tss.eflags = 0x0202;
  2519. tss.cr3 = page_directory().cr3();
  2520. tss.esp = user_stack_address;
  2521. // NOTE: The stack needs to be 16-byte aligned.
  2522. thread->push_value_on_stack((u32)argument);
  2523. thread->push_value_on_stack(0);
  2524. thread->make_thread_specific_region({});
  2525. thread->set_state(Thread::State::Runnable);
  2526. return thread->tid();
  2527. }
  2528. void Process::sys$exit_thread(void* exit_value)
  2529. {
  2530. current->m_exit_value = exit_value;
  2531. cli();
  2532. if (&current->process().main_thread() == current) {
  2533. // FIXME: For POSIXy reasons, we should only sys$exit once *all* threads have exited.
  2534. sys$exit(0);
  2535. return;
  2536. }
  2537. current->set_should_die();
  2538. big_lock().unlock_if_locked();
  2539. current->die_if_needed();
  2540. ASSERT_NOT_REACHED();
  2541. }
  2542. int Process::sys$join_thread(int tid, void** exit_value)
  2543. {
  2544. if (exit_value && !validate_write_typed(exit_value))
  2545. return -EFAULT;
  2546. Thread* thread = nullptr;
  2547. for_each_thread([&](auto& child_thread) {
  2548. if (child_thread.tid() == tid) {
  2549. thread = &child_thread;
  2550. return IterationDecision::Break;
  2551. }
  2552. return IterationDecision::Continue;
  2553. });
  2554. if (!thread)
  2555. return -ESRCH;
  2556. if (thread == current)
  2557. return -EDEADLK;
  2558. if (thread->m_joinee == current)
  2559. return -EDEADLK;
  2560. ASSERT(thread->m_joiner != current);
  2561. if (thread->m_joiner)
  2562. return -EINVAL;
  2563. if (!thread->is_joinable())
  2564. return -EINVAL;
  2565. void* joinee_exit_value = nullptr;
  2566. // FIXME: pthread_join() should not be interruptable. Enforce this somehow?
  2567. auto result = current->block<Thread::JoinBlocker>(*thread, joinee_exit_value);
  2568. (void)result;
  2569. // NOTE: 'thread' is very possibly deleted at this point. Clear it just to be safe.
  2570. thread = nullptr;
  2571. if (exit_value)
  2572. *exit_value = joinee_exit_value;
  2573. return 0;
  2574. }
  2575. int Process::sys$gettid()
  2576. {
  2577. return current->tid();
  2578. }
  2579. int Process::sys$donate(int tid)
  2580. {
  2581. if (tid < 0)
  2582. return -EINVAL;
  2583. InterruptDisabler disabler;
  2584. Thread* beneficiary = nullptr;
  2585. for_each_thread([&](Thread& thread) {
  2586. if (thread.tid() == tid) {
  2587. beneficiary = &thread;
  2588. return IterationDecision::Break;
  2589. }
  2590. return IterationDecision::Continue;
  2591. });
  2592. if (!beneficiary)
  2593. return -ENOTHREAD;
  2594. Scheduler::donate_to(beneficiary, "sys$donate");
  2595. return 0;
  2596. }
  2597. int Process::sys$rename(const char* oldpath, const char* newpath)
  2598. {
  2599. if (!validate_read_str(oldpath))
  2600. return -EFAULT;
  2601. if (!validate_read_str(newpath))
  2602. return -EFAULT;
  2603. return VFS::the().rename(StringView(oldpath), StringView(newpath), current_directory());
  2604. }
  2605. int Process::sys$shm_open(const char* name, int flags, mode_t mode)
  2606. {
  2607. if (!validate_read_str(name))
  2608. return -EFAULT;
  2609. int fd = alloc_fd();
  2610. if (fd < 0)
  2611. return fd;
  2612. auto shm_or_error = SharedMemory::open(String(name), flags, mode);
  2613. if (shm_or_error.is_error())
  2614. return shm_or_error.error();
  2615. auto description = FileDescription::create(shm_or_error.value());
  2616. m_fds[fd].set(move(description), FD_CLOEXEC);
  2617. return fd;
  2618. }
  2619. int Process::sys$shm_unlink(const char* name)
  2620. {
  2621. if (!validate_read_str(name))
  2622. return -EFAULT;
  2623. return SharedMemory::unlink(String(name));
  2624. }
  2625. int Process::sys$ftruncate(int fd, off_t length)
  2626. {
  2627. auto* description = file_description(fd);
  2628. if (!description)
  2629. return -EBADF;
  2630. // FIXME: Check that fd is writable, otherwise EINVAL.
  2631. return description->truncate(length);
  2632. }
  2633. int Process::sys$watch_file(const char* path, int path_length)
  2634. {
  2635. if (!validate_read(path, path_length))
  2636. return -EFAULT;
  2637. auto custody_or_error = VFS::the().resolve_path({ path, path_length }, current_directory());
  2638. if (custody_or_error.is_error())
  2639. return custody_or_error.error();
  2640. auto& custody = custody_or_error.value();
  2641. auto& inode = custody->inode();
  2642. int fd = alloc_fd();
  2643. if (fd < 0)
  2644. return fd;
  2645. m_fds[fd].set(FileDescription::create(*InodeWatcher::create(inode)));
  2646. return fd;
  2647. }
  2648. int Process::sys$systrace(pid_t pid)
  2649. {
  2650. InterruptDisabler disabler;
  2651. auto* peer = Process::from_pid(pid);
  2652. if (!peer)
  2653. return -ESRCH;
  2654. if (peer->uid() != m_euid)
  2655. return -EACCES;
  2656. int fd = alloc_fd();
  2657. if (fd < 0)
  2658. return fd;
  2659. auto description = FileDescription::create(peer->ensure_tracer());
  2660. m_fds[fd].set(move(description), 0);
  2661. return fd;
  2662. }
  2663. int Process::sys$halt()
  2664. {
  2665. if (!is_superuser())
  2666. return -EPERM;
  2667. dbgprintf("acquiring FS locks...\n");
  2668. FS::lock_all();
  2669. dbgprintf("syncing mounted filesystems...\n");
  2670. FS::sync();
  2671. dbgprintf("attempting system shutdown...\n");
  2672. IO::out16(0x604, 0x2000);
  2673. return ESUCCESS;
  2674. }
  2675. int Process::sys$reboot()
  2676. {
  2677. if (!is_superuser())
  2678. return -EPERM;
  2679. dbgprintf("acquiring FS locks...\n");
  2680. FS::lock_all();
  2681. dbgprintf("syncing mounted filesystems...\n");
  2682. FS::sync();
  2683. dbgprintf("attempting reboot via KB Controller...\n");
  2684. IO::out8(0x64, 0xFE);
  2685. return ESUCCESS;
  2686. }
  2687. int Process::sys$mount(const char* device_path, const char* mountpoint, const char* fstype)
  2688. {
  2689. if (!is_superuser())
  2690. return -EPERM;
  2691. if (!validate_read_str(device_path) || !validate_read_str(mountpoint) || !validate_read_str(fstype))
  2692. return -EFAULT;
  2693. dbg() << "mount " << fstype << ": device " << device_path << " @ " << mountpoint;
  2694. auto custody_or_error = VFS::the().resolve_path(mountpoint, current_directory());
  2695. if (custody_or_error.is_error())
  2696. return custody_or_error.error();
  2697. auto& mountpoint_custody = custody_or_error.value();
  2698. RefPtr<FS> fs { nullptr };
  2699. if (strcmp(fstype, "ext2") == 0 || strcmp(fstype, "Ext2FS") == 0) {
  2700. auto metadata_or_error = VFS::the().lookup_metadata(device_path, current_directory());
  2701. if (metadata_or_error.is_error())
  2702. return metadata_or_error.error();
  2703. auto major = metadata_or_error.value().major_device;
  2704. auto minor = metadata_or_error.value().minor_device;
  2705. auto* device = Device::get_device(major, minor);
  2706. if (!device) {
  2707. dbg() << "mount: device (" << major << "," << minor << ") not found";
  2708. return -ENODEV;
  2709. }
  2710. if (!device->is_disk_device()) {
  2711. dbg() << "mount: device (" << major << "," << minor << ") is not a DiskDevice";
  2712. return -ENODEV;
  2713. }
  2714. auto& disk_device = static_cast<DiskDevice&>(*device);
  2715. dbg() << "mount: attempting to mount device (" << major << "," << minor << ") on " << mountpoint;
  2716. fs = Ext2FS::create(disk_device);
  2717. } else if (strcmp(fstype, "proc") == 0 || strcmp(fstype, "ProcFS") == 0)
  2718. fs = ProcFS::create();
  2719. else if (strcmp(fstype, "devpts") == 0 || strcmp(fstype, "DevPtsFS") == 0)
  2720. fs = DevPtsFS::create();
  2721. else if (strcmp(fstype, "tmp") == 0 || strcmp(fstype, "TmpFS") == 0)
  2722. fs = TmpFS::create();
  2723. else
  2724. return -ENODEV;
  2725. if (!fs->initialize()) {
  2726. dbg() << "mount: failed to initialize " << fstype << " filesystem on " << device_path;
  2727. return -ENODEV;
  2728. }
  2729. auto result = VFS::the().mount(fs.release_nonnull(), mountpoint_custody);
  2730. dbg() << "mount: successfully mounted " << device_path << " on " << mountpoint;
  2731. return result;
  2732. }
  2733. int Process::sys$umount(const char* mountpoint)
  2734. {
  2735. if (!is_superuser())
  2736. return -EPERM;
  2737. if (!validate_read_str(mountpoint))
  2738. return -EFAULT;
  2739. auto metadata_or_error = VFS::the().lookup_metadata(mountpoint, current_directory());
  2740. if (metadata_or_error.is_error())
  2741. return metadata_or_error.error();
  2742. auto guest_inode_id = metadata_or_error.value().inode;
  2743. return VFS::the().unmount(guest_inode_id);
  2744. }
  2745. ProcessTracer& Process::ensure_tracer()
  2746. {
  2747. if (!m_tracer)
  2748. m_tracer = ProcessTracer::create(m_pid);
  2749. return *m_tracer;
  2750. }
  2751. void Process::FileDescriptionAndFlags::clear()
  2752. {
  2753. description = nullptr;
  2754. flags = 0;
  2755. }
  2756. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& d, u32 f)
  2757. {
  2758. description = move(d);
  2759. flags = f;
  2760. }
  2761. int Process::sys$mknod(const char* pathname, mode_t mode, dev_t dev)
  2762. {
  2763. if (!validate_read_str(pathname))
  2764. return -EFAULT;
  2765. return VFS::the().mknod(StringView(pathname), mode, dev, current_directory());
  2766. }
  2767. int Process::sys$dump_backtrace()
  2768. {
  2769. dump_backtrace();
  2770. return 0;
  2771. }
  2772. int Process::sys$dbgputch(u8 ch)
  2773. {
  2774. IO::out8(0xe9, ch);
  2775. return 0;
  2776. }
  2777. int Process::sys$dbgputstr(const u8* characters, int length)
  2778. {
  2779. if (!length)
  2780. return 0;
  2781. if (!validate_read(characters, length))
  2782. return -EFAULT;
  2783. for (int i = 0; i < length; ++i)
  2784. IO::out8(0xe9, characters[i]);
  2785. return 0;
  2786. }
  2787. KBuffer Process::backtrace(ProcessInspectionHandle& handle) const
  2788. {
  2789. KBufferBuilder builder;
  2790. for_each_thread([&](Thread& thread) {
  2791. builder.appendf("Thread %d:\n", thread.tid());
  2792. builder.append(thread.backtrace(handle));
  2793. return IterationDecision::Continue;
  2794. });
  2795. return builder.build();
  2796. }
  2797. int Process::sys$set_process_icon(int icon_id)
  2798. {
  2799. LOCKER(shared_buffers().lock());
  2800. auto it = shared_buffers().resource().find(icon_id);
  2801. if (it == shared_buffers().resource().end())
  2802. return -EINVAL;
  2803. auto& shared_buffer = *(*it).value;
  2804. if (!shared_buffer.is_shared_with(m_pid))
  2805. return -EPERM;
  2806. m_icon_id = icon_id;
  2807. return 0;
  2808. }
  2809. int Process::sys$get_process_name(char* buffer, int buffer_size)
  2810. {
  2811. if (buffer_size <= 0)
  2812. return -EINVAL;
  2813. if (!validate_write(buffer, buffer_size))
  2814. return -EFAULT;
  2815. if (m_name.length() >= buffer_size)
  2816. return -ENAMETOOLONG;
  2817. strncpy(buffer, m_name.characters(), buffer_size);
  2818. return 0;
  2819. }
  2820. // We don't use the flag yet, but we could use it for distinguishing
  2821. // random source like Linux, unlike the OpenBSD equivalent. However, if we
  2822. // do, we should be able of the caveats that Linux has dealt with.
  2823. int Process::sys$getrandom(void* buffer, size_t buffer_size, unsigned int flags __attribute__((unused)))
  2824. {
  2825. if (buffer_size <= 0)
  2826. return -EINVAL;
  2827. if (!validate_write(buffer, buffer_size))
  2828. return -EFAULT;
  2829. // We prefer to get whole words of entropy.
  2830. // If the length is unaligned, we can work with bytes instead.
  2831. // Mask out the bottom two bits for words.
  2832. size_t words_len = buffer_size & ~3;
  2833. if (words_len) {
  2834. uint32_t* words = (uint32_t*)buffer;
  2835. for (size_t i = 0; i < words_len / 4; i++)
  2836. words[i] = RandomDevice::random_value();
  2837. }
  2838. // The remaining non-whole word bytes we can fill in.
  2839. size_t bytes_len = buffer_size & 3;
  2840. if (bytes_len) {
  2841. uint8_t* bytes = (uint8_t*)buffer + words_len;
  2842. // Get a whole word of entropy to use.
  2843. uint32_t word = RandomDevice::random_value();
  2844. for (size_t i = 0; i < bytes_len; i++)
  2845. bytes[i] = ((uint8_t*)&word)[i];
  2846. }
  2847. return 0;
  2848. }
  2849. int Process::sys$setkeymap(char* map, char* shift_map, char* alt_map)
  2850. {
  2851. if (!is_superuser())
  2852. return -EPERM;
  2853. if (!validate_read(map, 0x80))
  2854. return -EFAULT;
  2855. if (!validate_read(shift_map, 0x80))
  2856. return -EFAULT;
  2857. if (!validate_read(alt_map, 0x80))
  2858. return -EFAULT;
  2859. KeyboardDevice::the().set_maps(map, shift_map, alt_map);
  2860. return 0;
  2861. }
  2862. int Process::sys$clock_gettime(clockid_t clock_id, timespec* ts)
  2863. {
  2864. if (!validate_write_typed(ts))
  2865. return -EFAULT;
  2866. switch (clock_id) {
  2867. case CLOCK_MONOTONIC:
  2868. ts->tv_sec = g_uptime / TICKS_PER_SECOND;
  2869. ts->tv_nsec = (g_uptime % TICKS_PER_SECOND) * 1000000;
  2870. break;
  2871. default:
  2872. return -EINVAL;
  2873. }
  2874. return 0;
  2875. }
  2876. int Process::sys$clock_nanosleep(const Syscall::SC_clock_nanosleep_params* params)
  2877. {
  2878. if (!validate_read_typed(params))
  2879. return -EFAULT;
  2880. auto& [clock_id, flags, requested_sleep, remaining_sleep] = *params;
  2881. if (requested_sleep && !validate_read_typed(requested_sleep))
  2882. return -EFAULT;
  2883. if (remaining_sleep && !validate_write_typed(remaining_sleep))
  2884. return -EFAULT;
  2885. bool is_absolute = flags & TIMER_ABSTIME;
  2886. switch (clock_id) {
  2887. case CLOCK_MONOTONIC: {
  2888. u64 wakeup_time;
  2889. if (is_absolute) {
  2890. u64 time_to_wake = (requested_sleep->tv_sec * 1000 + requested_sleep->tv_nsec / 1000000);
  2891. wakeup_time = current->sleep_until(time_to_wake);
  2892. } else {
  2893. u32 ticks_to_sleep = (requested_sleep->tv_sec * 1000 + requested_sleep->tv_nsec / 1000000);
  2894. if (!ticks_to_sleep)
  2895. return 0;
  2896. wakeup_time = current->sleep(ticks_to_sleep);
  2897. }
  2898. if (wakeup_time > g_uptime) {
  2899. u32 ticks_left = wakeup_time - g_uptime;
  2900. if (!is_absolute && remaining_sleep) {
  2901. remaining_sleep->tv_sec = ticks_left / TICKS_PER_SECOND;
  2902. ticks_left -= remaining_sleep->tv_sec * TICKS_PER_SECOND;
  2903. remaining_sleep->tv_nsec = ticks_left * 1000000;
  2904. }
  2905. return -EINTR;
  2906. }
  2907. return 0;
  2908. }
  2909. default:
  2910. return -EINVAL;
  2911. }
  2912. }
  2913. int Process::sys$sync()
  2914. {
  2915. VFS::the().sync();
  2916. return 0;
  2917. }
  2918. int Process::sys$putch(char ch)
  2919. {
  2920. Console::the().put_char(ch);
  2921. return 0;
  2922. }
  2923. int Process::sys$yield()
  2924. {
  2925. current->yield_without_holding_big_lock();
  2926. return 0;
  2927. }
  2928. int Process::sys$beep()
  2929. {
  2930. Scheduler::beep();
  2931. return 0;
  2932. }
  2933. extern "C" void outside_func()
  2934. {
  2935. kprintf("I'm the outside func!\n");
  2936. }
  2937. static u32 find_kernel_symbol(const StringView& name)
  2938. {
  2939. if (name == "kprintf")
  2940. return (u32)kprintf;
  2941. if (name == "outside_func")
  2942. return (u32)outside_func;
  2943. ASSERT_NOT_REACHED();
  2944. }
  2945. int Process::sys$module_load(const char* path, size_t path_length)
  2946. {
  2947. #if 0
  2948. if (!is_superuser())
  2949. return -EPERM;
  2950. #endif
  2951. if (!validate_read(path, path_length))
  2952. return -EFAULT;
  2953. auto description_or_error = VFS::the().open(path, 0, 0, current_directory());
  2954. if (description_or_error.is_error())
  2955. return description_or_error.error();
  2956. auto& description = description_or_error.value();
  2957. auto payload = description->read_entire_file();
  2958. auto storage = KBuffer::create_with_size(payload.size());
  2959. memcpy(storage.data(), payload.data(), payload.size());
  2960. payload.clear();
  2961. // FIXME: ELFImage should really be taking a size argument as well...
  2962. auto elf_image = make<ELFImage>(storage.data());
  2963. if (!elf_image->parse())
  2964. return -ENOEXEC;
  2965. ModuleInitPtr module_init = nullptr;
  2966. HashMap<String, u8*> section_storage_by_name;
  2967. auto module = make<Module>();
  2968. module->name = "FIXME";
  2969. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) {
  2970. auto section_storage = KBuffer::copy(section.raw_data(), section.size());
  2971. section_storage_by_name.set(section.name(), section_storage.data());
  2972. module->sections.append(move(section_storage));
  2973. return IterationDecision::Continue;
  2974. });
  2975. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) {
  2976. auto* section_storage = section_storage_by_name.get(section.name()).value_or(nullptr);
  2977. ASSERT(section_storage);
  2978. section.relocations().for_each_relocation([&](const ELFImage::Relocation& relocation) {
  2979. auto& patch_ptr = *reinterpret_cast<ptrdiff_t*>(section_storage + relocation.offset());
  2980. switch (relocation.type()) {
  2981. case R_386_PC32: {
  2982. // PC-relative relocation
  2983. dbg() << "PC-relative relocation: " << relocation.symbol().name();
  2984. u32 symbol_address = find_kernel_symbol(relocation.symbol().name());
  2985. dbg() << " Symbol address: " << (void*)symbol_address;
  2986. ptrdiff_t relative_offset = (char*)symbol_address - ((char*)&patch_ptr + 4);
  2987. patch_ptr = relative_offset;
  2988. break;
  2989. }
  2990. case R_386_32: // Absolute relocation
  2991. dbg() << "Absolute relocation: '" << relocation.symbol().name() << "' value:" << relocation.symbol().value() << ", index:" << relocation.symbol_index();
  2992. auto* section_storage_containing_symbol = section_storage_by_name.get(relocation.symbol().section().name()).value_or(nullptr);
  2993. ASSERT(section_storage_containing_symbol);
  2994. patch_ptr += (ptrdiff_t)(section_storage_containing_symbol + relocation.symbol().value());
  2995. break;
  2996. }
  2997. return IterationDecision::Continue;
  2998. });
  2999. return IterationDecision::Continue;
  3000. });
  3001. auto* text_base = section_storage_by_name.get(".text").value_or(nullptr);
  3002. if (!text_base) {
  3003. dbg() << "No .text section found in module!";
  3004. return -EINVAL;
  3005. }
  3006. elf_image->for_each_symbol([&](const ELFImage::Symbol& symbol) {
  3007. dbg() << " - " << symbol.type() << " '" << symbol.name() << "' @ " << (void*)symbol.value() << ", size=" << symbol.size();
  3008. if (!strcmp(symbol.name(), "module_init")) {
  3009. module_init = (ModuleInitPtr)(text_base + symbol.value());
  3010. }
  3011. return IterationDecision::Continue;
  3012. });
  3013. if (!module_init)
  3014. return -EINVAL;
  3015. module_init();
  3016. auto name = module->name;
  3017. g_modules->set(name, move(module));
  3018. return 0;
  3019. }
  3020. int Process::sys$module_unload(const char* name, size_t name_length)
  3021. {
  3022. #if 0
  3023. if (!is_superuser())
  3024. return -EPERM;
  3025. #endif
  3026. if (!validate_read(name, name_length))
  3027. return -EFAULT;
  3028. // FIXME: Implement this syscall!
  3029. return 0;
  3030. }