Process.cpp 82 KB

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