Process.cpp 74 KB

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