Process.cpp 49 KB

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