2023-03-31 21:16:46 +02:00
using LibHac.Account ;
using LibHac.Common ;
using LibHac.Fs ;
using LibHac.Fs.Shim ;
using LibHac.FsSystem ;
2021-08-12 23:56:24 +02:00
using LibHac.Loader ;
using LibHac.Ncm ;
2023-03-31 21:16:46 +02:00
using LibHac.Ns ;
using LibHac.Tools.Fs ;
using LibHac.Tools.FsSystem ;
using LibHac.Tools.FsSystem.NcaUtils ;
2018-11-28 23:18:09 +01:00
using Ryujinx.Common ;
using Ryujinx.Common.Logging ;
2023-03-31 21:16:46 +02:00
using Ryujinx.HLE.HOS ;
2020-05-04 05:41:29 +02:00
using Ryujinx.HLE.HOS.Kernel ;
2018-12-18 06:33:36 +01:00
using Ryujinx.HLE.HOS.Kernel.Common ;
using Ryujinx.HLE.HOS.Kernel.Memory ;
using Ryujinx.HLE.HOS.Kernel.Process ;
2018-11-28 23:18:09 +01:00
using Ryujinx.HLE.Loaders.Executables ;
2023-03-31 21:16:46 +02:00
using Ryujinx.HLE.Loaders.Processes.Extensions ;
2023-01-04 23:15:45 +01:00
using Ryujinx.Horizon.Common ;
2021-03-27 15:12:05 +01:00
using System ;
using System.Linq ;
2021-08-12 23:56:24 +02:00
using System.Runtime.InteropServices ;
2023-03-31 21:16:46 +02:00
using ApplicationId = LibHac . Ncm . ApplicationId ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
namespace Ryujinx.HLE.Loaders.Processes
2018-11-28 23:18:09 +01:00
{
2023-03-31 21:16:46 +02:00
static class ProcessLoaderHelper
2021-08-12 23:56:24 +02:00
{
2023-03-31 21:16:46 +02:00
public static LibHac . Result RegisterProgramMapInfo ( Switch device , PartitionFileSystem partitionFileSystem )
2021-08-12 23:56:24 +02:00
{
2023-03-31 21:16:46 +02:00
ulong applicationId = 0 ;
int programCount = 0 ;
2021-08-12 23:56:24 +02:00
2023-03-31 21:16:46 +02:00
Span < bool > hasIndex = stackalloc bool [ 0x10 ] ;
2023-01-05 00:01:44 +01:00
2023-03-31 21:16:46 +02:00
foreach ( DirectoryEntryEx fileEntry in partitionFileSystem . EnumerateEntries ( "/" , "*.nca" ) )
{
Nca nca = partitionFileSystem . GetNca ( device , fileEntry . FullPath ) ;
2023-01-05 00:01:44 +01:00
2023-03-31 21:16:46 +02:00
if ( ! nca . IsProgram ( ) & & nca . IsPatch ( ) )
{
continue ;
}
ulong currentProgramId = nca . Header . TitleId ;
ulong currentMainProgramId = currentProgramId & ~ 0xFFF ul ;
if ( applicationId = = 0 & & currentMainProgramId ! = 0 )
{
applicationId = currentMainProgramId ;
}
if ( applicationId ! = currentMainProgramId )
{
// Currently there aren't any known multi-application game cards containing multi-program applications,
// so because multi-application game cards are the only way we could run into multiple applications
// we'll just return that there's a single program.
programCount = 1 ;
break ;
}
hasIndex [ ( int ) ( currentProgramId & 0xF ) ] = true ;
}
if ( programCount = = 0 )
{
for ( int i = 0 ; i < hasIndex . Length & & hasIndex [ i ] ; i + + )
{
programCount + + ;
}
}
if ( programCount < = 0 )
{
return LibHac . Result . Success ;
}
Span < ProgramIndexMapInfo > mapInfo = stackalloc ProgramIndexMapInfo [ 0x10 ] ;
for ( int i = 0 ; i < programCount ; i + + )
{
mapInfo [ i ] . ProgramId = new ProgramId ( applicationId + ( uint ) i ) ;
mapInfo [ i ] . MainProgramId = new ApplicationId ( applicationId ) ;
mapInfo [ i ] . ProgramIndex = ( byte ) i ;
}
return device . System . LibHacHorizonManager . NsClient . Fs . RegisterProgramIndexMapInfo ( mapInfo [ . . programCount ] ) ;
2023-01-05 00:01:44 +01:00
}
2023-03-31 21:16:46 +02:00
public static LibHac . Result EnsureSaveData ( Switch device , ApplicationId applicationId , BlitStruct < ApplicationControlProperty > applicationControlProperty )
{
Logger . Info ? . Print ( LogClass . Application , "Ensuring required savedata exists." ) ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
ref ApplicationControlProperty control = ref applicationControlProperty . Value ;
if ( LibHac . Common . Utilities . IsZeros ( applicationControlProperty . ByteSpan ) )
{
// If the current application doesn't have a loaded control property, create a dummy one and set the savedata sizes so a user savedata will be created.
control = ref new BlitStruct < ApplicationControlProperty > ( 1 ) . Value ;
// The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
control . UserAccountSaveDataSize = 0x4000 ;
control . UserAccountSaveDataJournalSize = 0x4000 ;
control . SaveDataOwnerId = applicationId . Value ;
Logger . Warning ? . Print ( LogClass . Application , "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games." ) ;
}
LibHac . Result resultCode = device . System . LibHacHorizonManager . RyujinxClient . Fs . EnsureApplicationCacheStorage ( out _ , out _ , applicationId , in control ) ;
if ( resultCode . IsFailure ( ) )
{
Logger . Error ? . Print ( LogClass . Application , $"Error calling EnsureApplicationCacheStorage. Result code {resultCode.ToStringWithName()}" ) ;
return resultCode ;
}
Uid userId = device . System . AccountManager . LastOpenedUser . UserId . ToLibHacUid ( ) ;
resultCode = device . System . LibHacHorizonManager . RyujinxClient . Fs . EnsureApplicationSaveData ( out _ , applicationId , in control , in userId ) ;
if ( resultCode . IsFailure ( ) )
{
Logger . Error ? . Print ( LogClass . Application , $"Error calling EnsureApplicationSaveData. Result code {resultCode.ToStringWithName()}" ) ;
}
return resultCode ;
}
2018-11-28 23:18:09 +01:00
2020-05-04 05:41:29 +02:00
public static bool LoadKip ( KernelContext context , KipExecutable kip )
2018-11-28 23:18:09 +01:00
{
2020-12-13 08:30:27 +01:00
uint endOffset = kip . DataOffset + ( uint ) kip . Data . Length ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
if ( kip . BssSize ! = 0 )
2018-11-28 23:18:09 +01:00
{
2018-12-06 12:16:24 +01:00
endOffset = kip . BssOffset + kip . BssSize ;
2018-11-28 23:18:09 +01:00
}
2023-03-31 21:16:46 +02:00
uint codeSize = BitUtils . AlignUp < uint > ( kip . TextOffset + endOffset , KPageTableBase . PageSize ) ;
int codePagesCount = ( int ) ( codeSize / KPageTableBase . PageSize ) ;
2020-07-04 01:58:01 +02:00
ulong codeBaseAddress = kip . Is64BitAddressSpace ? 0x8000000 UL : 0x200000 UL ;
2023-03-31 21:16:46 +02:00
ulong codeAddress = codeBaseAddress + kip . TextOffset ;
2018-11-28 23:18:09 +01:00
2020-12-02 00:23:43 +01:00
ProcessCreationFlags flags = 0 ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
if ( ProcessConst . AslrEnabled )
2018-11-28 23:18:09 +01:00
{
2019-07-02 04:39:22 +02:00
// TODO: Randomization.
2018-11-28 23:18:09 +01:00
2020-12-02 00:23:43 +01:00
flags | = ProcessCreationFlags . EnableAslr ;
2018-11-28 23:18:09 +01:00
}
2020-07-04 01:58:01 +02:00
if ( kip . Is64BitAddressSpace )
2018-11-28 23:18:09 +01:00
{
2020-12-02 00:23:43 +01:00
flags | = ProcessCreationFlags . AddressSpace64Bit ;
2018-11-28 23:18:09 +01:00
}
2020-07-04 01:58:01 +02:00
if ( kip . Is64Bit )
2018-11-28 23:18:09 +01:00
{
2020-12-02 00:23:43 +01:00
flags | = ProcessCreationFlags . Is64Bit ;
2018-11-28 23:18:09 +01:00
}
2023-03-31 21:16:46 +02:00
ProcessCreationInfo creationInfo = new ( kip . Name , kip . Version , kip . ProgramId , codeAddress , codePagesCount , flags , 0 , 0 ) ;
MemoryRegion memoryRegion = kip . UsesSecureMemory ? MemoryRegion . Service : MemoryRegion . Application ;
KMemoryRegionManager region = context . MemoryManager . MemoryRegions [ ( int ) memoryRegion ] ;
2018-11-28 23:18:09 +01:00
2023-01-04 23:15:45 +01:00
Result result = region . AllocatePages ( out KPageList pageList , ( ulong ) codePagesCount ) ;
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization returned error \" { result } \ "." ) ;
2018-11-28 23:18:09 +01:00
return false ;
}
2023-03-31 21:16:46 +02:00
KProcess process = new ( context ) ;
2018-11-28 23:18:09 +01:00
2023-01-05 00:01:44 +01:00
var processContextFactory = new ArmProcessContextFactory (
2023-01-29 12:37:52 +01:00
context . Device . System . TickSource ,
2023-01-05 00:01:44 +01:00
context . Device . Gpu ,
string . Empty ,
string . Empty ,
false ,
codeAddress ,
codeSize ) ;
2020-12-02 00:23:43 +01:00
2023-03-31 21:16:46 +02:00
result = process . InitializeKip ( creationInfo , kip . Capabilities , pageList , context . ResourceLimit , memoryRegion , processContextFactory ) ;
2023-01-04 23:15:45 +01:00
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization returned error \" { result } \ "." ) ;
2018-11-28 23:18:09 +01:00
return false ;
}
2018-12-06 12:16:24 +01:00
result = LoadIntoMemory ( process , kip , codeBaseAddress ) ;
2023-01-04 23:15:45 +01:00
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization returned error \" { result } \ "." ) ;
2018-11-28 23:18:09 +01:00
return false ;
}
2020-07-04 01:58:01 +02:00
process . DefaultCpuCore = kip . IdealCoreId ;
2019-01-18 23:26:39 +01:00
2020-07-04 01:58:01 +02:00
result = process . Start ( kip . Priority , ( ulong ) kip . StackSize ) ;
2023-01-04 23:15:45 +01:00
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process start returned error \" { result } \ "." ) ;
2018-11-28 23:18:09 +01:00
return false ;
}
2020-05-04 05:41:29 +02:00
context . Processes . TryAdd ( process . Pid , process ) ;
2018-11-28 23:18:09 +01:00
return true ;
}
2023-03-31 21:16:46 +02:00
public static ProcessResult LoadNsos (
Switch device ,
2022-05-03 23:28:32 +02:00
KernelContext context ,
2023-03-31 21:16:46 +02:00
MetaLoader metaLoader ,
ApplicationControlProperty applicationControlProperties ,
bool diskCacheEnabled ,
bool allowCodeMemoryForJit ,
string name ,
ulong programId ,
2022-05-03 23:28:32 +02:00
byte [ ] arguments = null ,
params IExecutable [ ] executables )
2018-11-28 23:18:09 +01:00
{
2023-01-08 13:13:39 +01:00
context . Device . System . ServiceTable . WaitServicesReady ( ) ;
2023-03-31 21:16:46 +02:00
LibHac . Result resultCode = metaLoader . GetNpdm ( out var npdm ) ;
2021-08-12 23:56:24 +02:00
2023-03-31 21:16:46 +02:00
if ( resultCode . IsFailure ( ) )
2021-08-12 23:56:24 +02:00
{
2023-03-31 21:16:46 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization failed getting npdm. Result Code {resultCode.ToStringWithName()}" ) ;
return ProcessResult . Failed ;
2021-08-12 23:56:24 +02:00
}
2023-03-02 03:42:27 +01:00
ref readonly var meta = ref npdm . Meta ;
2021-08-12 23:56:24 +02:00
2018-12-06 12:16:24 +01:00
ulong argsStart = 0 ;
2020-12-13 08:30:27 +01:00
uint argsSize = 0 ;
2021-08-12 23:56:24 +02:00
ulong codeStart = ( meta . Flags & 1 ) ! = 0 ? 0x8000000 UL : 0x200000 UL ;
2020-12-13 08:30:27 +01:00
uint codeSize = 0 ;
2018-11-28 23:18:09 +01:00
2021-03-27 15:12:05 +01:00
var buildIds = executables . Select ( e = > ( e switch
{
2023-03-31 21:16:46 +02:00
NsoExecutable nso = > Convert . ToHexString ( nso . BuildId . ItemsRo . ToArray ( ) ) ,
NroExecutable nro = > Convert . ToHexString ( nro . Header . BuildId ) ,
2021-03-27 15:12:05 +01:00
_ = > ""
2023-03-31 21:16:46 +02:00
} ) . ToUpper ( ) ) ;
2021-03-27 15:12:05 +01:00
2020-05-15 08:16:46 +02:00
ulong [ ] nsoBase = new ulong [ executables . Length ] ;
2018-11-28 23:18:09 +01:00
2020-05-15 08:16:46 +02:00
for ( int index = 0 ; index < executables . Length ; index + + )
2018-11-28 23:18:09 +01:00
{
2020-12-13 08:30:27 +01:00
IExecutable nso = executables [ index ] ;
2018-11-28 23:18:09 +01:00
2020-12-13 08:30:27 +01:00
uint textEnd = nso . TextOffset + ( uint ) nso . Text . Length ;
2023-03-31 21:16:46 +02:00
uint roEnd = nso . RoOffset + ( uint ) nso . Ro . Length ;
2020-12-13 08:30:27 +01:00
uint dataEnd = nso . DataOffset + ( uint ) nso . Data . Length + nso . BssSize ;
2018-11-28 23:18:09 +01:00
2020-12-13 08:30:27 +01:00
uint nsoSize = textEnd ;
2018-11-28 23:18:09 +01:00
2020-12-13 08:30:27 +01:00
if ( nsoSize < roEnd )
2018-11-28 23:18:09 +01:00
{
2018-12-06 12:16:24 +01:00
nsoSize = roEnd ;
2018-11-28 23:18:09 +01:00
}
2020-12-13 08:30:27 +01:00
if ( nsoSize < dataEnd )
2018-11-28 23:18:09 +01:00
{
2018-12-06 12:16:24 +01:00
nsoSize = dataEnd ;
2018-11-28 23:18:09 +01:00
}
2022-12-26 15:11:05 +01:00
nsoSize = BitUtils . AlignUp < uint > ( nsoSize , KPageTableBase . PageSize ) ;
2018-11-28 23:18:09 +01:00
2023-03-17 12:55:19 +01:00
nsoBase [ index ] = codeStart + codeSize ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
codeSize + = nsoSize ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
if ( arguments ! = null & & argsSize = = 0 )
2018-11-28 23:18:09 +01:00
{
2023-03-17 12:55:19 +01:00
argsStart = codeSize ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
argsSize = ( uint ) BitUtils . AlignDown ( arguments . Length * 2 + ProcessConst . NsoArgsTotalSize - 1 , KPageTableBase . PageSize ) ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
codeSize + = argsSize ;
2018-11-28 23:18:09 +01:00
}
}
2023-03-31 21:16:46 +02:00
int codePagesCount = ( int ) ( codeSize / KPageTableBase . PageSize ) ;
2021-08-12 23:56:24 +02:00
int personalMmHeapPagesCount = ( int ) ( meta . SystemResourceSize / KPageTableBase . PageSize ) ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
ProcessCreationInfo creationInfo = new (
name ,
2021-08-12 23:56:24 +02:00
( int ) meta . Version ,
2023-03-31 21:16:46 +02:00
programId ,
2018-12-06 12:16:24 +01:00
codeStart ,
codePagesCount ,
2021-08-12 23:56:24 +02:00
( ProcessCreationFlags ) meta . Flags | ProcessCreationFlags . IsApplication ,
2018-11-28 23:18:09 +01:00
0 ,
2018-12-06 12:16:24 +01:00
personalMmHeapPagesCount ) ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
context . Device . System . LibHacHorizonManager . InitializeApplicationClient ( new ProgramId ( programId ) , in npdm ) ;
2021-08-12 23:56:24 +02:00
2023-01-04 23:15:45 +01:00
Result result ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
KResourceLimit resourceLimit = new ( context ) ;
2018-11-28 23:18:09 +01:00
POWER - Performance Optimizations With Extensive Ramifications (#2286)
* Refactoring of KMemoryManager class
* Replace some trivial uses of DRAM address with VA
* Get rid of GetDramAddressFromVa
* Abstracting more operations on derived page table class
* Run auto-format on KPageTableBase
* Managed to make TryConvertVaToPa private, few uses remains now
* Implement guest physical pages ref counting, remove manual freeing
* Make DoMmuOperation private and call new abstract methods only from the base class
* Pass pages count rather than size on Map/UnmapMemory
* Change memory managers to take host pointers
* Fix a guest memory leak and simplify KPageTable
* Expose new methods for host range query and mapping
* Some refactoring of MapPagesFromClientProcess to allow proper page ref counting and mapping without KPageLists
* Remove more uses of AddVaRangeToPageList, now only one remains (shared memory page checking)
* Add a SharedMemoryStorage class, will be useful for host mapping
* Sayonara AddVaRangeToPageList, you served us well
* Start to implement host memory mapping (WIP)
* Support memory tracking through host exception handling
* Fix some access violations from HLE service guest memory access and CPU
* Fix memory tracking
* Fix mapping list bugs, including a race and a error adding mapping ranges
* Simple page table for memory tracking
* Simple "volatile" region handle mode
* Update UBOs directly (experimental, rough)
* Fix the overlap check
* Only set non-modified buffers as volatile
* Fix some memory tracking issues
* Fix possible race in MapBufferFromClientProcess (block list updates were not locked)
* Write uniform update to memory immediately, only defer the buffer set.
* Fix some memory tracking issues
* Pass correct pages count on shared memory unmap
* Armeilleure Signal Handler v1 + Unix changes
Unix currently behaves like windows, rather than remapping physical
* Actually check if the host platform is unix
* Fix decommit on linux.
* Implement windows 10 placeholder shared memory, fix a buffer issue.
* Make PTC version something that will never match with master
* Remove testing variable for block count
* Add reference count for memory manager, fix dispose
Can still deadlock with OpenAL
* Add address validation, use page table for mapped check, add docs
Might clean up the page table traversing routines.
* Implement batched mapping/tracking.
* Move documentation, fix tests.
* Cleanup uniform buffer update stuff.
* Remove unnecessary assignment.
* Add unsafe host mapped memory switch
On by default. Would be good to turn this off for untrusted code (homebrew, exefs mods) and give the user the option to turn it on manually, though that requires some UI work.
* Remove C# exception handlers
They have issues due to current .NET limitations, so the meilleure one fully replaces them for now.
* Fix MapPhysicalMemory on the software MemoryManager.
* Null check for GetHostAddress, docs
* Add configuration for setting memory manager mode (not in UI yet)
* Add config to UI
* Fix type mismatch on Unix signal handler code emit
* Fix 6GB DRAM mode.
The size can be greater than `uint.MaxValue` when the DRAM is >4GB.
* Address some feedback.
* More detailed error if backing memory cannot be mapped.
* SetLastError on all OS functions for consistency
* Force pages dirty with UBO update instead of setting them directly.
Seems to be much faster across a few games. Need retesting.
* Rebase, configuration rework, fix mem tracking regression
* Fix race in FreePages
* Set memory managers null after decrementing ref count
* Remove readonly keyword, as this is now modified.
* Use a local variable for the signal handler rather than a register.
* Fix bug with buffer resize, and index/uniform buffer binding.
Should fix flickering in games.
* Add InvalidAccessHandler to MemoryTracking
Doesn't do anything yet
* Call invalid access handler on unmapped read/write.
Same rules as the regular memory manager.
* Make unsafe mapped memory its own MemoryManagerType
* Move FlushUboDirty into UpdateState.
* Buffer dirty cache, rather than ubo cache
Much cleaner, may be reusable for Inline2Memory updates.
* This doesn't return anything anymore.
* Add sigaction remove methods, correct a few function signatures.
* Return empty list of physical regions for size 0.
* Also on AddressSpaceManager
Co-authored-by: gdkchan <gab.dark.100@gmail.com>
2021-05-24 22:52:44 +02:00
long applicationRgSize = ( long ) context . MemoryManager . MemoryRegions [ ( int ) MemoryRegion . Application ] . Size ;
2018-11-28 23:18:09 +01:00
2023-01-04 23:15:45 +01:00
result = resourceLimit . SetLimitValue ( LimitableResource . Memory , applicationRgSize ) ;
2018-11-28 23:18:09 +01:00
2023-01-04 23:15:45 +01:00
if ( result . IsSuccess )
{
result = resourceLimit . SetLimitValue ( LimitableResource . Thread , 608 ) ;
}
if ( result . IsSuccess )
{
result = resourceLimit . SetLimitValue ( LimitableResource . Event , 700 ) ;
}
if ( result . IsSuccess )
{
result = resourceLimit . SetLimitValue ( LimitableResource . TransferMemory , 128 ) ;
}
if ( result . IsSuccess )
{
result = resourceLimit . SetLimitValue ( LimitableResource . Session , 894 ) ;
}
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization failed setting resource limit values." ) ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
return ProcessResult . Failed ;
2018-11-28 23:18:09 +01:00
}
2023-03-31 21:16:46 +02:00
KProcess process = new ( context , allowCodeMemoryForJit ) ;
2019-01-18 23:26:39 +01:00
2023-03-31 21:16:46 +02:00
// NOTE: This field doesn't exists one firmware pre-5.0.0, a workaround have to be found.
MemoryRegion memoryRegion = ( MemoryRegion ) ( npdm . Acid . Flags > > 2 & 0xf ) ;
2019-01-18 23:26:39 +01:00
if ( memoryRegion > MemoryRegion . NvServices )
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization failed due to invalid ACID flags." ) ;
2019-01-18 23:26:39 +01:00
2023-03-31 21:16:46 +02:00
return ProcessResult . Failed ;
2019-01-18 23:26:39 +01:00
}
2023-01-05 00:01:44 +01:00
var processContextFactory = new ArmProcessContextFactory (
2023-01-29 12:37:52 +01:00
context . Device . System . TickSource ,
2023-01-05 00:01:44 +01:00
context . Device . Gpu ,
2023-03-31 21:16:46 +02:00
$"{programId:x16}" ,
applicationControlProperties . DisplayVersionString . ToString ( ) ,
diskCacheEnabled ,
2023-01-05 00:01:44 +01:00
codeStart ,
codeSize ) ;
2020-12-02 00:23:43 +01:00
2018-12-06 12:16:24 +01:00
result = process . Initialize (
creationInfo ,
2023-03-17 12:55:19 +01:00
MemoryMarshal . Cast < byte , uint > ( npdm . KernelCapabilityData ) ,
2018-12-06 12:16:24 +01:00
resourceLimit ,
2020-12-02 00:23:43 +01:00
memoryRegion ,
processContextFactory ) ;
2018-11-28 23:18:09 +01:00
2023-01-04 23:15:45 +01:00
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization returned error \" { result } \ "." ) ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
return ProcessResult . Failed ;
2018-11-28 23:18:09 +01:00
}
2020-05-15 08:16:46 +02:00
for ( int index = 0 ; index < executables . Length ; index + + )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Info ? . Print ( LogClass . Loader , $"Loading image {index} at 0x{nsoBase[index]:x16}..." ) ;
2018-11-28 23:18:09 +01:00
2020-05-15 08:16:46 +02:00
result = LoadIntoMemory ( process , executables [ index ] , nsoBase [ index ] ) ;
2023-01-04 23:15:45 +01:00
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2020-08-04 01:32:53 +02:00
Logger . Error ? . Print ( LogClass . Loader , $"Process initialization returned error \" { result } \ "." ) ;
2018-11-28 23:18:09 +01:00
2023-03-31 21:16:46 +02:00
return ProcessResult . Failed ;
2018-11-28 23:18:09 +01:00
}
}
2021-08-12 23:56:24 +02:00
process . DefaultCpuCore = meta . DefaultCpuId ;
2019-01-18 23:26:39 +01:00
2020-05-04 05:41:29 +02:00
context . Processes . TryAdd ( process . Pid , process ) ;
2018-11-28 23:18:09 +01:00
2021-03-27 15:12:05 +01:00
// Keep the build ids because the tamper machine uses them to know which process to associate a
// tamper to and also keep the starting address of each executable inside a process because some
// memory modifications are relative to this address.
2023-03-31 21:16:46 +02:00
ProcessTamperInfo tamperInfo = new (
2023-01-05 00:01:44 +01:00
process ,
buildIds ,
nsoBase ,
process . MemoryManager . HeapRegionStart ,
process . MemoryManager . AliasRegionStart ,
process . MemoryManager . CodeRegionStart ) ;
2023-03-31 21:16:46 +02:00
// Once everything is loaded, we can load cheats.
device . Configuration . VirtualFileSystem . ModLoader . LoadCheats ( programId , tamperInfo , device . TamperMachine ) ;
return new ProcessResult ( metaLoader , applicationControlProperties , diskCacheEnabled , allowCodeMemoryForJit , processContextFactory . DiskCacheLoadState , process . Pid , meta . MainThreadPriority , meta . MainThreadStackSize ) ;
2018-11-28 23:18:09 +01:00
}
2023-03-31 21:16:46 +02:00
public static Result LoadIntoMemory ( KProcess process , IExecutable image , ulong baseAddress )
2018-11-28 23:18:09 +01:00
{
2023-01-04 23:15:45 +01:00
ulong textStart = baseAddress + image . TextOffset ;
ulong roStart = baseAddress + image . RoOffset ;
ulong dataStart = baseAddress + image . DataOffset ;
ulong bssStart = baseAddress + image . BssOffset ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
ulong end = dataStart + ( ulong ) image . Data . Length ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
if ( image . BssSize ! = 0 )
2018-11-28 23:18:09 +01:00
{
2023-01-04 23:15:45 +01:00
end = bssStart + image . BssSize ;
2018-11-28 23:18:09 +01:00
}
2020-05-04 00:54:50 +02:00
process . CpuMemory . Write ( textStart , image . Text ) ;
process . CpuMemory . Write ( roStart , image . Ro ) ;
process . CpuMemory . Write ( dataStart , image . Data ) ;
2018-11-28 23:18:09 +01:00
2020-12-13 08:30:27 +01:00
process . CpuMemory . Fill ( bssStart , image . BssSize , 0 ) ;
2018-11-28 23:18:09 +01:00
2023-01-04 23:15:45 +01:00
Result SetProcessMemoryPermission ( ulong address , ulong size , KMemoryPermission permission )
2018-11-28 23:18:09 +01:00
{
2018-12-06 12:16:24 +01:00
if ( size = = 0 )
2018-11-28 23:18:09 +01:00
{
2023-01-04 23:15:45 +01:00
return Result . Success ;
2018-11-28 23:18:09 +01:00
}
2022-12-26 15:11:05 +01:00
size = BitUtils . AlignUp < ulong > ( size , KPageTableBase . PageSize ) ;
2018-11-28 23:18:09 +01:00
2018-12-06 12:16:24 +01:00
return process . MemoryManager . SetProcessMemoryPermission ( address , size , permission ) ;
2018-11-28 23:18:09 +01:00
}
2023-01-04 23:15:45 +01:00
Result result = SetProcessMemoryPermission ( textStart , ( ulong ) image . Text . Length , KMemoryPermission . ReadAndExecute ) ;
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2018-12-06 12:16:24 +01:00
return result ;
2018-11-28 23:18:09 +01:00
}
2020-12-02 00:23:43 +01:00
result = SetProcessMemoryPermission ( roStart , ( ulong ) image . Ro . Length , KMemoryPermission . Read ) ;
2023-01-04 23:15:45 +01:00
if ( result ! = Result . Success )
2018-11-28 23:18:09 +01:00
{
2018-12-06 12:16:24 +01:00
return result ;
2018-11-28 23:18:09 +01:00
}
2020-12-02 00:23:43 +01:00
return SetProcessMemoryPermission ( dataStart , end - dataStart , KMemoryPermission . ReadAndWrite ) ;
2018-11-28 23:18:09 +01:00
}
}
2020-04-08 00:41:02 +02:00
}