Process.cpp 82 KB

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