Process.cpp 56 KB

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