Process.cpp 85 KB

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