Process.cpp 50 KB

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