Process.cpp 53 KB

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