Process.cpp 74 KB

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