Process.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484
  1. #include <AK/Types.h>
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "StdLib.h"
  5. #include "i386.h"
  6. #include <Kernel/FileSystem/FileDescriptor.h>
  7. #include <Kernel/FileSystem/VirtualFileSystem.h>
  8. #include <Kernel/Devices/NullDevice.h>
  9. #include <Kernel/ELF/ELFLoader.h>
  10. #include <Kernel/VM/MemoryManager.h>
  11. #include "i8253.h"
  12. #include "RTC.h"
  13. #include <AK/StdLibExtras.h>
  14. #include <LibC/signal_numbers.h>
  15. #include <LibC/errno_numbers.h>
  16. #include "Syscall.h"
  17. #include "Scheduler.h"
  18. #include <Kernel/FileSystem/FIFO.h>
  19. #include "KSyms.h"
  20. #include <Kernel/Net/Socket.h>
  21. #include <Kernel/TTY/MasterPTY.h>
  22. #include <Kernel/ELF/exec_elf.h>
  23. #include <AK/StringBuilder.h>
  24. #include <Kernel/SharedMemory.h>
  25. //#define DEBUG_IO
  26. //#define TASK_DEBUG
  27. //#define FORK_DEBUG
  28. #define SIGNAL_DEBUG
  29. //#define SHARED_BUFFER_DEBUG
  30. static pid_t next_pid;
  31. InlineLinkedList<Process>* g_processes;
  32. static String* s_hostname;
  33. static Lock* s_hostname_lock;
  34. void Process::initialize()
  35. {
  36. next_pid = 0;
  37. g_processes = new InlineLinkedList<Process>;
  38. s_hostname = new String("courage");
  39. s_hostname_lock = new Lock;
  40. }
  41. Vector<pid_t> Process::all_pids()
  42. {
  43. Vector<pid_t> pids;
  44. InterruptDisabler disabler;
  45. pids.ensure_capacity(g_processes->size_slow());
  46. for (auto* process = g_processes->head(); process; process = process->next())
  47. pids.append(process->pid());
  48. return pids;
  49. }
  50. Vector<Process*> Process::all_processes()
  51. {
  52. Vector<Process*> processes;
  53. InterruptDisabler disabler;
  54. processes.ensure_capacity(g_processes->size_slow());
  55. for (auto* process = g_processes->head(); process; process = process->next())
  56. processes.append(process);
  57. return processes;
  58. }
  59. bool Process::in_group(gid_t gid) const
  60. {
  61. return m_gids.contains(gid);
  62. }
  63. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  64. {
  65. size = PAGE_ROUND_UP(size);
  66. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  67. if (laddr.is_null()) {
  68. laddr = m_next_region;
  69. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  70. }
  71. laddr.mask(0xfffff000);
  72. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  73. MM.map_region(*this, *m_regions.last());
  74. if (commit)
  75. m_regions.last()->commit();
  76. return m_regions.last().ptr();
  77. }
  78. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  79. {
  80. size = PAGE_ROUND_UP(size);
  81. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  82. if (laddr.is_null()) {
  83. laddr = m_next_region;
  84. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  85. }
  86. laddr.mask(0xfffff000);
  87. m_regions.append(adopt(*new Region(laddr, size, move(inode), move(name), is_readable, is_writable)));
  88. MM.map_region(*this, *m_regions.last());
  89. return m_regions.last().ptr();
  90. }
  91. Region* Process::allocate_region_with_vmo(LinearAddress laddr, size_t size, Retained<VMObject>&& vmo, size_t offset_in_vmo, String&& name, bool is_readable, bool is_writable)
  92. {
  93. size = PAGE_ROUND_UP(size);
  94. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  95. if (laddr.is_null()) {
  96. laddr = m_next_region;
  97. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  98. }
  99. laddr.mask(0xfffff000);
  100. offset_in_vmo &= PAGE_MASK;
  101. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  102. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  103. MM.map_region(*this, *m_regions.last());
  104. return m_regions.last().ptr();
  105. }
  106. bool Process::deallocate_region(Region& region)
  107. {
  108. InterruptDisabler disabler;
  109. for (int i = 0; i < m_regions.size(); ++i) {
  110. if (m_regions[i] == &region) {
  111. MM.unmap_region(region);
  112. m_regions.remove(i);
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  119. {
  120. size = PAGE_ROUND_UP(size);
  121. for (auto& region : m_regions) {
  122. if (region->laddr() == laddr && region->size() == size)
  123. return region.ptr();
  124. }
  125. return nullptr;
  126. }
  127. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  128. {
  129. if (!validate_read_str(name))
  130. return -EFAULT;
  131. auto* region = region_from_range(LinearAddress((dword)addr), size);
  132. if (!region)
  133. return -EINVAL;
  134. region->set_name(String(name));
  135. return 0;
  136. }
  137. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  138. {
  139. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  140. return (void*)-EFAULT;
  141. void* addr = (void*)params->addr;
  142. size_t size = params->size;
  143. int prot = params->prot;
  144. int flags = params->flags;
  145. int fd = params->fd;
  146. off_t offset = params->offset;
  147. if (size == 0)
  148. return (void*)-EINVAL;
  149. if ((dword)addr & ~PAGE_MASK)
  150. return (void*)-EINVAL;
  151. if (flags & MAP_ANONYMOUS) {
  152. auto* region = allocate_region(LinearAddress((dword)addr), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  153. if (!region)
  154. return (void*)-ENOMEM;
  155. if (flags & MAP_SHARED)
  156. region->set_shared(true);
  157. return region->laddr().as_ptr();
  158. }
  159. if (offset & ~PAGE_MASK)
  160. return (void*)-EINVAL;
  161. auto* descriptor = file_descriptor(fd);
  162. if (!descriptor)
  163. return (void*)-EBADF;
  164. if (!descriptor->supports_mmap())
  165. return (void*)-ENODEV;
  166. auto* region = descriptor->mmap(*this, LinearAddress((dword)addr), offset, size, prot);
  167. if (!region)
  168. return (void*)-ENOMEM;
  169. if (flags & MAP_SHARED)
  170. region->set_shared(true);
  171. return region->laddr().as_ptr();
  172. }
  173. int Process::sys$munmap(void* addr, size_t size)
  174. {
  175. auto* region = region_from_range(LinearAddress((dword)addr), size);
  176. if (!region)
  177. return -EINVAL;
  178. if (!deallocate_region(*region))
  179. return -EINVAL;
  180. return 0;
  181. }
  182. int Process::sys$gethostname(char* buffer, ssize_t size)
  183. {
  184. if (size < 0)
  185. return -EINVAL;
  186. if (!validate_write(buffer, size))
  187. return -EFAULT;
  188. LOCKER(*s_hostname_lock);
  189. if (size < (s_hostname->length() + 1))
  190. return -ENAMETOOLONG;
  191. strcpy(buffer, s_hostname->characters());
  192. return 0;
  193. }
  194. Process* Process::fork(RegisterDump& regs)
  195. {
  196. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copy_ref(), m_executable.copy_ref(), m_tty, this);
  197. if (!child)
  198. return nullptr;
  199. #ifdef FORK_DEBUG
  200. dbgprintf("fork: child=%p\n", child);
  201. #endif
  202. for (auto& region : m_regions) {
  203. #ifdef FORK_DEBUG
  204. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name().characters(), region->laddr().get());
  205. #endif
  206. auto cloned_region = region->clone();
  207. child->m_regions.append(move(cloned_region));
  208. MM.map_region(*child, *child->m_regions.last());
  209. }
  210. for (auto gid : m_gids)
  211. child->m_gids.set(gid);
  212. auto& child_tss = child->main_thread().m_tss;
  213. child_tss.eax = 0; // fork() returns 0 in the child :^)
  214. child_tss.ebx = regs.ebx;
  215. child_tss.ecx = regs.ecx;
  216. child_tss.edx = regs.edx;
  217. child_tss.ebp = regs.ebp;
  218. child_tss.esp = regs.esp_if_crossRing;
  219. child_tss.esi = regs.esi;
  220. child_tss.edi = regs.edi;
  221. child_tss.eflags = regs.eflags;
  222. child_tss.eip = regs.eip;
  223. child_tss.cs = regs.cs;
  224. child_tss.ds = regs.ds;
  225. child_tss.es = regs.es;
  226. child_tss.fs = regs.fs;
  227. child_tss.gs = regs.gs;
  228. child_tss.ss = regs.ss_if_crossRing;
  229. #ifdef FORK_DEBUG
  230. 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);
  231. #endif
  232. {
  233. InterruptDisabler disabler;
  234. g_processes->prepend(child);
  235. }
  236. #ifdef TASK_DEBUG
  237. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child_tss.eip);
  238. #endif
  239. child->main_thread().set_state(Thread::State::Skip1SchedulerPass);
  240. return child;
  241. }
  242. pid_t Process::sys$fork(RegisterDump& regs)
  243. {
  244. auto* child = fork(regs);
  245. ASSERT(child);
  246. return child->pid();
  247. }
  248. int Process::do_exec(String path, Vector<String> arguments, Vector<String> environment)
  249. {
  250. ASSERT(is_ring3());
  251. dbgprintf("%s(%d) do_exec: thread_count() = %d\n", m_name.characters(), m_pid, thread_count());
  252. // FIXME(Thread): Kill any threads the moment we commit to the exec().
  253. ASSERT(thread_count() == 1);
  254. auto parts = path.split('/');
  255. if (parts.is_empty())
  256. return -ENOENT;
  257. auto result = VFS::the().open(path.view(), 0, 0, cwd_inode());
  258. if (result.is_error())
  259. return result.error();
  260. auto descriptor = result.value();
  261. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  262. return -EACCES;
  263. if (!descriptor->metadata().size) {
  264. return -ENOTIMPL;
  265. }
  266. dword entry_eip = 0;
  267. // FIXME: Is there a race here?
  268. auto old_page_directory = move(m_page_directory);
  269. m_page_directory = PageDirectory::create();
  270. #ifdef MM_DEBUG
  271. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  272. #endif
  273. ProcessPagingScope paging_scope(*this);
  274. auto vmo = VMObject::create_file_backed(descriptor->inode());
  275. #if 0
  276. // FIXME: I would like to do this, but it would instantiate all the damn inodes.
  277. vmo->set_name(descriptor->absolute_path());
  278. #else
  279. vmo->set_name("ELF image");
  280. #endif
  281. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "executable", true, false);
  282. if (this != &current->process()) {
  283. // FIXME: Don't force-load the entire executable at once, let the on-demand pager take care of it.
  284. bool success = region->page_in();
  285. ASSERT(success);
  286. }
  287. {
  288. // Okay, here comes the sleight of hand, pay close attention..
  289. auto old_regions = move(m_regions);
  290. m_regions.append(*region);
  291. ELFLoader loader(region->laddr().as_ptr());
  292. loader.map_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable, const String& name) {
  293. ASSERT(size);
  294. ASSERT(alignment == PAGE_SIZE);
  295. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  296. (void) allocate_region_with_vmo(laddr, size, vmo.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  297. return laddr.as_ptr();
  298. };
  299. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  300. ASSERT(size);
  301. ASSERT(alignment == PAGE_SIZE);
  302. size += laddr.get() & 0xfff;
  303. laddr.mask(0xffff000);
  304. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  305. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  306. return laddr.as_ptr();
  307. };
  308. bool success = loader.load();
  309. if (!success || !loader.entry().get()) {
  310. m_page_directory = move(old_page_directory);
  311. // FIXME: RAII this somehow instead.
  312. ASSERT(&current->process() == this);
  313. MM.enter_process_paging_scope(*this);
  314. m_regions = move(old_regions);
  315. kprintf("do_exec: Failure loading %s\n", path.characters());
  316. return -ENOEXEC;
  317. }
  318. entry_eip = loader.entry().get();
  319. }
  320. kfree(current->m_kernel_stack_for_signal_handler);
  321. current->m_kernel_stack_for_signal_handler = nullptr;
  322. current->m_signal_stack_user_region = nullptr;
  323. current->set_default_signal_dispositions();
  324. current->m_signal_mask = 0;
  325. current->m_pending_signals = 0;
  326. for (int i = 0; i < m_fds.size(); ++i) {
  327. auto& daf = m_fds[i];
  328. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  329. daf.descriptor->close();
  330. daf = { };
  331. }
  332. }
  333. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  334. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  335. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  336. if (&current->process() == this)
  337. cli();
  338. Scheduler::prepare_to_modify_tss(main_thread());
  339. m_name = parts.take_last();
  340. // ss0 sp!!!!!!!!!
  341. dword old_esp0 = main_thread().m_tss.esp0;
  342. memset(&main_thread().m_tss, 0, sizeof(main_thread().m_tss));
  343. main_thread().m_tss.eflags = 0x0202;
  344. main_thread().m_tss.eip = entry_eip;
  345. main_thread().m_tss.cs = 0x1b;
  346. main_thread().m_tss.ds = 0x23;
  347. main_thread().m_tss.es = 0x23;
  348. main_thread().m_tss.fs = 0x23;
  349. main_thread().m_tss.gs = 0x23;
  350. main_thread().m_tss.ss = 0x23;
  351. main_thread().m_tss.cr3 = page_directory().cr3();
  352. main_thread().make_userspace_stack_for_main_thread(move(arguments), move(environment));
  353. main_thread().m_tss.ss0 = 0x10;
  354. main_thread().m_tss.esp0 = old_esp0;
  355. main_thread().m_tss.ss2 = m_pid;
  356. m_executable = descriptor->inode();
  357. if (descriptor->metadata().is_setuid())
  358. m_euid = descriptor->metadata().uid;
  359. if (descriptor->metadata().is_setgid())
  360. m_egid = descriptor->metadata().gid;
  361. #ifdef TASK_DEBUG
  362. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), main_thread().tss().eip);
  363. #endif
  364. main_thread().set_state(Thread::State::Skip1SchedulerPass);
  365. return 0;
  366. }
  367. int Process::exec(String path, Vector<String> arguments, Vector<String> environment)
  368. {
  369. // The bulk of exec() is done by do_exec(), which ensures that all locals
  370. // are cleaned up by the time we yield-teleport below.
  371. int rc = do_exec(move(path), move(arguments), move(environment));
  372. if (rc < 0)
  373. return rc;
  374. if (&current->process() == this) {
  375. Scheduler::yield();
  376. ASSERT_NOT_REACHED();
  377. }
  378. return 0;
  379. }
  380. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  381. {
  382. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  383. // On success, the kernel stack will be lost.
  384. if (!validate_read_str(filename))
  385. return -EFAULT;
  386. if (argv) {
  387. if (!validate_read_typed(argv))
  388. return -EFAULT;
  389. for (size_t i = 0; argv[i]; ++i) {
  390. if (!validate_read_str(argv[i]))
  391. return -EFAULT;
  392. }
  393. }
  394. if (envp) {
  395. if (!validate_read_typed(envp))
  396. return -EFAULT;
  397. for (size_t i = 0; envp[i]; ++i) {
  398. if (!validate_read_str(envp[i]))
  399. return -EFAULT;
  400. }
  401. }
  402. String path(filename);
  403. Vector<String> arguments;
  404. Vector<String> environment;
  405. {
  406. auto parts = path.split('/');
  407. if (argv) {
  408. for (size_t i = 0; argv[i]; ++i) {
  409. arguments.append(argv[i]);
  410. }
  411. } else {
  412. arguments.append(parts.last());
  413. }
  414. if (envp) {
  415. for (size_t i = 0; envp[i]; ++i)
  416. environment.append(envp[i]);
  417. }
  418. }
  419. int rc = exec(move(path), move(arguments), move(environment));
  420. ASSERT(rc < 0); // We should never continue after a successful exec!
  421. return rc;
  422. }
  423. 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)
  424. {
  425. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  426. auto parts = path.split('/');
  427. if (arguments.is_empty()) {
  428. arguments.append(parts.last());
  429. }
  430. RetainPtr<Inode> cwd;
  431. {
  432. InterruptDisabler disabler;
  433. if (auto* parent = Process::from_pid(parent_pid))
  434. cwd = parent->m_cwd.copy_ref();
  435. }
  436. if (!cwd)
  437. cwd = VFS::the().root_inode();
  438. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  439. error = process->exec(path, move(arguments), move(environment));
  440. if (error != 0) {
  441. delete process;
  442. return nullptr;
  443. }
  444. {
  445. InterruptDisabler disabler;
  446. g_processes->prepend(process);
  447. }
  448. #ifdef TASK_DEBUG
  449. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->main_thread().tss().eip);
  450. #endif
  451. error = 0;
  452. return process;
  453. }
  454. Process* Process::create_kernel_process(String&& name, void (*e)())
  455. {
  456. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  457. process->main_thread().tss().eip = (dword)e;
  458. if (process->pid() != 0) {
  459. InterruptDisabler disabler;
  460. g_processes->prepend(process);
  461. #ifdef TASK_DEBUG
  462. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->main_thread().tss().eip);
  463. #endif
  464. }
  465. process->main_thread().set_state(Thread::State::Runnable);
  466. return process;
  467. }
  468. Process::Process(String&& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RetainPtr<Inode>&& cwd, RetainPtr<Inode>&& executable, TTY* tty, Process* fork_parent)
  469. : m_name(move(name))
  470. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  471. , m_uid(uid)
  472. , m_gid(gid)
  473. , m_euid(uid)
  474. , m_egid(gid)
  475. , m_ring(ring)
  476. , m_cwd(move(cwd))
  477. , m_executable(move(executable))
  478. , m_tty(tty)
  479. , m_ppid(ppid)
  480. , m_big_lock("Big Process Lock")
  481. {
  482. dbgprintf("Process: New process PID=%u with name=%s\n", m_pid, m_name.characters());
  483. m_page_directory = PageDirectory::create();
  484. #ifdef MM_DEBUG
  485. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  486. #endif
  487. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the main thread in the new process.
  488. if (fork_parent)
  489. m_main_thread = current->clone(*this);
  490. else
  491. m_main_thread = new Thread(*this);
  492. m_gids.set(m_gid);
  493. if (fork_parent) {
  494. m_sid = fork_parent->m_sid;
  495. m_pgid = fork_parent->m_pgid;
  496. } else {
  497. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  498. InterruptDisabler disabler;
  499. if (auto* parent = Process::from_pid(m_ppid)) {
  500. m_sid = parent->m_sid;
  501. m_pgid = parent->m_pgid;
  502. }
  503. }
  504. if (fork_parent) {
  505. m_fds.resize(fork_parent->m_fds.size());
  506. for (int i = 0; i < fork_parent->m_fds.size(); ++i) {
  507. if (!fork_parent->m_fds[i].descriptor)
  508. continue;
  509. #ifdef FORK_DEBUG
  510. dbgprintf("fork: cloning fd %u... (%p) istty? %u\n", i, fork_parent->m_fds[i].descriptor.ptr(), fork_parent->m_fds[i].descriptor->is_tty());
  511. #endif
  512. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  513. m_fds[i].flags = fork_parent->m_fds[i].flags;
  514. }
  515. } else {
  516. m_fds.resize(m_max_open_file_descriptors);
  517. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  518. m_fds[0].set(*device_to_use_as_tty.open(O_RDONLY).value());
  519. m_fds[1].set(*device_to_use_as_tty.open(O_WRONLY).value());
  520. m_fds[2].set(*device_to_use_as_tty.open(O_WRONLY).value());
  521. }
  522. if (fork_parent)
  523. m_next_region = fork_parent->m_next_region;
  524. else
  525. m_next_region = LinearAddress(0x10000000);
  526. if (fork_parent) {
  527. m_sid = fork_parent->m_sid;
  528. m_pgid = fork_parent->m_pgid;
  529. m_umask = fork_parent->m_umask;
  530. }
  531. }
  532. Process::~Process()
  533. {
  534. dbgprintf("~Process{%p} name=%s pid=%d, m_fds=%d\n", this, m_name.characters(), pid(), m_fds.size());
  535. delete m_main_thread;
  536. m_main_thread = nullptr;
  537. }
  538. void Process::dump_regions()
  539. {
  540. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  541. kprintf("BEGIN END SIZE NAME\n");
  542. for (auto& region : m_regions) {
  543. kprintf("%x -- %x %x %s\n",
  544. region->laddr().get(),
  545. region->laddr().offset(region->size() - 1).get(),
  546. region->size(),
  547. region->name().characters());
  548. }
  549. }
  550. void Process::sys$exit(int status)
  551. {
  552. cli();
  553. #ifdef TASK_DEBUG
  554. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  555. #endif
  556. m_termination_status = status;
  557. m_termination_signal = 0;
  558. die();
  559. ASSERT_NOT_REACHED();
  560. }
  561. void Process::create_signal_trampolines_if_needed()
  562. {
  563. if (!m_return_to_ring3_from_signal_trampoline.is_null())
  564. return;
  565. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  566. // FIXME: Remap as read-only after setup.
  567. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "Signal trampolines", true, true);
  568. m_return_to_ring3_from_signal_trampoline = region->laddr();
  569. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.as_ptr();
  570. *code_ptr++ = 0x58; // pop eax (Argument to signal handler (ignored here))
  571. *code_ptr++ = 0x5a; // pop edx (Original signal mask to restore)
  572. *code_ptr++ = 0xb8; // mov eax, <dword>
  573. *(dword*)code_ptr = Syscall::SC_restore_signal_mask;
  574. code_ptr += sizeof(dword);
  575. *code_ptr++ = 0xcd; // int 0x82
  576. *code_ptr++ = 0x82;
  577. *code_ptr++ = 0x83; // add esp, (stack alignment padding)
  578. *code_ptr++ = 0xc4;
  579. *code_ptr++ = sizeof(dword) * 3;
  580. *code_ptr++ = 0x61; // popa
  581. *code_ptr++ = 0x9d; // popf
  582. *code_ptr++ = 0xc3; // ret
  583. *code_ptr++ = 0x0f; // ud2
  584. *code_ptr++ = 0x0b;
  585. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  586. *code_ptr++ = 0x58; // pop eax (Argument to signal handler (ignored here))
  587. *code_ptr++ = 0x5a; // pop edx (Original signal mask to restore)
  588. *code_ptr++ = 0xb8; // mov eax, <dword>
  589. *(dword*)code_ptr = Syscall::SC_restore_signal_mask;
  590. code_ptr += sizeof(dword);
  591. *code_ptr++ = 0xcd; // int 0x82
  592. // NOTE: Stack alignment padding doesn't matter when returning to ring0.
  593. // Nothing matters really, as we're returning by replacing the entire TSS.
  594. *code_ptr++ = 0x82;
  595. *code_ptr++ = 0xb8; // mov eax, <dword>
  596. *(dword*)code_ptr = Syscall::SC_sigreturn;
  597. code_ptr += sizeof(dword);
  598. *code_ptr++ = 0xcd; // int 0x82
  599. *code_ptr++ = 0x82;
  600. *code_ptr++ = 0x0f; // ud2
  601. *code_ptr++ = 0x0b;
  602. }
  603. int Process::sys$restore_signal_mask(dword mask)
  604. {
  605. current->m_signal_mask = mask;
  606. return 0;
  607. }
  608. void Process::sys$sigreturn()
  609. {
  610. InterruptDisabler disabler;
  611. Scheduler::prepare_to_modify_tss(*current);
  612. current->m_tss = *current->m_tss_to_resume_kernel;
  613. current->m_tss_to_resume_kernel.clear();
  614. #ifdef SIGNAL_DEBUG
  615. kprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  616. auto& tss = current->tss();
  617. kprintf(" -> resuming execution at %w:%x stack %w:%x flags %x cr3 %x\n", tss.cs, tss.eip, tss.ss, tss.esp, tss.eflags, tss.cr3);
  618. #endif
  619. current->set_state(Thread::State::Skip1SchedulerPass);
  620. Scheduler::yield();
  621. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  622. ASSERT_NOT_REACHED();
  623. }
  624. void Process::crash()
  625. {
  626. ASSERT_INTERRUPTS_DISABLED();
  627. ASSERT(!is_dead());
  628. m_termination_signal = SIGSEGV;
  629. dump_regions();
  630. ASSERT(is_ring3());
  631. die();
  632. ASSERT_NOT_REACHED();
  633. }
  634. Process* Process::from_pid(pid_t pid)
  635. {
  636. ASSERT_INTERRUPTS_DISABLED();
  637. for (auto* process = g_processes->head(); process; process = process->next()) {
  638. if (process->pid() == pid)
  639. return process;
  640. }
  641. return nullptr;
  642. }
  643. FileDescriptor* Process::file_descriptor(int fd)
  644. {
  645. if (fd < 0)
  646. return nullptr;
  647. if (fd < m_fds.size())
  648. return m_fds[fd].descriptor.ptr();
  649. return nullptr;
  650. }
  651. const FileDescriptor* Process::file_descriptor(int fd) const
  652. {
  653. if (fd < 0)
  654. return nullptr;
  655. if (fd < m_fds.size())
  656. return m_fds[fd].descriptor.ptr();
  657. return nullptr;
  658. }
  659. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, ssize_t size)
  660. {
  661. if (size < 0)
  662. return -EINVAL;
  663. if (!validate_write(buffer, size))
  664. return -EFAULT;
  665. auto* descriptor = file_descriptor(fd);
  666. if (!descriptor)
  667. return -EBADF;
  668. return descriptor->get_dir_entries((byte*)buffer, size);
  669. }
  670. int Process::sys$lseek(int fd, off_t offset, int whence)
  671. {
  672. auto* descriptor = file_descriptor(fd);
  673. if (!descriptor)
  674. return -EBADF;
  675. return descriptor->seek(offset, whence);
  676. }
  677. int Process::sys$ttyname_r(int fd, char* buffer, ssize_t size)
  678. {
  679. if (size < 0)
  680. return -EINVAL;
  681. if (!validate_write(buffer, size))
  682. return -EFAULT;
  683. auto* descriptor = file_descriptor(fd);
  684. if (!descriptor)
  685. return -EBADF;
  686. if (!descriptor->is_tty())
  687. return -ENOTTY;
  688. auto tty_name = descriptor->tty()->tty_name();
  689. if (size < tty_name.length() + 1)
  690. return -ERANGE;
  691. strcpy(buffer, tty_name.characters());
  692. return 0;
  693. }
  694. int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size)
  695. {
  696. if (size < 0)
  697. return -EINVAL;
  698. if (!validate_write(buffer, size))
  699. return -EFAULT;
  700. auto* descriptor = file_descriptor(fd);
  701. if (!descriptor)
  702. return -EBADF;
  703. auto* master_pty = descriptor->master_pty();
  704. if (!master_pty)
  705. return -ENOTTY;
  706. auto pts_name = master_pty->pts_name();
  707. if (size < pts_name.length() + 1)
  708. return -ERANGE;
  709. strcpy(buffer, pts_name.characters());
  710. return 0;
  711. }
  712. ssize_t Process::sys$write(int fd, const byte* data, ssize_t size)
  713. {
  714. if (size < 0)
  715. return -EINVAL;
  716. if (!validate_read(data, size))
  717. return -EFAULT;
  718. #ifdef DEBUG_IO
  719. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  720. #endif
  721. auto* descriptor = file_descriptor(fd);
  722. if (!descriptor)
  723. return -EBADF;
  724. ssize_t nwritten = 0;
  725. if (descriptor->is_blocking()) {
  726. while (nwritten < (ssize_t)size) {
  727. #ifdef IO_DEBUG
  728. dbgprintf("while %u < %u\n", nwritten, size);
  729. #endif
  730. if (!descriptor->can_write(*this)) {
  731. #ifdef IO_DEBUG
  732. dbgprintf("block write on %d\n", fd);
  733. #endif
  734. current->m_blocked_fd = fd;
  735. current->block(Thread::State::BlockedWrite);
  736. }
  737. ssize_t rc = descriptor->write(*this, (const byte*)data + nwritten, size - nwritten);
  738. #ifdef IO_DEBUG
  739. dbgprintf(" -> write returned %d\n", rc);
  740. #endif
  741. if (rc < 0) {
  742. // FIXME: Support returning partial nwritten with errno.
  743. ASSERT(nwritten == 0);
  744. return rc;
  745. }
  746. if (rc == 0)
  747. break;
  748. if (current->has_unmasked_pending_signals()) {
  749. current->block(Thread::State::BlockedSignal);
  750. if (nwritten == 0)
  751. return -EINTR;
  752. }
  753. nwritten += rc;
  754. }
  755. } else {
  756. nwritten = descriptor->write(*this, (const byte*)data, size);
  757. }
  758. if (current->has_unmasked_pending_signals()) {
  759. current->block(Thread::State::BlockedSignal);
  760. if (nwritten == 0)
  761. return -EINTR;
  762. }
  763. return nwritten;
  764. }
  765. ssize_t Process::sys$read(int fd, byte* buffer, ssize_t size)
  766. {
  767. if (size < 0)
  768. return -EINVAL;
  769. if (!validate_write(buffer, size))
  770. return -EFAULT;
  771. #ifdef DEBUG_IO
  772. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, buffer, size);
  773. #endif
  774. auto* descriptor = file_descriptor(fd);
  775. if (!descriptor)
  776. return -EBADF;
  777. if (descriptor->is_blocking()) {
  778. if (!descriptor->can_read(*this)) {
  779. current->m_blocked_fd = fd;
  780. current->block(Thread::State::BlockedRead);
  781. if (current->m_was_interrupted_while_blocked)
  782. return -EINTR;
  783. }
  784. }
  785. return descriptor->read(*this, buffer, size);
  786. }
  787. int Process::sys$close(int fd)
  788. {
  789. auto* descriptor = file_descriptor(fd);
  790. if (!descriptor)
  791. return -EBADF;
  792. int rc = descriptor->close();
  793. m_fds[fd] = { };
  794. return rc;
  795. }
  796. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  797. {
  798. if (!validate_read_str(pathname))
  799. return -EFAULT;
  800. if (buf && !validate_read_typed(buf))
  801. return -EFAULT;
  802. time_t atime;
  803. time_t mtime;
  804. if (buf) {
  805. atime = buf->actime;
  806. mtime = buf->modtime;
  807. } else {
  808. struct timeval now;
  809. kgettimeofday(now);
  810. mtime = now.tv_sec;
  811. atime = now.tv_sec;
  812. }
  813. return VFS::the().utime(StringView(pathname), cwd_inode(), atime, mtime);
  814. }
  815. int Process::sys$access(const char* pathname, int mode)
  816. {
  817. if (!validate_read_str(pathname))
  818. return -EFAULT;
  819. return VFS::the().access(StringView(pathname), mode, cwd_inode());
  820. }
  821. int Process::sys$fcntl(int fd, int cmd, dword arg)
  822. {
  823. (void) cmd;
  824. (void) arg;
  825. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  826. auto* descriptor = file_descriptor(fd);
  827. if (!descriptor)
  828. return -EBADF;
  829. // NOTE: The FD flags are not shared between FileDescriptor objects.
  830. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  831. switch (cmd) {
  832. case F_DUPFD: {
  833. int arg_fd = (int)arg;
  834. if (arg_fd < 0)
  835. return -EINVAL;
  836. int new_fd = alloc_fd(arg_fd);
  837. if (new_fd < 0)
  838. return new_fd;
  839. m_fds[new_fd].set(*descriptor);
  840. break;
  841. }
  842. case F_GETFD:
  843. return m_fds[fd].flags;
  844. case F_SETFD:
  845. m_fds[fd].flags = arg;
  846. break;
  847. case F_GETFL:
  848. return descriptor->file_flags();
  849. case F_SETFL:
  850. // FIXME: Support changing O_NONBLOCK
  851. descriptor->set_file_flags(arg);
  852. break;
  853. default:
  854. ASSERT_NOT_REACHED();
  855. }
  856. return 0;
  857. }
  858. int Process::sys$fstat(int fd, stat* statbuf)
  859. {
  860. if (!validate_write_typed(statbuf))
  861. return -EFAULT;
  862. auto* descriptor = file_descriptor(fd);
  863. if (!descriptor)
  864. return -EBADF;
  865. return descriptor->fstat(*statbuf);
  866. }
  867. int Process::sys$lstat(const char* path, stat* statbuf)
  868. {
  869. if (!validate_write_typed(statbuf))
  870. return -EFAULT;
  871. return VFS::the().stat(StringView(path), O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf);
  872. }
  873. int Process::sys$stat(const char* path, stat* statbuf)
  874. {
  875. if (!validate_write_typed(statbuf))
  876. return -EFAULT;
  877. return VFS::the().stat(StringView(path), O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf);
  878. }
  879. int Process::sys$readlink(const char* path, char* buffer, ssize_t size)
  880. {
  881. if (size < 0)
  882. return -EINVAL;
  883. if (!validate_read_str(path))
  884. return -EFAULT;
  885. if (!validate_write(buffer, size))
  886. return -EFAULT;
  887. auto result = VFS::the().open(path, O_RDONLY | O_NOFOLLOW_NOERROR, 0, cwd_inode());
  888. if (result.is_error())
  889. return result.error();
  890. auto descriptor = result.value();
  891. if (!descriptor->metadata().is_symlink())
  892. return -EINVAL;
  893. auto contents = descriptor->read_entire_file(*this);
  894. if (!contents)
  895. return -EIO; // FIXME: Get a more detailed error from VFS.
  896. memcpy(buffer, contents.pointer(), min(size, (ssize_t)contents.size()));
  897. if (contents.size() + 1 < size)
  898. buffer[contents.size()] = '\0';
  899. return 0;
  900. }
  901. int Process::sys$chdir(const char* path)
  902. {
  903. if (!validate_read_str(path))
  904. return -EFAULT;
  905. auto directory_or_error = VFS::the().open_directory(StringView(path), cwd_inode());
  906. if (directory_or_error.is_error())
  907. return directory_or_error.error();
  908. m_cwd = *directory_or_error.value();
  909. return 0;
  910. }
  911. int Process::sys$getcwd(char* buffer, ssize_t size)
  912. {
  913. if (size < 0)
  914. return -EINVAL;
  915. if (!validate_write(buffer, size))
  916. return -EFAULT;
  917. auto path_or_error = VFS::the().absolute_path(cwd_inode());
  918. if (path_or_error.is_error())
  919. return path_or_error.error();
  920. auto path = path_or_error.value();
  921. if (size < path.length() + 1)
  922. return -ERANGE;
  923. strcpy(buffer, path.characters());
  924. return 0;
  925. }
  926. int Process::number_of_open_file_descriptors() const
  927. {
  928. int count = 0;
  929. for (auto& descriptor : m_fds) {
  930. if (descriptor)
  931. ++count;
  932. }
  933. return count;
  934. }
  935. int Process::sys$open(const char* path, int options, mode_t mode)
  936. {
  937. #ifdef DEBUG_IO
  938. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  939. #endif
  940. if (!validate_read_str(path))
  941. return -EFAULT;
  942. int fd = alloc_fd();
  943. if (fd < 0)
  944. return fd;
  945. auto result = VFS::the().open(path, options, mode & ~umask(), cwd_inode());
  946. if (result.is_error())
  947. return result.error();
  948. auto descriptor = result.value();
  949. if (options & O_DIRECTORY && !descriptor->is_directory())
  950. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  951. if (options & O_NONBLOCK)
  952. descriptor->set_blocking(false);
  953. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  954. m_fds[fd].set(move(descriptor), flags);
  955. return fd;
  956. }
  957. int Process::alloc_fd(int first_candidate_fd)
  958. {
  959. int fd = -EMFILE;
  960. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  961. if (!m_fds[i]) {
  962. fd = i;
  963. break;
  964. }
  965. }
  966. return fd;
  967. }
  968. int Process::sys$pipe(int pipefd[2])
  969. {
  970. if (!validate_write_typed(pipefd))
  971. return -EFAULT;
  972. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  973. return -EMFILE;
  974. auto fifo = FIFO::create();
  975. int reader_fd = alloc_fd();
  976. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  977. pipefd[0] = reader_fd;
  978. int writer_fd = alloc_fd();
  979. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  980. pipefd[1] = writer_fd;
  981. return 0;
  982. }
  983. int Process::sys$killpg(int pgrp, int signum)
  984. {
  985. if (signum < 1 || signum >= 32)
  986. return -EINVAL;
  987. (void) pgrp;
  988. ASSERT_NOT_REACHED();
  989. }
  990. int Process::sys$setuid(uid_t uid)
  991. {
  992. if (uid != m_uid && !is_superuser())
  993. return -EPERM;
  994. m_uid = uid;
  995. m_euid = uid;
  996. return 0;
  997. }
  998. int Process::sys$setgid(gid_t gid)
  999. {
  1000. if (gid != m_gid && !is_superuser())
  1001. return -EPERM;
  1002. m_gid = gid;
  1003. m_egid = gid;
  1004. return 0;
  1005. }
  1006. unsigned Process::sys$alarm(unsigned seconds)
  1007. {
  1008. (void) seconds;
  1009. ASSERT_NOT_REACHED();
  1010. }
  1011. int Process::sys$uname(utsname* buf)
  1012. {
  1013. if (!validate_write_typed(buf))
  1014. return -EFAULT;
  1015. strcpy(buf->sysname, "Serenity");
  1016. strcpy(buf->release, "1.0-dev");
  1017. strcpy(buf->version, "FIXME");
  1018. strcpy(buf->machine, "i386");
  1019. LOCKER(*s_hostname_lock);
  1020. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1021. return 0;
  1022. }
  1023. int Process::sys$isatty(int fd)
  1024. {
  1025. auto* descriptor = file_descriptor(fd);
  1026. if (!descriptor)
  1027. return -EBADF;
  1028. if (!descriptor->is_tty())
  1029. return -ENOTTY;
  1030. return 1;
  1031. }
  1032. int Process::sys$kill(pid_t pid, int signal)
  1033. {
  1034. if (signal < 0 || signal >= 32)
  1035. return -EINVAL;
  1036. if (pid == 0) {
  1037. // FIXME: Send to same-group processes.
  1038. ASSERT(pid != 0);
  1039. }
  1040. if (pid == -1) {
  1041. // FIXME: Send to all processes.
  1042. ASSERT(pid != -1);
  1043. }
  1044. if (pid == m_pid) {
  1045. current->send_signal(signal, this);
  1046. Scheduler::yield();
  1047. return 0;
  1048. }
  1049. InterruptDisabler disabler;
  1050. auto* peer = Process::from_pid(pid);
  1051. if (!peer)
  1052. return -ESRCH;
  1053. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1054. // FIXME: Should setuid processes have some special treatment here?
  1055. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  1056. return -EPERM;
  1057. if (peer->is_ring0() && signal == SIGKILL) {
  1058. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, peer->name().characters(), peer->pid());
  1059. return -EPERM;
  1060. }
  1061. peer->send_signal(signal, this);
  1062. return 0;
  1063. }
  1064. int Process::sys$usleep(useconds_t usec)
  1065. {
  1066. if (!usec)
  1067. return 0;
  1068. current->sleep(usec / 1000);
  1069. if (current->m_wakeup_time > g_uptime) {
  1070. ASSERT(current->m_was_interrupted_while_blocked);
  1071. dword ticks_left_until_original_wakeup_time = current->m_wakeup_time - g_uptime;
  1072. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1073. }
  1074. return 0;
  1075. }
  1076. int Process::sys$sleep(unsigned seconds)
  1077. {
  1078. if (!seconds)
  1079. return 0;
  1080. current->sleep(seconds * TICKS_PER_SECOND);
  1081. if (current->m_wakeup_time > g_uptime) {
  1082. ASSERT(current->m_was_interrupted_while_blocked);
  1083. dword ticks_left_until_original_wakeup_time = current->m_wakeup_time - g_uptime;
  1084. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1085. }
  1086. return 0;
  1087. }
  1088. void kgettimeofday(timeval& tv)
  1089. {
  1090. tv.tv_sec = RTC::boot_time() + PIT::seconds_since_boot();
  1091. tv.tv_usec = PIT::ticks_this_second() * 1000;
  1092. }
  1093. int Process::sys$gettimeofday(timeval* tv)
  1094. {
  1095. if (!validate_write_typed(tv))
  1096. return -EFAULT;
  1097. kgettimeofday(*tv);
  1098. return 0;
  1099. }
  1100. uid_t Process::sys$getuid()
  1101. {
  1102. return m_uid;
  1103. }
  1104. gid_t Process::sys$getgid()
  1105. {
  1106. return m_gid;
  1107. }
  1108. uid_t Process::sys$geteuid()
  1109. {
  1110. return m_euid;
  1111. }
  1112. gid_t Process::sys$getegid()
  1113. {
  1114. return m_egid;
  1115. }
  1116. pid_t Process::sys$getpid()
  1117. {
  1118. return m_pid;
  1119. }
  1120. pid_t Process::sys$getppid()
  1121. {
  1122. return m_ppid;
  1123. }
  1124. mode_t Process::sys$umask(mode_t mask)
  1125. {
  1126. auto old_mask = m_umask;
  1127. m_umask = mask & 0777;
  1128. return old_mask;
  1129. }
  1130. int Process::reap(Process& process)
  1131. {
  1132. int exit_status;
  1133. {
  1134. InterruptDisabler disabler;
  1135. exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1136. if (process.ppid()) {
  1137. auto* parent = Process::from_pid(process.ppid());
  1138. if (parent) {
  1139. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1140. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1141. }
  1142. }
  1143. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1144. ASSERT(process.is_dead());
  1145. g_processes->remove(&process);
  1146. }
  1147. delete &process;
  1148. return exit_status;
  1149. }
  1150. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1151. {
  1152. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1153. // FIXME: Respect options
  1154. (void) options;
  1155. if (wstatus)
  1156. if (!validate_write_typed(wstatus))
  1157. return -EFAULT;
  1158. int dummy_wstatus;
  1159. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1160. {
  1161. InterruptDisabler disabler;
  1162. if (waitee != -1 && !Process::from_pid(waitee))
  1163. return -ECHILD;
  1164. }
  1165. if (options & WNOHANG) {
  1166. if (waitee == -1) {
  1167. pid_t reaped_pid = 0;
  1168. InterruptDisabler disabler;
  1169. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1170. if (process.is_dead()) {
  1171. reaped_pid = process.pid();
  1172. exit_status = reap(process);
  1173. }
  1174. return true;
  1175. });
  1176. return reaped_pid;
  1177. } else {
  1178. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1179. InterruptDisabler disabler;
  1180. auto* waitee_process = Process::from_pid(waitee);
  1181. if (!waitee_process)
  1182. return -ECHILD;
  1183. if (waitee_process->is_dead()) {
  1184. exit_status = reap(*waitee_process);
  1185. return waitee;
  1186. }
  1187. return 0;
  1188. }
  1189. }
  1190. current->m_waitee_pid = waitee;
  1191. current->block(Thread::State::BlockedWait);
  1192. if (current->m_was_interrupted_while_blocked)
  1193. return -EINTR;
  1194. Process* waitee_process;
  1195. {
  1196. InterruptDisabler disabler;
  1197. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1198. waitee_process = Process::from_pid(current->m_waitee_pid);
  1199. }
  1200. ASSERT(waitee_process);
  1201. exit_status = reap(*waitee_process);
  1202. return current->m_waitee_pid;
  1203. }
  1204. enum class KernelMemoryCheckResult {
  1205. NotInsideKernelMemory,
  1206. AccessGranted,
  1207. AccessDenied
  1208. };
  1209. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1210. {
  1211. auto* kernel_elf_header = (Elf32_Ehdr*)0xf000;
  1212. auto* kernel_program_headers = (Elf32_Phdr*)(0xf000 + kernel_elf_header->e_phoff);
  1213. for (unsigned i = 0; i < kernel_elf_header->e_phnum; ++i) {
  1214. auto& segment = kernel_program_headers[i];
  1215. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1216. continue;
  1217. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1218. continue;
  1219. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1220. return KernelMemoryCheckResult::AccessDenied;
  1221. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1222. return KernelMemoryCheckResult::AccessDenied;
  1223. return KernelMemoryCheckResult::AccessGranted;
  1224. }
  1225. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1226. }
  1227. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1228. {
  1229. if (laddr.is_null())
  1230. return false;
  1231. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1232. // This code allows access outside of the known used address ranges to get caught.
  1233. auto kmc_result = check_kernel_memory_access(laddr, false);
  1234. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1235. return true;
  1236. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1237. return false;
  1238. if (is_kmalloc_address(laddr.as_ptr()))
  1239. return true;
  1240. return validate_read(laddr.as_ptr(), 1);
  1241. }
  1242. bool Process::validate_read_str(const char* str)
  1243. {
  1244. if (!validate_read(str, 1))
  1245. return false;
  1246. return validate_read(str, strlen(str) + 1);
  1247. }
  1248. bool Process::validate_read(const void* address, ssize_t size) const
  1249. {
  1250. ASSERT(size >= 0);
  1251. LinearAddress first_address((dword)address);
  1252. LinearAddress last_address = first_address.offset(size - 1);
  1253. if (is_ring0()) {
  1254. auto kmc_result = check_kernel_memory_access(first_address, false);
  1255. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1256. return true;
  1257. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1258. return false;
  1259. if (is_kmalloc_address(address))
  1260. return true;
  1261. }
  1262. ASSERT(size);
  1263. if (!size)
  1264. return false;
  1265. if (first_address.page_base() != last_address.page_base()) {
  1266. if (!MM.validate_user_read(*this, last_address))
  1267. return false;
  1268. }
  1269. return MM.validate_user_read(*this, first_address);
  1270. }
  1271. bool Process::validate_write(void* address, ssize_t size) const
  1272. {
  1273. ASSERT(size >= 0);
  1274. LinearAddress first_address((dword)address);
  1275. LinearAddress last_address = first_address.offset(size - 1);
  1276. if (is_ring0()) {
  1277. if (is_kmalloc_address(address))
  1278. return true;
  1279. auto kmc_result = check_kernel_memory_access(first_address, true);
  1280. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1281. return true;
  1282. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1283. return false;
  1284. }
  1285. if (!size)
  1286. return false;
  1287. if (first_address.page_base() != last_address.page_base()) {
  1288. if (!MM.validate_user_write(*this, last_address))
  1289. return false;
  1290. }
  1291. return MM.validate_user_write(*this, last_address);
  1292. }
  1293. pid_t Process::sys$getsid(pid_t pid)
  1294. {
  1295. if (pid == 0)
  1296. return m_sid;
  1297. InterruptDisabler disabler;
  1298. auto* process = Process::from_pid(pid);
  1299. if (!process)
  1300. return -ESRCH;
  1301. if (m_sid != process->m_sid)
  1302. return -EPERM;
  1303. return process->m_sid;
  1304. }
  1305. pid_t Process::sys$setsid()
  1306. {
  1307. InterruptDisabler disabler;
  1308. bool found_process_with_same_pgid_as_my_pid = false;
  1309. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1310. found_process_with_same_pgid_as_my_pid = true;
  1311. return false;
  1312. });
  1313. if (found_process_with_same_pgid_as_my_pid)
  1314. return -EPERM;
  1315. m_sid = m_pid;
  1316. m_pgid = m_pid;
  1317. return m_sid;
  1318. }
  1319. pid_t Process::sys$getpgid(pid_t pid)
  1320. {
  1321. if (pid == 0)
  1322. return m_pgid;
  1323. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1324. auto* process = Process::from_pid(pid);
  1325. if (!process)
  1326. return -ESRCH;
  1327. return process->m_pgid;
  1328. }
  1329. pid_t Process::sys$getpgrp()
  1330. {
  1331. return m_pgid;
  1332. }
  1333. static pid_t get_sid_from_pgid(pid_t pgid)
  1334. {
  1335. InterruptDisabler disabler;
  1336. auto* group_leader = Process::from_pid(pgid);
  1337. if (!group_leader)
  1338. return -1;
  1339. return group_leader->sid();
  1340. }
  1341. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1342. {
  1343. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1344. pid_t pid = specified_pid ? specified_pid : m_pid;
  1345. if (specified_pgid < 0)
  1346. return -EINVAL;
  1347. auto* process = Process::from_pid(pid);
  1348. if (!process)
  1349. return -ESRCH;
  1350. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1351. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1352. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1353. if (current_sid != new_sid) {
  1354. // Can't move a process between sessions.
  1355. return -EPERM;
  1356. }
  1357. // FIXME: There are more EPERM conditions to check for here..
  1358. process->m_pgid = new_pgid;
  1359. return 0;
  1360. }
  1361. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1362. {
  1363. auto* descriptor = file_descriptor(fd);
  1364. if (!descriptor)
  1365. return -EBADF;
  1366. if (!descriptor->is_device())
  1367. return -ENOTTY;
  1368. return descriptor->device()->ioctl(*this, request, arg);
  1369. }
  1370. int Process::sys$getdtablesize()
  1371. {
  1372. return m_max_open_file_descriptors;
  1373. }
  1374. int Process::sys$dup(int old_fd)
  1375. {
  1376. auto* descriptor = file_descriptor(old_fd);
  1377. if (!descriptor)
  1378. return -EBADF;
  1379. int new_fd = alloc_fd(0);
  1380. if (new_fd < 0)
  1381. return new_fd;
  1382. m_fds[new_fd].set(*descriptor);
  1383. return new_fd;
  1384. }
  1385. int Process::sys$dup2(int old_fd, int new_fd)
  1386. {
  1387. auto* descriptor = file_descriptor(old_fd);
  1388. if (!descriptor)
  1389. return -EBADF;
  1390. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  1391. return -EINVAL;
  1392. m_fds[new_fd].set(*descriptor);
  1393. return new_fd;
  1394. }
  1395. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1396. {
  1397. if (old_set) {
  1398. if (!validate_write_typed(old_set))
  1399. return -EFAULT;
  1400. *old_set = current->m_signal_mask;
  1401. }
  1402. if (set) {
  1403. if (!validate_read_typed(set))
  1404. return -EFAULT;
  1405. switch (how) {
  1406. case SIG_BLOCK:
  1407. current->m_signal_mask &= ~(*set);
  1408. break;
  1409. case SIG_UNBLOCK:
  1410. current->m_signal_mask |= *set;
  1411. break;
  1412. case SIG_SETMASK:
  1413. current->m_signal_mask = *set;
  1414. break;
  1415. default:
  1416. return -EINVAL;
  1417. }
  1418. }
  1419. return 0;
  1420. }
  1421. int Process::sys$sigpending(sigset_t* set)
  1422. {
  1423. if (!validate_write_typed(set))
  1424. return -EFAULT;
  1425. *set = current->m_pending_signals;
  1426. return 0;
  1427. }
  1428. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1429. {
  1430. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1431. return -EINVAL;
  1432. if (!validate_read_typed(act))
  1433. return -EFAULT;
  1434. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1435. auto& action = current->m_signal_action_data[signum];
  1436. if (old_act) {
  1437. if (!validate_write_typed(old_act))
  1438. return -EFAULT;
  1439. old_act->sa_flags = action.flags;
  1440. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1441. }
  1442. action.flags = act->sa_flags;
  1443. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1444. return 0;
  1445. }
  1446. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1447. {
  1448. if (count < 0)
  1449. return -EINVAL;
  1450. if (!count)
  1451. return m_gids.size();
  1452. if (count != (int)m_gids.size())
  1453. return -EINVAL;
  1454. if (!validate_write_typed(gids, m_gids.size()))
  1455. return -EFAULT;
  1456. size_t i = 0;
  1457. for (auto gid : m_gids)
  1458. gids[i++] = gid;
  1459. return 0;
  1460. }
  1461. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1462. {
  1463. if (count < 0)
  1464. return -EINVAL;
  1465. if (!is_superuser())
  1466. return -EPERM;
  1467. if (!validate_read(gids, count))
  1468. return -EFAULT;
  1469. m_gids.clear();
  1470. m_gids.set(m_gid);
  1471. for (int i = 0; i < count; ++i)
  1472. m_gids.set(gids[i]);
  1473. return 0;
  1474. }
  1475. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1476. {
  1477. if (!validate_read_str(pathname))
  1478. return -EFAULT;
  1479. size_t pathname_length = strlen(pathname);
  1480. if (pathname_length == 0)
  1481. return -EINVAL;
  1482. if (pathname_length >= 255)
  1483. return -ENAMETOOLONG;
  1484. return VFS::the().mkdir(StringView(pathname, pathname_length), mode & ~umask(), cwd_inode());
  1485. }
  1486. clock_t Process::sys$times(tms* times)
  1487. {
  1488. if (!validate_write_typed(times))
  1489. return -EFAULT;
  1490. times->tms_utime = m_ticks_in_user;
  1491. times->tms_stime = m_ticks_in_kernel;
  1492. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1493. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1494. return 0;
  1495. }
  1496. int Process::sys$select(const Syscall::SC_select_params* params)
  1497. {
  1498. if (!validate_read_typed(params))
  1499. return -EFAULT;
  1500. if (params->writefds && !validate_read_typed(params->writefds))
  1501. return -EFAULT;
  1502. if (params->readfds && !validate_read_typed(params->readfds))
  1503. return -EFAULT;
  1504. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1505. return -EFAULT;
  1506. if (params->timeout && !validate_read_typed(params->timeout))
  1507. return -EFAULT;
  1508. int nfds = params->nfds;
  1509. fd_set* writefds = params->writefds;
  1510. fd_set* readfds = params->readfds;
  1511. fd_set* exceptfds = params->exceptfds;
  1512. auto* timeout = params->timeout;
  1513. // FIXME: Implement exceptfds support.
  1514. (void)exceptfds;
  1515. if (timeout) {
  1516. current->m_select_timeout = *timeout;
  1517. current->m_select_has_timeout = true;
  1518. } else {
  1519. current->m_select_has_timeout = false;
  1520. }
  1521. if (nfds < 0)
  1522. return -EINVAL;
  1523. // FIXME: Return -EINTR if a signal is caught.
  1524. // FIXME: Return -EINVAL if timeout is invalid.
  1525. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1526. if (!set)
  1527. return 0;
  1528. vector.clear_with_capacity();
  1529. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1530. for (int i = 0; i < nfds; ++i) {
  1531. if (bitmap.get(i)) {
  1532. if (!file_descriptor(i))
  1533. return -EBADF;
  1534. vector.append(i);
  1535. }
  1536. }
  1537. return 0;
  1538. };
  1539. int error = 0;
  1540. error = transfer_fds(writefds, current->m_select_write_fds);
  1541. if (error)
  1542. return error;
  1543. error = transfer_fds(readfds, current->m_select_read_fds);
  1544. if (error)
  1545. return error;
  1546. error = transfer_fds(readfds, current->m_select_exceptional_fds);
  1547. if (error)
  1548. return error;
  1549. #ifdef DEBUG_IO
  1550. dbgprintf("%s<%u> selecting on (read:%u, write:%u), timeout=%p\n", name().characters(), pid(), current->m_select_read_fds.size(), current->m_select_write_fds.size(), timeout);
  1551. #endif
  1552. if (!timeout || (timeout->tv_sec || timeout->tv_usec))
  1553. current->block(Thread::State::BlockedSelect);
  1554. int markedfds = 0;
  1555. if (readfds) {
  1556. memset(readfds, 0, sizeof(fd_set));
  1557. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1558. for (int fd : current->m_select_read_fds) {
  1559. auto* descriptor = file_descriptor(fd);
  1560. if (!descriptor)
  1561. continue;
  1562. if (descriptor->can_read(*this)) {
  1563. bitmap.set(fd, true);
  1564. ++markedfds;
  1565. }
  1566. }
  1567. }
  1568. if (writefds) {
  1569. memset(writefds, 0, sizeof(fd_set));
  1570. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1571. for (int fd : current->m_select_write_fds) {
  1572. auto* descriptor = file_descriptor(fd);
  1573. if (!descriptor)
  1574. continue;
  1575. if (descriptor->can_write(*this)) {
  1576. bitmap.set(fd, true);
  1577. ++markedfds;
  1578. }
  1579. }
  1580. }
  1581. // FIXME: Check for exceptional conditions.
  1582. return markedfds;
  1583. }
  1584. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1585. {
  1586. if (!validate_read_typed(fds))
  1587. return -EFAULT;
  1588. current->m_select_write_fds.clear_with_capacity();
  1589. current->m_select_read_fds.clear_with_capacity();
  1590. for (int i = 0; i < nfds; ++i) {
  1591. if (fds[i].events & POLLIN)
  1592. current->m_select_read_fds.append(fds[i].fd);
  1593. if (fds[i].events & POLLOUT)
  1594. current->m_select_write_fds.append(fds[i].fd);
  1595. }
  1596. if (timeout < 0)
  1597. current->block(Thread::State::BlockedSelect);
  1598. int fds_with_revents = 0;
  1599. for (int i = 0; i < nfds; ++i) {
  1600. auto* descriptor = file_descriptor(fds[i].fd);
  1601. if (!descriptor) {
  1602. fds[i].revents = POLLNVAL;
  1603. continue;
  1604. }
  1605. fds[i].revents = 0;
  1606. if (fds[i].events & POLLIN && descriptor->can_read(*this))
  1607. fds[i].revents |= POLLIN;
  1608. if (fds[i].events & POLLOUT && descriptor->can_write(*this))
  1609. fds[i].revents |= POLLOUT;
  1610. if (fds[i].revents)
  1611. ++fds_with_revents;
  1612. }
  1613. return fds_with_revents;
  1614. }
  1615. Inode& Process::cwd_inode()
  1616. {
  1617. // FIXME: This is retarded factoring.
  1618. if (!m_cwd)
  1619. m_cwd = VFS::the().root_inode();
  1620. return *m_cwd;
  1621. }
  1622. int Process::sys$link(const char* old_path, const char* new_path)
  1623. {
  1624. if (!validate_read_str(old_path))
  1625. return -EFAULT;
  1626. if (!validate_read_str(new_path))
  1627. return -EFAULT;
  1628. return VFS::the().link(StringView(old_path), StringView(new_path), cwd_inode());
  1629. }
  1630. int Process::sys$unlink(const char* pathname)
  1631. {
  1632. if (!validate_read_str(pathname))
  1633. return -EFAULT;
  1634. return VFS::the().unlink(StringView(pathname), cwd_inode());
  1635. }
  1636. int Process::sys$symlink(const char* target, const char* linkpath)
  1637. {
  1638. if (!validate_read_str(target))
  1639. return -EFAULT;
  1640. if (!validate_read_str(linkpath))
  1641. return -EFAULT;
  1642. return VFS::the().symlink(StringView(target), StringView(linkpath), cwd_inode());
  1643. }
  1644. int Process::sys$rmdir(const char* pathname)
  1645. {
  1646. if (!validate_read_str(pathname))
  1647. return -EFAULT;
  1648. return VFS::the().rmdir(StringView(pathname), cwd_inode());
  1649. }
  1650. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1651. {
  1652. if (!validate_write_typed(lsw))
  1653. return -EFAULT;
  1654. if (!validate_write_typed(msw))
  1655. return -EFAULT;
  1656. read_tsc(*lsw, *msw);
  1657. return 0;
  1658. }
  1659. int Process::sys$chmod(const char* pathname, mode_t mode)
  1660. {
  1661. if (!validate_read_str(pathname))
  1662. return -EFAULT;
  1663. return VFS::the().chmod(StringView(pathname), mode, cwd_inode());
  1664. }
  1665. int Process::sys$fchmod(int fd, mode_t mode)
  1666. {
  1667. auto* descriptor = file_descriptor(fd);
  1668. if (!descriptor)
  1669. return -EBADF;
  1670. return descriptor->fchmod(mode);
  1671. }
  1672. int Process::sys$chown(const char* pathname, uid_t uid, gid_t gid)
  1673. {
  1674. if (!validate_read_str(pathname))
  1675. return -EFAULT;
  1676. return VFS::the().chown(StringView(pathname), uid, gid, cwd_inode());
  1677. }
  1678. void Process::finalize()
  1679. {
  1680. ASSERT(current == g_finalizer);
  1681. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  1682. m_fds.clear();
  1683. m_tty = nullptr;
  1684. disown_all_shared_buffers();
  1685. {
  1686. InterruptDisabler disabler;
  1687. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1688. // FIXME(Thread): What should we do here? Should we look at all threads' signal actions?
  1689. if (parent_process->main_thread().m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  1690. // NOTE: If the parent doesn't care about this process, let it go.
  1691. m_ppid = 0;
  1692. } else {
  1693. parent_process->send_signal(SIGCHLD, this);
  1694. }
  1695. }
  1696. }
  1697. m_dead = true;
  1698. }
  1699. void Process::die()
  1700. {
  1701. {
  1702. InterruptDisabler disabler;
  1703. for_each_thread([] (Thread& thread) {
  1704. if (thread.state() != Thread::State::Dead)
  1705. thread.set_state(Thread::State::Dying);
  1706. return IterationDecision::Continue;
  1707. });
  1708. }
  1709. if (!Scheduler::is_active())
  1710. Scheduler::pick_next_and_switch_now();
  1711. }
  1712. size_t Process::amount_virtual() const
  1713. {
  1714. size_t amount = 0;
  1715. for (auto& region : m_regions) {
  1716. amount += region->size();
  1717. }
  1718. return amount;
  1719. }
  1720. size_t Process::amount_resident() const
  1721. {
  1722. // FIXME: This will double count if multiple regions use the same physical page.
  1723. size_t amount = 0;
  1724. for (auto& region : m_regions) {
  1725. amount += region->amount_resident();
  1726. }
  1727. return amount;
  1728. }
  1729. size_t Process::amount_shared() const
  1730. {
  1731. // FIXME: This will double count if multiple regions use the same physical page.
  1732. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1733. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1734. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1735. size_t amount = 0;
  1736. for (auto& region : m_regions) {
  1737. amount += region->amount_shared();
  1738. }
  1739. return amount;
  1740. }
  1741. int Process::sys$socket(int domain, int type, int protocol)
  1742. {
  1743. int fd = alloc_fd();
  1744. if (fd < 0)
  1745. return fd;
  1746. auto result = Socket::create(domain, type, protocol);
  1747. if (result.is_error())
  1748. return result.error();
  1749. auto descriptor = FileDescriptor::create(*result.value());
  1750. unsigned flags = 0;
  1751. if (type & SOCK_CLOEXEC)
  1752. flags |= FD_CLOEXEC;
  1753. if (type & SOCK_NONBLOCK)
  1754. descriptor->set_blocking(false);
  1755. m_fds[fd].set(move(descriptor), flags);
  1756. return fd;
  1757. }
  1758. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  1759. {
  1760. if (!validate_read(address, address_length))
  1761. return -EFAULT;
  1762. auto* descriptor = file_descriptor(sockfd);
  1763. if (!descriptor)
  1764. return -EBADF;
  1765. if (!descriptor->is_socket())
  1766. return -ENOTSOCK;
  1767. auto& socket = *descriptor->socket();
  1768. return socket.bind(address, address_length);
  1769. }
  1770. int Process::sys$listen(int sockfd, int backlog)
  1771. {
  1772. auto* descriptor = file_descriptor(sockfd);
  1773. if (!descriptor)
  1774. return -EBADF;
  1775. if (!descriptor->is_socket())
  1776. return -ENOTSOCK;
  1777. auto& socket = *descriptor->socket();
  1778. auto result = socket.listen(backlog);
  1779. if (result.is_error())
  1780. return result;
  1781. descriptor->set_socket_role(SocketRole::Listener);
  1782. return 0;
  1783. }
  1784. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  1785. {
  1786. if (!validate_write_typed(address_size))
  1787. return -EFAULT;
  1788. if (!validate_write(address, *address_size))
  1789. return -EFAULT;
  1790. int accepted_socket_fd = alloc_fd();
  1791. if (accepted_socket_fd < 0)
  1792. return accepted_socket_fd;
  1793. auto* accepting_socket_descriptor = file_descriptor(accepting_socket_fd);
  1794. if (!accepting_socket_descriptor)
  1795. return -EBADF;
  1796. if (!accepting_socket_descriptor->is_socket())
  1797. return -ENOTSOCK;
  1798. auto& socket = *accepting_socket_descriptor->socket();
  1799. if (!socket.can_accept()) {
  1800. ASSERT(!accepting_socket_descriptor->is_blocking());
  1801. return -EAGAIN;
  1802. }
  1803. auto accepted_socket = socket.accept();
  1804. ASSERT(accepted_socket);
  1805. bool success = accepted_socket->get_address(address, address_size);
  1806. ASSERT(success);
  1807. auto accepted_socket_descriptor = FileDescriptor::create(move(accepted_socket), SocketRole::Accepted);
  1808. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  1809. // I'm not sure if this matches other systems but it makes sense to me.
  1810. accepted_socket_descriptor->set_blocking(accepting_socket_descriptor->is_blocking());
  1811. m_fds[accepted_socket_fd].set(move(accepted_socket_descriptor), m_fds[accepting_socket_fd].flags);
  1812. return accepted_socket_fd;
  1813. }
  1814. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  1815. {
  1816. if (!validate_read(address, address_size))
  1817. return -EFAULT;
  1818. int fd = alloc_fd();
  1819. if (fd < 0)
  1820. return fd;
  1821. auto* descriptor = file_descriptor(sockfd);
  1822. if (!descriptor)
  1823. return -EBADF;
  1824. if (!descriptor->is_socket())
  1825. return -ENOTSOCK;
  1826. if (descriptor->socket_role() == SocketRole::Connected)
  1827. return -EISCONN;
  1828. auto& socket = *descriptor->socket();
  1829. descriptor->set_socket_role(SocketRole::Connecting);
  1830. auto result = socket.connect(address, address_size, descriptor->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  1831. if (result.is_error()) {
  1832. descriptor->set_socket_role(SocketRole::None);
  1833. return result;
  1834. }
  1835. descriptor->set_socket_role(SocketRole::Connected);
  1836. return 0;
  1837. }
  1838. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* params)
  1839. {
  1840. if (!validate_read_typed(params))
  1841. return -EFAULT;
  1842. int sockfd = params->sockfd;
  1843. const void* data = params->data;
  1844. size_t data_length = params->data_length;
  1845. int flags = params->flags;
  1846. auto* addr = (const sockaddr*)params->addr;
  1847. auto addr_length = (socklen_t)params->addr_length;
  1848. if (!validate_read(data, data_length))
  1849. return -EFAULT;
  1850. if (addr && !validate_read(addr, addr_length))
  1851. return -EFAULT;
  1852. auto* descriptor = file_descriptor(sockfd);
  1853. if (!descriptor)
  1854. return -EBADF;
  1855. if (!descriptor->is_socket())
  1856. return -ENOTSOCK;
  1857. auto& socket = *descriptor->socket();
  1858. kprintf("sendto %p (%u), flags=%u, addr: %p (%u)\n", data, data_length, flags, addr, addr_length);
  1859. return socket.sendto(data, data_length, flags, addr, addr_length);
  1860. }
  1861. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params)
  1862. {
  1863. if (!validate_read_typed(params))
  1864. return -EFAULT;
  1865. int sockfd = params->sockfd;
  1866. void* buffer = params->buffer;
  1867. size_t buffer_length = params->buffer_length;
  1868. int flags = params->flags;
  1869. auto* addr = (sockaddr*)params->addr;
  1870. auto* addr_length = (socklen_t*)params->addr_length;
  1871. if (!validate_write(buffer, buffer_length))
  1872. return -EFAULT;
  1873. if (addr_length) {
  1874. if (!validate_read_typed(addr_length))
  1875. return -EFAULT;
  1876. if (!validate_read(addr, *addr_length))
  1877. return -EFAULT;
  1878. } else if (addr) {
  1879. return -EINVAL;
  1880. }
  1881. auto* descriptor = file_descriptor(sockfd);
  1882. if (!descriptor)
  1883. return -EBADF;
  1884. if (!descriptor->is_socket())
  1885. return -ENOTSOCK;
  1886. auto& socket = *descriptor->socket();
  1887. kprintf("recvfrom %p (%u), flags=%u, addr: %p (%p)\n", buffer, buffer_length, flags, addr, addr_length);
  1888. return socket.recvfrom(buffer, buffer_length, flags, addr, addr_length);
  1889. }
  1890. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  1891. {
  1892. if (!validate_read_typed(params))
  1893. return -EFAULT;
  1894. int sockfd = params->sockfd;
  1895. int level = params->level;
  1896. int option = params->option;
  1897. auto* value = params->value;
  1898. auto* value_size = (socklen_t*)params->value_size;
  1899. if (!validate_write_typed(value_size))
  1900. return -EFAULT;
  1901. if (!validate_write(value, *value_size))
  1902. return -EFAULT;
  1903. auto* descriptor = file_descriptor(sockfd);
  1904. if (!descriptor)
  1905. return -EBADF;
  1906. if (!descriptor->is_socket())
  1907. return -ENOTSOCK;
  1908. auto& socket = *descriptor->socket();
  1909. return socket.getsockopt(level, option, value, value_size);
  1910. }
  1911. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  1912. {
  1913. if (!validate_read_typed(params))
  1914. return -EFAULT;
  1915. int sockfd = params->sockfd;
  1916. int level = params->level;
  1917. int option = params->option;
  1918. auto* value = params->value;
  1919. auto value_size = (socklen_t)params->value_size;
  1920. if (!validate_read(value, value_size))
  1921. return -EFAULT;
  1922. auto* descriptor = file_descriptor(sockfd);
  1923. if (!descriptor)
  1924. return -EBADF;
  1925. if (!descriptor->is_socket())
  1926. return -ENOTSOCK;
  1927. auto& socket = *descriptor->socket();
  1928. return socket.setsockopt(level, option, value, value_size);
  1929. }
  1930. struct SharedBuffer {
  1931. SharedBuffer(pid_t pid1, pid_t pid2, int size)
  1932. : m_pid1(pid1)
  1933. , m_pid2(pid2)
  1934. , m_vmo(VMObject::create_anonymous(size))
  1935. {
  1936. ASSERT(pid1 != pid2);
  1937. }
  1938. void* retain(Process& process)
  1939. {
  1940. if (m_pid1 == process.pid()) {
  1941. ++m_pid1_retain_count;
  1942. if (!m_pid1_region) {
  1943. m_pid1_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, m_pid1_writable);
  1944. m_pid1_region->set_shared(true);
  1945. }
  1946. return m_pid1_region->laddr().as_ptr();
  1947. } else if (m_pid2 == process.pid()) {
  1948. ++m_pid2_retain_count;
  1949. if (!m_pid2_region) {
  1950. m_pid2_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, m_pid2_writable);
  1951. m_pid2_region->set_shared(true);
  1952. }
  1953. return m_pid2_region->laddr().as_ptr();
  1954. }
  1955. return nullptr;
  1956. }
  1957. void release(Process& process)
  1958. {
  1959. if (m_pid1 == process.pid()) {
  1960. ASSERT(m_pid1_retain_count);
  1961. --m_pid1_retain_count;
  1962. if (!m_pid1_retain_count) {
  1963. if (m_pid1_region)
  1964. process.deallocate_region(*m_pid1_region);
  1965. m_pid1_region = nullptr;
  1966. }
  1967. destroy_if_unused();
  1968. } else if (m_pid2 == process.pid()) {
  1969. ASSERT(m_pid2_retain_count);
  1970. --m_pid2_retain_count;
  1971. if (!m_pid2_retain_count) {
  1972. if (m_pid2_region)
  1973. process.deallocate_region(*m_pid2_region);
  1974. m_pid2_region = nullptr;
  1975. }
  1976. destroy_if_unused();
  1977. }
  1978. }
  1979. void disown(pid_t pid)
  1980. {
  1981. if (m_pid1 == pid) {
  1982. m_pid1 = 0;
  1983. m_pid1_retain_count = 0;
  1984. destroy_if_unused();
  1985. } else if (m_pid2 == pid) {
  1986. m_pid2 = 0;
  1987. m_pid2_retain_count = 0;
  1988. destroy_if_unused();
  1989. }
  1990. }
  1991. pid_t pid1() const { return m_pid1; }
  1992. pid_t pid2() const { return m_pid2; }
  1993. unsigned pid1_retain_count() const { return m_pid1_retain_count; }
  1994. unsigned pid2_retain_count() const { return m_pid2_retain_count; }
  1995. size_t size() const { return m_vmo->size(); }
  1996. void destroy_if_unused();
  1997. void seal()
  1998. {
  1999. m_pid1_writable = false;
  2000. m_pid2_writable = false;
  2001. if (m_pid1_region) {
  2002. m_pid1_region->set_writable(false);
  2003. MM.remap_region(*m_pid1_region->page_directory(), *m_pid1_region);
  2004. }
  2005. if (m_pid2_region) {
  2006. m_pid2_region->set_writable(false);
  2007. MM.remap_region(*m_pid2_region->page_directory(), *m_pid2_region);
  2008. }
  2009. }
  2010. int m_shared_buffer_id { -1 };
  2011. pid_t m_pid1;
  2012. pid_t m_pid2;
  2013. unsigned m_pid1_retain_count { 1 };
  2014. unsigned m_pid2_retain_count { 0 };
  2015. Region* m_pid1_region { nullptr };
  2016. Region* m_pid2_region { nullptr };
  2017. bool m_pid1_writable { false };
  2018. bool m_pid2_writable { false };
  2019. Retained<VMObject> m_vmo;
  2020. };
  2021. static int s_next_shared_buffer_id;
  2022. Lockable<HashMap<int, OwnPtr<SharedBuffer>>>& shared_buffers()
  2023. {
  2024. static Lockable<HashMap<int, OwnPtr<SharedBuffer>>>* map;
  2025. if (!map)
  2026. map = new Lockable<HashMap<int, OwnPtr<SharedBuffer>>>;
  2027. return *map;
  2028. }
  2029. void SharedBuffer::destroy_if_unused()
  2030. {
  2031. if (!m_pid1_retain_count && !m_pid2_retain_count) {
  2032. LOCKER(shared_buffers().lock());
  2033. #ifdef SHARED_BUFFER_DEBUG
  2034. kprintf("Destroying unused SharedBuffer{%p} id: %d (pid1: %d, pid2: %d)\n", this, m_shared_buffer_id, m_pid1, m_pid2);
  2035. #endif
  2036. size_t count_before = shared_buffers().resource().size();
  2037. shared_buffers().resource().remove(m_shared_buffer_id);
  2038. ASSERT(count_before != shared_buffers().resource().size());
  2039. }
  2040. }
  2041. void Process::disown_all_shared_buffers()
  2042. {
  2043. LOCKER(shared_buffers().lock());
  2044. Vector<SharedBuffer*, 32> buffers_to_disown;
  2045. for (auto& it : shared_buffers().resource())
  2046. buffers_to_disown.append(it.value.ptr());
  2047. for (auto* shared_buffer : buffers_to_disown)
  2048. shared_buffer->disown(m_pid);
  2049. }
  2050. int Process::sys$create_shared_buffer(pid_t peer_pid, int size, void** buffer)
  2051. {
  2052. if (!size || size < 0)
  2053. return -EINVAL;
  2054. size = PAGE_ROUND_UP(size);
  2055. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2056. return -EINVAL;
  2057. if (!validate_write_typed(buffer))
  2058. return -EFAULT;
  2059. {
  2060. InterruptDisabler disabler;
  2061. auto* peer = Process::from_pid(peer_pid);
  2062. if (!peer)
  2063. return -ESRCH;
  2064. }
  2065. LOCKER(shared_buffers().lock());
  2066. int shared_buffer_id = ++s_next_shared_buffer_id;
  2067. auto shared_buffer = make<SharedBuffer>(m_pid, peer_pid, size);
  2068. shared_buffer->m_shared_buffer_id = shared_buffer_id;
  2069. ASSERT(shared_buffer->size() >= size);
  2070. shared_buffer->m_pid1_region = allocate_region_with_vmo(LinearAddress(), shared_buffer->size(), shared_buffer->m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2071. shared_buffer->m_pid1_region->set_shared(true);
  2072. *buffer = shared_buffer->m_pid1_region->laddr().as_ptr();
  2073. #ifdef SHARED_BUFFER_DEBUG
  2074. kprintf("%s(%u): Created shared buffer %d (%u bytes, vmo is %u) for sharing with %d\n", name().characters(), pid(),shared_buffer_id, size, shared_buffer->size(), peer_pid);
  2075. #endif
  2076. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2077. return shared_buffer_id;
  2078. }
  2079. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2080. {
  2081. LOCKER(shared_buffers().lock());
  2082. auto it = shared_buffers().resource().find(shared_buffer_id);
  2083. if (it == shared_buffers().resource().end())
  2084. return -EINVAL;
  2085. auto& shared_buffer = *(*it).value;
  2086. #ifdef SHARED_BUFFER_DEBUG
  2087. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2088. #endif
  2089. shared_buffer.release(*this);
  2090. return 0;
  2091. }
  2092. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2093. {
  2094. LOCKER(shared_buffers().lock());
  2095. auto it = shared_buffers().resource().find(shared_buffer_id);
  2096. if (it == shared_buffers().resource().end())
  2097. return (void*)-EINVAL;
  2098. auto& shared_buffer = *(*it).value;
  2099. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2100. return (void*)-EINVAL;
  2101. #ifdef SHARED_BUFFER_DEBUG
  2102. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2103. #endif
  2104. return shared_buffer.retain(*this);
  2105. }
  2106. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  2107. {
  2108. LOCKER(shared_buffers().lock());
  2109. auto it = shared_buffers().resource().find(shared_buffer_id);
  2110. if (it == shared_buffers().resource().end())
  2111. return -EINVAL;
  2112. auto& shared_buffer = *(*it).value;
  2113. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2114. return -EINVAL;
  2115. #ifdef SHARED_BUFFER_DEBUG
  2116. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  2117. #endif
  2118. shared_buffer.seal();
  2119. return 0;
  2120. }
  2121. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  2122. {
  2123. LOCKER(shared_buffers().lock());
  2124. auto it = shared_buffers().resource().find(shared_buffer_id);
  2125. if (it == shared_buffers().resource().end())
  2126. return -EINVAL;
  2127. auto& shared_buffer = *(*it).value;
  2128. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2129. return -EINVAL;
  2130. #ifdef SHARED_BUFFER_DEBUG
  2131. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2132. #endif
  2133. return shared_buffer.size();
  2134. }
  2135. const char* to_string(Process::Priority priority)
  2136. {
  2137. switch (priority) {
  2138. case Process::IdlePriority: return "Idle";
  2139. case Process::LowPriority: return "Low";
  2140. case Process::NormalPriority: return "Normal";
  2141. case Process::HighPriority: return "High";
  2142. }
  2143. kprintf("to_string(Process::Priority): Invalid priority: %u\n", priority);
  2144. ASSERT_NOT_REACHED();
  2145. return nullptr;
  2146. }
  2147. void Process::terminate_due_to_signal(byte signal)
  2148. {
  2149. ASSERT_INTERRUPTS_DISABLED();
  2150. ASSERT(signal < 32);
  2151. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  2152. m_termination_status = 0;
  2153. m_termination_signal = signal;
  2154. die();
  2155. }
  2156. void Process::send_signal(byte signal, Process* sender)
  2157. {
  2158. // FIXME(Thread): Find the appropriate thread to deliver the signal to.
  2159. main_thread().send_signal(signal, sender);
  2160. }
  2161. int Process::thread_count() const
  2162. {
  2163. int count = 0;
  2164. for_each_thread([&count] (auto&) {
  2165. ++count;
  2166. return IterationDecision::Continue;
  2167. });
  2168. return count;
  2169. }
  2170. int Process::sys$create_thread(int(*entry)(void*), void* argument)
  2171. {
  2172. if (!validate_read((const void*)entry, sizeof(void*)))
  2173. return -EFAULT;
  2174. auto* thread = new Thread(*this);
  2175. auto& tss = thread->tss();
  2176. tss.eip = (dword)entry;
  2177. tss.eflags = 0x0202;
  2178. tss.cr3 = page_directory().cr3();
  2179. thread->make_userspace_stack_for_secondary_thread(argument);
  2180. thread->set_state(Thread::State::Runnable);
  2181. return 0;
  2182. }
  2183. int Process::sys$gettid()
  2184. {
  2185. return current->tid();
  2186. }
  2187. int Process::sys$donate(int tid)
  2188. {
  2189. if (tid < 0)
  2190. return -EINVAL;
  2191. InterruptDisabler disabler;
  2192. Thread* beneficiary = nullptr;
  2193. for_each_thread([&] (Thread& thread) {
  2194. if (thread.tid() == tid) {
  2195. beneficiary = &thread;
  2196. return IterationDecision::Abort;
  2197. }
  2198. return IterationDecision::Continue;
  2199. });
  2200. if (!beneficiary)
  2201. return -ENOTHREAD;
  2202. Scheduler::donate_to(beneficiary, "sys$donate");
  2203. return 0;
  2204. }
  2205. int Process::sys$rename(const char* oldpath, const char* newpath)
  2206. {
  2207. if (!validate_read_str(oldpath))
  2208. return -EFAULT;
  2209. if (!validate_read_str(newpath))
  2210. return -EFAULT;
  2211. return VFS::the().rename(StringView(oldpath), StringView(newpath), cwd_inode());
  2212. }
  2213. int Process::sys$shm_open(const char* name, int flags, mode_t mode)
  2214. {
  2215. if (!validate_read_str(name))
  2216. return -EFAULT;
  2217. int fd = alloc_fd();
  2218. if (fd < 0)
  2219. return fd;
  2220. auto shm_or_error = SharedMemory::open(String(name), flags, mode);
  2221. if (shm_or_error.is_error())
  2222. return shm_or_error.error();
  2223. auto descriptor = FileDescriptor::create(shm_or_error.value().ptr());
  2224. m_fds[fd].set(move(descriptor), FD_CLOEXEC);
  2225. return fd;
  2226. }
  2227. int Process::sys$shm_unlink(const char* name)
  2228. {
  2229. if (!validate_read_str(name))
  2230. return -EFAULT;
  2231. return SharedMemory::unlink(String(name));
  2232. }
  2233. int Process::sys$ftruncate(int fd, off_t length)
  2234. {
  2235. auto* descriptor = file_descriptor(fd);
  2236. if (!descriptor)
  2237. return -EBADF;
  2238. // FIXME: Check that fd is writable, otherwise EINVAL.
  2239. if (!descriptor->is_file() && !descriptor->is_shared_memory())
  2240. return -EINVAL;
  2241. return descriptor->truncate(length);
  2242. }