Commit Graph

523 Commits

Author SHA1 Message Date
Fernando Sahmkow d23d504d77 Kernel: Refactor synchronization to better match RE 2020-02-11 18:47:31 -04:00
Fernando Sahmkow c5aefe42aa Kernel: Change WaitObject to Synchronization object. In order to better reflect RE. 2020-02-11 10:46:25 -04:00
bunnei ba53543da6 kernel: transfer_memory: Properly reserve and reset memory region. 2020-02-05 23:06:54 -05:00
Fernando Sahmkow e4a1ead897 Core: Refactor CpuCoreManager to CpuManager and Cpu to Core Manager.
This commit instends on better naming the new purpose of this classes.
2020-01-26 14:07:22 -04:00
Lioncash 30e365e4fc kernel/svc: Correct function signature of SignalProcessWideKey
This function doesn't actually return a result code, so we can amend the
signature of it to match.
2019-12-11 07:13:27 -05:00
Lioncash 67b8265bd6 kernel/svc: Provide implementations for svcDumpInfo/svcDumpInfoNew
These are fairly trivial to implement, we can just do nothing. This also
provides a spot for us to potentially dump out any relevant info in the
future (e.g. for debugging purposes with homebrew, etc).

While we're at it, we can also correct the names of both of these
supervisor calls.
2019-12-07 22:01:17 -05:00
bunnei c3d3b173d3 kernel: Implement a more accurate IPC dispatch. 2019-11-28 12:01:53 -05:00
Lioncash e4c381b885 core/memory: Migrate over Write{8, 16, 32, 64, Block} to the Memory class
The Write functions are used slightly less than the Read functions,
which make these a bit nicer to move over.

The only adjustments we really need to make here are to Dynarmic's
exclusive monitor instance. We need to keep a reference to the currently
active memory instance to perform exclusive read/write operations.
2019-11-26 21:55:39 -05:00
Lioncash b05bfc6036 core/memory: Migrate over Read{8, 16, 32, 64, Block} to the Memory class
With all of the trivial parts of the memory interface moved over, we can
get right into moving over the bits that are used.

Note that this does require the use of GetInstance from the global
system instance to be used within hle_ipc.cpp and the gdbstub. This is
fine for the time being, as they both already rely on the global system
instance in other functions. These will be removed in a change directed
at both of these respectively.

For now, it's sufficient, as it still accomplishes the goal of
de-globalizing the memory code.
2019-11-26 21:55:39 -05:00
Lioncash b2165c6b35 core/memory: Migrate over ReadCString() to the Memory class
This only had one usage spot, so this is fairly straightforward to
convert over.
2019-11-26 21:55:38 -05:00
Lioncash 536fc7f0ea core: Prepare various classes for memory read/write migration
Amends a few interfaces to be able to handle the migration over to the
new Memory class by passing the class by reference as a function
parameter where necessary.

Notably, within the filesystem services, this eliminates two ReadBlock()
calls by using the helper functions of HLERequestContext to do that for
us.
2019-11-26 21:55:37 -05:00
Lioncash e58748fd80 core/memory: Migrate over address checking functions to the new Memory class
A fairly straightforward migration. These member functions can just be
mostly moved verbatim with minor changes. We already have the necessary
plumbing in places that they're used.

