Process.cpp 79 KB

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