| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005 |
- using Ryujinx.Common;
- using Ryujinx.Common.Logging;
- using Ryujinx.Cpu;
- using Ryujinx.HLE.Exceptions;
- using Ryujinx.HLE.HOS.Kernel.Common;
- using Ryujinx.HLE.HOS.Kernel.Ipc;
- using Ryujinx.HLE.HOS.Kernel.Memory;
- using Ryujinx.HLE.HOS.Kernel.Process;
- using Ryujinx.HLE.HOS.Kernel.Threading;
- using Ryujinx.Horizon.Common;
- using System;
- using System.Threading;
- namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
- {
- [SvcImpl]
- class Syscall : ISyscallApi
- {
- private readonly KernelContext _context;
- public Syscall(KernelContext context)
- {
- _context = context;
- }
- // Process
- [Svc(0x24)]
- public Result GetProcessId(out ulong pid, int handle)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KProcess process = currentProcess.HandleTable.GetKProcess(handle);
- if (process == null)
- {
- KThread thread = currentProcess.HandleTable.GetKThread(handle);
- if (thread != null)
- {
- process = thread.Owner;
- }
- // TODO: KDebugEvent.
- }
- pid = process?.Pid ?? 0;
- return process != null
- ? Result.Success
- : KernelResult.InvalidHandle;
- }
- public Result CreateProcess(
- out int handle,
- ProcessCreationInfo info,
- ReadOnlySpan<uint> capabilities,
- IProcessContextFactory contextFactory,
- ThreadStart customThreadStart = null)
- {
- handle = 0;
- if ((info.Flags & ~ProcessCreationFlags.All) != 0)
- {
- return KernelResult.InvalidEnumValue;
- }
- // TODO: Address space check.
- if ((info.Flags & ProcessCreationFlags.PoolPartitionMask) > ProcessCreationFlags.PoolPartitionSystemNonSecure)
- {
- return KernelResult.InvalidEnumValue;
- }
- if ((info.CodeAddress & 0x1fffff) != 0)
- {
- return KernelResult.InvalidAddress;
- }
- if (info.CodePagesCount < 0 || info.SystemResourcePagesCount < 0)
- {
- return KernelResult.InvalidSize;
- }
- if (info.Flags.HasFlag(ProcessCreationFlags.OptimizeMemoryAllocation) &&
- !info.Flags.HasFlag(ProcessCreationFlags.IsApplication))
- {
- return KernelResult.InvalidThread;
- }
- KHandleTable handleTable = KernelStatic.GetCurrentProcess().HandleTable;
- KProcess process = new KProcess(_context);
- using var _ = new OnScopeExit(process.DecrementReferenceCount);
- KResourceLimit resourceLimit;
- if (info.ResourceLimitHandle != 0)
- {
- resourceLimit = handleTable.GetObject<KResourceLimit>(info.ResourceLimitHandle);
- if (resourceLimit == null)
- {
- return KernelResult.InvalidHandle;
- }
- }
- else
- {
- resourceLimit = _context.ResourceLimit;
- }
- MemoryRegion memRegion = (info.Flags & ProcessCreationFlags.PoolPartitionMask) switch
- {
- ProcessCreationFlags.PoolPartitionApplication => MemoryRegion.Application,
- ProcessCreationFlags.PoolPartitionApplet => MemoryRegion.Applet,
- ProcessCreationFlags.PoolPartitionSystem => MemoryRegion.Service,
- ProcessCreationFlags.PoolPartitionSystemNonSecure => MemoryRegion.NvServices,
- _ => MemoryRegion.NvServices
- };
- Result result = process.Initialize(
- info,
- capabilities,
- resourceLimit,
- memRegion,
- contextFactory,
- customThreadStart);
- if (result != Result.Success)
- {
- return result;
- }
- _context.Processes.TryAdd(process.Pid, process);
- return handleTable.GenerateHandle(process, out handle);
- }
- public Result StartProcess(int handle, int priority, int cpuCore, ulong mainThreadStackSize)
- {
- KProcess process = KernelStatic.GetCurrentProcess().HandleTable.GetObject<KProcess>(handle);
- if (process == null)
- {
- return KernelResult.InvalidHandle;
- }
- if ((uint)cpuCore >= KScheduler.CpuCoresCount || !process.IsCpuCoreAllowed(cpuCore))
- {
- return KernelResult.InvalidCpuCore;
- }
- if ((uint)priority >= KScheduler.PrioritiesCount || !process.IsPriorityAllowed(priority))
- {
- return KernelResult.InvalidPriority;
- }
- process.DefaultCpuCore = cpuCore;
- Result result = process.Start(priority, mainThreadStackSize);
- if (result != Result.Success)
- {
- return result;
- }
- process.IncrementReferenceCount();
- return Result.Success;
- }
- [Svc(0x5f)]
- public Result FlushProcessDataCache(int processHandle, ulong address, ulong size)
- {
- // FIXME: This needs to be implemented as ARMv7 doesn't have any way to do cache maintenance operations on EL0.
- // As we don't support (and don't actually need) to flush the cache, this is stubbed.
- return Result.Success;
- }
- // IPC
- [Svc(0x1f)]
- public Result ConnectToNamedPort(out int handle, [PointerSized] ulong namePtr)
- {
- handle = 0;
- if (!KernelTransfer.UserToKernelString(out string name, namePtr, 12))
- {
- return KernelResult.UserCopyFailed;
- }
- return ConnectToNamedPort(out handle, name);
- }
- public Result ConnectToNamedPort(out int handle, string name)
- {
- handle = 0;
- if (name.Length > 11)
- {
- return KernelResult.MaximumExceeded;
- }
- KAutoObject autoObj = KAutoObject.FindNamedObject(_context, name);
- if (autoObj is not KClientPort clientPort)
- {
- return KernelResult.NotFound;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- Result result = currentProcess.HandleTable.ReserveHandle(out handle);
- if (result != Result.Success)
- {
- return result;
- }
- result = clientPort.Connect(out KClientSession clientSession);
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CancelHandleReservation(handle);
- return result;
- }
- currentProcess.HandleTable.SetReservedHandleObj(handle, clientSession);
- clientSession.DecrementReferenceCount();
- return result;
- }
- [Svc(0x21)]
- public Result SendSyncRequest(int handle)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KClientSession session = currentProcess.HandleTable.GetObject<KClientSession>(handle);
- if (session == null)
- {
- return KernelResult.InvalidHandle;
- }
- return session.SendSyncRequest();
- }
- [Svc(0x22)]
- public Result SendSyncRequestWithUserBuffer(
- [PointerSized] ulong messagePtr,
- [PointerSized] ulong messageSize,
- int handle)
- {
- if (!PageAligned(messagePtr))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(messageSize) || messageSize == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (messagePtr + messageSize <= messagePtr)
- {
- return KernelResult.InvalidMemState;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- Result result = currentProcess.MemoryManager.BorrowIpcBuffer(messagePtr, messageSize);
- if (result != Result.Success)
- {
- return result;
- }
- KClientSession session = currentProcess.HandleTable.GetObject<KClientSession>(handle);
- if (session == null)
- {
- result = KernelResult.InvalidHandle;
- }
- else
- {
- result = session.SendSyncRequest(messagePtr, messageSize);
- }
- Result result2 = currentProcess.MemoryManager.UnborrowIpcBuffer(messagePtr, messageSize);
- if (result == Result.Success)
- {
- result = result2;
- }
- return result;
- }
- [Svc(0x23)]
- public Result SendAsyncRequestWithUserBuffer(
- out int doneEventHandle,
- [PointerSized] ulong messagePtr,
- [PointerSized] ulong messageSize,
- int handle)
- {
- doneEventHandle = 0;
- if (!PageAligned(messagePtr))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(messageSize) || messageSize == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (messagePtr + messageSize <= messagePtr)
- {
- return KernelResult.InvalidMemState;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- Result result = currentProcess.MemoryManager.BorrowIpcBuffer(messagePtr, messageSize);
- if (result != Result.Success)
- {
- return result;
- }
- KResourceLimit resourceLimit = currentProcess.ResourceLimit;
- if (resourceLimit != null && !resourceLimit.Reserve(LimitableResource.Event, 1))
- {
- currentProcess.MemoryManager.UnborrowIpcBuffer(messagePtr, messageSize);
- return KernelResult.ResLimitExceeded;
- }
- KClientSession session = currentProcess.HandleTable.GetObject<KClientSession>(handle);
- if (session == null)
- {
- result = KernelResult.InvalidHandle;
- }
- else
- {
- KEvent doneEvent = new KEvent(_context);
- result = currentProcess.HandleTable.GenerateHandle(doneEvent.ReadableEvent, out doneEventHandle);
- if (result == Result.Success)
- {
- result = session.SendAsyncRequest(doneEvent.WritableEvent, messagePtr, messageSize);
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CloseHandle(doneEventHandle);
- }
- }
- }
- if (result != Result.Success)
- {
- resourceLimit?.Release(LimitableResource.Event, 1);
- currentProcess.MemoryManager.UnborrowIpcBuffer(messagePtr, messageSize);
- }
- return result;
- }
- [Svc(0x40)]
- public Result CreateSession(
- out int serverSessionHandle,
- out int clientSessionHandle,
- bool isLight,
- [PointerSized] ulong namePtr)
- {
- return CreateSession(out serverSessionHandle, out clientSessionHandle, isLight, null);
- }
- public Result CreateSession(
- out int serverSessionHandle,
- out int clientSessionHandle,
- bool isLight,
- string name)
- {
- serverSessionHandle = 0;
- clientSessionHandle = 0;
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KResourceLimit resourceLimit = currentProcess.ResourceLimit;
- if (resourceLimit != null && !resourceLimit.Reserve(LimitableResource.Session, 1))
- {
- return KernelResult.ResLimitExceeded;
- }
- Result result;
- if (isLight)
- {
- KLightSession session = new KLightSession(_context);
- result = currentProcess.HandleTable.GenerateHandle(session.ServerSession, out serverSessionHandle);
- if (result == Result.Success)
- {
- result = currentProcess.HandleTable.GenerateHandle(session.ClientSession, out clientSessionHandle);
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CloseHandle(serverSessionHandle);
- serverSessionHandle = 0;
- }
- }
- session.ServerSession.DecrementReferenceCount();
- session.ClientSession.DecrementReferenceCount();
- }
- else
- {
- KSession session = new KSession(_context);
- result = currentProcess.HandleTable.GenerateHandle(session.ServerSession, out serverSessionHandle);
- if (result == Result.Success)
- {
- result = currentProcess.HandleTable.GenerateHandle(session.ClientSession, out clientSessionHandle);
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CloseHandle(serverSessionHandle);
- serverSessionHandle = 0;
- }
- }
- session.ServerSession.DecrementReferenceCount();
- session.ClientSession.DecrementReferenceCount();
- }
- return result;
- }
- [Svc(0x41)]
- public Result AcceptSession(out int sessionHandle, int portHandle)
- {
- sessionHandle = 0;
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KServerPort serverPort = currentProcess.HandleTable.GetObject<KServerPort>(portHandle);
- if (serverPort == null)
- {
- return KernelResult.InvalidHandle;
- }
- Result result = currentProcess.HandleTable.ReserveHandle(out int handle);
- if (result != Result.Success)
- {
- return result;
- }
- KAutoObject session;
- if (serverPort.IsLight)
- {
- session = serverPort.AcceptIncomingLightConnection();
- }
- else
- {
- session = serverPort.AcceptIncomingConnection();
- }
- if (session != null)
- {
- currentProcess.HandleTable.SetReservedHandleObj(handle, session);
- session.DecrementReferenceCount();
- sessionHandle = handle;
- result = Result.Success;
- }
- else
- {
- currentProcess.HandleTable.CancelHandleReservation(handle);
- result = KernelResult.NotFound;
- }
- return result;
- }
- [Svc(0x43)]
- public Result ReplyAndReceive(
- out int handleIndex,
- [PointerSized] ulong handlesPtr,
- int handlesCount,
- int replyTargetHandle,
- long timeout)
- {
- handleIndex = 0;
- if ((uint)handlesCount > 0x40)
- {
- return KernelResult.MaximumExceeded;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- ulong copySize = (ulong)((long)handlesCount * 4);
- if (!currentProcess.MemoryManager.InsideAddrSpace(handlesPtr, copySize))
- {
- return KernelResult.UserCopyFailed;
- }
- if (handlesPtr + copySize < handlesPtr)
- {
- return KernelResult.UserCopyFailed;
- }
- int[] handles = new int[handlesCount];
- if (!KernelTransfer.UserToKernelArray<int>(handlesPtr, handles))
- {
- return KernelResult.UserCopyFailed;
- }
- if (timeout > 0)
- {
- timeout += KTimeManager.DefaultTimeIncrementNanoseconds;
- }
- return ReplyAndReceive(out handleIndex, handles, replyTargetHandle, timeout);
- }
- public Result ReplyAndReceive(out int handleIndex, ReadOnlySpan<int> handles, int replyTargetHandle, long timeout)
- {
- handleIndex = 0;
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KSynchronizationObject[] syncObjs = new KSynchronizationObject[handles.Length];
- for (int index = 0; index < handles.Length; index++)
- {
- KSynchronizationObject obj = currentProcess.HandleTable.GetObject<KSynchronizationObject>(handles[index]);
- if (obj == null)
- {
- return KernelResult.InvalidHandle;
- }
- syncObjs[index] = obj;
- }
- Result result = Result.Success;
- if (replyTargetHandle != 0)
- {
- KServerSession replyTarget = currentProcess.HandleTable.GetObject<KServerSession>(replyTargetHandle);
- if (replyTarget == null)
- {
- result = KernelResult.InvalidHandle;
- }
- else
- {
- result = replyTarget.Reply();
- }
- }
- if (result == Result.Success)
- {
- if (timeout > 0)
- {
- timeout += KTimeManager.DefaultTimeIncrementNanoseconds;
- }
- while ((result = _context.Synchronization.WaitFor(syncObjs, timeout, out handleIndex)) == Result.Success)
- {
- KServerSession session = currentProcess.HandleTable.GetObject<KServerSession>(handles[handleIndex]);
- if (session == null)
- {
- break;
- }
- if ((result = session.Receive()) != KernelResult.NotFound)
- {
- break;
- }
- }
- }
- return result;
- }
- [Svc(0x44)]
- public Result ReplyAndReceiveWithUserBuffer(
- out int handleIndex,
- [PointerSized] ulong messagePtr,
- [PointerSized] ulong messageSize,
- [PointerSized] ulong handlesPtr,
- int handlesCount,
- int replyTargetHandle,
- long timeout)
- {
- handleIndex = 0;
- if ((uint)handlesCount > 0x40)
- {
- return KernelResult.MaximumExceeded;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- ulong copySize = (ulong)((long)handlesCount * 4);
- if (!currentProcess.MemoryManager.InsideAddrSpace(handlesPtr, copySize))
- {
- return KernelResult.UserCopyFailed;
- }
- if (handlesPtr + copySize < handlesPtr)
- {
- return KernelResult.UserCopyFailed;
- }
- Result result = currentProcess.MemoryManager.BorrowIpcBuffer(messagePtr, messageSize);
- if (result != Result.Success)
- {
- return result;
- }
- int[] handles = new int[handlesCount];
- if (!KernelTransfer.UserToKernelArray<int>(handlesPtr, handles))
- {
- currentProcess.MemoryManager.UnborrowIpcBuffer(messagePtr, messageSize);
- return KernelResult.UserCopyFailed;
- }
- KSynchronizationObject[] syncObjs = new KSynchronizationObject[handlesCount];
- for (int index = 0; index < handlesCount; index++)
- {
- KSynchronizationObject obj = currentProcess.HandleTable.GetObject<KSynchronizationObject>(handles[index]);
- if (obj == null)
- {
- currentProcess.MemoryManager.UnborrowIpcBuffer(messagePtr, messageSize);
- return KernelResult.InvalidHandle;
- }
- syncObjs[index] = obj;
- }
- if (replyTargetHandle != 0)
- {
- KServerSession replyTarget = currentProcess.HandleTable.GetObject<KServerSession>(replyTargetHandle);
- if (replyTarget == null)
- {
- result = KernelResult.InvalidHandle;
- }
- else
- {
- result = replyTarget.Reply(messagePtr, messageSize);
- }
- }
- if (result == Result.Success)
- {
- if (timeout > 0)
- {
- timeout += KTimeManager.DefaultTimeIncrementNanoseconds;
- }
- while ((result = _context.Synchronization.WaitFor(syncObjs, timeout, out handleIndex)) == Result.Success)
- {
- KServerSession session = currentProcess.HandleTable.GetObject<KServerSession>(handles[handleIndex]);
- if (session == null)
- {
- break;
- }
- if ((result = session.Receive(messagePtr, messageSize)) != KernelResult.NotFound)
- {
- break;
- }
- }
- }
- currentProcess.MemoryManager.UnborrowIpcBuffer(messagePtr, messageSize);
- return result;
- }
- [Svc(0x70)]
- public Result CreatePort(
- out int serverPortHandle,
- out int clientPortHandle,
- int maxSessions,
- bool isLight,
- [PointerSized] ulong namePtr)
- {
- // The kernel doesn't use the name pointer, so we can just pass null as the name.
- return CreatePort(out serverPortHandle, out clientPortHandle, maxSessions, isLight, null);
- }
- public Result CreatePort(
- out int serverPortHandle,
- out int clientPortHandle,
- int maxSessions,
- bool isLight,
- string name)
- {
- serverPortHandle = clientPortHandle = 0;
- if (maxSessions < 1)
- {
- return KernelResult.MaximumExceeded;
- }
- KPort port = new KPort(_context, maxSessions, isLight, name);
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- Result result = currentProcess.HandleTable.GenerateHandle(port.ClientPort, out clientPortHandle);
- if (result != Result.Success)
- {
- return result;
- }
- result = currentProcess.HandleTable.GenerateHandle(port.ServerPort, out serverPortHandle);
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CloseHandle(clientPortHandle);
- }
- return result;
- }
- [Svc(0x71)]
- public Result ManageNamedPort(out int handle, [PointerSized] ulong namePtr, int maxSessions)
- {
- handle = 0;
- if (!KernelTransfer.UserToKernelString(out string name, namePtr, 12))
- {
- return KernelResult.UserCopyFailed;
- }
- if (name.Length > 11)
- {
- return KernelResult.MaximumExceeded;
- }
- return ManageNamedPort(out handle, name, maxSessions);
- }
- public Result ManageNamedPort(out int handle, string name, int maxSessions)
- {
- handle = 0;
- if (maxSessions < 0)
- {
- return KernelResult.MaximumExceeded;
- }
- if (maxSessions == 0)
- {
- return KAutoObject.RemoveName(_context, name);
- }
- KPort port = new KPort(_context, maxSessions, false, null);
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- Result result = currentProcess.HandleTable.GenerateHandle(port.ServerPort, out handle);
- if (result != Result.Success)
- {
- return result;
- }
- result = port.ClientPort.SetName(name);
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CloseHandle(handle);
- }
- return result;
- }
- [Svc(0x72)]
- public Result ConnectToPort(out int clientSessionHandle, int clientPortHandle)
- {
- clientSessionHandle = 0;
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KClientPort clientPort = currentProcess.HandleTable.GetObject<KClientPort>(clientPortHandle);
- if (clientPort == null)
- {
- return KernelResult.InvalidHandle;
- }
- Result result = currentProcess.HandleTable.ReserveHandle(out int handle);
- if (result != Result.Success)
- {
- return result;
- }
- KAutoObject session;
- if (clientPort.IsLight)
- {
- result = clientPort.ConnectLight(out KLightClientSession clientSession);
- session = clientSession;
- }
- else
- {
- result = clientPort.Connect(out KClientSession clientSession);
- session = clientSession;
- }
- if (result != Result.Success)
- {
- currentProcess.HandleTable.CancelHandleReservation(handle);
- return result;
- }
- currentProcess.HandleTable.SetReservedHandleObj(handle, session);
- session.DecrementReferenceCount();
- clientSessionHandle = handle;
- return result;
- }
- // Memory
- [Svc(1)]
- public Result SetHeapSize([PointerSized] out ulong address, [PointerSized] ulong size)
- {
- if ((size & 0xfffffffe001fffff) != 0)
- {
- address = 0;
- return KernelResult.InvalidSize;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- return process.MemoryManager.SetHeapSize(size, out address);
- }
- [Svc(2)]
- public Result SetMemoryPermission([PointerSized] ulong address, [PointerSized] ulong size, KMemoryPermission permission)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemState;
- }
- if (permission != KMemoryPermission.None && (permission | KMemoryPermission.Write) != KMemoryPermission.ReadAndWrite)
- {
- return KernelResult.InvalidPermission;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (!currentProcess.MemoryManager.InsideAddrSpace(address, size))
- {
- return KernelResult.InvalidMemState;
- }
- return currentProcess.MemoryManager.SetMemoryPermission(address, size, permission);
- }
- [Svc(3)]
- public Result SetMemoryAttribute(
- [PointerSized] ulong address,
- [PointerSized] ulong size,
- MemoryAttribute attributeMask,
- MemoryAttribute attributeValue)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- MemoryAttribute attributes = attributeMask | attributeValue;
- if (attributes != attributeMask ||
- (attributes | MemoryAttribute.Uncached) != MemoryAttribute.Uncached)
- {
- return KernelResult.InvalidCombination;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- if (!process.MemoryManager.InsideAddrSpace(address, size))
- {
- return KernelResult.InvalidMemState;
- }
- Result result = process.MemoryManager.SetMemoryAttribute(
- address,
- size,
- attributeMask,
- attributeValue);
- return result;
- }
- [Svc(4)]
- public Result MapMemory([PointerSized] ulong dst, [PointerSized] ulong src, [PointerSized] ulong size)
- {
- if (!PageAligned(src | dst))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (src + size <= src || dst + size <= dst)
- {
- return KernelResult.InvalidMemState;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (!currentProcess.MemoryManager.InsideAddrSpace(src, size))
- {
- return KernelResult.InvalidMemState;
- }
- if (currentProcess.MemoryManager.OutsideStackRegion(dst, size) ||
- currentProcess.MemoryManager.InsideHeapRegion(dst, size) ||
- currentProcess.MemoryManager.InsideAliasRegion(dst, size))
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- return process.MemoryManager.Map(dst, src, size);
- }
- [Svc(5)]
- public Result UnmapMemory([PointerSized] ulong dst, [PointerSized] ulong src, [PointerSized] ulong size)
- {
- if (!PageAligned(src | dst))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (src + size <= src || dst + size <= dst)
- {
- return KernelResult.InvalidMemState;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (!currentProcess.MemoryManager.InsideAddrSpace(src, size))
- {
- return KernelResult.InvalidMemState;
- }
- if (currentProcess.MemoryManager.OutsideStackRegion(dst, size) ||
- currentProcess.MemoryManager.InsideHeapRegion(dst, size) ||
- currentProcess.MemoryManager.InsideAliasRegion(dst, size))
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- return process.MemoryManager.Unmap(dst, src, size);
- }
- [Svc(6)]
- public Result QueryMemory([PointerSized] ulong infoPtr, [PointerSized] out ulong pageInfo, [PointerSized] ulong address)
- {
- Result result = QueryMemory(out MemoryInfo info, out pageInfo, address);
- if (result == Result.Success)
- {
- return KernelTransfer.KernelToUser(infoPtr, info)
- ? Result.Success
- : KernelResult.InvalidMemState;
- }
- return result;
- }
- public Result QueryMemory(out MemoryInfo info, out ulong pageInfo, ulong address)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KMemoryInfo blockInfo = process.MemoryManager.QueryMemory(address);
- info = new MemoryInfo(
- blockInfo.Address,
- blockInfo.Size,
- blockInfo.State & MemoryState.UserMask,
- blockInfo.Attribute,
- blockInfo.Permission & KMemoryPermission.UserMask,
- blockInfo.IpcRefCount,
- blockInfo.DeviceRefCount);
- pageInfo = 0;
- return Result.Success;
- }
- [Svc(0x13)]
- public Result MapSharedMemory(int handle, [PointerSized] ulong address, [PointerSized] ulong size, KMemoryPermission permission)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemState;
- }
- if ((permission | KMemoryPermission.Write) != KMemoryPermission.ReadAndWrite)
- {
- return KernelResult.InvalidPermission;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KSharedMemory sharedMemory = currentProcess.HandleTable.GetObject<KSharedMemory>(handle);
- if (sharedMemory == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (currentProcess.MemoryManager.IsInvalidRegion(address, size) ||
- currentProcess.MemoryManager.InsideHeapRegion(address, size) ||
- currentProcess.MemoryManager.InsideAliasRegion(address, size))
- {
- return KernelResult.InvalidMemRange;
- }
- return sharedMemory.MapIntoProcess(
- currentProcess.MemoryManager,
- address,
- size,
- currentProcess,
- permission);
- }
- [Svc(0x14)]
- public Result UnmapSharedMemory(int handle, [PointerSized] ulong address, [PointerSized] ulong size)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemState;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KSharedMemory sharedMemory = currentProcess.HandleTable.GetObject<KSharedMemory>(handle);
- if (sharedMemory == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (currentProcess.MemoryManager.IsInvalidRegion(address, size) ||
- currentProcess.MemoryManager.InsideHeapRegion(address, size) ||
- currentProcess.MemoryManager.InsideAliasRegion(address, size))
- {
- return KernelResult.InvalidMemRange;
- }
- return sharedMemory.UnmapFromProcess(
- currentProcess.MemoryManager,
- address,
- size,
- currentProcess);
- }
- [Svc(0x15)]
- public Result CreateTransferMemory(out int handle, [PointerSized] ulong address, [PointerSized] ulong size, KMemoryPermission permission)
- {
- handle = 0;
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemState;
- }
- if (permission > KMemoryPermission.ReadAndWrite || permission == KMemoryPermission.Write)
- {
- return KernelResult.InvalidPermission;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- KResourceLimit resourceLimit = process.ResourceLimit;
- if (resourceLimit != null && !resourceLimit.Reserve(LimitableResource.TransferMemory, 1))
- {
- return KernelResult.ResLimitExceeded;
- }
- void CleanUpForError()
- {
- resourceLimit?.Release(LimitableResource.TransferMemory, 1);
- }
- if (!process.MemoryManager.InsideAddrSpace(address, size))
- {
- CleanUpForError();
- return KernelResult.InvalidMemState;
- }
- KTransferMemory transferMemory = new KTransferMemory(_context);
- Result result = transferMemory.Initialize(address, size, permission);
- if (result != Result.Success)
- {
- CleanUpForError();
- return result;
- }
- result = process.HandleTable.GenerateHandle(transferMemory, out handle);
- transferMemory.DecrementReferenceCount();
- return result;
- }
- [Svc(0x51)]
- public Result MapTransferMemory(int handle, [PointerSized] ulong address, [PointerSized] ulong size, KMemoryPermission permission)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemState;
- }
- if (permission > KMemoryPermission.ReadAndWrite || permission == KMemoryPermission.Write)
- {
- return KernelResult.InvalidPermission;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KTransferMemory transferMemory = currentProcess.HandleTable.GetObject<KTransferMemory>(handle);
- if (transferMemory == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (currentProcess.MemoryManager.IsInvalidRegion(address, size) ||
- currentProcess.MemoryManager.InsideHeapRegion(address, size) ||
- currentProcess.MemoryManager.InsideAliasRegion(address, size))
- {
- return KernelResult.InvalidMemRange;
- }
- return transferMemory.MapIntoProcess(
- currentProcess.MemoryManager,
- address,
- size,
- currentProcess,
- permission);
- }
- [Svc(0x52)]
- public Result UnmapTransferMemory(int handle, [PointerSized] ulong address, [PointerSized] ulong size)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemState;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KTransferMemory transferMemory = currentProcess.HandleTable.GetObject<KTransferMemory>(handle);
- if (transferMemory == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (currentProcess.MemoryManager.IsInvalidRegion(address, size) ||
- currentProcess.MemoryManager.InsideHeapRegion(address, size) ||
- currentProcess.MemoryManager.InsideAliasRegion(address, size))
- {
- return KernelResult.InvalidMemRange;
- }
- return transferMemory.UnmapFromProcess(
- currentProcess.MemoryManager,
- address,
- size,
- currentProcess);
- }
- [Svc(0x2c)]
- public Result MapPhysicalMemory([PointerSized] ulong address, [PointerSized] ulong size)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if ((currentProcess.PersonalMmHeapPagesCount & 0xfffffffffffff) == 0)
- {
- return KernelResult.InvalidState;
- }
- if (!currentProcess.MemoryManager.InsideAddrSpace(address, size) ||
- currentProcess.MemoryManager.OutsideAliasRegion(address, size))
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- return process.MemoryManager.MapPhysicalMemory(address, size);
- }
- [Svc(0x2d)]
- public Result UnmapPhysicalMemory([PointerSized] ulong address, [PointerSized] ulong size)
- {
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (address + size <= address)
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if ((currentProcess.PersonalMmHeapPagesCount & 0xfffffffffffff) == 0)
- {
- return KernelResult.InvalidState;
- }
- if (!currentProcess.MemoryManager.InsideAddrSpace(address, size) ||
- currentProcess.MemoryManager.OutsideAliasRegion(address, size))
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- return process.MemoryManager.UnmapPhysicalMemory(address, size);
- }
- [Svc(0x4b)]
- public Result CreateCodeMemory(out int handle, [PointerSized] ulong address, [PointerSized] ulong size)
- {
- handle = 0;
- if (!PageAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (size + address <= address)
- {
- return KernelResult.InvalidMemState;
- }
- KCodeMemory codeMemory = new KCodeMemory(_context);
- using var _ = new OnScopeExit(codeMemory.DecrementReferenceCount);
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (!currentProcess.MemoryManager.InsideAddrSpace(address, size))
- {
- return KernelResult.InvalidMemState;
- }
- Result result = codeMemory.Initialize(address, size);
- if (result != Result.Success)
- {
- return result;
- }
- return currentProcess.HandleTable.GenerateHandle(codeMemory, out handle);
- }
- [Svc(0x4c)]
- public Result ControlCodeMemory(
- int handle,
- CodeMemoryOperation op,
- ulong address,
- ulong size,
- KMemoryPermission permission)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KCodeMemory codeMemory = currentProcess.HandleTable.GetObject<KCodeMemory>(handle);
- // Newer versions of the kernel also returns an error here if the owner and process
- // where the operation will happen are the same. We do not return an error here
- // for homebrew because some of them requires this to be patched out to work (for JIT).
- if (codeMemory == null || (!currentProcess.AllowCodeMemoryForJit && codeMemory.Owner == currentProcess))
- {
- return KernelResult.InvalidHandle;
- }
- switch (op)
- {
- case CodeMemoryOperation.Map:
- if (!currentProcess.MemoryManager.CanContain(address, size, MemoryState.CodeWritable))
- {
- return KernelResult.InvalidMemRange;
- }
- if (permission != KMemoryPermission.ReadAndWrite)
- {
- return KernelResult.InvalidPermission;
- }
- return codeMemory.Map(address, size, permission);
- case CodeMemoryOperation.MapToOwner:
- if (!currentProcess.MemoryManager.CanContain(address, size, MemoryState.CodeReadOnly))
- {
- return KernelResult.InvalidMemRange;
- }
- if (permission != KMemoryPermission.Read && permission != KMemoryPermission.ReadAndExecute)
- {
- return KernelResult.InvalidPermission;
- }
- return codeMemory.MapToOwner(address, size, permission);
- case CodeMemoryOperation.Unmap:
- if (!currentProcess.MemoryManager.CanContain(address, size, MemoryState.CodeWritable))
- {
- return KernelResult.InvalidMemRange;
- }
- if (permission != KMemoryPermission.None)
- {
- return KernelResult.InvalidPermission;
- }
- return codeMemory.Unmap(address, size);
- case CodeMemoryOperation.UnmapFromOwner:
- if (!currentProcess.MemoryManager.CanContain(address, size, MemoryState.CodeReadOnly))
- {
- return KernelResult.InvalidMemRange;
- }
- if (permission != KMemoryPermission.None)
- {
- return KernelResult.InvalidPermission;
- }
- return codeMemory.UnmapFromOwner(address, size);
- default: return KernelResult.InvalidEnumValue;
- }
- }
- [Svc(0x73)]
- public Result SetProcessMemoryPermission(
- int handle,
- [PointerSized] ulong src,
- [PointerSized] ulong size,
- KMemoryPermission permission)
- {
- if (!PageAligned(src))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (permission != KMemoryPermission.None &&
- permission != KMemoryPermission.Read &&
- permission != KMemoryPermission.ReadAndWrite &&
- permission != KMemoryPermission.ReadAndExecute)
- {
- return KernelResult.InvalidPermission;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KProcess targetProcess = currentProcess.HandleTable.GetObject<KProcess>(handle);
- if (targetProcess == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (targetProcess.MemoryManager.OutsideAddrSpace(src, size))
- {
- return KernelResult.InvalidMemState;
- }
- return targetProcess.MemoryManager.SetProcessMemoryPermission(src, size, permission);
- }
- [Svc(0x74)]
- public Result MapProcessMemory(
- [PointerSized] ulong dst,
- int handle,
- ulong src,
- [PointerSized] ulong size)
- {
- if (!PageAligned(src) || !PageAligned(dst))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (dst + size <= dst || src + size <= src)
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess dstProcess = KernelStatic.GetCurrentProcess();
- KProcess srcProcess = dstProcess.HandleTable.GetObject<KProcess>(handle);
- if (srcProcess == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (!srcProcess.MemoryManager.InsideAddrSpace(src, size) ||
- !dstProcess.MemoryManager.CanContain(dst, size, MemoryState.ProcessMemory))
- {
- return KernelResult.InvalidMemRange;
- }
- KPageList pageList = new KPageList();
- Result result = srcProcess.MemoryManager.GetPagesIfStateEquals(
- src,
- size,
- MemoryState.MapProcessAllowed,
- MemoryState.MapProcessAllowed,
- KMemoryPermission.None,
- KMemoryPermission.None,
- MemoryAttribute.Mask,
- MemoryAttribute.None,
- pageList);
- if (result != Result.Success)
- {
- return result;
- }
- return dstProcess.MemoryManager.MapPages(dst, pageList, MemoryState.ProcessMemory, KMemoryPermission.ReadAndWrite);
- }
- [Svc(0x75)]
- public Result UnmapProcessMemory(
- [PointerSized] ulong dst,
- int handle,
- ulong src,
- [PointerSized] ulong size)
- {
- if (!PageAligned(src) || !PageAligned(dst))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- if (dst + size <= dst || src + size <= src)
- {
- return KernelResult.InvalidMemRange;
- }
- KProcess dstProcess = KernelStatic.GetCurrentProcess();
- KProcess srcProcess = dstProcess.HandleTable.GetObject<KProcess>(handle);
- if (srcProcess == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (!srcProcess.MemoryManager.InsideAddrSpace(src, size) ||
- !dstProcess.MemoryManager.CanContain(dst, size, MemoryState.ProcessMemory))
- {
- return KernelResult.InvalidMemRange;
- }
- Result result = dstProcess.MemoryManager.UnmapProcessMemory(dst, size, srcProcess.MemoryManager, src);
- if (result != Result.Success)
- {
- return result;
- }
- return Result.Success;
- }
- [Svc(0x77)]
- public Result MapProcessCodeMemory(int handle, ulong dst, ulong src, ulong size)
- {
- if (!PageAligned(dst) || !PageAligned(src))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KProcess targetProcess = currentProcess.HandleTable.GetObject<KProcess>(handle);
- if (targetProcess == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (targetProcess.MemoryManager.OutsideAddrSpace(dst, size) ||
- targetProcess.MemoryManager.OutsideAddrSpace(src, size) ||
- targetProcess.MemoryManager.InsideAliasRegion(dst, size) ||
- targetProcess.MemoryManager.InsideHeapRegion(dst, size))
- {
- return KernelResult.InvalidMemRange;
- }
- if (size + dst <= dst || size + src <= src)
- {
- return KernelResult.InvalidMemState;
- }
- return targetProcess.MemoryManager.MapProcessCodeMemory(dst, src, size);
- }
- [Svc(0x78)]
- public Result UnmapProcessCodeMemory(int handle, ulong dst, ulong src, ulong size)
- {
- if (!PageAligned(dst) || !PageAligned(src))
- {
- return KernelResult.InvalidAddress;
- }
- if (!PageAligned(size) || size == 0)
- {
- return KernelResult.InvalidSize;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KProcess targetProcess = currentProcess.HandleTable.GetObject<KProcess>(handle);
- if (targetProcess == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (targetProcess.MemoryManager.OutsideAddrSpace(dst, size) ||
- targetProcess.MemoryManager.OutsideAddrSpace(src, size) ||
- targetProcess.MemoryManager.InsideAliasRegion(dst, size) ||
- targetProcess.MemoryManager.InsideHeapRegion(dst, size))
- {
- return KernelResult.InvalidMemRange;
- }
- if (size + dst <= dst || size + src <= src)
- {
- return KernelResult.InvalidMemState;
- }
- return targetProcess.MemoryManager.UnmapProcessCodeMemory(dst, src, size);
- }
- private static bool PageAligned(ulong address)
- {
- return (address & (KPageTableBase.PageSize - 1)) == 0;
- }
- // System
- [Svc(0x7b)]
- public Result TerminateProcess(int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- process = process.HandleTable.GetObject<KProcess>(handle);
- Result result;
- if (process != null)
- {
- if (process == KernelStatic.GetCurrentProcess())
- {
- result = Result.Success;
- process.DecrementToZeroWhileTerminatingCurrent();
- }
- else
- {
- result = process.Terminate();
- process.DecrementReferenceCount();
- }
- }
- else
- {
- result = KernelResult.InvalidHandle;
- }
- return result;
- }
- [Svc(7)]
- public void ExitProcess()
- {
- KernelStatic.GetCurrentProcess().TerminateCurrentProcess();
- }
- [Svc(0x11)]
- public Result SignalEvent(int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KWritableEvent writableEvent = process.HandleTable.GetObject<KWritableEvent>(handle);
- Result result;
- if (writableEvent != null)
- {
- writableEvent.Signal();
- result = Result.Success;
- }
- else
- {
- result = KernelResult.InvalidHandle;
- }
- return result;
- }
- [Svc(0x12)]
- public Result ClearEvent(int handle)
- {
- Result result;
- KProcess process = KernelStatic.GetCurrentProcess();
- KWritableEvent writableEvent = process.HandleTable.GetObject<KWritableEvent>(handle);
- if (writableEvent == null)
- {
- KReadableEvent readableEvent = process.HandleTable.GetObject<KReadableEvent>(handle);
- result = readableEvent?.Clear() ?? KernelResult.InvalidHandle;
- }
- else
- {
- result = writableEvent.Clear();
- }
- return result;
- }
- [Svc(0x16)]
- public Result CloseHandle(int handle)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- return currentProcess.HandleTable.CloseHandle(handle) ? Result.Success : KernelResult.InvalidHandle;
- }
- [Svc(0x17)]
- public Result ResetSignal(int handle)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KReadableEvent readableEvent = currentProcess.HandleTable.GetObject<KReadableEvent>(handle);
- Result result;
- if (readableEvent != null)
- {
- result = readableEvent.ClearIfSignaled();
- }
- else
- {
- KProcess process = currentProcess.HandleTable.GetKProcess(handle);
- if (process != null)
- {
- result = process.ClearIfNotExited();
- }
- else
- {
- result = KernelResult.InvalidHandle;
- }
- }
- return result;
- }
- [Svc(0x1e)]
- public ulong GetSystemTick()
- {
- return _context.TickSource.Counter;
- }
- [Svc(0x26)]
- public void Break(ulong reason)
- {
- KThread currentThread = KernelStatic.GetCurrentThread();
- if ((reason & (1UL << 31)) == 0)
- {
- currentThread.PrintGuestStackTrace();
- currentThread.PrintGuestRegisterPrintout();
- // As the process is exiting, this is probably caused by emulation termination.
- if (currentThread.Owner.State == ProcessState.Exiting)
- {
- return;
- }
- // TODO: Debug events.
- currentThread.Owner.TerminateCurrentProcess();
- throw new GuestBrokeExecutionException();
- }
- else
- {
- Logger.Debug?.Print(LogClass.KernelSvc, "Debugger triggered.");
- }
- }
- [Svc(0x27)]
- public void OutputDebugString([PointerSized] ulong strPtr, [PointerSized] ulong size)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- string str = MemoryHelper.ReadAsciiString(process.CpuMemory, strPtr, (long)size);
- Logger.Warning?.Print(LogClass.KernelSvc, str);
- }
- [Svc(0x29)]
- public Result GetInfo(out ulong value, InfoType id, int handle, long subId)
- {
- value = 0;
- switch (id)
- {
- case InfoType.CoreMask:
- case InfoType.PriorityMask:
- case InfoType.AliasRegionAddress:
- case InfoType.AliasRegionSize:
- case InfoType.HeapRegionAddress:
- case InfoType.HeapRegionSize:
- case InfoType.TotalMemorySize:
- case InfoType.UsedMemorySize:
- case InfoType.AslrRegionAddress:
- case InfoType.AslrRegionSize:
- case InfoType.StackRegionAddress:
- case InfoType.StackRegionSize:
- case InfoType.SystemResourceSizeTotal:
- case InfoType.SystemResourceSizeUsed:
- case InfoType.ProgramId:
- case InfoType.UserExceptionContextAddress:
- case InfoType.TotalNonSystemMemorySize:
- case InfoType.UsedNonSystemMemorySize:
- case InfoType.IsApplication:
- case InfoType.FreeThreadCount:
- {
- if (subId != 0)
- {
- return KernelResult.InvalidCombination;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KProcess process = currentProcess.HandleTable.GetKProcess(handle);
- if (process == null)
- {
- return KernelResult.InvalidHandle;
- }
- switch (id)
- {
- case InfoType.CoreMask: value = process.Capabilities.AllowedCpuCoresMask; break;
- case InfoType.PriorityMask: value = process.Capabilities.AllowedThreadPriosMask; break;
- case InfoType.AliasRegionAddress: value = process.MemoryManager.AliasRegionStart; break;
- case InfoType.AliasRegionSize:
- value = (process.MemoryManager.AliasRegionEnd -
- process.MemoryManager.AliasRegionStart); break;
- case InfoType.HeapRegionAddress: value = process.MemoryManager.HeapRegionStart; break;
- case InfoType.HeapRegionSize:
- value = (process.MemoryManager.HeapRegionEnd -
- process.MemoryManager.HeapRegionStart); break;
- case InfoType.TotalMemorySize: value = process.GetMemoryCapacity(); break;
- case InfoType.UsedMemorySize: value = process.GetMemoryUsage(); break;
- case InfoType.AslrRegionAddress: value = process.MemoryManager.GetAddrSpaceBaseAddr(); break;
- case InfoType.AslrRegionSize: value = process.MemoryManager.GetAddrSpaceSize(); break;
- case InfoType.StackRegionAddress: value = process.MemoryManager.StackRegionStart; break;
- case InfoType.StackRegionSize:
- value = (process.MemoryManager.StackRegionEnd -
- process.MemoryManager.StackRegionStart); break;
- case InfoType.SystemResourceSizeTotal: value = process.PersonalMmHeapPagesCount * KPageTableBase.PageSize; break;
- case InfoType.SystemResourceSizeUsed:
- if (process.PersonalMmHeapPagesCount != 0)
- {
- value = process.MemoryManager.GetMmUsedPages() * KPageTableBase.PageSize;
- }
- break;
- case InfoType.ProgramId: value = process.TitleId; break;
- case InfoType.UserExceptionContextAddress: value = process.UserExceptionContextAddress; break;
- case InfoType.TotalNonSystemMemorySize: value = process.GetMemoryCapacityWithoutPersonalMmHeap(); break;
- case InfoType.UsedNonSystemMemorySize: value = process.GetMemoryUsageWithoutPersonalMmHeap(); break;
- case InfoType.IsApplication: value = process.IsApplication ? 1UL : 0UL; break;
- case InfoType.FreeThreadCount:
- if (process.ResourceLimit != null)
- {
- value = (ulong)(process.ResourceLimit.GetLimitValue(LimitableResource.Thread) -
- process.ResourceLimit.GetCurrentValue(LimitableResource.Thread));
- }
- else
- {
- value = 0;
- }
- break;
- }
- break;
- }
- case InfoType.DebuggerAttached:
- {
- if (handle != 0)
- {
- return KernelResult.InvalidHandle;
- }
- if (subId != 0)
- {
- return KernelResult.InvalidCombination;
- }
- value = KernelStatic.GetCurrentProcess().Debug ? 1UL : 0UL;
- break;
- }
- case InfoType.ResourceLimit:
- {
- if (handle != 0)
- {
- return KernelResult.InvalidHandle;
- }
- if (subId != 0)
- {
- return KernelResult.InvalidCombination;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (currentProcess.ResourceLimit != null)
- {
- KHandleTable handleTable = currentProcess.HandleTable;
- KResourceLimit resourceLimit = currentProcess.ResourceLimit;
- Result result = handleTable.GenerateHandle(resourceLimit, out int resLimHandle);
- if (result != Result.Success)
- {
- return result;
- }
- value = (uint)resLimHandle;
- }
- break;
- }
- case InfoType.IdleTickCount:
- {
- if (handle != 0)
- {
- return KernelResult.InvalidHandle;
- }
- int currentCore = KernelStatic.GetCurrentThread().CurrentCore;
- if (subId != -1 && subId != currentCore)
- {
- return KernelResult.InvalidCombination;
- }
- value = (ulong)KTimeManager.ConvertHostTicksToTicks(_context.Schedulers[currentCore].TotalIdleTimeTicks);
- break;
- }
- case InfoType.RandomEntropy:
- {
- if (handle != 0)
- {
- return KernelResult.InvalidHandle;
- }
- if ((ulong)subId > 3)
- {
- return KernelResult.InvalidCombination;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- value = currentProcess.RandomEntropy[subId];
- break;
- }
- case InfoType.ThreadTickCount:
- {
- if (subId < -1 || subId > 3)
- {
- return KernelResult.InvalidCombination;
- }
- KThread thread = KernelStatic.GetCurrentProcess().HandleTable.GetKThread(handle);
- if (thread == null)
- {
- return KernelResult.InvalidHandle;
- }
- KThread currentThread = KernelStatic.GetCurrentThread();
- int currentCore = currentThread.CurrentCore;
- if (subId != -1 && subId != currentCore)
- {
- return Result.Success;
- }
- KScheduler scheduler = _context.Schedulers[currentCore];
- long timeDelta = PerformanceCounter.ElapsedTicks - scheduler.LastContextSwitchTime;
- if (subId != -1)
- {
- value = (ulong)KTimeManager.ConvertHostTicksToTicks(timeDelta);
- }
- else
- {
- long totalTimeRunning = thread.TotalTimeRunning;
- if (thread == currentThread)
- {
- totalTimeRunning += timeDelta;
- }
- value = (ulong)KTimeManager.ConvertHostTicksToTicks(totalTimeRunning);
- }
- break;
- }
- case InfoType.MesosphereCurrentProcess:
- {
- if (handle != 0)
- {
- return KernelResult.InvalidHandle;
- }
- if ((ulong)subId != 0)
- {
- return KernelResult.InvalidCombination;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KHandleTable handleTable = currentProcess.HandleTable;
- Result result = handleTable.GenerateHandle(currentProcess, out int outHandle);
- if (result != Result.Success)
- {
- return result;
- }
- value = (ulong)outHandle;
- break;
- }
- default: return KernelResult.InvalidEnumValue;
- }
- return Result.Success;
- }
- [Svc(0x45)]
- public Result CreateEvent(out int wEventHandle, out int rEventHandle)
- {
- KEvent Event = new KEvent(_context);
- KProcess process = KernelStatic.GetCurrentProcess();
- Result result = process.HandleTable.GenerateHandle(Event.WritableEvent, out wEventHandle);
- if (result == Result.Success)
- {
- result = process.HandleTable.GenerateHandle(Event.ReadableEvent, out rEventHandle);
- if (result != Result.Success)
- {
- process.HandleTable.CloseHandle(wEventHandle);
- }
- }
- else
- {
- rEventHandle = 0;
- }
- return result;
- }
- [Svc(0x65)]
- public Result GetProcessList(out int count, [PointerSized] ulong address, int maxCount)
- {
- count = 0;
- if ((maxCount >> 28) != 0)
- {
- return KernelResult.MaximumExceeded;
- }
- if (maxCount != 0)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- ulong copySize = (ulong)maxCount * 8;
- if (address + copySize <= address)
- {
- return KernelResult.InvalidMemState;
- }
- if (currentProcess.MemoryManager.OutsideAddrSpace(address, copySize))
- {
- return KernelResult.InvalidMemState;
- }
- }
- int copyCount = 0;
- lock (_context.Processes)
- {
- foreach (KProcess process in _context.Processes.Values)
- {
- if (copyCount < maxCount)
- {
- if (!KernelTransfer.KernelToUser(address + (ulong)copyCount * 8, process.Pid))
- {
- return KernelResult.UserCopyFailed;
- }
- }
- copyCount++;
- }
- }
- count = copyCount;
- return Result.Success;
- }
- [Svc(0x6f)]
- public Result GetSystemInfo(out long value, uint id, int handle, long subId)
- {
- value = 0;
- if (id > 2)
- {
- return KernelResult.InvalidEnumValue;
- }
- if (handle != 0)
- {
- return KernelResult.InvalidHandle;
- }
- if (id < 2)
- {
- if ((ulong)subId > 3)
- {
- return KernelResult.InvalidCombination;
- }
- KMemoryRegionManager region = _context.MemoryManager.MemoryRegions[subId];
- switch (id)
- {
- // Memory region capacity.
- case 0: value = (long)region.Size; break;
- // Memory region free space.
- case 1:
- {
- ulong freePagesCount = region.GetFreePages();
- value = (long)(freePagesCount * KPageTableBase.PageSize);
- break;
- }
- }
- }
- else /* if (Id == 2) */
- {
- if ((ulong)subId > 1)
- {
- return KernelResult.InvalidCombination;
- }
- switch (subId)
- {
- case 0: value = _context.PrivilegedProcessLowestId; break;
- case 1: value = _context.PrivilegedProcessHighestId; break;
- }
- }
- return Result.Success;
- }
- [Svc(0x30)]
- public Result GetResourceLimitLimitValue(out long limitValue, int handle, LimitableResource resource)
- {
- limitValue = 0;
- if (resource >= LimitableResource.Count)
- {
- return KernelResult.InvalidEnumValue;
- }
- KResourceLimit resourceLimit = KernelStatic.GetCurrentProcess().HandleTable.GetObject<KResourceLimit>(handle);
- if (resourceLimit == null)
- {
- return KernelResult.InvalidHandle;
- }
- limitValue = resourceLimit.GetLimitValue(resource);
- return Result.Success;
- }
- [Svc(0x31)]
- public Result GetResourceLimitCurrentValue(out long limitValue, int handle, LimitableResource resource)
- {
- limitValue = 0;
- if (resource >= LimitableResource.Count)
- {
- return KernelResult.InvalidEnumValue;
- }
- KResourceLimit resourceLimit = KernelStatic.GetCurrentProcess().HandleTable.GetObject<KResourceLimit>(handle);
- if (resourceLimit == null)
- {
- return KernelResult.InvalidHandle;
- }
- limitValue = resourceLimit.GetCurrentValue(resource);
- return Result.Success;
- }
- [Svc(0x37)]
- public Result GetResourceLimitPeakValue(out long peak, int handle, LimitableResource resource)
- {
- peak = 0;
- if (resource >= LimitableResource.Count)
- {
- return KernelResult.InvalidEnumValue;
- }
- KResourceLimit resourceLimit = KernelStatic.GetCurrentProcess().HandleTable.GetObject<KResourceLimit>(handle);
- if (resourceLimit == null)
- {
- return KernelResult.InvalidHandle;
- }
- peak = resourceLimit.GetPeakValue(resource);
- return Result.Success;
- }
- [Svc(0x7d)]
- public Result CreateResourceLimit(out int handle)
- {
- KResourceLimit limit = new KResourceLimit(_context);
- KProcess process = KernelStatic.GetCurrentProcess();
- return process.HandleTable.GenerateHandle(limit, out handle);
- }
- [Svc(0x7e)]
- public Result SetResourceLimitLimitValue(int handle, LimitableResource resource, long limitValue)
- {
- if (resource >= LimitableResource.Count)
- {
- return KernelResult.InvalidEnumValue;
- }
- KResourceLimit resourceLimit = KernelStatic.GetCurrentProcess().HandleTable.GetObject<KResourceLimit>(handle);
- if (resourceLimit == null)
- {
- return KernelResult.InvalidHandle;
- }
- return resourceLimit.SetLimitValue(resource, limitValue);
- }
- // Thread
- [Svc(8)]
- public Result CreateThread(
- out int handle,
- [PointerSized] ulong entrypoint,
- [PointerSized] ulong argsPtr,
- [PointerSized] ulong stackTop,
- int priority,
- int cpuCore)
- {
- return CreateThread(out handle, entrypoint, argsPtr, stackTop, priority, cpuCore, null);
- }
- public Result CreateThread(
- out int handle,
- ulong entrypoint,
- ulong argsPtr,
- ulong stackTop,
- int priority,
- int cpuCore,
- ThreadStart customThreadStart)
- {
- handle = 0;
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (cpuCore == -2)
- {
- cpuCore = currentProcess.DefaultCpuCore;
- }
- if ((uint)cpuCore >= KScheduler.CpuCoresCount || !currentProcess.IsCpuCoreAllowed(cpuCore))
- {
- return KernelResult.InvalidCpuCore;
- }
- if ((uint)priority >= KScheduler.PrioritiesCount || !currentProcess.IsPriorityAllowed(priority))
- {
- return KernelResult.InvalidPriority;
- }
- long timeout = KTimeManager.ConvertMillisecondsToNanoseconds(100);
- if (currentProcess.ResourceLimit != null &&
- !currentProcess.ResourceLimit.Reserve(LimitableResource.Thread, 1, timeout))
- {
- return KernelResult.ResLimitExceeded;
- }
- KThread thread = new KThread(_context);
- Result result = currentProcess.InitializeThread(
- thread,
- entrypoint,
- argsPtr,
- stackTop,
- priority,
- cpuCore,
- customThreadStart);
- if (result == Result.Success)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- result = process.HandleTable.GenerateHandle(thread, out handle);
- }
- else
- {
- currentProcess.ResourceLimit?.Release(LimitableResource.Thread, 1);
- }
- thread.DecrementReferenceCount();
- return result;
- }
- [Svc(9)]
- public Result StartThread(int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread != null)
- {
- thread.IncrementReferenceCount();
- Result result = thread.Start();
- if (result == Result.Success)
- {
- thread.IncrementReferenceCount();
- }
- thread.DecrementReferenceCount();
- return result;
- }
- else
- {
- return KernelResult.InvalidHandle;
- }
- }
- [Svc(0xa)]
- public void ExitThread()
- {
- KThread currentThread = KernelStatic.GetCurrentThread();
- currentThread.Exit();
- }
- [Svc(0xb)]
- public void SleepThread(long timeout)
- {
- if (timeout < 1)
- {
- switch (timeout)
- {
- case 0: KScheduler.Yield(_context); break;
- case -1: KScheduler.YieldWithLoadBalancing(_context); break;
- case -2: KScheduler.YieldToAnyThread(_context); break;
- }
- }
- else
- {
- KernelStatic.GetCurrentThread().Sleep(timeout + KTimeManager.DefaultTimeIncrementNanoseconds);
- }
- }
- [Svc(0xc)]
- public Result GetThreadPriority(out int priority, int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread != null)
- {
- priority = thread.DynamicPriority;
- return Result.Success;
- }
- else
- {
- priority = 0;
- return KernelResult.InvalidHandle;
- }
- }
- [Svc(0xd)]
- public Result SetThreadPriority(int handle, int priority)
- {
- // TODO: NPDM check.
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread == null)
- {
- return KernelResult.InvalidHandle;
- }
- thread.SetPriority(priority);
- return Result.Success;
- }
- [Svc(0xe)]
- public Result GetThreadCoreMask(out int preferredCore, out ulong affinityMask, int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread != null)
- {
- preferredCore = thread.PreferredCore;
- affinityMask = thread.AffinityMask;
- return Result.Success;
- }
- else
- {
- preferredCore = 0;
- affinityMask = 0;
- return KernelResult.InvalidHandle;
- }
- }
- [Svc(0xf)]
- public Result SetThreadCoreMask(int handle, int preferredCore, ulong affinityMask)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (preferredCore == -2)
- {
- preferredCore = currentProcess.DefaultCpuCore;
- affinityMask = 1UL << preferredCore;
- }
- else
- {
- if ((currentProcess.Capabilities.AllowedCpuCoresMask | affinityMask) !=
- currentProcess.Capabilities.AllowedCpuCoresMask)
- {
- return KernelResult.InvalidCpuCore;
- }
- if (affinityMask == 0)
- {
- return KernelResult.InvalidCombination;
- }
- if ((uint)preferredCore > 3)
- {
- if ((preferredCore | 2) != -1)
- {
- return KernelResult.InvalidCpuCore;
- }
- }
- else if ((affinityMask & (1UL << preferredCore)) == 0)
- {
- return KernelResult.InvalidCombination;
- }
- }
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread == null)
- {
- return KernelResult.InvalidHandle;
- }
- return thread.SetCoreAndAffinityMask(preferredCore, affinityMask);
- }
- [Svc(0x10)]
- public int GetCurrentProcessorNumber()
- {
- return KernelStatic.GetCurrentThread().CurrentCore;
- }
- [Svc(0x25)]
- public Result GetThreadId(out ulong threadUid, int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread != null)
- {
- threadUid = thread.ThreadUid;
- return Result.Success;
- }
- else
- {
- threadUid = 0;
- return KernelResult.InvalidHandle;
- }
- }
- [Svc(0x32)]
- public Result SetThreadActivity(int handle, bool pause)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetObject<KThread>(handle);
- if (thread == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (thread.Owner != process)
- {
- return KernelResult.InvalidHandle;
- }
- if (thread == KernelStatic.GetCurrentThread())
- {
- return KernelResult.InvalidThread;
- }
- return thread.SetActivity(pause);
- }
- [Svc(0x33)]
- public Result GetThreadContext3([PointerSized] ulong address, int handle)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- KThread currentThread = KernelStatic.GetCurrentThread();
- KThread thread = currentProcess.HandleTable.GetObject<KThread>(handle);
- if (thread == null)
- {
- return KernelResult.InvalidHandle;
- }
- if (thread.Owner != currentProcess)
- {
- return KernelResult.InvalidHandle;
- }
- if (currentThread == thread)
- {
- return KernelResult.InvalidThread;
- }
- Result result = thread.GetThreadContext3(out ThreadContext context);
- if (result == Result.Success)
- {
- return KernelTransfer.KernelToUser(address, context)
- ? Result.Success
- : KernelResult.InvalidMemState;
- }
- return result;
- }
- // Thread synchronization
- [Svc(0x18)]
- public Result WaitSynchronization(out int handleIndex, [PointerSized] ulong handlesPtr, int handlesCount, long timeout)
- {
- handleIndex = 0;
- if ((uint)handlesCount > KThread.MaxWaitSyncObjects)
- {
- return KernelResult.MaximumExceeded;
- }
- KThread currentThread = KernelStatic.GetCurrentThread();
- if (handlesCount != 0)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (currentProcess.MemoryManager.AddrSpaceStart > handlesPtr)
- {
- return KernelResult.UserCopyFailed;
- }
- long handlesSize = handlesCount * 4;
- if (handlesPtr + (ulong)handlesSize <= handlesPtr)
- {
- return KernelResult.UserCopyFailed;
- }
- if (handlesPtr + (ulong)handlesSize - 1 > currentProcess.MemoryManager.AddrSpaceEnd - 1)
- {
- return KernelResult.UserCopyFailed;
- }
- Span<int> handles = new Span<int>(currentThread.WaitSyncHandles).Slice(0, handlesCount);
- if (!KernelTransfer.UserToKernelArray(handlesPtr, handles))
- {
- return KernelResult.UserCopyFailed;
- }
- return WaitSynchronization(out handleIndex, handles, timeout);
- }
- return WaitSynchronization(out handleIndex, ReadOnlySpan<int>.Empty, timeout);
- }
- public Result WaitSynchronization(out int handleIndex, ReadOnlySpan<int> handles, long timeout)
- {
- handleIndex = 0;
- if ((uint)handles.Length > KThread.MaxWaitSyncObjects)
- {
- return KernelResult.MaximumExceeded;
- }
- KThread currentThread = KernelStatic.GetCurrentThread();
- var syncObjs = new Span<KSynchronizationObject>(currentThread.WaitSyncObjects).Slice(0, handles.Length);
- if (handles.Length != 0)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- int processedHandles = 0;
- for (; processedHandles < handles.Length; processedHandles++)
- {
- KSynchronizationObject syncObj = currentProcess.HandleTable.GetObject<KSynchronizationObject>(handles[processedHandles]);
- if (syncObj == null)
- {
- break;
- }
- syncObjs[processedHandles] = syncObj;
- syncObj.IncrementReferenceCount();
- }
- if (processedHandles != handles.Length)
- {
- // One or more handles are invalid.
- for (int index = 0; index < processedHandles; index++)
- {
- currentThread.WaitSyncObjects[index].DecrementReferenceCount();
- }
- return KernelResult.InvalidHandle;
- }
- }
- if (timeout > 0)
- {
- timeout += KTimeManager.DefaultTimeIncrementNanoseconds;
- }
- Result result = _context.Synchronization.WaitFor(syncObjs, timeout, out handleIndex);
- if (result == KernelResult.PortRemoteClosed)
- {
- result = Result.Success;
- }
- for (int index = 0; index < handles.Length; index++)
- {
- currentThread.WaitSyncObjects[index].DecrementReferenceCount();
- }
- return result;
- }
- [Svc(0x19)]
- public Result CancelSynchronization(int handle)
- {
- KProcess process = KernelStatic.GetCurrentProcess();
- KThread thread = process.HandleTable.GetKThread(handle);
- if (thread == null)
- {
- return KernelResult.InvalidHandle;
- }
- thread.CancelSynchronization();
- return Result.Success;
- }
- [Svc(0x1a)]
- public Result ArbitrateLock(int ownerHandle, [PointerSized] ulong mutexAddress, int requesterHandle)
- {
- if (IsPointingInsideKernel(mutexAddress))
- {
- return KernelResult.InvalidMemState;
- }
- if (IsAddressNotWordAligned(mutexAddress))
- {
- return KernelResult.InvalidAddress;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- return currentProcess.AddressArbiter.ArbitrateLock(ownerHandle, mutexAddress, requesterHandle);
- }
- [Svc(0x1b)]
- public Result ArbitrateUnlock([PointerSized] ulong mutexAddress)
- {
- if (IsPointingInsideKernel(mutexAddress))
- {
- return KernelResult.InvalidMemState;
- }
- if (IsAddressNotWordAligned(mutexAddress))
- {
- return KernelResult.InvalidAddress;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- return currentProcess.AddressArbiter.ArbitrateUnlock(mutexAddress);
- }
- [Svc(0x1c)]
- public Result WaitProcessWideKeyAtomic(
- [PointerSized] ulong mutexAddress,
- [PointerSized] ulong condVarAddress,
- int handle,
- long timeout)
- {
- if (IsPointingInsideKernel(mutexAddress))
- {
- return KernelResult.InvalidMemState;
- }
- if (IsAddressNotWordAligned(mutexAddress))
- {
- return KernelResult.InvalidAddress;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (timeout > 0)
- {
- timeout += KTimeManager.DefaultTimeIncrementNanoseconds;
- }
- return currentProcess.AddressArbiter.WaitProcessWideKeyAtomic(
- mutexAddress,
- condVarAddress,
- handle,
- timeout);
- }
- [Svc(0x1d)]
- public Result SignalProcessWideKey([PointerSized] ulong address, int count)
- {
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- currentProcess.AddressArbiter.SignalProcessWideKey(address, count);
- return Result.Success;
- }
- [Svc(0x34)]
- public Result WaitForAddress([PointerSized] ulong address, ArbitrationType type, int value, long timeout)
- {
- if (IsPointingInsideKernel(address))
- {
- return KernelResult.InvalidMemState;
- }
- if (IsAddressNotWordAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- if (timeout > 0)
- {
- timeout += KTimeManager.DefaultTimeIncrementNanoseconds;
- }
- return type switch
- {
- ArbitrationType.WaitIfLessThan
- => currentProcess.AddressArbiter.WaitForAddressIfLessThan(address, value, false, timeout),
- ArbitrationType.DecrementAndWaitIfLessThan
- => currentProcess.AddressArbiter.WaitForAddressIfLessThan(address, value, true, timeout),
- ArbitrationType.WaitIfEqual
- => currentProcess.AddressArbiter.WaitForAddressIfEqual(address, value, timeout),
- _ => KernelResult.InvalidEnumValue,
- };
- }
- [Svc(0x35)]
- public Result SignalToAddress([PointerSized] ulong address, SignalType type, int value, int count)
- {
- if (IsPointingInsideKernel(address))
- {
- return KernelResult.InvalidMemState;
- }
- if (IsAddressNotWordAligned(address))
- {
- return KernelResult.InvalidAddress;
- }
- KProcess currentProcess = KernelStatic.GetCurrentProcess();
- return type switch
- {
- SignalType.Signal
- => currentProcess.AddressArbiter.Signal(address, count),
- SignalType.SignalAndIncrementIfEqual
- => currentProcess.AddressArbiter.SignalAndIncrementIfEqual(address, value, count),
- SignalType.SignalAndModifyIfEqual
- => currentProcess.AddressArbiter.SignalAndModifyIfEqual(address, value, count),
- _ => KernelResult.InvalidEnumValue
- };
- }
- [Svc(0x36)]
- public Result SynchronizePreemptionState()
- {
- KernelStatic.GetCurrentThread().SynchronizePreemptionState();
- return Result.Success;
- }
- private static bool IsPointingInsideKernel(ulong address)
- {
- return (address + 0x1000000000) < 0xffffff000;
- }
- private static bool IsAddressNotWordAligned(ulong address)
- {
- return (address & 3) != 0;
- }
- }
- }
|