Process.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735
  1. #include "types.h"
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "StdLib.h"
  5. #include "i386.h"
  6. #include "system.h"
  7. #include <Kernel/FileDescriptor.h>
  8. #include <Kernel/VirtualFileSystem.h>
  9. #include <Kernel/NullDevice.h>
  10. #include "ELFLoader.h"
  11. #include "MemoryManager.h"
  12. #include "i8253.h"
  13. #include "RTC.h"
  14. #include <AK/StdLibExtras.h>
  15. #include <LibC/signal_numbers.h>
  16. #include <LibC/errno_numbers.h>
  17. #include "Syscall.h"
  18. #include "Scheduler.h"
  19. #include "FIFO.h"
  20. #include "KSyms.h"
  21. #include <Kernel/Socket.h>
  22. #include "MasterPTY.h"
  23. #include "elf.h"
  24. #include <AK/StringBuilder.h>
  25. //#define DEBUG_IO
  26. //#define TASK_DEBUG
  27. //#define FORK_DEBUG
  28. //#define SIGNAL_DEBUG
  29. #define MAX_PROCESS_GIDS 32
  30. //#define SHARED_BUFFER_DEBUG
  31. static const dword default_kernel_stack_size = 16384;
  32. static const dword default_userspace_stack_size = 65536;
  33. static pid_t next_pid;
  34. InlineLinkedList<Process>* g_processes;
  35. static String* s_hostname;
  36. static Lock* s_hostname_lock;
  37. CoolGlobals* g_cool_globals;
  38. void Process::initialize()
  39. {
  40. #ifdef COOL_GLOBALS
  41. g_cool_globals = reinterpret_cast<CoolGlobals*>(0x1000);
  42. #endif
  43. next_pid = 0;
  44. g_processes = new InlineLinkedList<Process>;
  45. s_hostname = new String("courage");
  46. s_hostname_lock = new Lock;
  47. Scheduler::initialize();
  48. }
  49. Vector<pid_t> Process::all_pids()
  50. {
  51. Vector<pid_t> pids;
  52. pids.ensure_capacity(system.nprocess);
  53. InterruptDisabler disabler;
  54. for (auto* process = g_processes->head(); process; process = process->next())
  55. pids.append(process->pid());
  56. return pids;
  57. }
  58. Vector<Process*> Process::all_processes()
  59. {
  60. Vector<Process*> processes;
  61. processes.ensure_capacity(system.nprocess);
  62. InterruptDisabler disabler;
  63. for (auto* process = g_processes->head(); process; process = process->next())
  64. processes.append(process);
  65. return processes;
  66. }
  67. bool Process::in_group(gid_t gid) const
  68. {
  69. return m_gids.contains(gid);
  70. }
  71. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  72. {
  73. size = PAGE_ROUND_UP(size);
  74. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  75. if (laddr.is_null()) {
  76. laddr = m_next_region;
  77. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  78. }
  79. laddr.mask(0xfffff000);
  80. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  81. MM.map_region(*this, *m_regions.last());
  82. if (commit)
  83. m_regions.last()->commit();
  84. return m_regions.last().ptr();
  85. }
  86. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  87. {
  88. size = PAGE_ROUND_UP(size);
  89. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  90. if (laddr.is_null()) {
  91. laddr = m_next_region;
  92. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  93. }
  94. laddr.mask(0xfffff000);
  95. m_regions.append(adopt(*new Region(laddr, size, move(inode), move(name), is_readable, is_writable)));
  96. MM.map_region(*this, *m_regions.last());
  97. return m_regions.last().ptr();
  98. }
  99. 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)
  100. {
  101. size = PAGE_ROUND_UP(size);
  102. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  103. if (laddr.is_null()) {
  104. laddr = m_next_region;
  105. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  106. }
  107. laddr.mask(0xfffff000);
  108. offset_in_vmo &= PAGE_MASK;
  109. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  110. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  111. MM.map_region(*this, *m_regions.last());
  112. return m_regions.last().ptr();
  113. }
  114. bool Process::deallocate_region(Region& region)
  115. {
  116. InterruptDisabler disabler;
  117. for (int i = 0; i < m_regions.size(); ++i) {
  118. if (m_regions[i].ptr() == &region) {
  119. MM.unmap_region(region);
  120. m_regions.remove(i);
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  127. {
  128. size = PAGE_ROUND_UP(size);
  129. for (auto& region : m_regions) {
  130. if (region->laddr() == laddr && region->size() == size)
  131. return region.ptr();
  132. }
  133. return nullptr;
  134. }
  135. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  136. {
  137. if (!validate_read_str(name))
  138. return -EFAULT;
  139. auto* region = region_from_range(LinearAddress((dword)addr), size);
  140. if (!region)
  141. return -EINVAL;
  142. region->set_name(String(name));
  143. return 0;
  144. }
  145. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  146. {
  147. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  148. return (void*)-EFAULT;
  149. void* addr = (void*)params->addr;
  150. size_t size = params->size;
  151. int prot = params->prot;
  152. int flags = params->flags;
  153. int fd = params->fd;
  154. off_t offset = params->offset;
  155. if (size == 0)
  156. return (void*)-EINVAL;
  157. if ((dword)addr & ~PAGE_MASK)
  158. return (void*)-EINVAL;
  159. if (flags & MAP_ANONYMOUS) {
  160. auto* region = allocate_region(LinearAddress((dword)addr), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  161. if (!region)
  162. return (void*)-ENOMEM;
  163. if (flags & MAP_SHARED)
  164. region->set_shared(true);
  165. return region->laddr().as_ptr();
  166. }
  167. if (offset & ~PAGE_MASK)
  168. return (void*)-EINVAL;
  169. auto* descriptor = file_descriptor(fd);
  170. if (!descriptor)
  171. return (void*)-EBADF;
  172. if (!descriptor->supports_mmap())
  173. return (void*)-ENODEV;
  174. auto* region = descriptor->mmap(*this, LinearAddress((dword)addr), offset, size, prot);
  175. if (!region)
  176. return (void*)-ENOMEM;
  177. if (flags & MAP_SHARED)
  178. region->set_shared(true);
  179. return region->laddr().as_ptr();
  180. }
  181. int Process::sys$munmap(void* addr, size_t size)
  182. {
  183. auto* region = region_from_range(LinearAddress((dword)addr), size);
  184. if (!region)
  185. return -EINVAL;
  186. if (!deallocate_region(*region))
  187. return -EINVAL;
  188. return 0;
  189. }
  190. int Process::sys$gethostname(char* buffer, ssize_t size)
  191. {
  192. if (size < 0)
  193. return -EINVAL;
  194. if (!validate_write(buffer, size))
  195. return -EFAULT;
  196. LOCKER(*s_hostname_lock);
  197. if (size < (s_hostname->length() + 1))
  198. return -ENAMETOOLONG;
  199. strcpy(buffer, s_hostname->characters());
  200. return 0;
  201. }
  202. Process* Process::fork(RegisterDump& regs)
  203. {
  204. 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);
  205. if (!child)
  206. return nullptr;
  207. memcpy(child->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  208. child->m_signal_mask = m_signal_mask;
  209. #ifdef FORK_DEBUG
  210. dbgprintf("fork: child=%p\n", child);
  211. #endif
  212. for (auto& region : m_regions) {
  213. #ifdef FORK_DEBUG
  214. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name().characters(), region->laddr().get());
  215. #endif
  216. auto cloned_region = region->clone();
  217. child->m_regions.append(move(cloned_region));
  218. MM.map_region(*child, *child->m_regions.last());
  219. if (region.ptr() == m_display_framebuffer_region.ptr())
  220. child->m_display_framebuffer_region = child->m_regions.last().copy_ref();
  221. }
  222. for (auto gid : m_gids)
  223. child->m_gids.set(gid);
  224. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  225. child->m_tss.ebx = regs.ebx;
  226. child->m_tss.ecx = regs.ecx;
  227. child->m_tss.edx = regs.edx;
  228. child->m_tss.ebp = regs.ebp;
  229. child->m_tss.esp = regs.esp_if_crossRing;
  230. child->m_tss.esi = regs.esi;
  231. child->m_tss.edi = regs.edi;
  232. child->m_tss.eflags = regs.eflags;
  233. child->m_tss.eip = regs.eip;
  234. child->m_tss.cs = regs.cs;
  235. child->m_tss.ds = regs.ds;
  236. child->m_tss.es = regs.es;
  237. child->m_tss.fs = regs.fs;
  238. child->m_tss.gs = regs.gs;
  239. child->m_tss.ss = regs.ss_if_crossRing;
  240. child->m_fpu_state = m_fpu_state;
  241. child->m_has_used_fpu = m_has_used_fpu;
  242. #ifdef FORK_DEBUG
  243. 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);
  244. #endif
  245. {
  246. InterruptDisabler disabler;
  247. g_processes->prepend(child);
  248. system.nprocess++;
  249. }
  250. #ifdef TASK_DEBUG
  251. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  252. #endif
  253. return child;
  254. }
  255. pid_t Process::sys$fork(RegisterDump& regs)
  256. {
  257. auto* child = fork(regs);
  258. ASSERT(child);
  259. return child->pid();
  260. }
  261. int Process::do_exec(String path, Vector<String> arguments, Vector<String> environment)
  262. {
  263. ASSERT(is_ring3());
  264. auto parts = path.split('/');
  265. if (parts.is_empty())
  266. return -ENOENT;
  267. int error;
  268. auto descriptor = VFS::the().open(path, error, 0, 0, cwd_inode());
  269. if (!descriptor) {
  270. ASSERT(error != 0);
  271. return error;
  272. }
  273. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  274. return -EACCES;
  275. if (!descriptor->metadata().size) {
  276. kprintf("exec() of 0-length binaries not supported\n");
  277. return -ENOTIMPL;
  278. }
  279. dword entry_eip = 0;
  280. // FIXME: Is there a race here?
  281. auto old_page_directory = move(m_page_directory);
  282. m_page_directory = PageDirectory::create();
  283. #ifdef MM_DEBUG
  284. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  285. #endif
  286. ProcessPagingScope paging_scope(*this);
  287. auto vmo = VMObject::create_file_backed(descriptor->inode());
  288. #if 0
  289. // FIXME: I would like to do this, but it would instantiate all the damn inodes.
  290. vmo->set_name(descriptor->absolute_path());
  291. #else
  292. vmo->set_name("ELF image");
  293. #endif
  294. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "executable", true, false);
  295. // FIXME: Should we consider doing on-demand paging here? Is it actually useful?
  296. bool success = region->page_in();
  297. ASSERT(success);
  298. {
  299. // Okay, here comes the sleight of hand, pay close attention..
  300. auto old_regions = move(m_regions);
  301. ELFLoader loader(region->laddr().as_ptr());
  302. 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) {
  303. ASSERT(size);
  304. ASSERT(alignment == PAGE_SIZE);
  305. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  306. (void) allocate_region_with_vmo(laddr, size, vmo.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  307. return laddr.as_ptr();
  308. };
  309. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  310. ASSERT(size);
  311. ASSERT(alignment == PAGE_SIZE);
  312. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  313. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  314. return laddr.as_ptr();
  315. };
  316. bool success = loader.load();
  317. if (!success) {
  318. m_page_directory = move(old_page_directory);
  319. // FIXME: RAII this somehow instead.
  320. ASSERT(current == this);
  321. MM.enter_process_paging_scope(*this);
  322. m_regions = move(old_regions);
  323. kprintf("sys$execve: Failure loading %s\n", path.characters());
  324. return -ENOEXEC;
  325. }
  326. entry_eip = loader.entry().get();
  327. if (!entry_eip) {
  328. m_page_directory = move(old_page_directory);
  329. // FIXME: RAII this somehow instead.
  330. ASSERT(current == this);
  331. MM.enter_process_paging_scope(*this);
  332. m_regions = move(old_regions);
  333. return -ENOEXEC;
  334. }
  335. }
  336. kfree(m_kernel_stack_for_signal_handler);
  337. m_kernel_stack_for_signal_handler = nullptr;
  338. m_signal_stack_user_region = nullptr;
  339. m_display_framebuffer_region = nullptr;
  340. set_default_signal_dispositions();
  341. m_signal_mask = 0;
  342. m_pending_signals = 0;
  343. for (int i = 0; i < m_fds.size(); ++i) {
  344. auto& daf = m_fds[i];
  345. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  346. daf.descriptor->close();
  347. daf = { };
  348. }
  349. }
  350. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  351. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  352. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  353. if (current == this)
  354. cli();
  355. Scheduler::prepare_to_modify_tss(*this);
  356. m_name = parts.take_last();
  357. dword old_esp0 = m_tss.esp0;
  358. memset(&m_tss, 0, sizeof(m_tss));
  359. m_tss.eflags = 0x0202;
  360. m_tss.eip = entry_eip;
  361. m_tss.cs = 0x1b;
  362. m_tss.ds = 0x23;
  363. m_tss.es = 0x23;
  364. m_tss.fs = 0x23;
  365. m_tss.gs = 0x23;
  366. m_tss.ss = 0x23;
  367. m_tss.cr3 = page_directory().cr3();
  368. make_userspace_stack(move(arguments), move(environment));
  369. m_tss.ss0 = 0x10;
  370. m_tss.esp0 = old_esp0;
  371. m_tss.ss2 = m_pid;
  372. m_executable = descriptor->inode();
  373. if (descriptor->metadata().is_setuid())
  374. m_euid = descriptor->metadata().uid;
  375. if (descriptor->metadata().is_setgid())
  376. m_egid = descriptor->metadata().gid;
  377. #ifdef TASK_DEBUG
  378. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), m_tss.eip);
  379. #endif
  380. set_state(Skip1SchedulerPass);
  381. return 0;
  382. }
  383. void Process::make_userspace_stack(Vector<String> arguments, Vector<String> environment)
  384. {
  385. auto* region = allocate_region(LinearAddress(), default_userspace_stack_size, "stack");
  386. ASSERT(region);
  387. m_stack_top3 = region->laddr().offset(default_userspace_stack_size).get();
  388. m_tss.esp = m_stack_top3;
  389. char* stack_base = (char*)region->laddr().get();
  390. int argc = arguments.size();
  391. char** argv = (char**)stack_base;
  392. char** env = argv + arguments.size() + 1;
  393. char* bufptr = stack_base + (sizeof(char*) * (arguments.size() + 1)) + (sizeof(char*) * (environment.size() + 1));
  394. size_t total_blob_size = 0;
  395. for (auto& a : arguments)
  396. total_blob_size += a.length() + 1;
  397. for (auto& e : environment)
  398. total_blob_size += e.length() + 1;
  399. size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1);
  400. // FIXME: It would be better if this didn't make us panic.
  401. ASSERT((total_blob_size + total_meta_size) < default_userspace_stack_size);
  402. for (int i = 0; i < arguments.size(); ++i) {
  403. argv[i] = bufptr;
  404. memcpy(bufptr, arguments[i].characters(), arguments[i].length());
  405. bufptr += arguments[i].length();
  406. *(bufptr++) = '\0';
  407. }
  408. argv[arguments.size()] = nullptr;
  409. for (int i = 0; i < environment.size(); ++i) {
  410. env[i] = bufptr;
  411. memcpy(bufptr, environment[i].characters(), environment[i].length());
  412. bufptr += environment[i].length();
  413. *(bufptr++) = '\0';
  414. }
  415. env[environment.size()] = nullptr;
  416. // NOTE: The stack needs to be 16-byte aligned.
  417. push_value_on_stack((dword)env);
  418. push_value_on_stack((dword)argv);
  419. push_value_on_stack((dword)argc);
  420. push_value_on_stack(0);
  421. }
  422. int Process::exec(String path, Vector<String> arguments, Vector<String> environment)
  423. {
  424. // The bulk of exec() is done by do_exec(), which ensures that all locals
  425. // are cleaned up by the time we yield-teleport below.
  426. int rc = do_exec(move(path), move(arguments), move(environment));
  427. if (rc < 0)
  428. return rc;
  429. if (current == this) {
  430. Scheduler::yield();
  431. ASSERT_NOT_REACHED();
  432. }
  433. return 0;
  434. }
  435. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  436. {
  437. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  438. // On success, the kernel stack will be lost.
  439. if (!validate_read_str(filename))
  440. return -EFAULT;
  441. if (argv) {
  442. if (!validate_read_typed(argv))
  443. return -EFAULT;
  444. for (size_t i = 0; argv[i]; ++i) {
  445. if (!validate_read_str(argv[i]))
  446. return -EFAULT;
  447. }
  448. }
  449. if (envp) {
  450. if (!validate_read_typed(envp))
  451. return -EFAULT;
  452. for (size_t i = 0; envp[i]; ++i) {
  453. if (!validate_read_str(envp[i]))
  454. return -EFAULT;
  455. }
  456. }
  457. String path(filename);
  458. Vector<String> arguments;
  459. Vector<String> environment;
  460. {
  461. auto parts = path.split('/');
  462. if (argv) {
  463. for (size_t i = 0; argv[i]; ++i) {
  464. arguments.append(argv[i]);
  465. }
  466. } else {
  467. arguments.append(parts.last());
  468. }
  469. if (envp) {
  470. for (size_t i = 0; envp[i]; ++i)
  471. environment.append(envp[i]);
  472. }
  473. }
  474. int rc = exec(move(path), move(arguments), move(environment));
  475. ASSERT(rc < 0); // We should never continue after a successful exec!
  476. return rc;
  477. }
  478. 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)
  479. {
  480. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  481. auto parts = path.split('/');
  482. if (arguments.is_empty()) {
  483. arguments.append(parts.last());
  484. }
  485. RetainPtr<Inode> cwd;
  486. {
  487. InterruptDisabler disabler;
  488. if (auto* parent = Process::from_pid(parent_pid))
  489. cwd = parent->m_cwd.copy_ref();
  490. }
  491. if (!cwd)
  492. cwd = VFS::the().root_inode();
  493. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  494. error = process->exec(path, move(arguments), move(environment));
  495. if (error != 0) {
  496. delete process;
  497. return nullptr;
  498. }
  499. {
  500. InterruptDisabler disabler;
  501. g_processes->prepend(process);
  502. system.nprocess++;
  503. }
  504. #ifdef TASK_DEBUG
  505. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  506. #endif
  507. error = 0;
  508. return process;
  509. }
  510. Process* Process::create_kernel_process(String&& name, void (*e)())
  511. {
  512. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  513. process->m_tss.eip = (dword)e;
  514. if (process->pid() != 0) {
  515. {
  516. InterruptDisabler disabler;
  517. g_processes->prepend(process);
  518. system.nprocess++;
  519. }
  520. #ifdef TASK_DEBUG
  521. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  522. #endif
  523. }
  524. return process;
  525. }
  526. 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)
  527. : m_name(move(name))
  528. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  529. , m_uid(uid)
  530. , m_gid(gid)
  531. , m_euid(uid)
  532. , m_egid(gid)
  533. , m_state(Runnable)
  534. , m_ring(ring)
  535. , m_cwd(move(cwd))
  536. , m_executable(move(executable))
  537. , m_tty(tty)
  538. , m_ppid(ppid)
  539. {
  540. set_default_signal_dispositions();
  541. memset(&m_fpu_state, 0, sizeof(FPUState));
  542. m_gids.set(m_gid);
  543. if (fork_parent) {
  544. m_sid = fork_parent->m_sid;
  545. m_pgid = fork_parent->m_pgid;
  546. } else {
  547. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  548. InterruptDisabler disabler;
  549. if (auto* parent = Process::from_pid(m_ppid)) {
  550. m_sid = parent->m_sid;
  551. m_pgid = parent->m_pgid;
  552. }
  553. }
  554. m_page_directory = PageDirectory::create();
  555. #ifdef MM_DEBUG
  556. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  557. #endif
  558. if (fork_parent) {
  559. m_fds.resize(fork_parent->m_fds.size());
  560. for (int i = 0; i < fork_parent->m_fds.size(); ++i) {
  561. if (!fork_parent->m_fds[i].descriptor)
  562. continue;
  563. #ifdef FORK_DEBUG
  564. 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());
  565. #endif
  566. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  567. m_fds[i].flags = fork_parent->m_fds[i].flags;
  568. }
  569. } else {
  570. m_fds.resize(m_max_open_file_descriptors);
  571. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  572. int error;
  573. m_fds[0].set(device_to_use_as_tty.open(error, O_RDONLY));
  574. m_fds[1].set(device_to_use_as_tty.open(error, O_WRONLY));
  575. m_fds[2].set(device_to_use_as_tty.open(error, O_WRONLY));
  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. int error;
  1210. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, 0, cwd_inode());
  1211. if (!descriptor)
  1212. return error;
  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 = VFS::the().absolute_path(cwd_inode());
  1240. if (path.is_null())
  1241. return -EINVAL;
  1242. if (size < path.length() + 1)
  1243. return -ERANGE;
  1244. strcpy(buffer, path.characters());
  1245. return 0;
  1246. }
  1247. size_t Process::number_of_open_file_descriptors() const
  1248. {
  1249. size_t count = 0;
  1250. for (auto& descriptor : m_fds) {
  1251. if (descriptor)
  1252. ++count;
  1253. }
  1254. return count;
  1255. }
  1256. int Process::sys$open(const char* path, int options, mode_t mode)
  1257. {
  1258. #ifdef DEBUG_IO
  1259. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1260. #endif
  1261. if (!validate_read_str(path))
  1262. return -EFAULT;
  1263. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1264. return -EMFILE;
  1265. int error = -EWHYTHO;
  1266. auto descriptor = VFS::the().open(path, error, options, mode & ~umask(), cwd_inode());
  1267. if (!descriptor)
  1268. return error;
  1269. if (options & O_DIRECTORY && !descriptor->is_directory())
  1270. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1271. if (options & O_NONBLOCK)
  1272. descriptor->set_blocking(false);
  1273. int fd = 0;
  1274. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1275. if (!m_fds[fd])
  1276. break;
  1277. }
  1278. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1279. m_fds[fd].set(move(descriptor), flags);
  1280. return fd;
  1281. }
  1282. int Process::alloc_fd()
  1283. {
  1284. int fd = -1;
  1285. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1286. if (!m_fds[i]) {
  1287. fd = i;
  1288. break;
  1289. }
  1290. }
  1291. return fd;
  1292. }
  1293. int Process::sys$pipe(int pipefd[2])
  1294. {
  1295. if (!validate_write_typed(pipefd))
  1296. return -EFAULT;
  1297. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1298. return -EMFILE;
  1299. auto fifo = FIFO::create();
  1300. int reader_fd = alloc_fd();
  1301. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1302. pipefd[0] = reader_fd;
  1303. int writer_fd = alloc_fd();
  1304. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1305. pipefd[1] = writer_fd;
  1306. return 0;
  1307. }
  1308. int Process::sys$killpg(int pgrp, int signum)
  1309. {
  1310. if (signum < 1 || signum >= 32)
  1311. return -EINVAL;
  1312. (void) pgrp;
  1313. ASSERT_NOT_REACHED();
  1314. }
  1315. int Process::sys$setuid(uid_t uid)
  1316. {
  1317. if (uid != m_uid && !is_superuser())
  1318. return -EPERM;
  1319. m_uid = uid;
  1320. m_euid = uid;
  1321. return 0;
  1322. }
  1323. int Process::sys$setgid(gid_t gid)
  1324. {
  1325. if (gid != m_gid && !is_superuser())
  1326. return -EPERM;
  1327. m_gid = gid;
  1328. m_egid = gid;
  1329. return 0;
  1330. }
  1331. unsigned Process::sys$alarm(unsigned seconds)
  1332. {
  1333. (void) seconds;
  1334. ASSERT_NOT_REACHED();
  1335. }
  1336. int Process::sys$uname(utsname* buf)
  1337. {
  1338. if (!validate_write_typed(buf))
  1339. return -EFAULT;
  1340. strcpy(buf->sysname, "Serenity");
  1341. strcpy(buf->release, "1.0-dev");
  1342. strcpy(buf->version, "FIXME");
  1343. strcpy(buf->machine, "i386");
  1344. LOCKER(*s_hostname_lock);
  1345. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1346. return 0;
  1347. }
  1348. int Process::sys$isatty(int fd)
  1349. {
  1350. auto* descriptor = file_descriptor(fd);
  1351. if (!descriptor)
  1352. return -EBADF;
  1353. if (!descriptor->is_tty())
  1354. return -ENOTTY;
  1355. return 1;
  1356. }
  1357. int Process::sys$kill(pid_t pid, int signal)
  1358. {
  1359. if (signal < 0 || signal >= 32)
  1360. return -EINVAL;
  1361. if (pid == 0) {
  1362. // FIXME: Send to same-group processes.
  1363. ASSERT(pid != 0);
  1364. }
  1365. if (pid == -1) {
  1366. // FIXME: Send to all processes.
  1367. ASSERT(pid != -1);
  1368. }
  1369. if (pid == m_pid) {
  1370. send_signal(signal, this);
  1371. Scheduler::yield();
  1372. return 0;
  1373. }
  1374. InterruptDisabler disabler;
  1375. auto* peer = Process::from_pid(pid);
  1376. if (!peer)
  1377. return -ESRCH;
  1378. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1379. // FIXME: Should setuid processes have some special treatment here?
  1380. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  1381. return -EPERM;
  1382. if (peer->is_ring0() && signal == SIGKILL) {
  1383. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, peer->name().characters(), peer->pid());
  1384. return -EPERM;
  1385. }
  1386. peer->send_signal(signal, this);
  1387. return 0;
  1388. }
  1389. int Process::sys$usleep(useconds_t usec)
  1390. {
  1391. if (!usec)
  1392. return 0;
  1393. sleep(usec / 1000);
  1394. if (m_wakeup_time > system.uptime) {
  1395. ASSERT(m_was_interrupted_while_blocked);
  1396. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1397. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1398. }
  1399. return 0;
  1400. }
  1401. int Process::sys$sleep(unsigned seconds)
  1402. {
  1403. if (!seconds)
  1404. return 0;
  1405. sleep(seconds * TICKS_PER_SECOND);
  1406. if (m_wakeup_time > system.uptime) {
  1407. ASSERT(m_was_interrupted_while_blocked);
  1408. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1409. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1410. }
  1411. return 0;
  1412. }
  1413. int Process::sys$gettimeofday(timeval* tv)
  1414. {
  1415. if (!validate_write_typed(tv))
  1416. return -EFAULT;
  1417. auto now = RTC::now();
  1418. tv->tv_sec = now;
  1419. tv->tv_usec = PIT::ticks_since_boot() % 1000;
  1420. return 0;
  1421. }
  1422. uid_t Process::sys$getuid()
  1423. {
  1424. return m_uid;
  1425. }
  1426. gid_t Process::sys$getgid()
  1427. {
  1428. return m_gid;
  1429. }
  1430. uid_t Process::sys$geteuid()
  1431. {
  1432. return m_euid;
  1433. }
  1434. gid_t Process::sys$getegid()
  1435. {
  1436. return m_egid;
  1437. }
  1438. pid_t Process::sys$getpid()
  1439. {
  1440. return m_pid;
  1441. }
  1442. pid_t Process::sys$getppid()
  1443. {
  1444. return m_ppid;
  1445. }
  1446. mode_t Process::sys$umask(mode_t mask)
  1447. {
  1448. auto old_mask = m_umask;
  1449. m_umask = mask & 0777;
  1450. return old_mask;
  1451. }
  1452. int Process::reap(Process& process)
  1453. {
  1454. InterruptDisabler disabler;
  1455. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1456. if (process.ppid()) {
  1457. auto* parent = Process::from_pid(process.ppid());
  1458. if (parent) {
  1459. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1460. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1461. }
  1462. }
  1463. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1464. ASSERT(process.state() == Dead);
  1465. g_processes->remove(&process);
  1466. delete &process;
  1467. return exit_status;
  1468. }
  1469. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1470. {
  1471. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1472. // FIXME: Respect options
  1473. (void) options;
  1474. if (wstatus)
  1475. if (!validate_write_typed(wstatus))
  1476. return -EFAULT;
  1477. int dummy_wstatus;
  1478. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1479. {
  1480. InterruptDisabler disabler;
  1481. if (waitee != -1 && !Process::from_pid(waitee))
  1482. return -ECHILD;
  1483. }
  1484. if (options & WNOHANG) {
  1485. if (waitee == -1) {
  1486. pid_t reaped_pid = 0;
  1487. InterruptDisabler disabler;
  1488. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1489. if (process.state() == Dead) {
  1490. reaped_pid = process.pid();
  1491. exit_status = reap(process);
  1492. }
  1493. return true;
  1494. });
  1495. return reaped_pid;
  1496. } else {
  1497. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1498. InterruptDisabler disabler;
  1499. auto* waitee_process = Process::from_pid(waitee);
  1500. if (!waitee_process)
  1501. return -ECHILD;
  1502. if (waitee_process->state() == Dead) {
  1503. exit_status = reap(*waitee_process);
  1504. return waitee;
  1505. }
  1506. return 0;
  1507. }
  1508. }
  1509. m_waitee_pid = waitee;
  1510. block(BlockedWait);
  1511. Scheduler::yield();
  1512. if (m_was_interrupted_while_blocked)
  1513. return -EINTR;
  1514. Process* waitee_process;
  1515. {
  1516. InterruptDisabler disabler;
  1517. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1518. waitee_process = Process::from_pid(m_waitee_pid);
  1519. }
  1520. ASSERT(waitee_process);
  1521. exit_status = reap(*waitee_process);
  1522. return m_waitee_pid;
  1523. }
  1524. void Process::unblock()
  1525. {
  1526. if (current == this) {
  1527. system.nblocked--;
  1528. m_state = Process::Running;
  1529. return;
  1530. }
  1531. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1532. system.nblocked--;
  1533. m_state = Process::Runnable;
  1534. }
  1535. void Process::block(Process::State new_state)
  1536. {
  1537. if (state() != Process::Running) {
  1538. 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()));
  1539. }
  1540. ASSERT(state() == Process::Running);
  1541. system.nblocked++;
  1542. m_was_interrupted_while_blocked = false;
  1543. set_state(new_state);
  1544. }
  1545. void block(Process::State state)
  1546. {
  1547. current->block(state);
  1548. Scheduler::yield();
  1549. }
  1550. void sleep(dword ticks)
  1551. {
  1552. ASSERT(current->state() == Process::Running);
  1553. current->set_wakeup_time(system.uptime + ticks);
  1554. current->block(Process::BlockedSleep);
  1555. Scheduler::yield();
  1556. }
  1557. enum class KernelMemoryCheckResult {
  1558. NotInsideKernelMemory,
  1559. AccessGranted,
  1560. AccessDenied
  1561. };
  1562. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1563. {
  1564. auto* kernel_elf_header = (Elf32_Ehdr*)0xf000;
  1565. auto* kernel_program_headers = (Elf32_Phdr*)(0xf000 + kernel_elf_header->e_phoff);
  1566. for (unsigned i = 0; i < kernel_elf_header->e_phnum; ++i) {
  1567. auto& segment = kernel_program_headers[i];
  1568. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1569. continue;
  1570. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1571. continue;
  1572. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1573. return KernelMemoryCheckResult::AccessDenied;
  1574. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1575. return KernelMemoryCheckResult::AccessDenied;
  1576. return KernelMemoryCheckResult::AccessGranted;
  1577. }
  1578. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1579. }
  1580. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1581. {
  1582. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1583. // This code allows access outside of the known used address ranges to get caught.
  1584. auto kmc_result = check_kernel_memory_access(laddr, false);
  1585. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1586. return true;
  1587. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1588. return false;
  1589. if (is_kmalloc_address(laddr.as_ptr()))
  1590. return true;
  1591. return validate_read(laddr.as_ptr(), 1);
  1592. }
  1593. bool Process::validate_read_str(const char* str)
  1594. {
  1595. if (!validate_read(str, 1))
  1596. return false;
  1597. return validate_read(str, strlen(str) + 1);
  1598. }
  1599. bool Process::validate_read(const void* address, ssize_t size) const
  1600. {
  1601. ASSERT(size >= 0);
  1602. LinearAddress first_address((dword)address);
  1603. LinearAddress last_address = first_address.offset(size - 1);
  1604. if (is_ring0()) {
  1605. auto kmc_result = check_kernel_memory_access(first_address, false);
  1606. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1607. return true;
  1608. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1609. return false;
  1610. if (is_kmalloc_address(address))
  1611. return true;
  1612. }
  1613. ASSERT(size);
  1614. if (!size)
  1615. return false;
  1616. if (first_address.page_base() != last_address.page_base()) {
  1617. if (!MM.validate_user_read(*this, last_address))
  1618. return false;
  1619. }
  1620. return MM.validate_user_read(*this, first_address);
  1621. }
  1622. bool Process::validate_write(void* address, ssize_t size) const
  1623. {
  1624. ASSERT(size >= 0);
  1625. LinearAddress first_address((dword)address);
  1626. LinearAddress last_address = first_address.offset(size - 1);
  1627. if (is_ring0()) {
  1628. if (is_kmalloc_address(address))
  1629. return true;
  1630. auto kmc_result = check_kernel_memory_access(first_address, true);
  1631. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1632. return true;
  1633. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1634. return false;
  1635. }
  1636. if (!size)
  1637. return false;
  1638. if (first_address.page_base() != last_address.page_base()) {
  1639. if (!MM.validate_user_write(*this, last_address))
  1640. return false;
  1641. }
  1642. return MM.validate_user_write(*this, last_address);
  1643. }
  1644. pid_t Process::sys$getsid(pid_t pid)
  1645. {
  1646. if (pid == 0)
  1647. return m_sid;
  1648. InterruptDisabler disabler;
  1649. auto* process = Process::from_pid(pid);
  1650. if (!process)
  1651. return -ESRCH;
  1652. if (m_sid != process->m_sid)
  1653. return -EPERM;
  1654. return process->m_sid;
  1655. }
  1656. pid_t Process::sys$setsid()
  1657. {
  1658. InterruptDisabler disabler;
  1659. bool found_process_with_same_pgid_as_my_pid = false;
  1660. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1661. found_process_with_same_pgid_as_my_pid = true;
  1662. return false;
  1663. });
  1664. if (found_process_with_same_pgid_as_my_pid)
  1665. return -EPERM;
  1666. m_sid = m_pid;
  1667. m_pgid = m_pid;
  1668. return m_sid;
  1669. }
  1670. pid_t Process::sys$getpgid(pid_t pid)
  1671. {
  1672. if (pid == 0)
  1673. return m_pgid;
  1674. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1675. auto* process = Process::from_pid(pid);
  1676. if (!process)
  1677. return -ESRCH;
  1678. return process->m_pgid;
  1679. }
  1680. pid_t Process::sys$getpgrp()
  1681. {
  1682. return m_pgid;
  1683. }
  1684. static pid_t get_sid_from_pgid(pid_t pgid)
  1685. {
  1686. InterruptDisabler disabler;
  1687. auto* group_leader = Process::from_pid(pgid);
  1688. if (!group_leader)
  1689. return -1;
  1690. return group_leader->sid();
  1691. }
  1692. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1693. {
  1694. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1695. pid_t pid = specified_pid ? specified_pid : m_pid;
  1696. if (specified_pgid < 0)
  1697. return -EINVAL;
  1698. auto* process = Process::from_pid(pid);
  1699. if (!process)
  1700. return -ESRCH;
  1701. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1702. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1703. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1704. if (current_sid != new_sid) {
  1705. // Can't move a process between sessions.
  1706. return -EPERM;
  1707. }
  1708. // FIXME: There are more EPERM conditions to check for here..
  1709. process->m_pgid = new_pgid;
  1710. return 0;
  1711. }
  1712. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1713. {
  1714. auto* descriptor = file_descriptor(fd);
  1715. if (!descriptor)
  1716. return -EBADF;
  1717. if (descriptor->is_socket() && request == 413) {
  1718. auto* pid = (pid_t*)arg;
  1719. if (!validate_write_typed(pid))
  1720. return -EFAULT;
  1721. *pid = descriptor->socket()->origin_pid();
  1722. return 0;
  1723. }
  1724. if (!descriptor->is_device())
  1725. return -ENOTTY;
  1726. return descriptor->device()->ioctl(*this, request, arg);
  1727. }
  1728. int Process::sys$getdtablesize()
  1729. {
  1730. return m_max_open_file_descriptors;
  1731. }
  1732. int Process::sys$dup(int old_fd)
  1733. {
  1734. auto* descriptor = file_descriptor(old_fd);
  1735. if (!descriptor)
  1736. return -EBADF;
  1737. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1738. return -EMFILE;
  1739. int new_fd = 0;
  1740. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1741. if (!m_fds[new_fd])
  1742. break;
  1743. }
  1744. m_fds[new_fd].set(descriptor);
  1745. return new_fd;
  1746. }
  1747. int Process::sys$dup2(int old_fd, int new_fd)
  1748. {
  1749. auto* descriptor = file_descriptor(old_fd);
  1750. if (!descriptor)
  1751. return -EBADF;
  1752. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1753. return -EMFILE;
  1754. m_fds[new_fd].set(descriptor);
  1755. return new_fd;
  1756. }
  1757. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1758. {
  1759. if (old_set) {
  1760. if (!validate_write_typed(old_set))
  1761. return -EFAULT;
  1762. *old_set = m_signal_mask;
  1763. }
  1764. if (set) {
  1765. if (!validate_read_typed(set))
  1766. return -EFAULT;
  1767. switch (how) {
  1768. case SIG_BLOCK:
  1769. m_signal_mask &= ~(*set);
  1770. break;
  1771. case SIG_UNBLOCK:
  1772. m_signal_mask |= *set;
  1773. break;
  1774. case SIG_SETMASK:
  1775. m_signal_mask = *set;
  1776. break;
  1777. default:
  1778. return -EINVAL;
  1779. }
  1780. }
  1781. return 0;
  1782. }
  1783. int Process::sys$sigpending(sigset_t* set)
  1784. {
  1785. if (!validate_write_typed(set))
  1786. return -EFAULT;
  1787. *set = m_pending_signals;
  1788. return 0;
  1789. }
  1790. void Process::set_default_signal_dispositions()
  1791. {
  1792. // FIXME: Set up all the right default actions. See signal(7).
  1793. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  1794. m_signal_action_data[SIGCHLD].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1795. m_signal_action_data[SIGWINCH].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1796. }
  1797. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1798. {
  1799. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1800. return -EINVAL;
  1801. if (!validate_read_typed(act))
  1802. return -EFAULT;
  1803. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1804. auto& action = m_signal_action_data[signum];
  1805. if (old_act) {
  1806. if (!validate_write_typed(old_act))
  1807. return -EFAULT;
  1808. old_act->sa_flags = action.flags;
  1809. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1810. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1811. }
  1812. action.restorer = LinearAddress((dword)act->sa_restorer);
  1813. action.flags = act->sa_flags;
  1814. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1815. return 0;
  1816. }
  1817. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1818. {
  1819. if (count < 0)
  1820. return -EINVAL;
  1821. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1822. if (!count)
  1823. return m_gids.size();
  1824. if (count != (int)m_gids.size())
  1825. return -EINVAL;
  1826. if (!validate_write_typed(gids, m_gids.size()))
  1827. return -EFAULT;
  1828. size_t i = 0;
  1829. for (auto gid : m_gids)
  1830. gids[i++] = gid;
  1831. return 0;
  1832. }
  1833. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1834. {
  1835. if (count < 0)
  1836. return -EINVAL;
  1837. if (!is_superuser())
  1838. return -EPERM;
  1839. if (count >= MAX_PROCESS_GIDS)
  1840. return -EINVAL;
  1841. if (!validate_read(gids, count))
  1842. return -EFAULT;
  1843. m_gids.clear();
  1844. m_gids.set(m_gid);
  1845. for (int i = 0; i < count; ++i)
  1846. m_gids.set(gids[i]);
  1847. return 0;
  1848. }
  1849. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1850. {
  1851. if (!validate_read_str(pathname))
  1852. return -EFAULT;
  1853. size_t pathname_length = strlen(pathname);
  1854. if (pathname_length == 0)
  1855. return -EINVAL;
  1856. if (pathname_length >= 255)
  1857. return -ENAMETOOLONG;
  1858. return VFS::the().mkdir(String(pathname, pathname_length), mode & ~umask(), cwd_inode());
  1859. }
  1860. clock_t Process::sys$times(tms* times)
  1861. {
  1862. if (!validate_write_typed(times))
  1863. return -EFAULT;
  1864. times->tms_utime = m_ticks_in_user;
  1865. times->tms_stime = m_ticks_in_kernel;
  1866. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1867. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1868. return 0;
  1869. }
  1870. int Process::sys$select(const Syscall::SC_select_params* params)
  1871. {
  1872. if (!validate_read_typed(params))
  1873. return -EFAULT;
  1874. if (params->writefds && !validate_read_typed(params->writefds))
  1875. return -EFAULT;
  1876. if (params->readfds && !validate_read_typed(params->readfds))
  1877. return -EFAULT;
  1878. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1879. return -EFAULT;
  1880. if (params->timeout && !validate_read_typed(params->timeout))
  1881. return -EFAULT;
  1882. int nfds = params->nfds;
  1883. fd_set* writefds = params->writefds;
  1884. fd_set* readfds = params->readfds;
  1885. fd_set* exceptfds = params->exceptfds;
  1886. auto* timeout = params->timeout;
  1887. // FIXME: Implement exceptfds support.
  1888. (void)exceptfds;
  1889. if (timeout) {
  1890. m_select_timeout = *timeout;
  1891. m_select_has_timeout = true;
  1892. } else {
  1893. m_select_has_timeout = false;
  1894. }
  1895. if (nfds < 0)
  1896. return -EINVAL;
  1897. // FIXME: Return -EINTR if a signal is caught.
  1898. // FIXME: Return -EINVAL if timeout is invalid.
  1899. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1900. if (!set)
  1901. return 0;
  1902. vector.clear_with_capacity();
  1903. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1904. for (int i = 0; i < nfds; ++i) {
  1905. if (bitmap.get(i)) {
  1906. if (!file_descriptor(i))
  1907. return -EBADF;
  1908. vector.append(i);
  1909. }
  1910. }
  1911. return 0;
  1912. };
  1913. int error = 0;
  1914. error = transfer_fds(writefds, m_select_write_fds);
  1915. if (error)
  1916. return error;
  1917. error = transfer_fds(readfds, m_select_read_fds);
  1918. if (error)
  1919. return error;
  1920. error = transfer_fds(readfds, m_select_exceptional_fds);
  1921. if (error)
  1922. return error;
  1923. #ifdef DEBUG_IO
  1924. dbgprintf("%s<%u> selecting on (read:%u, write:%u), wakeup_req:%u, timeout=%p\n", name().characters(), pid(), m_select_read_fds.size(), m_select_write_fds.size(), m_wakeup_requested, timeout);
  1925. #endif
  1926. if (!m_wakeup_requested && (!timeout || (timeout->tv_sec || timeout->tv_usec))) {
  1927. block(BlockedSelect);
  1928. Scheduler::yield();
  1929. }
  1930. m_wakeup_requested = false;
  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 (!m_wakeup_requested && timeout < 0) {
  1974. block(BlockedSelect);
  1975. Scheduler::yield();
  1976. }
  1977. m_wakeup_requested = false;
  1978. int fds_with_revents = 0;
  1979. for (int i = 0; i < nfds; ++i) {
  1980. auto* descriptor = file_descriptor(fds[i].fd);
  1981. if (!descriptor) {
  1982. fds[i].revents = POLLNVAL;
  1983. continue;
  1984. }
  1985. fds[i].revents = 0;
  1986. if (fds[i].events & POLLIN && descriptor->can_read(*this))
  1987. fds[i].revents |= POLLIN;
  1988. if (fds[i].events & POLLOUT && descriptor->can_write(*this))
  1989. fds[i].revents |= POLLOUT;
  1990. if (fds[i].revents)
  1991. ++fds_with_revents;
  1992. }
  1993. return fds_with_revents;
  1994. }
  1995. Inode& Process::cwd_inode()
  1996. {
  1997. // FIXME: This is retarded factoring.
  1998. if (!m_cwd)
  1999. m_cwd = VFS::the().root_inode();
  2000. return *m_cwd;
  2001. }
  2002. int Process::sys$link(const char* old_path, const char* new_path)
  2003. {
  2004. if (!validate_read_str(old_path))
  2005. return -EFAULT;
  2006. if (!validate_read_str(new_path))
  2007. return -EFAULT;
  2008. return VFS::the().link(String(old_path), String(new_path), cwd_inode());
  2009. }
  2010. int Process::sys$unlink(const char* pathname)
  2011. {
  2012. if (!validate_read_str(pathname))
  2013. return -EFAULT;
  2014. return VFS::the().unlink(String(pathname), cwd_inode());
  2015. }
  2016. int Process::sys$symlink(const char* target, const char* linkpath)
  2017. {
  2018. if (!validate_read_str(target))
  2019. return -EFAULT;
  2020. if (!validate_read_str(linkpath))
  2021. return -EFAULT;
  2022. return VFS::the().symlink(String(target), String(linkpath), cwd_inode());
  2023. }
  2024. int Process::sys$rmdir(const char* pathname)
  2025. {
  2026. if (!validate_read_str(pathname))
  2027. return -EFAULT;
  2028. return VFS::the().rmdir(String(pathname), cwd_inode());
  2029. }
  2030. int Process::sys$read_tsc(dword* lsw, dword* msw)
  2031. {
  2032. if (!validate_write_typed(lsw))
  2033. return -EFAULT;
  2034. if (!validate_write_typed(msw))
  2035. return -EFAULT;
  2036. read_tsc(*lsw, *msw);
  2037. return 0;
  2038. }
  2039. int Process::sys$chmod(const char* pathname, mode_t mode)
  2040. {
  2041. if (!validate_read_str(pathname))
  2042. return -EFAULT;
  2043. return VFS::the().chmod(String(pathname), mode, cwd_inode());
  2044. }
  2045. int Process::sys$fchmod(int fd, mode_t mode)
  2046. {
  2047. auto* descriptor = file_descriptor(fd);
  2048. if (!descriptor)
  2049. return -EBADF;
  2050. return descriptor->fchmod(mode);
  2051. }
  2052. int Process::sys$chown(const char* pathname, uid_t uid, gid_t gid)
  2053. {
  2054. if (!validate_read_str(pathname))
  2055. return -EFAULT;
  2056. return VFS::the().chown(String(pathname), uid, gid, cwd_inode());
  2057. }
  2058. void Process::finalize()
  2059. {
  2060. ASSERT(current == g_finalizer);
  2061. m_fds.clear();
  2062. m_tty = nullptr;
  2063. disown_all_shared_buffers();
  2064. {
  2065. InterruptDisabler disabler;
  2066. if (auto* parent_process = Process::from_pid(m_ppid)) {
  2067. if (parent_process->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  2068. // NOTE: If the parent doesn't care about this process, let it go.
  2069. m_ppid = 0;
  2070. } else {
  2071. parent_process->send_signal(SIGCHLD, this);
  2072. }
  2073. }
  2074. }
  2075. set_state(Dead);
  2076. }
  2077. void Process::die()
  2078. {
  2079. set_state(Dying);
  2080. if (!Scheduler::is_active())
  2081. Scheduler::pick_next_and_switch_now();
  2082. }
  2083. size_t Process::amount_virtual() const
  2084. {
  2085. size_t amount = 0;
  2086. for (auto& region : m_regions) {
  2087. amount += region->size();
  2088. }
  2089. return amount;
  2090. }
  2091. size_t Process::amount_resident() const
  2092. {
  2093. // FIXME: This will double count if multiple regions use the same physical page.
  2094. size_t amount = 0;
  2095. for (auto& region : m_regions) {
  2096. amount += region->amount_resident();
  2097. }
  2098. return amount;
  2099. }
  2100. size_t Process::amount_shared() const
  2101. {
  2102. // FIXME: This will double count if multiple regions use the same physical page.
  2103. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  2104. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  2105. // so that every Region contributes +1 retain to each of its PhysicalPages.
  2106. size_t amount = 0;
  2107. for (auto& region : m_regions) {
  2108. amount += region->amount_shared();
  2109. }
  2110. return amount;
  2111. }
  2112. void Process::finalize_dying_processes()
  2113. {
  2114. Vector<Process*> dying_processes;
  2115. {
  2116. InterruptDisabler disabler;
  2117. dying_processes.ensure_capacity(system.nprocess);
  2118. for (auto* process = g_processes->head(); process; process = process->next()) {
  2119. if (process->state() == Process::Dying)
  2120. dying_processes.append(process);
  2121. }
  2122. }
  2123. for (auto* process : dying_processes)
  2124. process->finalize();
  2125. }
  2126. bool Process::tick()
  2127. {
  2128. ++m_ticks;
  2129. if (tss().cs & 3)
  2130. ++m_ticks_in_user;
  2131. else
  2132. ++m_ticks_in_kernel;
  2133. return --m_ticks_left;
  2134. }
  2135. int Process::sys$socket(int domain, int type, int protocol)
  2136. {
  2137. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2138. return -EMFILE;
  2139. int fd = 0;
  2140. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2141. if (!m_fds[fd])
  2142. break;
  2143. }
  2144. int error;
  2145. auto socket = Socket::create(domain, type, protocol, error);
  2146. if (!socket)
  2147. return error;
  2148. auto descriptor = FileDescriptor::create(move(socket));
  2149. unsigned flags = 0;
  2150. if (type & SOCK_CLOEXEC)
  2151. flags |= FD_CLOEXEC;
  2152. if (type & SOCK_NONBLOCK)
  2153. descriptor->set_blocking(false);
  2154. m_fds[fd].set(move(descriptor), flags);
  2155. return fd;
  2156. }
  2157. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2158. {
  2159. if (!validate_read(address, address_length))
  2160. return -EFAULT;
  2161. auto* descriptor = file_descriptor(sockfd);
  2162. if (!descriptor)
  2163. return -EBADF;
  2164. if (!descriptor->is_socket())
  2165. return -ENOTSOCK;
  2166. auto& socket = *descriptor->socket();
  2167. int error;
  2168. if (!socket.bind(address, address_length, error))
  2169. return error;
  2170. return 0;
  2171. }
  2172. int Process::sys$listen(int sockfd, int backlog)
  2173. {
  2174. auto* descriptor = file_descriptor(sockfd);
  2175. if (!descriptor)
  2176. return -EBADF;
  2177. if (!descriptor->is_socket())
  2178. return -ENOTSOCK;
  2179. auto& socket = *descriptor->socket();
  2180. int error;
  2181. if (!socket.listen(backlog, error))
  2182. return error;
  2183. descriptor->set_socket_role(SocketRole::Listener);
  2184. return 0;
  2185. }
  2186. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  2187. {
  2188. if (!validate_write_typed(address_size))
  2189. return -EFAULT;
  2190. if (!validate_write(address, *address_size))
  2191. return -EFAULT;
  2192. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2193. return -EMFILE;
  2194. int accepted_socket_fd = 0;
  2195. for (; accepted_socket_fd < (int)m_max_open_file_descriptors; ++accepted_socket_fd) {
  2196. if (!m_fds[accepted_socket_fd])
  2197. break;
  2198. }
  2199. auto* accepting_socket_descriptor = file_descriptor(accepting_socket_fd);
  2200. if (!accepting_socket_descriptor)
  2201. return -EBADF;
  2202. if (!accepting_socket_descriptor->is_socket())
  2203. return -ENOTSOCK;
  2204. auto& socket = *accepting_socket_descriptor->socket();
  2205. if (!socket.can_accept()) {
  2206. ASSERT(!accepting_socket_descriptor->is_blocking());
  2207. return -EAGAIN;
  2208. }
  2209. auto accepted_socket = socket.accept();
  2210. ASSERT(accepted_socket);
  2211. bool success = accepted_socket->get_address(address, address_size);
  2212. ASSERT(success);
  2213. auto accepted_socket_descriptor = FileDescriptor::create(move(accepted_socket), SocketRole::Accepted);
  2214. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2215. // I'm not sure if this matches other systems but it makes sense to me.
  2216. accepted_socket_descriptor->set_blocking(accepting_socket_descriptor->is_blocking());
  2217. m_fds[accepted_socket_fd].set(move(accepted_socket_descriptor), m_fds[accepting_socket_fd].flags);
  2218. return accepted_socket_fd;
  2219. }
  2220. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2221. {
  2222. if (!validate_read(address, address_size))
  2223. return -EFAULT;
  2224. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  2225. return -EMFILE;
  2226. int fd = 0;
  2227. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  2228. if (!m_fds[fd])
  2229. break;
  2230. }
  2231. auto* descriptor = file_descriptor(sockfd);
  2232. if (!descriptor)
  2233. return -EBADF;
  2234. if (!descriptor->is_socket())
  2235. return -ENOTSOCK;
  2236. auto& socket = *descriptor->socket();
  2237. int error;
  2238. if (!socket.connect(address, address_size, error))
  2239. return error;
  2240. descriptor->set_socket_role(SocketRole::Connected);
  2241. return 0;
  2242. }
  2243. bool Process::wait_for_connect(Socket& socket, int& error)
  2244. {
  2245. if (socket.is_connected())
  2246. return true;
  2247. m_blocked_connecting_socket = socket;
  2248. block(BlockedConnect);
  2249. Scheduler::yield();
  2250. m_blocked_connecting_socket = nullptr;
  2251. if (!socket.is_connected()) {
  2252. error = -ECONNREFUSED;
  2253. return false;
  2254. }
  2255. return true;
  2256. }
  2257. struct SharedBuffer {
  2258. SharedBuffer(pid_t pid1, pid_t pid2, size_t size)
  2259. : m_pid1(pid1)
  2260. , m_pid2(pid2)
  2261. , m_vmo(VMObject::create_anonymous(size))
  2262. {
  2263. ASSERT(pid1 != pid2);
  2264. }
  2265. void* retain(Process& process)
  2266. {
  2267. if (m_pid1 == process.pid()) {
  2268. ++m_pid1_retain_count;
  2269. if (!m_pid1_region) {
  2270. m_pid1_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2271. m_pid1_region->set_shared(true);
  2272. }
  2273. return m_pid1_region->laddr().as_ptr();
  2274. } else if (m_pid2 == process.pid()) {
  2275. ++m_pid2_retain_count;
  2276. if (!m_pid2_region) {
  2277. m_pid2_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2278. m_pid2_region->set_shared(true);
  2279. }
  2280. return m_pid2_region->laddr().as_ptr();
  2281. }
  2282. return nullptr;
  2283. }
  2284. void release(Process& process)
  2285. {
  2286. if (m_pid1 == process.pid()) {
  2287. ASSERT(m_pid1_retain_count);
  2288. --m_pid1_retain_count;
  2289. if (!m_pid1_retain_count) {
  2290. if (m_pid1_region)
  2291. process.deallocate_region(*m_pid1_region);
  2292. m_pid1_region = nullptr;
  2293. }
  2294. destroy_if_unused();
  2295. } else if (m_pid2 == process.pid()) {
  2296. ASSERT(m_pid2_retain_count);
  2297. --m_pid2_retain_count;
  2298. if (!m_pid2_retain_count) {
  2299. if (m_pid2_region)
  2300. process.deallocate_region(*m_pid2_region);
  2301. m_pid2_region = nullptr;
  2302. }
  2303. destroy_if_unused();
  2304. }
  2305. }
  2306. void disown(pid_t pid)
  2307. {
  2308. if (m_pid1 == pid) {
  2309. m_pid1 = 0;
  2310. m_pid1_retain_count = 0;
  2311. destroy_if_unused();
  2312. } else if (m_pid2 == pid) {
  2313. m_pid2 = 0;
  2314. m_pid2_retain_count = 0;
  2315. destroy_if_unused();
  2316. }
  2317. }
  2318. pid_t pid1() const { return m_pid1; }
  2319. pid_t pid2() const { return m_pid2; }
  2320. unsigned pid1_retain_count() const { return m_pid1_retain_count; }
  2321. unsigned pid2_retain_count() const { return m_pid2_retain_count; }
  2322. size_t size() const { return m_vmo->size(); }
  2323. void destroy_if_unused();
  2324. int m_shared_buffer_id { -1 };
  2325. pid_t m_pid1;
  2326. pid_t m_pid2;
  2327. unsigned m_pid1_retain_count { 1 };
  2328. unsigned m_pid2_retain_count { 0 };
  2329. Region* m_pid1_region { nullptr };
  2330. Region* m_pid2_region { nullptr };
  2331. Retained<VMObject> m_vmo;
  2332. };
  2333. static int s_next_shared_buffer_id;
  2334. Lockable<HashMap<int, OwnPtr<SharedBuffer>>>& shared_buffers()
  2335. {
  2336. static Lockable<HashMap<int, OwnPtr<SharedBuffer>>>* map;
  2337. if (!map)
  2338. map = new Lockable<HashMap<int, OwnPtr<SharedBuffer>>>;
  2339. return *map;
  2340. }
  2341. void SharedBuffer::destroy_if_unused()
  2342. {
  2343. if (!m_pid1_retain_count && !m_pid2_retain_count) {
  2344. LOCKER(shared_buffers().lock());
  2345. #ifdef SHARED_BUFFER_DEBUG
  2346. dbgprintf("Destroying unused SharedBuffer{%p} id: %d (pid1: %d, pid2: %d)\n", this, m_shared_buffer_id, m_pid1, m_pid2);
  2347. #endif
  2348. size_t count_before = shared_buffers().resource().size();
  2349. shared_buffers().resource().remove(m_shared_buffer_id);
  2350. ASSERT(count_before != shared_buffers().resource().size());
  2351. }
  2352. }
  2353. void Process::disown_all_shared_buffers()
  2354. {
  2355. LOCKER(shared_buffers().lock());
  2356. Vector<SharedBuffer*> buffers_to_disown;
  2357. for (auto& it : shared_buffers().resource())
  2358. buffers_to_disown.append(it.value.ptr());
  2359. for (auto* shared_buffer : buffers_to_disown)
  2360. shared_buffer->disown(m_pid);
  2361. }
  2362. int Process::sys$create_shared_buffer(pid_t peer_pid, size_t size, void** buffer)
  2363. {
  2364. if (!size)
  2365. return -EINVAL;
  2366. size = PAGE_ROUND_UP(size);
  2367. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2368. return -EINVAL;
  2369. if (!validate_write_typed(buffer))
  2370. return -EFAULT;
  2371. {
  2372. InterruptDisabler disabler;
  2373. auto* peer = Process::from_pid(peer_pid);
  2374. if (!peer)
  2375. return -ESRCH;
  2376. }
  2377. LOCKER(shared_buffers().lock());
  2378. int shared_buffer_id = ++s_next_shared_buffer_id;
  2379. auto shared_buffer = make<SharedBuffer>(m_pid, peer_pid, size);
  2380. shared_buffer->m_shared_buffer_id = shared_buffer_id;
  2381. ASSERT(shared_buffer->size() >= size);
  2382. shared_buffer->m_pid1_region = allocate_region_with_vmo(LinearAddress(), shared_buffer->size(), shared_buffer->m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2383. shared_buffer->m_pid1_region->set_shared(true);
  2384. *buffer = shared_buffer->m_pid1_region->laddr().as_ptr();
  2385. #ifdef SHARED_BUFFER_DEBUG
  2386. dbgprintf("%s(%u): Created shared buffer %d (%u bytes, vmo is %u) for sharing with %d\n", name().characters(), pid(),shared_buffer_id, size, shared_buffer->size(), peer_pid);
  2387. #endif
  2388. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2389. return shared_buffer_id;
  2390. }
  2391. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2392. {
  2393. LOCKER(shared_buffers().lock());
  2394. auto it = shared_buffers().resource().find(shared_buffer_id);
  2395. if (it == shared_buffers().resource().end())
  2396. return -EINVAL;
  2397. auto& shared_buffer = *(*it).value;
  2398. #ifdef SHARED_BUFFER_DEBUG
  2399. dbgprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2400. #endif
  2401. shared_buffer.release(*this);
  2402. return 0;
  2403. }
  2404. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2405. {
  2406. LOCKER(shared_buffers().lock());
  2407. auto it = shared_buffers().resource().find(shared_buffer_id);
  2408. if (it == shared_buffers().resource().end())
  2409. return (void*)-EINVAL;
  2410. auto& shared_buffer = *(*it).value;
  2411. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2412. return (void*)-EINVAL;
  2413. #ifdef SHARED_BUFFER_DEBUG
  2414. dbgprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2415. #endif
  2416. return shared_buffer.retain(*this);
  2417. }
  2418. const char* to_string(Process::State state)
  2419. {
  2420. switch (state) {
  2421. case Process::Invalid: return "Invalid";
  2422. case Process::Runnable: return "Runnable";
  2423. case Process::Running: return "Running";
  2424. case Process::Dying: return "Dying";
  2425. case Process::Dead: return "Dead";
  2426. case Process::Stopped: return "Stopped";
  2427. case Process::Skip1SchedulerPass: return "Skip1";
  2428. case Process::Skip0SchedulerPasses: return "Skip0";
  2429. case Process::BlockedSleep: return "Sleep";
  2430. case Process::BlockedWait: return "Wait";
  2431. case Process::BlockedRead: return "Read";
  2432. case Process::BlockedWrite: return "Write";
  2433. case Process::BlockedSignal: return "Signal";
  2434. case Process::BlockedSelect: return "Select";
  2435. case Process::BlockedLurking: return "Lurking";
  2436. case Process::BlockedConnect: return "Connect";
  2437. case Process::BeingInspected: return "Inspect";
  2438. }
  2439. kprintf("to_string(Process::State): Invalid state: %u\n", state);
  2440. ASSERT_NOT_REACHED();
  2441. return nullptr;
  2442. }
  2443. const char* to_string(Process::Priority priority)
  2444. {
  2445. switch (priority) {
  2446. case Process::LowPriority: return "Low";
  2447. case Process::NormalPriority: return "Normal";
  2448. case Process::HighPriority: return "High";
  2449. }
  2450. kprintf("to_string(Process::Priority): Invalid priority: %u\n", priority);
  2451. ASSERT_NOT_REACHED();
  2452. return nullptr;
  2453. }