Process.cpp 99 KB

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