Process.cpp 81 KB

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