Process.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  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/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/StdLib.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).isolatedCopy();
  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->sizeSlow());
  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.mapRegion(*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.mapRegion(*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.mapRegion(*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.unmapRegion(*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.mapRegion(*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().addProcess(*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.isEmpty())
  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.isEmpty()) {
  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().addProcess(*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.mapRegion(*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.mapRegion(*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().addProcess(*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().removeProcess(*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->isTTY())
  860. return -ENOTTY;
  861. auto ttyName = descriptor->tty()->ttyName();
  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->isBlocking()) {
  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->isBlocking()) {
  935. if (!descriptor->hasDataAvailableForRead()) {
  936. m_fdBlockedOnRead = 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$access(const char* pathname, int mode)
  959. {
  960. (void) mode;
  961. if (!validate_read_str(pathname))
  962. return -EFAULT;
  963. ASSERT_NOT_REACHED();
  964. }
  965. int Process::sys$fcntl(int fd, int cmd, dword arg)
  966. {
  967. (void) cmd;
  968. (void) arg;
  969. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  970. auto* descriptor = file_descriptor(fd);
  971. if (!descriptor)
  972. return -EBADF;
  973. // NOTE: The FD flags are not shared between FileDescriptor objects.
  974. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  975. switch (cmd) {
  976. case F_DUPFD: {
  977. int arg_fd = (int)arg;
  978. if (arg_fd < 0)
  979. return -EINVAL;
  980. int new_fd = -1;
  981. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  982. if (!m_fds[i]) {
  983. new_fd = i;
  984. break;
  985. }
  986. }
  987. if (new_fd == -1)
  988. return -EMFILE;
  989. m_fds[new_fd].set(descriptor);
  990. break;
  991. }
  992. case F_GETFD:
  993. return m_fds[fd].flags;
  994. case F_SETFD:
  995. m_fds[fd].flags = arg;
  996. break;
  997. case F_GETFL:
  998. return descriptor->file_flags();
  999. case F_SETFL:
  1000. descriptor->set_file_flags(arg);
  1001. break;
  1002. default:
  1003. ASSERT_NOT_REACHED();
  1004. }
  1005. return 0;
  1006. }
  1007. int Process::sys$fstat(int fd, Unix::stat* statbuf)
  1008. {
  1009. if (!validate_write_typed(statbuf))
  1010. return -EFAULT;
  1011. auto* descriptor = file_descriptor(fd);
  1012. if (!descriptor)
  1013. return -EBADF;
  1014. descriptor->stat(statbuf);
  1015. return 0;
  1016. }
  1017. int Process::sys$lstat(const char* path, Unix::stat* statbuf)
  1018. {
  1019. if (!validate_write_typed(statbuf))
  1020. return -EFAULT;
  1021. int error;
  1022. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1023. if (!descriptor)
  1024. return error;
  1025. descriptor->stat(statbuf);
  1026. return 0;
  1027. }
  1028. int Process::sys$stat(const char* path, Unix::stat* statbuf)
  1029. {
  1030. if (!validate_write_typed(statbuf))
  1031. return -EFAULT;
  1032. int error;
  1033. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  1034. if (!descriptor)
  1035. return error;
  1036. descriptor->stat(statbuf);
  1037. return 0;
  1038. }
  1039. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1040. {
  1041. if (!validate_read_str(path))
  1042. return -EFAULT;
  1043. if (!validate_write(buffer, size))
  1044. return -EFAULT;
  1045. int error;
  1046. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1047. if (!descriptor)
  1048. return error;
  1049. if (!descriptor->metadata().isSymbolicLink())
  1050. return -EINVAL;
  1051. auto contents = descriptor->readEntireFile();
  1052. if (!contents)
  1053. return -EIO; // FIXME: Get a more detailed error from VFS.
  1054. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1055. if (contents.size() + 1 < size)
  1056. buffer[contents.size()] = '\0';
  1057. return 0;
  1058. }
  1059. int Process::sys$chdir(const char* path)
  1060. {
  1061. if (!validate_read_str(path))
  1062. return -EFAULT;
  1063. int error;
  1064. auto descriptor = VFS::the().open(path, error, 0, cwd_inode()->identifier());
  1065. if (!descriptor)
  1066. return error;
  1067. if (!descriptor->isDirectory())
  1068. return -ENOTDIR;
  1069. m_cwd = descriptor->vnode();
  1070. return 0;
  1071. }
  1072. int Process::sys$getcwd(char* buffer, size_t size)
  1073. {
  1074. if (!validate_write(buffer, size))
  1075. return -EFAULT;
  1076. ASSERT(cwd_inode());
  1077. auto path = VFS::the().absolute_path(*cwd_inode());
  1078. if (path.isNull())
  1079. return -EINVAL;
  1080. if (size < path.length() + 1)
  1081. return -ERANGE;
  1082. strcpy(buffer, path.characters());
  1083. return 0;
  1084. }
  1085. size_t Process::number_of_open_file_descriptors() const
  1086. {
  1087. size_t count = 0;
  1088. for (auto& descriptor : m_fds) {
  1089. if (descriptor)
  1090. ++count;
  1091. }
  1092. return count;
  1093. }
  1094. int Process::sys$open(const char* path, int options)
  1095. {
  1096. #ifdef DEBUG_IO
  1097. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1098. #endif
  1099. if (!validate_read_str(path))
  1100. return -EFAULT;
  1101. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1102. return -EMFILE;
  1103. int error;
  1104. auto descriptor = VFS::the().open(path, error, options, cwd_inode()->identifier());
  1105. if (!descriptor)
  1106. return error;
  1107. if (options & O_DIRECTORY && !descriptor->isDirectory())
  1108. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1109. int fd = 0;
  1110. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1111. if (!m_fds[fd])
  1112. break;
  1113. }
  1114. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1115. m_fds[fd].set(move(descriptor), flags);
  1116. return fd;
  1117. }
  1118. int Process::alloc_fd()
  1119. {
  1120. int fd = -1;
  1121. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1122. if (!m_fds[i]) {
  1123. fd = i;
  1124. break;
  1125. }
  1126. }
  1127. return fd;
  1128. }
  1129. int Process::sys$pipe(int pipefd[2])
  1130. {
  1131. if (!validate_write_typed(pipefd))
  1132. return -EFAULT;
  1133. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1134. return -EMFILE;
  1135. auto fifo = FIFO::create();
  1136. int reader_fd = alloc_fd();
  1137. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1138. pipefd[0] = reader_fd;
  1139. int writer_fd = alloc_fd();
  1140. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1141. pipefd[1] = writer_fd;
  1142. return 0;
  1143. }
  1144. int Process::sys$killpg(int pgrp, int signum)
  1145. {
  1146. if (signum < 1 || signum >= 32)
  1147. return -EINVAL;
  1148. (void) pgrp;
  1149. ASSERT_NOT_REACHED();
  1150. }
  1151. int Process::sys$setuid(uid_t)
  1152. {
  1153. ASSERT_NOT_REACHED();
  1154. }
  1155. int Process::sys$setgid(gid_t)
  1156. {
  1157. ASSERT_NOT_REACHED();
  1158. }
  1159. unsigned Process::sys$alarm(unsigned seconds)
  1160. {
  1161. (void) seconds;
  1162. ASSERT_NOT_REACHED();
  1163. }
  1164. int Process::sys$uname(utsname* buf)
  1165. {
  1166. if (!validate_write_typed(buf))
  1167. return -EFAULT;
  1168. strcpy(buf->sysname, "Serenity");
  1169. strcpy(buf->release, "1.0-dev");
  1170. strcpy(buf->version, "FIXME");
  1171. strcpy(buf->machine, "i386");
  1172. strcpy(buf->nodename, getHostname().characters());
  1173. return 0;
  1174. }
  1175. int Process::sys$isatty(int fd)
  1176. {
  1177. auto* descriptor = file_descriptor(fd);
  1178. if (!descriptor)
  1179. return -EBADF;
  1180. if (!descriptor->isTTY())
  1181. return -ENOTTY;
  1182. return 1;
  1183. }
  1184. int Process::sys$kill(pid_t pid, int signal)
  1185. {
  1186. if (pid == 0) {
  1187. // FIXME: Send to same-group processes.
  1188. ASSERT(pid != 0);
  1189. }
  1190. if (pid == -1) {
  1191. // FIXME: Send to all processes.
  1192. ASSERT(pid != -1);
  1193. }
  1194. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1195. InterruptDisabler disabler;
  1196. auto* peer = Process::from_pid(pid);
  1197. if (!peer)
  1198. return -ESRCH;
  1199. peer->send_signal(signal, this);
  1200. return 0;
  1201. }
  1202. int Process::sys$sleep(unsigned seconds)
  1203. {
  1204. if (!seconds)
  1205. return 0;
  1206. sleep(seconds * TICKS_PER_SECOND);
  1207. if (m_wakeupTime > system.uptime) {
  1208. ASSERT(m_was_interrupted_while_blocked);
  1209. dword ticks_left_until_original_wakeup_time = m_wakeupTime - system.uptime;
  1210. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1211. }
  1212. return 0;
  1213. }
  1214. int Process::sys$gettimeofday(timeval* tv)
  1215. {
  1216. if (!validate_write_typed(tv))
  1217. return -EFAULT;
  1218. InterruptDisabler disabler;
  1219. auto now = RTC::now();
  1220. tv->tv_sec = now;
  1221. tv->tv_usec = 0;
  1222. return 0;
  1223. }
  1224. uid_t Process::sys$getuid()
  1225. {
  1226. return m_uid;
  1227. }
  1228. gid_t Process::sys$getgid()
  1229. {
  1230. return m_gid;
  1231. }
  1232. uid_t Process::sys$geteuid()
  1233. {
  1234. return m_euid;
  1235. }
  1236. gid_t Process::sys$getegid()
  1237. {
  1238. return m_egid;
  1239. }
  1240. pid_t Process::sys$getpid()
  1241. {
  1242. return m_pid;
  1243. }
  1244. pid_t Process::sys$getppid()
  1245. {
  1246. return m_ppid;
  1247. }
  1248. mode_t Process::sys$umask(mode_t mask)
  1249. {
  1250. auto old_mask = m_umask;
  1251. m_umask = mask;
  1252. return old_mask;
  1253. }
  1254. int Process::reap(Process& process)
  1255. {
  1256. InterruptDisabler disabler;
  1257. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1258. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), toString(process.state()));
  1259. ASSERT(process.state() == Dead);
  1260. g_processes->remove(&process);
  1261. delete &process;
  1262. return exit_status;
  1263. }
  1264. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1265. {
  1266. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1267. // FIXME: Respect options
  1268. (void) options;
  1269. if (wstatus)
  1270. if (!validate_write_typed(wstatus))
  1271. return -EFAULT;
  1272. int dummy_wstatus;
  1273. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1274. {
  1275. InterruptDisabler disabler;
  1276. if (waitee != -1 && !Process::from_pid(waitee))
  1277. return -ECHILD;
  1278. }
  1279. if (options & WNOHANG) {
  1280. if (waitee == -1) {
  1281. pid_t reaped_pid = 0;
  1282. InterruptDisabler disabler;
  1283. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1284. if (process.state() == Dead) {
  1285. reaped_pid = process.pid();
  1286. exit_status = reap(process);
  1287. }
  1288. return true;
  1289. });
  1290. return reaped_pid;
  1291. } else {
  1292. auto* waitee_process = Process::from_pid(waitee);
  1293. if (!waitee_process)
  1294. return -ECHILD;
  1295. if (waitee_process->state() == Dead) {
  1296. exit_status = reap(*waitee_process);
  1297. return waitee;
  1298. }
  1299. return 0;
  1300. }
  1301. }
  1302. m_waitee = waitee;
  1303. block(BlockedWait);
  1304. sched_yield();
  1305. if (m_was_interrupted_while_blocked)
  1306. return -EINTR;
  1307. Process* waitee_process;
  1308. {
  1309. InterruptDisabler disabler;
  1310. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1311. waitee_process = Process::from_pid(m_waitee);
  1312. }
  1313. ASSERT(waitee_process);
  1314. exit_status = reap(*waitee_process);
  1315. return m_waitee;
  1316. }
  1317. void Process::unblock()
  1318. {
  1319. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1320. system.nblocked--;
  1321. m_state = Process::Runnable;
  1322. }
  1323. void Process::block(Process::State new_state)
  1324. {
  1325. if (state() != Process::Running) {
  1326. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, toString(new_state), state(), toString(state()));
  1327. }
  1328. ASSERT(state() == Process::Running);
  1329. system.nblocked++;
  1330. m_was_interrupted_while_blocked = false;
  1331. set_state(new_state);
  1332. }
  1333. void block(Process::State state)
  1334. {
  1335. current->block(state);
  1336. sched_yield();
  1337. }
  1338. void sleep(dword ticks)
  1339. {
  1340. ASSERT(current->state() == Process::Running);
  1341. current->setWakeupTime(system.uptime + ticks);
  1342. current->block(Process::BlockedSleep);
  1343. sched_yield();
  1344. }
  1345. bool Process::isValidAddressForKernel(LinearAddress laddr) const
  1346. {
  1347. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1348. // This code allows access outside of the known used address ranges to get caught.
  1349. InterruptDisabler disabler;
  1350. if (laddr.get() >= ksyms().first().address && laddr.get() <= ksyms().last().address)
  1351. return true;
  1352. if (is_kmalloc_address(laddr.asPtr()))
  1353. return true;
  1354. return validate_read(laddr.asPtr(), 1);
  1355. }
  1356. bool Process::validate_read(const void* address, size_t size) const
  1357. {
  1358. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1359. if (!MM.validate_user_read(*this, LinearAddress((dword)address).offset(size)))
  1360. return false;
  1361. }
  1362. return MM.validate_user_read(*this, LinearAddress((dword)address));
  1363. }
  1364. bool Process::validate_write(void* address, size_t size) const
  1365. {
  1366. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1367. if (!MM.validate_user_write(*this, LinearAddress((dword)address).offset(size)))
  1368. return false;
  1369. }
  1370. return MM.validate_user_write(*this, LinearAddress((dword)address));
  1371. }
  1372. pid_t Process::sys$getsid(pid_t pid)
  1373. {
  1374. if (pid == 0)
  1375. return m_sid;
  1376. InterruptDisabler disabler;
  1377. auto* process = Process::from_pid(pid);
  1378. if (!process)
  1379. return -ESRCH;
  1380. if (m_sid != process->m_sid)
  1381. return -EPERM;
  1382. return process->m_sid;
  1383. }
  1384. pid_t Process::sys$setsid()
  1385. {
  1386. InterruptDisabler disabler;
  1387. bool found_process_with_same_pgid_as_my_pid = false;
  1388. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1389. found_process_with_same_pgid_as_my_pid = true;
  1390. return false;
  1391. });
  1392. if (found_process_with_same_pgid_as_my_pid)
  1393. return -EPERM;
  1394. m_sid = m_pid;
  1395. m_pgid = m_pid;
  1396. return m_sid;
  1397. }
  1398. pid_t Process::sys$getpgid(pid_t pid)
  1399. {
  1400. if (pid == 0)
  1401. return m_pgid;
  1402. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1403. auto* process = Process::from_pid(pid);
  1404. if (!process)
  1405. return -ESRCH;
  1406. return process->m_pgid;
  1407. }
  1408. pid_t Process::sys$getpgrp()
  1409. {
  1410. return m_pgid;
  1411. }
  1412. static pid_t get_sid_from_pgid(pid_t pgid)
  1413. {
  1414. InterruptDisabler disabler;
  1415. auto* group_leader = Process::from_pid(pgid);
  1416. if (!group_leader)
  1417. return -1;
  1418. return group_leader->sid();
  1419. }
  1420. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1421. {
  1422. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1423. pid_t pid = specified_pid ? specified_pid : m_pid;
  1424. if (specified_pgid < 0)
  1425. return -EINVAL;
  1426. auto* process = Process::from_pid(pid);
  1427. if (!process)
  1428. return -ESRCH;
  1429. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1430. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1431. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1432. if (current_sid != new_sid) {
  1433. // Can't move a process between sessions.
  1434. return -EPERM;
  1435. }
  1436. // FIXME: There are more EPERM conditions to check for here..
  1437. process->m_pgid = new_pgid;
  1438. return 0;
  1439. }
  1440. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1441. {
  1442. auto* descriptor = file_descriptor(fd);
  1443. if (!descriptor)
  1444. return -EBADF;
  1445. if (!descriptor->is_character_device())
  1446. return -ENOTTY;
  1447. return descriptor->character_device()->ioctl(*this, request, arg);
  1448. }
  1449. int Process::sys$getdtablesize()
  1450. {
  1451. return m_max_open_file_descriptors;
  1452. }
  1453. int Process::sys$dup(int old_fd)
  1454. {
  1455. auto* descriptor = file_descriptor(old_fd);
  1456. if (!descriptor)
  1457. return -EBADF;
  1458. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1459. return -EMFILE;
  1460. int new_fd = 0;
  1461. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1462. if (!m_fds[new_fd])
  1463. break;
  1464. }
  1465. m_fds[new_fd].set(descriptor);
  1466. return new_fd;
  1467. }
  1468. int Process::sys$dup2(int old_fd, int new_fd)
  1469. {
  1470. auto* descriptor = file_descriptor(old_fd);
  1471. if (!descriptor)
  1472. return -EBADF;
  1473. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1474. return -EMFILE;
  1475. m_fds[new_fd].set(descriptor);
  1476. return new_fd;
  1477. }
  1478. Unix::sighandler_t Process::sys$signal(int signum, Unix::sighandler_t handler)
  1479. {
  1480. // FIXME: Fail with -EINVAL if attepmting to catch or ignore SIGKILL or SIGSTOP.
  1481. if (signum < 1 || signum >= 32)
  1482. return (Unix::sighandler_t)-EINVAL;
  1483. dbgprintf("sys$signal: %d => L%x\n", signum, handler);
  1484. return nullptr;
  1485. }
  1486. int Process::sys$sigprocmask(int how, const Unix::sigset_t* set, Unix::sigset_t* old_set)
  1487. {
  1488. if (old_set) {
  1489. if (!validate_read_typed(old_set))
  1490. return -EFAULT;
  1491. *old_set = m_signal_mask;
  1492. }
  1493. if (set) {
  1494. if (!validate_read_typed(set))
  1495. return -EFAULT;
  1496. switch (how) {
  1497. case SIG_BLOCK:
  1498. m_signal_mask &= ~(*set);
  1499. break;
  1500. case SIG_UNBLOCK:
  1501. m_signal_mask |= *set;
  1502. break;
  1503. case SIG_SETMASK:
  1504. m_signal_mask = *set;
  1505. break;
  1506. default:
  1507. return -EINVAL;
  1508. }
  1509. }
  1510. return 0;
  1511. }
  1512. int Process::sys$sigpending(Unix::sigset_t* set)
  1513. {
  1514. if (!validate_read_typed(set))
  1515. return -EFAULT;
  1516. *set = m_pending_signals;
  1517. return 0;
  1518. }
  1519. int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
  1520. {
  1521. // FIXME: Fail with -EINVAL if attepmting to change action for SIGKILL or SIGSTOP.
  1522. if (signum < 1 || signum >= 32)
  1523. return -EINVAL;
  1524. if (!validate_read_typed(act))
  1525. return -EFAULT;
  1526. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1527. auto& action = m_signal_action_data[signum];
  1528. if (old_act) {
  1529. if (!validate_write_typed(old_act))
  1530. return -EFAULT;
  1531. old_act->sa_flags = action.flags;
  1532. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1533. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1534. }
  1535. action.restorer = LinearAddress((dword)act->sa_restorer);
  1536. action.flags = act->sa_flags;
  1537. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1538. return 0;
  1539. }
  1540. int Process::sys$getgroups(int count, gid_t* gids)
  1541. {
  1542. if (count < 0)
  1543. return -EINVAL;
  1544. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1545. if (!count)
  1546. return m_gids.size();
  1547. if (count != (int)m_gids.size())
  1548. return -EINVAL;
  1549. if (!validate_write_typed(gids, m_gids.size()))
  1550. return -EFAULT;
  1551. size_t i = 0;
  1552. for (auto gid : m_gids)
  1553. gids[i++] = gid;
  1554. return 0;
  1555. }
  1556. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1557. {
  1558. if (!is_root())
  1559. return -EPERM;
  1560. if (count >= MAX_PROCESS_GIDS)
  1561. return -EINVAL;
  1562. if (!validate_read(gids, count))
  1563. return -EFAULT;
  1564. m_gids.clear();
  1565. m_gids.set(m_gid);
  1566. for (size_t i = 0; i < count; ++i)
  1567. m_gids.set(gids[i]);
  1568. return 0;
  1569. }
  1570. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1571. {
  1572. if (!validate_read_str(pathname))
  1573. return -EFAULT;
  1574. if (strlen(pathname) >= 255)
  1575. return -ENAMETOOLONG;
  1576. int error;
  1577. if (!VFS::the().mkdir(pathname, mode, cwd_inode()->identifier(), error))
  1578. return error;
  1579. return 0;
  1580. }