Process.cpp 120 KB

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