Process.cpp 51 KB

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