Process.cpp 82 KB

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