Process.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537
  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. error = inode.set_atime(atime);
  1023. if (error)
  1024. return error;
  1025. error = inode.set_mtime(mtime);
  1026. return error;
  1027. }
  1028. int Process::sys$access(const char* pathname, int mode)
  1029. {
  1030. (void) mode;
  1031. if (!validate_read_str(pathname))
  1032. return -EFAULT;
  1033. ASSERT_NOT_REACHED();
  1034. }
  1035. int Process::sys$fcntl(int fd, int cmd, dword arg)
  1036. {
  1037. (void) cmd;
  1038. (void) arg;
  1039. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1040. auto* descriptor = file_descriptor(fd);
  1041. if (!descriptor)
  1042. return -EBADF;
  1043. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1044. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1045. switch (cmd) {
  1046. case F_DUPFD: {
  1047. int arg_fd = (int)arg;
  1048. if (arg_fd < 0)
  1049. return -EINVAL;
  1050. int new_fd = -1;
  1051. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1052. if (!m_fds[i]) {
  1053. new_fd = i;
  1054. break;
  1055. }
  1056. }
  1057. if (new_fd == -1)
  1058. return -EMFILE;
  1059. m_fds[new_fd].set(descriptor);
  1060. break;
  1061. }
  1062. case F_GETFD:
  1063. return m_fds[fd].flags;
  1064. case F_SETFD:
  1065. m_fds[fd].flags = arg;
  1066. break;
  1067. case F_GETFL:
  1068. return descriptor->file_flags();
  1069. case F_SETFL:
  1070. // FIXME: Support changing O_NONBLOCK
  1071. descriptor->set_file_flags(arg);
  1072. break;
  1073. default:
  1074. ASSERT_NOT_REACHED();
  1075. }
  1076. return 0;
  1077. }
  1078. int Process::sys$fstat(int fd, stat* statbuf)
  1079. {
  1080. if (!validate_write_typed(statbuf))
  1081. return -EFAULT;
  1082. auto* descriptor = file_descriptor(fd);
  1083. if (!descriptor)
  1084. return -EBADF;
  1085. return descriptor->fstat(statbuf);
  1086. }
  1087. int Process::sys$lstat(const char* path, stat* statbuf)
  1088. {
  1089. if (!validate_write_typed(statbuf))
  1090. return -EFAULT;
  1091. int error;
  1092. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR | O_DONT_OPEN_DEVICE, 0, *cwd_inode());
  1093. if (!descriptor)
  1094. return error;
  1095. return descriptor->fstat(statbuf);
  1096. }
  1097. int Process::sys$stat(const char* path, stat* statbuf)
  1098. {
  1099. if (!validate_write_typed(statbuf))
  1100. return -EFAULT;
  1101. int error;
  1102. auto descriptor = VFS::the().open(move(path), error, O_DONT_OPEN_DEVICE, 0, *cwd_inode());
  1103. if (!descriptor)
  1104. return error;
  1105. return descriptor->fstat(statbuf);
  1106. }
  1107. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1108. {
  1109. if (!validate_read_str(path))
  1110. return -EFAULT;
  1111. if (!validate_write(buffer, size))
  1112. return -EFAULT;
  1113. int error;
  1114. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, 0, *cwd_inode());
  1115. if (!descriptor)
  1116. return error;
  1117. if (!descriptor->metadata().is_symlink())
  1118. return -EINVAL;
  1119. auto contents = descriptor->read_entire_file(*this);
  1120. if (!contents)
  1121. return -EIO; // FIXME: Get a more detailed error from VFS.
  1122. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1123. if (contents.size() + 1 < size)
  1124. buffer[contents.size()] = '\0';
  1125. return 0;
  1126. }
  1127. int Process::sys$chdir(const char* path)
  1128. {
  1129. if (!validate_read_str(path))
  1130. return -EFAULT;
  1131. int error;
  1132. auto descriptor = VFS::the().open(path, error, 0, 0, *cwd_inode());
  1133. if (!descriptor)
  1134. return error;
  1135. if (!descriptor->is_directory())
  1136. return -ENOTDIR;
  1137. m_cwd = descriptor->inode();
  1138. return 0;
  1139. }
  1140. int Process::sys$getcwd(char* buffer, size_t size)
  1141. {
  1142. if (!validate_write(buffer, size))
  1143. return -EFAULT;
  1144. ASSERT(cwd_inode());
  1145. auto path = VFS::the().absolute_path(*cwd_inode());
  1146. if (path.is_null())
  1147. return -EINVAL;
  1148. if (size < path.length() + 1)
  1149. return -ERANGE;
  1150. strcpy(buffer, path.characters());
  1151. return 0;
  1152. }
  1153. size_t Process::number_of_open_file_descriptors() const
  1154. {
  1155. size_t count = 0;
  1156. for (auto& descriptor : m_fds) {
  1157. if (descriptor)
  1158. ++count;
  1159. }
  1160. return count;
  1161. }
  1162. int Process::sys$open(const char* path, int options, mode_t mode)
  1163. {
  1164. #ifdef DEBUG_IO
  1165. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1166. #endif
  1167. if (!validate_read_str(path))
  1168. return -EFAULT;
  1169. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1170. return -EMFILE;
  1171. int error = -EWHYTHO;
  1172. ASSERT(cwd_inode());
  1173. auto descriptor = VFS::the().open(path, error, options, mode, *cwd_inode());
  1174. if (!descriptor)
  1175. return error;
  1176. if (options & O_DIRECTORY && !descriptor->is_directory())
  1177. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1178. if (options & O_NONBLOCK)
  1179. descriptor->set_blocking(false);
  1180. int fd = 0;
  1181. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1182. if (!m_fds[fd])
  1183. break;
  1184. }
  1185. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1186. m_fds[fd].set(move(descriptor), flags);
  1187. return fd;
  1188. }
  1189. int Process::alloc_fd()
  1190. {
  1191. int fd = -1;
  1192. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1193. if (!m_fds[i]) {
  1194. fd = i;
  1195. break;
  1196. }
  1197. }
  1198. return fd;
  1199. }
  1200. int Process::sys$pipe(int pipefd[2])
  1201. {
  1202. if (!validate_write_typed(pipefd))
  1203. return -EFAULT;
  1204. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1205. return -EMFILE;
  1206. auto fifo = FIFO::create();
  1207. int reader_fd = alloc_fd();
  1208. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1209. pipefd[0] = reader_fd;
  1210. int writer_fd = alloc_fd();
  1211. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1212. pipefd[1] = writer_fd;
  1213. return 0;
  1214. }
  1215. int Process::sys$killpg(int pgrp, int signum)
  1216. {
  1217. if (signum < 1 || signum >= 32)
  1218. return -EINVAL;
  1219. (void) pgrp;
  1220. ASSERT_NOT_REACHED();
  1221. }
  1222. int Process::sys$setuid(uid_t)
  1223. {
  1224. ASSERT_NOT_REACHED();
  1225. }
  1226. int Process::sys$setgid(gid_t)
  1227. {
  1228. ASSERT_NOT_REACHED();
  1229. }
  1230. unsigned Process::sys$alarm(unsigned seconds)
  1231. {
  1232. (void) seconds;
  1233. ASSERT_NOT_REACHED();
  1234. }
  1235. int Process::sys$uname(utsname* buf)
  1236. {
  1237. if (!validate_write_typed(buf))
  1238. return -EFAULT;
  1239. strcpy(buf->sysname, "Serenity");
  1240. strcpy(buf->release, "1.0-dev");
  1241. strcpy(buf->version, "FIXME");
  1242. strcpy(buf->machine, "i386");
  1243. LOCKER(*s_hostname_lock);
  1244. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1245. return 0;
  1246. }
  1247. int Process::sys$isatty(int fd)
  1248. {
  1249. auto* descriptor = file_descriptor(fd);
  1250. if (!descriptor)
  1251. return -EBADF;
  1252. if (!descriptor->is_tty())
  1253. return -ENOTTY;
  1254. return 1;
  1255. }
  1256. int Process::sys$kill(pid_t pid, int signal)
  1257. {
  1258. if (pid == 0) {
  1259. // FIXME: Send to same-group processes.
  1260. ASSERT(pid != 0);
  1261. }
  1262. if (pid == -1) {
  1263. // FIXME: Send to all processes.
  1264. ASSERT(pid != -1);
  1265. }
  1266. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1267. Process* peer = nullptr;
  1268. {
  1269. InterruptDisabler disabler;
  1270. peer = Process::from_pid(pid);
  1271. }
  1272. if (!peer)
  1273. return -ESRCH;
  1274. peer->send_signal(signal, this);
  1275. return 0;
  1276. }
  1277. int Process::sys$usleep(useconds_t usec)
  1278. {
  1279. if (!usec)
  1280. return 0;
  1281. sleep(usec / 1000);
  1282. if (m_wakeup_time > system.uptime) {
  1283. ASSERT(m_was_interrupted_while_blocked);
  1284. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1285. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1286. }
  1287. return 0;
  1288. }
  1289. int Process::sys$sleep(unsigned seconds)
  1290. {
  1291. if (!seconds)
  1292. return 0;
  1293. sleep(seconds * TICKS_PER_SECOND);
  1294. if (m_wakeup_time > system.uptime) {
  1295. ASSERT(m_was_interrupted_while_blocked);
  1296. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1297. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1298. }
  1299. return 0;
  1300. }
  1301. int Process::sys$gettimeofday(timeval* tv)
  1302. {
  1303. if (!validate_write_typed(tv))
  1304. return -EFAULT;
  1305. auto now = RTC::now();
  1306. tv->tv_sec = now;
  1307. tv->tv_usec = PIT::ticks_since_boot() % 1000;
  1308. return 0;
  1309. }
  1310. uid_t Process::sys$getuid()
  1311. {
  1312. return m_uid;
  1313. }
  1314. gid_t Process::sys$getgid()
  1315. {
  1316. return m_gid;
  1317. }
  1318. uid_t Process::sys$geteuid()
  1319. {
  1320. return m_euid;
  1321. }
  1322. gid_t Process::sys$getegid()
  1323. {
  1324. return m_egid;
  1325. }
  1326. pid_t Process::sys$getpid()
  1327. {
  1328. return m_pid;
  1329. }
  1330. pid_t Process::sys$getppid()
  1331. {
  1332. return m_ppid;
  1333. }
  1334. mode_t Process::sys$umask(mode_t mask)
  1335. {
  1336. auto old_mask = m_umask;
  1337. m_umask = mask;
  1338. return old_mask;
  1339. }
  1340. int Process::reap(Process& process)
  1341. {
  1342. InterruptDisabler disabler;
  1343. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1344. if (process.ppid()) {
  1345. auto* parent = Process::from_pid(process.ppid());
  1346. if (parent) {
  1347. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1348. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1349. }
  1350. }
  1351. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1352. ASSERT(process.state() == Dead);
  1353. g_processes->remove(&process);
  1354. delete &process;
  1355. return exit_status;
  1356. }
  1357. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1358. {
  1359. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1360. // FIXME: Respect options
  1361. (void) options;
  1362. if (wstatus)
  1363. if (!validate_write_typed(wstatus))
  1364. return -EFAULT;
  1365. int dummy_wstatus;
  1366. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1367. {
  1368. InterruptDisabler disabler;
  1369. if (waitee != -1 && !Process::from_pid(waitee))
  1370. return -ECHILD;
  1371. }
  1372. if (options & WNOHANG) {
  1373. if (waitee == -1) {
  1374. pid_t reaped_pid = 0;
  1375. InterruptDisabler disabler;
  1376. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1377. if (process.state() == Dead) {
  1378. reaped_pid = process.pid();
  1379. exit_status = reap(process);
  1380. }
  1381. return true;
  1382. });
  1383. return reaped_pid;
  1384. } else {
  1385. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1386. auto* waitee_process = Process::from_pid(waitee);
  1387. if (!waitee_process)
  1388. return -ECHILD;
  1389. if (waitee_process->state() == Dead) {
  1390. exit_status = reap(*waitee_process);
  1391. return waitee;
  1392. }
  1393. return 0;
  1394. }
  1395. }
  1396. m_waitee_pid = waitee;
  1397. block(BlockedWait);
  1398. Scheduler::yield();
  1399. if (m_was_interrupted_while_blocked)
  1400. return -EINTR;
  1401. Process* waitee_process;
  1402. {
  1403. InterruptDisabler disabler;
  1404. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1405. waitee_process = Process::from_pid(m_waitee_pid);
  1406. }
  1407. ASSERT(waitee_process);
  1408. exit_status = reap(*waitee_process);
  1409. return m_waitee_pid;
  1410. }
  1411. void Process::unblock()
  1412. {
  1413. if (current == this) {
  1414. system.nblocked--;
  1415. m_state = Process::Running;
  1416. return;
  1417. }
  1418. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1419. system.nblocked--;
  1420. m_state = Process::Runnable;
  1421. }
  1422. void Process::block(Process::State new_state)
  1423. {
  1424. if (state() != Process::Running) {
  1425. 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()));
  1426. }
  1427. ASSERT(state() == Process::Running);
  1428. system.nblocked++;
  1429. m_was_interrupted_while_blocked = false;
  1430. set_state(new_state);
  1431. }
  1432. void block(Process::State state)
  1433. {
  1434. current->block(state);
  1435. Scheduler::yield();
  1436. }
  1437. void sleep(dword ticks)
  1438. {
  1439. ASSERT(current->state() == Process::Running);
  1440. current->set_wakeup_time(system.uptime + ticks);
  1441. current->block(Process::BlockedSleep);
  1442. Scheduler::yield();
  1443. }
  1444. enum class KernelMemoryCheckResult {
  1445. NotInsideKernelMemory,
  1446. AccessGranted,
  1447. AccessDenied
  1448. };
  1449. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1450. {
  1451. auto* kernel_elf_header = (Elf32_Ehdr*)0xf000;
  1452. auto* kernel_program_headers = (Elf32_Phdr*)(0xf000 + kernel_elf_header->e_phoff);
  1453. for (unsigned i = 0; i < kernel_elf_header->e_phnum; ++i) {
  1454. auto& segment = kernel_program_headers[i];
  1455. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1456. continue;
  1457. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1458. continue;
  1459. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1460. return KernelMemoryCheckResult::AccessDenied;
  1461. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1462. return KernelMemoryCheckResult::AccessDenied;
  1463. return KernelMemoryCheckResult::AccessGranted;
  1464. }
  1465. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1466. }
  1467. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1468. {
  1469. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1470. // This code allows access outside of the known used address ranges to get caught.
  1471. auto kmc_result = check_kernel_memory_access(laddr, false);
  1472. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1473. return true;
  1474. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1475. return false;
  1476. if (is_kmalloc_address(laddr.as_ptr()))
  1477. return true;
  1478. return validate_read(laddr.as_ptr(), 1);
  1479. }
  1480. bool Process::validate_read_str(const char* str)
  1481. {
  1482. if (!validate_read(str, 1))
  1483. return false;
  1484. return validate_read(str, strlen(str) + 1);
  1485. }
  1486. bool Process::validate_read(const void* address, size_t size) const
  1487. {
  1488. LinearAddress first_address((dword)address);
  1489. LinearAddress last_address = first_address.offset(size - 1);
  1490. if (is_ring0()) {
  1491. auto kmc_result = check_kernel_memory_access(first_address, false);
  1492. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1493. return true;
  1494. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1495. return false;
  1496. if (is_kmalloc_address(address))
  1497. return true;
  1498. }
  1499. ASSERT(size);
  1500. if (!size)
  1501. return false;
  1502. if (first_address.page_base() != last_address.page_base()) {
  1503. if (!MM.validate_user_read(*this, last_address))
  1504. return false;
  1505. }
  1506. return MM.validate_user_read(*this, first_address);
  1507. }
  1508. bool Process::validate_write(void* address, size_t size) const
  1509. {
  1510. LinearAddress first_address((dword)address);
  1511. LinearAddress last_address = first_address.offset(size - 1);
  1512. if (is_ring0()) {
  1513. if (is_kmalloc_address(address))
  1514. return true;
  1515. auto kmc_result = check_kernel_memory_access(first_address, true);
  1516. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1517. return true;
  1518. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1519. return false;
  1520. }
  1521. if (!size)
  1522. return false;
  1523. if (first_address.page_base() != last_address.page_base()) {
  1524. if (!MM.validate_user_write(*this, last_address))
  1525. return false;
  1526. }
  1527. return MM.validate_user_write(*this, last_address);
  1528. }
  1529. pid_t Process::sys$getsid(pid_t pid)
  1530. {
  1531. if (pid == 0)
  1532. return m_sid;
  1533. InterruptDisabler disabler;
  1534. auto* process = Process::from_pid(pid);
  1535. if (!process)
  1536. return -ESRCH;
  1537. if (m_sid != process->m_sid)
  1538. return -EPERM;
  1539. return process->m_sid;
  1540. }
  1541. pid_t Process::sys$setsid()
  1542. {
  1543. InterruptDisabler disabler;
  1544. bool found_process_with_same_pgid_as_my_pid = false;
  1545. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1546. found_process_with_same_pgid_as_my_pid = true;
  1547. return false;
  1548. });
  1549. if (found_process_with_same_pgid_as_my_pid)
  1550. return -EPERM;
  1551. m_sid = m_pid;
  1552. m_pgid = m_pid;
  1553. return m_sid;
  1554. }
  1555. pid_t Process::sys$getpgid(pid_t pid)
  1556. {
  1557. if (pid == 0)
  1558. return m_pgid;
  1559. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1560. auto* process = Process::from_pid(pid);
  1561. if (!process)
  1562. return -ESRCH;
  1563. return process->m_pgid;
  1564. }
  1565. pid_t Process::sys$getpgrp()
  1566. {
  1567. return m_pgid;
  1568. }
  1569. static pid_t get_sid_from_pgid(pid_t pgid)
  1570. {
  1571. InterruptDisabler disabler;
  1572. auto* group_leader = Process::from_pid(pgid);
  1573. if (!group_leader)
  1574. return -1;
  1575. return group_leader->sid();
  1576. }
  1577. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1578. {
  1579. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1580. pid_t pid = specified_pid ? specified_pid : m_pid;
  1581. if (specified_pgid < 0)
  1582. return -EINVAL;
  1583. auto* process = Process::from_pid(pid);
  1584. if (!process)
  1585. return -ESRCH;
  1586. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1587. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1588. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1589. if (current_sid != new_sid) {
  1590. // Can't move a process between sessions.
  1591. return -EPERM;
  1592. }
  1593. // FIXME: There are more EPERM conditions to check for here..
  1594. process->m_pgid = new_pgid;
  1595. return 0;
  1596. }
  1597. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1598. {
  1599. auto* descriptor = file_descriptor(fd);
  1600. if (!descriptor)
  1601. return -EBADF;
  1602. if (descriptor->is_socket() && request == 413) {
  1603. auto* pid = (pid_t*)arg;
  1604. if (!validate_write_typed(pid))
  1605. return -EFAULT;
  1606. *pid = descriptor->socket()->origin_pid();
  1607. return 0;
  1608. }
  1609. if (!descriptor->is_device())
  1610. return -ENOTTY;
  1611. return descriptor->device()->ioctl(*this, request, arg);
  1612. }
  1613. int Process::sys$getdtablesize()
  1614. {
  1615. return m_max_open_file_descriptors;
  1616. }
  1617. int Process::sys$dup(int old_fd)
  1618. {
  1619. auto* descriptor = file_descriptor(old_fd);
  1620. if (!descriptor)
  1621. return -EBADF;
  1622. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1623. return -EMFILE;
  1624. int new_fd = 0;
  1625. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1626. if (!m_fds[new_fd])
  1627. break;
  1628. }
  1629. m_fds[new_fd].set(descriptor);
  1630. return new_fd;
  1631. }
  1632. int Process::sys$dup2(int old_fd, int new_fd)
  1633. {
  1634. auto* descriptor = file_descriptor(old_fd);
  1635. if (!descriptor)
  1636. return -EBADF;
  1637. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1638. return -EMFILE;
  1639. m_fds[new_fd].set(descriptor);
  1640. return new_fd;
  1641. }
  1642. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1643. {
  1644. if (old_set) {
  1645. if (!validate_read_typed(old_set))
  1646. return -EFAULT;
  1647. *old_set = m_signal_mask;
  1648. }
  1649. if (set) {
  1650. if (!validate_read_typed(set))
  1651. return -EFAULT;
  1652. switch (how) {
  1653. case SIG_BLOCK:
  1654. m_signal_mask &= ~(*set);
  1655. break;
  1656. case SIG_UNBLOCK:
  1657. m_signal_mask |= *set;
  1658. break;
  1659. case SIG_SETMASK:
  1660. m_signal_mask = *set;
  1661. break;
  1662. default:
  1663. return -EINVAL;
  1664. }
  1665. }
  1666. return 0;
  1667. }
  1668. int Process::sys$sigpending(sigset_t* set)
  1669. {
  1670. if (!validate_read_typed(set))
  1671. return -EFAULT;
  1672. *set = m_pending_signals;
  1673. return 0;
  1674. }
  1675. void Process::set_default_signal_dispositions()
  1676. {
  1677. // FIXME: Set up all the right default actions. See signal(7).
  1678. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  1679. m_signal_action_data[SIGCHLD].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1680. m_signal_action_data[SIGWINCH].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1681. }
  1682. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1683. {
  1684. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1685. return -EINVAL;
  1686. if (!validate_read_typed(act))
  1687. return -EFAULT;
  1688. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1689. auto& action = m_signal_action_data[signum];
  1690. if (old_act) {
  1691. if (!validate_write_typed(old_act))
  1692. return -EFAULT;
  1693. old_act->sa_flags = action.flags;
  1694. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1695. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1696. }
  1697. action.restorer = LinearAddress((dword)act->sa_restorer);
  1698. action.flags = act->sa_flags;
  1699. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1700. return 0;
  1701. }
  1702. int Process::sys$getgroups(int count, gid_t* gids)
  1703. {
  1704. if (count < 0)
  1705. return -EINVAL;
  1706. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1707. if (!count)
  1708. return m_gids.size();
  1709. if (count != (int)m_gids.size())
  1710. return -EINVAL;
  1711. if (!validate_write_typed(gids, m_gids.size()))
  1712. return -EFAULT;
  1713. size_t i = 0;
  1714. for (auto gid : m_gids)
  1715. gids[i++] = gid;
  1716. return 0;
  1717. }
  1718. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1719. {
  1720. if (!is_root())
  1721. return -EPERM;
  1722. if (count >= MAX_PROCESS_GIDS)
  1723. return -EINVAL;
  1724. if (!validate_read(gids, count))
  1725. return -EFAULT;
  1726. m_gids.clear();
  1727. m_gids.set(m_gid);
  1728. for (size_t i = 0; i < count; ++i)
  1729. m_gids.set(gids[i]);
  1730. return 0;
  1731. }
  1732. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1733. {
  1734. if (!validate_read_str(pathname))
  1735. return -EFAULT;
  1736. size_t pathname_length = strlen(pathname);
  1737. if (pathname_length == 0)
  1738. return -EINVAL;
  1739. if (pathname_length >= 255)
  1740. return -ENAMETOOLONG;
  1741. int error;
  1742. if (!VFS::the().mkdir(String(pathname, pathname_length), mode, *cwd_inode(), error))
  1743. return error;
  1744. return 0;
  1745. }
  1746. clock_t Process::sys$times(tms* times)
  1747. {
  1748. if (!validate_write_typed(times))
  1749. return -EFAULT;
  1750. times->tms_utime = m_ticks_in_user;
  1751. times->tms_stime = m_ticks_in_kernel;
  1752. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1753. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1754. return 0;
  1755. }
  1756. int Process::sys$select(const Syscall::SC_select_params* params)
  1757. {
  1758. if (!validate_read_typed(params))
  1759. return -EFAULT;
  1760. if (params->writefds && !validate_read_typed(params->writefds))
  1761. return -EFAULT;
  1762. if (params->readfds && !validate_read_typed(params->readfds))
  1763. return -EFAULT;
  1764. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1765. return -EFAULT;
  1766. if (params->timeout && !validate_read_typed(params->timeout))
  1767. return -EFAULT;
  1768. int nfds = params->nfds;
  1769. fd_set* writefds = params->writefds;
  1770. fd_set* readfds = params->readfds;
  1771. fd_set* exceptfds = params->exceptfds;
  1772. auto* timeout = params->timeout;
  1773. // FIXME: Implement exceptfds support.
  1774. ASSERT(!exceptfds);
  1775. if (timeout) {
  1776. m_select_timeout = *timeout;
  1777. m_select_has_timeout = true;
  1778. } else {
  1779. m_select_has_timeout = false;
  1780. }
  1781. if (nfds < 0)
  1782. return -EINVAL;
  1783. // FIXME: Return -EINTR if a signal is caught.
  1784. // FIXME: Return -EINVAL if timeout is invalid.
  1785. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1786. if (!set)
  1787. return 0;
  1788. vector.clear_with_capacity();
  1789. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1790. for (int i = 0; i < nfds; ++i) {
  1791. if (bitmap.get(i)) {
  1792. if (!file_descriptor(i))
  1793. return -EBADF;
  1794. vector.append(i);
  1795. }
  1796. }
  1797. return 0;
  1798. };
  1799. int error = 0;
  1800. error = transfer_fds(writefds, m_select_write_fds);
  1801. if (error)
  1802. return error;
  1803. error = transfer_fds(readfds, m_select_read_fds);
  1804. if (error)
  1805. return error;
  1806. #ifdef DEBUG_IO
  1807. 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);
  1808. #endif
  1809. if (!m_wakeup_requested && (!timeout || (timeout->tv_sec || timeout->tv_usec))) {
  1810. block(BlockedSelect);
  1811. Scheduler::yield();
  1812. }
  1813. m_wakeup_requested = false;
  1814. int markedfds = 0;
  1815. if (readfds) {
  1816. memset(readfds, 0, sizeof(fd_set));
  1817. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1818. for (int fd : m_select_read_fds) {
  1819. auto* descriptor = file_descriptor(fd);
  1820. if (!descriptor)
  1821. continue;
  1822. if (descriptor->can_read(*this)) {
  1823. bitmap.set(fd, true);
  1824. ++markedfds;
  1825. }
  1826. }
  1827. }
  1828. if (writefds) {
  1829. memset(writefds, 0, sizeof(fd_set));
  1830. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1831. for (int fd : m_select_write_fds) {
  1832. auto* descriptor = file_descriptor(fd);
  1833. if (!descriptor)
  1834. continue;
  1835. if (descriptor->can_write(*this)) {
  1836. bitmap.set(fd, true);
  1837. ++markedfds;
  1838. }
  1839. }
  1840. }
  1841. return markedfds;
  1842. }
  1843. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1844. {
  1845. if (!validate_read_typed(fds))
  1846. return -EFAULT;
  1847. m_select_write_fds.clear_with_capacity();
  1848. m_select_read_fds.clear_with_capacity();
  1849. for (int i = 0; i < nfds; ++i) {
  1850. if (fds[i].events & POLLIN)
  1851. m_select_read_fds.append(fds[i].fd);
  1852. if (fds[i].events & POLLOUT)
  1853. m_select_write_fds.append(fds[i].fd);
  1854. }
  1855. if (!m_wakeup_requested && timeout < 0) {
  1856. block(BlockedSelect);
  1857. Scheduler::yield();
  1858. }
  1859. m_wakeup_requested = false;
  1860. int fds_with_revents = 0;
  1861. for (int i = 0; i < nfds; ++i) {
  1862. auto* descriptor = file_descriptor(fds[i].fd);
  1863. if (!descriptor) {
  1864. fds[i].revents = POLLNVAL;
  1865. continue;
  1866. }
  1867. fds[i].revents = 0;
  1868. if (fds[i].events & POLLIN && descriptor->can_read(*this))
  1869. fds[i].revents |= POLLIN;
  1870. if (fds[i].events & POLLOUT && descriptor->can_write(*this))
  1871. fds[i].revents |= POLLOUT;
  1872. if (fds[i].revents)
  1873. ++fds_with_revents;
  1874. }
  1875. return fds_with_revents;
  1876. }
  1877. Inode* Process::cwd_inode()
  1878. {
  1879. // FIXME: This is retarded factoring.
  1880. if (!m_cwd)
  1881. m_cwd = VFS::the().root_inode();
  1882. return m_cwd.ptr();
  1883. }
  1884. int Process::sys$link(const char* old_path, const char* new_path)
  1885. {
  1886. if (!validate_read_str(old_path))
  1887. return -EFAULT;
  1888. if (!validate_read_str(new_path))
  1889. return -EFAULT;
  1890. int error;
  1891. if (!VFS::the().link(String(old_path), String(new_path), *cwd_inode(), error))
  1892. return error;
  1893. return 0;
  1894. }
  1895. int Process::sys$unlink(const char* pathname)
  1896. {
  1897. if (!validate_read_str(pathname))
  1898. return -EFAULT;
  1899. int error;
  1900. if (!VFS::the().unlink(String(pathname), *cwd_inode(), error))
  1901. return error;
  1902. return 0;
  1903. }
  1904. int Process::sys$rmdir(const char* pathname)
  1905. {
  1906. if (!validate_read_str(pathname))
  1907. return -EFAULT;
  1908. int error;
  1909. if (!VFS::the().rmdir(String(pathname), *cwd_inode(), error))
  1910. return error;
  1911. return 0;
  1912. }
  1913. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1914. {
  1915. if (!validate_write_typed(lsw))
  1916. return -EFAULT;
  1917. if (!validate_write_typed(msw))
  1918. return -EFAULT;
  1919. read_tsc(*lsw, *msw);
  1920. return 0;
  1921. }
  1922. int Process::sys$chmod(const char* pathname, mode_t mode)
  1923. {
  1924. if (!validate_read_str(pathname))
  1925. return -EFAULT;
  1926. int error;
  1927. if (!VFS::the().chmod(String(pathname), mode, *cwd_inode(), error))
  1928. return error;
  1929. return 0;
  1930. }
  1931. void Process::finalize()
  1932. {
  1933. ASSERT(current == g_finalizer);
  1934. m_fds.clear();
  1935. m_tty = nullptr;
  1936. disown_all_shared_buffers();
  1937. {
  1938. InterruptDisabler disabler;
  1939. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1940. parent_process->send_signal(SIGCHLD, this);
  1941. }
  1942. }
  1943. set_state(Dead);
  1944. }
  1945. void Process::die()
  1946. {
  1947. set_state(Dying);
  1948. if (!Scheduler::is_active())
  1949. Scheduler::pick_next_and_switch_now();
  1950. }
  1951. size_t Process::amount_virtual() const
  1952. {
  1953. size_t amount = 0;
  1954. for (auto& region : m_regions) {
  1955. amount += region->size();
  1956. }
  1957. return amount;
  1958. }
  1959. size_t Process::amount_resident() const
  1960. {
  1961. // FIXME: This will double count if multiple regions use the same physical page.
  1962. size_t amount = 0;
  1963. for (auto& region : m_regions) {
  1964. amount += region->amount_resident();
  1965. }
  1966. return amount;
  1967. }
  1968. size_t Process::amount_shared() const
  1969. {
  1970. // FIXME: This will double count if multiple regions use the same physical page.
  1971. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1972. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1973. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1974. size_t amount = 0;
  1975. for (auto& region : m_regions) {
  1976. amount += region->amount_shared();
  1977. }
  1978. return amount;
  1979. }
  1980. void Process::finalize_dying_processes()
  1981. {
  1982. Vector<Process*> dying_processes;
  1983. {
  1984. InterruptDisabler disabler;
  1985. dying_processes.ensure_capacity(system.nprocess);
  1986. for (auto* process = g_processes->head(); process; process = process->next()) {
  1987. if (process->state() == Process::Dying)
  1988. dying_processes.append(process);
  1989. }
  1990. }
  1991. for (auto* process : dying_processes)
  1992. process->finalize();
  1993. }
  1994. bool Process::tick()
  1995. {
  1996. ++m_ticks;
  1997. if (tss().cs & 3)
  1998. ++m_ticks_in_user;
  1999. else
  2000. ++m_ticks_in_kernel;
  2001. return --m_ticks_left;
  2002. }
  2003. int Process::sys$socket(int domain, int type, int protocol)
  2004. {
  2005. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2006. return -EMFILE;
  2007. int fd = 0;
  2008. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2009. if (!m_fds[fd])
  2010. break;
  2011. }
  2012. int error;
  2013. auto socket = Socket::create(domain, type, protocol, error);
  2014. if (!socket)
  2015. return error;
  2016. auto descriptor = FileDescriptor::create(move(socket));
  2017. unsigned flags = 0;
  2018. if (type & SOCK_CLOEXEC)
  2019. flags |= FD_CLOEXEC;
  2020. if (type & SOCK_NONBLOCK)
  2021. descriptor->set_blocking(false);
  2022. m_fds[fd].set(move(descriptor), flags);
  2023. return fd;
  2024. }
  2025. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2026. {
  2027. if (!validate_read(address, address_length))
  2028. return -EFAULT;
  2029. auto* descriptor = file_descriptor(sockfd);
  2030. if (!descriptor)
  2031. return -EBADF;
  2032. if (!descriptor->is_socket())
  2033. return -ENOTSOCK;
  2034. auto& socket = *descriptor->socket();
  2035. int error;
  2036. if (!socket.bind(address, address_length, error))
  2037. return error;
  2038. return 0;
  2039. }
  2040. int Process::sys$listen(int sockfd, int backlog)
  2041. {
  2042. auto* descriptor = file_descriptor(sockfd);
  2043. if (!descriptor)
  2044. return -EBADF;
  2045. if (!descriptor->is_socket())
  2046. return -ENOTSOCK;
  2047. auto& socket = *descriptor->socket();
  2048. int error;
  2049. if (!socket.listen(backlog, error))
  2050. return error;
  2051. descriptor->set_socket_role(SocketRole::Listener);
  2052. return 0;
  2053. }
  2054. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  2055. {
  2056. if (!validate_write_typed(address_size))
  2057. return -EFAULT;
  2058. if (!validate_write(address, *address_size))
  2059. return -EFAULT;
  2060. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2061. return -EMFILE;
  2062. int accepted_socket_fd = 0;
  2063. for (; accepted_socket_fd < (int)m_max_open_file_descriptors; ++accepted_socket_fd) {
  2064. if (!m_fds[accepted_socket_fd])
  2065. break;
  2066. }
  2067. auto* accepting_socket_descriptor = file_descriptor(accepting_socket_fd);
  2068. if (!accepting_socket_descriptor)
  2069. return -EBADF;
  2070. if (!accepting_socket_descriptor->is_socket())
  2071. return -ENOTSOCK;
  2072. auto& socket = *accepting_socket_descriptor->socket();
  2073. if (!socket.can_accept()) {
  2074. ASSERT(!accepting_socket_descriptor->is_blocking());
  2075. return -EAGAIN;
  2076. }
  2077. auto accepted_socket = socket.accept();
  2078. ASSERT(accepted_socket);
  2079. bool success = accepted_socket->get_address(address, address_size);
  2080. ASSERT(success);
  2081. auto accepted_socket_descriptor = FileDescriptor::create(move(accepted_socket), SocketRole::Accepted);
  2082. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2083. // I'm not sure if this matches other systems but it makes sense to me.
  2084. accepted_socket_descriptor->set_blocking(accepting_socket_descriptor->is_blocking());
  2085. m_fds[accepted_socket_fd].set(move(accepted_socket_descriptor), m_fds[accepting_socket_fd].flags);
  2086. return accepted_socket_fd;
  2087. }
  2088. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2089. {
  2090. if (!validate_read(address, address_size))
  2091. return -EFAULT;
  2092. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2093. return -EMFILE;
  2094. int fd = 0;
  2095. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2096. if (!m_fds[fd])
  2097. break;
  2098. }
  2099. auto* descriptor = file_descriptor(sockfd);
  2100. if (!descriptor)
  2101. return -EBADF;
  2102. if (!descriptor->is_socket())
  2103. return -ENOTSOCK;
  2104. auto& socket = *descriptor->socket();
  2105. int error;
  2106. if (!socket.connect(address, address_size, error))
  2107. return error;
  2108. descriptor->set_socket_role(SocketRole::Connected);
  2109. return 0;
  2110. }
  2111. bool Process::wait_for_connect(Socket& socket, int& error)
  2112. {
  2113. if (socket.is_connected())
  2114. return true;
  2115. m_blocked_connecting_socket = socket;
  2116. block(BlockedConnect);
  2117. Scheduler::yield();
  2118. m_blocked_connecting_socket = nullptr;
  2119. if (!socket.is_connected()) {
  2120. error = -ECONNREFUSED;
  2121. return false;
  2122. }
  2123. return true;
  2124. }
  2125. struct SharedBuffer {
  2126. SharedBuffer(pid_t pid1, pid_t pid2, size_t size)
  2127. : m_pid1(pid1)
  2128. , m_pid2(pid2)
  2129. , m_vmo(VMObject::create_anonymous(size))
  2130. {
  2131. ASSERT(pid1 != pid2);
  2132. }
  2133. void* retain(Process& process)
  2134. {
  2135. if (m_pid1 == process.pid()) {
  2136. ++m_pid1_retain_count;
  2137. if (!m_pid1_region) {
  2138. m_pid1_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2139. m_pid1_region->set_shared(true);
  2140. }
  2141. return m_pid1_region->laddr().as_ptr();
  2142. } else if (m_pid2 == process.pid()) {
  2143. ++m_pid2_retain_count;
  2144. if (!m_pid2_region) {
  2145. m_pid2_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2146. m_pid2_region->set_shared(true);
  2147. }
  2148. return m_pid2_region->laddr().as_ptr();
  2149. }
  2150. return nullptr;
  2151. }
  2152. void release(Process& process)
  2153. {
  2154. if (m_pid1 == process.pid()) {
  2155. ASSERT(m_pid1_retain_count);
  2156. --m_pid1_retain_count;
  2157. if (!m_pid1_retain_count) {
  2158. if (m_pid1_region)
  2159. process.deallocate_region(*m_pid1_region);
  2160. m_pid1_region = nullptr;
  2161. }
  2162. destroy_if_unused();
  2163. } else if (m_pid2 == process.pid()) {
  2164. ASSERT(m_pid2_retain_count);
  2165. --m_pid2_retain_count;
  2166. if (!m_pid2_retain_count) {
  2167. if (m_pid2_region)
  2168. process.deallocate_region(*m_pid2_region);
  2169. m_pid2_region = nullptr;
  2170. }
  2171. destroy_if_unused();
  2172. }
  2173. }
  2174. void disown(pid_t pid)
  2175. {
  2176. if (m_pid1 == pid) {
  2177. m_pid1 = 0;
  2178. m_pid1_retain_count = 0;
  2179. destroy_if_unused();
  2180. } else if (m_pid2 == pid) {
  2181. m_pid2 = 0;
  2182. m_pid2_retain_count = 0;
  2183. destroy_if_unused();
  2184. }
  2185. }
  2186. pid_t pid1() const { return m_pid1; }
  2187. pid_t pid2() const { return m_pid2; }
  2188. unsigned pid1_retain_count() const { return m_pid1_retain_count; }
  2189. unsigned pid2_retain_count() const { return m_pid2_retain_count; }
  2190. size_t size() const { return m_vmo->size(); }
  2191. void destroy_if_unused();
  2192. int m_shared_buffer_id { -1 };
  2193. pid_t m_pid1;
  2194. pid_t m_pid2;
  2195. unsigned m_pid1_retain_count { 1 };
  2196. unsigned m_pid2_retain_count { 0 };
  2197. Region* m_pid1_region { nullptr };
  2198. Region* m_pid2_region { nullptr };
  2199. RetainPtr<VMObject> m_vmo;
  2200. };
  2201. static int s_next_shared_buffer_id;
  2202. Lockable<HashMap<int, OwnPtr<SharedBuffer>>>& shared_buffers()
  2203. {
  2204. static Lockable<HashMap<int, OwnPtr<SharedBuffer>>>* map;
  2205. if (!map)
  2206. map = new Lockable<HashMap<int, OwnPtr<SharedBuffer>>>;
  2207. return *map;
  2208. }
  2209. void SharedBuffer::destroy_if_unused()
  2210. {
  2211. if (!m_pid1_retain_count && !m_pid2_retain_count) {
  2212. LOCKER(shared_buffers().lock());
  2213. #ifdef SHARED_BUFFER_DEBUG
  2214. dbgprintf("Destroying unused SharedBuffer{%p} id: %d (pid1: %d, pid2: %d)\n", this, m_shared_buffer_id, m_pid1, m_pid2);
  2215. #endif
  2216. size_t count_before = shared_buffers().resource().size();
  2217. shared_buffers().resource().remove(m_shared_buffer_id);
  2218. ASSERT(count_before != shared_buffers().resource().size());
  2219. }
  2220. }
  2221. void Process::disown_all_shared_buffers()
  2222. {
  2223. LOCKER(shared_buffers().lock());
  2224. Vector<SharedBuffer*> buffers_to_disown;
  2225. for (auto& it : shared_buffers().resource())
  2226. buffers_to_disown.append(it.value.ptr());
  2227. for (auto* shared_buffer : buffers_to_disown)
  2228. shared_buffer->disown(m_pid);
  2229. }
  2230. int Process::sys$create_shared_buffer(pid_t peer_pid, size_t size, void** buffer)
  2231. {
  2232. if (!size)
  2233. return -EINVAL;
  2234. size = PAGE_ROUND_UP(size);
  2235. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2236. return -EINVAL;
  2237. if (!validate_write_typed(buffer))
  2238. return -EFAULT;
  2239. {
  2240. InterruptDisabler disabler;
  2241. auto* peer = Process::from_pid(peer_pid);
  2242. if (!peer)
  2243. return -ESRCH;
  2244. }
  2245. LOCKER(shared_buffers().lock());
  2246. int shared_buffer_id = ++s_next_shared_buffer_id;
  2247. auto shared_buffer = make<SharedBuffer>(m_pid, peer_pid, size);
  2248. shared_buffer->m_shared_buffer_id = shared_buffer_id;
  2249. ASSERT(shared_buffer->size() >= size);
  2250. shared_buffer->m_pid1_region = allocate_region_with_vmo(LinearAddress(), shared_buffer->size(), shared_buffer->m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2251. shared_buffer->m_pid1_region->set_shared(true);
  2252. *buffer = shared_buffer->m_pid1_region->laddr().as_ptr();
  2253. #ifdef SHARED_BUFFER_DEBUG
  2254. 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);
  2255. #endif
  2256. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2257. return shared_buffer_id;
  2258. }
  2259. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2260. {
  2261. LOCKER(shared_buffers().lock());
  2262. auto it = shared_buffers().resource().find(shared_buffer_id);
  2263. if (it == shared_buffers().resource().end())
  2264. return -EINVAL;
  2265. auto& shared_buffer = *(*it).value;
  2266. #ifdef SHARED_BUFFER_DEBUG
  2267. dbgprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2268. #endif
  2269. shared_buffer.release(*this);
  2270. return 0;
  2271. }
  2272. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2273. {
  2274. LOCKER(shared_buffers().lock());
  2275. auto it = shared_buffers().resource().find(shared_buffer_id);
  2276. if (it == shared_buffers().resource().end())
  2277. return (void*)-EINVAL;
  2278. auto& shared_buffer = *(*it).value;
  2279. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2280. return (void*)-EINVAL;
  2281. #ifdef SHARED_BUFFER_DEBUG
  2282. dbgprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2283. #endif
  2284. return shared_buffer.retain(*this);
  2285. }