Process.cpp 60 KB

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