Process.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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 <VirtualFileSystem/FileDescriptor.h>
  8. #include <VirtualFileSystem/VirtualFileSystem.h>
  9. #include "ELFLoader.h"
  10. #include "MemoryManager.h"
  11. #include "errno.h"
  12. #include "i8253.h"
  13. #include "RTC.h"
  14. #include "ProcFileSystem.h"
  15. #include <AK/StdLibExtras.h>
  16. #include <LibC/signal_numbers.h>
  17. #include "Syscall.h"
  18. #include "Scheduler.h"
  19. #include "FIFO.h"
  20. //#define DEBUG_IO
  21. //#define TASK_DEBUG
  22. //#define FORK_DEBUG
  23. #define SIGNAL_DEBUG
  24. #define MAX_PROCESS_GIDS 32
  25. static const dword defaultStackSize = 16384;
  26. static pid_t next_pid;
  27. InlineLinkedList<Process>* g_processes;
  28. static String* s_hostname;
  29. static String& hostnameStorage(InterruptDisabler&)
  30. {
  31. ASSERT(s_hostname);
  32. return *s_hostname;
  33. }
  34. static String getHostname()
  35. {
  36. InterruptDisabler disabler;
  37. return hostnameStorage(disabler).isolated_copy();
  38. }
  39. CoolGlobals* g_cool_globals;
  40. void Process::initialize()
  41. {
  42. #ifdef COOL_GLOBALS
  43. g_cool_globals = reinterpret_cast<CoolGlobals*>(0x1000);
  44. #endif
  45. next_pid = 0;
  46. g_processes = new InlineLinkedList<Process>;
  47. s_hostname = new String("courage");
  48. Scheduler::initialize();
  49. }
  50. Vector<Process*> Process::allProcesses()
  51. {
  52. InterruptDisabler disabler;
  53. Vector<Process*> processes;
  54. processes.ensureCapacity(g_processes->size_slow());
  55. for (auto* process = g_processes->head(); process; process = process->next())
  56. processes.append(process);
  57. return processes;
  58. }
  59. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  60. {
  61. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  62. if (laddr.is_null()) {
  63. laddr = m_nextRegion;
  64. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  65. }
  66. laddr.mask(0xfffff000);
  67. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  68. if (commit)
  69. m_regions.last()->commit(*this);
  70. MM.map_region(*this, *m_regions.last());
  71. return m_regions.last().ptr();
  72. }
  73. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Vnode>&& vnode, String&& name, bool is_readable, bool is_writable)
  74. {
  75. ASSERT(!vnode->isCharacterDevice());
  76. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  77. if (laddr.is_null()) {
  78. laddr = m_nextRegion;
  79. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  80. }
  81. laddr.mask(0xfffff000);
  82. m_regions.append(adopt(*new Region(laddr, size, move(vnode), move(name), is_readable, is_writable)));
  83. MM.map_region(*this, *m_regions.last());
  84. return m_regions.last().ptr();
  85. }
  86. 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)
  87. {
  88. ASSERT(vmo);
  89. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  90. if (laddr.is_null()) {
  91. laddr = m_nextRegion;
  92. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  93. }
  94. laddr.mask(0xfffff000);
  95. offset_in_vmo &= PAGE_MASK;
  96. size = ceilDiv(size, PAGE_SIZE) * PAGE_SIZE;
  97. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  98. MM.map_region(*this, *m_regions.last());
  99. return m_regions.last().ptr();
  100. }
  101. bool Process::deallocate_region(Region& region)
  102. {
  103. InterruptDisabler disabler;
  104. for (size_t i = 0; i < m_regions.size(); ++i) {
  105. if (m_regions[i].ptr() == &region) {
  106. MM.unmap_region(*this, region);
  107. m_regions.remove(i);
  108. return true;
  109. }
  110. }
  111. return false;
  112. }
  113. Region* Process::regionFromRange(LinearAddress laddr, size_t size)
  114. {
  115. for (auto& region : m_regions) {
  116. if (region->linearAddress == laddr && region->size == size)
  117. return region.ptr();
  118. }
  119. return nullptr;
  120. }
  121. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  122. {
  123. if (!validate_read_str(name))
  124. return -EFAULT;
  125. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  126. if (!region)
  127. return -EINVAL;
  128. region->name = name;
  129. return 0;
  130. }
  131. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  132. {
  133. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  134. return (void*)-EFAULT;
  135. void* addr = (void*)params->addr;
  136. size_t size = params->size;
  137. int prot = params->prot;
  138. int flags = params->flags;
  139. int fd = params->fd;
  140. Unix::off_t offset = params->offset;
  141. if (size == 0)
  142. return (void*)-EINVAL;
  143. if ((dword)addr & ~PAGE_MASK || size & ~PAGE_MASK)
  144. return (void*)-EINVAL;
  145. if (flags & MAP_ANONYMOUS) {
  146. InterruptDisabler disabler;
  147. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  148. ASSERT(addr == nullptr);
  149. auto* region = allocate_region(LinearAddress(), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  150. if (!region)
  151. return (void*)-ENOMEM;
  152. return region->linearAddress.asPtr();
  153. }
  154. if (offset & ~PAGE_MASK)
  155. return (void*)-EINVAL;
  156. auto* descriptor = file_descriptor(fd);
  157. if (!descriptor)
  158. return (void*)-EBADF;
  159. if (descriptor->vnode()->isCharacterDevice())
  160. return (void*)-ENODEV;
  161. // FIXME: If PROT_EXEC, check that the underlying file system isn't mounted noexec.
  162. auto region_name = descriptor->absolute_path();
  163. InterruptDisabler disabler;
  164. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  165. ASSERT(addr == nullptr);
  166. auto* region = allocate_file_backed_region(LinearAddress(), size, descriptor->vnode(), move(region_name), prot & PROT_READ, prot & PROT_WRITE);
  167. if (!region)
  168. return (void*)-ENOMEM;
  169. return region->linearAddress.asPtr();
  170. }
  171. int Process::sys$munmap(void* addr, size_t size)
  172. {
  173. InterruptDisabler disabler;
  174. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  175. if (!region)
  176. return -1;
  177. if (!deallocate_region(*region))
  178. return -1;
  179. return 0;
  180. }
  181. int Process::sys$gethostname(char* buffer, size_t size)
  182. {
  183. if (!validate_write(buffer, size))
  184. return -EFAULT;
  185. auto hostname = getHostname();
  186. if (size < (hostname.length() + 1))
  187. return -ENAMETOOLONG;
  188. memcpy(buffer, hostname.characters(), size);
  189. return 0;
  190. }
  191. Process* Process::fork(RegisterDump& regs)
  192. {
  193. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copyRef(), m_executable.copyRef(), m_tty, this);
  194. if (!child)
  195. return nullptr;
  196. memcpy(child->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  197. child->m_signal_mask = m_signal_mask;
  198. #ifdef FORK_DEBUG
  199. dbgprintf("fork: child=%p\n", child);
  200. #endif
  201. #if 0
  202. // FIXME: An honest fork() would copy these. Needs a Vector copy ctor.
  203. child->m_arguments = m_arguments;
  204. child->m_initialEnvironment = m_initialEnvironment;
  205. #endif
  206. for (auto& region : m_regions) {
  207. #ifdef FORK_DEBUG
  208. dbgprintf("fork: cloning Region{%p}\n", region.ptr());
  209. #endif
  210. auto cloned_region = region->clone();
  211. child->m_regions.append(move(cloned_region));
  212. MM.map_region(*child, *child->m_regions.last());
  213. }
  214. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  215. child->m_tss.ebx = regs.ebx;
  216. child->m_tss.ecx = regs.ecx;
  217. child->m_tss.edx = regs.edx;
  218. child->m_tss.ebp = regs.ebp;
  219. child->m_tss.esp = regs.esp_if_crossRing;
  220. child->m_tss.esi = regs.esi;
  221. child->m_tss.edi = regs.edi;
  222. child->m_tss.eflags = regs.eflags;
  223. child->m_tss.eip = regs.eip;
  224. child->m_tss.cs = regs.cs;
  225. child->m_tss.ds = regs.ds;
  226. child->m_tss.es = regs.es;
  227. child->m_tss.fs = regs.fs;
  228. child->m_tss.gs = regs.gs;
  229. child->m_tss.ss = regs.ss_if_crossRing;
  230. #ifdef FORK_DEBUG
  231. 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);
  232. #endif
  233. ProcFS::the().add_process(*child);
  234. {
  235. InterruptDisabler disabler;
  236. g_processes->prepend(child);
  237. system.nprocess++;
  238. }
  239. #ifdef TASK_DEBUG
  240. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  241. #endif
  242. return child;
  243. }
  244. pid_t Process::sys$fork(RegisterDump& regs)
  245. {
  246. auto* child = fork(regs);
  247. ASSERT(child);
  248. return child->pid();
  249. }
  250. int Process::do_exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  251. {
  252. auto parts = path.split('/');
  253. if (parts.is_empty())
  254. return -ENOENT;
  255. int error;
  256. auto descriptor = VFS::the().open(path, error, 0, m_cwd ? m_cwd->inode : InodeIdentifier());
  257. if (!descriptor) {
  258. ASSERT(error != 0);
  259. return error;
  260. }
  261. if (!descriptor->metadata().mayExecute(m_euid, m_gids))
  262. return -EACCES;
  263. if (!descriptor->metadata().size) {
  264. kprintf("exec() of 0-length binaries not supported\n");
  265. return -ENOTIMPL;
  266. }
  267. auto vmo = VMObject::create_file_backed(descriptor->vnode(), descriptor->metadata().size);
  268. vmo->set_name(descriptor->absolute_path());
  269. auto* region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copyRef(), 0, "helper", true, false);
  270. dword entry_eip = 0;
  271. PageDirectory* old_page_directory = m_page_directory;
  272. PageDirectory* new_page_directory = reinterpret_cast<PageDirectory*>(kmalloc_page_aligned(sizeof(PageDirectory)));
  273. #ifdef MM_DEBUG
  274. dbgprintf("Process %u exec: PD=%x created\n", pid(), new_page_directory);
  275. #endif
  276. MM.populate_page_directory(*new_page_directory);
  277. m_page_directory = new_page_directory;
  278. ProcessPagingScope paging_scope(*this);
  279. // FIXME: Should we consider doing on-demand paging here? Is it actually useful?
  280. bool success = region->page_in(*new_page_directory);
  281. ASSERT(success);
  282. {
  283. InterruptDisabler disabler;
  284. // Okay, here comes the sleight of hand, pay close attention..
  285. auto old_regions = move(m_regions);
  286. ELFLoader loader(region->linearAddress.asPtr());
  287. 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) {
  288. ASSERT(size);
  289. ASSERT(alignment == PAGE_SIZE);
  290. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  291. (void) allocate_region_with_vmo(laddr, size, vmo.copyRef(), offset_in_image, String(name), is_readable, is_writable);
  292. return laddr.asPtr();
  293. };
  294. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  295. ASSERT(size);
  296. ASSERT(alignment == PAGE_SIZE);
  297. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  298. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  299. return laddr.asPtr();
  300. };
  301. bool success = loader.load();
  302. if (!success) {
  303. m_page_directory = old_page_directory;
  304. MM.enter_process_paging_scope(*this);
  305. MM.release_page_directory(*new_page_directory);
  306. m_regions = move(old_regions);
  307. kprintf("sys$execve: Failure loading %s\n", path.characters());
  308. return -ENOEXEC;
  309. }
  310. entry_eip = (dword)loader.symbol_ptr("_start");
  311. if (!entry_eip) {
  312. m_page_directory = old_page_directory;
  313. MM.enter_process_paging_scope(*this);
  314. MM.release_page_directory(*new_page_directory);
  315. m_regions = move(old_regions);
  316. return -ENOEXEC;
  317. }
  318. }
  319. m_signal_stack_kernel_region = nullptr;
  320. m_signal_stack_user_region = nullptr;
  321. memset(m_signal_action_data, 0, sizeof(m_signal_action_data));
  322. m_signal_mask = 0xffffffff;
  323. m_pending_signals = 0;
  324. for (size_t i = 0; i < m_fds.size(); ++i) {
  325. auto& daf = m_fds[i];
  326. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  327. daf.descriptor->close();
  328. daf = { };
  329. }
  330. }
  331. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  332. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  333. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  334. cli();
  335. Scheduler::prepare_to_modify_tss(*this);
  336. m_name = parts.takeLast();
  337. dword old_esp0 = m_tss.esp0;
  338. memset(&m_tss, 0, sizeof(m_tss));
  339. m_tss.eflags = 0x0202;
  340. m_tss.eip = entry_eip;
  341. m_tss.cs = 0x1b;
  342. m_tss.ds = 0x23;
  343. m_tss.es = 0x23;
  344. m_tss.fs = 0x23;
  345. m_tss.gs = 0x23;
  346. m_tss.ss = 0x23;
  347. m_tss.cr3 = (dword)m_page_directory;
  348. m_stack_region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  349. ASSERT(m_stack_region);
  350. m_stackTop3 = m_stack_region->linearAddress.offset(defaultStackSize).get();
  351. m_tss.esp = m_stackTop3;
  352. m_tss.ss0 = 0x10;
  353. m_tss.esp0 = old_esp0;
  354. m_tss.ss2 = m_pid;
  355. MM.release_page_directory(*old_page_directory);
  356. m_executable = descriptor->vnode();
  357. m_arguments = move(arguments);
  358. m_initialEnvironment = move(environment);
  359. #ifdef TASK_DEBUG
  360. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), m_tss.eip);
  361. #endif
  362. set_state(Skip1SchedulerPass);
  363. return 0;
  364. }
  365. int Process::exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  366. {
  367. // The bulk of exec() is done by do_exec(), which ensures that all locals
  368. // are cleaned up by the time we yield-teleport below.
  369. int rc = do_exec(path, move(arguments), move(environment));
  370. if (rc < 0)
  371. return rc;
  372. if (current == this) {
  373. Scheduler::yield();
  374. ASSERT_NOT_REACHED();
  375. }
  376. return 0;
  377. }
  378. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  379. {
  380. if (!validate_read_str(filename))
  381. return -EFAULT;
  382. if (argv) {
  383. if (!validate_read_typed(argv))
  384. return -EFAULT;
  385. for (size_t i = 0; argv[i]; ++i) {
  386. if (!validate_read_str(argv[i]))
  387. return -EFAULT;
  388. }
  389. }
  390. if (envp) {
  391. if (!validate_read_typed(envp))
  392. return -EFAULT;
  393. for (size_t i = 0; envp[i]; ++i) {
  394. if (!validate_read_str(envp[i]))
  395. return -EFAULT;
  396. }
  397. }
  398. String path(filename);
  399. auto parts = path.split('/');
  400. Vector<String> arguments;
  401. if (argv) {
  402. for (size_t i = 0; argv[i]; ++i) {
  403. arguments.append(argv[i]);
  404. }
  405. } else {
  406. arguments.append(parts.last());
  407. }
  408. Vector<String> environment;
  409. if (envp) {
  410. for (size_t i = 0; envp[i]; ++i)
  411. environment.append(envp[i]);
  412. }
  413. int rc = exec(path, move(arguments), move(environment));
  414. ASSERT(rc < 0); // We should never continue after a successful exec!
  415. return rc;
  416. }
  417. 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)
  418. {
  419. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  420. auto parts = path.split('/');
  421. if (arguments.is_empty()) {
  422. arguments.append(parts.last());
  423. }
  424. RetainPtr<Vnode> cwd;
  425. {
  426. InterruptDisabler disabler;
  427. if (auto* parent = Process::from_pid(parent_pid))
  428. cwd = parent->m_cwd.copyRef();
  429. }
  430. if (!cwd)
  431. cwd = VFS::the().root();
  432. auto* process = new Process(parts.takeLast(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  433. error = process->exec(path, move(arguments), move(environment));
  434. if (error != 0)
  435. return nullptr;
  436. ProcFS::the().add_process(*process);
  437. {
  438. InterruptDisabler disabler;
  439. g_processes->prepend(process);
  440. system.nprocess++;
  441. }
  442. #ifdef TASK_DEBUG
  443. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  444. #endif
  445. error = 0;
  446. return process;
  447. }
  448. int Process::sys$get_environment(char*** environ)
  449. {
  450. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
  451. if (!region)
  452. return -ENOMEM;
  453. MM.map_region(*this, *region);
  454. char* envpage = (char*)region->linearAddress.get();
  455. *environ = (char**)envpage;
  456. char* bufptr = envpage + (sizeof(char*) * (m_initialEnvironment.size() + 1));
  457. for (size_t i = 0; i < m_initialEnvironment.size(); ++i) {
  458. (*environ)[i] = bufptr;
  459. memcpy(bufptr, m_initialEnvironment[i].characters(), m_initialEnvironment[i].length());
  460. bufptr += m_initialEnvironment[i].length();
  461. *(bufptr++) = '\0';
  462. }
  463. (*environ)[m_initialEnvironment.size()] = nullptr;
  464. return 0;
  465. }
  466. int Process::sys$get_arguments(int* argc, char*** argv)
  467. {
  468. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
  469. if (!region)
  470. return -ENOMEM;
  471. MM.map_region(*this, *region);
  472. char* argpage = (char*)region->linearAddress.get();
  473. *argc = m_arguments.size();
  474. *argv = (char**)argpage;
  475. char* bufptr = argpage + (sizeof(char*) * m_arguments.size());
  476. for (size_t i = 0; i < m_arguments.size(); ++i) {
  477. (*argv)[i] = bufptr;
  478. memcpy(bufptr, m_arguments[i].characters(), m_arguments[i].length());
  479. bufptr += m_arguments[i].length();
  480. *(bufptr++) = '\0';
  481. }
  482. return 0;
  483. }
  484. Process* Process::create_kernel_process(void (*e)(), String&& name)
  485. {
  486. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  487. process->m_tss.eip = (dword)e;
  488. if (process->pid() != 0) {
  489. {
  490. InterruptDisabler disabler;
  491. g_processes->prepend(process);
  492. system.nprocess++;
  493. }
  494. ProcFS::the().add_process(*process);
  495. #ifdef TASK_DEBUG
  496. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  497. #endif
  498. }
  499. return process;
  500. }
  501. Process::Process(String&& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RetainPtr<Vnode>&& cwd, RetainPtr<Vnode>&& executable, TTY* tty, Process* fork_parent)
  502. : m_name(move(name))
  503. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  504. , m_uid(uid)
  505. , m_gid(gid)
  506. , m_euid(uid)
  507. , m_egid(gid)
  508. , m_state(Runnable)
  509. , m_ring(ring)
  510. , m_cwd(move(cwd))
  511. , m_executable(move(executable))
  512. , m_tty(tty)
  513. , m_ppid(ppid)
  514. {
  515. m_gids.set(m_gid);
  516. if (fork_parent) {
  517. m_sid = fork_parent->m_sid;
  518. m_pgid = fork_parent->m_pgid;
  519. } else {
  520. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  521. InterruptDisabler disabler;
  522. if (auto* parent = Process::from_pid(m_ppid)) {
  523. m_sid = parent->m_sid;
  524. m_pgid = parent->m_pgid;
  525. }
  526. }
  527. m_page_directory = (PageDirectory*)kmalloc_page_aligned(sizeof(PageDirectory));
  528. #ifdef MM_DEBUG
  529. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory);
  530. #endif
  531. MM.populate_page_directory(*m_page_directory);
  532. if (fork_parent) {
  533. m_fds.resize(fork_parent->m_fds.size());
  534. for (size_t i = 0; i < fork_parent->m_fds.size(); ++i) {
  535. if (!fork_parent->m_fds[i].descriptor)
  536. continue;
  537. #ifdef FORK_DEBUG
  538. dbgprintf("fork: cloning fd %u... (%p) istty? %u\n", i, fork_parent->m_fds[i].ptr(), fork_parent->m_fds[i]->isTTY());
  539. #endif
  540. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  541. m_fds[i].flags = fork_parent->m_fds[i].flags;
  542. }
  543. } else {
  544. m_fds.resize(m_max_open_file_descriptors);
  545. if (tty) {
  546. m_fds[0].set(tty->open(O_RDONLY));
  547. m_fds[1].set(tty->open(O_WRONLY));
  548. m_fds[2].set(tty->open(O_WRONLY));
  549. }
  550. }
  551. if (fork_parent)
  552. m_nextRegion = fork_parent->m_nextRegion;
  553. else
  554. m_nextRegion = LinearAddress(0x10000000);
  555. if (fork_parent) {
  556. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  557. } else {
  558. memset(&m_tss, 0, sizeof(m_tss));
  559. // Only IF is set when a process boots.
  560. m_tss.eflags = 0x0202;
  561. word cs, ds, ss;
  562. if (isRing0()) {
  563. cs = 0x08;
  564. ds = 0x10;
  565. ss = 0x10;
  566. } else {
  567. cs = 0x1b;
  568. ds = 0x23;
  569. ss = 0x23;
  570. }
  571. m_tss.ds = ds;
  572. m_tss.es = ds;
  573. m_tss.fs = ds;
  574. m_tss.gs = ds;
  575. m_tss.ss = ss;
  576. m_tss.cs = cs;
  577. }
  578. m_tss.cr3 = (dword)m_page_directory;
  579. if (isRing0()) {
  580. // FIXME: This memory is leaked.
  581. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  582. dword stackBottom = (dword)kmalloc_eternal(defaultStackSize);
  583. m_stackTop0 = (stackBottom + defaultStackSize) & 0xffffff8;
  584. m_tss.esp = m_stackTop0;
  585. } else {
  586. if (fork_parent) {
  587. m_stackTop3 = fork_parent->m_stackTop3;
  588. } else {
  589. auto* region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  590. ASSERT(region);
  591. m_stackTop3 = region->linearAddress.offset(defaultStackSize).get();
  592. m_tss.esp = m_stackTop3;
  593. }
  594. }
  595. if (isRing3()) {
  596. // Ring3 processes need a separate stack for Ring0.
  597. m_kernelStack = kmalloc(defaultStackSize);
  598. m_stackTop0 = ((dword)m_kernelStack + defaultStackSize) & 0xffffff8;
  599. m_tss.ss0 = 0x10;
  600. m_tss.esp0 = m_stackTop0;
  601. }
  602. // HACK: Ring2 SS in the TSS is the current PID.
  603. m_tss.ss2 = m_pid;
  604. m_farPtr.offset = 0x98765432;
  605. }
  606. Process::~Process()
  607. {
  608. InterruptDisabler disabler;
  609. ProcFS::the().remove_process(*this);
  610. system.nprocess--;
  611. gdt_free_entry(selector());
  612. if (m_kernelStack) {
  613. kfree(m_kernelStack);
  614. m_kernelStack = nullptr;
  615. }
  616. MM.release_page_directory(*m_page_directory);
  617. }
  618. void Process::dumpRegions()
  619. {
  620. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  621. kprintf("BEGIN END SIZE NAME\n");
  622. for (auto& region : m_regions) {
  623. kprintf("%x -- %x %x %s\n",
  624. region->linearAddress.get(),
  625. region->linearAddress.offset(region->size - 1).get(),
  626. region->size,
  627. region->name.characters());
  628. }
  629. }
  630. void Process::sys$exit(int status)
  631. {
  632. cli();
  633. #ifdef TASK_DEBUG
  634. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  635. #endif
  636. set_state(Dead);
  637. m_termination_status = status;
  638. m_termination_signal = 0;
  639. Scheduler::pick_next_and_switch_now();
  640. ASSERT_NOT_REACHED();
  641. }
  642. void Process::terminate_due_to_signal(byte signal)
  643. {
  644. ASSERT_INTERRUPTS_DISABLED();
  645. ASSERT(signal < 32);
  646. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  647. m_termination_status = 0;
  648. m_termination_signal = signal;
  649. set_state(Dead);
  650. }
  651. void Process::send_signal(byte signal, Process* sender)
  652. {
  653. ASSERT_INTERRUPTS_DISABLED();
  654. ASSERT(signal < 32);
  655. m_pending_signals |= 1 << signal;
  656. if (sender)
  657. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
  658. else
  659. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
  660. }
  661. bool Process::has_unmasked_pending_signals() const
  662. {
  663. return m_pending_signals & m_signal_mask;
  664. }
  665. bool Process::dispatch_one_pending_signal()
  666. {
  667. ASSERT_INTERRUPTS_DISABLED();
  668. dword signal_candidates = m_pending_signals & m_signal_mask;
  669. ASSERT(signal_candidates);
  670. byte signal = 0;
  671. for (; signal < 32; ++signal) {
  672. if (signal_candidates & (1 << signal)) {
  673. break;
  674. }
  675. }
  676. return dispatch_signal(signal);
  677. }
  678. bool Process::dispatch_signal(byte signal)
  679. {
  680. ASSERT_INTERRUPTS_DISABLED();
  681. ASSERT(signal < 32);
  682. dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  683. auto& action = m_signal_action_data[signal];
  684. // FIXME: Implement SA_SIGINFO signal handlers.
  685. ASSERT(!(action.flags & SA_SIGINFO));
  686. auto handler_laddr = action.handler_or_sigaction;
  687. if (handler_laddr.is_null()) {
  688. // FIXME: Is termination really always the appropriate action?
  689. terminate_due_to_signal(signal);
  690. return true;
  691. }
  692. m_pending_signals &= ~(1 << signal);
  693. if (handler_laddr.asPtr() == SIG_IGN) {
  694. dbgprintf("%s(%u) ignored signal %u\n", name().characters(), pid(), signal); return false;
  695. }
  696. Scheduler::prepare_to_modify_tss(*this);
  697. word ret_cs = m_tss.cs;
  698. dword ret_eip = m_tss.eip;
  699. dword ret_eflags = m_tss.eflags;
  700. bool interrupting_in_kernel = (ret_cs & 3) == 0;
  701. if (interrupting_in_kernel) {
  702. dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), toString(state()), ret_cs, ret_eip);
  703. ASSERT(is_blocked());
  704. m_tss_to_resume_kernel = m_tss;
  705. #ifdef SIGNAL_DEBUG
  706. dbgprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
  707. #endif
  708. }
  709. ProcessPagingScope pagingScope(*this);
  710. if (interrupting_in_kernel) {
  711. if (!m_signal_stack_user_region) {
  712. m_signal_stack_user_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (user)");
  713. ASSERT(m_signal_stack_user_region);
  714. m_signal_stack_kernel_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (kernel)");
  715. ASSERT(m_signal_stack_user_region);
  716. }
  717. m_tss.ss = 0x23;
  718. m_tss.esp = m_signal_stack_user_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  719. m_tss.ss0 = 0x10;
  720. m_tss.esp0 = m_signal_stack_kernel_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  721. push_value_on_stack(ret_eflags);
  722. push_value_on_stack(ret_cs);
  723. push_value_on_stack(ret_eip);
  724. } else {
  725. push_value_on_stack(ret_cs);
  726. push_value_on_stack(ret_eip);
  727. push_value_on_stack(ret_eflags);
  728. }
  729. // PUSHA
  730. dword old_esp = m_tss.esp;
  731. push_value_on_stack(m_tss.eax);
  732. push_value_on_stack(m_tss.ecx);
  733. push_value_on_stack(m_tss.edx);
  734. push_value_on_stack(m_tss.ebx);
  735. push_value_on_stack(old_esp);
  736. push_value_on_stack(m_tss.ebp);
  737. push_value_on_stack(m_tss.esi);
  738. push_value_on_stack(m_tss.edi);
  739. m_tss.eax = (dword)signal;
  740. m_tss.cs = 0x1b;
  741. m_tss.ds = 0x23;
  742. m_tss.es = 0x23;
  743. m_tss.fs = 0x23;
  744. m_tss.gs = 0x23;
  745. m_tss.eip = handler_laddr.get();
  746. if (m_return_to_ring3_from_signal_trampoline.is_null()) {
  747. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  748. // FIXME: Remap as read-only after setup.
  749. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
  750. m_return_to_ring3_from_signal_trampoline = region->linearAddress;
  751. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.asPtr();
  752. *code_ptr++ = 0x61; // popa
  753. *code_ptr++ = 0x9d; // popf
  754. *code_ptr++ = 0xc3; // ret
  755. *code_ptr++ = 0x0f; // ud2
  756. *code_ptr++ = 0x0b;
  757. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  758. *code_ptr++ = 0x61; // popa
  759. *code_ptr++ = 0xb8; // mov eax, <dword>
  760. *(dword*)code_ptr = Syscall::SC_sigreturn;
  761. code_ptr += sizeof(dword);
  762. *code_ptr++ = 0xcd; // int 0x80
  763. *code_ptr++ = 0x80;
  764. *code_ptr++ = 0x0f; // ud2
  765. *code_ptr++ = 0x0b;
  766. // FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
  767. // unmasks the signal so it can be received again? I guess then I would need one trampoline
  768. // per signal number if it's hard-coded, but it's just a few bytes per each.
  769. }
  770. if (interrupting_in_kernel)
  771. push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
  772. else
  773. push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
  774. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  775. set_state(Skip1SchedulerPass);
  776. #ifdef SIGNAL_DEBUG
  777. dbgprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", name().characters(), pid(), toString(state()), m_tss.cs, m_tss.eip);
  778. #endif
  779. return true;
  780. }
  781. void Process::sys$sigreturn()
  782. {
  783. InterruptDisabler disabler;
  784. Scheduler::prepare_to_modify_tss(*this);
  785. m_tss = m_tss_to_resume_kernel;
  786. #ifdef SIGNAL_DEBUG
  787. dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  788. dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
  789. #endif
  790. set_state(Skip1SchedulerPass);
  791. Scheduler::yield();
  792. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  793. ASSERT_NOT_REACHED();
  794. }
  795. void Process::push_value_on_stack(dword value)
  796. {
  797. m_tss.esp -= 4;
  798. dword* stack_ptr = (dword*)m_tss.esp;
  799. *stack_ptr = value;
  800. }
  801. void Process::crash()
  802. {
  803. ASSERT_INTERRUPTS_DISABLED();
  804. ASSERT(state() != Dead);
  805. m_termination_signal = SIGSEGV;
  806. set_state(Dead);
  807. dumpRegions();
  808. Scheduler::pick_next_and_switch_now();
  809. ASSERT_NOT_REACHED();
  810. }
  811. Process* Process::from_pid(pid_t pid)
  812. {
  813. ASSERT_INTERRUPTS_DISABLED();
  814. for (auto* process = g_processes->head(); process; process = process->next()) {
  815. if (process->pid() == pid)
  816. return process;
  817. }
  818. return nullptr;
  819. }
  820. FileDescriptor* Process::file_descriptor(int fd)
  821. {
  822. if (fd < 0)
  823. return nullptr;
  824. if ((size_t)fd < m_fds.size())
  825. return m_fds[fd].descriptor.ptr();
  826. return nullptr;
  827. }
  828. const FileDescriptor* Process::file_descriptor(int fd) const
  829. {
  830. if (fd < 0)
  831. return nullptr;
  832. if ((size_t)fd < m_fds.size())
  833. return m_fds[fd].descriptor.ptr();
  834. return nullptr;
  835. }
  836. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, size_t size)
  837. {
  838. if (!validate_write(buffer, size))
  839. return -EFAULT;
  840. auto* descriptor = file_descriptor(fd);
  841. if (!descriptor)
  842. return -EBADF;
  843. return descriptor->get_dir_entries((byte*)buffer, size);
  844. }
  845. int Process::sys$lseek(int fd, off_t offset, int whence)
  846. {
  847. auto* descriptor = file_descriptor(fd);
  848. if (!descriptor)
  849. return -EBADF;
  850. return descriptor->seek(offset, whence);
  851. }
  852. int Process::sys$ttyname_r(int fd, char* buffer, size_t size)
  853. {
  854. if (!validate_write(buffer, size))
  855. return -EFAULT;
  856. auto* descriptor = file_descriptor(fd);
  857. if (!descriptor)
  858. return -EBADF;
  859. if (!descriptor->is_tty())
  860. return -ENOTTY;
  861. auto ttyName = descriptor->tty()->tty_name();
  862. if (size < ttyName.length() + 1)
  863. return -ERANGE;
  864. strcpy(buffer, ttyName.characters());
  865. return 0;
  866. }
  867. ssize_t Process::sys$write(int fd, const void* data, size_t size)
  868. {
  869. if (!validate_read(data, size))
  870. return -EFAULT;
  871. #ifdef DEBUG_IO
  872. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  873. #endif
  874. auto* descriptor = file_descriptor(fd);
  875. if (!descriptor)
  876. return -EBADF;
  877. ssize_t nwritten = 0;
  878. if (descriptor->is_blocking()) {
  879. while (nwritten < (ssize_t)size) {
  880. #ifdef IO_DEBUG
  881. dbgprintf("while %u < %u\n", nwritten, size);
  882. #endif
  883. if (!descriptor->can_write()) {
  884. #ifdef IO_DEBUG
  885. dbgprintf("block write on %d\n", fd);
  886. #endif
  887. m_blocked_fd = fd;
  888. block(BlockedWrite);
  889. Scheduler::yield();
  890. }
  891. ssize_t rc = descriptor->write((const byte*)data + nwritten, size - nwritten);
  892. #ifdef IO_DEBUG
  893. dbgprintf(" -> write returned %d\n", rc);
  894. #endif
  895. if (rc < 0) {
  896. // FIXME: Support returning partial nwritten with errno.
  897. ASSERT(nwritten == 0);
  898. return rc;
  899. }
  900. if (rc == 0)
  901. break;
  902. if (has_unmasked_pending_signals()) {
  903. block(BlockedSignal);
  904. Scheduler::yield();
  905. if (nwritten == 0)
  906. return -EINTR;
  907. }
  908. nwritten += rc;
  909. }
  910. } else {
  911. nwritten = descriptor->write((const byte*)data, size);
  912. }
  913. if (has_unmasked_pending_signals()) {
  914. block(BlockedSignal);
  915. Scheduler::yield();
  916. if (nwritten == 0)
  917. return -EINTR;
  918. }
  919. #ifdef DEBUG_IO
  920. dbgprintf("%s(%u) sys$write: nwritten=%u\n", name().characters(), pid(), nwritten);
  921. #endif
  922. return nwritten;
  923. }
  924. ssize_t Process::sys$read(int fd, void* outbuf, size_t nread)
  925. {
  926. if (!validate_write(outbuf, nread))
  927. return -EFAULT;
  928. #ifdef DEBUG_IO
  929. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, outbuf, nread);
  930. #endif
  931. auto* descriptor = file_descriptor(fd);
  932. if (!descriptor)
  933. return -EBADF;
  934. if (descriptor->is_blocking()) {
  935. if (!descriptor->has_data_available_for_reading()) {
  936. m_blocked_fd = fd;
  937. block(BlockedRead);
  938. sched_yield();
  939. if (m_was_interrupted_while_blocked)
  940. return -EINTR;
  941. }
  942. }
  943. nread = descriptor->read((byte*)outbuf, nread);
  944. #ifdef DEBUG_IO
  945. dbgprintf("%s(%u) Process::sys$read: nread=%u\n", name().characters(), pid(), nread);
  946. #endif
  947. return nread;
  948. }
  949. int Process::sys$close(int fd)
  950. {
  951. auto* descriptor = file_descriptor(fd);
  952. if (!descriptor)
  953. return -EBADF;
  954. int rc = descriptor->close();
  955. m_fds[fd] = { };
  956. return rc;
  957. }
  958. int Process::sys$utime(const char* pathname, const Unix::utimbuf* buf)
  959. {
  960. if (!validate_read_str(pathname))
  961. return -EFAULT;
  962. if (buf && !validate_read_typed(buf))
  963. return -EFAULT;
  964. String path(pathname);
  965. int error;
  966. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  967. if (!descriptor)
  968. return error;
  969. auto& inode = *descriptor->inode();
  970. if (inode.fs().is_readonly())
  971. return -EROFS;
  972. Unix::time_t atime;
  973. Unix::time_t mtime;
  974. if (buf) {
  975. atime = buf->actime;
  976. mtime = buf->modtime;
  977. } else {
  978. auto now = RTC::now();
  979. mtime = now;
  980. atime = now;
  981. }
  982. inode.set_atime(atime);
  983. inode.set_mtime(mtime);
  984. return 0;
  985. }
  986. int Process::sys$access(const char* pathname, int mode)
  987. {
  988. (void) mode;
  989. if (!validate_read_str(pathname))
  990. return -EFAULT;
  991. ASSERT_NOT_REACHED();
  992. }
  993. int Process::sys$fcntl(int fd, int cmd, dword arg)
  994. {
  995. (void) cmd;
  996. (void) arg;
  997. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  998. auto* descriptor = file_descriptor(fd);
  999. if (!descriptor)
  1000. return -EBADF;
  1001. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1002. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1003. switch (cmd) {
  1004. case F_DUPFD: {
  1005. int arg_fd = (int)arg;
  1006. if (arg_fd < 0)
  1007. return -EINVAL;
  1008. int new_fd = -1;
  1009. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1010. if (!m_fds[i]) {
  1011. new_fd = i;
  1012. break;
  1013. }
  1014. }
  1015. if (new_fd == -1)
  1016. return -EMFILE;
  1017. m_fds[new_fd].set(descriptor);
  1018. break;
  1019. }
  1020. case F_GETFD:
  1021. return m_fds[fd].flags;
  1022. case F_SETFD:
  1023. m_fds[fd].flags = arg;
  1024. break;
  1025. case F_GETFL:
  1026. return descriptor->file_flags();
  1027. case F_SETFL:
  1028. descriptor->set_file_flags(arg);
  1029. break;
  1030. default:
  1031. ASSERT_NOT_REACHED();
  1032. }
  1033. return 0;
  1034. }
  1035. int Process::sys$fstat(int fd, Unix::stat* statbuf)
  1036. {
  1037. if (!validate_write_typed(statbuf))
  1038. return -EFAULT;
  1039. auto* descriptor = file_descriptor(fd);
  1040. if (!descriptor)
  1041. return -EBADF;
  1042. descriptor->stat(statbuf);
  1043. return 0;
  1044. }
  1045. int Process::sys$lstat(const char* path, Unix::stat* statbuf)
  1046. {
  1047. if (!validate_write_typed(statbuf))
  1048. return -EFAULT;
  1049. int error;
  1050. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1051. if (!descriptor)
  1052. return error;
  1053. descriptor->stat(statbuf);
  1054. return 0;
  1055. }
  1056. int Process::sys$stat(const char* path, Unix::stat* statbuf)
  1057. {
  1058. if (!validate_write_typed(statbuf))
  1059. return -EFAULT;
  1060. int error;
  1061. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  1062. if (!descriptor)
  1063. return error;
  1064. descriptor->stat(statbuf);
  1065. return 0;
  1066. }
  1067. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1068. {
  1069. if (!validate_read_str(path))
  1070. return -EFAULT;
  1071. if (!validate_write(buffer, size))
  1072. return -EFAULT;
  1073. int error;
  1074. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1075. if (!descriptor)
  1076. return error;
  1077. if (!descriptor->metadata().isSymbolicLink())
  1078. return -EINVAL;
  1079. auto contents = descriptor->read_entire_file();
  1080. if (!contents)
  1081. return -EIO; // FIXME: Get a more detailed error from VFS.
  1082. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1083. if (contents.size() + 1 < size)
  1084. buffer[contents.size()] = '\0';
  1085. return 0;
  1086. }
  1087. int Process::sys$chdir(const char* path)
  1088. {
  1089. if (!validate_read_str(path))
  1090. return -EFAULT;
  1091. int error;
  1092. auto descriptor = VFS::the().open(path, error, 0, cwd_inode()->identifier());
  1093. if (!descriptor)
  1094. return error;
  1095. if (!descriptor->is_directory())
  1096. return -ENOTDIR;
  1097. m_cwd = descriptor->vnode();
  1098. return 0;
  1099. }
  1100. int Process::sys$getcwd(char* buffer, size_t size)
  1101. {
  1102. if (!validate_write(buffer, size))
  1103. return -EFAULT;
  1104. ASSERT(cwd_inode());
  1105. auto path = VFS::the().absolute_path(*cwd_inode());
  1106. if (path.is_null())
  1107. return -EINVAL;
  1108. if (size < path.length() + 1)
  1109. return -ERANGE;
  1110. strcpy(buffer, path.characters());
  1111. return 0;
  1112. }
  1113. size_t Process::number_of_open_file_descriptors() const
  1114. {
  1115. size_t count = 0;
  1116. for (auto& descriptor : m_fds) {
  1117. if (descriptor)
  1118. ++count;
  1119. }
  1120. return count;
  1121. }
  1122. int Process::sys$open(const char* path, int options)
  1123. {
  1124. #ifdef DEBUG_IO
  1125. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1126. #endif
  1127. if (!validate_read_str(path))
  1128. return -EFAULT;
  1129. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1130. return -EMFILE;
  1131. int error;
  1132. auto descriptor = VFS::the().open(path, error, options, cwd_inode()->identifier());
  1133. if (!descriptor)
  1134. return error;
  1135. if (options & O_DIRECTORY && !descriptor->is_directory())
  1136. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1137. int fd = 0;
  1138. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1139. if (!m_fds[fd])
  1140. break;
  1141. }
  1142. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1143. m_fds[fd].set(move(descriptor), flags);
  1144. return fd;
  1145. }
  1146. int Process::alloc_fd()
  1147. {
  1148. int fd = -1;
  1149. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1150. if (!m_fds[i]) {
  1151. fd = i;
  1152. break;
  1153. }
  1154. }
  1155. return fd;
  1156. }
  1157. int Process::sys$pipe(int pipefd[2])
  1158. {
  1159. if (!validate_write_typed(pipefd))
  1160. return -EFAULT;
  1161. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1162. return -EMFILE;
  1163. auto fifo = FIFO::create();
  1164. int reader_fd = alloc_fd();
  1165. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1166. pipefd[0] = reader_fd;
  1167. int writer_fd = alloc_fd();
  1168. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1169. pipefd[1] = writer_fd;
  1170. return 0;
  1171. }
  1172. int Process::sys$killpg(int pgrp, int signum)
  1173. {
  1174. if (signum < 1 || signum >= 32)
  1175. return -EINVAL;
  1176. (void) pgrp;
  1177. ASSERT_NOT_REACHED();
  1178. }
  1179. int Process::sys$setuid(uid_t)
  1180. {
  1181. ASSERT_NOT_REACHED();
  1182. }
  1183. int Process::sys$setgid(gid_t)
  1184. {
  1185. ASSERT_NOT_REACHED();
  1186. }
  1187. unsigned Process::sys$alarm(unsigned seconds)
  1188. {
  1189. (void) seconds;
  1190. ASSERT_NOT_REACHED();
  1191. }
  1192. int Process::sys$uname(utsname* buf)
  1193. {
  1194. if (!validate_write_typed(buf))
  1195. return -EFAULT;
  1196. strcpy(buf->sysname, "Serenity");
  1197. strcpy(buf->release, "1.0-dev");
  1198. strcpy(buf->version, "FIXME");
  1199. strcpy(buf->machine, "i386");
  1200. strcpy(buf->nodename, getHostname().characters());
  1201. return 0;
  1202. }
  1203. int Process::sys$isatty(int fd)
  1204. {
  1205. auto* descriptor = file_descriptor(fd);
  1206. if (!descriptor)
  1207. return -EBADF;
  1208. if (!descriptor->is_tty())
  1209. return -ENOTTY;
  1210. return 1;
  1211. }
  1212. int Process::sys$kill(pid_t pid, int signal)
  1213. {
  1214. if (pid == 0) {
  1215. // FIXME: Send to same-group processes.
  1216. ASSERT(pid != 0);
  1217. }
  1218. if (pid == -1) {
  1219. // FIXME: Send to all processes.
  1220. ASSERT(pid != -1);
  1221. }
  1222. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1223. InterruptDisabler disabler;
  1224. auto* peer = Process::from_pid(pid);
  1225. if (!peer)
  1226. return -ESRCH;
  1227. peer->send_signal(signal, this);
  1228. return 0;
  1229. }
  1230. int Process::sys$sleep(unsigned seconds)
  1231. {
  1232. if (!seconds)
  1233. return 0;
  1234. sleep(seconds * TICKS_PER_SECOND);
  1235. if (m_wakeupTime > system.uptime) {
  1236. ASSERT(m_was_interrupted_while_blocked);
  1237. dword ticks_left_until_original_wakeup_time = m_wakeupTime - system.uptime;
  1238. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1239. }
  1240. return 0;
  1241. }
  1242. int Process::sys$gettimeofday(timeval* tv)
  1243. {
  1244. if (!validate_write_typed(tv))
  1245. return -EFAULT;
  1246. InterruptDisabler disabler;
  1247. auto now = RTC::now();
  1248. tv->tv_sec = now;
  1249. tv->tv_usec = 0;
  1250. return 0;
  1251. }
  1252. uid_t Process::sys$getuid()
  1253. {
  1254. return m_uid;
  1255. }
  1256. gid_t Process::sys$getgid()
  1257. {
  1258. return m_gid;
  1259. }
  1260. uid_t Process::sys$geteuid()
  1261. {
  1262. return m_euid;
  1263. }
  1264. gid_t Process::sys$getegid()
  1265. {
  1266. return m_egid;
  1267. }
  1268. pid_t Process::sys$getpid()
  1269. {
  1270. return m_pid;
  1271. }
  1272. pid_t Process::sys$getppid()
  1273. {
  1274. return m_ppid;
  1275. }
  1276. mode_t Process::sys$umask(mode_t mask)
  1277. {
  1278. auto old_mask = m_umask;
  1279. m_umask = mask;
  1280. return old_mask;
  1281. }
  1282. int Process::reap(Process& process)
  1283. {
  1284. InterruptDisabler disabler;
  1285. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1286. if (process.ppid()) {
  1287. auto* parent = Process::from_pid(process.ppid());
  1288. ASSERT(parent);
  1289. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1290. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1291. }
  1292. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), toString(process.state()));
  1293. ASSERT(process.state() == Dead);
  1294. g_processes->remove(&process);
  1295. delete &process;
  1296. return exit_status;
  1297. }
  1298. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1299. {
  1300. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1301. // FIXME: Respect options
  1302. (void) options;
  1303. if (wstatus)
  1304. if (!validate_write_typed(wstatus))
  1305. return -EFAULT;
  1306. int dummy_wstatus;
  1307. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1308. {
  1309. InterruptDisabler disabler;
  1310. if (waitee != -1 && !Process::from_pid(waitee))
  1311. return -ECHILD;
  1312. }
  1313. if (options & WNOHANG) {
  1314. if (waitee == -1) {
  1315. pid_t reaped_pid = 0;
  1316. InterruptDisabler disabler;
  1317. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1318. if (process.state() == Dead) {
  1319. reaped_pid = process.pid();
  1320. exit_status = reap(process);
  1321. }
  1322. return true;
  1323. });
  1324. return reaped_pid;
  1325. } else {
  1326. auto* waitee_process = Process::from_pid(waitee);
  1327. if (!waitee_process)
  1328. return -ECHILD;
  1329. if (waitee_process->state() == Dead) {
  1330. exit_status = reap(*waitee_process);
  1331. return waitee;
  1332. }
  1333. return 0;
  1334. }
  1335. }
  1336. m_waitee_pid = waitee;
  1337. block(BlockedWait);
  1338. sched_yield();
  1339. if (m_was_interrupted_while_blocked)
  1340. return -EINTR;
  1341. Process* waitee_process;
  1342. {
  1343. InterruptDisabler disabler;
  1344. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1345. waitee_process = Process::from_pid(m_waitee_pid);
  1346. }
  1347. ASSERT(waitee_process);
  1348. exit_status = reap(*waitee_process);
  1349. return m_waitee_pid;
  1350. }
  1351. void Process::unblock()
  1352. {
  1353. if (current == this) {
  1354. kprintf("ignoring unblock() on current, %s(%u) {%s}\n", name().characters(), pid(), toString(state()));
  1355. return;
  1356. }
  1357. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1358. system.nblocked--;
  1359. m_state = Process::Runnable;
  1360. }
  1361. void Process::block(Process::State new_state)
  1362. {
  1363. if (state() != Process::Running) {
  1364. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, toString(new_state), state(), toString(state()));
  1365. }
  1366. ASSERT(state() == Process::Running);
  1367. system.nblocked++;
  1368. m_was_interrupted_while_blocked = false;
  1369. set_state(new_state);
  1370. }
  1371. void block(Process::State state)
  1372. {
  1373. current->block(state);
  1374. sched_yield();
  1375. }
  1376. void sleep(dword ticks)
  1377. {
  1378. ASSERT(current->state() == Process::Running);
  1379. current->setWakeupTime(system.uptime + ticks);
  1380. current->block(Process::BlockedSleep);
  1381. sched_yield();
  1382. }
  1383. bool Process::isValidAddressForKernel(LinearAddress laddr) const
  1384. {
  1385. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1386. // This code allows access outside of the known used address ranges to get caught.
  1387. InterruptDisabler disabler;
  1388. if (laddr.get() >= ksyms().first().address && laddr.get() <= ksyms().last().address)
  1389. return true;
  1390. if (is_kmalloc_address(laddr.asPtr()))
  1391. return true;
  1392. return validate_read(laddr.asPtr(), 1);
  1393. }
  1394. bool Process::validate_read(const void* address, size_t size) const
  1395. {
  1396. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1397. if (!MM.validate_user_read(*this, LinearAddress((dword)address).offset(size)))
  1398. return false;
  1399. }
  1400. return MM.validate_user_read(*this, LinearAddress((dword)address));
  1401. }
  1402. bool Process::validate_write(void* address, size_t size) const
  1403. {
  1404. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1405. if (!MM.validate_user_write(*this, LinearAddress((dword)address).offset(size)))
  1406. return false;
  1407. }
  1408. return MM.validate_user_write(*this, LinearAddress((dword)address));
  1409. }
  1410. pid_t Process::sys$getsid(pid_t pid)
  1411. {
  1412. if (pid == 0)
  1413. return m_sid;
  1414. InterruptDisabler disabler;
  1415. auto* process = Process::from_pid(pid);
  1416. if (!process)
  1417. return -ESRCH;
  1418. if (m_sid != process->m_sid)
  1419. return -EPERM;
  1420. return process->m_sid;
  1421. }
  1422. pid_t Process::sys$setsid()
  1423. {
  1424. InterruptDisabler disabler;
  1425. bool found_process_with_same_pgid_as_my_pid = false;
  1426. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1427. found_process_with_same_pgid_as_my_pid = true;
  1428. return false;
  1429. });
  1430. if (found_process_with_same_pgid_as_my_pid)
  1431. return -EPERM;
  1432. m_sid = m_pid;
  1433. m_pgid = m_pid;
  1434. return m_sid;
  1435. }
  1436. pid_t Process::sys$getpgid(pid_t pid)
  1437. {
  1438. if (pid == 0)
  1439. return m_pgid;
  1440. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1441. auto* process = Process::from_pid(pid);
  1442. if (!process)
  1443. return -ESRCH;
  1444. return process->m_pgid;
  1445. }
  1446. pid_t Process::sys$getpgrp()
  1447. {
  1448. return m_pgid;
  1449. }
  1450. static pid_t get_sid_from_pgid(pid_t pgid)
  1451. {
  1452. InterruptDisabler disabler;
  1453. auto* group_leader = Process::from_pid(pgid);
  1454. if (!group_leader)
  1455. return -1;
  1456. return group_leader->sid();
  1457. }
  1458. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1459. {
  1460. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1461. pid_t pid = specified_pid ? specified_pid : m_pid;
  1462. if (specified_pgid < 0)
  1463. return -EINVAL;
  1464. auto* process = Process::from_pid(pid);
  1465. if (!process)
  1466. return -ESRCH;
  1467. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1468. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1469. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1470. if (current_sid != new_sid) {
  1471. // Can't move a process between sessions.
  1472. return -EPERM;
  1473. }
  1474. // FIXME: There are more EPERM conditions to check for here..
  1475. process->m_pgid = new_pgid;
  1476. return 0;
  1477. }
  1478. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1479. {
  1480. auto* descriptor = file_descriptor(fd);
  1481. if (!descriptor)
  1482. return -EBADF;
  1483. if (!descriptor->is_character_device())
  1484. return -ENOTTY;
  1485. return descriptor->character_device()->ioctl(*this, request, arg);
  1486. }
  1487. int Process::sys$getdtablesize()
  1488. {
  1489. return m_max_open_file_descriptors;
  1490. }
  1491. int Process::sys$dup(int old_fd)
  1492. {
  1493. auto* descriptor = file_descriptor(old_fd);
  1494. if (!descriptor)
  1495. return -EBADF;
  1496. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1497. return -EMFILE;
  1498. int new_fd = 0;
  1499. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1500. if (!m_fds[new_fd])
  1501. break;
  1502. }
  1503. m_fds[new_fd].set(descriptor);
  1504. return new_fd;
  1505. }
  1506. int Process::sys$dup2(int old_fd, int new_fd)
  1507. {
  1508. auto* descriptor = file_descriptor(old_fd);
  1509. if (!descriptor)
  1510. return -EBADF;
  1511. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1512. return -EMFILE;
  1513. m_fds[new_fd].set(descriptor);
  1514. return new_fd;
  1515. }
  1516. int Process::sys$sigprocmask(int how, const Unix::sigset_t* set, Unix::sigset_t* old_set)
  1517. {
  1518. if (old_set) {
  1519. if (!validate_read_typed(old_set))
  1520. return -EFAULT;
  1521. *old_set = m_signal_mask;
  1522. }
  1523. if (set) {
  1524. if (!validate_read_typed(set))
  1525. return -EFAULT;
  1526. switch (how) {
  1527. case SIG_BLOCK:
  1528. m_signal_mask &= ~(*set);
  1529. break;
  1530. case SIG_UNBLOCK:
  1531. m_signal_mask |= *set;
  1532. break;
  1533. case SIG_SETMASK:
  1534. m_signal_mask = *set;
  1535. break;
  1536. default:
  1537. return -EINVAL;
  1538. }
  1539. }
  1540. return 0;
  1541. }
  1542. int Process::sys$sigpending(Unix::sigset_t* set)
  1543. {
  1544. if (!validate_read_typed(set))
  1545. return -EFAULT;
  1546. *set = m_pending_signals;
  1547. return 0;
  1548. }
  1549. int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
  1550. {
  1551. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1552. return -EINVAL;
  1553. if (!validate_read_typed(act))
  1554. return -EFAULT;
  1555. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1556. auto& action = m_signal_action_data[signum];
  1557. if (old_act) {
  1558. if (!validate_write_typed(old_act))
  1559. return -EFAULT;
  1560. old_act->sa_flags = action.flags;
  1561. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1562. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1563. }
  1564. action.restorer = LinearAddress((dword)act->sa_restorer);
  1565. action.flags = act->sa_flags;
  1566. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1567. return 0;
  1568. }
  1569. int Process::sys$getgroups(int count, gid_t* gids)
  1570. {
  1571. if (count < 0)
  1572. return -EINVAL;
  1573. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1574. if (!count)
  1575. return m_gids.size();
  1576. if (count != (int)m_gids.size())
  1577. return -EINVAL;
  1578. if (!validate_write_typed(gids, m_gids.size()))
  1579. return -EFAULT;
  1580. size_t i = 0;
  1581. for (auto gid : m_gids)
  1582. gids[i++] = gid;
  1583. return 0;
  1584. }
  1585. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1586. {
  1587. if (!is_root())
  1588. return -EPERM;
  1589. if (count >= MAX_PROCESS_GIDS)
  1590. return -EINVAL;
  1591. if (!validate_read(gids, count))
  1592. return -EFAULT;
  1593. m_gids.clear();
  1594. m_gids.set(m_gid);
  1595. for (size_t i = 0; i < count; ++i)
  1596. m_gids.set(gids[i]);
  1597. return 0;
  1598. }
  1599. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1600. {
  1601. if (!validate_read_str(pathname))
  1602. return -EFAULT;
  1603. if (strlen(pathname) >= 255)
  1604. return -ENAMETOOLONG;
  1605. int error;
  1606. if (!VFS::the().mkdir(pathname, mode, cwd_inode()->identifier(), error))
  1607. return error;
  1608. return 0;
  1609. }
  1610. Unix::clock_t Process::sys$times(Unix::tms* times)
  1611. {
  1612. if (!validate_write_typed(times))
  1613. return -EFAULT;
  1614. times->tms_utime = m_ticks_in_user;
  1615. times->tms_stime = m_ticks_in_kernel;
  1616. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1617. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1618. return 0;
  1619. }