Process.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986
  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. #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<Vnode>&& vnode, String&& name, bool is_readable, bool is_writable)
  79. {
  80. ASSERT(!vnode->isCharacterDevice());
  81. size = PAGE_ROUND_UP(size);
  82. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  83. if (laddr.is_null()) {
  84. laddr = m_nextRegion;
  85. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  86. }
  87. laddr.mask(0xfffff000);
  88. m_regions.append(adopt(*new Region(laddr, size, move(vnode), move(name), is_readable, is_writable)));
  89. MM.map_region(*this, *m_regions.last());
  90. return m_regions.last().ptr();
  91. }
  92. 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)
  93. {
  94. ASSERT(vmo);
  95. size = PAGE_ROUND_UP(size);
  96. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  97. if (laddr.is_null()) {
  98. laddr = m_nextRegion;
  99. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  100. }
  101. laddr.mask(0xfffff000);
  102. offset_in_vmo &= PAGE_MASK;
  103. size = ceilDiv(size, PAGE_SIZE) * PAGE_SIZE;
  104. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  105. MM.map_region(*this, *m_regions.last());
  106. return m_regions.last().ptr();
  107. }
  108. bool Process::deallocate_region(Region& region)
  109. {
  110. InterruptDisabler disabler;
  111. for (size_t i = 0; i < m_regions.size(); ++i) {
  112. if (m_regions[i].ptr() == &region) {
  113. MM.unmap_region(*this, region);
  114. m_regions.remove(i);
  115. return true;
  116. }
  117. }
  118. return false;
  119. }
  120. Region* Process::regionFromRange(LinearAddress laddr, size_t size)
  121. {
  122. for (auto& region : m_regions) {
  123. if (region->linearAddress == laddr && region->size == size)
  124. return region.ptr();
  125. }
  126. return nullptr;
  127. }
  128. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  129. {
  130. if (!validate_read_str(name))
  131. return -EFAULT;
  132. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  133. if (!region)
  134. return -EINVAL;
  135. region->name = name;
  136. return 0;
  137. }
  138. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  139. {
  140. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  141. return (void*)-EFAULT;
  142. void* addr = (void*)params->addr;
  143. size_t size = params->size;
  144. int prot = params->prot;
  145. int flags = params->flags;
  146. int fd = params->fd;
  147. Unix::off_t offset = params->offset;
  148. if (size == 0)
  149. return (void*)-EINVAL;
  150. if ((dword)addr & ~PAGE_MASK || size & ~PAGE_MASK)
  151. return (void*)-EINVAL;
  152. if (flags & MAP_ANONYMOUS) {
  153. InterruptDisabler disabler;
  154. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  155. ASSERT(addr == nullptr);
  156. auto* region = allocate_region(LinearAddress(), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  157. if (!region)
  158. return (void*)-ENOMEM;
  159. return region->linearAddress.asPtr();
  160. }
  161. if (offset & ~PAGE_MASK)
  162. return (void*)-EINVAL;
  163. auto* descriptor = file_descriptor(fd);
  164. if (!descriptor)
  165. return (void*)-EBADF;
  166. if (descriptor->vnode()->isCharacterDevice())
  167. return (void*)-ENODEV;
  168. // FIXME: If PROT_EXEC, check that the underlying file system isn't mounted noexec.
  169. auto region_name = descriptor->absolute_path();
  170. InterruptDisabler disabler;
  171. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  172. ASSERT(addr == nullptr);
  173. auto* region = allocate_file_backed_region(LinearAddress(), size, descriptor->vnode(), move(region_name), prot & PROT_READ, prot & PROT_WRITE);
  174. if (!region)
  175. return (void*)-ENOMEM;
  176. return region->linearAddress.asPtr();
  177. }
  178. int Process::sys$munmap(void* addr, size_t size)
  179. {
  180. InterruptDisabler disabler;
  181. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  182. if (!region)
  183. return -1;
  184. if (!deallocate_region(*region))
  185. return -1;
  186. return 0;
  187. }
  188. int Process::sys$gethostname(char* buffer, size_t size)
  189. {
  190. if (!validate_write(buffer, size))
  191. return -EFAULT;
  192. auto hostname = getHostname();
  193. if (size < (hostname.length() + 1))
  194. return -ENAMETOOLONG;
  195. memcpy(buffer, hostname.characters(), size);
  196. return 0;
  197. }
  198. Process* Process::fork(RegisterDump& regs)
  199. {
  200. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copyRef(), m_executable.copyRef(), m_tty, this);
  201. if (!child)
  202. return nullptr;
  203. memcpy(child->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  204. child->m_signal_mask = m_signal_mask;
  205. #ifdef FORK_DEBUG
  206. dbgprintf("fork: child=%p\n", child);
  207. #endif
  208. #if 0
  209. // FIXME: An honest fork() would copy these. Needs a Vector copy ctor.
  210. child->m_arguments = m_arguments;
  211. child->m_initialEnvironment = m_initialEnvironment;
  212. #endif
  213. for (auto& region : m_regions) {
  214. #ifdef FORK_DEBUG
  215. dbgprintf("fork: cloning Region{%p}\n", region.ptr());
  216. #endif
  217. auto cloned_region = region->clone();
  218. child->m_regions.append(move(cloned_region));
  219. MM.map_region(*child, *child->m_regions.last());
  220. }
  221. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  222. child->m_tss.ebx = regs.ebx;
  223. child->m_tss.ecx = regs.ecx;
  224. child->m_tss.edx = regs.edx;
  225. child->m_tss.ebp = regs.ebp;
  226. child->m_tss.esp = regs.esp_if_crossRing;
  227. child->m_tss.esi = regs.esi;
  228. child->m_tss.edi = regs.edi;
  229. child->m_tss.eflags = regs.eflags;
  230. child->m_tss.eip = regs.eip;
  231. child->m_tss.cs = regs.cs;
  232. child->m_tss.ds = regs.ds;
  233. child->m_tss.es = regs.es;
  234. child->m_tss.fs = regs.fs;
  235. child->m_tss.gs = regs.gs;
  236. child->m_tss.ss = regs.ss_if_crossRing;
  237. #ifdef FORK_DEBUG
  238. 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);
  239. #endif
  240. ProcFS::the().add_process(*child);
  241. {
  242. InterruptDisabler disabler;
  243. g_processes->prepend(child);
  244. system.nprocess++;
  245. }
  246. #ifdef TASK_DEBUG
  247. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  248. #endif
  249. return child;
  250. }
  251. pid_t Process::sys$fork(RegisterDump& regs)
  252. {
  253. auto* child = fork(regs);
  254. ASSERT(child);
  255. return child->pid();
  256. }
  257. int Process::do_exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  258. {
  259. auto parts = path.split('/');
  260. if (parts.is_empty())
  261. return -ENOENT;
  262. int error;
  263. auto descriptor = VFS::the().open(path, error, 0, m_cwd ? m_cwd->inode : InodeIdentifier());
  264. if (!descriptor) {
  265. ASSERT(error != 0);
  266. return error;
  267. }
  268. if (!descriptor->metadata().mayExecute(m_euid, m_gids))
  269. return -EACCES;
  270. if (!descriptor->metadata().size) {
  271. kprintf("exec() of 0-length binaries not supported\n");
  272. return -ENOTIMPL;
  273. }
  274. auto vmo = VMObject::create_file_backed(descriptor->vnode(), descriptor->metadata().size);
  275. vmo->set_name(descriptor->absolute_path());
  276. auto* region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copyRef(), 0, "helper", true, false);
  277. dword entry_eip = 0;
  278. // FIXME: Is there a race here?
  279. auto old_page_directory = move(m_page_directory);
  280. m_page_directory = make<PageDirectory>();
  281. #ifdef MM_DEBUG
  282. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  283. #endif
  284. ProcessPagingScope paging_scope(*this);
  285. // FIXME: Should we consider doing on-demand paging here? Is it actually useful?
  286. bool success = region->page_in(*m_page_directory);
  287. ASSERT(success);
  288. {
  289. InterruptDisabler disabler;
  290. // Okay, here comes the sleight of hand, pay close attention..
  291. auto old_regions = move(m_regions);
  292. ELFLoader loader(region->linearAddress.asPtr());
  293. 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) {
  294. ASSERT(size);
  295. ASSERT(alignment == PAGE_SIZE);
  296. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  297. (void) allocate_region_with_vmo(laddr, size, vmo.copyRef(), offset_in_image, String(name), is_readable, is_writable);
  298. return laddr.asPtr();
  299. };
  300. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  301. ASSERT(size);
  302. ASSERT(alignment == PAGE_SIZE);
  303. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  304. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  305. return laddr.asPtr();
  306. };
  307. bool success = loader.load();
  308. if (!success) {
  309. m_page_directory = move(old_page_directory);
  310. // FIXME: RAII this somehow instead.
  311. ASSERT(current == this);
  312. MM.enter_process_paging_scope(*this);
  313. m_regions = move(old_regions);
  314. kprintf("sys$execve: Failure loading %s\n", path.characters());
  315. return -ENOEXEC;
  316. }
  317. entry_eip = loader.entry().get();
  318. if (!entry_eip) {
  319. m_page_directory = move(old_page_directory);
  320. // FIXME: RAII this somehow instead.
  321. ASSERT(current == this);
  322. MM.enter_process_paging_scope(*this);
  323. m_regions = move(old_regions);
  324. return -ENOEXEC;
  325. }
  326. }
  327. m_signal_stack_kernel_region = nullptr;
  328. m_signal_stack_user_region = nullptr;
  329. memset(m_signal_action_data, 0, sizeof(m_signal_action_data));
  330. m_signal_mask = 0xffffffff;
  331. m_pending_signals = 0;
  332. for (size_t i = 0; i < m_fds.size(); ++i) {
  333. auto& daf = m_fds[i];
  334. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  335. daf.descriptor->close();
  336. daf = { };
  337. }
  338. }
  339. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  340. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  341. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  342. cli();
  343. Scheduler::prepare_to_modify_tss(*this);
  344. m_name = parts.takeLast();
  345. dword old_esp0 = m_tss.esp0;
  346. memset(&m_tss, 0, sizeof(m_tss));
  347. m_tss.eflags = 0x0202;
  348. m_tss.eip = entry_eip;
  349. m_tss.cs = 0x1b;
  350. m_tss.ds = 0x23;
  351. m_tss.es = 0x23;
  352. m_tss.fs = 0x23;
  353. m_tss.gs = 0x23;
  354. m_tss.ss = 0x23;
  355. m_tss.cr3 = page_directory().cr3();
  356. m_stack_region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  357. ASSERT(m_stack_region);
  358. m_stackTop3 = m_stack_region->linearAddress.offset(defaultStackSize).get();
  359. m_tss.esp = m_stackTop3;
  360. m_tss.ss0 = 0x10;
  361. m_tss.esp0 = old_esp0;
  362. m_tss.ss2 = m_pid;
  363. m_executable = descriptor->vnode();
  364. m_arguments = move(arguments);
  365. m_initialEnvironment = move(environment);
  366. #ifdef TASK_DEBUG
  367. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), m_tss.eip);
  368. #endif
  369. set_state(Skip1SchedulerPass);
  370. return 0;
  371. }
  372. int Process::exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  373. {
  374. // The bulk of exec() is done by do_exec(), which ensures that all locals
  375. // are cleaned up by the time we yield-teleport below.
  376. int rc = do_exec(path, move(arguments), move(environment));
  377. if (rc < 0)
  378. return rc;
  379. if (current == this) {
  380. Scheduler::yield();
  381. ASSERT_NOT_REACHED();
  382. }
  383. return 0;
  384. }
  385. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  386. {
  387. if (!validate_read_str(filename))
  388. return -EFAULT;
  389. if (argv) {
  390. if (!validate_read_typed(argv))
  391. return -EFAULT;
  392. for (size_t i = 0; argv[i]; ++i) {
  393. if (!validate_read_str(argv[i]))
  394. return -EFAULT;
  395. }
  396. }
  397. if (envp) {
  398. if (!validate_read_typed(envp))
  399. return -EFAULT;
  400. for (size_t i = 0; envp[i]; ++i) {
  401. if (!validate_read_str(envp[i]))
  402. return -EFAULT;
  403. }
  404. }
  405. String path(filename);
  406. auto parts = path.split('/');
  407. Vector<String> arguments;
  408. if (argv) {
  409. for (size_t i = 0; argv[i]; ++i) {
  410. arguments.append(argv[i]);
  411. }
  412. } else {
  413. arguments.append(parts.last());
  414. }
  415. Vector<String> environment;
  416. if (envp) {
  417. for (size_t i = 0; envp[i]; ++i)
  418. environment.append(envp[i]);
  419. }
  420. int rc = exec(path, move(arguments), move(environment));
  421. ASSERT(rc < 0); // We should never continue after a successful exec!
  422. return rc;
  423. }
  424. 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)
  425. {
  426. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  427. auto parts = path.split('/');
  428. if (arguments.is_empty()) {
  429. arguments.append(parts.last());
  430. }
  431. RetainPtr<Vnode> cwd;
  432. {
  433. InterruptDisabler disabler;
  434. if (auto* parent = Process::from_pid(parent_pid))
  435. cwd = parent->m_cwd.copyRef();
  436. }
  437. if (!cwd)
  438. cwd = VFS::the().root();
  439. auto* process = new Process(parts.takeLast(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  440. error = process->exec(path, move(arguments), move(environment));
  441. if (error != 0) {
  442. delete process;
  443. return nullptr;
  444. }
  445. ProcFS::the().add_process(*process);
  446. {
  447. InterruptDisabler disabler;
  448. g_processes->prepend(process);
  449. system.nprocess++;
  450. }
  451. #ifdef TASK_DEBUG
  452. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  453. #endif
  454. error = 0;
  455. return process;
  456. }
  457. int Process::sys$get_environment(char*** environ)
  458. {
  459. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
  460. if (!region)
  461. return -ENOMEM;
  462. MM.map_region(*this, *region);
  463. char* envpage = (char*)region->linearAddress.get();
  464. *environ = (char**)envpage;
  465. char* bufptr = envpage + (sizeof(char*) * (m_initialEnvironment.size() + 1));
  466. for (size_t i = 0; i < m_initialEnvironment.size(); ++i) {
  467. (*environ)[i] = bufptr;
  468. memcpy(bufptr, m_initialEnvironment[i].characters(), m_initialEnvironment[i].length());
  469. bufptr += m_initialEnvironment[i].length();
  470. *(bufptr++) = '\0';
  471. }
  472. (*environ)[m_initialEnvironment.size()] = nullptr;
  473. return 0;
  474. }
  475. int Process::sys$get_arguments(int* argc, char*** argv)
  476. {
  477. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
  478. if (!region)
  479. return -ENOMEM;
  480. MM.map_region(*this, *region);
  481. char* argpage = (char*)region->linearAddress.get();
  482. *argc = m_arguments.size();
  483. *argv = (char**)argpage;
  484. char* bufptr = argpage + (sizeof(char*) * m_arguments.size());
  485. for (size_t i = 0; i < m_arguments.size(); ++i) {
  486. (*argv)[i] = bufptr;
  487. memcpy(bufptr, m_arguments[i].characters(), m_arguments[i].length());
  488. bufptr += m_arguments[i].length();
  489. *(bufptr++) = '\0';
  490. }
  491. return 0;
  492. }
  493. Process* Process::create_kernel_process(String&& name, void (*e)())
  494. {
  495. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  496. process->m_tss.eip = (dword)e;
  497. if (process->pid() != 0) {
  498. {
  499. InterruptDisabler disabler;
  500. g_processes->prepend(process);
  501. system.nprocess++;
  502. }
  503. ProcFS::the().add_process(*process);
  504. #ifdef TASK_DEBUG
  505. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  506. #endif
  507. }
  508. return process;
  509. }
  510. 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)
  511. : m_name(move(name))
  512. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  513. , m_uid(uid)
  514. , m_gid(gid)
  515. , m_euid(uid)
  516. , m_egid(gid)
  517. , m_state(Runnable)
  518. , m_ring(ring)
  519. , m_cwd(move(cwd))
  520. , m_executable(move(executable))
  521. , m_tty(tty)
  522. , m_ppid(ppid)
  523. {
  524. m_gids.set(m_gid);
  525. if (fork_parent) {
  526. m_sid = fork_parent->m_sid;
  527. m_pgid = fork_parent->m_pgid;
  528. } else {
  529. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  530. InterruptDisabler disabler;
  531. if (auto* parent = Process::from_pid(m_ppid)) {
  532. m_sid = parent->m_sid;
  533. m_pgid = parent->m_pgid;
  534. }
  535. }
  536. m_page_directory = make<PageDirectory>();
  537. #ifdef MM_DEBUG
  538. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  539. #endif
  540. if (fork_parent) {
  541. m_fds.resize(fork_parent->m_fds.size());
  542. for (size_t i = 0; i < fork_parent->m_fds.size(); ++i) {
  543. if (!fork_parent->m_fds[i].descriptor)
  544. continue;
  545. #ifdef FORK_DEBUG
  546. 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());
  547. #endif
  548. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  549. m_fds[i].flags = fork_parent->m_fds[i].flags;
  550. }
  551. } else {
  552. m_fds.resize(m_max_open_file_descriptors);
  553. if (tty) {
  554. m_fds[0].set(tty->open(O_RDONLY));
  555. m_fds[1].set(tty->open(O_WRONLY));
  556. m_fds[2].set(tty->open(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. if (descriptor->is_blocking()) {
  959. if (!descriptor->has_data_available_for_reading(*this)) {
  960. m_blocked_fd = fd;
  961. block(BlockedRead);
  962. sched_yield();
  963. if (m_was_interrupted_while_blocked)
  964. return -EINTR;
  965. }
  966. }
  967. nread = descriptor->read(*this, (byte*)outbuf, nread);
  968. #ifdef DEBUG_IO
  969. dbgprintf("%s(%u) Process::sys$read: nread=%u\n", name().characters(), pid(), nread);
  970. #endif
  971. return nread;
  972. }
  973. int Process::sys$close(int fd)
  974. {
  975. auto* descriptor = file_descriptor(fd);
  976. if (!descriptor)
  977. return -EBADF;
  978. int rc = descriptor->close();
  979. m_fds[fd] = { };
  980. return rc;
  981. }
  982. int Process::sys$utime(const char* pathname, const Unix::utimbuf* buf)
  983. {
  984. if (!validate_read_str(pathname))
  985. return -EFAULT;
  986. if (buf && !validate_read_typed(buf))
  987. return -EFAULT;
  988. String path(pathname);
  989. int error;
  990. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  991. if (!descriptor)
  992. return error;
  993. auto& inode = *descriptor->inode();
  994. if (inode.fs().is_readonly())
  995. return -EROFS;
  996. Unix::time_t atime;
  997. Unix::time_t mtime;
  998. if (buf) {
  999. atime = buf->actime;
  1000. mtime = buf->modtime;
  1001. } else {
  1002. auto now = RTC::now();
  1003. mtime = now;
  1004. atime = now;
  1005. }
  1006. inode.set_atime(atime);
  1007. inode.set_mtime(mtime);
  1008. return 0;
  1009. }
  1010. int Process::sys$access(const char* pathname, int mode)
  1011. {
  1012. (void) mode;
  1013. if (!validate_read_str(pathname))
  1014. return -EFAULT;
  1015. ASSERT_NOT_REACHED();
  1016. }
  1017. int Process::sys$fcntl(int fd, int cmd, dword arg)
  1018. {
  1019. (void) cmd;
  1020. (void) arg;
  1021. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1022. auto* descriptor = file_descriptor(fd);
  1023. if (!descriptor)
  1024. return -EBADF;
  1025. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1026. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1027. switch (cmd) {
  1028. case F_DUPFD: {
  1029. int arg_fd = (int)arg;
  1030. if (arg_fd < 0)
  1031. return -EINVAL;
  1032. int new_fd = -1;
  1033. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1034. if (!m_fds[i]) {
  1035. new_fd = i;
  1036. break;
  1037. }
  1038. }
  1039. if (new_fd == -1)
  1040. return -EMFILE;
  1041. m_fds[new_fd].set(descriptor);
  1042. break;
  1043. }
  1044. case F_GETFD:
  1045. return m_fds[fd].flags;
  1046. case F_SETFD:
  1047. m_fds[fd].flags = arg;
  1048. break;
  1049. case F_GETFL:
  1050. return descriptor->file_flags();
  1051. case F_SETFL:
  1052. // FIXME: Support changing O_NONBLOCK
  1053. descriptor->set_file_flags(arg);
  1054. break;
  1055. default:
  1056. ASSERT_NOT_REACHED();
  1057. }
  1058. return 0;
  1059. }
  1060. int Process::sys$fstat(int fd, Unix::stat* statbuf)
  1061. {
  1062. if (!validate_write_typed(statbuf))
  1063. return -EFAULT;
  1064. auto* descriptor = file_descriptor(fd);
  1065. if (!descriptor)
  1066. return -EBADF;
  1067. descriptor->stat(statbuf);
  1068. return 0;
  1069. }
  1070. int Process::sys$lstat(const char* path, Unix::stat* statbuf)
  1071. {
  1072. if (!validate_write_typed(statbuf))
  1073. return -EFAULT;
  1074. int error;
  1075. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1076. if (!descriptor)
  1077. return error;
  1078. descriptor->stat(statbuf);
  1079. return 0;
  1080. }
  1081. int Process::sys$stat(const char* path, Unix::stat* statbuf)
  1082. {
  1083. if (!validate_write_typed(statbuf))
  1084. return -EFAULT;
  1085. int error;
  1086. auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier());
  1087. if (!descriptor)
  1088. return error;
  1089. descriptor->stat(statbuf);
  1090. return 0;
  1091. }
  1092. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1093. {
  1094. if (!validate_read_str(path))
  1095. return -EFAULT;
  1096. if (!validate_write(buffer, size))
  1097. return -EFAULT;
  1098. int error;
  1099. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwd_inode()->identifier());
  1100. if (!descriptor)
  1101. return error;
  1102. if (!descriptor->metadata().isSymbolicLink())
  1103. return -EINVAL;
  1104. auto contents = descriptor->read_entire_file(*this);
  1105. if (!contents)
  1106. return -EIO; // FIXME: Get a more detailed error from VFS.
  1107. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1108. if (contents.size() + 1 < size)
  1109. buffer[contents.size()] = '\0';
  1110. return 0;
  1111. }
  1112. int Process::sys$chdir(const char* path)
  1113. {
  1114. if (!validate_read_str(path))
  1115. return -EFAULT;
  1116. int error;
  1117. auto descriptor = VFS::the().open(path, error, 0, cwd_inode()->identifier());
  1118. if (!descriptor)
  1119. return error;
  1120. if (!descriptor->is_directory())
  1121. return -ENOTDIR;
  1122. m_cwd = descriptor->vnode();
  1123. return 0;
  1124. }
  1125. int Process::sys$getcwd(char* buffer, size_t size)
  1126. {
  1127. if (!validate_write(buffer, size))
  1128. return -EFAULT;
  1129. ASSERT(cwd_inode());
  1130. auto path = VFS::the().absolute_path(*cwd_inode());
  1131. if (path.is_null())
  1132. return -EINVAL;
  1133. if (size < path.length() + 1)
  1134. return -ERANGE;
  1135. strcpy(buffer, path.characters());
  1136. return 0;
  1137. }
  1138. size_t Process::number_of_open_file_descriptors() const
  1139. {
  1140. size_t count = 0;
  1141. for (auto& descriptor : m_fds) {
  1142. if (descriptor)
  1143. ++count;
  1144. }
  1145. return count;
  1146. }
  1147. int Process::sys$open(const char* path, int options)
  1148. {
  1149. #ifdef DEBUG_IO
  1150. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1151. #endif
  1152. if (!validate_read_str(path))
  1153. return -EFAULT;
  1154. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1155. return -EMFILE;
  1156. int error = -EWHYTHO;
  1157. auto descriptor = VFS::the().open(path, error, options, cwd_inode()->identifier());
  1158. if (!descriptor)
  1159. return error;
  1160. if (options & O_DIRECTORY && !descriptor->is_directory())
  1161. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1162. if (options & O_NONBLOCK)
  1163. descriptor->set_blocking(false);
  1164. int fd = 0;
  1165. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1166. if (!m_fds[fd])
  1167. break;
  1168. }
  1169. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1170. m_fds[fd].set(move(descriptor), flags);
  1171. return fd;
  1172. }
  1173. int Process::alloc_fd()
  1174. {
  1175. int fd = -1;
  1176. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1177. if (!m_fds[i]) {
  1178. fd = i;
  1179. break;
  1180. }
  1181. }
  1182. return fd;
  1183. }
  1184. int Process::sys$pipe(int pipefd[2])
  1185. {
  1186. if (!validate_write_typed(pipefd))
  1187. return -EFAULT;
  1188. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1189. return -EMFILE;
  1190. auto fifo = FIFO::create();
  1191. int reader_fd = alloc_fd();
  1192. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1193. pipefd[0] = reader_fd;
  1194. int writer_fd = alloc_fd();
  1195. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1196. pipefd[1] = writer_fd;
  1197. return 0;
  1198. }
  1199. int Process::sys$killpg(int pgrp, int signum)
  1200. {
  1201. if (signum < 1 || signum >= 32)
  1202. return -EINVAL;
  1203. (void) pgrp;
  1204. ASSERT_NOT_REACHED();
  1205. }
  1206. int Process::sys$setuid(uid_t)
  1207. {
  1208. ASSERT_NOT_REACHED();
  1209. }
  1210. int Process::sys$setgid(gid_t)
  1211. {
  1212. ASSERT_NOT_REACHED();
  1213. }
  1214. unsigned Process::sys$alarm(unsigned seconds)
  1215. {
  1216. (void) seconds;
  1217. ASSERT_NOT_REACHED();
  1218. }
  1219. int Process::sys$uname(utsname* buf)
  1220. {
  1221. if (!validate_write_typed(buf))
  1222. return -EFAULT;
  1223. strcpy(buf->sysname, "Serenity");
  1224. strcpy(buf->release, "1.0-dev");
  1225. strcpy(buf->version, "FIXME");
  1226. strcpy(buf->machine, "i386");
  1227. strcpy(buf->nodename, getHostname().characters());
  1228. return 0;
  1229. }
  1230. int Process::sys$isatty(int fd)
  1231. {
  1232. auto* descriptor = file_descriptor(fd);
  1233. if (!descriptor)
  1234. return -EBADF;
  1235. if (!descriptor->is_tty())
  1236. return -ENOTTY;
  1237. return 1;
  1238. }
  1239. int Process::sys$kill(pid_t pid, int signal)
  1240. {
  1241. if (pid == 0) {
  1242. // FIXME: Send to same-group processes.
  1243. ASSERT(pid != 0);
  1244. }
  1245. if (pid == -1) {
  1246. // FIXME: Send to all processes.
  1247. ASSERT(pid != -1);
  1248. }
  1249. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1250. InterruptDisabler disabler;
  1251. auto* peer = Process::from_pid(pid);
  1252. if (!peer)
  1253. return -ESRCH;
  1254. peer->send_signal(signal, this);
  1255. return 0;
  1256. }
  1257. int Process::sys$sleep(unsigned seconds)
  1258. {
  1259. if (!seconds)
  1260. return 0;
  1261. sleep(seconds * TICKS_PER_SECOND);
  1262. if (m_wakeupTime > system.uptime) {
  1263. ASSERT(m_was_interrupted_while_blocked);
  1264. dword ticks_left_until_original_wakeup_time = m_wakeupTime - system.uptime;
  1265. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1266. }
  1267. return 0;
  1268. }
  1269. int Process::sys$gettimeofday(timeval* tv)
  1270. {
  1271. if (!validate_write_typed(tv))
  1272. return -EFAULT;
  1273. InterruptDisabler disabler;
  1274. auto now = RTC::now();
  1275. tv->tv_sec = now;
  1276. tv->tv_usec = 0;
  1277. return 0;
  1278. }
  1279. uid_t Process::sys$getuid()
  1280. {
  1281. return m_uid;
  1282. }
  1283. gid_t Process::sys$getgid()
  1284. {
  1285. return m_gid;
  1286. }
  1287. uid_t Process::sys$geteuid()
  1288. {
  1289. return m_euid;
  1290. }
  1291. gid_t Process::sys$getegid()
  1292. {
  1293. return m_egid;
  1294. }
  1295. pid_t Process::sys$getpid()
  1296. {
  1297. return m_pid;
  1298. }
  1299. pid_t Process::sys$getppid()
  1300. {
  1301. return m_ppid;
  1302. }
  1303. mode_t Process::sys$umask(mode_t mask)
  1304. {
  1305. auto old_mask = m_umask;
  1306. m_umask = mask;
  1307. return old_mask;
  1308. }
  1309. int Process::reap(Process& process)
  1310. {
  1311. InterruptDisabler disabler;
  1312. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1313. if (process.ppid()) {
  1314. auto* parent = Process::from_pid(process.ppid());
  1315. ASSERT(parent);
  1316. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1317. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1318. }
  1319. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), toString(process.state()));
  1320. ASSERT(process.state() == Dead);
  1321. g_processes->remove(&process);
  1322. delete &process;
  1323. return exit_status;
  1324. }
  1325. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1326. {
  1327. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1328. // FIXME: Respect options
  1329. (void) options;
  1330. if (wstatus)
  1331. if (!validate_write_typed(wstatus))
  1332. return -EFAULT;
  1333. int dummy_wstatus;
  1334. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1335. {
  1336. InterruptDisabler disabler;
  1337. if (waitee != -1 && !Process::from_pid(waitee))
  1338. return -ECHILD;
  1339. }
  1340. if (options & WNOHANG) {
  1341. if (waitee == -1) {
  1342. pid_t reaped_pid = 0;
  1343. InterruptDisabler disabler;
  1344. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1345. if (process.state() == Dead) {
  1346. reaped_pid = process.pid();
  1347. exit_status = reap(process);
  1348. }
  1349. return true;
  1350. });
  1351. return reaped_pid;
  1352. } else {
  1353. auto* waitee_process = Process::from_pid(waitee);
  1354. if (!waitee_process)
  1355. return -ECHILD;
  1356. if (waitee_process->state() == Dead) {
  1357. exit_status = reap(*waitee_process);
  1358. return waitee;
  1359. }
  1360. return 0;
  1361. }
  1362. }
  1363. m_waitee_pid = waitee;
  1364. block(BlockedWait);
  1365. sched_yield();
  1366. if (m_was_interrupted_while_blocked)
  1367. return -EINTR;
  1368. Process* waitee_process;
  1369. {
  1370. InterruptDisabler disabler;
  1371. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1372. waitee_process = Process::from_pid(m_waitee_pid);
  1373. }
  1374. ASSERT(waitee_process);
  1375. exit_status = reap(*waitee_process);
  1376. return m_waitee_pid;
  1377. }
  1378. void Process::unblock()
  1379. {
  1380. if (current == this) {
  1381. kprintf("ignoring unblock() on current, %s(%u) {%s}\n", name().characters(), pid(), toString(state()));
  1382. return;
  1383. }
  1384. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1385. system.nblocked--;
  1386. m_state = Process::Runnable;
  1387. }
  1388. void Process::block(Process::State new_state)
  1389. {
  1390. if (state() != Process::Running) {
  1391. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, toString(new_state), state(), toString(state()));
  1392. }
  1393. ASSERT(state() == Process::Running);
  1394. system.nblocked++;
  1395. m_was_interrupted_while_blocked = false;
  1396. set_state(new_state);
  1397. }
  1398. void block(Process::State state)
  1399. {
  1400. current->block(state);
  1401. sched_yield();
  1402. }
  1403. void sleep(dword ticks)
  1404. {
  1405. ASSERT(current->state() == Process::Running);
  1406. current->setWakeupTime(system.uptime + ticks);
  1407. current->block(Process::BlockedSleep);
  1408. sched_yield();
  1409. }
  1410. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1411. {
  1412. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1413. // This code allows access outside of the known used address ranges to get caught.
  1414. InterruptDisabler disabler;
  1415. // FIXME: What if we're indexing into the ksym with the highest address though?
  1416. if (laddr.get() >= ksym_lowest_address && laddr.get() <= ksym_highest_address)
  1417. return true;
  1418. if (is_kmalloc_address(laddr.asPtr()))
  1419. return true;
  1420. return validate_read(laddr.asPtr(), 1);
  1421. }
  1422. bool Process::validate_read(const void* address, size_t size) const
  1423. {
  1424. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1425. if (!MM.validate_user_read(*this, LinearAddress((dword)address).offset(size)))
  1426. return false;
  1427. }
  1428. return MM.validate_user_read(*this, LinearAddress((dword)address));
  1429. }
  1430. bool Process::validate_write(void* address, size_t size) const
  1431. {
  1432. if ((reinterpret_cast<dword>(address) & PAGE_MASK) != ((reinterpret_cast<dword>(address) + (size - 1)) & PAGE_MASK)) {
  1433. if (!MM.validate_user_write(*this, LinearAddress((dword)address).offset(size)))
  1434. return false;
  1435. }
  1436. return MM.validate_user_write(*this, LinearAddress((dword)address));
  1437. }
  1438. pid_t Process::sys$getsid(pid_t pid)
  1439. {
  1440. if (pid == 0)
  1441. return m_sid;
  1442. InterruptDisabler disabler;
  1443. auto* process = Process::from_pid(pid);
  1444. if (!process)
  1445. return -ESRCH;
  1446. if (m_sid != process->m_sid)
  1447. return -EPERM;
  1448. return process->m_sid;
  1449. }
  1450. pid_t Process::sys$setsid()
  1451. {
  1452. InterruptDisabler disabler;
  1453. bool found_process_with_same_pgid_as_my_pid = false;
  1454. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1455. found_process_with_same_pgid_as_my_pid = true;
  1456. return false;
  1457. });
  1458. if (found_process_with_same_pgid_as_my_pid)
  1459. return -EPERM;
  1460. m_sid = m_pid;
  1461. m_pgid = m_pid;
  1462. return m_sid;
  1463. }
  1464. pid_t Process::sys$getpgid(pid_t pid)
  1465. {
  1466. if (pid == 0)
  1467. return m_pgid;
  1468. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1469. auto* process = Process::from_pid(pid);
  1470. if (!process)
  1471. return -ESRCH;
  1472. return process->m_pgid;
  1473. }
  1474. pid_t Process::sys$getpgrp()
  1475. {
  1476. return m_pgid;
  1477. }
  1478. static pid_t get_sid_from_pgid(pid_t pgid)
  1479. {
  1480. InterruptDisabler disabler;
  1481. auto* group_leader = Process::from_pid(pgid);
  1482. if (!group_leader)
  1483. return -1;
  1484. return group_leader->sid();
  1485. }
  1486. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1487. {
  1488. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1489. pid_t pid = specified_pid ? specified_pid : m_pid;
  1490. if (specified_pgid < 0)
  1491. return -EINVAL;
  1492. auto* process = Process::from_pid(pid);
  1493. if (!process)
  1494. return -ESRCH;
  1495. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1496. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1497. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1498. if (current_sid != new_sid) {
  1499. // Can't move a process between sessions.
  1500. return -EPERM;
  1501. }
  1502. // FIXME: There are more EPERM conditions to check for here..
  1503. process->m_pgid = new_pgid;
  1504. return 0;
  1505. }
  1506. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1507. {
  1508. auto* descriptor = file_descriptor(fd);
  1509. if (!descriptor)
  1510. return -EBADF;
  1511. if (!descriptor->is_character_device())
  1512. return -ENOTTY;
  1513. return descriptor->character_device()->ioctl(*this, request, arg);
  1514. }
  1515. int Process::sys$getdtablesize()
  1516. {
  1517. return m_max_open_file_descriptors;
  1518. }
  1519. int Process::sys$dup(int old_fd)
  1520. {
  1521. auto* descriptor = file_descriptor(old_fd);
  1522. if (!descriptor)
  1523. return -EBADF;
  1524. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1525. return -EMFILE;
  1526. int new_fd = 0;
  1527. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1528. if (!m_fds[new_fd])
  1529. break;
  1530. }
  1531. m_fds[new_fd].set(descriptor);
  1532. return new_fd;
  1533. }
  1534. int Process::sys$dup2(int old_fd, int new_fd)
  1535. {
  1536. auto* descriptor = file_descriptor(old_fd);
  1537. if (!descriptor)
  1538. return -EBADF;
  1539. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1540. return -EMFILE;
  1541. m_fds[new_fd].set(descriptor);
  1542. return new_fd;
  1543. }
  1544. int Process::sys$sigprocmask(int how, const Unix::sigset_t* set, Unix::sigset_t* old_set)
  1545. {
  1546. if (old_set) {
  1547. if (!validate_read_typed(old_set))
  1548. return -EFAULT;
  1549. *old_set = m_signal_mask;
  1550. }
  1551. if (set) {
  1552. if (!validate_read_typed(set))
  1553. return -EFAULT;
  1554. switch (how) {
  1555. case SIG_BLOCK:
  1556. m_signal_mask &= ~(*set);
  1557. break;
  1558. case SIG_UNBLOCK:
  1559. m_signal_mask |= *set;
  1560. break;
  1561. case SIG_SETMASK:
  1562. m_signal_mask = *set;
  1563. break;
  1564. default:
  1565. return -EINVAL;
  1566. }
  1567. }
  1568. return 0;
  1569. }
  1570. int Process::sys$sigpending(Unix::sigset_t* set)
  1571. {
  1572. if (!validate_read_typed(set))
  1573. return -EFAULT;
  1574. *set = m_pending_signals;
  1575. return 0;
  1576. }
  1577. int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
  1578. {
  1579. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1580. return -EINVAL;
  1581. if (!validate_read_typed(act))
  1582. return -EFAULT;
  1583. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1584. auto& action = m_signal_action_data[signum];
  1585. if (old_act) {
  1586. if (!validate_write_typed(old_act))
  1587. return -EFAULT;
  1588. old_act->sa_flags = action.flags;
  1589. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1590. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1591. }
  1592. action.restorer = LinearAddress((dword)act->sa_restorer);
  1593. action.flags = act->sa_flags;
  1594. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1595. return 0;
  1596. }
  1597. int Process::sys$getgroups(int count, gid_t* gids)
  1598. {
  1599. if (count < 0)
  1600. return -EINVAL;
  1601. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1602. if (!count)
  1603. return m_gids.size();
  1604. if (count != (int)m_gids.size())
  1605. return -EINVAL;
  1606. if (!validate_write_typed(gids, m_gids.size()))
  1607. return -EFAULT;
  1608. size_t i = 0;
  1609. for (auto gid : m_gids)
  1610. gids[i++] = gid;
  1611. return 0;
  1612. }
  1613. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1614. {
  1615. if (!is_root())
  1616. return -EPERM;
  1617. if (count >= MAX_PROCESS_GIDS)
  1618. return -EINVAL;
  1619. if (!validate_read(gids, count))
  1620. return -EFAULT;
  1621. m_gids.clear();
  1622. m_gids.set(m_gid);
  1623. for (size_t i = 0; i < count; ++i)
  1624. m_gids.set(gids[i]);
  1625. return 0;
  1626. }
  1627. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1628. {
  1629. if (!validate_read_str(pathname))
  1630. return -EFAULT;
  1631. if (strlen(pathname) >= 255)
  1632. return -ENAMETOOLONG;
  1633. int error;
  1634. if (!VFS::the().mkdir(pathname, mode, cwd_inode()->identifier(), error))
  1635. return error;
  1636. return 0;
  1637. }
  1638. Unix::clock_t Process::sys$times(Unix::tms* times)
  1639. {
  1640. if (!validate_write_typed(times))
  1641. return -EFAULT;
  1642. times->tms_utime = m_ticks_in_user;
  1643. times->tms_stime = m_ticks_in_kernel;
  1644. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1645. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1646. return 0;
  1647. }
  1648. struct vbe_info_structure {
  1649. char signature[4]; // must be "VESA" to indicate valid VBE support
  1650. word version; // VBE version; high byte is major version, low byte is minor version
  1651. dword oem; // segment:offset pointer to OEM
  1652. dword capabilities; // bitfield that describes card capabilities
  1653. dword video_modes; // segment:offset pointer to list of supported video modes
  1654. word video_memory; // amount of video memory in 64KB blocks
  1655. word software_rev; // software revision
  1656. dword vendor; // segment:offset to card vendor string
  1657. dword product_name; // segment:offset to card model name
  1658. dword product_rev; // segment:offset pointer to product revision
  1659. char reserved[222]; // reserved for future expansion
  1660. char oem_data[256]; // OEM BIOSes store their strings in this area
  1661. } __attribute__ ((packed));
  1662. struct vbe_mode_info_structure {
  1663. word attributes; // deprecated, only bit 7 should be of interest to you, and it indicates the mode supports a linear frame buffer.
  1664. byte window_a; // deprecated
  1665. byte window_b; // deprecated
  1666. word granularity; // deprecated; used while calculating bank numbers
  1667. word window_size;
  1668. word segment_a;
  1669. word segment_b;
  1670. dword win_func_ptr; // deprecated; used to switch banks from protected mode without returning to real mode
  1671. word pitch; // number of bytes per horizontal line
  1672. word width; // width in pixels
  1673. word height; // height in pixels
  1674. byte w_char; // unused...
  1675. byte y_char; // ...
  1676. byte planes;
  1677. byte bpp; // bits per pixel in this mode
  1678. byte banks; // deprecated; total number of banks in this mode
  1679. byte memory_model;
  1680. byte bank_size; // deprecated; size of a bank, almost always 64 KB but may be 16 KB...
  1681. byte image_pages;
  1682. byte reserved0;
  1683. byte red_mask;
  1684. byte red_position;
  1685. byte green_mask;
  1686. byte green_position;
  1687. byte blue_mask;
  1688. byte blue_position;
  1689. byte reserved_mask;
  1690. byte reserved_position;
  1691. byte direct_color_attributes;
  1692. dword framebuffer; // physical address of the linear frame buffer; write here to draw to the screen
  1693. dword off_screen_mem_off;
  1694. word off_screen_mem_size; // size of memory in the framebuffer but not being displayed on the screen
  1695. byte reserved1[206];
  1696. } __attribute__ ((packed));
  1697. DisplayInfo Process::get_display_info()
  1698. {
  1699. DisplayInfo info;
  1700. //auto* vinfo = reinterpret_cast<vbe_info_structure*>(0xc000);
  1701. auto* vmode = reinterpret_cast<vbe_mode_info_structure*>(0x2000);
  1702. dbgprintf("VESA framebuffer, %ux%u, %u bpp @ P%x\n", vmode->width, vmode->height, vmode->bpp, vmode->framebuffer);
  1703. dbgprintf("Returning display info in %s<%u>\n", name().characters(), pid());
  1704. info.width = vmode->width;
  1705. info.height = vmode->height;
  1706. info.bpp = vmode->bpp;
  1707. info.pitch = vmode->pitch;
  1708. size_t framebuffer_size = info.pitch * info.height;
  1709. if (!m_display_framebuffer_region) {
  1710. auto framebuffer_vmo = VMObject::create_framebuffer_wrapper(PhysicalAddress(vmode->framebuffer), framebuffer_size);
  1711. m_display_framebuffer_region = allocate_region_with_vmo(LinearAddress(0xe0000000), framebuffer_size, move(framebuffer_vmo), 0, "framebuffer", true, true);
  1712. }
  1713. info.framebuffer = m_display_framebuffer_region->linearAddress.asPtr();
  1714. return info;
  1715. }
  1716. int Process::sys$select(const Syscall::SC_select_params* params)
  1717. {
  1718. if (!validate_read_typed(params))
  1719. return -EFAULT;
  1720. if (params->writefds && !validate_read_typed(params->writefds))
  1721. return -EFAULT;
  1722. if (params->readfds && !validate_read_typed(params->readfds))
  1723. return -EFAULT;
  1724. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1725. return -EFAULT;
  1726. if (params->timeout && !validate_read_typed(params->timeout))
  1727. return -EFAULT;
  1728. int nfds = params->nfds;
  1729. fd_set* writefds = params->writefds;
  1730. fd_set* readfds = params->readfds;
  1731. fd_set* exceptfds = params->exceptfds;
  1732. auto* timeout = params->timeout;
  1733. // FIXME: Implement exceptfds support.
  1734. ASSERT(!exceptfds);
  1735. // FIXME: Implement timeout support.
  1736. ASSERT(!timeout);
  1737. if (nfds < 0)
  1738. return -EINVAL;
  1739. // FIXME: Return -EBADF if one of the fd sets contains an invalid fd.
  1740. // FIXME: Return -EINTR if a signal is caught.
  1741. // FIXME: Return -EINVAL if timeout is invalid.
  1742. auto transfer_fds = [nfds] (fd_set* set, auto& vector) {
  1743. if (!set)
  1744. return;
  1745. vector.clear_with_capacity();
  1746. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1747. for (int i = 0; i < nfds; ++i) {
  1748. if (bitmap.get(i))
  1749. vector.append(i);
  1750. }
  1751. };
  1752. transfer_fds(writefds, m_select_write_fds);
  1753. transfer_fds(readfds, m_select_read_fds);
  1754. block(BlockedSelect);
  1755. Scheduler::yield();
  1756. int markedfds = 0;
  1757. if (readfds) {
  1758. memset(readfds, 0, sizeof(fd_set));
  1759. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1760. for (int fd : m_select_read_fds) {
  1761. if (m_fds[fd].descriptor->has_data_available_for_reading(*this)) {
  1762. bitmap.set(fd, true);
  1763. ++markedfds;
  1764. }
  1765. }
  1766. }
  1767. if (writefds) {
  1768. memset(writefds, 0, sizeof(fd_set));
  1769. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1770. for (int fd : m_select_write_fds) {
  1771. if (m_fds[fd].descriptor->can_write(*this)) {
  1772. bitmap.set(fd, true);
  1773. ++markedfds;
  1774. }
  1775. }
  1776. }
  1777. return markedfds;
  1778. }