Process.cpp 125 KB

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