Process.cpp 50 KB

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