Process.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. #include "types.h"
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "StdLib.h"
  5. #include "i386.h"
  6. #include "system.h"
  7. #include <Kernel/FileDescriptor.h>
  8. #include <Kernel/VirtualFileSystem.h>
  9. #include <Kernel/NullDevice.h>
  10. #include "ELFLoader.h"
  11. #include "MemoryManager.h"
  12. #include "i8253.h"
  13. #include "RTC.h"
  14. #include <AK/StdLibExtras.h>
  15. #include <LibC/signal_numbers.h>
  16. #include <LibC/errno_numbers.h>
  17. #include "Syscall.h"
  18. #include "Scheduler.h"
  19. #include "FIFO.h"
  20. #include "KSyms.h"
  21. #include <WindowServer/WSMessageLoop.h>
  22. #include <Kernel/BochsVGADevice.h>
  23. #include <Kernel/Socket.h>
  24. #include "MasterPTY.h"
  25. #include "elf.h"
  26. //#define DEBUG_IO
  27. //#define TASK_DEBUG
  28. //#define FORK_DEBUG
  29. #define SIGNAL_DEBUG
  30. #define MAX_PROCESS_GIDS 32
  31. static const dword default_kernel_stack_size = 16384;
  32. static const dword default_userspace_stack_size = 65536;
  33. static pid_t next_pid;
  34. InlineLinkedList<Process>* g_processes;
  35. static String* s_hostname;
  36. static Lock* s_hostname_lock;
  37. CoolGlobals* g_cool_globals;
  38. void Process::initialize()
  39. {
  40. #ifdef COOL_GLOBALS
  41. g_cool_globals = reinterpret_cast<CoolGlobals*>(0x1000);
  42. #endif
  43. next_pid = 0;
  44. g_processes = new InlineLinkedList<Process>;
  45. s_hostname = new String("courage");
  46. s_hostname_lock = new Lock;
  47. Scheduler::initialize();
  48. new WSMessageLoop;
  49. }
  50. Vector<pid_t> Process::all_pids()
  51. {
  52. Vector<pid_t> pids;
  53. pids.ensure_capacity(system.nprocess);
  54. InterruptDisabler disabler;
  55. for (auto* process = g_processes->head(); process; process = process->next())
  56. pids.append(process->pid());
  57. return pids;
  58. }
  59. Vector<Process*> Process::all_processes()
  60. {
  61. Vector<Process*> processes;
  62. processes.ensure_capacity(system.nprocess);
  63. InterruptDisabler disabler;
  64. for (auto* process = g_processes->head(); process; process = process->next())
  65. processes.append(process);
  66. return processes;
  67. }
  68. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  69. {
  70. size = PAGE_ROUND_UP(size);
  71. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  72. if (laddr.is_null()) {
  73. laddr = m_next_region;
  74. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  75. }
  76. laddr.mask(0xfffff000);
  77. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  78. MM.map_region(*this, *m_regions.last());
  79. if (commit)
  80. m_regions.last()->commit();
  81. return m_regions.last().ptr();
  82. }
  83. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  84. {
  85. size = PAGE_ROUND_UP(size);
  86. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  87. if (laddr.is_null()) {
  88. laddr = m_next_region;
  89. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  90. }
  91. laddr.mask(0xfffff000);
  92. m_regions.append(adopt(*new Region(laddr, size, move(inode), move(name), is_readable, is_writable)));
  93. MM.map_region(*this, *m_regions.last());
  94. return m_regions.last().ptr();
  95. }
  96. Region* Process::allocate_region_with_vmo(LinearAddress laddr, size_t size, RetainPtr<VMObject>&& vmo, size_t offset_in_vmo, String&& name, bool is_readable, bool is_writable)
  97. {
  98. ASSERT(vmo);
  99. size = PAGE_ROUND_UP(size);
  100. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  101. if (laddr.is_null()) {
  102. laddr = m_next_region;
  103. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  104. }
  105. laddr.mask(0xfffff000);
  106. offset_in_vmo &= PAGE_MASK;
  107. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  108. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  109. MM.map_region(*this, *m_regions.last());
  110. return m_regions.last().ptr();
  111. }
  112. bool Process::deallocate_region(Region& region)
  113. {
  114. InterruptDisabler disabler;
  115. for (size_t i = 0; i < m_regions.size(); ++i) {
  116. if (m_regions[i].ptr() == &region) {
  117. MM.unmap_region(region);
  118. m_regions.remove(i);
  119. return true;
  120. }
  121. }
  122. return false;
  123. }
  124. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  125. {
  126. for (auto& region : m_regions) {
  127. if (region->laddr() == laddr && region->size() == size)
  128. return region.ptr();
  129. }
  130. return nullptr;
  131. }
  132. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  133. {
  134. if (!validate_read_str(name))
  135. return -EFAULT;
  136. auto* region = region_from_range(LinearAddress((dword)addr), size);
  137. if (!region)
  138. return -EINVAL;
  139. region->set_name(String(name));
  140. return 0;
  141. }
  142. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  143. {
  144. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  145. return (void*)-EFAULT;
  146. void* addr = (void*)params->addr;
  147. size_t size = params->size;
  148. int prot = params->prot;
  149. int flags = params->flags;
  150. int fd = params->fd;
  151. off_t offset = params->offset;
  152. if (size == 0)
  153. return (void*)-EINVAL;
  154. if ((dword)addr & ~PAGE_MASK)
  155. return (void*)-EINVAL;
  156. if (flags & MAP_ANONYMOUS) {
  157. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  158. ASSERT(addr == nullptr);
  159. auto* region = allocate_region(LinearAddress(), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  160. if (!region)
  161. return (void*)-ENOMEM;
  162. return region->laddr().as_ptr();
  163. }
  164. if (offset & ~PAGE_MASK)
  165. return (void*)-EINVAL;
  166. auto* descriptor = file_descriptor(fd);
  167. if (!descriptor)
  168. return (void*)-EBADF;
  169. if (!descriptor->supports_mmap())
  170. return (void*)-ENODEV;
  171. // FIXME: If PROT_EXEC, check that the underlying file system isn't mounted noexec.
  172. auto region_name = descriptor->absolute_path();
  173. InterruptDisabler disabler;
  174. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  175. ASSERT(addr == nullptr);
  176. auto* region = allocate_file_backed_region(LinearAddress(), size, descriptor->inode(), move(region_name), prot & PROT_READ, prot & PROT_WRITE);
  177. if (!region)
  178. return (void*)-ENOMEM;
  179. return region->laddr().as_ptr();
  180. }
  181. int Process::sys$munmap(void* addr, size_t size)
  182. {
  183. auto* region = region_from_range(LinearAddress((dword)addr), size);
  184. if (!region)
  185. return -1;
  186. if (!deallocate_region(*region))
  187. return -1;
  188. return 0;
  189. }
  190. int Process::sys$gethostname(char* buffer, size_t size)
  191. {
  192. if (!validate_write(buffer, size))
  193. return -EFAULT;
  194. LOCKER(*s_hostname_lock);
  195. if (size < (s_hostname->length() + 1))
  196. return -ENAMETOOLONG;
  197. strcpy(buffer, s_hostname->characters());
  198. return 0;
  199. }
  200. Process* Process::fork(RegisterDump& regs)
  201. {
  202. 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);
  203. if (!child)
  204. return nullptr;
  205. memcpy(child->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  206. child->m_signal_mask = m_signal_mask;
  207. #ifdef FORK_DEBUG
  208. dbgprintf("fork: child=%p\n", child);
  209. #endif
  210. child->m_initial_arguments = m_initial_arguments;
  211. child->m_initial_environment = m_initial_environment;
  212. for (auto& region : m_regions) {
  213. #ifdef FORK_DEBUG
  214. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name.characters(), region->laddr().get());
  215. #endif
  216. auto cloned_region = region->clone();
  217. child->m_regions.append(move(cloned_region));
  218. MM.map_region(*child, *child->m_regions.last());
  219. if (region.ptr() == m_display_framebuffer_region.ptr())
  220. child->m_display_framebuffer_region = child->m_regions.last().copy_ref();
  221. }
  222. for (auto gid : m_gids)
  223. child->m_gids.set(gid);
  224. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  225. child->m_tss.ebx = regs.ebx;
  226. child->m_tss.ecx = regs.ecx;
  227. child->m_tss.edx = regs.edx;
  228. child->m_tss.ebp = regs.ebp;
  229. child->m_tss.esp = regs.esp_if_crossRing;
  230. child->m_tss.esi = regs.esi;
  231. child->m_tss.edi = regs.edi;
  232. child->m_tss.eflags = regs.eflags;
  233. child->m_tss.eip = regs.eip;
  234. child->m_tss.cs = regs.cs;
  235. child->m_tss.ds = regs.ds;
  236. child->m_tss.es = regs.es;
  237. child->m_tss.fs = regs.fs;
  238. child->m_tss.gs = regs.gs;
  239. child->m_tss.ss = regs.ss_if_crossRing;
  240. child->m_fpu_state = m_fpu_state;
  241. child->m_has_used_fpu = m_has_used_fpu;
  242. #ifdef FORK_DEBUG
  243. dbgprintf("fork: child will begin executing at %w:%x with stack %w:%x\n", child->m_tss.cs, child->m_tss.eip, child->m_tss.ss, child->m_tss.esp);
  244. #endif
  245. {
  246. InterruptDisabler disabler;
  247. g_processes->prepend(child);
  248. system.nprocess++;
  249. }
  250. #ifdef TASK_DEBUG
  251. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  252. #endif
  253. return child;
  254. }
  255. pid_t Process::sys$fork(RegisterDump& regs)
  256. {
  257. auto* child = fork(regs);
  258. ASSERT(child);
  259. return child->pid();
  260. }
  261. int Process::do_exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  262. {
  263. ASSERT(is_ring3());
  264. auto parts = path.split('/');
  265. if (parts.is_empty())
  266. return -ENOENT;
  267. int error;
  268. auto descriptor = VFS::the().open(path, error, 0, 0, *cwd_inode());
  269. if (!descriptor) {
  270. ASSERT(error != 0);
  271. return error;
  272. }
  273. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  274. return -EACCES;
  275. if (!descriptor->metadata().size) {
  276. kprintf("exec() of 0-length binaries not supported\n");
  277. return -ENOTIMPL;
  278. }
  279. dword entry_eip = 0;
  280. // FIXME: Is there a race here?
  281. auto old_page_directory = move(m_page_directory);
  282. m_page_directory = PageDirectory::create();
  283. #ifdef MM_DEBUG
  284. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  285. #endif
  286. ProcessPagingScope paging_scope(*this);
  287. auto vmo = VMObject::create_file_backed(descriptor->inode());
  288. vmo->set_name(descriptor->absolute_path());
  289. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "executable", true, false);
  290. // FIXME: Should we consider doing on-demand paging here? Is it actually useful?
  291. bool success = region->page_in();
  292. ASSERT(success);
  293. {
  294. // Okay, here comes the sleight of hand, pay close attention..
  295. auto old_regions = move(m_regions);
  296. ELFLoader loader(region->laddr().as_ptr());
  297. 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) {
  298. ASSERT(size);
  299. ASSERT(alignment == PAGE_SIZE);
  300. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  301. (void) allocate_region_with_vmo(laddr, size, vmo.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  302. return laddr.as_ptr();
  303. };
  304. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  305. ASSERT(size);
  306. ASSERT(alignment == PAGE_SIZE);
  307. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  308. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  309. return laddr.as_ptr();
  310. };
  311. bool success = loader.load();
  312. if (!success) {
  313. m_page_directory = move(old_page_directory);
  314. // FIXME: RAII this somehow instead.
  315. ASSERT(current == this);
  316. MM.enter_process_paging_scope(*this);
  317. m_regions = move(old_regions);
  318. kprintf("sys$execve: Failure loading %s\n", path.characters());
  319. return -ENOEXEC;
  320. }
  321. entry_eip = loader.entry().get();
  322. if (!entry_eip) {
  323. m_page_directory = move(old_page_directory);
  324. // FIXME: RAII this somehow instead.
  325. ASSERT(current == this);
  326. MM.enter_process_paging_scope(*this);
  327. m_regions = move(old_regions);
  328. return -ENOEXEC;
  329. }
  330. }
  331. m_signal_stack_kernel_region = nullptr;
  332. m_signal_stack_user_region = nullptr;
  333. m_display_framebuffer_region = nullptr;
  334. set_default_signal_dispositions();
  335. m_signal_mask = 0xffffffff;
  336. m_pending_signals = 0;
  337. for (size_t 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 == this)
  348. cli();
  349. Scheduler::prepare_to_modify_tss(*this);
  350. m_name = parts.take_last();
  351. dword old_esp0 = m_tss.esp0;
  352. memset(&m_tss, 0, sizeof(m_tss));
  353. m_tss.eflags = 0x0202;
  354. m_tss.eip = entry_eip;
  355. m_tss.cs = 0x1b;
  356. m_tss.ds = 0x23;
  357. m_tss.es = 0x23;
  358. m_tss.fs = 0x23;
  359. m_tss.gs = 0x23;
  360. m_tss.ss = 0x23;
  361. m_tss.cr3 = page_directory().cr3();
  362. m_stack_region = allocate_region(LinearAddress(), default_userspace_stack_size, "stack");
  363. ASSERT(m_stack_region);
  364. m_stack_top3 = m_stack_region->laddr().offset(default_userspace_stack_size).get();
  365. m_tss.esp = m_stack_top3;
  366. m_tss.ss0 = 0x10;
  367. m_tss.esp0 = old_esp0;
  368. m_tss.ss2 = m_pid;
  369. m_executable = descriptor->inode();
  370. m_initial_arguments = move(arguments);
  371. m_initial_environment = move(environment);
  372. #ifdef TASK_DEBUG
  373. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), m_tss.eip);
  374. #endif
  375. set_state(Skip1SchedulerPass);
  376. return 0;
  377. }
  378. int Process::exec(const 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(path, move(arguments), move(environment));
  383. if (rc < 0)
  384. return rc;
  385. if (current == 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. if (!validate_read_str(filename))
  394. return -EFAULT;
  395. if (argv) {
  396. if (!validate_read_typed(argv))
  397. return -EFAULT;
  398. for (size_t i = 0; argv[i]; ++i) {
  399. if (!validate_read_str(argv[i]))
  400. return -EFAULT;
  401. }
  402. }
  403. if (envp) {
  404. if (!validate_read_typed(envp))
  405. return -EFAULT;
  406. for (size_t i = 0; envp[i]; ++i) {
  407. if (!validate_read_str(envp[i]))
  408. return -EFAULT;
  409. }
  410. }
  411. String path(filename);
  412. auto parts = path.split('/');
  413. Vector<String> arguments;
  414. if (argv) {
  415. for (size_t i = 0; argv[i]; ++i) {
  416. arguments.append(argv[i]);
  417. }
  418. } else {
  419. arguments.append(parts.last());
  420. }
  421. Vector<String> environment;
  422. if (envp) {
  423. for (size_t i = 0; envp[i]; ++i)
  424. environment.append(envp[i]);
  425. }
  426. int rc = exec(path, move(arguments), move(environment));
  427. ASSERT(rc < 0); // We should never continue after a successful exec!
  428. return rc;
  429. }
  430. 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)
  431. {
  432. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  433. auto parts = path.split('/');
  434. if (arguments.is_empty()) {
  435. arguments.append(parts.last());
  436. }
  437. RetainPtr<Inode> cwd;
  438. {
  439. InterruptDisabler disabler;
  440. if (auto* parent = Process::from_pid(parent_pid))
  441. cwd = parent->m_cwd.copy_ref();
  442. }
  443. if (!cwd)
  444. cwd = VFS::the().root_inode();
  445. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  446. error = process->exec(path, move(arguments), move(environment));
  447. if (error != 0) {
  448. delete process;
  449. return nullptr;
  450. }
  451. {
  452. InterruptDisabler disabler;
  453. g_processes->prepend(process);
  454. system.nprocess++;
  455. }
  456. #ifdef TASK_DEBUG
  457. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  458. #endif
  459. error = 0;
  460. return process;
  461. }
  462. int Process::sys$get_environment(char*** environ)
  463. {
  464. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
  465. if (!region)
  466. return -ENOMEM;
  467. MM.map_region(*this, *region);
  468. char* envpage = (char*)region->laddr().get();
  469. *environ = (char**)envpage;
  470. char* bufptr = envpage + (sizeof(char*) * (m_initial_environment.size() + 1));
  471. for (size_t i = 0; i < m_initial_environment.size(); ++i) {
  472. (*environ)[i] = bufptr;
  473. memcpy(bufptr, m_initial_environment[i].characters(), m_initial_environment[i].length());
  474. bufptr += m_initial_environment[i].length();
  475. *(bufptr++) = '\0';
  476. }
  477. (*environ)[m_initial_environment.size()] = nullptr;
  478. return 0;
  479. }
  480. int Process::sys$get_arguments(int* argc, char*** argv)
  481. {
  482. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
  483. if (!region)
  484. return -ENOMEM;
  485. MM.map_region(*this, *region);
  486. char* argpage = (char*)region->laddr().get();
  487. *argc = m_initial_arguments.size();
  488. *argv = (char**)argpage;
  489. char* bufptr = argpage + (sizeof(char*) * (m_initial_arguments.size() + 1));
  490. for (size_t i = 0; i < m_initial_arguments.size(); ++i) {
  491. (*argv)[i] = bufptr;
  492. memcpy(bufptr, m_initial_arguments[i].characters(), m_initial_arguments[i].length());
  493. bufptr += m_initial_arguments[i].length();
  494. *(bufptr++) = '\0';
  495. }
  496. (*argv)[m_initial_arguments.size()] = nullptr;
  497. return 0;
  498. }
  499. Process* Process::create_kernel_process(String&& name, void (*e)())
  500. {
  501. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  502. process->m_tss.eip = (dword)e;
  503. if (process->pid() != 0) {
  504. {
  505. InterruptDisabler disabler;
  506. g_processes->prepend(process);
  507. system.nprocess++;
  508. }
  509. #ifdef TASK_DEBUG
  510. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  511. #endif
  512. }
  513. return process;
  514. }
  515. 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)
  516. : m_name(move(name))
  517. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  518. , m_uid(uid)
  519. , m_gid(gid)
  520. , m_euid(uid)
  521. , m_egid(gid)
  522. , m_state(Runnable)
  523. , m_ring(ring)
  524. , m_cwd(move(cwd))
  525. , m_executable(move(executable))
  526. , m_tty(tty)
  527. , m_ppid(ppid)
  528. {
  529. set_default_signal_dispositions();
  530. memset(&m_fpu_state, 0, sizeof(FPUState));
  531. m_gids.set(m_gid);
  532. if (fork_parent) {
  533. m_sid = fork_parent->m_sid;
  534. m_pgid = fork_parent->m_pgid;
  535. } else {
  536. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  537. InterruptDisabler disabler;
  538. if (auto* parent = Process::from_pid(m_ppid)) {
  539. m_sid = parent->m_sid;
  540. m_pgid = parent->m_pgid;
  541. }
  542. }
  543. m_page_directory = PageDirectory::create();
  544. #ifdef MM_DEBUG
  545. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  546. #endif
  547. if (fork_parent) {
  548. m_fds.resize(fork_parent->m_fds.size());
  549. for (size_t i = 0; i < fork_parent->m_fds.size(); ++i) {
  550. if (!fork_parent->m_fds[i].descriptor)
  551. continue;
  552. #ifdef FORK_DEBUG
  553. 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());
  554. #endif
  555. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  556. m_fds[i].flags = fork_parent->m_fds[i].flags;
  557. }
  558. } else {
  559. m_fds.resize(m_max_open_file_descriptors);
  560. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  561. int error;
  562. m_fds[0].set(device_to_use_as_tty.open(error, O_RDONLY));
  563. m_fds[1].set(device_to_use_as_tty.open(error, O_WRONLY));
  564. m_fds[2].set(device_to_use_as_tty.open(error, O_WRONLY));
  565. }
  566. if (fork_parent)
  567. m_next_region = fork_parent->m_next_region;
  568. else
  569. m_next_region = LinearAddress(0x10000000);
  570. if (fork_parent) {
  571. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  572. } else {
  573. memset(&m_tss, 0, sizeof(m_tss));
  574. // Only IF is set when a process boots.
  575. m_tss.eflags = 0x0202;
  576. word cs, ds, ss;
  577. if (is_ring0()) {
  578. cs = 0x08;
  579. ds = 0x10;
  580. ss = 0x10;
  581. } else {
  582. cs = 0x1b;
  583. ds = 0x23;
  584. ss = 0x23;
  585. }
  586. m_tss.ds = ds;
  587. m_tss.es = ds;
  588. m_tss.fs = ds;
  589. m_tss.gs = ds;
  590. m_tss.ss = ss;
  591. m_tss.cs = cs;
  592. }
  593. m_tss.cr3 = page_directory().cr3();
  594. if (is_ring0()) {
  595. // FIXME: This memory is leaked.
  596. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  597. dword stack_bottom = (dword)kmalloc_eternal(default_kernel_stack_size);
  598. m_stack_top0 = (stack_bottom + default_kernel_stack_size) & 0xffffff8;
  599. m_tss.esp = m_stack_top0;
  600. } else {
  601. if (fork_parent) {
  602. m_stack_top3 = fork_parent->m_stack_top3;
  603. } else {
  604. auto* region = allocate_region(LinearAddress(), default_userspace_stack_size, "stack");
  605. ASSERT(region);
  606. m_stack_top3 = region->laddr().offset(default_userspace_stack_size).get();
  607. m_tss.esp = m_stack_top3;
  608. }
  609. }
  610. if (is_ring3()) {
  611. // Ring3 processes need a separate stack for Ring0.
  612. m_kernel_stack = kmalloc(default_kernel_stack_size);
  613. m_stack_top0 = ((dword)m_kernel_stack + default_kernel_stack_size) & 0xffffff8;
  614. m_tss.ss0 = 0x10;
  615. m_tss.esp0 = m_stack_top0;
  616. }
  617. // HACK: Ring2 SS in the TSS is the current PID.
  618. m_tss.ss2 = m_pid;
  619. m_far_ptr.offset = 0x98765432;
  620. }
  621. Process::~Process()
  622. {
  623. {
  624. InterruptDisabler disabler;
  625. system.nprocess--;
  626. }
  627. if (g_last_fpu_process == this)
  628. g_last_fpu_process = nullptr;
  629. if (selector())
  630. gdt_free_entry(selector());
  631. if (m_kernel_stack) {
  632. kfree(m_kernel_stack);
  633. m_kernel_stack = nullptr;
  634. }
  635. }
  636. void Process::dump_regions()
  637. {
  638. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  639. kprintf("BEGIN END SIZE NAME\n");
  640. for (auto& region : m_regions) {
  641. kprintf("%x -- %x %x %s\n",
  642. region->laddr().get(),
  643. region->laddr().offset(region->size() - 1).get(),
  644. region->size(),
  645. region->name().characters());
  646. }
  647. }
  648. void Process::sys$exit(int status)
  649. {
  650. cli();
  651. #ifdef TASK_DEBUG
  652. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  653. #endif
  654. m_termination_status = status;
  655. m_termination_signal = 0;
  656. die();
  657. ASSERT_NOT_REACHED();
  658. }
  659. void Process::terminate_due_to_signal(byte signal)
  660. {
  661. ASSERT_INTERRUPTS_DISABLED();
  662. ASSERT(signal < 32);
  663. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  664. m_termination_status = 0;
  665. m_termination_signal = signal;
  666. die();
  667. }
  668. void Process::send_signal(byte signal, Process* sender)
  669. {
  670. ASSERT_INTERRUPTS_DISABLED();
  671. ASSERT(signal < 32);
  672. if (sender)
  673. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
  674. else
  675. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
  676. m_pending_signals |= 1 << signal;
  677. }
  678. bool Process::has_unmasked_pending_signals() const
  679. {
  680. return m_pending_signals & m_signal_mask;
  681. }
  682. ShouldUnblockProcess Process::dispatch_one_pending_signal()
  683. {
  684. ASSERT_INTERRUPTS_DISABLED();
  685. dword signal_candidates = m_pending_signals & m_signal_mask;
  686. ASSERT(signal_candidates);
  687. byte signal = 0;
  688. for (; signal < 32; ++signal) {
  689. if (signal_candidates & (1 << signal)) {
  690. break;
  691. }
  692. }
  693. return dispatch_signal(signal);
  694. }
  695. ShouldUnblockProcess Process::dispatch_signal(byte signal)
  696. {
  697. ASSERT_INTERRUPTS_DISABLED();
  698. ASSERT(signal < 32);
  699. dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  700. auto& action = m_signal_action_data[signal];
  701. // FIXME: Implement SA_SIGINFO signal handlers.
  702. ASSERT(!(action.flags & SA_SIGINFO));
  703. // Mark this signal as handled.
  704. m_pending_signals &= ~(1 << signal);
  705. auto handler_laddr = action.handler_or_sigaction;
  706. if (handler_laddr.is_null()) {
  707. // FIXME: Is termination really always the appropriate action?
  708. terminate_due_to_signal(signal);
  709. return ShouldUnblockProcess::No;
  710. }
  711. if (handler_laddr.as_ptr() == SIG_IGN) {
  712. dbgprintf("%s(%u) ignored signal %u\n", name().characters(), pid(), signal);
  713. return ShouldUnblockProcess::Yes;
  714. }
  715. Scheduler::prepare_to_modify_tss(*this);
  716. word ret_cs = m_tss.cs;
  717. dword ret_eip = m_tss.eip;
  718. dword ret_eflags = m_tss.eflags;
  719. bool interrupting_in_kernel = (ret_cs & 3) == 0;
  720. if (interrupting_in_kernel) {
  721. dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), to_string(state()), ret_cs, ret_eip);
  722. ASSERT(is_blocked());
  723. m_tss_to_resume_kernel = m_tss;
  724. #ifdef SIGNAL_DEBUG
  725. dbgprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
  726. #endif
  727. }
  728. ProcessPagingScope paging_scope(*this);
  729. if (interrupting_in_kernel) {
  730. if (!m_signal_stack_user_region) {
  731. m_signal_stack_user_region = allocate_region(LinearAddress(), default_userspace_stack_size, "signal stack (user)");
  732. ASSERT(m_signal_stack_user_region);
  733. m_signal_stack_kernel_region = allocate_region(LinearAddress(), default_userspace_stack_size, "signal stack (kernel)");
  734. ASSERT(m_signal_stack_user_region);
  735. }
  736. m_tss.ss = 0x23;
  737. m_tss.esp = m_signal_stack_user_region->laddr().offset(default_userspace_stack_size).get() & 0xfffffff8;
  738. m_tss.ss0 = 0x10;
  739. m_tss.esp0 = m_signal_stack_kernel_region->laddr().offset(default_userspace_stack_size).get() & 0xfffffff8;
  740. push_value_on_stack(ret_eflags);
  741. push_value_on_stack(ret_cs);
  742. push_value_on_stack(ret_eip);
  743. } else {
  744. push_value_on_stack(ret_cs);
  745. push_value_on_stack(ret_eip);
  746. push_value_on_stack(ret_eflags);
  747. }
  748. // PUSHA
  749. dword old_esp = m_tss.esp;
  750. push_value_on_stack(m_tss.eax);
  751. push_value_on_stack(m_tss.ecx);
  752. push_value_on_stack(m_tss.edx);
  753. push_value_on_stack(m_tss.ebx);
  754. push_value_on_stack(old_esp);
  755. push_value_on_stack(m_tss.ebp);
  756. push_value_on_stack(m_tss.esi);
  757. push_value_on_stack(m_tss.edi);
  758. m_tss.eax = (dword)signal;
  759. m_tss.cs = 0x1b;
  760. m_tss.ds = 0x23;
  761. m_tss.es = 0x23;
  762. m_tss.fs = 0x23;
  763. m_tss.gs = 0x23;
  764. m_tss.eip = handler_laddr.get();
  765. if (m_return_to_ring3_from_signal_trampoline.is_null()) {
  766. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  767. // FIXME: Remap as read-only after setup.
  768. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
  769. m_return_to_ring3_from_signal_trampoline = region->laddr();
  770. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.as_ptr();
  771. *code_ptr++ = 0x61; // popa
  772. *code_ptr++ = 0x9d; // popf
  773. *code_ptr++ = 0xc3; // ret
  774. *code_ptr++ = 0x0f; // ud2
  775. *code_ptr++ = 0x0b;
  776. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  777. *code_ptr++ = 0x61; // popa
  778. *code_ptr++ = 0xb8; // mov eax, <dword>
  779. *(dword*)code_ptr = Syscall::SC_sigreturn;
  780. code_ptr += sizeof(dword);
  781. *code_ptr++ = 0xcd; // int 0x80
  782. *code_ptr++ = 0x80;
  783. *code_ptr++ = 0x0f; // ud2
  784. *code_ptr++ = 0x0b;
  785. // FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
  786. // unmasks the signal so it can be received again? I guess then I would need one trampoline
  787. // per signal number if it's hard-coded, but it's just a few bytes per each.
  788. }
  789. if (interrupting_in_kernel)
  790. push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
  791. else
  792. push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
  793. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  794. set_state(Skip1SchedulerPass);
  795. #ifdef SIGNAL_DEBUG
  796. dbgprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", name().characters(), pid(), to_string(state()), m_tss.cs, m_tss.eip);
  797. #endif
  798. return ShouldUnblockProcess::Yes;
  799. }
  800. void Process::sys$sigreturn()
  801. {
  802. InterruptDisabler disabler;
  803. Scheduler::prepare_to_modify_tss(*this);
  804. m_tss = m_tss_to_resume_kernel;
  805. #ifdef SIGNAL_DEBUG
  806. dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  807. dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
  808. #endif
  809. set_state(Skip1SchedulerPass);
  810. Scheduler::yield();
  811. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  812. ASSERT_NOT_REACHED();
  813. }
  814. void Process::push_value_on_stack(dword value)
  815. {
  816. m_tss.esp -= 4;
  817. dword* stack_ptr = (dword*)m_tss.esp;
  818. *stack_ptr = value;
  819. }
  820. void Process::crash()
  821. {
  822. ASSERT_INTERRUPTS_DISABLED();
  823. ASSERT(state() != Dead);
  824. m_termination_signal = SIGSEGV;
  825. dump_regions();
  826. ASSERT(is_ring3());
  827. die();
  828. ASSERT_NOT_REACHED();
  829. }
  830. Process* Process::from_pid(pid_t pid)
  831. {
  832. ASSERT_INTERRUPTS_DISABLED();
  833. for (auto* process = g_processes->head(); process; process = process->next()) {
  834. if (process->pid() == pid)
  835. return process;
  836. }
  837. return nullptr;
  838. }
  839. FileDescriptor* Process::file_descriptor(int fd)
  840. {
  841. if (fd < 0)
  842. return nullptr;
  843. if ((size_t)fd < m_fds.size())
  844. return m_fds[fd].descriptor.ptr();
  845. return nullptr;
  846. }
  847. const FileDescriptor* Process::file_descriptor(int fd) const
  848. {
  849. if (fd < 0)
  850. return nullptr;
  851. if ((size_t)fd < m_fds.size())
  852. return m_fds[fd].descriptor.ptr();
  853. return nullptr;
  854. }
  855. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, size_t size)
  856. {
  857. if (!validate_write(buffer, size))
  858. return -EFAULT;
  859. auto* descriptor = file_descriptor(fd);
  860. if (!descriptor)
  861. return -EBADF;
  862. return descriptor->get_dir_entries((byte*)buffer, size);
  863. }
  864. int Process::sys$lseek(int fd, off_t offset, int whence)
  865. {
  866. auto* descriptor = file_descriptor(fd);
  867. if (!descriptor)
  868. return -EBADF;
  869. return descriptor->seek(offset, whence);
  870. }
  871. int Process::sys$ttyname_r(int fd, char* buffer, size_t size)
  872. {
  873. if (!validate_write(buffer, size))
  874. return -EFAULT;
  875. auto* descriptor = file_descriptor(fd);
  876. if (!descriptor)
  877. return -EBADF;
  878. if (!descriptor->is_tty())
  879. return -ENOTTY;
  880. auto tty_name = descriptor->tty()->tty_name();
  881. if (size < tty_name.length() + 1)
  882. return -ERANGE;
  883. strcpy(buffer, tty_name.characters());
  884. return 0;
  885. }
  886. int Process::sys$ptsname_r(int fd, char* buffer, size_t size)
  887. {
  888. if (!validate_write(buffer, size))
  889. return -EFAULT;
  890. auto* descriptor = file_descriptor(fd);
  891. if (!descriptor)
  892. return -EBADF;
  893. auto* master_pty = descriptor->master_pty();
  894. if (!master_pty)
  895. return -ENOTTY;
  896. auto pts_name = master_pty->pts_name();
  897. if (size < pts_name.length() + 1)
  898. return -ERANGE;
  899. strcpy(buffer, pts_name.characters());
  900. return 0;
  901. }
  902. ssize_t Process::sys$write(int fd, const void* data, size_t size)
  903. {
  904. if (!validate_read(data, size))
  905. return -EFAULT;
  906. #ifdef DEBUG_IO
  907. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  908. #endif
  909. auto* descriptor = file_descriptor(fd);
  910. if (!descriptor)
  911. return -EBADF;
  912. ssize_t nwritten = 0;
  913. if (descriptor->is_blocking()) {
  914. while (nwritten < (ssize_t)size) {
  915. #ifdef IO_DEBUG
  916. dbgprintf("while %u < %u\n", nwritten, size);
  917. #endif
  918. if (!descriptor->can_write(*this)) {
  919. #ifdef IO_DEBUG
  920. dbgprintf("block write on %d\n", fd);
  921. #endif
  922. m_blocked_fd = fd;
  923. block(BlockedWrite);
  924. Scheduler::yield();
  925. }
  926. ssize_t rc = descriptor->write(*this, (const byte*)data + nwritten, size - nwritten);
  927. #ifdef IO_DEBUG
  928. dbgprintf(" -> write returned %d\n", rc);
  929. #endif
  930. if (rc < 0) {
  931. // FIXME: Support returning partial nwritten with errno.
  932. ASSERT(nwritten == 0);
  933. return rc;
  934. }
  935. if (rc == 0)
  936. break;
  937. if (has_unmasked_pending_signals()) {
  938. block(BlockedSignal);
  939. Scheduler::yield();
  940. if (nwritten == 0)
  941. return -EINTR;
  942. }
  943. nwritten += rc;
  944. }
  945. } else {
  946. nwritten = descriptor->write(*this, (const byte*)data, size);
  947. }
  948. if (has_unmasked_pending_signals()) {
  949. block(BlockedSignal);
  950. Scheduler::yield();
  951. if (nwritten == 0)
  952. return -EINTR;
  953. }
  954. #ifdef DEBUG_IO
  955. dbgprintf("%s(%u) sys$write: nwritten=%u\n", name().characters(), pid(), nwritten);
  956. #endif
  957. return nwritten;
  958. }
  959. ssize_t Process::sys$read(int fd, void* outbuf, size_t nread)
  960. {
  961. if (!validate_write(outbuf, nread))
  962. return -EFAULT;
  963. #ifdef DEBUG_IO
  964. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, outbuf, nread);
  965. #endif
  966. auto* descriptor = file_descriptor(fd);
  967. if (!descriptor)
  968. return -EBADF;
  969. #ifdef DEBUG_IO
  970. dbgprintf(" > descriptor:%p, is_blocking:%u, can_read:%u\n", descriptor, descriptor->is_blocking(), descriptor->can_read(*this));
  971. dbgprintf(" > inode:K%x, device:K%x\n", descriptor->inode(), descriptor->character_device());
  972. #endif
  973. if (descriptor->is_blocking()) {
  974. if (!descriptor->can_read(*this)) {
  975. m_blocked_fd = fd;
  976. block(BlockedRead);
  977. Scheduler::yield();
  978. if (m_was_interrupted_while_blocked)
  979. return -EINTR;
  980. }
  981. }
  982. nread = descriptor->read(*this, (byte*)outbuf, nread);
  983. #ifdef DEBUG_IO
  984. dbgprintf("%s(%u) Process::sys$read: nread=%u\n", name().characters(), pid(), nread);
  985. #endif
  986. return nread;
  987. }
  988. int Process::sys$close(int fd)
  989. {
  990. auto* descriptor = file_descriptor(fd);
  991. if (!descriptor)
  992. return -EBADF;
  993. int rc = descriptor->close();
  994. m_fds[fd] = { };
  995. return rc;
  996. }
  997. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  998. {
  999. if (!validate_read_str(pathname))
  1000. return -EFAULT;
  1001. if (buf && !validate_read_typed(buf))
  1002. return -EFAULT;
  1003. String path(pathname);
  1004. int error;
  1005. auto descriptor = VFS::the().open(move(path), error, 0, 0, *cwd_inode());
  1006. if (!descriptor)
  1007. return error;
  1008. auto& inode = *descriptor->inode();
  1009. if (inode.fs().is_readonly())
  1010. return -EROFS;
  1011. time_t atime;
  1012. time_t mtime;
  1013. if (buf) {
  1014. atime = buf->actime;
  1015. mtime = buf->modtime;
  1016. } else {
  1017. auto now = RTC::now();
  1018. mtime = now;
  1019. atime = now;
  1020. }
  1021. inode.set_atime(atime);
  1022. inode.set_mtime(mtime);
  1023. return 0;
  1024. }
  1025. int Process::sys$access(const char* pathname, int mode)
  1026. {
  1027. (void) mode;
  1028. if (!validate_read_str(pathname))
  1029. return -EFAULT;
  1030. ASSERT_NOT_REACHED();
  1031. }
  1032. int Process::sys$fcntl(int fd, int cmd, dword arg)
  1033. {
  1034. (void) cmd;
  1035. (void) arg;
  1036. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1037. auto* descriptor = file_descriptor(fd);
  1038. if (!descriptor)
  1039. return -EBADF;
  1040. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1041. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1042. switch (cmd) {
  1043. case F_DUPFD: {
  1044. int arg_fd = (int)arg;
  1045. if (arg_fd < 0)
  1046. return -EINVAL;
  1047. int new_fd = -1;
  1048. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1049. if (!m_fds[i]) {
  1050. new_fd = i;
  1051. break;
  1052. }
  1053. }
  1054. if (new_fd == -1)
  1055. return -EMFILE;
  1056. m_fds[new_fd].set(descriptor);
  1057. break;
  1058. }
  1059. case F_GETFD:
  1060. return m_fds[fd].flags;
  1061. case F_SETFD:
  1062. m_fds[fd].flags = arg;
  1063. break;
  1064. case F_GETFL:
  1065. return descriptor->file_flags();
  1066. case F_SETFL:
  1067. // FIXME: Support changing O_NONBLOCK
  1068. descriptor->set_file_flags(arg);
  1069. break;
  1070. default:
  1071. ASSERT_NOT_REACHED();
  1072. }
  1073. return 0;
  1074. }
  1075. int Process::sys$fstat(int fd, stat* statbuf)
  1076. {
  1077. if (!validate_write_typed(statbuf))
  1078. return -EFAULT;
  1079. auto* descriptor = file_descriptor(fd);
  1080. if (!descriptor)
  1081. return -EBADF;
  1082. return descriptor->fstat(statbuf);
  1083. }
  1084. int Process::sys$lstat(const char* path, stat* statbuf)
  1085. {
  1086. if (!validate_write_typed(statbuf))
  1087. return -EFAULT;
  1088. int error;
  1089. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR | O_DONT_OPEN_DEVICE, 0, *cwd_inode());
  1090. if (!descriptor)
  1091. return error;
  1092. return descriptor->fstat(statbuf);
  1093. }
  1094. int Process::sys$stat(const char* path, stat* statbuf)
  1095. {
  1096. if (!validate_write_typed(statbuf))
  1097. return -EFAULT;
  1098. int error;
  1099. auto descriptor = VFS::the().open(move(path), error, O_DONT_OPEN_DEVICE, 0, *cwd_inode());
  1100. if (!descriptor)
  1101. return error;
  1102. return descriptor->fstat(statbuf);
  1103. }
  1104. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1105. {
  1106. if (!validate_read_str(path))
  1107. return -EFAULT;
  1108. if (!validate_write(buffer, size))
  1109. return -EFAULT;
  1110. int error;
  1111. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, 0, *cwd_inode());
  1112. if (!descriptor)
  1113. return error;
  1114. if (!descriptor->metadata().is_symlink())
  1115. return -EINVAL;
  1116. auto contents = descriptor->read_entire_file(*this);
  1117. if (!contents)
  1118. return -EIO; // FIXME: Get a more detailed error from VFS.
  1119. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1120. if (contents.size() + 1 < size)
  1121. buffer[contents.size()] = '\0';
  1122. return 0;
  1123. }
  1124. int Process::sys$chdir(const char* path)
  1125. {
  1126. if (!validate_read_str(path))
  1127. return -EFAULT;
  1128. int error;
  1129. auto descriptor = VFS::the().open(path, error, 0, 0, *cwd_inode());
  1130. if (!descriptor)
  1131. return error;
  1132. if (!descriptor->is_directory())
  1133. return -ENOTDIR;
  1134. m_cwd = descriptor->inode();
  1135. return 0;
  1136. }
  1137. int Process::sys$getcwd(char* buffer, size_t size)
  1138. {
  1139. if (!validate_write(buffer, size))
  1140. return -EFAULT;
  1141. ASSERT(cwd_inode());
  1142. auto path = VFS::the().absolute_path(*cwd_inode());
  1143. if (path.is_null())
  1144. return -EINVAL;
  1145. if (size < path.length() + 1)
  1146. return -ERANGE;
  1147. strcpy(buffer, path.characters());
  1148. return 0;
  1149. }
  1150. size_t Process::number_of_open_file_descriptors() const
  1151. {
  1152. size_t count = 0;
  1153. for (auto& descriptor : m_fds) {
  1154. if (descriptor)
  1155. ++count;
  1156. }
  1157. return count;
  1158. }
  1159. int Process::sys$open(const char* path, int options, mode_t mode)
  1160. {
  1161. #ifdef DEBUG_IO
  1162. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1163. #endif
  1164. if (!validate_read_str(path))
  1165. return -EFAULT;
  1166. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1167. return -EMFILE;
  1168. int error = -EWHYTHO;
  1169. ASSERT(cwd_inode());
  1170. auto descriptor = VFS::the().open(path, error, options, mode, *cwd_inode());
  1171. if (!descriptor)
  1172. return error;
  1173. if (options & O_DIRECTORY && !descriptor->is_directory())
  1174. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1175. if (options & O_NONBLOCK)
  1176. descriptor->set_blocking(false);
  1177. int fd = 0;
  1178. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1179. if (!m_fds[fd])
  1180. break;
  1181. }
  1182. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1183. m_fds[fd].set(move(descriptor), flags);
  1184. return fd;
  1185. }
  1186. int Process::alloc_fd()
  1187. {
  1188. int fd = -1;
  1189. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1190. if (!m_fds[i]) {
  1191. fd = i;
  1192. break;
  1193. }
  1194. }
  1195. return fd;
  1196. }
  1197. int Process::sys$pipe(int pipefd[2])
  1198. {
  1199. if (!validate_write_typed(pipefd))
  1200. return -EFAULT;
  1201. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1202. return -EMFILE;
  1203. auto fifo = FIFO::create();
  1204. int reader_fd = alloc_fd();
  1205. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1206. pipefd[0] = reader_fd;
  1207. int writer_fd = alloc_fd();
  1208. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1209. pipefd[1] = writer_fd;
  1210. return 0;
  1211. }
  1212. int Process::sys$killpg(int pgrp, int signum)
  1213. {
  1214. if (signum < 1 || signum >= 32)
  1215. return -EINVAL;
  1216. (void) pgrp;
  1217. ASSERT_NOT_REACHED();
  1218. }
  1219. int Process::sys$setuid(uid_t)
  1220. {
  1221. ASSERT_NOT_REACHED();
  1222. }
  1223. int Process::sys$setgid(gid_t)
  1224. {
  1225. ASSERT_NOT_REACHED();
  1226. }
  1227. unsigned Process::sys$alarm(unsigned seconds)
  1228. {
  1229. (void) seconds;
  1230. ASSERT_NOT_REACHED();
  1231. }
  1232. int Process::sys$uname(utsname* buf)
  1233. {
  1234. if (!validate_write_typed(buf))
  1235. return -EFAULT;
  1236. strcpy(buf->sysname, "Serenity");
  1237. strcpy(buf->release, "1.0-dev");
  1238. strcpy(buf->version, "FIXME");
  1239. strcpy(buf->machine, "i386");
  1240. LOCKER(*s_hostname_lock);
  1241. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1242. return 0;
  1243. }
  1244. int Process::sys$isatty(int fd)
  1245. {
  1246. auto* descriptor = file_descriptor(fd);
  1247. if (!descriptor)
  1248. return -EBADF;
  1249. if (!descriptor->is_tty())
  1250. return -ENOTTY;
  1251. return 1;
  1252. }
  1253. int Process::sys$kill(pid_t pid, int signal)
  1254. {
  1255. if (pid == 0) {
  1256. // FIXME: Send to same-group processes.
  1257. ASSERT(pid != 0);
  1258. }
  1259. if (pid == -1) {
  1260. // FIXME: Send to all processes.
  1261. ASSERT(pid != -1);
  1262. }
  1263. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1264. Process* peer = nullptr;
  1265. {
  1266. InterruptDisabler disabler;
  1267. peer = Process::from_pid(pid);
  1268. }
  1269. if (!peer)
  1270. return -ESRCH;
  1271. peer->send_signal(signal, this);
  1272. return 0;
  1273. }
  1274. int Process::sys$usleep(useconds_t usec)
  1275. {
  1276. if (!usec)
  1277. return 0;
  1278. sleep(usec / 1000);
  1279. if (m_wakeup_time > system.uptime) {
  1280. ASSERT(m_was_interrupted_while_blocked);
  1281. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1282. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1283. }
  1284. return 0;
  1285. }
  1286. int Process::sys$sleep(unsigned seconds)
  1287. {
  1288. if (!seconds)
  1289. return 0;
  1290. sleep(seconds * TICKS_PER_SECOND);
  1291. if (m_wakeup_time > system.uptime) {
  1292. ASSERT(m_was_interrupted_while_blocked);
  1293. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1294. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1295. }
  1296. return 0;
  1297. }
  1298. int Process::sys$gettimeofday(timeval* tv)
  1299. {
  1300. if (!validate_write_typed(tv))
  1301. return -EFAULT;
  1302. auto now = RTC::now();
  1303. tv->tv_sec = now;
  1304. tv->tv_usec = PIT::ticks_since_boot() % 1000;
  1305. return 0;
  1306. }
  1307. uid_t Process::sys$getuid()
  1308. {
  1309. return m_uid;
  1310. }
  1311. gid_t Process::sys$getgid()
  1312. {
  1313. return m_gid;
  1314. }
  1315. uid_t Process::sys$geteuid()
  1316. {
  1317. return m_euid;
  1318. }
  1319. gid_t Process::sys$getegid()
  1320. {
  1321. return m_egid;
  1322. }
  1323. pid_t Process::sys$getpid()
  1324. {
  1325. return m_pid;
  1326. }
  1327. pid_t Process::sys$getppid()
  1328. {
  1329. return m_ppid;
  1330. }
  1331. mode_t Process::sys$umask(mode_t mask)
  1332. {
  1333. auto old_mask = m_umask;
  1334. m_umask = mask;
  1335. return old_mask;
  1336. }
  1337. int Process::reap(Process& process)
  1338. {
  1339. InterruptDisabler disabler;
  1340. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1341. if (process.ppid()) {
  1342. auto* parent = Process::from_pid(process.ppid());
  1343. if (parent) {
  1344. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1345. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1346. }
  1347. }
  1348. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1349. ASSERT(process.state() == Dead);
  1350. g_processes->remove(&process);
  1351. delete &process;
  1352. return exit_status;
  1353. }
  1354. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1355. {
  1356. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1357. // FIXME: Respect options
  1358. (void) options;
  1359. if (wstatus)
  1360. if (!validate_write_typed(wstatus))
  1361. return -EFAULT;
  1362. int dummy_wstatus;
  1363. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1364. {
  1365. InterruptDisabler disabler;
  1366. if (waitee != -1 && !Process::from_pid(waitee))
  1367. return -ECHILD;
  1368. }
  1369. if (options & WNOHANG) {
  1370. if (waitee == -1) {
  1371. pid_t reaped_pid = 0;
  1372. InterruptDisabler disabler;
  1373. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1374. if (process.state() == Dead) {
  1375. reaped_pid = process.pid();
  1376. exit_status = reap(process);
  1377. }
  1378. return true;
  1379. });
  1380. return reaped_pid;
  1381. } else {
  1382. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1383. auto* waitee_process = Process::from_pid(waitee);
  1384. if (!waitee_process)
  1385. return -ECHILD;
  1386. if (waitee_process->state() == Dead) {
  1387. exit_status = reap(*waitee_process);
  1388. return waitee;
  1389. }
  1390. return 0;
  1391. }
  1392. }
  1393. m_waitee_pid = waitee;
  1394. block(BlockedWait);
  1395. Scheduler::yield();
  1396. if (m_was_interrupted_while_blocked)
  1397. return -EINTR;
  1398. Process* waitee_process;
  1399. {
  1400. InterruptDisabler disabler;
  1401. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1402. waitee_process = Process::from_pid(m_waitee_pid);
  1403. }
  1404. ASSERT(waitee_process);
  1405. exit_status = reap(*waitee_process);
  1406. return m_waitee_pid;
  1407. }
  1408. void Process::unblock()
  1409. {
  1410. if (current == this) {
  1411. system.nblocked--;
  1412. m_state = Process::Running;
  1413. return;
  1414. }
  1415. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1416. system.nblocked--;
  1417. m_state = Process::Runnable;
  1418. }
  1419. void Process::block(Process::State new_state)
  1420. {
  1421. if (state() != Process::Running) {
  1422. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, to_string(new_state), state(), to_string(state()));
  1423. }
  1424. ASSERT(state() == Process::Running);
  1425. system.nblocked++;
  1426. m_was_interrupted_while_blocked = false;
  1427. set_state(new_state);
  1428. }
  1429. void block(Process::State state)
  1430. {
  1431. current->block(state);
  1432. Scheduler::yield();
  1433. }
  1434. void sleep(dword ticks)
  1435. {
  1436. ASSERT(current->state() == Process::Running);
  1437. current->set_wakeup_time(system.uptime + ticks);
  1438. current->block(Process::BlockedSleep);
  1439. Scheduler::yield();
  1440. }
  1441. enum class KernelMemoryCheckResult {
  1442. NotInsideKernelMemory,
  1443. AccessGranted,
  1444. AccessDenied
  1445. };
  1446. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1447. {
  1448. auto* kernel_elf_header = (Elf32_Ehdr*)0xf000;
  1449. auto* kernel_program_headers = (Elf32_Phdr*)(0xf000 + kernel_elf_header->e_phoff);
  1450. for (unsigned i = 0; i < kernel_elf_header->e_phnum; ++i) {
  1451. auto& segment = kernel_program_headers[i];
  1452. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1453. continue;
  1454. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1455. continue;
  1456. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1457. return KernelMemoryCheckResult::AccessDenied;
  1458. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1459. return KernelMemoryCheckResult::AccessDenied;
  1460. return KernelMemoryCheckResult::AccessGranted;
  1461. }
  1462. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1463. }
  1464. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1465. {
  1466. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1467. // This code allows access outside of the known used address ranges to get caught.
  1468. auto kmc_result = check_kernel_memory_access(laddr, false);
  1469. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1470. return true;
  1471. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1472. return false;
  1473. if (is_kmalloc_address(laddr.as_ptr()))
  1474. return true;
  1475. return validate_read(laddr.as_ptr(), 1);
  1476. }
  1477. bool Process::validate_read_str(const char* str)
  1478. {
  1479. if (!validate_read(str, 1))
  1480. return false;
  1481. return validate_read(str, strlen(str) + 1);
  1482. }
  1483. bool Process::validate_read(const void* address, size_t size) const
  1484. {
  1485. LinearAddress first_address((dword)address);
  1486. LinearAddress last_address = first_address.offset(size - 1);
  1487. if (is_ring0()) {
  1488. auto kmc_result = check_kernel_memory_access(first_address, false);
  1489. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1490. return true;
  1491. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1492. return false;
  1493. if (is_kmalloc_address(address))
  1494. return true;
  1495. }
  1496. ASSERT(size);
  1497. if (!size)
  1498. return false;
  1499. if (first_address.page_base() != last_address.page_base()) {
  1500. if (!MM.validate_user_read(*this, last_address))
  1501. return false;
  1502. }
  1503. return MM.validate_user_read(*this, first_address);
  1504. }
  1505. bool Process::validate_write(void* address, size_t size) const
  1506. {
  1507. LinearAddress first_address((dword)address);
  1508. LinearAddress last_address = first_address.offset(size - 1);
  1509. if (is_ring0()) {
  1510. if (is_kmalloc_address(address))
  1511. return true;
  1512. auto kmc_result = check_kernel_memory_access(first_address, true);
  1513. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1514. return true;
  1515. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1516. return false;
  1517. }
  1518. if (!size)
  1519. return false;
  1520. if (first_address.page_base() != last_address.page_base()) {
  1521. if (!MM.validate_user_write(*this, last_address))
  1522. return false;
  1523. }
  1524. return MM.validate_user_write(*this, last_address);
  1525. }
  1526. pid_t Process::sys$getsid(pid_t pid)
  1527. {
  1528. if (pid == 0)
  1529. return m_sid;
  1530. InterruptDisabler disabler;
  1531. auto* process = Process::from_pid(pid);
  1532. if (!process)
  1533. return -ESRCH;
  1534. if (m_sid != process->m_sid)
  1535. return -EPERM;
  1536. return process->m_sid;
  1537. }
  1538. pid_t Process::sys$setsid()
  1539. {
  1540. InterruptDisabler disabler;
  1541. bool found_process_with_same_pgid_as_my_pid = false;
  1542. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1543. found_process_with_same_pgid_as_my_pid = true;
  1544. return false;
  1545. });
  1546. if (found_process_with_same_pgid_as_my_pid)
  1547. return -EPERM;
  1548. m_sid = m_pid;
  1549. m_pgid = m_pid;
  1550. return m_sid;
  1551. }
  1552. pid_t Process::sys$getpgid(pid_t pid)
  1553. {
  1554. if (pid == 0)
  1555. return m_pgid;
  1556. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1557. auto* process = Process::from_pid(pid);
  1558. if (!process)
  1559. return -ESRCH;
  1560. return process->m_pgid;
  1561. }
  1562. pid_t Process::sys$getpgrp()
  1563. {
  1564. return m_pgid;
  1565. }
  1566. static pid_t get_sid_from_pgid(pid_t pgid)
  1567. {
  1568. InterruptDisabler disabler;
  1569. auto* group_leader = Process::from_pid(pgid);
  1570. if (!group_leader)
  1571. return -1;
  1572. return group_leader->sid();
  1573. }
  1574. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1575. {
  1576. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1577. pid_t pid = specified_pid ? specified_pid : m_pid;
  1578. if (specified_pgid < 0)
  1579. return -EINVAL;
  1580. auto* process = Process::from_pid(pid);
  1581. if (!process)
  1582. return -ESRCH;
  1583. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1584. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1585. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1586. if (current_sid != new_sid) {
  1587. // Can't move a process between sessions.
  1588. return -EPERM;
  1589. }
  1590. // FIXME: There are more EPERM conditions to check for here..
  1591. process->m_pgid = new_pgid;
  1592. return 0;
  1593. }
  1594. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1595. {
  1596. auto* descriptor = file_descriptor(fd);
  1597. if (!descriptor)
  1598. return -EBADF;
  1599. if (descriptor->is_socket() && request == 413) {
  1600. auto* pid = (pid_t*)arg;
  1601. if (!validate_write_typed(pid))
  1602. return -EFAULT;
  1603. *pid = descriptor->socket()->origin_pid();
  1604. return 0;
  1605. }
  1606. if (!descriptor->is_character_device())
  1607. return -ENOTTY;
  1608. return descriptor->character_device()->ioctl(*this, request, arg);
  1609. }
  1610. int Process::sys$getdtablesize()
  1611. {
  1612. return m_max_open_file_descriptors;
  1613. }
  1614. int Process::sys$dup(int old_fd)
  1615. {
  1616. auto* descriptor = file_descriptor(old_fd);
  1617. if (!descriptor)
  1618. return -EBADF;
  1619. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1620. return -EMFILE;
  1621. int new_fd = 0;
  1622. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1623. if (!m_fds[new_fd])
  1624. break;
  1625. }
  1626. m_fds[new_fd].set(descriptor);
  1627. return new_fd;
  1628. }
  1629. int Process::sys$dup2(int old_fd, int new_fd)
  1630. {
  1631. auto* descriptor = file_descriptor(old_fd);
  1632. if (!descriptor)
  1633. return -EBADF;
  1634. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1635. return -EMFILE;
  1636. m_fds[new_fd].set(descriptor);
  1637. return new_fd;
  1638. }
  1639. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1640. {
  1641. if (old_set) {
  1642. if (!validate_read_typed(old_set))
  1643. return -EFAULT;
  1644. *old_set = m_signal_mask;
  1645. }
  1646. if (set) {
  1647. if (!validate_read_typed(set))
  1648. return -EFAULT;
  1649. switch (how) {
  1650. case SIG_BLOCK:
  1651. m_signal_mask &= ~(*set);
  1652. break;
  1653. case SIG_UNBLOCK:
  1654. m_signal_mask |= *set;
  1655. break;
  1656. case SIG_SETMASK:
  1657. m_signal_mask = *set;
  1658. break;
  1659. default:
  1660. return -EINVAL;
  1661. }
  1662. }
  1663. return 0;
  1664. }
  1665. int Process::sys$sigpending(sigset_t* set)
  1666. {
  1667. if (!validate_read_typed(set))
  1668. return -EFAULT;
  1669. *set = m_pending_signals;
  1670. return 0;
  1671. }
  1672. void Process::set_default_signal_dispositions()
  1673. {
  1674. // FIXME: Set up all the right default actions. See signal(7).
  1675. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  1676. m_signal_action_data[SIGCHLD].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1677. }
  1678. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1679. {
  1680. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1681. return -EINVAL;
  1682. if (!validate_read_typed(act))
  1683. return -EFAULT;
  1684. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1685. auto& action = m_signal_action_data[signum];
  1686. if (old_act) {
  1687. if (!validate_write_typed(old_act))
  1688. return -EFAULT;
  1689. old_act->sa_flags = action.flags;
  1690. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1691. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1692. }
  1693. action.restorer = LinearAddress((dword)act->sa_restorer);
  1694. action.flags = act->sa_flags;
  1695. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1696. return 0;
  1697. }
  1698. int Process::sys$getgroups(int count, gid_t* gids)
  1699. {
  1700. if (count < 0)
  1701. return -EINVAL;
  1702. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1703. if (!count)
  1704. return m_gids.size();
  1705. if (count != (int)m_gids.size())
  1706. return -EINVAL;
  1707. if (!validate_write_typed(gids, m_gids.size()))
  1708. return -EFAULT;
  1709. size_t i = 0;
  1710. for (auto gid : m_gids)
  1711. gids[i++] = gid;
  1712. return 0;
  1713. }
  1714. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1715. {
  1716. if (!is_root())
  1717. return -EPERM;
  1718. if (count >= MAX_PROCESS_GIDS)
  1719. return -EINVAL;
  1720. if (!validate_read(gids, count))
  1721. return -EFAULT;
  1722. m_gids.clear();
  1723. m_gids.set(m_gid);
  1724. for (size_t i = 0; i < count; ++i)
  1725. m_gids.set(gids[i]);
  1726. return 0;
  1727. }
  1728. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1729. {
  1730. if (!validate_read_str(pathname))
  1731. return -EFAULT;
  1732. size_t pathname_length = strlen(pathname);
  1733. if (pathname_length == 0)
  1734. return -EINVAL;
  1735. if (pathname_length >= 255)
  1736. return -ENAMETOOLONG;
  1737. int error;
  1738. if (!VFS::the().mkdir(String(pathname, pathname_length), mode, *cwd_inode(), error))
  1739. return error;
  1740. return 0;
  1741. }
  1742. clock_t Process::sys$times(tms* times)
  1743. {
  1744. if (!validate_write_typed(times))
  1745. return -EFAULT;
  1746. times->tms_utime = m_ticks_in_user;
  1747. times->tms_stime = m_ticks_in_kernel;
  1748. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1749. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1750. return 0;
  1751. }
  1752. int Process::sys$select(const Syscall::SC_select_params* params)
  1753. {
  1754. if (!validate_read_typed(params))
  1755. return -EFAULT;
  1756. if (params->writefds && !validate_read_typed(params->writefds))
  1757. return -EFAULT;
  1758. if (params->readfds && !validate_read_typed(params->readfds))
  1759. return -EFAULT;
  1760. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1761. return -EFAULT;
  1762. if (params->timeout && !validate_read_typed(params->timeout))
  1763. return -EFAULT;
  1764. int nfds = params->nfds;
  1765. fd_set* writefds = params->writefds;
  1766. fd_set* readfds = params->readfds;
  1767. fd_set* exceptfds = params->exceptfds;
  1768. auto* timeout = params->timeout;
  1769. // FIXME: Implement exceptfds support.
  1770. ASSERT(!exceptfds);
  1771. if (timeout) {
  1772. m_select_timeout = *timeout;
  1773. m_select_has_timeout = true;
  1774. } else {
  1775. m_select_has_timeout = false;
  1776. }
  1777. if (nfds < 0)
  1778. return -EINVAL;
  1779. // FIXME: Return -EINTR if a signal is caught.
  1780. // FIXME: Return -EINVAL if timeout is invalid.
  1781. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1782. if (!set)
  1783. return 0;
  1784. vector.clear_with_capacity();
  1785. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1786. for (int i = 0; i < nfds; ++i) {
  1787. if (bitmap.get(i)) {
  1788. if (!file_descriptor(i))
  1789. return -EBADF;
  1790. vector.append(i);
  1791. }
  1792. }
  1793. return 0;
  1794. };
  1795. int error = 0;
  1796. error = transfer_fds(writefds, m_select_write_fds);
  1797. if (error)
  1798. return error;
  1799. error = transfer_fds(readfds, m_select_read_fds);
  1800. if (error)
  1801. return error;
  1802. #ifdef DEBUG_IO
  1803. dbgprintf("%s<%u> selecting on (read:%u, write:%u), wakeup_req:%u, timeout=%p\n", name().characters(), pid(), m_select_read_fds.size(), m_select_write_fds.size(), m_wakeup_requested, timeout);
  1804. #endif
  1805. if (!m_wakeup_requested && (!timeout || (timeout->tv_sec || timeout->tv_usec))) {
  1806. block(BlockedSelect);
  1807. Scheduler::yield();
  1808. }
  1809. m_wakeup_requested = false;
  1810. int markedfds = 0;
  1811. if (readfds) {
  1812. memset(readfds, 0, sizeof(fd_set));
  1813. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1814. for (int fd : m_select_read_fds) {
  1815. auto* descriptor = file_descriptor(fd);
  1816. if (!descriptor)
  1817. continue;
  1818. if (descriptor->can_read(*this)) {
  1819. bitmap.set(fd, true);
  1820. ++markedfds;
  1821. }
  1822. }
  1823. }
  1824. if (writefds) {
  1825. memset(writefds, 0, sizeof(fd_set));
  1826. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1827. for (int fd : m_select_write_fds) {
  1828. auto* descriptor = file_descriptor(fd);
  1829. if (!descriptor)
  1830. continue;
  1831. if (descriptor->can_write(*this)) {
  1832. bitmap.set(fd, true);
  1833. ++markedfds;
  1834. }
  1835. }
  1836. }
  1837. return markedfds;
  1838. }
  1839. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1840. {
  1841. if (!validate_read_typed(fds))
  1842. return -EFAULT;
  1843. m_select_write_fds.clear_with_capacity();
  1844. m_select_read_fds.clear_with_capacity();
  1845. for (int i = 0; i < nfds; ++i) {
  1846. if (fds[i].events & POLLIN)
  1847. m_select_read_fds.append(fds[i].fd);
  1848. if (fds[i].events & POLLOUT)
  1849. m_select_write_fds.append(fds[i].fd);
  1850. }
  1851. if (!m_wakeup_requested && timeout < 0) {
  1852. block(BlockedSelect);
  1853. Scheduler::yield();
  1854. }
  1855. m_wakeup_requested = false;
  1856. int fds_with_revents = 0;
  1857. for (int i = 0; i < nfds; ++i) {
  1858. auto* descriptor = file_descriptor(fds[i].fd);
  1859. if (!descriptor) {
  1860. fds[i].revents = POLLNVAL;
  1861. continue;
  1862. }
  1863. fds[i].revents = 0;
  1864. if (fds[i].events & POLLIN && descriptor->can_read(*this))
  1865. fds[i].revents |= POLLIN;
  1866. if (fds[i].events & POLLOUT && descriptor->can_write(*this))
  1867. fds[i].revents |= POLLOUT;
  1868. if (fds[i].revents)
  1869. ++fds_with_revents;
  1870. }
  1871. return fds_with_revents;
  1872. }
  1873. Inode* Process::cwd_inode()
  1874. {
  1875. // FIXME: This is retarded factoring.
  1876. if (!m_cwd)
  1877. m_cwd = VFS::the().root_inode();
  1878. return m_cwd.ptr();
  1879. }
  1880. int Process::sys$unlink(const char* pathname)
  1881. {
  1882. if (!validate_read_str(pathname))
  1883. return -EFAULT;
  1884. int error;
  1885. if (!VFS::the().unlink(String(pathname), *cwd_inode(), error))
  1886. return error;
  1887. return 0;
  1888. }
  1889. int Process::sys$rmdir(const char* pathname)
  1890. {
  1891. if (!validate_read_str(pathname))
  1892. return -EFAULT;
  1893. int error;
  1894. if (!VFS::the().rmdir(String(pathname), *cwd_inode(), error))
  1895. return error;
  1896. return 0;
  1897. }
  1898. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1899. {
  1900. if (!validate_write_typed(lsw))
  1901. return -EFAULT;
  1902. if (!validate_write_typed(msw))
  1903. return -EFAULT;
  1904. read_tsc(*lsw, *msw);
  1905. return 0;
  1906. }
  1907. int Process::sys$chmod(const char* pathname, mode_t mode)
  1908. {
  1909. if (!validate_read_str(pathname))
  1910. return -EFAULT;
  1911. int error;
  1912. if (!VFS::the().chmod(String(pathname), mode, *cwd_inode(), error))
  1913. return error;
  1914. return 0;
  1915. }
  1916. void Process::finalize()
  1917. {
  1918. ASSERT(current == g_finalizer);
  1919. if (WSMessageLoop::the().running())
  1920. WSMessageLoop::the().notify_client_died(gui_client_id());
  1921. m_fds.clear();
  1922. m_tty = nullptr;
  1923. {
  1924. InterruptDisabler disabler;
  1925. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1926. parent_process->send_signal(SIGCHLD, this);
  1927. }
  1928. }
  1929. set_state(Dead);
  1930. }
  1931. void Process::die()
  1932. {
  1933. set_state(Dying);
  1934. if (!Scheduler::is_active())
  1935. Scheduler::pick_next_and_switch_now();
  1936. }
  1937. size_t Process::amount_virtual() const
  1938. {
  1939. size_t amount = 0;
  1940. for (auto& region : m_regions) {
  1941. amount += region->size();
  1942. }
  1943. return amount;
  1944. }
  1945. size_t Process::amount_in_bitmaps() const
  1946. {
  1947. size_t amount = 0;
  1948. for (auto& region : m_regions) {
  1949. if (region->is_bitmap())
  1950. amount += region->size();
  1951. }
  1952. return amount;
  1953. }
  1954. size_t Process::amount_resident() const
  1955. {
  1956. // FIXME: This will double count if multiple regions use the same physical page.
  1957. size_t amount = 0;
  1958. for (auto& region : m_regions) {
  1959. amount += region->amount_resident();
  1960. }
  1961. return amount;
  1962. }
  1963. size_t Process::amount_shared() const
  1964. {
  1965. // FIXME: This will double count if multiple regions use the same physical page.
  1966. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1967. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1968. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1969. size_t amount = 0;
  1970. for (auto& region : m_regions) {
  1971. amount += region->amount_shared();
  1972. }
  1973. return amount;
  1974. }
  1975. void Process::finalize_dying_processes()
  1976. {
  1977. Vector<Process*> dying_processes;
  1978. {
  1979. InterruptDisabler disabler;
  1980. dying_processes.ensure_capacity(system.nprocess);
  1981. for (auto* process = g_processes->head(); process; process = process->next()) {
  1982. if (process->state() == Process::Dying)
  1983. dying_processes.append(process);
  1984. }
  1985. }
  1986. for (auto* process : dying_processes)
  1987. process->finalize();
  1988. }
  1989. bool Process::tick()
  1990. {
  1991. ++m_ticks;
  1992. if (tss().cs & 3)
  1993. ++m_ticks_in_user;
  1994. else
  1995. ++m_ticks_in_kernel;
  1996. return --m_ticks_left;
  1997. }
  1998. DisplayInfo Process::set_video_resolution(int width, int height)
  1999. {
  2000. DisplayInfo info;
  2001. info.width = width;
  2002. info.height = height;
  2003. info.bpp = 32;
  2004. info.pitch = width * 4;
  2005. size_t framebuffer_size = width * height * 4 * 2;
  2006. if (!m_display_framebuffer_region) {
  2007. auto framebuffer_vmo = VMObject::create_framebuffer_wrapper(BochsVGADevice::the().framebuffer_address(), framebuffer_size);
  2008. m_display_framebuffer_region = allocate_region_with_vmo(LinearAddress(0xe0000000), framebuffer_size, move(framebuffer_vmo), 0, "framebuffer", true, true);
  2009. }
  2010. info.framebuffer = m_display_framebuffer_region->laddr().as_ptr();
  2011. BochsVGADevice::the().set_resolution(width, height);
  2012. return info;
  2013. }
  2014. int Process::sys$socket(int domain, int type, int protocol)
  2015. {
  2016. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2017. return -EMFILE;
  2018. int fd = 0;
  2019. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2020. if (!m_fds[fd])
  2021. break;
  2022. }
  2023. int error;
  2024. auto socket = Socket::create(domain, type, protocol, error);
  2025. if (!socket)
  2026. return error;
  2027. auto descriptor = FileDescriptor::create(move(socket));
  2028. unsigned flags = 0;
  2029. if (type & SOCK_CLOEXEC)
  2030. flags |= O_CLOEXEC;
  2031. if (type & SOCK_NONBLOCK)
  2032. descriptor->set_blocking(false);
  2033. m_fds[fd].set(move(descriptor), flags);
  2034. return fd;
  2035. }
  2036. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2037. {
  2038. if (!validate_read(address, address_length))
  2039. return -EFAULT;
  2040. auto* descriptor = file_descriptor(sockfd);
  2041. if (!descriptor)
  2042. return -EBADF;
  2043. if (!descriptor->is_socket())
  2044. return -ENOTSOCK;
  2045. auto& socket = *descriptor->socket();
  2046. int error;
  2047. if (!socket.bind(address, address_length, error))
  2048. return error;
  2049. return 0;
  2050. }
  2051. int Process::sys$listen(int sockfd, int backlog)
  2052. {
  2053. auto* descriptor = file_descriptor(sockfd);
  2054. if (!descriptor)
  2055. return -EBADF;
  2056. if (!descriptor->is_socket())
  2057. return -ENOTSOCK;
  2058. auto& socket = *descriptor->socket();
  2059. int error;
  2060. if (!socket.listen(backlog, error))
  2061. return error;
  2062. return 0;
  2063. }
  2064. int Process::sys$accept(int sockfd, sockaddr* address, socklen_t* address_size)
  2065. {
  2066. if (!validate_write_typed(address_size))
  2067. return -EFAULT;
  2068. if (!validate_write(address, *address_size))
  2069. return -EFAULT;
  2070. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2071. return -EMFILE;
  2072. int fd = 0;
  2073. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2074. if (!m_fds[fd])
  2075. break;
  2076. }
  2077. auto* descriptor = file_descriptor(sockfd);
  2078. if (!descriptor)
  2079. return -EBADF;
  2080. if (!descriptor->is_socket())
  2081. return -ENOTSOCK;
  2082. auto& socket = *descriptor->socket();
  2083. if (!socket.can_accept()) {
  2084. ASSERT(!descriptor->is_blocking());
  2085. return -EAGAIN;
  2086. }
  2087. auto client = socket.accept();
  2088. ASSERT(client);
  2089. bool success = client->get_address(address, address_size);
  2090. ASSERT(success);
  2091. auto client_descriptor = FileDescriptor::create(move(client), SocketRole::Accepted);
  2092. m_fds[fd].set(move(client_descriptor));
  2093. return fd;
  2094. }
  2095. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2096. {
  2097. if (!validate_read(address, address_size))
  2098. return -EFAULT;
  2099. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2100. return -EMFILE;
  2101. int fd = 0;
  2102. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2103. if (!m_fds[fd])
  2104. break;
  2105. }
  2106. auto* descriptor = file_descriptor(sockfd);
  2107. if (!descriptor)
  2108. return -EBADF;
  2109. if (!descriptor->is_socket())
  2110. return -ENOTSOCK;
  2111. auto& socket = *descriptor->socket();
  2112. int error;
  2113. if (!socket.connect(address, address_size, error))
  2114. return error;
  2115. descriptor->set_socket_role(SocketRole::Connected);
  2116. return 0;
  2117. }
  2118. bool Process::wait_for_connect(Socket& socket, int& error)
  2119. {
  2120. if (socket.is_connected())
  2121. return true;
  2122. m_blocked_connecting_socket = socket;
  2123. block(BlockedConnect);
  2124. Scheduler::yield();
  2125. m_blocked_connecting_socket = nullptr;
  2126. if (!socket.is_connected()) {
  2127. error = -ECONNREFUSED;
  2128. return false;
  2129. }
  2130. return true;
  2131. }