Process.cpp 52 KB

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