Process.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007
  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 <WindowServer/WSWindow.h>
  22. #include "MasterPTY.h"
  23. //#define DEBUG_IO
  24. //#define TASK_DEBUG
  25. //#define FORK_DEBUG
  26. #define SIGNAL_DEBUG
  27. #define MAX_PROCESS_GIDS 32
  28. static const dword defaultStackSize = 16384;
  29. static pid_t next_pid;
  30. InlineLinkedList<Process>* g_processes;
  31. static String* s_hostname;
  32. static String& hostnameStorage(InterruptDisabler&)
  33. {
  34. ASSERT(s_hostname);
  35. return *s_hostname;
  36. }
  37. static String getHostname()
  38. {
  39. InterruptDisabler disabler;
  40. return hostnameStorage(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<Process*> Process::allProcesses()
  55. {
  56. InterruptDisabler disabler;
  57. Vector<Process*> processes;
  58. processes.ensureCapacity(g_processes->size_slow());
  59. for (auto* process = g_processes->head(); process; process = process->next())
  60. processes.append(process);
  61. return processes;
  62. }
  63. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  64. {
  65. size = PAGE_ROUND_UP(size);
  66. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  67. if (laddr.is_null()) {
  68. laddr = m_nextRegion;
  69. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  70. }
  71. laddr.mask(0xfffff000);
  72. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  73. if (commit)
  74. m_regions.last()->commit(*this);
  75. MM.map_region(*this, *m_regions.last());
  76. return m_regions.last().ptr();
  77. }
  78. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  79. {
  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(inode), 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->supports_mmap())
  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->inode(), 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->identifier() : 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->inode(), 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->inode();
  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<Inode> 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_inode();
  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<Inode>&& cwd, RetainPtr<Inode>&& 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. int error;
  554. m_fds[0].set(tty->open(error, O_RDONLY));
  555. m_fds[1].set(tty->open(error, O_WRONLY));
  556. m_fds[2].set(tty->open(error, O_WRONLY));
  557. }
  558. }
  559. if (fork_parent)
  560. m_nextRegion = fork_parent->m_nextRegion;
  561. else
  562. m_nextRegion = LinearAddress(0x10000000);
  563. if (fork_parent) {
  564. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  565. } else {
  566. memset(&m_tss, 0, sizeof(m_tss));
  567. // Only IF is set when a process boots.
  568. m_tss.eflags = 0x0202;
  569. word cs, ds, ss;
  570. if (isRing0()) {
  571. cs = 0x08;
  572. ds = 0x10;
  573. ss = 0x10;
  574. } else {
  575. cs = 0x1b;
  576. ds = 0x23;
  577. ss = 0x23;
  578. }
  579. m_tss.ds = ds;
  580. m_tss.es = ds;
  581. m_tss.fs = ds;
  582. m_tss.gs = ds;
  583. m_tss.ss = ss;
  584. m_tss.cs = cs;
  585. }
  586. m_tss.cr3 = page_directory().cr3();
  587. if (isRing0()) {
  588. // FIXME: This memory is leaked.
  589. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  590. dword stackBottom = (dword)kmalloc_eternal(defaultStackSize);
  591. m_stackTop0 = (stackBottom + defaultStackSize) & 0xffffff8;
  592. m_tss.esp = m_stackTop0;
  593. } else {
  594. if (fork_parent) {
  595. m_stackTop3 = fork_parent->m_stackTop3;
  596. } else {
  597. auto* region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  598. ASSERT(region);
  599. m_stackTop3 = region->linearAddress.offset(defaultStackSize).get();
  600. m_tss.esp = m_stackTop3;
  601. }
  602. }
  603. if (isRing3()) {
  604. // Ring3 processes need a separate stack for Ring0.
  605. m_kernelStack = kmalloc(defaultStackSize);
  606. m_stackTop0 = ((dword)m_kernelStack + defaultStackSize) & 0xffffff8;
  607. m_tss.ss0 = 0x10;
  608. m_tss.esp0 = m_stackTop0;
  609. }
  610. // HACK: Ring2 SS in the TSS is the current PID.
  611. m_tss.ss2 = m_pid;
  612. m_farPtr.offset = 0x98765432;
  613. }
  614. Process::~Process()
  615. {
  616. InterruptDisabler disabler;
  617. ProcFS::the().remove_process(*this);
  618. system.nprocess--;
  619. if (selector())
  620. gdt_free_entry(selector());
  621. if (m_kernelStack) {
  622. kfree(m_kernelStack);
  623. m_kernelStack = nullptr;
  624. }
  625. }
  626. void Process::dumpRegions()
  627. {
  628. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  629. kprintf("BEGIN END SIZE NAME\n");
  630. for (auto& region : m_regions) {
  631. kprintf("%x -- %x %x %s\n",
  632. region->linearAddress.get(),
  633. region->linearAddress.offset(region->size - 1).get(),
  634. region->size,
  635. region->name.characters());
  636. }
  637. }
  638. void Process::sys$exit(int status)
  639. {
  640. cli();
  641. #ifdef TASK_DEBUG
  642. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  643. #endif
  644. set_state(Dead);
  645. m_termination_status = status;
  646. m_termination_signal = 0;
  647. Scheduler::pick_next_and_switch_now();
  648. ASSERT_NOT_REACHED();
  649. }
  650. void Process::terminate_due_to_signal(byte signal)
  651. {
  652. ASSERT_INTERRUPTS_DISABLED();
  653. ASSERT(signal < 32);
  654. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  655. m_termination_status = 0;
  656. m_termination_signal = signal;
  657. set_state(Dead);
  658. }
  659. void Process::send_signal(byte signal, Process* sender)
  660. {
  661. ASSERT_INTERRUPTS_DISABLED();
  662. ASSERT(signal < 32);
  663. m_pending_signals |= 1 << signal;
  664. if (sender)
  665. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
  666. else
  667. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
  668. }
  669. bool Process::has_unmasked_pending_signals() const
  670. {
  671. return m_pending_signals & m_signal_mask;
  672. }
  673. bool Process::dispatch_one_pending_signal()
  674. {
  675. ASSERT_INTERRUPTS_DISABLED();
  676. dword signal_candidates = m_pending_signals & m_signal_mask;
  677. ASSERT(signal_candidates);
  678. byte signal = 0;
  679. for (; signal < 32; ++signal) {
  680. if (signal_candidates & (1 << signal)) {
  681. break;
  682. }
  683. }
  684. return dispatch_signal(signal);
  685. }
  686. bool Process::dispatch_signal(byte signal)
  687. {
  688. ASSERT_INTERRUPTS_DISABLED();
  689. ASSERT(signal < 32);
  690. dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  691. auto& action = m_signal_action_data[signal];
  692. // FIXME: Implement SA_SIGINFO signal handlers.
  693. ASSERT(!(action.flags & SA_SIGINFO));
  694. auto handler_laddr = action.handler_or_sigaction;
  695. if (handler_laddr.is_null()) {
  696. // FIXME: Is termination really always the appropriate action?
  697. terminate_due_to_signal(signal);
  698. return true;
  699. }
  700. m_pending_signals &= ~(1 << signal);
  701. if (handler_laddr.asPtr() == SIG_IGN) {
  702. dbgprintf("%s(%u) ignored signal %u\n", name().characters(), pid(), signal); return false;
  703. }
  704. Scheduler::prepare_to_modify_tss(*this);
  705. word ret_cs = m_tss.cs;
  706. dword ret_eip = m_tss.eip;
  707. dword ret_eflags = m_tss.eflags;
  708. bool interrupting_in_kernel = (ret_cs & 3) == 0;
  709. if (interrupting_in_kernel) {
  710. dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), toString(state()), ret_cs, ret_eip);
  711. ASSERT(is_blocked());
  712. m_tss_to_resume_kernel = m_tss;
  713. #ifdef SIGNAL_DEBUG
  714. dbgprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
  715. #endif
  716. }
  717. ProcessPagingScope pagingScope(*this);
  718. if (interrupting_in_kernel) {
  719. if (!m_signal_stack_user_region) {
  720. m_signal_stack_user_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (user)");
  721. ASSERT(m_signal_stack_user_region);
  722. m_signal_stack_kernel_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (kernel)");
  723. ASSERT(m_signal_stack_user_region);
  724. }
  725. m_tss.ss = 0x23;
  726. m_tss.esp = m_signal_stack_user_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  727. m_tss.ss0 = 0x10;
  728. m_tss.esp0 = m_signal_stack_kernel_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  729. push_value_on_stack(ret_eflags);
  730. push_value_on_stack(ret_cs);
  731. push_value_on_stack(ret_eip);
  732. } else {
  733. push_value_on_stack(ret_cs);
  734. push_value_on_stack(ret_eip);
  735. push_value_on_stack(ret_eflags);
  736. }
  737. // PUSHA
  738. dword old_esp = m_tss.esp;
  739. push_value_on_stack(m_tss.eax);
  740. push_value_on_stack(m_tss.ecx);
  741. push_value_on_stack(m_tss.edx);
  742. push_value_on_stack(m_tss.ebx);
  743. push_value_on_stack(old_esp);
  744. push_value_on_stack(m_tss.ebp);
  745. push_value_on_stack(m_tss.esi);
  746. push_value_on_stack(m_tss.edi);
  747. m_tss.eax = (dword)signal;
  748. m_tss.cs = 0x1b;
  749. m_tss.ds = 0x23;
  750. m_tss.es = 0x23;
  751. m_tss.fs = 0x23;
  752. m_tss.gs = 0x23;
  753. m_tss.eip = handler_laddr.get();
  754. if (m_return_to_ring3_from_signal_trampoline.is_null()) {
  755. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  756. // FIXME: Remap as read-only after setup.
  757. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
  758. m_return_to_ring3_from_signal_trampoline = region->linearAddress;
  759. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.asPtr();
  760. *code_ptr++ = 0x61; // popa
  761. *code_ptr++ = 0x9d; // popf
  762. *code_ptr++ = 0xc3; // ret
  763. *code_ptr++ = 0x0f; // ud2
  764. *code_ptr++ = 0x0b;
  765. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  766. *code_ptr++ = 0x61; // popa
  767. *code_ptr++ = 0xb8; // mov eax, <dword>
  768. *(dword*)code_ptr = Syscall::SC_sigreturn;
  769. code_ptr += sizeof(dword);
  770. *code_ptr++ = 0xcd; // int 0x80
  771. *code_ptr++ = 0x80;
  772. *code_ptr++ = 0x0f; // ud2
  773. *code_ptr++ = 0x0b;
  774. // FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
  775. // unmasks the signal so it can be received again? I guess then I would need one trampoline
  776. // per signal number if it's hard-coded, but it's just a few bytes per each.
  777. }
  778. if (interrupting_in_kernel)
  779. push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
  780. else
  781. push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
  782. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  783. set_state(Skip1SchedulerPass);
  784. #ifdef SIGNAL_DEBUG
  785. 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);
  786. #endif
  787. return true;
  788. }
  789. void Process::sys$sigreturn()
  790. {
  791. InterruptDisabler disabler;
  792. Scheduler::prepare_to_modify_tss(*this);
  793. m_tss = m_tss_to_resume_kernel;
  794. #ifdef SIGNAL_DEBUG
  795. dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  796. dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
  797. #endif
  798. set_state(Skip1SchedulerPass);
  799. Scheduler::yield();
  800. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  801. ASSERT_NOT_REACHED();
  802. }
  803. void Process::push_value_on_stack(dword value)
  804. {
  805. m_tss.esp -= 4;
  806. dword* stack_ptr = (dword*)m_tss.esp;
  807. *stack_ptr = value;
  808. }
  809. void Process::crash()
  810. {
  811. ASSERT_INTERRUPTS_DISABLED();
  812. ASSERT(state() != Dead);
  813. m_termination_signal = SIGSEGV;
  814. set_state(Dead);
  815. dumpRegions();
  816. Scheduler::pick_next_and_switch_now();
  817. ASSERT_NOT_REACHED();
  818. }
  819. Process* Process::from_pid(pid_t pid)
  820. {
  821. ASSERT_INTERRUPTS_DISABLED();
  822. for (auto* process = g_processes->head(); process; process = process->next()) {
  823. if (process->pid() == pid)
  824. return process;
  825. }
  826. return nullptr;
  827. }
  828. FileDescriptor* Process::file_descriptor(int fd)
  829. {
  830. if (fd < 0)
  831. return nullptr;
  832. if ((size_t)fd < m_fds.size())
  833. return m_fds[fd].descriptor.ptr();
  834. return nullptr;
  835. }
  836. const FileDescriptor* Process::file_descriptor(int fd) const
  837. {
  838. if (fd < 0)
  839. return nullptr;
  840. if ((size_t)fd < m_fds.size())
  841. return m_fds[fd].descriptor.ptr();
  842. return nullptr;
  843. }
  844. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, size_t size)
  845. {
  846. if (!validate_write(buffer, size))
  847. return -EFAULT;
  848. auto* descriptor = file_descriptor(fd);
  849. if (!descriptor)
  850. return -EBADF;
  851. return descriptor->get_dir_entries((byte*)buffer, size);
  852. }
  853. int Process::sys$lseek(int fd, off_t offset, int whence)
  854. {
  855. auto* descriptor = file_descriptor(fd);
  856. if (!descriptor)
  857. return -EBADF;
  858. return descriptor->seek(offset, whence);
  859. }
  860. int Process::sys$ttyname_r(int fd, char* buffer, size_t size)
  861. {
  862. if (!validate_write(buffer, size))
  863. return -EFAULT;
  864. auto* descriptor = file_descriptor(fd);
  865. if (!descriptor)
  866. return -EBADF;
  867. if (!descriptor->is_tty())
  868. return -ENOTTY;
  869. auto ttyName = descriptor->tty()->tty_name();
  870. if (size < ttyName.length() + 1)
  871. return -ERANGE;
  872. strcpy(buffer, ttyName.characters());
  873. return 0;
  874. }
  875. int Process::sys$ptsname_r(int fd, char* buffer, size_t size)
  876. {
  877. if (!validate_write(buffer, size))
  878. return -EFAULT;
  879. auto* descriptor = file_descriptor(fd);
  880. if (!descriptor)
  881. return -EBADF;
  882. auto* master_pty = descriptor->master_pty();
  883. if (!master_pty)
  884. return -ENOTTY;
  885. auto pts_name = master_pty->pts_name();
  886. if (size < pts_name.length() + 1)
  887. return -ERANGE;
  888. strcpy(buffer, pts_name.characters());
  889. return 0;
  890. }
  891. ssize_t Process::sys$write(int fd, const void* data, size_t size)
  892. {
  893. if (!validate_read(data, size))
  894. return -EFAULT;
  895. #ifdef DEBUG_IO
  896. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  897. #endif
  898. auto* descriptor = file_descriptor(fd);
  899. if (!descriptor)
  900. return -EBADF;
  901. ssize_t nwritten = 0;
  902. if (descriptor->is_blocking()) {
  903. while (nwritten < (ssize_t)size) {
  904. #ifdef IO_DEBUG
  905. dbgprintf("while %u < %u\n", nwritten, size);
  906. #endif
  907. if (!descriptor->can_write(*this)) {
  908. #ifdef IO_DEBUG
  909. dbgprintf("block write on %d\n", fd);
  910. #endif
  911. m_blocked_fd = fd;
  912. block(BlockedWrite);
  913. Scheduler::yield();
  914. }
  915. ssize_t rc = descriptor->write(*this, (const byte*)data + nwritten, size - nwritten);
  916. #ifdef IO_DEBUG
  917. dbgprintf(" -> write returned %d\n", rc);
  918. #endif
  919. if (rc < 0) {
  920. // FIXME: Support returning partial nwritten with errno.
  921. ASSERT(nwritten == 0);
  922. return rc;
  923. }
  924. if (rc == 0)
  925. break;
  926. if (has_unmasked_pending_signals()) {
  927. block(BlockedSignal);
  928. Scheduler::yield();
  929. if (nwritten == 0)
  930. return -EINTR;
  931. }
  932. nwritten += rc;
  933. }
  934. } else {
  935. nwritten = descriptor->write(*this, (const byte*)data, size);
  936. }
  937. if (has_unmasked_pending_signals()) {
  938. block(BlockedSignal);
  939. Scheduler::yield();
  940. if (nwritten == 0)
  941. return -EINTR;
  942. }
  943. #ifdef DEBUG_IO
  944. dbgprintf("%s(%u) sys$write: nwritten=%u\n", name().characters(), pid(), nwritten);
  945. #endif
  946. return nwritten;
  947. }
  948. ssize_t Process::sys$read(int fd, void* outbuf, size_t nread)
  949. {
  950. if (!validate_write(outbuf, nread))
  951. return -EFAULT;
  952. #ifdef DEBUG_IO
  953. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, outbuf, nread);
  954. #endif
  955. auto* descriptor = file_descriptor(fd);
  956. if (!descriptor)
  957. return -EBADF;
  958. #ifdef DEBUG_IO
  959. dbgprintf(" > descriptor:%p, is_blocking:%u, can_read:%u\n", descriptor, descriptor->is_blocking(), descriptor->can_read(*this));
  960. dbgprintf(" > inode:K%x, device:K%x\n", descriptor->inode(), descriptor->character_device());
  961. #endif
  962. if (descriptor->is_blocking()) {
  963. if (!descriptor->can_read(*this)) {
  964. m_blocked_fd = fd;
  965. block(BlockedRead);
  966. sched_yield();
  967. if (m_was_interrupted_while_blocked)
  968. return -EINTR;
  969. }
  970. }
  971. nread = descriptor->read(*this, (byte*)outbuf, nread);
  972. #ifdef DEBUG_IO
  973. dbgprintf("%s(%u) Process::sys$read: nread=%u\n", name().characters(), pid(), nread);
  974. #endif
  975. return nread;
  976. }
  977. int Process::sys$close(int fd)
  978. {
  979. auto* descriptor = file_descriptor(fd);
  980. if (!descriptor)
  981. return -EBADF;
  982. int rc = descriptor->close();
  983. m_fds[fd] = { };
  984. return rc;
  985. }
  986. int Process::sys$utime(const char* pathname, const Unix::utimbuf* buf)
  987. {
  988. if (!validate_read_str(pathname))
  989. return -EFAULT;
  990. if (buf && !validate_read_typed(buf))
  991. return -EFAULT;
  992. String path(pathname);
  993. int error;
  994. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  995. if (!descriptor)
  996. return error;
  997. auto& inode = *descriptor->inode();
  998. if (inode.fs().is_readonly())
  999. return -EROFS;
  1000. Unix::time_t atime;
  1001. Unix::time_t mtime;
  1002. if (buf) {
  1003. atime = buf->actime;
  1004. mtime = buf->modtime;
  1005. } else {
  1006. auto now = RTC::now();
  1007. mtime = now;
  1008. atime = now;
  1009. }
  1010. inode.set_atime(atime);
  1011. inode.set_mtime(mtime);
  1012. return 0;
  1013. }
  1014. int Process::sys$access(const char* pathname, int mode)
  1015. {
  1016. (void) mode;
  1017. if (!validate_read_str(pathname))
  1018. return -EFAULT;
  1019. ASSERT_NOT_REACHED();
  1020. }
  1021. int Process::sys$fcntl(int fd, int cmd, dword arg)
  1022. {
  1023. (void) cmd;
  1024. (void) arg;
  1025. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1026. auto* descriptor = file_descriptor(fd);
  1027. if (!descriptor)
  1028. return -EBADF;
  1029. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1030. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1031. switch (cmd) {
  1032. case F_DUPFD: {
  1033. int arg_fd = (int)arg;
  1034. if (arg_fd < 0)
  1035. return -EINVAL;
  1036. int new_fd = -1;
  1037. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1038. if (!m_fds[i]) {
  1039. new_fd = i;
  1040. break;
  1041. }
  1042. }
  1043. if (new_fd == -1)
  1044. return -EMFILE;
  1045. m_fds[new_fd].set(descriptor);
  1046. break;
  1047. }
  1048. case F_GETFD:
  1049. return m_fds[fd].flags;
  1050. case F_SETFD:
  1051. m_fds[fd].flags = arg;
  1052. break;
  1053. case F_GETFL:
  1054. return descriptor->file_flags();
  1055. case F_SETFL:
  1056. // FIXME: Support changing O_NONBLOCK
  1057. descriptor->set_file_flags(arg);
  1058. break;
  1059. default:
  1060. ASSERT_NOT_REACHED();
  1061. }
  1062. return 0;
  1063. }
  1064. int Process::sys$fstat(int fd, Unix::stat* statbuf)
  1065. {
  1066. if (!validate_write_typed(statbuf))
  1067. return -EFAULT;
  1068. auto* descriptor = file_descriptor(fd);
  1069. if (!descriptor)
  1070. return -EBADF;
  1071. descriptor->stat(statbuf);
  1072. return 0;
  1073. }
  1074. int Process::sys$lstat(const char* path, Unix::stat* statbuf)
  1075. {
  1076. if (!validate_write_typed(statbuf))
  1077. return -EFAULT;
  1078. int error;
  1079. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1080. if (!descriptor)
  1081. return error;
  1082. descriptor->stat(statbuf);
  1083. return 0;
  1084. }
  1085. int Process::sys$stat(const char* path, Unix::stat* statbuf)
  1086. {
  1087. if (!validate_write_typed(statbuf))
  1088. return -EFAULT;
  1089. int error;
  1090. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  1091. if (!descriptor)
  1092. return error;
  1093. descriptor->stat(statbuf);
  1094. return 0;
  1095. }
  1096. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1097. {
  1098. if (!validate_read_str(path))
  1099. return -EFAULT;
  1100. if (!validate_write(buffer, size))
  1101. return -EFAULT;
  1102. int error;
  1103. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1104. if (!descriptor)
  1105. return error;
  1106. if (!descriptor->metadata().isSymbolicLink())
  1107. return -EINVAL;
  1108. auto contents = descriptor->read_entire_file(*this);
  1109. if (!contents)
  1110. return -EIO; // FIXME: Get a more detailed error from VFS.
  1111. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1112. if (contents.size() + 1 < size)
  1113. buffer[contents.size()] = '\0';
  1114. return 0;
  1115. }
  1116. int Process::sys$chdir(const char* path)
  1117. {
  1118. if (!validate_read_str(path))
  1119. return -EFAULT;
  1120. int error;
  1121. auto descriptor = VFS::the().open(path, error, 0, cwd_inode()->identifier());
  1122. if (!descriptor)
  1123. return error;
  1124. if (!descriptor->is_directory())
  1125. return -ENOTDIR;
  1126. m_cwd = descriptor->inode();
  1127. return 0;
  1128. }
  1129. int Process::sys$getcwd(char* buffer, size_t size)
  1130. {
  1131. if (!validate_write(buffer, size))
  1132. return -EFAULT;
  1133. ASSERT(cwd_inode());
  1134. auto path = VFS::the().absolute_path(*cwd_inode());
  1135. if (path.is_null())
  1136. return -EINVAL;
  1137. if (size < path.length() + 1)
  1138. return -ERANGE;
  1139. strcpy(buffer, path.characters());
  1140. return 0;
  1141. }
  1142. size_t Process::number_of_open_file_descriptors() const
  1143. {
  1144. size_t count = 0;
  1145. for (auto& descriptor : m_fds) {
  1146. if (descriptor)
  1147. ++count;
  1148. }
  1149. return count;
  1150. }
  1151. int Process::sys$open(const char* path, int options)
  1152. {
  1153. #ifdef DEBUG_IO
  1154. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1155. #endif
  1156. if (!validate_read_str(path))
  1157. return -EFAULT;
  1158. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1159. return -EMFILE;
  1160. int error = -EWHYTHO;
  1161. ASSERT(cwd_inode());
  1162. auto descriptor = VFS::the().open(path, error, options, cwd_inode()->identifier());
  1163. if (!descriptor)
  1164. return error;
  1165. if (options & O_DIRECTORY && !descriptor->is_directory())
  1166. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1167. if (options & O_NONBLOCK)
  1168. descriptor->set_blocking(false);
  1169. int fd = 0;
  1170. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1171. if (!m_fds[fd])
  1172. break;
  1173. }
  1174. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1175. m_fds[fd].set(move(descriptor), flags);
  1176. return fd;
  1177. }
  1178. int Process::alloc_fd()
  1179. {
  1180. int fd = -1;
  1181. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1182. if (!m_fds[i]) {
  1183. fd = i;
  1184. break;
  1185. }
  1186. }
  1187. return fd;
  1188. }
  1189. int Process::sys$pipe(int pipefd[2])
  1190. {
  1191. if (!validate_write_typed(pipefd))
  1192. return -EFAULT;
  1193. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1194. return -EMFILE;
  1195. auto fifo = FIFO::create();
  1196. int reader_fd = alloc_fd();
  1197. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1198. pipefd[0] = reader_fd;
  1199. int writer_fd = alloc_fd();
  1200. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1201. pipefd[1] = writer_fd;
  1202. return 0;
  1203. }
  1204. int Process::sys$killpg(int pgrp, int signum)
  1205. {
  1206. if (signum < 1 || signum >= 32)
  1207. return -EINVAL;
  1208. (void) pgrp;
  1209. ASSERT_NOT_REACHED();
  1210. }
  1211. int Process::sys$setuid(uid_t)
  1212. {
  1213. ASSERT_NOT_REACHED();
  1214. }
  1215. int Process::sys$setgid(gid_t)
  1216. {
  1217. ASSERT_NOT_REACHED();
  1218. }
  1219. unsigned Process::sys$alarm(unsigned seconds)
  1220. {
  1221. (void) seconds;
  1222. ASSERT_NOT_REACHED();
  1223. }
  1224. int Process::sys$uname(utsname* buf)
  1225. {
  1226. if (!validate_write_typed(buf))
  1227. return -EFAULT;
  1228. strcpy(buf->sysname, "Serenity");
  1229. strcpy(buf->release, "1.0-dev");
  1230. strcpy(buf->version, "FIXME");
  1231. strcpy(buf->machine, "i386");
  1232. strcpy(buf->nodename, getHostname().characters());
  1233. return 0;
  1234. }
  1235. int Process::sys$isatty(int fd)
  1236. {
  1237. auto* descriptor = file_descriptor(fd);
  1238. if (!descriptor)
  1239. return -EBADF;
  1240. if (!descriptor->is_tty())
  1241. return -ENOTTY;
  1242. return 1;
  1243. }
  1244. int Process::sys$kill(pid_t pid, int signal)
  1245. {
  1246. if (pid == 0) {
  1247. // FIXME: Send to same-group processes.
  1248. ASSERT(pid != 0);
  1249. }
  1250. if (pid == -1) {
  1251. // FIXME: Send to all processes.
  1252. ASSERT(pid != -1);
  1253. }
  1254. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1255. InterruptDisabler disabler;
  1256. auto* peer = Process::from_pid(pid);
  1257. if (!peer)
  1258. return -ESRCH;
  1259. peer->send_signal(signal, this);
  1260. return 0;
  1261. }
  1262. int Process::sys$sleep(unsigned seconds)
  1263. {
  1264. if (!seconds)
  1265. return 0;
  1266. sleep(seconds * TICKS_PER_SECOND);
  1267. if (m_wakeupTime > system.uptime) {
  1268. ASSERT(m_was_interrupted_while_blocked);
  1269. dword ticks_left_until_original_wakeup_time = m_wakeupTime - system.uptime;
  1270. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1271. }
  1272. return 0;
  1273. }
  1274. int Process::sys$gettimeofday(timeval* tv)
  1275. {
  1276. if (!validate_write_typed(tv))
  1277. return -EFAULT;
  1278. InterruptDisabler disabler;
  1279. auto now = RTC::now();
  1280. tv->tv_sec = now;
  1281. tv->tv_usec = 0;
  1282. return 0;
  1283. }
  1284. uid_t Process::sys$getuid()
  1285. {
  1286. return m_uid;
  1287. }
  1288. gid_t Process::sys$getgid()
  1289. {
  1290. return m_gid;
  1291. }
  1292. uid_t Process::sys$geteuid()
  1293. {
  1294. return m_euid;
  1295. }
  1296. gid_t Process::sys$getegid()
  1297. {
  1298. return m_egid;
  1299. }
  1300. pid_t Process::sys$getpid()
  1301. {
  1302. return m_pid;
  1303. }
  1304. pid_t Process::sys$getppid()
  1305. {
  1306. return m_ppid;
  1307. }
  1308. mode_t Process::sys$umask(mode_t mask)
  1309. {
  1310. auto old_mask = m_umask;
  1311. m_umask = mask;
  1312. return old_mask;
  1313. }
  1314. int Process::reap(Process& process)
  1315. {
  1316. InterruptDisabler disabler;
  1317. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1318. if (process.ppid()) {
  1319. auto* parent = Process::from_pid(process.ppid());
  1320. ASSERT(parent);
  1321. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1322. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1323. }
  1324. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), toString(process.state()));
  1325. ASSERT(process.state() == Dead);
  1326. g_processes->remove(&process);
  1327. delete &process;
  1328. return exit_status;
  1329. }
  1330. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1331. {
  1332. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1333. // FIXME: Respect options
  1334. (void) options;
  1335. if (wstatus)
  1336. if (!validate_write_typed(wstatus))
  1337. return -EFAULT;
  1338. int dummy_wstatus;
  1339. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1340. {
  1341. InterruptDisabler disabler;
  1342. if (waitee != -1 && !Process::from_pid(waitee))
  1343. return -ECHILD;
  1344. }
  1345. if (options & WNOHANG) {
  1346. if (waitee == -1) {
  1347. pid_t reaped_pid = 0;
  1348. InterruptDisabler disabler;
  1349. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1350. if (process.state() == Dead) {
  1351. reaped_pid = process.pid();
  1352. exit_status = reap(process);
  1353. }
  1354. return true;
  1355. });
  1356. return reaped_pid;
  1357. } else {
  1358. auto* waitee_process = Process::from_pid(waitee);
  1359. if (!waitee_process)
  1360. return -ECHILD;
  1361. if (waitee_process->state() == Dead) {
  1362. exit_status = reap(*waitee_process);
  1363. return waitee;
  1364. }
  1365. return 0;
  1366. }
  1367. }
  1368. m_waitee_pid = waitee;
  1369. block(BlockedWait);
  1370. sched_yield();
  1371. if (m_was_interrupted_while_blocked)
  1372. return -EINTR;
  1373. Process* waitee_process;
  1374. {
  1375. InterruptDisabler disabler;
  1376. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1377. waitee_process = Process::from_pid(m_waitee_pid);
  1378. }
  1379. ASSERT(waitee_process);
  1380. exit_status = reap(*waitee_process);
  1381. return m_waitee_pid;
  1382. }
  1383. void Process::unblock()
  1384. {
  1385. if (current == this) {
  1386. kprintf("ignoring unblock() on current, %s(%u) {%s}\n", name().characters(), pid(), toString(state()));
  1387. return;
  1388. }
  1389. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1390. system.nblocked--;
  1391. m_state = Process::Runnable;
  1392. }
  1393. void Process::block(Process::State new_state)
  1394. {
  1395. if (state() != Process::Running) {
  1396. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, toString(new_state), state(), toString(state()));
  1397. }
  1398. ASSERT(state() == Process::Running);
  1399. system.nblocked++;
  1400. m_was_interrupted_while_blocked = false;
  1401. set_state(new_state);
  1402. }
  1403. void block(Process::State state)
  1404. {
  1405. current->block(state);
  1406. sched_yield();
  1407. }
  1408. void sleep(dword ticks)
  1409. {
  1410. ASSERT(current->state() == Process::Running);
  1411. current->setWakeupTime(system.uptime + ticks);
  1412. current->block(Process::BlockedSleep);
  1413. sched_yield();
  1414. }
  1415. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1416. {
  1417. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1418. // This code allows access outside of the known used address ranges to get caught.
  1419. InterruptDisabler disabler;
  1420. // FIXME: What if we're indexing into the ksym with the highest address though?
  1421. if (laddr.get() >= ksym_lowest_address && laddr.get() <= ksym_highest_address)
  1422. return true;
  1423. if (is_kmalloc_address(laddr.asPtr()))
  1424. return true;
  1425. return validate_read(laddr.asPtr(), 1);
  1426. }
  1427. bool Process::validate_read(const void* address, size_t size) const
  1428. {
  1429. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1430. if (!MM.validate_user_read(*this, LinearAddress((dword)address).offset(size)))
  1431. return false;
  1432. }
  1433. return MM.validate_user_read(*this, LinearAddress((dword)address));
  1434. }
  1435. bool Process::validate_write(void* address, size_t size) const
  1436. {
  1437. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1438. if (!MM.validate_user_write(*this, LinearAddress((dword)address).offset(size)))
  1439. return false;
  1440. }
  1441. return MM.validate_user_write(*this, LinearAddress((dword)address));
  1442. }
  1443. pid_t Process::sys$getsid(pid_t pid)
  1444. {
  1445. if (pid == 0)
  1446. return m_sid;
  1447. InterruptDisabler disabler;
  1448. auto* process = Process::from_pid(pid);
  1449. if (!process)
  1450. return -ESRCH;
  1451. if (m_sid != process->m_sid)
  1452. return -EPERM;
  1453. return process->m_sid;
  1454. }
  1455. pid_t Process::sys$setsid()
  1456. {
  1457. InterruptDisabler disabler;
  1458. bool found_process_with_same_pgid_as_my_pid = false;
  1459. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1460. found_process_with_same_pgid_as_my_pid = true;
  1461. return false;
  1462. });
  1463. if (found_process_with_same_pgid_as_my_pid)
  1464. return -EPERM;
  1465. m_sid = m_pid;
  1466. m_pgid = m_pid;
  1467. return m_sid;
  1468. }
  1469. pid_t Process::sys$getpgid(pid_t pid)
  1470. {
  1471. if (pid == 0)
  1472. return m_pgid;
  1473. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1474. auto* process = Process::from_pid(pid);
  1475. if (!process)
  1476. return -ESRCH;
  1477. return process->m_pgid;
  1478. }
  1479. pid_t Process::sys$getpgrp()
  1480. {
  1481. return m_pgid;
  1482. }
  1483. static pid_t get_sid_from_pgid(pid_t pgid)
  1484. {
  1485. InterruptDisabler disabler;
  1486. auto* group_leader = Process::from_pid(pgid);
  1487. if (!group_leader)
  1488. return -1;
  1489. return group_leader->sid();
  1490. }
  1491. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1492. {
  1493. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1494. pid_t pid = specified_pid ? specified_pid : m_pid;
  1495. if (specified_pgid < 0)
  1496. return -EINVAL;
  1497. auto* process = Process::from_pid(pid);
  1498. if (!process)
  1499. return -ESRCH;
  1500. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1501. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1502. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1503. if (current_sid != new_sid) {
  1504. // Can't move a process between sessions.
  1505. return -EPERM;
  1506. }
  1507. // FIXME: There are more EPERM conditions to check for here..
  1508. process->m_pgid = new_pgid;
  1509. return 0;
  1510. }
  1511. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1512. {
  1513. auto* descriptor = file_descriptor(fd);
  1514. if (!descriptor)
  1515. return -EBADF;
  1516. if (!descriptor->is_character_device())
  1517. return -ENOTTY;
  1518. return descriptor->character_device()->ioctl(*this, request, arg);
  1519. }
  1520. int Process::sys$getdtablesize()
  1521. {
  1522. return m_max_open_file_descriptors;
  1523. }
  1524. int Process::sys$dup(int old_fd)
  1525. {
  1526. auto* descriptor = file_descriptor(old_fd);
  1527. if (!descriptor)
  1528. return -EBADF;
  1529. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1530. return -EMFILE;
  1531. int new_fd = 0;
  1532. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1533. if (!m_fds[new_fd])
  1534. break;
  1535. }
  1536. m_fds[new_fd].set(descriptor);
  1537. return new_fd;
  1538. }
  1539. int Process::sys$dup2(int old_fd, int new_fd)
  1540. {
  1541. auto* descriptor = file_descriptor(old_fd);
  1542. if (!descriptor)
  1543. return -EBADF;
  1544. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1545. return -EMFILE;
  1546. m_fds[new_fd].set(descriptor);
  1547. return new_fd;
  1548. }
  1549. int Process::sys$sigprocmask(int how, const Unix::sigset_t* set, Unix::sigset_t* old_set)
  1550. {
  1551. if (old_set) {
  1552. if (!validate_read_typed(old_set))
  1553. return -EFAULT;
  1554. *old_set = m_signal_mask;
  1555. }
  1556. if (set) {
  1557. if (!validate_read_typed(set))
  1558. return -EFAULT;
  1559. switch (how) {
  1560. case SIG_BLOCK:
  1561. m_signal_mask &= ~(*set);
  1562. break;
  1563. case SIG_UNBLOCK:
  1564. m_signal_mask |= *set;
  1565. break;
  1566. case SIG_SETMASK:
  1567. m_signal_mask = *set;
  1568. break;
  1569. default:
  1570. return -EINVAL;
  1571. }
  1572. }
  1573. return 0;
  1574. }
  1575. int Process::sys$sigpending(Unix::sigset_t* set)
  1576. {
  1577. if (!validate_read_typed(set))
  1578. return -EFAULT;
  1579. *set = m_pending_signals;
  1580. return 0;
  1581. }
  1582. int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
  1583. {
  1584. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1585. return -EINVAL;
  1586. if (!validate_read_typed(act))
  1587. return -EFAULT;
  1588. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1589. auto& action = m_signal_action_data[signum];
  1590. if (old_act) {
  1591. if (!validate_write_typed(old_act))
  1592. return -EFAULT;
  1593. old_act->sa_flags = action.flags;
  1594. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1595. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1596. }
  1597. action.restorer = LinearAddress((dword)act->sa_restorer);
  1598. action.flags = act->sa_flags;
  1599. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1600. return 0;
  1601. }
  1602. int Process::sys$getgroups(int count, gid_t* gids)
  1603. {
  1604. if (count < 0)
  1605. return -EINVAL;
  1606. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1607. if (!count)
  1608. return m_gids.size();
  1609. if (count != (int)m_gids.size())
  1610. return -EINVAL;
  1611. if (!validate_write_typed(gids, m_gids.size()))
  1612. return -EFAULT;
  1613. size_t i = 0;
  1614. for (auto gid : m_gids)
  1615. gids[i++] = gid;
  1616. return 0;
  1617. }
  1618. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1619. {
  1620. if (!is_root())
  1621. return -EPERM;
  1622. if (count >= MAX_PROCESS_GIDS)
  1623. return -EINVAL;
  1624. if (!validate_read(gids, count))
  1625. return -EFAULT;
  1626. m_gids.clear();
  1627. m_gids.set(m_gid);
  1628. for (size_t i = 0; i < count; ++i)
  1629. m_gids.set(gids[i]);
  1630. return 0;
  1631. }
  1632. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1633. {
  1634. if (!validate_read_str(pathname))
  1635. return -EFAULT;
  1636. if (strlen(pathname) >= 255)
  1637. return -ENAMETOOLONG;
  1638. int error;
  1639. if (!VFS::the().mkdir(pathname, mode, cwd_inode()->identifier(), error))
  1640. return error;
  1641. return 0;
  1642. }
  1643. Unix::clock_t Process::sys$times(Unix::tms* times)
  1644. {
  1645. if (!validate_write_typed(times))
  1646. return -EFAULT;
  1647. times->tms_utime = m_ticks_in_user;
  1648. times->tms_stime = m_ticks_in_kernel;
  1649. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1650. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1651. return 0;
  1652. }
  1653. struct vbe_info_structure {
  1654. char signature[4]; // must be "VESA" to indicate valid VBE support
  1655. word version; // VBE version; high byte is major version, low byte is minor version
  1656. dword oem; // segment:offset pointer to OEM
  1657. dword capabilities; // bitfield that describes card capabilities
  1658. dword video_modes; // segment:offset pointer to list of supported video modes
  1659. word video_memory; // amount of video memory in 64KB blocks
  1660. word software_rev; // software revision
  1661. dword vendor; // segment:offset to card vendor string
  1662. dword product_name; // segment:offset to card model name
  1663. dword product_rev; // segment:offset pointer to product revision
  1664. char reserved[222]; // reserved for future expansion
  1665. char oem_data[256]; // OEM BIOSes store their strings in this area
  1666. } __attribute__ ((packed));
  1667. struct vbe_mode_info_structure {
  1668. word attributes; // deprecated, only bit 7 should be of interest to you, and it indicates the mode supports a linear frame buffer.
  1669. byte window_a; // deprecated
  1670. byte window_b; // deprecated
  1671. word granularity; // deprecated; used while calculating bank numbers
  1672. word window_size;
  1673. word segment_a;
  1674. word segment_b;
  1675. dword win_func_ptr; // deprecated; used to switch banks from protected mode without returning to real mode
  1676. word pitch; // number of bytes per horizontal line
  1677. word width; // width in pixels
  1678. word height; // height in pixels
  1679. byte w_char; // unused...
  1680. byte y_char; // ...
  1681. byte planes;
  1682. byte bpp; // bits per pixel in this mode
  1683. byte banks; // deprecated; total number of banks in this mode
  1684. byte memory_model;
  1685. byte bank_size; // deprecated; size of a bank, almost always 64 KB but may be 16 KB...
  1686. byte image_pages;
  1687. byte reserved0;
  1688. byte red_mask;
  1689. byte red_position;
  1690. byte green_mask;
  1691. byte green_position;
  1692. byte blue_mask;
  1693. byte blue_position;
  1694. byte reserved_mask;
  1695. byte reserved_position;
  1696. byte direct_color_attributes;
  1697. dword framebuffer; // physical address of the linear frame buffer; write here to draw to the screen
  1698. dword off_screen_mem_off;
  1699. word off_screen_mem_size; // size of memory in the framebuffer but not being displayed on the screen
  1700. byte reserved1[206];
  1701. } __attribute__ ((packed));
  1702. DisplayInfo Process::get_display_info()
  1703. {
  1704. DisplayInfo info;
  1705. //auto* vinfo = reinterpret_cast<vbe_info_structure*>(0xc000);
  1706. auto* vmode = reinterpret_cast<vbe_mode_info_structure*>(0x2000);
  1707. dbgprintf("VESA framebuffer, %ux%u, %u bpp @ P%x\n", vmode->width, vmode->height, vmode->bpp, vmode->framebuffer);
  1708. dbgprintf("Returning display info in %s<%u>\n", name().characters(), pid());
  1709. info.width = vmode->width;
  1710. info.height = vmode->height;
  1711. info.bpp = vmode->bpp;
  1712. info.pitch = vmode->pitch;
  1713. size_t framebuffer_size = info.pitch * info.height;
  1714. if (!m_display_framebuffer_region) {
  1715. auto framebuffer_vmo = VMObject::create_framebuffer_wrapper(PhysicalAddress(vmode->framebuffer), framebuffer_size);
  1716. m_display_framebuffer_region = allocate_region_with_vmo(LinearAddress(0xe0000000), framebuffer_size, move(framebuffer_vmo), 0, "framebuffer", true, true);
  1717. }
  1718. info.framebuffer = m_display_framebuffer_region->linearAddress.asPtr();
  1719. return info;
  1720. }
  1721. int Process::sys$select(const Syscall::SC_select_params* params)
  1722. {
  1723. if (!validate_read_typed(params))
  1724. return -EFAULT;
  1725. if (params->writefds && !validate_read_typed(params->writefds))
  1726. return -EFAULT;
  1727. if (params->readfds && !validate_read_typed(params->readfds))
  1728. return -EFAULT;
  1729. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1730. return -EFAULT;
  1731. if (params->timeout && !validate_read_typed(params->timeout))
  1732. return -EFAULT;
  1733. int nfds = params->nfds;
  1734. fd_set* writefds = params->writefds;
  1735. fd_set* readfds = params->readfds;
  1736. fd_set* exceptfds = params->exceptfds;
  1737. auto* timeout = params->timeout;
  1738. // FIXME: Implement exceptfds support.
  1739. ASSERT(!exceptfds);
  1740. // FIXME: Implement timeout support.
  1741. ASSERT(!timeout);
  1742. if (nfds < 0)
  1743. return -EINVAL;
  1744. // FIXME: Return -EBADF if one of the fd sets contains an invalid fd.
  1745. // FIXME: Return -EINTR if a signal is caught.
  1746. // FIXME: Return -EINVAL if timeout is invalid.
  1747. auto transfer_fds = [nfds] (fd_set* set, auto& vector) {
  1748. if (!set)
  1749. return;
  1750. vector.clear_with_capacity();
  1751. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1752. for (int i = 0; i < nfds; ++i) {
  1753. if (bitmap.get(i))
  1754. vector.append(i);
  1755. }
  1756. };
  1757. transfer_fds(writefds, m_select_write_fds);
  1758. transfer_fds(readfds, m_select_read_fds);
  1759. #ifdef DEBUG_IO
  1760. dbgprintf("%s<%u> selecting on (read:%u, write:%u)\n", name().characters(), pid(), m_select_read_fds.size(), m_select_write_fds.size());
  1761. #endif
  1762. if (!m_wakeup_requested) {
  1763. block(BlockedSelect);
  1764. Scheduler::yield();
  1765. }
  1766. m_wakeup_requested = false;
  1767. int markedfds = 0;
  1768. if (readfds) {
  1769. memset(readfds, 0, sizeof(fd_set));
  1770. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1771. for (int fd : m_select_read_fds) {
  1772. if (m_fds[fd].descriptor->can_read(*this)) {
  1773. bitmap.set(fd, true);
  1774. ++markedfds;
  1775. }
  1776. }
  1777. }
  1778. if (writefds) {
  1779. memset(writefds, 0, sizeof(fd_set));
  1780. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1781. for (int fd : m_select_write_fds) {
  1782. if (m_fds[fd].descriptor->can_write(*this)) {
  1783. bitmap.set(fd, true);
  1784. ++markedfds;
  1785. }
  1786. }
  1787. }
  1788. return markedfds;
  1789. }
  1790. Inode* Process::cwd_inode()
  1791. {
  1792. // FIXME: This is retarded factoring.
  1793. if (!m_cwd)
  1794. m_cwd = VFS::the().root_inode();
  1795. return m_cwd.ptr();
  1796. }