Process.cpp 78 KB

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