Process.cpp 74 KB

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