Process.cpp 88 KB

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