Process.cpp 121 KB

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