Process.cpp 90 KB

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