IsKernelVirtualAddress() can remain a non-member function, since it
doesn't rely on class state in any form.
2019-11-26 21:53:34 -05:00
bunnei 9046d4a548
kernel: Replace usage of boost::intrusive_ptr with std::shared_ptr for kernel objects. (#3154)
* kernel: Replace usage of boost::intrusive_ptr with std::shared_ptr for kernel objects.

- See https://github.com/citra-emu/citra/pull/4710 for details.
2019-11-24 20:15:51 -05:00
bunnei 63248f4edd
Update svc.cpp 2019-11-23 16:01:06 -05:00
bunnei 6eaf7ab55f svc: GetSystemTick should return cntpct_el0, not core ticks. 2019-11-23 15:29:15 -05:00
bunnei 6a3fc5d2ff
Merge pull request #3114 from FernandoS27/cond-var
Kernel: Correct behavior of Condition Variables to be more similar to real hardware.
2019-11-23 13:24:39 -05:00
Fernando Sahmkow 46bb609981 Kernel: Optimize condition variable threads management. 2019-11-21 11:13:29 -04:00
Fernando Sahmkow 2ab41ceff4 Kernel: Correct SignalProcessWideKey
When the target is 0, all threads must be processed.
2019-11-21 10:46:55 -04:00
Fernando Sahmkow 2d16507f9f Kernel: Correct behavior of Condition Variables to be more similar to real hardware.
This commit ensures cond var threads act exactly as they do in the real
console. The original implementation uses an RBTree and the behavior of
cond var threads is that at the same priority level they act like a
FIFO.
2019-11-21 10:46:55 -04:00
Fernando Sahmkow 7d16b2d2dd Kernel: Correct Cancel Synchronization.
This commit corrects the behavior of cancel synchronization when the
thread is running/ready and ensures the next wait is cancelled as it's
suppose to.
2019-11-16 12:41:51 -04:00
bunnei b0ab803ce8 kernel: events: Remove ResetType::Automatic.
- This does not actually seem to exist in the real kernel - games reset these automatically.

# Conflicts:
#	src/core/hle/service/am/applets/applets.cpp
#	src/core/hle/service/filesystem/fsp_srv.cpp
2019-11-03 04:22:45 -05:00
Fernando Sahmkow 3073615dbc Kernel: Address Feedback. 2019-10-15 11:55:25 -04:00
Fernando Sahmkow 0b72b34d89 KernelSVC: Assert that condition variable address is aligned to 4 bytes. 2019-10-15 11:55:22 -04:00
Fernando Sahmkow 27d571c084 Kernel: Correct redundant yields to only advance time forward. 2019-10-15 11:55:20 -04:00
Fernando Sahmkow 44e09e5f21 Kernel: Correct Results in Condition Variables and Mutexes 2019-10-15 11:55:18 -04:00
Fernando Sahmkow 103f3a2fe5 Scheduler: Add protections for Yield bombing
In case of redundant yields, the scheduler will now idle the core for 
it's timeslice, in order to avoid continuously yielding the same thing 
over and over.
2019-10-15 11:55:13 -04:00
Fernando Sahmkow 82218c925a Kernel: Style and Corrections 2019-10-15 11:55:12 -04:00
Fernando Sahmkow fcc6b34fff Correct PrepareReschedule 2019-10-15 11:55:12 -04:00
Fernando Sahmkow 9031502974 Correct Supervisor Calls to work with the new scheduler, 2019-10-15 11:55:08 -04:00
bunnei 5d369112d9
Merge pull request #2687 from lioncash/tls-process
kernel/process: Allocate the process' TLS region during initialization
2019-07-18 13:53:04 -04:00
Fernando Sahmkow 5e457bf258 Kernel: Downgrade WaitForAddress and SignalToAddress messages to Trace.
This messages were originally set as warnning since few games used these
svcs and it was needed for debugging. This is no longer the case.
2019-07-17 22:05:47 -04:00
Fernando Sahmkow 4882c058fd
Merge pull request #2690 from SciresM/physmem_fixes
Implement MapPhysicalMemory/UnmapPhysicalMemory
2019-07-14 09:16:46 -04:00
Michael Scire 072a9796f5 Restore memory perms on svcUnmapMemory/UnloadNro
Prior to PR, Yuzu did not restore memory to RW-
on unmap of mirrored memory or unloading of NRO.

(In fact, in the NRO case, the memory was unmapped
instead of reprotected to --- on Load, so it was
actually lost entirely...)

This PR addresses that, and restores memory to RW-
as it should.

This fixes a crash in Super Smash Bros when creating
a World of Light save for the first time, and possibly
other games/circumstances.
2019-07-11 01:38:28 -07:00
Michael Scire b901cd584e clang-format fixes 2019-07-07 12:08:29 -07:00
Michael Scire 1689784c19 address review commentary 2019-07-07 11:48:11 -07:00
Michael Scire 13a8fde3ad Implement MapPhysicalMemory/UnmapPhysicalMemory
This implements svcMapPhysicalMemory/svcUnmapPhysicalMemory for Yuzu,
which can be used to map memory at a desired address by games since
3.0.0.

It also properly parses SystemResourceSize from NPDM, and makes
information available via svcGetInfo.

This is needed for games like Super Smash Bros. and Diablo 3 -- this
PR's implementation does not run into the "ASCII reads" issue mentioned
in the comments of #2626, which was caused by the following bugs in
Yuzu's memory management that this PR also addresses:
* Yuzu's memory coalescing does not properly merge blocks. This results
  in a polluted address space/svcQueryMemory results that would be
  impossible to replicate on hardware, which can lead to game code making
  the wrong assumptions about memory layout.
  * This implements better merging for AllocatedMemoryBlocks.
* Yuzu's implementation of svcMirrorMemory unprotected the entire
  virtual memory range containing the range being mirrored. This could
  lead to games attempting to map data at that unprotected
  range/attempting to access that range after yuzu improperly unmapped
  it.
  * This PR fixes it by simply calling ReprotectRange instead of
    Reprotect.
2019-07-07 11:45:53 -07:00
Lioncash 56c7912159 kernel/process: Allocate the process' TLS region during initialization
Prior to execution within a process beginning, the process establishes
its own TLS region for uses (as far as I can tell) related to exception
handling.

Now that TLS creation was decoupled from threads themselves, we can add
this behavior to our Process class. This is also good, as it allows us
to remove a stub within svcGetInfo, namely querying the address of that
region.
2019-07-07 14:08:28 -04:00
Lioncash 2a9e388290 kernel/vm_manager: Rename 'new map' to 'stack'
Provides a more accurate name for the memory region and also
disambiguates between the map and new map regions of memory, making it
easier to understand.
2019-07-06 02:24:30 -04:00
bunnei 96412848a9
Merge pull request #2482 from DarkLordZach/prepo
core: Add detailed local reporting feature for development
2019-06-21 14:05:18 -04:00
Lioncash 3f87664d8f kernel/svc: Implement TotalMemoryUsedWithoutMmHeap/TotalMemoryAvailableWithoutMmHeap
Given we don't currently implement the personal heap yet, the existing
memory querying functions are essentially doing what the memory querying
types introduced in 6.0.0 do.

So, we can build the necessary machinery over the top of those and just
use them as part of info types.
2019-06-09 18:22:30 -04:00
Lioncash c1a8f684df kernel/svc: Amend naming for TotalMemoryUsage in svcGetInfo()
Disambiguates and makes the name a little more consistent with
TotalPhysicalMemoryUsed.
2019-06-09 18:12:05 -04:00
Lioncash 81b1102090 kernel/svc: Remove duplicate enum entry in svcGetInfo() 2019-06-09 18:08:37 -04:00
Zach Hilman 186db894b9 svc: Save report on call to svcBreak 2019-05-25 16:09:20 -04:00
bunnei 13dda1d8ed
Merge pull request #2410 from lioncash/affinity
kernel/svc: Reorganize and fix up the initial handling of svcSetThreadCoreMask()
2019-05-19 13:59:52 -04:00
Sebastian Valle 27033de2e5
Merge pull request #2486 from lioncash/resetname
core/kernel/object: Rename ResetType enum members for clarity
2019-05-19 08:47:59 -05:00
Lioncash d5cce86431 kernel/svc: Mark GetThreadList() and UnmapProcessCodeMemory() as internally linked
These are only used from within this translation unit, so they don't
need to have external linkage. They were intended to be marked with this
anyways to be consistent with the other service functions.
2019-05-18 19:10:34 -04:00
Lioncash a47aaa7f1b core/kernel/object: Rename ResetType enum members
Renames the members to more accurately indicate what they signify.
"OneShot" and "Sticky" are kind of ambiguous identifiers for the reset
types, and can be kind of misleading. Automatic and Manual communicate
the kind of reset type in a clearer manner. Either the event is
automatically reset, or it isn't and must be manually cleared.

The "OneShot" and "Sticky" terminology is just a hold-over from Citra
where the kernel had a third type of event reset type known as "Pulse".
Given the Switch kernel only has two forms of event reset types, we
don't need to keep the old terminology around anymore.
2019-05-18 15:52:51 -04:00
Lioncash 19632d2421 kernel/svc: Make svcCreateThread/svcStartThread/svcSleepThread/svcExitThread calls show up in the debug log
These are actually quite important indicators of thread lifetimes, so
they should be going into the debug log, rather than being treated as
misc info and delegated to the trace log.
2019-04-29 01:38:27 -04:00
Lioncash d672c6e759 kernel/svc: Reorganize svcSetThreadCoreMask()
Makes the code much nicer to follow in terms of behavior and control
flow. It also fixes a few bugs in the implementation.

Notably, the thread's owner process shouldn't be accessed in order to
retrieve the core mask or ideal core. This should be done through the
current running process. The only reason this bug wasn't encountered yet
is because we currently only support running one process, and thus every
owner process will be the current process.

We also weren't checking against the process' CPU core mask to see if an
allowed core is specified or not.

With this out of the way, it'll be less noisy to implement proper
handling of the affinity flags internally within the kernel thread
instances.
2019-04-29 01:38:27 -04:00
Lioncash 69a2003a8e kernel/thread: Update thread processor ID flags
Adds the missing flags to the enum and documents them.
2019-04-29 01:37:51 -04:00
bunnei 78574e7a47
Merge pull request #2416 from lioncash/wait
kernel/svc: Clean up wait synchronization related functionality
2019-04-24 22:56:08 -04:00
Lioncash f8be3f55da kernel/svc: Name supervisor call 0x36
This call was added to the SVC handlers in the 8.0.0 kernel, so we can
finally give it a name.
2019-04-19 14:34:56 -04:00
bunnei 83b830eb2f
Merge pull request #2397 from lioncash/thread-unused
kernel/thread: Remove unused guest_handle member variable
2019-04-17 21:46:46 -04:00
Lioncash c268ffd831 kernel/thread: Unify wait synchronization types
This is a holdover from Citra, where the 3DS has both
WaitSynchronization1 and WaitSynchronizationN. The switch only has one
form of wait synchronizing (literally WaitSynchonization). This allows
us to throw out code that doesn't apply at all to the Switch kernel.

Because of this unnecessary dichotomy within the wait synchronization
utilities, we were also neglecting to properly handle waiting on
multiple objects.

While we're at it, we can also scrub out any lingering references to
WaitSynchronization1/WaitSynchronizationN in comments, and change them
to WaitSynchronization (or remove them if the mention no longer
applies).
2019-04-17 09:30:56 -04:00
Lioncash 433b59c112 kernel/svc: Migrate svcCancelSynchronization behavior to a thread function
The actual behavior of this function is slightly more complex than what
we're currently doing within the supervisor call. To avoid dumping most
of this behavior in the supervisor call itself, we can migrate this to
another function.
2019-04-17 09:30:56 -04:00
Lioncash 3283aa1e20 svc: Specify handle value in thread's name
Allows the handle to be seen alongside the entry point.
2019-04-15 15:56:18 -04:00
Lioncash 09caf8a756 kernel/thread: Remove unused guest_handle member variable
This member variable is entirely unused. It was only set but never
actually utilized. Given that, we can remove it to get rid of noise in
the thread interface.
2019-04-14 06:06:06 -04:00
Lioncash 4d293bb5cb kernel/svc: Implement svcUnmapProcessCodeMemory
Essentially performs the inverse of svcMapProcessCodeMemory. This unmaps
the aliasing region first, then restores the general traits of the
aliased memory.

What this entails, is:

- Restoring Read/Write permissions to the VMA.
- Restoring its memory state to reflect it as a general heap memory region.
- Clearing the memory attributes on the region.
2019-04-12 21:56:03 -04:00
Lioncash 76a2465655 kernel/svc: Implement svcMapProcessCodeMemory
This is utilized for mapping code modules into memory. Notably, the
ldr service would call this in order to map objects into memory.
2019-04-12 21:55:50 -04:00
Lioncash b117ca5fce kernel/svc: Deglobalize the supervisor call handlers
Adjusts the interface of the wrappers to take a system reference, which
allows accessing a system instance without using the global accessors.

This also allows getting rid of all global accessors within the
supervisor call handling code. While this does make the wrappers
themselves slightly more noisy, this will be further cleaned up in a
follow-up. This eliminates the global system accessors in the current
code while preserving the existing interface.
2019-04-07 20:30:05 -04:00
Lioncash c39c8e6982 kernel/svc: Properly sanitize mutex address in WaitProcessWideKeyAtomic
We need to be checking whether or not the given address is within the
kernel address space or if the given address isn't word-aligned and bail
in these scenarios instead of trashing any kernel state.
2019-04-03 20:25:41 -04:00
bunnei 580e3564c9
Merge pull request #2305 from lioncash/shared
kernel/shared_memory: Sanitize supplied size when unmapping
2019-04-03 11:48:11 -04:00
Lioncash 28719ee3b4 kernel/svc: Implement svcGetThreadList
Similarly like svcGetProcessList, this retrieves the list of threads
from the current process. In the kernel itself, a process instance
maintains a list of threads, which are used within this function.

Threads are registered to a process' thread list at thread
initialization, and unregistered from the list upon thread destruction
(if said thread has a non-null owning process).

We assert on the debug event case, as we currently don't implement
kernel debug objects.
2019-04-02 00:48:40 -04:00
Lioncash cb2bce8006 kernel/svc: Implement svcGetProcessList
This service function simply copies out a specified number of kernel
process IDs, while simultaneously reporting the total number of
processes.
2019-04-02 00:47:14 -04:00
Lioncash 781ab8407b general: Use deducation guides for std::lock_guard and std::unique_lock
Since C++17, the introduction of deduction guides for locking facilities
means that we no longer need to hardcode the mutex type into the locks
themselves, making it easier to switch mutex types, should it ever be
necessary in the future.
2019-04-01 12:53:47 -04:00
bunnei d9b7bc4474
Merge pull request #2304 from lioncash/memsize
kernel/process: Report total physical memory used to svcGetInfo slightly better
2019-03-30 20:11:17 -04:00
Lioncash c6147a439d kernel/shared_memory: Sanitize supplied size when unmapping
The kernel makes sure that the given size to unmap is always the same
size as the entire region managed by the shared memory instance,
otherwise it returns an error code signifying an invalid size.

This is similarly done for transfer memory (which we already check for).
2019-03-29 18:16:19 -04:00
Lioncash 3a846aa80f kernel/process: Report total physical memory used to svcGetInfo
Reports the (mostly) correct size through svcGetInfo now for queries to
total used physical memory. This still doesn't correctly handle memory
allocated via svcMapPhysicalMemory, however, we don't currently handle
that case anyways.
2019-03-28 22:59:20 -04:00
bunnei f770c17d01
Merge pull request #2266 from FernandoS27/arbitration
Kernel: Fixes to Arbitration and SignalProcessWideKey Management
2019-03-28 21:42:24 -04:00
bunnei 16dc3a1dd5
Merge pull request #2284 from lioncash/heap-alloc
kernel/vm_manager: Unify heap allocation/freeing functions
2019-03-28 17:56:49 -04:00
Lioncash 99a163478b kernel/vm_manager: Rename HeapAllocate to SetHeapSize
Makes it more obvious that this function is intending to stand in for
the actual supervisor call itself, and not acting as a general heap
allocation function.

Also the following change will merge the freeing behavior of HeapFree
into this function, so leaving it as HeapAllocate would be misleading.
2019-03-24 17:08:30 -04:00
Lioncash 52980df1aa kernel/vm_manager: Remove unnecessary heap_used data member
This isn't required anymore, as all the kernel ever queries is the size
of the current heap, not the total usage of it.
2019-03-24 17:08:16 -04:00
Lioncash 586cab6172 kernel/vm_manager: Tidy up heap allocation code
Another holdover from citra that can be tossed out is the notion of the
heap needing to be allocated in different addresses. On the switch, the
base address of the heap will always be managed by the memory allocator
in the kernel, so this doesn't need to be specified in the function's
interface itself.

The heap on the switch is always allocated with read/write permissions,
so we don't need to add specifying the memory permissions as part of the
heap allocation itself either.

This also corrects the error code returned from within the function.
If the size of the heap is larger than the entire heap region, then the
kernel will report an out of memory condition.
2019-03-24 16:17:31 -04:00
bunnei 3f74518e19
Merge pull request #2232 from lioncash/transfer-memory
core/hle/kernel: Split transfer memory handling out into its own class
2019-03-24 16:00:23 -04:00
bunnei 7b6d516faa
Merge pull request #2234 from lioncash/mutex
core/hle/kernel: Make Mutex a per-process class.
2019-03-21 22:18:36 -04:00
Fernando Sahmkow 9c7319a4d4 Fix small bug that kept a thread as a condvar thread after being signalled. 2019-03-19 22:43:13 -04:00
Fernando Sahmkow acbdfdae64 Add CondVar Thread State. 2019-03-19 20:32:47 -04:00
Fernando Sahmkow 774f139e65 Small fixes to address_arbiter to better match the IDB. 2019-03-19 20:32:46 -04:00
Lioncash 51d7f6bffc kernel/thread: Move thread exiting logic from ExitCurrentThread to svcExitThread
Puts the operation on global state in the same places as the rest of the
svc calls.
2019-03-15 23:58:37 -04:00
Lioncash c892cf01fa kernel/thread: Migrate WaitCurrentThread_Sleep into the Thread interface
Rather than make a global accessor for this sort of thing. We can make
it a part of the thread interface itself. This allows getting rid of a
hidden global accessor in the kernel code.
2019-03-15 23:58:31 -04:00
Lioncash 555cd26ec2 core/hle/kernel: Make Mutex a per-process class.
Makes it an instantiable class like it is in the actual kernel. This
will also allow removing reliance on global accessors in a following
change, now that we can encapsulate a reference to the system instance
in the class.
2019-03-14 20:55:52 -04:00
Lioncash 5379063108 core/hle/kernel/svc: Implement svcUnmapTransferMemory
Similarly, like svcMapTransferMemory, we can also implement
svcUnmapTransferMemory fairly trivially as well.
2019-03-13 06:04:49 -04:00
Lioncash 567134f874 core/hle/kernel/svc: Implement svcMapTransferMemory
Now that transfer memory handling is separated from shared memory, we
can implement svcMapTransferMemory pretty trivially.
2019-03-13 06:04:49 -04:00
Lioncash cb198d7985 core/hle/kernel: Split transfer memory handling out into its own class
Within the kernel, shared memory and transfer memory facilities exist as
completely different kernel objects. They also have different validity
checking as well. Therefore, we shouldn't be treating the two as the
same kind of memory.

They also differ in terms of their behavioral aspect as well. Shared
memory is intended for sharing memory between processes, while transfer
memory is intended to be for transferring memory to other processes.

This breaks out the handling for transfer memory into its own class and
treats it as its own kernel object. This is also important when we
consider resource limits as well. Particularly because transfer memory
is limited by the resource limit value set for it.

While we currently don't handle resource limit testing against objects
yet (but we do allow setting them), this will make implementing that
behavior much easier in the future, as we don't need to distinguish
between shared memory and transfer memory allocations in the same place.
2019-03-13 06:04:44 -04:00
Lioncash 8e510d5afa kernel: Make the address arbiter instance per-process
Now that we have the address arbiter extracted to its own class, we can
fix an innaccuracy with the kernel. Said inaccuracy being that there
isn't only one address arbiter. Each process instance contains its own
AddressArbiter instance in the actual kernel.

This fixes that and gets rid of another long-standing issue that could
arise when attempting to create more than one process.
2019-03-07 23:27:51 -05:00
Lioncash b7f331afa3 kernel/svc: Move address arbiter signaling behind a unified API function
Similar to how WaitForAddress was isolated to its own function, we can
also move the necessary conditional checking into the address arbiter
class itself, allowing us to hide the implementation details of it from
public use.
2019-03-07 23:27:47 -05:00
Lioncash 0209de123b kernel/svc: Move address arbiter waiting behind a unified API function
Rather than let the service call itself work out which function is the
proper one to call, we can make that a behavior of the arbiter itself,
so we don't need to directly expose those implementation details.
2019-03-07 23:27:20 -05:00
bunnei ed0bdcc638
Merge pull request #2197 from lioncash/include
core/hle/ipc: Remove unnecessary includes
2019-03-06 21:55:16 -05:00
bunnei 75b417489a
Merge pull request #2199 from lioncash/arbiter
kernel/address_arbiter: Convert the address arbiter into a class
2019-03-06 15:55:56 -05:00
Lioncash ec6664f6d6 kernel/address_arbiter: Convert the address arbiter into a class
Places all of the functions for address arbiter operation into a class.
This will be necessary for future deglobalizing efforts related to both
the memory and system itself.
2019-03-05 12:58:26 -05:00
Lioncash 02bc9e9de1 core/hle/ipc: Remove unnecessary includes
Removes a few inclusion dependencies from the headers or replaces
existing ones with ones that don't indirectly include the required
headers.

This allows removing an inclusion of core/memory.h, meaning that if the
memory header is ever changed in the future, it won't result in
rebuilding the entirety of the HLE services (as the IPC headers are used
quite ubiquitously throughout the HLE service implementations).
2019-03-05 09:53:38 -05:00
Lioncash 0be8fffc99 svc: Migrate address range checking functions to VMManager
Provides a bit of a more proper interface for these functions.
2019-03-04 16:32:03 -05:00
Lioncash bd983414f6 core_timing: Convert core timing into a class
Gets rid of the largest set of mutable global state within the core.
This also paves a way for eliminating usages of GetInstance() on the
System class as a follow-up.

Note that no behavioral changes have been made, and this simply extracts
the functionality into a class. This also has the benefit of making
dependencies on the core timing functionality explicit within the
relevant interfaces.
2019-02-15 21:50:25 -05:00
Lioncash 48d9d66dc5 core_timing: Rename CoreTiming namespace to Core::Timing
Places all of the timing-related functionality under the existing Core
namespace to keep things consistent, rather than having the timing
utilities sitting in its own completely separate namespace.
2019-02-12 12:42:17 -05:00
Lioncash 7842536ddb
kernel/svc: Log out uncaught C++ exceptions from svcBreak
Looking into the implementation of the C++ standard facilities that seem
to be within all modules, it appears that they use 7 as a break reason
to indicate an uncaught C++ exception.

This was primarily found via the third last function called within
Horizon's equivalent of libcxxabi's demangling_terminate_handler(),
which passes the value 0x80000007 to svcBreak.
2019-01-26 21:19:13 -05:00
Lioncash b4242633ad kernel/svc: Correct misleading error message within CreateThread()
This is a bounds check to ensure that the thread priority is within the
valid range of 0-64. If it exceeds 64, that doesn't necessarily mean
that an actual priority of 64 was expected (it actually means whoever
called the function screwed up their math).

Instead clarify the message to indicate the allowed range of thread
priorities.
2018-12-30 21:29:38 -05:00
Lioncash 3a8d38be7e kernel/svc: Sanitize core number and thread priorities in CreateThread()
Now that we handle the kernel capability descriptors we can correct
CreateThread to properly check against the core and priority masks
like the actual kernel does.
2018-12-30 21:23:56 -05:00
Lioncash 8769604144 kernel/process: Rename GetAllowedProcessorMask() and GetAllowedThreadPriorityMask()
Makes them consistent with their kernel capability counterparts.
2018-12-30 21:09:46 -05:00
Lioncash 205e6d3b97 kernel/svc: Simplify thread core ID sanitizing in CreateThread
Rather than use a switch here, this can be collapsed into a simple range
check, which is a little easier on the eyes.
2018-12-30 20:59:54 -05:00
Sebastian Valle e5dfbe22ee
Merge pull request #1956 from lioncash/process-thread
kernel/process: Start the main thread using the specified ideal core
2018-12-30 20:32:41 -05:00
bunnei 331c252509
Merge pull request #1847 from ogniK5377/backtrace-break
Print backtrace on svcBreak
2018-12-29 22:58:13 -05:00
Lioncash f80bc712ea kernel: Rename 'default' CPU core to 'ideal' core
This makes the naming more closely match its meaning. It's just a
preferred core, not a required default core. This also makes the usages
of this term consistent across the thread and process implementations.
2018-12-27 21:48:49 -05:00
Lioncash fbeaa330a3 kernel/process: Remove most allocation functions from Process' interface
In all cases that these functions are needed, the VMManager can just be
retrieved and used instead of providing the same functions in Process'
interface.

This also makes it a little nicer dependency-wise, since it gets rid of
cases where the VMManager interface was being used, and then switched
over to using the interface for a Process instance. Instead, it makes
all accesses uniform and uses the VMManager instance for all necessary
tasks.

All the basic memory mapping functions did was forward to the Process'
VMManager instance anyways.
2018-12-27 19:08:47 -05:00
bunnei ae582b6669
Merge pull request #1849 from encounter/svcSetThreadActivity
svc: Implement SetThreadActivity (thread suspension)
2018-12-26 15:54:14 -05:00
bunnei 59ac3346eb
Merge pull request #1925 from lioncash/pid
kernel/{process, thread}: Amend behavior related to IDs
2018-12-21 13:45:27 -05:00
Lioncash b74eb88c68 kernel/svc: Handle thread handles within GetProcessId
If a thread handle is passed to svcGetProcessId, the kernel attempts to
access the process ID via the thread's instance's owning process.

Technically, this function should also be handling the kernel debug
objects as well, however we currently don't handle those kernel objects
yet, so I've left a note via a comment about it to remind myself when
implementing it in the future.
2018-12-19 12:16:15 -05:00
Lioncash caab838bdb svc: Implement svcSetMemoryAttribute
With all the basic backing functionality implemented, we can now unstub
svcSetMemoryAttribute.
2018-12-19 10:59:40 -05:00
Lioncash 0906302ca9 kernel/svc: Correct output parameter for svcGetThreadId
The service call uses a 64-bit value, just like svcGetProcessId. This
amends the function signature accordingly.
2018-12-18 22:38:26 -05:00
Lioncash 43e1189688 kernel/svc: Correct output parameter for svcGetProcessId
svcGetProcessId's out parameter is a pointer to a 64-bit value, not a
32-bit one.
2018-12-18 22:30:56 -05:00
David Marcec 08d5663cb8 Moved backtrace to ArmInterface 2018-12-19 14:10:51 +11:00
bunnei 2f2fc47af2
Merge pull request #1732 from DarkLordZach/yield-types
svc: Implement yield types 0 and -1
2018-12-15 00:28:12 -05:00
bunnei 1a23970d17
Merge pull request #1899 from lioncash/state
vm_manager/svc: Modify MemoryState enum, and correct error handling for svcQueryMemory
2018-12-14 15:30:02 -05:00
Lioncash b79f086613 svc: Enable svcQueryProcessMemory
svcQueryProcessMemory is trivial to implement, given all the behavior
necessary for it is present, it just needs a handler for it.
2018-12-12 15:45:05 -05:00
Lioncash 09a219d5b4 svc: Write out the complete MemoryInfo structure in QueryProcessMemory
In the previous change, the memory writing was moved into the service
function itself, however it still had a problem, in that the entire
MemoryInfo structure wasn't being written out, only the first 32 bytes
of it were being written out. We still need to write out the trailing
two reference count members and zero out the padding bits.

Not doing this can result in wrong behavior in userland code in the following
scenario:

MemoryInfo info;                 // Put on the stack, not quaranteed to be zeroed out.
svcQueryMemory(&info, ...);

if (info.device_refcount == ...) // Whoops, uninitialized read.

This can also cause the wrong thing to happen if the user code uses
std::memcmp to compare the struct, with another one (questionable, but
allowed), as the padding bits are not guaranteed to be a deterministic
value. Note that the kernel itself also fully zeroes out the structure
before writing it out including the padding bits.
2018-12-12 15:44:58 -05:00
Lioncash d8deb39b83 svc: Handle memory writing explicitly within QueryProcessMemory
Moves the memory writes directly into QueryProcessMemory instead of
letting the wrapper function do it. It would be inaccurate to allow the
handler to do it because there's cases where memory shouldn't even be
written to. For example, if the given process handle is invalid.

HOWEVER, if the memory writing is within the wrapper, then we have no
control over if these memory writes occur, meaning in an error case, 68
bytes of memory randomly get trashed with zeroes, 64 of those being
written to wherever the memory info address points to, and the remaining
4 being written wherever the page info address points to.

One solution in this case would be to just conditionally check within
the handler itself, but this is kind of smelly, given the handler
shouldn't be performing conditional behavior itself, it's a behavior of
the managed function. In other words, if you remove the handler from the
equation entirely, does the function still retain its proper behavior?
In this case, no.

Now, we don't potentially trash memory from this function if an invalid
query is performed.
2018-12-12 15:43:31 -05:00
Lioncash a8cc03502b vm_manager: Migrate memory querying to the VMManager interface
Gets rid of the need to directly access the managed VMAs outside of the
memory manager itself just for querying memory.
2018-12-12 15:07:30 -05:00
Lioncash 366985ca92 vm_manager: Amend MemoryState enum members
Amends the MemoryState enum to use the same values like the actual
kernel does. Also provides the necessary operators to operate on them.
This will be necessary in the future for implementing
svcSetMemoryAttribute, as memory block state is checked before applying
the attribute.
2018-12-12 14:03:50 -05:00
Jens Schmer ae390ad5a2 Fix Process object leak on emulation stop
The Process object kept itself alive indefinitely because its handle_table
contains a SharedMemory object which owns a reference to the same Process object,
creating a circular ownership scenario.

Break that up by storing only a non-owning pointer in the SharedMemory object.
2018-12-12 17:25:56 +01:00
bunnei 74242a8fb4
Merge pull request #1876 from lioncash/vma
vm_manager: Make vma_map private
2018-12-10 10:09:50 -05:00
Lioncash d4c1b9d311 vm_manager: Make vma_map private
This was only ever public so that code could check whether or not a
handle was valid or not. Instead of exposing the object directly and
allowing external code to potentially mess with the map contents, we
just provide a member function that allows checking whether or not a
handle is valid.

This makes all member variables of the VMManager class private except
for the page table.
2018-12-06 15:02:17 -05:00
Zach Hilman e6f7825a24 svc: Avoid incorrect fast yield condition 2018-12-04 22:11:32 -05:00
Lioncash 2f253986df kernel/svc: Correct behavior of svcResetSignal()
While partially correct, this service call allows the retrieved event to
be null, as it also uses the same handle to check if it was referring to
a Process instance. The previous two changes put the necessary machinery
in place to allow for this, so we can simply call those member functions
here and be done with it.
2018-12-04 20:14:59 -05:00
Lioncash 8ea1f28614 kernel/svc: Remove unused header inclusion 2018-12-04 15:48:20 -05:00
Lioncash a543c35962 kernel/svc: Implement svcSignalEvent()
This function simply does a handle table lookup for a writable event
instance identified by the given handle value. If a writable event
cannot be found for the given handle, then an invalid handle error is
returned. If a writable event is found, then it simply signals the
event, as one would expect.
2018-12-04 15:47:59 -05:00
Lioncash 2a1f59b301 kernel/svc: Implement svcCreateEvent()
svcCreateEvent operates by creating both a readable and writable event
and then attempts to add both to the current process' handle table.

If adding either of the events to the handle table fails, then the
relevant error from the handle table is returned.

If adding the readable event after the writable event to the table
fails, then the writable event is removed from the handle table and the
relevant error from the handle table is returned.

Note that since we do not currently test resource limits, we don't check
the resource limit table yet.
2018-12-04 15:47:55 -05:00
bunnei d533767623
Merge pull request #1853 from lioncash/event
kernel/object: Amend handle types to distinguish between readable and writable events
2018-12-04 12:25:40 -05:00
Lioncash 5eb057f422 kernel/object: Amend handle types to distinguish between readable and writable events
Two kernel object should absolutely never have the same handle ID type.
This can cause incorrect behavior when it comes to retrieving object
types from the handle table. In this case it allows converting a
WritableEvent into a ReadableEvent and vice-versa, which is undefined
behavior, since the object types are not the same.

This also corrects ClearEvent() to check both kernel types like the
kernel itself does.
2018-12-04 02:20:47 -05:00
Lioncash 312690b450 kernel/svc: Implement the resource limit svcGetInfo option
Allows a process to register the resource limit as part of its handle
table.
2018-12-04 01:50:30 -05:00
Luke Street 3e75175d02 svc: Implement SetThreadActivity (thread suspension) 2018-12-04 01:23:50 -05:00
V.Kalyuzhny b330b495dc [Kernel::CreateThread] Match format specifiers to LOG_TRACE's arguments 2018-12-04 05:13:50 +02:00
Zach Hilman ddf5903cd9 scheduler: Avoid manual Reschedule call
This will automatically occur anyway when PrepareReschedule is called
2018-12-03 21:22:09 -05:00
bunnei 9f1ac96afa
Merge pull request #1840 from lioncash/info
svc: Reorganize svcGetInfo, handle more error cases for existing implemented info categories
2018-12-03 18:46:22 -05:00
Zach Hilman b5af41a07b scheduler: Only work steal higher priority threads from other cores 2018-12-03 17:29:30 -05:00
bunnei ef69b4b830
Merge pull request #1803 from DarkLordZach/k-able-event
kernel: Divide Event into ReadableEvent and WritableEvent
2018-12-03 17:05:57 -05:00
David Marcec 7149332712 Print backtrace on svcBreak
When we get an svcBreak we get a backtrace now
2018-12-03 19:12:09 +11:00
Lioncash 7fe27de26e svc: Use the current process' handle table for retrieving the process instance to act upon
The kernel uses the handle table of the current process to retrieve the
process that should be used to retrieve certain information. To someone
not familiar with the kernel, this might raise the question of "Ok,
sounds nice, but doesn't this make it impossible to retrieve information
about the current process?".

No, it doesn't, because HandleTable instances in the kernel have the
notion of a "pseudo-handle", where certain values allow the kernel to
lookup objects outside of a given handle table. Currently, there's only
a pseudo-handle for the current process (0xFFFF8001) and a pseudo-handle
for the current thread (0xFFFF8000), so to retrieve the current process,
one would just pass 0xFFFF8001 into svcGetInfo.

The lookup itself in the handle table would be something like:

template <typename T>
T* Lookup(Handle handle) {
    if (handle == PSEUDO_HANDLE_CURRENT_PROCESS) {
        return CurrentProcess();
    }

    if (handle == PSUEDO_HANDLE_CURRENT_THREAD) {
        return CurrentThread();
    }

    return static_cast<T*>(&objects[handle]);
}

which, as is shown, allows accessing the current process or current
thread, even if those two objects aren't actually within the HandleTable
instance.
2018-12-02 03:41:49 -05:00
Lioncash 6712e7402c svc: Reorganize svcGetInfo, handle more error cases for existing implemented info categories
Our implementation of svcGetInfo was slightly incorrect in that we
weren't doing proper error checking everywhere. Instead, reorganize it
to be similar to how the kernel seems to do it.
2018-12-02 03:40:10 -05:00
Zach Hilman 3476830b26 svc: Avoid performance-degrading unnecessary reschedule 2018-12-02 00:44:40 -05:00
Lioncash e88cdcc912 Fix debug build
A non-existent parameter was left in some formatting calls (the logging
macro for which only does anything meaningful on debug builds)
2018-12-01 02:11:42 -05:00
Zach Hilman a342bcc9b1 kernel/event: Reference ReadableEvent from WritableEvent 2018-11-29 08:48:40 -05:00
Zach Hilman ff610103b5 core: Port all current usages of Event to Readable/WritableEvent 2018-11-29 08:45:41 -05:00
bunnei 1e49a85106
Merge pull request #1801 from ogniK5377/log-before-execute
Changed logging to be "Log before execution", Added more error logging, all services/svc should now log on some level
2018-11-29 00:58:46 -05:00
Lioncash 5905162e36 svc: Implement svcSetResourceLimitLimitValue()
The opposite of the getter functions, this function sets the limit value
for a particular ResourceLimit resource category, with the restriction
that the  new limit value must be equal to or greater than the current
resource value. If this is violated, then ERR_INVALID_STATE is returned.

e.g.

Assume:

current[Events] = 10;
limit[Events] = 20;

a call to this service function lowering the limit value to 10 would be
fine, however, attempting to lower it to 9 in this case would cause an
invalid state error.
2018-11-26 21:23:15 -05:00
Lioncash eb5596044d svc: Implement svcGetResourceLimitCurrentValue()
This kernel service function is essentially the exact same as
svcGetResourceLimitLimitValue(), with the only difference being that it
retrieves the current value for a given resource category using the
provided resource limit handle, rather than retrieving the limiting
value of that resource limit instance.

Given these are exactly the same and only differ on returned values, we
can extract the existing code for svcGetResourceLimitLimitValue() to
handle both values.
2018-11-26 21:23:11 -05:00
Lioncash 1d6399c222 svc: Implement svcGetResourceLimitLimitValue()
This kernel service function retrieves the maximum allowable value for
a provided resource category for a given resource limit instance. Given
we already have the functionality added to the resource limit instance
itself, it's sufficient to just hook it up.

The error scenarios for this are:

1. If an invalid resource category type is provided, then ERR_INVALID_ENUM is returned.

2. If an invalid handle is provided, then ERR_INVALID_HANDLE is returned (bad thing goes in, bad thing goes out, as one would expect).

If neither of the above error cases occur, then the out parameter is
provided with the maximum limit value for the given category and success
is returned.
2018-11-26 21:12:13 -05:00
Lioncash 4ef2af8c98 svc: Implement svcCreateResourceLimit()
This function simply creates a ResourceLimit instance and attempts to
create a handle for it within the current process' handle table. If the
kernal fails to either create the ResourceLimit instance or create a
handle for the ResourceLimit instance, it returns a failure code
(OUT_OF_RESOURCE, and HANDLE_TABLE_FULL respectively). Finally, it exits
by providing the output parameter with the handle value for the
ResourceLimit instance and returning that it was successful.

Note: We do not return OUT_OF_RESOURCE because, if yuzu runs out of
available memory, then new will currently throw. We *could* allocate the
kernel instance with std::nothrow, however this would be inconsistent
with how all other kernel objects are currently allocated.
2018-11-26 21:10:31 -05:00
David Marcec cc4521fc70 Added comment on Main memory size for more clarity 2018-11-27 12:56:50 +11:00
David Marcec f058de337e Made svcSetHeapSize and svcCreateSharedMemory more readable 2018-11-27 12:53:18 +11:00
David Marcec f271316822 Reworked svcs slightly, improved error messages in AM and fsp_srv 2018-11-27 12:29:06 +11:00
David Marcec 9662ca918d Improved error messages for SVCs 2018-11-26 19:47:39 +11:00
David Marcec a2cc3b10bb Changed logging to be "Log before execution", Added more error logging, all services should now log on some level 2018-11-26 17:06:13 +11:00
Luke Street 94e8dfc0c7 svc: Return ERR_INVALID_ENUM_VALUE from svcGetInfo 2018-11-25 16:48:44 -05:00
Zach Hilman 820d81b9a5 scheduler: Add explanations for YieldWith and WithoutLoadBalancing 2018-11-22 00:33:53 -05:00
bunnei aa7e53ab5c
Merge pull request #1734 from lioncash/shared
kernel/shared_memory: Make data members private, plus minor interface changes
2018-11-20 16:13:30 -08:00
bunnei b6d2c64f4d
Merge pull request #1667 from DarkLordZach/swkbd
am: Implement HLE software keyboard applet
2018-11-20 08:24:11 -08:00
Lioncash 5d46038c5c kernel/resource_limit: Clean up interface
Cleans out the citra/3DS-specific implementation details that don't
apply to the Switch. Sets the stage for implementing ResourceLimit
instances properly.

While we're at it, remove the erroneous checks within CreateThread() and
SetThreadPriority(). While these are indeed checked in some capacity,
they are not checked via a ResourceLimit instance.

In the process of moving out Citra-specifics, this also replaces the
system ResourceLimit instance's values with ones from the Switch.
2018-11-19 18:16:39 -05:00
Lioncash 233e495c14 kernel/shared_memory: Make Map() and Unmap() take the target process by reference rather than as a pointer
Both member functions assume the passed in target process will not be
null. Instead of making this assumption implicit, we can change the
functions to be references and enforce this at the type-system level.
2018-11-19 09:20:29 -05:00
Zach Hilman 409dcf0e0a svc: Implement yield types 0 and -1 2018-11-18 23:44:19 -05:00
Mat M 9a1bac840e
Merge pull request #1728 from FearlessTobi/reset-signal
svc: ResetSignal is not stubbed
2018-11-18 15:51:32 -05:00
Tobias 13f79cc5bd
svc: ResetSignal is not stubbed
https://user-images.githubusercontent.com/20753089/48677874-b8e01c80-eb7b-11e8-8043-b99faa29022c.PNG
2018-11-18 21:49:17 +01:00
Zach Hilman e696ed1f4d am: Deglobalize software keyboard applet 2018-11-18 10:53:47 -05:00
Zach Hilman 7901de2b75 svc: Implement svcCreateTransferMemory
Seems to be used and created identically to SharedMemory, so just reuse that.
2018-11-18 10:53:47 -05:00
Lioncash d21b2164e9 kernel/errors: Clean up error codes
Similar to PR 1706, which cleans up the error codes for the filesystem
code, but done for the kernel error codes. This removes the ErrCodes
namespace and specifies the errors directly. This also fixes up any
straggling lines of code that weren't using the named error codes where
applicable.
2018-11-16 14:32:30 -05:00
Mat M 14cede1a0c
Merge pull request #1638 from FreddyFunk/SetMemoryPermission-Stubbed
Implement SetMemoryPermission
2018-11-16 10:35:56 -05:00
Zach Hilman ab552e4a25 svc: Use proper random entropy generation algorithm 2018-11-13 12:26:03 -05:00
Zach Hilman cb1e63ef09 svc: Return random seed for svcGetInfo RandomEntropy 2018-11-12 21:46:21 -05:00
David 581406af18 svcBreak now dumps information from the debug buffer passed (#1646)
* svcBreak now dumps information from the debug buffer passed

info1 and info2 seem to somtimes hold an address to a buffer, this is usually 4 bytes or the size of the int and contains an error code. There's other circumstances where it can be something different so we hexdump these to examine them at a later date.

* Addressed comments
2018-11-07 20:43:54 -08:00
Frederic Laing ba2cdcdc5a Implement SetMemoryPermission 2018-11-06 10:21:01 +01:00
Frederic Laing ab7472345b Stubbed SetMemoryPermission 2018-11-03 16:01:34 +01:00
Lioncash a973a049b7 core: Make System references const where applicable 2018-10-28 17:45:29 -04:00
Lioncash 7de8e36343 svc: Localize the GetInfo enum class to the function itself
Nothing from this enum is intended to be used outside of this function.
2018-10-26 12:49:14 -04:00
Lioncash 6594853eb1 svc: Implement svcGetInfo command 0xF0000002
This retrieves:

if (curr_thread == handle_thread) {
   result = total_thread_ticks + (hardware_tick_count - last_context_switch_ticks);
} else if (curr_thread == handle_thread && sub_id == current_core_index) {
   result = hardware_tick_count - last_context_switch_ticks;
}
2018-10-26 12:49:11 -04:00
Lioncash fcf8f53a63 kernel/svc: Amend returned error code for invalid priorities in CreateThread
Like with the previous change, the kernel doesn't return NOT_AUTHORIZED
here. It returns INVALID_THREAD_PRIORITY.
2018-10-24 14:11:11 -04:00
Lioncash 77328b0f19 kernel/svc: Move and correct returned error code for invalid thread priorities in SetThreadPriority()
All priority checks are supposed to occur before checking the validity
of the thread handle, we're also not supposed to return
ERR_NOT_AUTHORIZED here.
2018-10-24 14:10:48 -04:00
bunnei a94e5d9e68
Merge pull request #1551 from ogniK5377/improved-svcbreak
Added break types to svcBreak
2018-10-23 19:56:42 -04:00
bunnei e61a62066a
Merge pull request #1540 from lioncash/handle
kernel/process: Make the handle table per-process
2018-10-23 18:43:11 -04:00
David Marcec 38cdb6744d Added assertion failed, reworked logging levels 2018-10-23 15:17:13 +11:00
David Marcec 8042731da9 Added break types to svcBreak
There seems to be more such as type 1, and 2. Unsure what these currently are but when a game hits them we can investigate and add the rest
2018-10-23 15:03:59 +11:00
Lioncash 90a981a03a kernel/process: Make the handle table per-process
In the kernel, there isn't a singular handle table that everything gets
tossed into or used, rather, each process gets its own handle table that
it uses. This currently isn't an issue for us, since we only execute one
process at the moment, but we may as well get this out of the way so
it's not a headache later on.
2018-10-20 16:38:32 -04:00
Lioncash 896c0f61a0 svc: Fix vma boundary check in svcQueryMemory
This should be comparing against the queried process' vma_map, not the
current process'. The only reason this hasn't become an issue yet is we
currently only handle one process being active at any time.
2018-10-20 14:56:51 -04:00
bunnei 60317e6306
Merge pull request #1520 from lioncash/san
svc: Add missing sanitizing checks for MapSharedMemory/UnmapSharedMemory
2018-10-19 22:58:57 -04:00
Lioncash 4b5ae8dbaa svc: Check for word alignment of addresses within svcArbitrateLock/svcArbitrateUnlock
The kernel itself checks whether or not the provided addresses are word
aligned before continuing, so we should be doing the same.
2018-10-18 13:01:29 -04:00
Lioncash d27f4a4928 common: Move Is4KBAligned() to alignment.h
Aligning on 4KB pages isn't a Switch-specific thing, so this can be
moved to common so it can be used with other things as well.
2018-10-18 12:57:02 -04:00
Lioncash 33830aa65a svc: Add missing sanitizing checks for MapSharedMemory/UnmapSharedMemory
Now that the changes clarifying the address spaces has been merged, we
can wrap the checks that the kernel performs when mapping shared memory
(and other forms of memory) into its own helper function and then use
those within MapSharedMemory and UnmapSharedMemory to complete the
sanitizing checks that are supposed to be done.
2018-10-18 02:01:21 -04:00
bunnei 6e8752881c
Merge pull request #1498 from lioncash/aslr
svc: Clarify enum values for AddressSpaceBaseAddr and AddressSpaceSize in svcGetInfo()
2018-10-17 18:31:51 -04:00
Lioncash 5484742fda core_cpu: Make Cpu scheduler instances unique_ptrs instead of shared_ptrs 2018-10-15 14:15:56 -04:00
Lioncash 90f8474fc1 svc: Clarify enum values for AddressSpaceBaseAddr and AddressSpaceSize in svcGetInfo()
So, one thing that's puzzled me is why the kernel seemed to *not* use
the direct code address ranges in some cases for some service functions.
For example, in svcMapMemory, the full address space width is compared
against for validity, but for svcMapSharedMemory, it compares against
0xFFE00000, 0xFF8000000, and 0x7FF8000000 as upper bounds, and uses
either 0x200000 or 0x8000000 as the lower-bounds as the beginning of the
compared range. Coincidentally, these exact same values are also used in
svcGetInfo, and also when initializing the user address space, so this
is actually retrieving the ASLR extents, not the extents of the address
space in general.
2018-10-14 20:11:16 -04:00
bunnei 2f8ca32020
Merge pull request #1492 from lioncash/proc
svc: Implement svcGetProcessInfo
2018-10-14 14:37:58 -04:00
David Marcec 92fae7e1ab Stop all threads on svcBreak
This should help diagnose crashes easier and prevent many users thinking that a game is still running when in fact it's just an audio thread still running(this is typically not killed when svcBreak is hit since the game expects us to do this)
2018-10-14 18:14:51 +11:00
Lioncash 1c7a7ed79b svc: Implement svcGetProcessInfo
A fairly basic service function, which only appears to currently support
retrieving the process state. This also alters the ProcessStatus enum to
contain all of the values that a kernel process seems to be able of
reporting with regards to state.
2018-10-13 17:00:43 -04:00
bunnei ffcda6c08e
Merge pull request #1481 from lioncash/typo
svc: Fix typos in sanitizing checks for MapMemory/UnmapMemory
2018-10-12 20:46:55 -04:00
bunnei 2946d4bdbe
Merge pull request #1467 from ogniK5377/svcbreak-type-fix
Fixed incorrect types for svcBreak
2018-10-12 12:08:08 -04:00
Lioncash 4ccf30dfaa svc: Fix typos in sanitizing checks for MapMemory/UnmapMemory 2018-10-12 01:48:26 -04:00
Lioncash 72e9cb523e svc: Add missing address range sanitizing checks to MapMemory/UnmapMemory
This adds the missing address range checking that the service functions
do before attempting to map or unmap memory. Given that both service
functions perform the same set of checks in the same order, we can wrap
these into a function and just call it from both functions, which
deduplicates a little bit of code.
2018-10-10 20:30:49 -04:00
Lioncash 5c0408596f kernel/thread: Use a regular pointer for the owner/current process
There's no real need to use a shared pointer in these cases, and only
makes object management more fragile in terms of how easy it would be to
introduce cycles. Instead, just do the simple thing of using a regular
pointer. Much of this is just a hold-over from citra anyways.

It also doesn't make sense from a behavioral point of view for a
process' thread to prolong the lifetime of the process itself (the
process is supposed to own the thread, not the other way around).
2018-10-10 02:04:55 -04:00
David Marcec 09b6dda8f0 Use a better name than "dont_kill_application"
signal_debugger seems like a more fitting name
2018-10-10 12:27:44 +11:00
David Marcec a4412c8e22 Fixed incorrect types for svcBreak
svcBreak reason should be a u32, not a u64.
2018-10-10 12:23:50 +11:00
David Marcec f5631e78d1 Added bitfield instead of manually checking if the bit is set 2018-10-09 12:11:14 +11:00
David Marcec af3ba94b2a Actual kill execution when the bit isn't set, not the other way around 2018-10-09 11:14:48 +11:00
David Marcec c50f66a8eb svcBreak, Signalling to the debugger should not kill execution
When loading NROs, svcBreak is called to signal to the debugger that a new "module" is loaded. As no debugger is technically attached we shouldn't be killing the programs execution.
2018-10-09 11:10:30 +11:00
Lioncash baed7e1fba kernel/thread: Make all instance variables private
Many of the member variables of the thread class aren't even used
outside of the class itself, so there's no need to make those variables
public. This change follows in the steps of the previous changes that
made other kernel types' members private.

The main motivation behind this is that the Thread class will likely
change in the future as emulation becomes more accurate, and letting
random bits of the emulator access data members of the Thread class
directly makes it a pain to shuffle around and/or modify internals.
Having all data members public like this also makes it difficult to
reason about certain bits of behavior without first verifying what parts
of the core actually use them.

Everything being public also generally follows the tendency for changes
to be introduced in completely different translation units that would
otherwise be better introduced as an addition to the Thread class'
public interface.
2018-10-04 00:14:15 -04:00
Lioncash 541c550753 kernel/svc: Implement svcGetThreadContext()
Now that we have all of the rearranging and proper structure sizes in
place, it's fairly trivial to implement svcGetThreadContext(). In the
64-bit case we can more or less just write out the context as is, minus
some minor value sanitizing. In the 32-bit case we'll need to clear out
the registers that wouldn't normally be accessible from a 32-bit
AArch32 exectuable (or process).
2018-09-30 05:29:40 -04:00
Lioncash cf9d6c6f52 kernel/process: Make data member variables private
Makes the public interface consistent in terms of how accesses are done
on a process object. It also makes it slightly nicer to reason about the
logic of the process class, as we don't want to expose everything to
external code.
2018-09-30 02:30:01 -04:00
bunnei f7b69d61f2
Merge pull request #1395 from lioncash/vm
process/vm_manager: Initial modifications to load NPDM metadata
2018-09-29 10:54:39 -04:00
bunnei b67c1fdf38
Merge pull request #1393 from tech4me/svc
svc: Updated svc names
2018-09-25 10:47:12 -04:00
Lioncash 83377113bf memory: Dehardcode the use of fixed memory range constants
The locations of these can actually vary depending on the address space
layout, so we shouldn't be using these when determining where to map
memory or be using them as offsets for calculations. This keeps all the
memory ranges flexible and malleable based off of the virtual memory
manager instance state.
2018-09-24 22:16:03 -04:00
Lioncash 6c6f95d071 svc: Report correct memory-related values within some of the cases in svcGetInfo()
Previously, these were reporting hardcoded values, but given the regions
can change depending on the requested address spaces, these need to
report the values that the memory manager contains.
2018-09-24 22:16:03 -04:00
tech4me d42424ace0 svc: Updated svc names 2018-09-23 17:03:38 -07:00
Lioncash 48b2eda492 svc: Move most process termination code to its own function within Process
Reduces the use of Process class members externally and keeps most code
related to tearing down a process with the rest of the process code.
2018-09-21 06:07:41 -04:00
Lioncash b6867602ca kernel/svc: Handle error cases for svcArbitrateLock() and svcArbitrateUnlock()
The kernel does the equivalent of the following check before proceeding:

if (address + 0x8000000000 < 0x7FFFE00000) {
    return ERR_INVALID_MEMORY_STATE;
}

which is essentially what our IsKernelVirtualAddress() function does. So
we should also be checking for this.

The kernel also checks if the given input addresses are 4-byte aligned,
however our Mutex::TryAcquire() and Mutex::Release() functions already
handle this, so we don't need to add code for this case.
2018-09-17 23:27:53 -04:00
bunnei e6367ab955
Merge pull request #1315 from lioncash/size
kernel/svc: Handle a few error cases within memory-related functions
2018-09-17 10:11:26 -04:00
bunnei e561afdcd5
Merge pull request #1328 from FearlessTobi/port-4192
Port #4192 from Citra: "svc: change unknown to thread in CreateThread"
2018-09-17 09:56:48 -04:00
Valentin Vanelslande 54ddb37b3c Port # #4192 from Citra: "svc: change unknown to thread in CreateThread" 2018-09-15 15:28:35 +02:00
fearlessTobi 63c2e32e20 Port #4182 from Citra: "Prefix all size_t with std::" 2018-09-15 15:21:06 +02:00
Lioncash 4f8756edd0 kernel/svc: Sanitize creation of shared memory via svcCreateSharedMemory()
The kernel caps the size limit of shared memory to 8589930496 bytes (or
(1GB - 512 bytes) * 8), so approximately 8GB, where every GB has a 512
byte sector taken off of it.

It also ensures the shared memory is created with either read or
read/write permissions for both permission types passed in, allowing the
remote permissions to also be set as "don't care".
2018-09-13 23:07:27 -04:00
Lioncash accd1f17e4 kernel/svc: Sanitize addresses, permissions, and sizes within svcMapSharedMemory() and svcUnmapSharedMemory()
Part of the checking done by the kernel is to check if the given
address and size are 4KB aligned, as well as checking if the size isn't
zero. It also only allows mapping shared memory as readable or
read/write, but nothing else, and so we shouldn't allow mapping as
anything else either.
2018-09-13 23:07:23 -04:00
Lioncash 496c67fd73 kernel/svc: Sanitize addresses and sizes within svcMapMemory() and svcUnmapMemory()
The kernel checks if the addresses and given size is 4KB aligned before
continuing onwards to map the memory.
2018-09-13 21:34:54 -04:00
Lioncash 7bd2faad9a kernel/svc: Sanitize heap sizes within svcSetHeapSize()
The kernel checks if the given size is a multiple of 2MB and <= to 4GB
before going ahead and attempting to allocate that much memory.
2018-09-13 21:34:48 -04:00
bunnei 79217f9870
Merge pull request #1303 from lioncash/error
kernel/errors: Amend invalid thread priority and invalid processor ID error codes
2018-09-12 12:14:51 -04:00
Lioncash fbe462099b svc: Return ERR_INVALID_PROCESSOR_ID in CreateThread() if an invalid processor ID is given
This is what the kernel does for an out-of-range processor ID.
2018-09-12 05:20:02 -04:00
Lioncash 3c5c292592 kernel/errors: Correct error codes for invalid thread priority and invalid processor ID 2018-09-12 05:19:57 -04:00
Lioncash 9b3bc0b282 svc: Do nothing if svcOutputDebugString() is given a length of zero
While unlikely, it does avoid constructing a std::string and
unnecessarily calling into the memory code if a game or executable
decides to be really silly about their logging.
2018-09-12 04:51:44 -04:00
Lioncash 04d723baf9 svc: Correct parameter type for OutputDebugString()
This should be a u64 to represent size.
2018-09-12 04:49:11 -04:00
Lioncash 1242c1ec0a service: Migrate global named port map to the KernelCore class
Now that we have a class representing the kernel in some capacity, we
now have a place to put the named port map, so we move it over and get
rid of another piece of global state within the core.
2018-09-02 12:35:30 -04:00
Lioncash 4a587b81b2 core/core: Replace includes with forward declarations where applicable
The follow-up to e2457418da, which
replaces most of the includes in the core header with forward declarations.

This makes it so that if any of the headers the core header was
previously including change, then no one will need to rebuild the bulk
of the core, due to core.h being quite a prevalent inclusion.

This should make turnaround for changes much faster for developers.
2018-08-31 16:30:14 -04:00
Lioncash 0cbcd6ec9a kernel: Eliminate kernel global state
As means to pave the way for getting rid of global state within core,
This eliminates kernel global state by removing all globals. Instead
this introduces a KernelCore class which acts as a kernel instance. This
instance lives in the System class, which keeps its lifetime contained
to the lifetime of the System class.

This also forces the kernel types to actually interact with the main
kernel instance itself instead of having transient kernel state placed
all over several translation units, keeping everything together. It also
has a nice consequence of making dependencies much more explicit.

This also makes our initialization a tad bit more correct. Previously we
were creating a kernel process before the actual kernel was initialized,
which doesn't really make much sense.

The KernelCore class itself follows the PImpl idiom, which allows
keeping all the implementation details sealed away from everything else,
which forces the use of the exposed API and allows us to avoid any
unnecessary inclusions within the main kernel header.
2018-08-28 22:31:51 -04:00
Lioncash e81354ae38 svc: Return process title ID if queried in GetInfo()
We already have the variable itself set up to perform this task, so we
can just return its value from the currently executing process instead
of always stubbing it to zero.
2018-08-25 05:02:28 -04:00
Lioncash 25d71454d1 kernel/svc: Log svcBreak parameters
Given if we hit here all is lost, we should probably be logging the
break reason code and associated information to distinguish between the
causes.
2018-08-14 20:54:05 -04:00
bunnei fecffeb0dd
Merge pull request #1043 from Subv/timing
Use an approximated amortized amount of ticks when advancing timing.
2018-08-12 22:31:55 -04:00
Subv a9877c8f65 Kernel/SVC: Don't reschedule the current core when creating a new thread.
The current core may have nothing to do with the core where the new thread was scheduled to run. In case it's the same core, then the following PrepareReshedule call will take care of that.
2018-08-12 20:38:37 -05:00
Subv 5224cc49c4 Kernel/Mutex: Don't duplicate threads in the mutex waiter list.
Exit from AddMutexWaiter early if the thread is already waiting for a mutex owned by the owner thread.

This accounts for the possibility of a thread that is waiting on a condition variable being awakened twice in a row.

Also added more validation asserts.

This should fix one of the random crashes in Breath Of The Wild.
2018-08-12 16:35:27 -05:00
Lioncash c4e0c3d76c kernel/vm_manager: Use const where applicable
Makes our immutable state explicit.
2018-08-02 12:21:46 -04:00
bunnei ff2c1b0a94
Merge pull request #877 from lioncash/remove
kernel: Remove unused object_address_table.cpp/.h
2018-07-31 20:11:39 -07:00
Lioncash 369f6e58aa kernel: Remove unused object_address_table.cpp/.h
These source files were entirely unused throughout the rest of the
codebase. This also has the benefit of getting rid of a global variable
as well.
2018-07-31 11:03:08 -04:00
Lioncash a2304fad16 kernel: Remove unnecessary includes
Removes unnecessary direct dependencies in some headers and also gets
rid of indirect dependencies that were being relied on to be included.
2018-07-31 10:15:17 -04:00
Mat M d3fd0351a7
Merge pull request #804 from lioncash/log
svc: Log parameters in SetMemoryAttribute()
2018-07-25 14:43:24 -04:00
Lioncash c73410bf2c svc: Resolve sign comparison warnings in WaitSynchronization()
The loop's induction variable was signed, but we were comparing against
an unsigned variable.
2018-07-24 09:55:17 -04:00
Lioncash 8e8e906432 svc: Log parameters in SetMemoryAttribute()
Provides slightly more context than only logging out the address value.
2018-07-24 09:46:46 -04:00
Subv 7841447cf0 Kernel/SVC: Perform atomic accesses in SignalProcessWideKey as per the real kernel. 2018-07-22 12:27:24 -05:00
Lioncash dbfe82773d thread: Convert ThreadStatus into an enum class
Makes the thread status strongly typed, so implicit conversions can't
happen. It also makes it easier to catch mistakes at compile time.
2018-07-19 22:08:56 -04:00
Lioncash b879fb84a2 svc: Correct always true assertion case in SetThreadCoreMask
The reason this would never be true is that ideal_processor is a u8 and
THREADPROCESSORID_DEFAULT is an s32. In this case, it boils down to how
arithmetic conversions are performed before performing the comparison.

If an unsigned value has a lesser conversion rank (aka smaller size)
than the signed type being compared, then the unsigned value is promoted
to the signed value (i.e. u8 -> s32 happens before the comparison). No
sign-extension occurs here either.

An alternative phrasing:

Say we have a variable named core and it's given a value of -2.

u8 core = -2;

This becomes 254 due to the lack of sign. During integral promotion to
the signed type, this still remains as 254, and therefore the condition
will always be true, because no matter what value the u8 is given it
will never be -2 in terms of 32 bits.

Now, if one type was a s32 and one was a u32, this would be entirely
different, since they have the same bit width (and the signed type would
be converted to unsigned instead of the other way around) but would
still have its representation preserved in terms of bits, allowing the
comparison to be false in some cases, as opposed to being true all the
time.

---

We also get rid of two signed/unsigned comparison warnings while we're
at it.
2018-07-19 15:46:17 -04:00
James Rowe 0d46f0df12 Update clang format 2018-07-02 21:45:47 -04:00
James Rowe 638956aa81 Rename logging macro back to LOG_* 2018-07-02 21:45:47 -04:00
Michael Scire 067ac434ba Kernel/Arbiters: Fix casts, cleanup comments/magic numbers 2018-06-22 00:47:59 -06:00
Michael Scire 5f8aa02584 Add additional missing format. 2018-06-21 21:09:51 -06:00
Michael Scire 8f8fe62a19 Kernel/Arbiters: Initialize arb_wait_address in thread struct. 2018-06-21 05:13:06 -06:00
Michael Scire 4f81bc4e1b Kernel/Arbiters: Mostly implement SignalToAddress 2018-06-21 04:10:11 -06:00
Michael Scire 7e191dccc1 Kernel/Arbiters: Add stubs for 4.x SignalToAddress/WaitForAddres SVCs. 2018-06-21 00:49:43 -06:00
Subv a3d82ef5d9 Build: Fixed some MSVC warnings in various parts of the code. 2018-06-20 11:39:10 -05:00
bunnei 4ac4b308e4
Merge pull request #572 from Armada651/user-except-stub
svc: Add a stub for UserExceptionContextAddr.
2018-06-18 11:37:13 -04:00