Process.cpp 65 KB

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