Process.cpp 112 KB

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