Process.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  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 <Kernel/NullDevice.h>
  10. #include "ELFLoader.h"
  11. #include "MemoryManager.h"
  12. #include "i8253.h"
  13. #include "RTC.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 <Kernel/Socket.h>
  22. #include "MasterPTY.h"
  23. #include "elf.h"
  24. #include <AK/StringBuilder.h>
  25. //#define DEBUG_IO
  26. //#define TASK_DEBUG
  27. //#define FORK_DEBUG
  28. #define SIGNAL_DEBUG
  29. #define MAX_PROCESS_GIDS 32
  30. //#define SHARED_BUFFER_DEBUG
  31. static const dword default_kernel_stack_size = 16384;
  32. static const dword default_userspace_stack_size = 65536;
  33. static pid_t next_pid;
  34. InlineLinkedList<Process>* g_processes;
  35. static String* s_hostname;
  36. static Lock* s_hostname_lock;
  37. CoolGlobals* g_cool_globals;
  38. void Process::initialize()
  39. {
  40. #ifdef COOL_GLOBALS
  41. g_cool_globals = reinterpret_cast<CoolGlobals*>(0x1000);
  42. #endif
  43. next_pid = 0;
  44. g_processes = new InlineLinkedList<Process>;
  45. s_hostname = new String("courage");
  46. s_hostname_lock = new Lock;
  47. Scheduler::initialize();
  48. }
  49. Vector<pid_t> Process::all_pids()
  50. {
  51. Vector<pid_t> pids;
  52. pids.ensure_capacity(system.nprocess);
  53. InterruptDisabler disabler;
  54. for (auto* process = g_processes->head(); process; process = process->next())
  55. pids.append(process->pid());
  56. return pids;
  57. }
  58. Vector<Process*> Process::all_processes()
  59. {
  60. Vector<Process*> processes;
  61. processes.ensure_capacity(system.nprocess);
  62. InterruptDisabler disabler;
  63. for (auto* process = g_processes->head(); process; process = process->next())
  64. processes.append(process);
  65. return processes;
  66. }
  67. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  68. {
  69. size = PAGE_ROUND_UP(size);
  70. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  71. if (laddr.is_null()) {
  72. laddr = m_next_region;
  73. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  74. }
  75. laddr.mask(0xfffff000);
  76. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  77. MM.map_region(*this, *m_regions.last());
  78. if (commit)
  79. m_regions.last()->commit();
  80. return m_regions.last().ptr();
  81. }
  82. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  83. {
  84. size = PAGE_ROUND_UP(size);
  85. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  86. if (laddr.is_null()) {
  87. laddr = m_next_region;
  88. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  89. }
  90. laddr.mask(0xfffff000);
  91. m_regions.append(adopt(*new Region(laddr, size, move(inode), move(name), is_readable, is_writable)));
  92. MM.map_region(*this, *m_regions.last());
  93. return m_regions.last().ptr();
  94. }
  95. Region* Process::allocate_region_with_vmo(LinearAddress laddr, size_t size, Retained<VMObject>&& vmo, size_t offset_in_vmo, String&& name, bool is_readable, bool is_writable)
  96. {
  97. size = PAGE_ROUND_UP(size);
  98. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  99. if (laddr.is_null()) {
  100. laddr = m_next_region;
  101. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  102. }
  103. laddr.mask(0xfffff000);
  104. offset_in_vmo &= PAGE_MASK;
  105. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  106. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  107. MM.map_region(*this, *m_regions.last());
  108. return m_regions.last().ptr();
  109. }
  110. bool Process::deallocate_region(Region& region)
  111. {
  112. InterruptDisabler disabler;
  113. for (int i = 0; i < m_regions.size(); ++i) {
  114. if (m_regions[i].ptr() == &region) {
  115. MM.unmap_region(region);
  116. m_regions.remove(i);
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  123. {
  124. size = PAGE_ROUND_UP(size);
  125. for (auto& region : m_regions) {
  126. if (region->laddr() == laddr && region->size() == size)
  127. return region.ptr();
  128. }
  129. return nullptr;
  130. }
  131. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  132. {
  133. if (!validate_read_str(name))
  134. return -EFAULT;
  135. auto* region = region_from_range(LinearAddress((dword)addr), size);
  136. if (!region)
  137. return -EINVAL;
  138. region->set_name(String(name));
  139. return 0;
  140. }
  141. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  142. {
  143. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  144. return (void*)-EFAULT;
  145. void* addr = (void*)params->addr;
  146. size_t size = params->size;
  147. int prot = params->prot;
  148. int flags = params->flags;
  149. int fd = params->fd;
  150. off_t offset = params->offset;
  151. if (size == 0)
  152. return (void*)-EINVAL;
  153. if ((dword)addr & ~PAGE_MASK)
  154. return (void*)-EINVAL;
  155. if (flags & MAP_ANONYMOUS) {
  156. auto* region = allocate_region(LinearAddress((dword)addr), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  157. if (!region)
  158. return (void*)-ENOMEM;
  159. if (flags & MAP_SHARED)
  160. region->set_shared(true);
  161. return region->laddr().as_ptr();
  162. }
  163. if (offset & ~PAGE_MASK)
  164. return (void*)-EINVAL;
  165. auto* descriptor = file_descriptor(fd);
  166. if (!descriptor)
  167. return (void*)-EBADF;
  168. if (!descriptor->supports_mmap())
  169. return (void*)-ENODEV;
  170. auto* region = descriptor->mmap(*this, LinearAddress((dword)addr), offset, size, prot);
  171. if (!region)
  172. return (void*)-ENOMEM;
  173. if (flags & MAP_SHARED)
  174. region->set_shared(true);
  175. return region->laddr().as_ptr();
  176. }
  177. int Process::sys$munmap(void* addr, size_t size)
  178. {
  179. auto* region = region_from_range(LinearAddress((dword)addr), size);
  180. if (!region)
  181. return -EINVAL;
  182. if (!deallocate_region(*region))
  183. return -EINVAL;
  184. return 0;
  185. }
  186. int Process::sys$gethostname(char* buffer, ssize_t size)
  187. {
  188. if (size < 0)
  189. return -EINVAL;
  190. if (!validate_write(buffer, size))
  191. return -EFAULT;
  192. LOCKER(*s_hostname_lock);
  193. if (size < (s_hostname->length() + 1))
  194. return -ENAMETOOLONG;
  195. strcpy(buffer, s_hostname->characters());
  196. return 0;
  197. }
  198. Process* Process::fork(RegisterDump& regs)
  199. {
  200. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copy_ref(), m_executable.copy_ref(), m_tty, this);
  201. if (!child)
  202. return nullptr;
  203. memcpy(child->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  204. child->m_signal_mask = m_signal_mask;
  205. #ifdef FORK_DEBUG
  206. dbgprintf("fork: child=%p\n", child);
  207. #endif
  208. for (auto& region : m_regions) {
  209. #ifdef FORK_DEBUG
  210. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name.characters(), region->laddr().get());
  211. #endif
  212. auto cloned_region = region->clone();
  213. child->m_regions.append(move(cloned_region));
  214. MM.map_region(*child, *child->m_regions.last());
  215. if (region.ptr() == m_display_framebuffer_region.ptr())
  216. child->m_display_framebuffer_region = child->m_regions.last().copy_ref();
  217. }
  218. for (auto gid : m_gids)
  219. child->m_gids.set(gid);
  220. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  221. child->m_tss.ebx = regs.ebx;
  222. child->m_tss.ecx = regs.ecx;
  223. child->m_tss.edx = regs.edx;
  224. child->m_tss.ebp = regs.ebp;
  225. child->m_tss.esp = regs.esp_if_crossRing;
  226. child->m_tss.esi = regs.esi;
  227. child->m_tss.edi = regs.edi;
  228. child->m_tss.eflags = regs.eflags;
  229. child->m_tss.eip = regs.eip;
  230. child->m_tss.cs = regs.cs;
  231. child->m_tss.ds = regs.ds;
  232. child->m_tss.es = regs.es;
  233. child->m_tss.fs = regs.fs;
  234. child->m_tss.gs = regs.gs;
  235. child->m_tss.ss = regs.ss_if_crossRing;
  236. child->m_fpu_state = m_fpu_state;
  237. child->m_has_used_fpu = m_has_used_fpu;
  238. #ifdef FORK_DEBUG
  239. 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);
  240. #endif
  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(String path, Vector<String> arguments, Vector<String> environment)
  258. {
  259. ASSERT(is_ring3());
  260. auto parts = path.split('/');
  261. if (parts.is_empty())
  262. return -ENOENT;
  263. int error;
  264. auto descriptor = VFS::the().open(path, error, 0, 0, cwd_inode());
  265. if (!descriptor) {
  266. ASSERT(error != 0);
  267. return error;
  268. }
  269. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  270. return -EACCES;
  271. if (!descriptor->metadata().size) {
  272. kprintf("exec() of 0-length binaries not supported\n");
  273. return -ENOTIMPL;
  274. }
  275. dword entry_eip = 0;
  276. // FIXME: Is there a race here?
  277. auto old_page_directory = move(m_page_directory);
  278. m_page_directory = PageDirectory::create();
  279. #ifdef MM_DEBUG
  280. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  281. #endif
  282. ProcessPagingScope paging_scope(*this);
  283. auto vmo = VMObject::create_file_backed(descriptor->inode());
  284. vmo->set_name(descriptor->absolute_path());
  285. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "executable", true, false);
  286. // FIXME: Should we consider doing on-demand paging here? Is it actually useful?
  287. bool success = region->page_in();
  288. ASSERT(success);
  289. {
  290. // Okay, here comes the sleight of hand, pay close attention..
  291. auto old_regions = move(m_regions);
  292. ELFLoader loader(region->laddr().as_ptr());
  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.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  298. return laddr.as_ptr();
  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.as_ptr();
  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. set_default_signal_dispositions();
  331. m_signal_mask = 0xffffffff;
  332. m_pending_signals = 0;
  333. for (int 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. if (current == this)
  344. cli();
  345. Scheduler::prepare_to_modify_tss(*this);
  346. m_name = parts.take_last();
  347. dword old_esp0 = m_tss.esp0;
  348. memset(&m_tss, 0, sizeof(m_tss));
  349. m_tss.eflags = 0x0202;
  350. m_tss.eip = entry_eip;
  351. m_tss.cs = 0x1b;
  352. m_tss.ds = 0x23;
  353. m_tss.es = 0x23;
  354. m_tss.fs = 0x23;
  355. m_tss.gs = 0x23;
  356. m_tss.ss = 0x23;
  357. m_tss.cr3 = page_directory().cr3();
  358. make_userspace_stack(move(arguments), move(environment));
  359. m_tss.ss0 = 0x10;
  360. m_tss.esp0 = old_esp0;
  361. m_tss.ss2 = m_pid;
  362. m_executable = descriptor->inode();
  363. if (descriptor->metadata().is_setuid())
  364. m_euid = descriptor->metadata().uid;
  365. if (descriptor->metadata().is_setgid())
  366. m_egid = descriptor->metadata().gid;
  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. void Process::make_userspace_stack(Vector<String> arguments, Vector<String> environment)
  374. {
  375. auto* region = allocate_region(LinearAddress(), default_userspace_stack_size, "stack");
  376. ASSERT(region);
  377. m_stack_top3 = region->laddr().offset(default_userspace_stack_size).get();
  378. m_tss.esp = m_stack_top3;
  379. char* stack_base = (char*)region->laddr().get();
  380. int argc = arguments.size();
  381. char** argv = (char**)stack_base;
  382. char** env = argv + arguments.size() + 1;
  383. char* bufptr = stack_base + (sizeof(char*) * (arguments.size() + 1)) + (sizeof(char*) * (environment.size() + 1));
  384. size_t total_blob_size = 0;
  385. for (auto& a : arguments)
  386. total_blob_size += a.length() + 1;
  387. for (auto& e : environment)
  388. total_blob_size += e.length() + 1;
  389. size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1);
  390. // FIXME: It would be better if this didn't make us panic.
  391. ASSERT((total_blob_size + total_meta_size) < default_userspace_stack_size);
  392. for (int i = 0; i < arguments.size(); ++i) {
  393. argv[i] = bufptr;
  394. memcpy(bufptr, arguments[i].characters(), arguments[i].length());
  395. bufptr += arguments[i].length();
  396. *(bufptr++) = '\0';
  397. }
  398. argv[arguments.size()] = nullptr;
  399. for (int i = 0; i < environment.size(); ++i) {
  400. env[i] = bufptr;
  401. memcpy(bufptr, environment[i].characters(), environment[i].length());
  402. bufptr += environment[i].length();
  403. *(bufptr++) = '\0';
  404. }
  405. env[environment.size()] = nullptr;
  406. // NOTE: The stack needs to be 16-byte aligned.
  407. push_value_on_stack((dword)env);
  408. push_value_on_stack((dword)argv);
  409. push_value_on_stack((dword)argc);
  410. push_value_on_stack(0);
  411. }
  412. int Process::exec(String path, Vector<String> arguments, Vector<String> environment)
  413. {
  414. // The bulk of exec() is done by do_exec(), which ensures that all locals
  415. // are cleaned up by the time we yield-teleport below.
  416. int rc = do_exec(move(path), move(arguments), move(environment));
  417. if (rc < 0)
  418. return rc;
  419. if (current == this) {
  420. Scheduler::yield();
  421. ASSERT_NOT_REACHED();
  422. }
  423. return 0;
  424. }
  425. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  426. {
  427. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  428. // On success, the kernel stack will be lost.
  429. if (!validate_read_str(filename))
  430. return -EFAULT;
  431. if (argv) {
  432. if (!validate_read_typed(argv))
  433. return -EFAULT;
  434. for (size_t i = 0; argv[i]; ++i) {
  435. if (!validate_read_str(argv[i]))
  436. return -EFAULT;
  437. }
  438. }
  439. if (envp) {
  440. if (!validate_read_typed(envp))
  441. return -EFAULT;
  442. for (size_t i = 0; envp[i]; ++i) {
  443. if (!validate_read_str(envp[i]))
  444. return -EFAULT;
  445. }
  446. }
  447. String path(filename);
  448. Vector<String> arguments;
  449. Vector<String> environment;
  450. {
  451. auto parts = path.split('/');
  452. if (argv) {
  453. for (size_t i = 0; argv[i]; ++i) {
  454. arguments.append(argv[i]);
  455. }
  456. } else {
  457. arguments.append(parts.last());
  458. }
  459. if (envp) {
  460. for (size_t i = 0; envp[i]; ++i)
  461. environment.append(envp[i]);
  462. }
  463. }
  464. int rc = exec(move(path), move(arguments), move(environment));
  465. ASSERT(rc < 0); // We should never continue after a successful exec!
  466. return rc;
  467. }
  468. 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)
  469. {
  470. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  471. auto parts = path.split('/');
  472. if (arguments.is_empty()) {
  473. arguments.append(parts.last());
  474. }
  475. RetainPtr<Inode> cwd;
  476. {
  477. InterruptDisabler disabler;
  478. if (auto* parent = Process::from_pid(parent_pid))
  479. cwd = parent->m_cwd.copy_ref();
  480. }
  481. if (!cwd)
  482. cwd = VFS::the().root_inode();
  483. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  484. error = process->exec(path, move(arguments), move(environment));
  485. if (error != 0) {
  486. delete process;
  487. return nullptr;
  488. }
  489. {
  490. InterruptDisabler disabler;
  491. g_processes->prepend(process);
  492. system.nprocess++;
  493. }
  494. #ifdef TASK_DEBUG
  495. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  496. #endif
  497. error = 0;
  498. return process;
  499. }
  500. Process* Process::create_kernel_process(String&& name, void (*e)())
  501. {
  502. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  503. process->m_tss.eip = (dword)e;
  504. if (process->pid() != 0) {
  505. {
  506. InterruptDisabler disabler;
  507. g_processes->prepend(process);
  508. system.nprocess++;
  509. }
  510. #ifdef TASK_DEBUG
  511. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  512. #endif
  513. }
  514. return process;
  515. }
  516. 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)
  517. : m_name(move(name))
  518. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  519. , m_uid(uid)
  520. , m_gid(gid)
  521. , m_euid(uid)
  522. , m_egid(gid)
  523. , m_state(Runnable)
  524. , m_ring(ring)
  525. , m_cwd(move(cwd))
  526. , m_executable(move(executable))
  527. , m_tty(tty)
  528. , m_ppid(ppid)
  529. {
  530. set_default_signal_dispositions();
  531. memset(&m_fpu_state, 0, sizeof(FPUState));
  532. m_gids.set(m_gid);
  533. if (fork_parent) {
  534. m_sid = fork_parent->m_sid;
  535. m_pgid = fork_parent->m_pgid;
  536. } else {
  537. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  538. InterruptDisabler disabler;
  539. if (auto* parent = Process::from_pid(m_ppid)) {
  540. m_sid = parent->m_sid;
  541. m_pgid = parent->m_pgid;
  542. }
  543. }
  544. m_page_directory = PageDirectory::create();
  545. #ifdef MM_DEBUG
  546. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  547. #endif
  548. if (fork_parent) {
  549. m_fds.resize(fork_parent->m_fds.size());
  550. for (int i = 0; i < fork_parent->m_fds.size(); ++i) {
  551. if (!fork_parent->m_fds[i].descriptor)
  552. continue;
  553. #ifdef FORK_DEBUG
  554. 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());
  555. #endif
  556. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  557. m_fds[i].flags = fork_parent->m_fds[i].flags;
  558. }
  559. } else {
  560. m_fds.resize(m_max_open_file_descriptors);
  561. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  562. int error;
  563. m_fds[0].set(device_to_use_as_tty.open(error, O_RDONLY));
  564. m_fds[1].set(device_to_use_as_tty.open(error, O_WRONLY));
  565. m_fds[2].set(device_to_use_as_tty.open(error, O_WRONLY));
  566. }
  567. if (fork_parent)
  568. m_next_region = fork_parent->m_next_region;
  569. else
  570. m_next_region = LinearAddress(0x10000000);
  571. if (fork_parent) {
  572. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  573. } else {
  574. memset(&m_tss, 0, sizeof(m_tss));
  575. // Only IF is set when a process boots.
  576. m_tss.eflags = 0x0202;
  577. word cs, ds, ss;
  578. if (is_ring0()) {
  579. cs = 0x08;
  580. ds = 0x10;
  581. ss = 0x10;
  582. } else {
  583. cs = 0x1b;
  584. ds = 0x23;
  585. ss = 0x23;
  586. }
  587. m_tss.ds = ds;
  588. m_tss.es = ds;
  589. m_tss.fs = ds;
  590. m_tss.gs = ds;
  591. m_tss.ss = ss;
  592. m_tss.cs = cs;
  593. }
  594. m_tss.cr3 = page_directory().cr3();
  595. if (is_ring0()) {
  596. // FIXME: This memory is leaked.
  597. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  598. dword stack_bottom = (dword)kmalloc_eternal(default_kernel_stack_size);
  599. m_stack_top0 = (stack_bottom + default_kernel_stack_size) & 0xffffff8;
  600. m_tss.esp = m_stack_top0;
  601. } else {
  602. // Ring3 processes need a separate stack for Ring0.
  603. m_kernel_stack = kmalloc(default_kernel_stack_size);
  604. m_stack_top0 = ((dword)m_kernel_stack + default_kernel_stack_size) & 0xffffff8;
  605. m_tss.ss0 = 0x10;
  606. m_tss.esp0 = m_stack_top0;
  607. }
  608. if (fork_parent) {
  609. m_sid = fork_parent->m_sid;
  610. m_pgid = fork_parent->m_pgid;
  611. m_umask = fork_parent->m_umask;
  612. }
  613. // HACK: Ring2 SS in the TSS is the current PID.
  614. m_tss.ss2 = m_pid;
  615. m_far_ptr.offset = 0x98765432;
  616. }
  617. Process::~Process()
  618. {
  619. {
  620. InterruptDisabler disabler;
  621. system.nprocess--;
  622. }
  623. if (g_last_fpu_process == this)
  624. g_last_fpu_process = nullptr;
  625. if (selector())
  626. gdt_free_entry(selector());
  627. if (m_kernel_stack) {
  628. kfree(m_kernel_stack);
  629. m_kernel_stack = nullptr;
  630. }
  631. }
  632. void Process::dump_regions()
  633. {
  634. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  635. kprintf("BEGIN END SIZE NAME\n");
  636. for (auto& region : m_regions) {
  637. kprintf("%x -- %x %x %s\n",
  638. region->laddr().get(),
  639. region->laddr().offset(region->size() - 1).get(),
  640. region->size(),
  641. region->name().characters());
  642. }
  643. }
  644. void Process::sys$exit(int status)
  645. {
  646. cli();
  647. #ifdef TASK_DEBUG
  648. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  649. #endif
  650. m_termination_status = status;
  651. m_termination_signal = 0;
  652. die();
  653. ASSERT_NOT_REACHED();
  654. }
  655. void Process::terminate_due_to_signal(byte signal)
  656. {
  657. ASSERT_INTERRUPTS_DISABLED();
  658. ASSERT(signal < 32);
  659. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  660. m_termination_status = 0;
  661. m_termination_signal = signal;
  662. die();
  663. }
  664. void Process::send_signal(byte signal, Process* sender)
  665. {
  666. ASSERT(signal < 32);
  667. if (sender)
  668. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
  669. else
  670. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
  671. InterruptDisabler disabler;
  672. m_pending_signals |= 1 << signal;
  673. }
  674. bool Process::has_unmasked_pending_signals() const
  675. {
  676. return m_pending_signals & m_signal_mask;
  677. }
  678. ShouldUnblockProcess Process::dispatch_one_pending_signal()
  679. {
  680. ASSERT_INTERRUPTS_DISABLED();
  681. dword signal_candidates = m_pending_signals & m_signal_mask;
  682. ASSERT(signal_candidates);
  683. byte signal = 0;
  684. for (; signal < 32; ++signal) {
  685. if (signal_candidates & (1 << signal)) {
  686. break;
  687. }
  688. }
  689. return dispatch_signal(signal);
  690. }
  691. ShouldUnblockProcess Process::dispatch_signal(byte signal)
  692. {
  693. ASSERT_INTERRUPTS_DISABLED();
  694. ASSERT(signal < 32);
  695. dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  696. auto& action = m_signal_action_data[signal];
  697. // FIXME: Implement SA_SIGINFO signal handlers.
  698. ASSERT(!(action.flags & SA_SIGINFO));
  699. // Mark this signal as handled.
  700. m_pending_signals &= ~(1 << signal);
  701. auto handler_laddr = action.handler_or_sigaction;
  702. if (handler_laddr.is_null()) {
  703. // FIXME: Is termination really always the appropriate action?
  704. terminate_due_to_signal(signal);
  705. return ShouldUnblockProcess::No;
  706. }
  707. if (handler_laddr.as_ptr() == SIG_IGN) {
  708. dbgprintf("%s(%u) ignored signal %u\n", name().characters(), pid(), signal);
  709. return ShouldUnblockProcess::Yes;
  710. }
  711. Scheduler::prepare_to_modify_tss(*this);
  712. word ret_cs = m_tss.cs;
  713. dword ret_eip = m_tss.eip;
  714. dword ret_eflags = m_tss.eflags;
  715. bool interrupting_in_kernel = (ret_cs & 3) == 0;
  716. if (interrupting_in_kernel) {
  717. dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), to_string(state()), ret_cs, ret_eip);
  718. ASSERT(is_blocked());
  719. m_tss_to_resume_kernel = m_tss;
  720. #ifdef SIGNAL_DEBUG
  721. dbgprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
  722. #endif
  723. }
  724. ProcessPagingScope paging_scope(*this);
  725. if (interrupting_in_kernel) {
  726. if (!m_signal_stack_user_region) {
  727. m_signal_stack_user_region = allocate_region(LinearAddress(), default_userspace_stack_size, "signal stack (user)");
  728. ASSERT(m_signal_stack_user_region);
  729. m_signal_stack_kernel_region = allocate_region(LinearAddress(), default_userspace_stack_size, "signal stack (kernel)");
  730. ASSERT(m_signal_stack_user_region);
  731. }
  732. m_tss.ss = 0x23;
  733. m_tss.esp = m_signal_stack_user_region->laddr().offset(default_userspace_stack_size).get() & 0xfffffff8;
  734. m_tss.ss0 = 0x10;
  735. m_tss.esp0 = m_signal_stack_kernel_region->laddr().offset(default_userspace_stack_size).get() & 0xfffffff8;
  736. push_value_on_stack(ret_eflags);
  737. push_value_on_stack(ret_cs);
  738. push_value_on_stack(ret_eip);
  739. } else {
  740. push_value_on_stack(ret_cs);
  741. push_value_on_stack(ret_eip);
  742. push_value_on_stack(ret_eflags);
  743. }
  744. // PUSHA
  745. dword old_esp = m_tss.esp;
  746. push_value_on_stack(m_tss.eax);
  747. push_value_on_stack(m_tss.ecx);
  748. push_value_on_stack(m_tss.edx);
  749. push_value_on_stack(m_tss.ebx);
  750. push_value_on_stack(old_esp);
  751. push_value_on_stack(m_tss.ebp);
  752. push_value_on_stack(m_tss.esi);
  753. push_value_on_stack(m_tss.edi);
  754. m_tss.eax = (dword)signal;
  755. m_tss.cs = 0x1b;
  756. m_tss.ds = 0x23;
  757. m_tss.es = 0x23;
  758. m_tss.fs = 0x23;
  759. m_tss.gs = 0x23;
  760. m_tss.eip = handler_laddr.get();
  761. if (m_return_to_ring3_from_signal_trampoline.is_null()) {
  762. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  763. // FIXME: Remap as read-only after setup.
  764. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
  765. m_return_to_ring3_from_signal_trampoline = region->laddr();
  766. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.as_ptr();
  767. *code_ptr++ = 0x61; // popa
  768. *code_ptr++ = 0x9d; // popf
  769. *code_ptr++ = 0xc3; // ret
  770. *code_ptr++ = 0x0f; // ud2
  771. *code_ptr++ = 0x0b;
  772. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  773. *code_ptr++ = 0x61; // popa
  774. *code_ptr++ = 0xb8; // mov eax, <dword>
  775. *(dword*)code_ptr = Syscall::SC_sigreturn;
  776. code_ptr += sizeof(dword);
  777. *code_ptr++ = 0xcd; // int 0x82
  778. *code_ptr++ = 0x82;
  779. *code_ptr++ = 0x0f; // ud2
  780. *code_ptr++ = 0x0b;
  781. // FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
  782. // unmasks the signal so it can be received again? I guess then I would need one trampoline
  783. // per signal number if it's hard-coded, but it's just a few bytes per each.
  784. }
  785. if (interrupting_in_kernel)
  786. push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
  787. else
  788. push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
  789. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  790. set_state(Skip1SchedulerPass);
  791. #ifdef SIGNAL_DEBUG
  792. dbgprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", name().characters(), pid(), to_string(state()), m_tss.cs, m_tss.eip);
  793. #endif
  794. return ShouldUnblockProcess::Yes;
  795. }
  796. void Process::sys$sigreturn()
  797. {
  798. InterruptDisabler disabler;
  799. Scheduler::prepare_to_modify_tss(*this);
  800. m_tss = m_tss_to_resume_kernel;
  801. #ifdef SIGNAL_DEBUG
  802. dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  803. dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
  804. #endif
  805. set_state(Skip1SchedulerPass);
  806. Scheduler::yield();
  807. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  808. ASSERT_NOT_REACHED();
  809. }
  810. void Process::push_value_on_stack(dword value)
  811. {
  812. m_tss.esp -= 4;
  813. dword* stack_ptr = (dword*)m_tss.esp;
  814. *stack_ptr = value;
  815. }
  816. void Process::crash()
  817. {
  818. ASSERT_INTERRUPTS_DISABLED();
  819. ASSERT(state() != Dead);
  820. m_termination_signal = SIGSEGV;
  821. dump_regions();
  822. ASSERT(is_ring3());
  823. die();
  824. ASSERT_NOT_REACHED();
  825. }
  826. Process* Process::from_pid(pid_t pid)
  827. {
  828. ASSERT_INTERRUPTS_DISABLED();
  829. for (auto* process = g_processes->head(); process; process = process->next()) {
  830. if (process->pid() == pid)
  831. return process;
  832. }
  833. return nullptr;
  834. }
  835. FileDescriptor* Process::file_descriptor(int fd)
  836. {
  837. if (fd < 0)
  838. return nullptr;
  839. if (fd < m_fds.size())
  840. return m_fds[fd].descriptor.ptr();
  841. return nullptr;
  842. }
  843. const FileDescriptor* Process::file_descriptor(int fd) const
  844. {
  845. if (fd < 0)
  846. return nullptr;
  847. if (fd < m_fds.size())
  848. return m_fds[fd].descriptor.ptr();
  849. return nullptr;
  850. }
  851. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, ssize_t size)
  852. {
  853. if (size < 0)
  854. return -EINVAL;
  855. if (!validate_write(buffer, size))
  856. return -EFAULT;
  857. auto* descriptor = file_descriptor(fd);
  858. if (!descriptor)
  859. return -EBADF;
  860. return descriptor->get_dir_entries((byte*)buffer, size);
  861. }
  862. int Process::sys$lseek(int fd, off_t offset, int whence)
  863. {
  864. auto* descriptor = file_descriptor(fd);
  865. if (!descriptor)
  866. return -EBADF;
  867. return descriptor->seek(offset, whence);
  868. }
  869. int Process::sys$ttyname_r(int fd, char* buffer, ssize_t size)
  870. {
  871. if (size < 0)
  872. return -EINVAL;
  873. if (!validate_write(buffer, size))
  874. return -EFAULT;
  875. auto* descriptor = file_descriptor(fd);
  876. if (!descriptor)
  877. return -EBADF;
  878. if (!descriptor->is_tty())
  879. return -ENOTTY;
  880. auto tty_name = descriptor->tty()->tty_name();
  881. if (size < tty_name.length() + 1)
  882. return -ERANGE;
  883. strcpy(buffer, tty_name.characters());
  884. return 0;
  885. }
  886. int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size)
  887. {
  888. if (size < 0)
  889. return -EINVAL;
  890. if (!validate_write(buffer, size))
  891. return -EFAULT;
  892. auto* descriptor = file_descriptor(fd);
  893. if (!descriptor)
  894. return -EBADF;
  895. auto* master_pty = descriptor->master_pty();
  896. if (!master_pty)
  897. return -ENOTTY;
  898. auto pts_name = master_pty->pts_name();
  899. if (size < pts_name.length() + 1)
  900. return -ERANGE;
  901. strcpy(buffer, pts_name.characters());
  902. return 0;
  903. }
  904. ssize_t Process::sys$write(int fd, const byte* data, ssize_t size)
  905. {
  906. if (size < 0)
  907. return -EINVAL;
  908. if (!validate_read(data, size))
  909. return -EFAULT;
  910. #ifdef DEBUG_IO
  911. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  912. #endif
  913. auto* descriptor = file_descriptor(fd);
  914. if (!descriptor)
  915. return -EBADF;
  916. ssize_t nwritten = 0;
  917. if (descriptor->is_blocking()) {
  918. while (nwritten < (ssize_t)size) {
  919. #ifdef IO_DEBUG
  920. dbgprintf("while %u < %u\n", nwritten, size);
  921. #endif
  922. if (!descriptor->can_write(*this)) {
  923. #ifdef IO_DEBUG
  924. dbgprintf("block write on %d\n", fd);
  925. #endif
  926. m_blocked_fd = fd;
  927. block(BlockedWrite);
  928. Scheduler::yield();
  929. }
  930. ssize_t rc = descriptor->write(*this, (const byte*)data + nwritten, size - nwritten);
  931. #ifdef IO_DEBUG
  932. dbgprintf(" -> write returned %d\n", rc);
  933. #endif
  934. if (rc < 0) {
  935. // FIXME: Support returning partial nwritten with errno.
  936. ASSERT(nwritten == 0);
  937. return rc;
  938. }
  939. if (rc == 0)
  940. break;
  941. if (has_unmasked_pending_signals()) {
  942. block(BlockedSignal);
  943. Scheduler::yield();
  944. if (nwritten == 0)
  945. return -EINTR;
  946. }
  947. nwritten += rc;
  948. }
  949. } else {
  950. nwritten = descriptor->write(*this, (const byte*)data, size);
  951. }
  952. if (has_unmasked_pending_signals()) {
  953. block(BlockedSignal);
  954. Scheduler::yield();
  955. if (nwritten == 0)
  956. return -EINTR;
  957. }
  958. return nwritten;
  959. }
  960. ssize_t Process::sys$read(int fd, byte* buffer, ssize_t size)
  961. {
  962. if (size < 0)
  963. return -EINVAL;
  964. if (!validate_write(buffer, size))
  965. return -EFAULT;
  966. #ifdef DEBUG_IO
  967. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, buffer, size);
  968. #endif
  969. auto* descriptor = file_descriptor(fd);
  970. if (!descriptor)
  971. return -EBADF;
  972. if (descriptor->is_blocking()) {
  973. if (!descriptor->can_read(*this)) {
  974. m_blocked_fd = fd;
  975. block(BlockedRead);
  976. Scheduler::yield();
  977. if (m_was_interrupted_while_blocked)
  978. return -EINTR;
  979. }
  980. }
  981. return descriptor->read(*this, buffer, size);
  982. }
  983. int Process::sys$close(int fd)
  984. {
  985. auto* descriptor = file_descriptor(fd);
  986. if (!descriptor)
  987. return -EBADF;
  988. int rc = descriptor->close();
  989. m_fds[fd] = { };
  990. return rc;
  991. }
  992. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  993. {
  994. if (!validate_read_str(pathname))
  995. return -EFAULT;
  996. if (buf && !validate_read_typed(buf))
  997. return -EFAULT;
  998. time_t atime;
  999. time_t mtime;
  1000. if (buf) {
  1001. atime = buf->actime;
  1002. mtime = buf->modtime;
  1003. } else {
  1004. auto now = RTC::now();
  1005. mtime = now;
  1006. atime = now;
  1007. }
  1008. return VFS::the().utime(String(pathname), cwd_inode(), atime, mtime);
  1009. }
  1010. int Process::sys$access(const char* pathname, int mode)
  1011. {
  1012. (void) mode;
  1013. if (!validate_read_str(pathname))
  1014. return -EFAULT;
  1015. ASSERT_NOT_REACHED();
  1016. }
  1017. int Process::sys$fcntl(int fd, int cmd, dword arg)
  1018. {
  1019. (void) cmd;
  1020. (void) arg;
  1021. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1022. auto* descriptor = file_descriptor(fd);
  1023. if (!descriptor)
  1024. return -EBADF;
  1025. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1026. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1027. switch (cmd) {
  1028. case F_DUPFD: {
  1029. int arg_fd = (int)arg;
  1030. if (arg_fd < 0)
  1031. return -EINVAL;
  1032. int new_fd = -1;
  1033. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1034. if (!m_fds[i]) {
  1035. new_fd = i;
  1036. break;
  1037. }
  1038. }
  1039. if (new_fd == -1)
  1040. return -EMFILE;
  1041. m_fds[new_fd].set(descriptor);
  1042. break;
  1043. }
  1044. case F_GETFD:
  1045. return m_fds[fd].flags;
  1046. case F_SETFD:
  1047. m_fds[fd].flags = arg;
  1048. break;
  1049. case F_GETFL:
  1050. return descriptor->file_flags();
  1051. case F_SETFL:
  1052. // FIXME: Support changing O_NONBLOCK
  1053. descriptor->set_file_flags(arg);
  1054. break;
  1055. default:
  1056. ASSERT_NOT_REACHED();
  1057. }
  1058. return 0;
  1059. }
  1060. int Process::sys$fstat(int fd, stat* statbuf)
  1061. {
  1062. if (!validate_write_typed(statbuf))
  1063. return -EFAULT;
  1064. auto* descriptor = file_descriptor(fd);
  1065. if (!descriptor)
  1066. return -EBADF;
  1067. return descriptor->fstat(statbuf);
  1068. }
  1069. int Process::sys$lstat(const char* path, stat* statbuf)
  1070. {
  1071. if (!validate_write_typed(statbuf))
  1072. return -EFAULT;
  1073. int error;
  1074. if (!VFS::the().stat(move(path), error, O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf))
  1075. return error;
  1076. return 0;
  1077. }
  1078. int Process::sys$stat(const char* path, stat* statbuf)
  1079. {
  1080. if (!validate_write_typed(statbuf))
  1081. return -EFAULT;
  1082. int error;
  1083. if (!VFS::the().stat(move(path), error, 0, cwd_inode(), *statbuf))
  1084. return error;
  1085. return 0;
  1086. }
  1087. int Process::sys$readlink(const char* path, char* buffer, ssize_t size)
  1088. {
  1089. if (size < 0)
  1090. return -EINVAL;
  1091. if (!validate_read_str(path))
  1092. return -EFAULT;
  1093. if (!validate_write(buffer, size))
  1094. return -EFAULT;
  1095. int error;
  1096. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, 0, cwd_inode());
  1097. if (!descriptor)
  1098. return error;
  1099. if (!descriptor->metadata().is_symlink())
  1100. return -EINVAL;
  1101. auto contents = descriptor->read_entire_file(*this);
  1102. if (!contents)
  1103. return -EIO; // FIXME: Get a more detailed error from VFS.
  1104. memcpy(buffer, contents.pointer(), min(size, (ssize_t)contents.size()));
  1105. if (contents.size() + 1 < size)
  1106. buffer[contents.size()] = '\0';
  1107. return 0;
  1108. }
  1109. int Process::sys$chdir(const char* path)
  1110. {
  1111. if (!validate_read_str(path))
  1112. return -EFAULT;
  1113. int error;
  1114. auto descriptor = VFS::the().open(path, error, 0, 0, cwd_inode());
  1115. if (!descriptor)
  1116. return error;
  1117. if (!descriptor->is_directory())
  1118. return -ENOTDIR;
  1119. m_cwd = descriptor->inode();
  1120. return 0;
  1121. }
  1122. int Process::sys$getcwd(char* buffer, ssize_t size)
  1123. {
  1124. if (size < 0)
  1125. return -EINVAL;
  1126. if (!validate_write(buffer, size))
  1127. return -EFAULT;
  1128. auto path = VFS::the().absolute_path(cwd_inode());
  1129. if (path.is_null())
  1130. return -EINVAL;
  1131. if (size < path.length() + 1)
  1132. return -ERANGE;
  1133. strcpy(buffer, path.characters());
  1134. return 0;
  1135. }
  1136. size_t Process::number_of_open_file_descriptors() const
  1137. {
  1138. size_t count = 0;
  1139. for (auto& descriptor : m_fds) {
  1140. if (descriptor)
  1141. ++count;
  1142. }
  1143. return count;
  1144. }
  1145. int Process::sys$open(const char* path, int options, mode_t mode)
  1146. {
  1147. #ifdef DEBUG_IO
  1148. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1149. #endif
  1150. if (!validate_read_str(path))
  1151. return -EFAULT;
  1152. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1153. return -EMFILE;
  1154. int error = -EWHYTHO;
  1155. auto descriptor = VFS::the().open(path, error, options, mode & ~umask(), cwd_inode());
  1156. if (!descriptor)
  1157. return error;
  1158. if (options & O_DIRECTORY && !descriptor->is_directory())
  1159. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1160. if (options & O_NONBLOCK)
  1161. descriptor->set_blocking(false);
  1162. int fd = 0;
  1163. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1164. if (!m_fds[fd])
  1165. break;
  1166. }
  1167. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1168. m_fds[fd].set(move(descriptor), flags);
  1169. return fd;
  1170. }
  1171. int Process::alloc_fd()
  1172. {
  1173. int fd = -1;
  1174. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1175. if (!m_fds[i]) {
  1176. fd = i;
  1177. break;
  1178. }
  1179. }
  1180. return fd;
  1181. }
  1182. int Process::sys$pipe(int pipefd[2])
  1183. {
  1184. if (!validate_write_typed(pipefd))
  1185. return -EFAULT;
  1186. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1187. return -EMFILE;
  1188. auto fifo = FIFO::create();
  1189. int reader_fd = alloc_fd();
  1190. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1191. pipefd[0] = reader_fd;
  1192. int writer_fd = alloc_fd();
  1193. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1194. pipefd[1] = writer_fd;
  1195. return 0;
  1196. }
  1197. int Process::sys$killpg(int pgrp, int signum)
  1198. {
  1199. if (signum < 1 || signum >= 32)
  1200. return -EINVAL;
  1201. (void) pgrp;
  1202. ASSERT_NOT_REACHED();
  1203. }
  1204. int Process::sys$setuid(uid_t uid)
  1205. {
  1206. if (uid != m_uid && !is_superuser())
  1207. return -EPERM;
  1208. m_uid = uid;
  1209. m_euid = uid;
  1210. return 0;
  1211. }
  1212. int Process::sys$setgid(gid_t gid)
  1213. {
  1214. if (gid != m_gid && !is_superuser())
  1215. return -EPERM;
  1216. m_gid = gid;
  1217. m_egid = gid;
  1218. return 0;
  1219. }
  1220. unsigned Process::sys$alarm(unsigned seconds)
  1221. {
  1222. (void) seconds;
  1223. ASSERT_NOT_REACHED();
  1224. }
  1225. int Process::sys$uname(utsname* buf)
  1226. {
  1227. if (!validate_write_typed(buf))
  1228. return -EFAULT;
  1229. strcpy(buf->sysname, "Serenity");
  1230. strcpy(buf->release, "1.0-dev");
  1231. strcpy(buf->version, "FIXME");
  1232. strcpy(buf->machine, "i386");
  1233. LOCKER(*s_hostname_lock);
  1234. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  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. Process* peer = nullptr;
  1258. {
  1259. InterruptDisabler disabler;
  1260. peer = Process::from_pid(pid);
  1261. }
  1262. if (!peer)
  1263. return -ESRCH;
  1264. peer->send_signal(signal, this);
  1265. return 0;
  1266. }
  1267. int Process::sys$usleep(useconds_t usec)
  1268. {
  1269. if (!usec)
  1270. return 0;
  1271. sleep(usec / 1000);
  1272. if (m_wakeup_time > system.uptime) {
  1273. ASSERT(m_was_interrupted_while_blocked);
  1274. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1275. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1276. }
  1277. return 0;
  1278. }
  1279. int Process::sys$sleep(unsigned seconds)
  1280. {
  1281. if (!seconds)
  1282. return 0;
  1283. sleep(seconds * TICKS_PER_SECOND);
  1284. if (m_wakeup_time > system.uptime) {
  1285. ASSERT(m_was_interrupted_while_blocked);
  1286. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1287. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1288. }
  1289. return 0;
  1290. }
  1291. int Process::sys$gettimeofday(timeval* tv)
  1292. {
  1293. if (!validate_write_typed(tv))
  1294. return -EFAULT;
  1295. auto now = RTC::now();
  1296. tv->tv_sec = now;
  1297. tv->tv_usec = PIT::ticks_since_boot() % 1000;
  1298. return 0;
  1299. }
  1300. uid_t Process::sys$getuid()
  1301. {
  1302. return m_uid;
  1303. }
  1304. gid_t Process::sys$getgid()
  1305. {
  1306. return m_gid;
  1307. }
  1308. uid_t Process::sys$geteuid()
  1309. {
  1310. return m_euid;
  1311. }
  1312. gid_t Process::sys$getegid()
  1313. {
  1314. return m_egid;
  1315. }
  1316. pid_t Process::sys$getpid()
  1317. {
  1318. return m_pid;
  1319. }
  1320. pid_t Process::sys$getppid()
  1321. {
  1322. return m_ppid;
  1323. }
  1324. mode_t Process::sys$umask(mode_t mask)
  1325. {
  1326. auto old_mask = m_umask;
  1327. m_umask = mask & 0777;
  1328. return old_mask;
  1329. }
  1330. int Process::reap(Process& process)
  1331. {
  1332. InterruptDisabler disabler;
  1333. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1334. if (process.ppid()) {
  1335. auto* parent = Process::from_pid(process.ppid());
  1336. if (parent) {
  1337. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1338. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1339. }
  1340. }
  1341. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1342. ASSERT(process.state() == Dead);
  1343. g_processes->remove(&process);
  1344. delete &process;
  1345. return exit_status;
  1346. }
  1347. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1348. {
  1349. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1350. // FIXME: Respect options
  1351. (void) options;
  1352. if (wstatus)
  1353. if (!validate_write_typed(wstatus))
  1354. return -EFAULT;
  1355. int dummy_wstatus;
  1356. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1357. {
  1358. InterruptDisabler disabler;
  1359. if (waitee != -1 && !Process::from_pid(waitee))
  1360. return -ECHILD;
  1361. }
  1362. if (options & WNOHANG) {
  1363. if (waitee == -1) {
  1364. pid_t reaped_pid = 0;
  1365. InterruptDisabler disabler;
  1366. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1367. if (process.state() == Dead) {
  1368. reaped_pid = process.pid();
  1369. exit_status = reap(process);
  1370. }
  1371. return true;
  1372. });
  1373. return reaped_pid;
  1374. } else {
  1375. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1376. auto* waitee_process = Process::from_pid(waitee);
  1377. if (!waitee_process)
  1378. return -ECHILD;
  1379. if (waitee_process->state() == Dead) {
  1380. exit_status = reap(*waitee_process);
  1381. return waitee;
  1382. }
  1383. return 0;
  1384. }
  1385. }
  1386. m_waitee_pid = waitee;
  1387. block(BlockedWait);
  1388. Scheduler::yield();
  1389. if (m_was_interrupted_while_blocked)
  1390. return -EINTR;
  1391. Process* waitee_process;
  1392. {
  1393. InterruptDisabler disabler;
  1394. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1395. waitee_process = Process::from_pid(m_waitee_pid);
  1396. }
  1397. ASSERT(waitee_process);
  1398. exit_status = reap(*waitee_process);
  1399. return m_waitee_pid;
  1400. }
  1401. void Process::unblock()
  1402. {
  1403. if (current == this) {
  1404. system.nblocked--;
  1405. m_state = Process::Running;
  1406. return;
  1407. }
  1408. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1409. system.nblocked--;
  1410. m_state = Process::Runnable;
  1411. }
  1412. void Process::block(Process::State new_state)
  1413. {
  1414. if (state() != Process::Running) {
  1415. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, to_string(new_state), state(), to_string(state()));
  1416. }
  1417. ASSERT(state() == Process::Running);
  1418. system.nblocked++;
  1419. m_was_interrupted_while_blocked = false;
  1420. set_state(new_state);
  1421. }
  1422. void block(Process::State state)
  1423. {
  1424. current->block(state);
  1425. Scheduler::yield();
  1426. }
  1427. void sleep(dword ticks)
  1428. {
  1429. ASSERT(current->state() == Process::Running);
  1430. current->set_wakeup_time(system.uptime + ticks);
  1431. current->block(Process::BlockedSleep);
  1432. Scheduler::yield();
  1433. }
  1434. enum class KernelMemoryCheckResult {
  1435. NotInsideKernelMemory,
  1436. AccessGranted,
  1437. AccessDenied
  1438. };
  1439. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1440. {
  1441. auto* kernel_elf_header = (Elf32_Ehdr*)0xf000;
  1442. auto* kernel_program_headers = (Elf32_Phdr*)(0xf000 + kernel_elf_header->e_phoff);
  1443. for (unsigned i = 0; i < kernel_elf_header->e_phnum; ++i) {
  1444. auto& segment = kernel_program_headers[i];
  1445. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1446. continue;
  1447. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1448. continue;
  1449. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1450. return KernelMemoryCheckResult::AccessDenied;
  1451. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1452. return KernelMemoryCheckResult::AccessDenied;
  1453. return KernelMemoryCheckResult::AccessGranted;
  1454. }
  1455. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1456. }
  1457. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1458. {
  1459. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1460. // This code allows access outside of the known used address ranges to get caught.
  1461. auto kmc_result = check_kernel_memory_access(laddr, false);
  1462. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1463. return true;
  1464. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1465. return false;
  1466. if (is_kmalloc_address(laddr.as_ptr()))
  1467. return true;
  1468. return validate_read(laddr.as_ptr(), 1);
  1469. }
  1470. bool Process::validate_read_str(const char* str)
  1471. {
  1472. if (!validate_read(str, 1))
  1473. return false;
  1474. return validate_read(str, strlen(str) + 1);
  1475. }
  1476. bool Process::validate_read(const void* address, ssize_t size) const
  1477. {
  1478. ASSERT(size >= 0);
  1479. LinearAddress first_address((dword)address);
  1480. LinearAddress last_address = first_address.offset(size - 1);
  1481. if (is_ring0()) {
  1482. auto kmc_result = check_kernel_memory_access(first_address, false);
  1483. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1484. return true;
  1485. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1486. return false;
  1487. if (is_kmalloc_address(address))
  1488. return true;
  1489. }
  1490. ASSERT(size);
  1491. if (!size)
  1492. return false;
  1493. if (first_address.page_base() != last_address.page_base()) {
  1494. if (!MM.validate_user_read(*this, last_address))
  1495. return false;
  1496. }
  1497. return MM.validate_user_read(*this, first_address);
  1498. }
  1499. bool Process::validate_write(void* address, ssize_t size) const
  1500. {
  1501. ASSERT(size >= 0);
  1502. LinearAddress first_address((dword)address);
  1503. LinearAddress last_address = first_address.offset(size - 1);
  1504. if (is_ring0()) {
  1505. if (is_kmalloc_address(address))
  1506. return true;
  1507. auto kmc_result = check_kernel_memory_access(first_address, true);
  1508. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1509. return true;
  1510. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1511. return false;
  1512. }
  1513. if (!size)
  1514. return false;
  1515. if (first_address.page_base() != last_address.page_base()) {
  1516. if (!MM.validate_user_write(*this, last_address))
  1517. return false;
  1518. }
  1519. return MM.validate_user_write(*this, last_address);
  1520. }
  1521. pid_t Process::sys$getsid(pid_t pid)
  1522. {
  1523. if (pid == 0)
  1524. return m_sid;
  1525. InterruptDisabler disabler;
  1526. auto* process = Process::from_pid(pid);
  1527. if (!process)
  1528. return -ESRCH;
  1529. if (m_sid != process->m_sid)
  1530. return -EPERM;
  1531. return process->m_sid;
  1532. }
  1533. pid_t Process::sys$setsid()
  1534. {
  1535. InterruptDisabler disabler;
  1536. bool found_process_with_same_pgid_as_my_pid = false;
  1537. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1538. found_process_with_same_pgid_as_my_pid = true;
  1539. return false;
  1540. });
  1541. if (found_process_with_same_pgid_as_my_pid)
  1542. return -EPERM;
  1543. m_sid = m_pid;
  1544. m_pgid = m_pid;
  1545. return m_sid;
  1546. }
  1547. pid_t Process::sys$getpgid(pid_t pid)
  1548. {
  1549. if (pid == 0)
  1550. return m_pgid;
  1551. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1552. auto* process = Process::from_pid(pid);
  1553. if (!process)
  1554. return -ESRCH;
  1555. return process->m_pgid;
  1556. }
  1557. pid_t Process::sys$getpgrp()
  1558. {
  1559. return m_pgid;
  1560. }
  1561. static pid_t get_sid_from_pgid(pid_t pgid)
  1562. {
  1563. InterruptDisabler disabler;
  1564. auto* group_leader = Process::from_pid(pgid);
  1565. if (!group_leader)
  1566. return -1;
  1567. return group_leader->sid();
  1568. }
  1569. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1570. {
  1571. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1572. pid_t pid = specified_pid ? specified_pid : m_pid;
  1573. if (specified_pgid < 0)
  1574. return -EINVAL;
  1575. auto* process = Process::from_pid(pid);
  1576. if (!process)
  1577. return -ESRCH;
  1578. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1579. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1580. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1581. if (current_sid != new_sid) {
  1582. // Can't move a process between sessions.
  1583. return -EPERM;
  1584. }
  1585. // FIXME: There are more EPERM conditions to check for here..
  1586. process->m_pgid = new_pgid;
  1587. return 0;
  1588. }
  1589. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1590. {
  1591. auto* descriptor = file_descriptor(fd);
  1592. if (!descriptor)
  1593. return -EBADF;
  1594. if (descriptor->is_socket() && request == 413) {
  1595. auto* pid = (pid_t*)arg;
  1596. if (!validate_write_typed(pid))
  1597. return -EFAULT;
  1598. *pid = descriptor->socket()->origin_pid();
  1599. return 0;
  1600. }
  1601. if (!descriptor->is_device())
  1602. return -ENOTTY;
  1603. return descriptor->device()->ioctl(*this, request, arg);
  1604. }
  1605. int Process::sys$getdtablesize()
  1606. {
  1607. return m_max_open_file_descriptors;
  1608. }
  1609. int Process::sys$dup(int old_fd)
  1610. {
  1611. auto* descriptor = file_descriptor(old_fd);
  1612. if (!descriptor)
  1613. return -EBADF;
  1614. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1615. return -EMFILE;
  1616. int new_fd = 0;
  1617. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1618. if (!m_fds[new_fd])
  1619. break;
  1620. }
  1621. m_fds[new_fd].set(descriptor);
  1622. return new_fd;
  1623. }
  1624. int Process::sys$dup2(int old_fd, int new_fd)
  1625. {
  1626. auto* descriptor = file_descriptor(old_fd);
  1627. if (!descriptor)
  1628. return -EBADF;
  1629. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1630. return -EMFILE;
  1631. m_fds[new_fd].set(descriptor);
  1632. return new_fd;
  1633. }
  1634. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1635. {
  1636. if (old_set) {
  1637. if (!validate_write_typed(old_set))
  1638. return -EFAULT;
  1639. *old_set = m_signal_mask;
  1640. }
  1641. if (set) {
  1642. if (!validate_read_typed(set))
  1643. return -EFAULT;
  1644. switch (how) {
  1645. case SIG_BLOCK:
  1646. m_signal_mask &= ~(*set);
  1647. break;
  1648. case SIG_UNBLOCK:
  1649. m_signal_mask |= *set;
  1650. break;
  1651. case SIG_SETMASK:
  1652. m_signal_mask = *set;
  1653. break;
  1654. default:
  1655. return -EINVAL;
  1656. }
  1657. }
  1658. return 0;
  1659. }
  1660. int Process::sys$sigpending(sigset_t* set)
  1661. {
  1662. if (!validate_write_typed(set))
  1663. return -EFAULT;
  1664. *set = m_pending_signals;
  1665. return 0;
  1666. }
  1667. void Process::set_default_signal_dispositions()
  1668. {
  1669. // FIXME: Set up all the right default actions. See signal(7).
  1670. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  1671. m_signal_action_data[SIGCHLD].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1672. m_signal_action_data[SIGWINCH].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1673. }
  1674. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1675. {
  1676. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1677. return -EINVAL;
  1678. if (!validate_read_typed(act))
  1679. return -EFAULT;
  1680. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1681. auto& action = m_signal_action_data[signum];
  1682. if (old_act) {
  1683. if (!validate_write_typed(old_act))
  1684. return -EFAULT;
  1685. old_act->sa_flags = action.flags;
  1686. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1687. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1688. }
  1689. action.restorer = LinearAddress((dword)act->sa_restorer);
  1690. action.flags = act->sa_flags;
  1691. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1692. return 0;
  1693. }
  1694. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1695. {
  1696. if (count < 0)
  1697. return -EINVAL;
  1698. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1699. if (!count)
  1700. return m_gids.size();
  1701. if (count != (int)m_gids.size())
  1702. return -EINVAL;
  1703. if (!validate_write_typed(gids, m_gids.size()))
  1704. return -EFAULT;
  1705. size_t i = 0;
  1706. for (auto gid : m_gids)
  1707. gids[i++] = gid;
  1708. return 0;
  1709. }
  1710. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1711. {
  1712. if (count < 0)
  1713. return -EINVAL;
  1714. if (!is_superuser())
  1715. return -EPERM;
  1716. if (count >= MAX_PROCESS_GIDS)
  1717. return -EINVAL;
  1718. if (!validate_read(gids, count))
  1719. return -EFAULT;
  1720. m_gids.clear();
  1721. m_gids.set(m_gid);
  1722. for (int i = 0; i < count; ++i)
  1723. m_gids.set(gids[i]);
  1724. return 0;
  1725. }
  1726. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1727. {
  1728. if (!validate_read_str(pathname))
  1729. return -EFAULT;
  1730. size_t pathname_length = strlen(pathname);
  1731. if (pathname_length == 0)
  1732. return -EINVAL;
  1733. if (pathname_length >= 255)
  1734. return -ENAMETOOLONG;
  1735. return VFS::the().mkdir(String(pathname, pathname_length), mode & ~umask(), cwd_inode());
  1736. }
  1737. clock_t Process::sys$times(tms* times)
  1738. {
  1739. if (!validate_write_typed(times))
  1740. return -EFAULT;
  1741. times->tms_utime = m_ticks_in_user;
  1742. times->tms_stime = m_ticks_in_kernel;
  1743. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1744. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1745. return 0;
  1746. }
  1747. int Process::sys$select(const Syscall::SC_select_params* params)
  1748. {
  1749. if (!validate_read_typed(params))
  1750. return -EFAULT;
  1751. if (params->writefds && !validate_read_typed(params->writefds))
  1752. return -EFAULT;
  1753. if (params->readfds && !validate_read_typed(params->readfds))
  1754. return -EFAULT;
  1755. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1756. return -EFAULT;
  1757. if (params->timeout && !validate_read_typed(params->timeout))
  1758. return -EFAULT;
  1759. int nfds = params->nfds;
  1760. fd_set* writefds = params->writefds;
  1761. fd_set* readfds = params->readfds;
  1762. fd_set* exceptfds = params->exceptfds;
  1763. auto* timeout = params->timeout;
  1764. // FIXME: Implement exceptfds support.
  1765. ASSERT(!exceptfds);
  1766. if (timeout) {
  1767. m_select_timeout = *timeout;
  1768. m_select_has_timeout = true;
  1769. } else {
  1770. m_select_has_timeout = false;
  1771. }
  1772. if (nfds < 0)
  1773. return -EINVAL;
  1774. // FIXME: Return -EINTR if a signal is caught.
  1775. // FIXME: Return -EINVAL if timeout is invalid.
  1776. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1777. if (!set)
  1778. return 0;
  1779. vector.clear_with_capacity();
  1780. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1781. for (int i = 0; i < nfds; ++i) {
  1782. if (bitmap.get(i)) {
  1783. if (!file_descriptor(i))
  1784. return -EBADF;
  1785. vector.append(i);
  1786. }
  1787. }
  1788. return 0;
  1789. };
  1790. int error = 0;
  1791. error = transfer_fds(writefds, m_select_write_fds);
  1792. if (error)
  1793. return error;
  1794. error = transfer_fds(readfds, m_select_read_fds);
  1795. if (error)
  1796. return error;
  1797. #ifdef DEBUG_IO
  1798. 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);
  1799. #endif
  1800. if (!m_wakeup_requested && (!timeout || (timeout->tv_sec || timeout->tv_usec))) {
  1801. block(BlockedSelect);
  1802. Scheduler::yield();
  1803. }
  1804. m_wakeup_requested = false;
  1805. int markedfds = 0;
  1806. if (readfds) {
  1807. memset(readfds, 0, sizeof(fd_set));
  1808. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1809. for (int fd : m_select_read_fds) {
  1810. auto* descriptor = file_descriptor(fd);
  1811. if (!descriptor)
  1812. continue;
  1813. if (descriptor->can_read(*this)) {
  1814. bitmap.set(fd, true);
  1815. ++markedfds;
  1816. }
  1817. }
  1818. }
  1819. if (writefds) {
  1820. memset(writefds, 0, sizeof(fd_set));
  1821. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1822. for (int fd : m_select_write_fds) {
  1823. auto* descriptor = file_descriptor(fd);
  1824. if (!descriptor)
  1825. continue;
  1826. if (descriptor->can_write(*this)) {
  1827. bitmap.set(fd, true);
  1828. ++markedfds;
  1829. }
  1830. }
  1831. }
  1832. return markedfds;
  1833. }
  1834. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1835. {
  1836. if (!validate_read_typed(fds))
  1837. return -EFAULT;
  1838. m_select_write_fds.clear_with_capacity();
  1839. m_select_read_fds.clear_with_capacity();
  1840. for (int i = 0; i < nfds; ++i) {
  1841. if (fds[i].events & POLLIN)
  1842. m_select_read_fds.append(fds[i].fd);
  1843. if (fds[i].events & POLLOUT)
  1844. m_select_write_fds.append(fds[i].fd);
  1845. }
  1846. if (!m_wakeup_requested && timeout < 0) {
  1847. block(BlockedSelect);
  1848. Scheduler::yield();
  1849. }
  1850. m_wakeup_requested = false;
  1851. int fds_with_revents = 0;
  1852. for (int i = 0; i < nfds; ++i) {
  1853. auto* descriptor = file_descriptor(fds[i].fd);
  1854. if (!descriptor) {
  1855. fds[i].revents = POLLNVAL;
  1856. continue;
  1857. }
  1858. fds[i].revents = 0;
  1859. if (fds[i].events & POLLIN && descriptor->can_read(*this))
  1860. fds[i].revents |= POLLIN;
  1861. if (fds[i].events & POLLOUT && descriptor->can_write(*this))
  1862. fds[i].revents |= POLLOUT;
  1863. if (fds[i].revents)
  1864. ++fds_with_revents;
  1865. }
  1866. return fds_with_revents;
  1867. }
  1868. Inode& Process::cwd_inode()
  1869. {
  1870. // FIXME: This is retarded factoring.
  1871. if (!m_cwd)
  1872. m_cwd = VFS::the().root_inode();
  1873. return *m_cwd;
  1874. }
  1875. int Process::sys$link(const char* old_path, const char* new_path)
  1876. {
  1877. if (!validate_read_str(old_path))
  1878. return -EFAULT;
  1879. if (!validate_read_str(new_path))
  1880. return -EFAULT;
  1881. int error;
  1882. if (!VFS::the().link(String(old_path), String(new_path), cwd_inode(), error))
  1883. return error;
  1884. return 0;
  1885. }
  1886. int Process::sys$unlink(const char* pathname)
  1887. {
  1888. if (!validate_read_str(pathname))
  1889. return -EFAULT;
  1890. int error;
  1891. if (!VFS::the().unlink(String(pathname), cwd_inode(), error))
  1892. return error;
  1893. return 0;
  1894. }
  1895. int Process::sys$rmdir(const char* pathname)
  1896. {
  1897. if (!validate_read_str(pathname))
  1898. return -EFAULT;
  1899. int error;
  1900. if (!VFS::the().rmdir(String(pathname), cwd_inode(), error))
  1901. return error;
  1902. return 0;
  1903. }
  1904. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1905. {
  1906. if (!validate_write_typed(lsw))
  1907. return -EFAULT;
  1908. if (!validate_write_typed(msw))
  1909. return -EFAULT;
  1910. read_tsc(*lsw, *msw);
  1911. return 0;
  1912. }
  1913. int Process::sys$chmod(const char* pathname, mode_t mode)
  1914. {
  1915. if (!validate_read_str(pathname))
  1916. return -EFAULT;
  1917. return VFS::the().chmod(String(pathname), mode, cwd_inode());
  1918. }
  1919. void Process::finalize()
  1920. {
  1921. ASSERT(current == g_finalizer);
  1922. m_fds.clear();
  1923. m_tty = nullptr;
  1924. disown_all_shared_buffers();
  1925. {
  1926. InterruptDisabler disabler;
  1927. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1928. parent_process->send_signal(SIGCHLD, this);
  1929. }
  1930. }
  1931. set_state(Dead);
  1932. }
  1933. void Process::die()
  1934. {
  1935. set_state(Dying);
  1936. if (!Scheduler::is_active())
  1937. Scheduler::pick_next_and_switch_now();
  1938. }
  1939. size_t Process::amount_virtual() const
  1940. {
  1941. size_t amount = 0;
  1942. for (auto& region : m_regions) {
  1943. amount += region->size();
  1944. }
  1945. return amount;
  1946. }
  1947. size_t Process::amount_resident() const
  1948. {
  1949. // FIXME: This will double count if multiple regions use the same physical page.
  1950. size_t amount = 0;
  1951. for (auto& region : m_regions) {
  1952. amount += region->amount_resident();
  1953. }
  1954. return amount;
  1955. }
  1956. size_t Process::amount_shared() const
  1957. {
  1958. // FIXME: This will double count if multiple regions use the same physical page.
  1959. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1960. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1961. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1962. size_t amount = 0;
  1963. for (auto& region : m_regions) {
  1964. amount += region->amount_shared();
  1965. }
  1966. return amount;
  1967. }
  1968. void Process::finalize_dying_processes()
  1969. {
  1970. Vector<Process*> dying_processes;
  1971. {
  1972. InterruptDisabler disabler;
  1973. dying_processes.ensure_capacity(system.nprocess);
  1974. for (auto* process = g_processes->head(); process; process = process->next()) {
  1975. if (process->state() == Process::Dying)
  1976. dying_processes.append(process);
  1977. }
  1978. }
  1979. for (auto* process : dying_processes)
  1980. process->finalize();
  1981. }
  1982. bool Process::tick()
  1983. {
  1984. ++m_ticks;
  1985. if (tss().cs & 3)
  1986. ++m_ticks_in_user;
  1987. else
  1988. ++m_ticks_in_kernel;
  1989. return --m_ticks_left;
  1990. }
  1991. int Process::sys$socket(int domain, int type, int protocol)
  1992. {
  1993. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1994. return -EMFILE;
  1995. int fd = 0;
  1996. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1997. if (!m_fds[fd])
  1998. break;
  1999. }
  2000. int error;
  2001. auto socket = Socket::create(domain, type, protocol, error);
  2002. if (!socket)
  2003. return error;
  2004. auto descriptor = FileDescriptor::create(move(socket));
  2005. unsigned flags = 0;
  2006. if (type & SOCK_CLOEXEC)
  2007. flags |= FD_CLOEXEC;
  2008. if (type & SOCK_NONBLOCK)
  2009. descriptor->set_blocking(false);
  2010. m_fds[fd].set(move(descriptor), flags);
  2011. return fd;
  2012. }
  2013. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2014. {
  2015. if (!validate_read(address, address_length))
  2016. return -EFAULT;
  2017. auto* descriptor = file_descriptor(sockfd);
  2018. if (!descriptor)
  2019. return -EBADF;
  2020. if (!descriptor->is_socket())
  2021. return -ENOTSOCK;
  2022. auto& socket = *descriptor->socket();
  2023. int error;
  2024. if (!socket.bind(address, address_length, error))
  2025. return error;
  2026. return 0;
  2027. }
  2028. int Process::sys$listen(int sockfd, int backlog)
  2029. {
  2030. auto* descriptor = file_descriptor(sockfd);
  2031. if (!descriptor)
  2032. return -EBADF;
  2033. if (!descriptor->is_socket())
  2034. return -ENOTSOCK;
  2035. auto& socket = *descriptor->socket();
  2036. int error;
  2037. if (!socket.listen(backlog, error))
  2038. return error;
  2039. descriptor->set_socket_role(SocketRole::Listener);
  2040. return 0;
  2041. }
  2042. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  2043. {
  2044. if (!validate_write_typed(address_size))
  2045. return -EFAULT;
  2046. if (!validate_write(address, *address_size))
  2047. return -EFAULT;
  2048. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2049. return -EMFILE;
  2050. int accepted_socket_fd = 0;
  2051. for (; accepted_socket_fd < (int)m_max_open_file_descriptors; ++accepted_socket_fd) {
  2052. if (!m_fds[accepted_socket_fd])
  2053. break;
  2054. }
  2055. auto* accepting_socket_descriptor = file_descriptor(accepting_socket_fd);
  2056. if (!accepting_socket_descriptor)
  2057. return -EBADF;
  2058. if (!accepting_socket_descriptor->is_socket())
  2059. return -ENOTSOCK;
  2060. auto& socket = *accepting_socket_descriptor->socket();
  2061. if (!socket.can_accept()) {
  2062. ASSERT(!accepting_socket_descriptor->is_blocking());
  2063. return -EAGAIN;
  2064. }
  2065. auto accepted_socket = socket.accept();
  2066. ASSERT(accepted_socket);
  2067. bool success = accepted_socket->get_address(address, address_size);
  2068. ASSERT(success);
  2069. auto accepted_socket_descriptor = FileDescriptor::create(move(accepted_socket), SocketRole::Accepted);
  2070. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2071. // I'm not sure if this matches other systems but it makes sense to me.
  2072. accepted_socket_descriptor->set_blocking(accepting_socket_descriptor->is_blocking());
  2073. m_fds[accepted_socket_fd].set(move(accepted_socket_descriptor), m_fds[accepting_socket_fd].flags);
  2074. return accepted_socket_fd;
  2075. }
  2076. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2077. {
  2078. if (!validate_read(address, address_size))
  2079. return -EFAULT;
  2080. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2081. return -EMFILE;
  2082. int fd = 0;
  2083. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2084. if (!m_fds[fd])
  2085. break;
  2086. }
  2087. auto* descriptor = file_descriptor(sockfd);
  2088. if (!descriptor)
  2089. return -EBADF;
  2090. if (!descriptor->is_socket())
  2091. return -ENOTSOCK;
  2092. auto& socket = *descriptor->socket();
  2093. int error;
  2094. if (!socket.connect(address, address_size, error))
  2095. return error;
  2096. descriptor->set_socket_role(SocketRole::Connected);
  2097. return 0;
  2098. }
  2099. bool Process::wait_for_connect(Socket& socket, int& error)
  2100. {
  2101. if (socket.is_connected())
  2102. return true;
  2103. m_blocked_connecting_socket = socket;
  2104. block(BlockedConnect);
  2105. Scheduler::yield();
  2106. m_blocked_connecting_socket = nullptr;
  2107. if (!socket.is_connected()) {
  2108. error = -ECONNREFUSED;
  2109. return false;
  2110. }
  2111. return true;
  2112. }
  2113. struct SharedBuffer {
  2114. SharedBuffer(pid_t pid1, pid_t pid2, size_t size)
  2115. : m_pid1(pid1)
  2116. , m_pid2(pid2)
  2117. , m_vmo(VMObject::create_anonymous(size))
  2118. {
  2119. ASSERT(pid1 != pid2);
  2120. }
  2121. void* retain(Process& process)
  2122. {
  2123. if (m_pid1 == process.pid()) {
  2124. ++m_pid1_retain_count;
  2125. if (!m_pid1_region) {
  2126. m_pid1_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2127. m_pid1_region->set_shared(true);
  2128. }
  2129. return m_pid1_region->laddr().as_ptr();
  2130. } else if (m_pid2 == process.pid()) {
  2131. ++m_pid2_retain_count;
  2132. if (!m_pid2_region) {
  2133. m_pid2_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2134. m_pid2_region->set_shared(true);
  2135. }
  2136. return m_pid2_region->laddr().as_ptr();
  2137. }
  2138. return nullptr;
  2139. }
  2140. void release(Process& process)
  2141. {
  2142. if (m_pid1 == process.pid()) {
  2143. ASSERT(m_pid1_retain_count);
  2144. --m_pid1_retain_count;
  2145. if (!m_pid1_retain_count) {
  2146. if (m_pid1_region)
  2147. process.deallocate_region(*m_pid1_region);
  2148. m_pid1_region = nullptr;
  2149. }
  2150. destroy_if_unused();
  2151. } else if (m_pid2 == process.pid()) {
  2152. ASSERT(m_pid2_retain_count);
  2153. --m_pid2_retain_count;
  2154. if (!m_pid2_retain_count) {
  2155. if (m_pid2_region)
  2156. process.deallocate_region(*m_pid2_region);
  2157. m_pid2_region = nullptr;
  2158. }
  2159. destroy_if_unused();
  2160. }
  2161. }
  2162. void disown(pid_t pid)
  2163. {
  2164. if (m_pid1 == pid) {
  2165. m_pid1 = 0;
  2166. m_pid1_retain_count = 0;
  2167. destroy_if_unused();
  2168. } else if (m_pid2 == pid) {
  2169. m_pid2 = 0;
  2170. m_pid2_retain_count = 0;
  2171. destroy_if_unused();
  2172. }
  2173. }
  2174. pid_t pid1() const { return m_pid1; }
  2175. pid_t pid2() const { return m_pid2; }
  2176. unsigned pid1_retain_count() const { return m_pid1_retain_count; }
  2177. unsigned pid2_retain_count() const { return m_pid2_retain_count; }
  2178. size_t size() const { return m_vmo->size(); }
  2179. void destroy_if_unused();
  2180. int m_shared_buffer_id { -1 };
  2181. pid_t m_pid1;
  2182. pid_t m_pid2;
  2183. unsigned m_pid1_retain_count { 1 };
  2184. unsigned m_pid2_retain_count { 0 };
  2185. Region* m_pid1_region { nullptr };
  2186. Region* m_pid2_region { nullptr };
  2187. Retained<VMObject> m_vmo;
  2188. };
  2189. static int s_next_shared_buffer_id;
  2190. Lockable<HashMap<int, OwnPtr<SharedBuffer>>>& shared_buffers()
  2191. {
  2192. static Lockable<HashMap<int, OwnPtr<SharedBuffer>>>* map;
  2193. if (!map)
  2194. map = new Lockable<HashMap<int, OwnPtr<SharedBuffer>>>;
  2195. return *map;
  2196. }
  2197. void SharedBuffer::destroy_if_unused()
  2198. {
  2199. if (!m_pid1_retain_count && !m_pid2_retain_count) {
  2200. LOCKER(shared_buffers().lock());
  2201. #ifdef SHARED_BUFFER_DEBUG
  2202. dbgprintf("Destroying unused SharedBuffer{%p} id: %d (pid1: %d, pid2: %d)\n", this, m_shared_buffer_id, m_pid1, m_pid2);
  2203. #endif
  2204. size_t count_before = shared_buffers().resource().size();
  2205. shared_buffers().resource().remove(m_shared_buffer_id);
  2206. ASSERT(count_before != shared_buffers().resource().size());
  2207. }
  2208. }
  2209. void Process::disown_all_shared_buffers()
  2210. {
  2211. LOCKER(shared_buffers().lock());
  2212. Vector<SharedBuffer*> buffers_to_disown;
  2213. for (auto& it : shared_buffers().resource())
  2214. buffers_to_disown.append(it.value.ptr());
  2215. for (auto* shared_buffer : buffers_to_disown)
  2216. shared_buffer->disown(m_pid);
  2217. }
  2218. int Process::sys$create_shared_buffer(pid_t peer_pid, size_t size, void** buffer)
  2219. {
  2220. if (!size)
  2221. return -EINVAL;
  2222. size = PAGE_ROUND_UP(size);
  2223. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2224. return -EINVAL;
  2225. if (!validate_write_typed(buffer))
  2226. return -EFAULT;
  2227. {
  2228. InterruptDisabler disabler;
  2229. auto* peer = Process::from_pid(peer_pid);
  2230. if (!peer)
  2231. return -ESRCH;
  2232. }
  2233. LOCKER(shared_buffers().lock());
  2234. int shared_buffer_id = ++s_next_shared_buffer_id;
  2235. auto shared_buffer = make<SharedBuffer>(m_pid, peer_pid, size);
  2236. shared_buffer->m_shared_buffer_id = shared_buffer_id;
  2237. ASSERT(shared_buffer->size() >= size);
  2238. shared_buffer->m_pid1_region = allocate_region_with_vmo(LinearAddress(), shared_buffer->size(), shared_buffer->m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2239. shared_buffer->m_pid1_region->set_shared(true);
  2240. *buffer = shared_buffer->m_pid1_region->laddr().as_ptr();
  2241. #ifdef SHARED_BUFFER_DEBUG
  2242. dbgprintf("%s(%u): Created shared buffer %d (%u bytes, vmo is %u) for sharing with %d\n", name().characters(), pid(),shared_buffer_id, size, shared_buffer->size(), peer_pid);
  2243. #endif
  2244. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2245. return shared_buffer_id;
  2246. }
  2247. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2248. {
  2249. LOCKER(shared_buffers().lock());
  2250. auto it = shared_buffers().resource().find(shared_buffer_id);
  2251. if (it == shared_buffers().resource().end())
  2252. return -EINVAL;
  2253. auto& shared_buffer = *(*it).value;
  2254. #ifdef SHARED_BUFFER_DEBUG
  2255. dbgprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2256. #endif
  2257. shared_buffer.release(*this);
  2258. return 0;
  2259. }
  2260. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2261. {
  2262. LOCKER(shared_buffers().lock());
  2263. auto it = shared_buffers().resource().find(shared_buffer_id);
  2264. if (it == shared_buffers().resource().end())
  2265. return (void*)-EINVAL;
  2266. auto& shared_buffer = *(*it).value;
  2267. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2268. return (void*)-EINVAL;
  2269. #ifdef SHARED_BUFFER_DEBUG
  2270. dbgprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2271. #endif
  2272. return shared_buffer.retain(*this);
  2273. }