Process.cpp 74 KB

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