Process.cpp 90 KB

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