Process.cpp 119 KB

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