Process.cpp 62 KB

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