Process.cpp 45 KB

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