Process.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  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("courage");
  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. dbgprintf("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. if (options & WNOHANG) {
  1269. if (waitee == -1) {
  1270. pid_t reaped_pid = 0;
  1271. InterruptDisabler disabler;
  1272. for_each_child([&reaped_pid] (Process& process) {
  1273. if (process.state() == Dead) {
  1274. reaped_pid = process.pid();
  1275. reap(process);
  1276. }
  1277. return true;
  1278. });
  1279. return reaped_pid;
  1280. } else {
  1281. auto* waitee_process = Process::from_pid(waitee);
  1282. if (!waitee_process)
  1283. return -ECHILD;
  1284. if (waitee_process->state() == Dead) {
  1285. reap(*waitee_process);
  1286. return waitee;
  1287. }
  1288. return 0;
  1289. }
  1290. }
  1291. m_waitee = waitee;
  1292. m_waitee_status = 0;
  1293. block(BlockedWait);
  1294. sched_yield();
  1295. if (m_was_interrupted_while_blocked)
  1296. return -EINTR;
  1297. Process* waitee_process;
  1298. {
  1299. InterruptDisabler disabler;
  1300. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1301. waitee_process = Process::from_pid(m_waitee);
  1302. }
  1303. ASSERT(waitee_process);
  1304. reap(*waitee_process);
  1305. if (wstatus)
  1306. *wstatus = m_waitee_status;
  1307. return m_waitee;
  1308. }
  1309. void Process::unblock()
  1310. {
  1311. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1312. system.nblocked--;
  1313. m_state = Process::Runnable;
  1314. }
  1315. void Process::block(Process::State new_state)
  1316. {
  1317. if (state() != Process::Running) {
  1318. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, toString(new_state), state(), toString(state()));
  1319. }
  1320. ASSERT(state() == Process::Running);
  1321. system.nblocked++;
  1322. m_was_interrupted_while_blocked = false;
  1323. set_state(new_state);
  1324. }
  1325. void block(Process::State state)
  1326. {
  1327. current->block(state);
  1328. sched_yield();
  1329. }
  1330. void sleep(dword ticks)
  1331. {
  1332. ASSERT(current->state() == Process::Running);
  1333. current->setWakeupTime(system.uptime + ticks);
  1334. current->block(Process::BlockedSleep);
  1335. sched_yield();
  1336. }
  1337. bool Process::isValidAddressForKernel(LinearAddress laddr) const
  1338. {
  1339. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1340. // This code allows access outside of the known used address ranges to get caught.
  1341. InterruptDisabler disabler;
  1342. if (laddr.get() >= ksyms().first().address && laddr.get() <= ksyms().last().address)
  1343. return true;
  1344. if (is_kmalloc_address(laddr.asPtr()))
  1345. return true;
  1346. return validate_read(laddr.asPtr(), 1);
  1347. }
  1348. bool Process::validate_read(const void* address, size_t size) const
  1349. {
  1350. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1351. if (!MM.validate_user_read(*this, LinearAddress((dword)address).offset(size)))
  1352. return false;
  1353. }
  1354. return MM.validate_user_read(*this, LinearAddress((dword)address));
  1355. }
  1356. bool Process::validate_write(void* address, size_t size) const
  1357. {
  1358. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1359. if (!MM.validate_user_write(*this, LinearAddress((dword)address).offset(size)))
  1360. return false;
  1361. }
  1362. return MM.validate_user_write(*this, LinearAddress((dword)address));
  1363. }
  1364. pid_t Process::sys$getsid(pid_t pid)
  1365. {
  1366. if (pid == 0)
  1367. return m_sid;
  1368. InterruptDisabler disabler;
  1369. auto* process = Process::from_pid(pid);
  1370. if (!process)
  1371. return -ESRCH;
  1372. if (m_sid != process->m_sid)
  1373. return -EPERM;
  1374. return process->m_sid;
  1375. }
  1376. pid_t Process::sys$setsid()
  1377. {
  1378. InterruptDisabler disabler;
  1379. bool found_process_with_same_pgid_as_my_pid = false;
  1380. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1381. found_process_with_same_pgid_as_my_pid = true;
  1382. return false;
  1383. });
  1384. if (found_process_with_same_pgid_as_my_pid)
  1385. return -EPERM;
  1386. m_sid = m_pid;
  1387. m_pgid = m_pid;
  1388. return m_sid;
  1389. }
  1390. pid_t Process::sys$getpgid(pid_t pid)
  1391. {
  1392. if (pid == 0)
  1393. return m_pgid;
  1394. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1395. auto* process = Process::from_pid(pid);
  1396. if (!process)
  1397. return -ESRCH;
  1398. return process->m_pgid;
  1399. }
  1400. pid_t Process::sys$getpgrp()
  1401. {
  1402. return m_pgid;
  1403. }
  1404. static pid_t get_sid_from_pgid(pid_t pgid)
  1405. {
  1406. InterruptDisabler disabler;
  1407. auto* group_leader = Process::from_pid(pgid);
  1408. if (!group_leader)
  1409. return -1;
  1410. return group_leader->sid();
  1411. }
  1412. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1413. {
  1414. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1415. pid_t pid = specified_pid ? specified_pid : m_pid;
  1416. if (specified_pgid < 0)
  1417. return -EINVAL;
  1418. auto* process = Process::from_pid(pid);
  1419. if (!process)
  1420. return -ESRCH;
  1421. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1422. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1423. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1424. if (current_sid != new_sid) {
  1425. // Can't move a process between sessions.
  1426. return -EPERM;
  1427. }
  1428. // FIXME: There are more EPERM conditions to check for here..
  1429. process->m_pgid = new_pgid;
  1430. return 0;
  1431. }
  1432. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1433. {
  1434. auto* descriptor = file_descriptor(fd);
  1435. if (!descriptor)
  1436. return -EBADF;
  1437. if (!descriptor->is_character_device())
  1438. return -ENOTTY;
  1439. return descriptor->character_device()->ioctl(*this, request, arg);
  1440. }
  1441. int Process::sys$getdtablesize()
  1442. {
  1443. return m_max_open_file_descriptors;
  1444. }
  1445. int Process::sys$dup(int old_fd)
  1446. {
  1447. auto* descriptor = file_descriptor(old_fd);
  1448. if (!descriptor)
  1449. return -EBADF;
  1450. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1451. return -EMFILE;
  1452. int new_fd = 0;
  1453. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1454. if (!m_fds[new_fd])
  1455. break;
  1456. }
  1457. m_fds[new_fd].set(descriptor);
  1458. return new_fd;
  1459. }
  1460. int Process::sys$dup2(int old_fd, int new_fd)
  1461. {
  1462. auto* descriptor = file_descriptor(old_fd);
  1463. if (!descriptor)
  1464. return -EBADF;
  1465. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1466. return -EMFILE;
  1467. m_fds[new_fd].set(descriptor);
  1468. return new_fd;
  1469. }
  1470. Unix::sighandler_t Process::sys$signal(int signum, Unix::sighandler_t handler)
  1471. {
  1472. // FIXME: Fail with -EINVAL if attepmting to catch or ignore SIGKILL or SIGSTOP.
  1473. if (signum < 1 || signum >= 32)
  1474. return (Unix::sighandler_t)-EINVAL;
  1475. dbgprintf("sys$signal: %d => L%x\n", signum, handler);
  1476. return nullptr;
  1477. }
  1478. int Process::sys$sigprocmask(int how, const Unix::sigset_t* set, Unix::sigset_t* old_set)
  1479. {
  1480. if (old_set) {
  1481. if (!validate_read_typed(old_set))
  1482. return -EFAULT;
  1483. *old_set = m_signal_mask;
  1484. }
  1485. if (set) {
  1486. if (!validate_read_typed(set))
  1487. return -EFAULT;
  1488. switch (how) {
  1489. case SIG_BLOCK:
  1490. m_signal_mask &= ~(*set);
  1491. break;
  1492. case SIG_UNBLOCK:
  1493. m_signal_mask |= *set;
  1494. break;
  1495. case SIG_SETMASK:
  1496. m_signal_mask = *set;
  1497. break;
  1498. default:
  1499. return -EINVAL;
  1500. }
  1501. }
  1502. return 0;
  1503. }
  1504. int Process::sys$sigpending(Unix::sigset_t* set)
  1505. {
  1506. if (!validate_read_typed(set))
  1507. return -EFAULT;
  1508. *set = m_pending_signals;
  1509. return 0;
  1510. }
  1511. int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
  1512. {
  1513. // FIXME: Fail with -EINVAL if attepmting to change action for SIGKILL or SIGSTOP.
  1514. if (signum < 1 || signum >= 32)
  1515. return -EINVAL;
  1516. if (!validate_read_typed(act))
  1517. return -EFAULT;
  1518. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1519. auto& action = m_signal_action_data[signum];
  1520. if (old_act) {
  1521. if (!validate_write_typed(old_act))
  1522. return -EFAULT;
  1523. old_act->sa_flags = action.flags;
  1524. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1525. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1526. }
  1527. action.restorer = LinearAddress((dword)act->sa_restorer);
  1528. action.flags = act->sa_flags;
  1529. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1530. return 0;
  1531. }
  1532. int Process::sys$getgroups(int count, gid_t* gids)
  1533. {
  1534. if (count < 0)
  1535. return -EINVAL;
  1536. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1537. if (!count)
  1538. return m_gids.size();
  1539. if (count != (int)m_gids.size())
  1540. return -EINVAL;
  1541. if (!validate_write_typed(gids, m_gids.size()))
  1542. return -EFAULT;
  1543. size_t i = 0;
  1544. for (auto gid : m_gids)
  1545. gids[i++] = gid;
  1546. return 0;
  1547. }
  1548. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1549. {
  1550. if (!is_root())
  1551. return -EPERM;
  1552. if (count >= MAX_PROCESS_GIDS)
  1553. return -EINVAL;
  1554. if (!validate_read(gids, count))
  1555. return -EFAULT;
  1556. m_gids.clear();
  1557. m_gids.set(m_gid);
  1558. for (size_t i = 0; i < count; ++i)
  1559. m_gids.set(gids[i]);
  1560. return 0;
  1561. }