Process.cpp 77 KB

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