Process.cpp 85 KB

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