Process.cpp 80 KB

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