Process.cpp 124 KB

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