Process.cpp 80 KB

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