Process.cpp 64 KB

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