Process.cpp 49 KB

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