41 Commits
Author SHA1 Message Date
Huo YaoyuanandJan Kotas 8cc7586135 Convert fast path of ValueType.GetHashCode to managed (#97590)
* Access CanCompareBits from MethodTableAuxiliaryData

* Switch to QCall

* Fast path of GetHashCode

* Call for RegularGetValueTypeHashCode

* Cleanup unused FCall

* Use HashCode type

* Handle recursive case inside native code

* Remove Double and Single from CoreLibBinder

* Apply suggestions from code review

Co-authored-by: Jan Kotas <jkotas@microsoft.com>

---------

Co-authored-by: Jan Kotas <jkotas@microsoft.com>
2024-02-20 20:22:35 -08:00
50371d39b2 Remove HELPER_METHOD_FRAMEs from built-in marshalers (#97432)
* Remove HELPER_METHOD_FRAME from MngdNativeArrayMarshaler

* Mechanically convert the fixed array marshaller to QCalls.

* Move MngdFixedArrayMarshaler.ConvertSpaceToNative to managed code.

* Move the ICustomMarshaler-based marshalling to be written primarily in managed code instead of FCALLs

* Convert SafeArray marshaller to QCalls

* PR feedback and move CreateMarshaler implementations to manged code for marshalers that already have the state type defined in managed code.

* Remove some unused parameters, make some test failures more diagnosable, fix test failures.

* Instead of passing around an IntPtr to the helper, just pass around the custom marshaler object itself.

* Swallow exceptions from CleanUpNativeData like how the old implementation used to.

* Fix two edge cases.

* Fix null ref check

* Use `in` in more cases to make things clearer

* Don't call CleanUpManagedData for null managed values

* One more case I missed

* Apply suggestions from code review

Co-authored-by: Aaron Robinson <arobins@microsoft.com>

* PR feedback

* Apply suggestions from code review

Co-authored-by: Jan Kotas <jkotas@microsoft.com>

---------

Co-authored-by: Aaron Robinson <arobins@microsoft.com>
Co-authored-by: Jan Kotas <jkotas@microsoft.com>
2024-02-08 19:02:56 -08:00
Mike MarynowskiandJan Kotas 9f3a439bbe Improved uninitialized object creation performance (#98016)
* Improved uninitialized object creation performance

* Remove duplicate GenericCache getter call, revert to direct throw

Co-authored-by: Jan Kotas <jkotas@microsoft.com>

---------

Co-authored-by: Jan Kotas <jkotas@microsoft.com>
2024-02-08 05:23:24 -08:00
Huo YaoyuanandAaron Robinson ca703a199f Convert Array.CopySlow to managed (#97202)
* Body of CopySlow and setup QCall for CanAssignArrayType

* UnBoxEachElement

* BoxEachElement

* CastCheckEachElement

* Move Unbox_Nullable to RuntimeHelpers
---------

Co-authored-by: Aaron Robinson <arobins@microsoft.com>
2024-01-26 11:26:25 -08:00
Aaron Robinson cd7e4cacce Remove more helper frames by converting methods to QCalls (#96926)
* Remove FCall in interop code

* Convert DisableComObjectEagerCleanup to QCall.

* Convert the following to QCalls.
Thread.SleepWorker
Thread.GetIsBackground
Thread.SetIsBackground
Thread.Interrupt

* Feedback
2024-01-15 21:56:16 -08:00
Aaron RobinsonandJan Kotas 22ba7d607b Remove helperframe marshal (#96860)
* Remove HelperMethodFrames from Marshal APIs

Convert Marshal.GetHRForException and Marshal.GetExceptionForHRInternal to QCalls.

* Convert OffsetOfHelper to QCall

* Feedback

* Remove GC transition.

* Update src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs

* Update src/coreclr/vm/marshalnative.cpp

---------

Co-authored-by: Jan Kotas <jkotas@microsoft.com>
2024-01-11 20:41:50 -08:00
Jan KotasandAaron Robinson 23258f52b9 Convert HELPER_METHOD_FRAME to QCalls (5/N) (#96526)
* Assembly.GetManifestResourceNames, GetReferencedAssemblies

* AssemblyLoadContext.GetLoadedAssemblies

* RuntimeModule.GetTypes

* Delegate.BindToMethodName

* Delegate.BindToMethodInfo

* Delegate.GetCallStub, Delegate.AdjustTarget

* Delegate.InternalAlloc, InternalAllocAlike

* Delegate,FindMethodHandle, InternalEqualMethodHandles

* GC.GetTotalAllocatedBytes

* GC.WaitForFullGCApproach, WaitForFullGCComplete

* Update src/coreclr/vm/commodule.cpp

Co-authored-by: Aaron Robinson <arobins@microsoft.com>

* Apply suggestions from code review

* CR feedback, cleanup

- Delete dead code
- Move data first in RuntimeModule.cs

---------

Co-authored-by: Aaron Robinson <arobins@microsoft.com>
2024-01-06 10:16:24 -08:00
Jan Vorlicek 955604c662 New exception handling diagnostic fixes (#96065)
* New exception handling diagnostic fixes

This change
* Adds debugger and profiler events in the right places and order
* Adds debugger exception interception implementation
* Ensures that the new managed exceptino handling frames are not visible
  to the debugger stack trace
* Fixes some missing frames on stack traces (coming from
  HelperMethodFrame)
* Moves first chance exception handling to the native code. It is
  necessary to ensure that the exception stack trace contains frames
  from the explicit frames that have MethodDesc at the time the event
  fires.
* Makes some refactoring around the ExInfo - the CONTEXT and REGDISPLAY
  are now in the ExInfo, the ExInfo contains the original exception pointers.
* Fixes one case when an UnhandledException at the boundary of managed
  and native code was not handled correctly.
* Changes the way an unhandled exception in exception filter is
  swallowed. The stack frame iterator was having issues with the fact
  that the exception "leaked" from the actual filter and was caught by
  another filter in the managed EH. Now the exception is always
  swallowed at the filter.

* Fix bad merge

* Fix win x86 build break

* Reflect PR feedback

* Fix Watson not being triggered on unhandled exception

* Modify the unhandled exception processing

Slight modification of the code enables second pass for unhandled
exceptions. That makes finallys get called the same way as without the
new exception handling.

* Fix accidental edit
2023-12-23 17:30:05 +01:00
Jan Kotas 6dc10870f5 Convert HELPER_METHOD_FRAME to QCalls (4/N) (#95670)
* StubHelpers.FmtClassUpdateNativeInternal, FmtClassUpdateCLRInternal,
LayoutDestroyNativeInternal

* Delegate.GetDelegateForFunctionPointerInternal,
GetFunctionPointerForDelegateInternal

* String.Intern, IsInterned

* StubHelpers.ThrowInteropParamException

* SetStringTrailByte

* Delete dead code

* ArgIterator.Init, Init2, GetNextArgType, GetNextArg, GetNextArg2, GetRemainingCount

* FB
2023-12-07 18:43:31 -08:00
Jan Kotas 8530ac7f7d Convert HELPER_METHOD_FRAME to QCalls (3/N) (#95306)
* InterfaceMarshaler.ConvertToManaged,ConvertToNative

* Fix handling of unmanaged CALLI in StubHelpers by the JIT

The free pass for CALLI inlining in IL stubs should not apply to inlined StubHelpers. The inlined StubHelpers need to pass inlining legality checks.
2023-11-30 08:19:28 -08:00
Jan KotasandAaron Robinson 8105b6714a Convert HELPER_METHOD_FRAME to QCalls (2/N) (#95233)
* GetObjectValue

* Monitor - Wait, Pulse, PulseAll

* CreateCustomMarshalerHelper

* DependentHandle - InternalInitialize, InternalFree

* GCHandle - InternalAlloc, InternalFree

* Marshal.SizeOfHelper

* Marshal.StructureToPtr

* Delete redundant NativeDecimal, NativeVariant

* PtrToStructureHelper, DestroyStructure

* ObjectMarshaler.ConvertToNative,ConvertToManager,ClearNative

* Fix build breaks

* Fix test failures

* Update src/coreclr/vm/stubhelpers.cpp

Co-authored-by: Aaron Robinson <arobins@microsoft.com>

* CR feedback

---------

Co-authored-by: Aaron Robinson <arobins@microsoft.com>
2023-11-27 16:37:29 -08:00
Jan Kotas d20b96d234 Convert S.R.InteropServices.Marshal COM-related FCalls to QCalls (#95038)
* Marshal.ChangeWrapperHandleStrength(object

* GetStartComSlot, GetEndComSlot

* GetNativeVariantForObject, GetObjectForNativeVariant,
GetObjectsForNativeVariants

* IsTypeVisibleFromCom

* InternalCreateWrapperOfType

* ReleaseComObject, FinalReleaseComObject

* CreateAggregatedObject

* CleanupUnusedObjectsInCurrentContext

* GetTypedObjectForIUnknown

* GetObjectForIUnknown, GetUniqueObjectForIUnknown

* GetComInterfaceForObject

* GetIUnknownForObject, GetIDispatchForObject

* Update tests
2023-11-21 07:55:08 -08:00
115199da04 [API Proposal]: Create array from array type (#88620)
* Create array from array type

* InternalCreateFromArrayType

* code review:

- add missing comments for new public APIs
- use the new API in DataTypeImplementation (and solve a TODO)
- fix typo
- remove code that was commented out
- improve test name

* Fix perf and corner-case behaviors

* Delete superfluous validation

* Skip handling of void arrays for this PR

---------

Co-authored-by: Adam Sitnik <adam.sitnik@gmail.com>
Co-authored-by: Jan Kotas <jkotas@microsoft.com>
2023-11-16 11:18:01 -08:00
Koundinya Veluri a2818c5728 Include info about system call errors in some exceptions from operating on named mutexes (#92603)
* Include info about system call errors in some exceptions from operating on named mutexes

- Added new PAL APIs for creating and opening mutexes that take a string buffer for system call error info. These are called with a stack-allocated buffer and upon error the system call errors are appended to the exception message.
- When there is a system call failure that leads to the PAL API failing, some info is appended to the error string, including the system call, relevant arguments, return value, and `errno`
- `chmod` on OSX seemingly can be interrupted by signals, fixed to retry. Also fixed a couple other small things.

Fixes https://github.com/dotnet/runtime/issues/89090
2023-09-30 00:14:34 -07:00
Jan Kotas 93cd68fbef Convert SpinWait to QCall (#92675) 2023-09-26 19:18:48 -07:00
Jan Vorlicek f8d9b3cf5b Port NativeAOT exception handling to CoreCLR (#88034)
* Port NativeAOT exception handling to CoreCLR

This change ports NativeAOT exception handling to CoreCLR, resulting in
3.5..4 times speedup in exception handling. Due to time constraints and
various complexities, thread abort and debugger support is not
completed yet, so this change is enabled only when
`DOTNET_EnableNewExceptionHandling` env variable is set. By default,
the old way is used.
This change supports all OSes and targets we support except of x86
Windows. That may be doable too in the future, but the difference in
exception handling on x86 Windows adds quite a lot of complexity into
the picture.

Notes for the PR:
* I have left the `ExceptionHandling.cs` and `StackFrameIterator.cs` in
  the nativeaot folder to simplify the review. I can move it to some
  common location after the change is reviewed. Also it was not clear to
  me where that should be, so advise would be welcome here.
* Naming of the native helpers like `RhpCallCatchFunclet` was left the
  same as in the NativeAOT for now.
* There are still some little things I'd like to eventually clean up,
  like `ExInfo` encapsulation and possibly moving `REGDISPLAY` and
  `CONTEXT` it uses into the `ExInfo` itself or moving debug members of
  `StackFrameIterator` and `REGDISPLAY` to the end of those structures
  so that the `AsmOffsets.cs` can be simplified. It also may be possible
  to unify the exception handling callback that's used for ObjectiveC to
  use the managed version. I've tried and there were some ugly
  complications, so I've left it separated.
* There are two bug fixes for bugs unrelated to this PR and a removal of
  unused parameter in existing code that could be made as separate PRs
  before this PR.
  * `ProfilerEnter` and `ProfilerLeave` for the case of
    `UnmanagedCallersOnly` method were being called in preemptive mode.
  * NativeAOT code for rethrowing exception was incorrectly calling
    `DispatchEx` with last argument set to `activeExInfo._idxCurClause`
    to start at the last clause processed when the rethrown exception
    was originally thrown instead of starting from the first one again.
    I have a accidentally came with a simple test that discovered this
    bug and causes failures in  the original NativeAOT too.
* Changes in  the stackwalk.cpp add support for
  * Usage of `ExInfo` instead of `ExceptionTracker`
  * Handling of case when GC runs while finally funclet is on the stack
    and then again when the code is back in the new exception handling
    code in managed code before other finally or catch funclet is
    called. The NativeAOT solves that by disabling GC for the 2nd pass
    of EH, for this change it would not be reasonable.
  * Handling the GC reporting when funclet is found while walking the
    stack. It needs to scan frames of the managed code that handles the
    exception too,  since it contains live references. The old EH way
    doesn't have this case.
* I needed to add `GCFrame::Remove` method that can remove the `GCFrame`
  from any location in the chain. There is a managed runtime method that
  calls `GCReporting::Unregister` that was popping it with my changes
  out of order due to the exception handling code being managed.

Fix context initialization after rebase

* Remove Rhp prefix from the native helpers

* Fix handling of exceptions from JIT

The `UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE` in the
`EE_TO_JIT_TRANSITION` needs to rethrow an exception (if any) using native
exception handling mechanism instead of calling the new managed
exception handling, as the native exception needs to propagate through
some native code layers from there.
This change adds parameter to the
`UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE` macro to select whether
to rethrow the exception as native or to invoke the new managed
exception handling.

This problem didn't show up until I ran the coreclr tests with tiered
compilation disabled.

* Update UNINSTALL_UNWIND_AND_CONTINUE_HANDLER usage

There were three places where the UNINSTALL_UNWIND_AND_CONTINUE_HANDLER
needed to be replaced by
UNINSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE(true).

* Rename INSTALL_UNWIND_AND_CONTINUE_HANDLER_NO_PROBE

To INSTALL_UNWIND_AND_CONTINUE_HANDLER_EX, as the old name is obsolete
2023-08-24 22:50:20 +02:00
Andrew Au 0dd733eeba Gen0 Budget counter (#89412) 2023-07-28 10:12:12 -07:00
Koundinya Veluri 4302b80fa0 Add managed entry points for raising Contention events (#87087)
* Add managed entry points for raising Contention events

- Added the events similarly to how the PortableThreadPool events are currently set up. They may need further tweaking to make them work from NativeAOT.
- The events are not raised anywhere from the managed side yet, it's expected that they will eventually be raised by a new Lock type and at least by NativeAOT's Lock
2023-06-15 06:36:33 -07:00
Andrew AuandJan Kotas 6a02ab256b NoGCRegion Callback (#82045)
Co-authored-by: Jan Kotas <jkotas@microsoft.com>
2023-05-20 18:46:51 -07:00
Andrew Au bb858125e9 Private API for RefreshMemoryLimit (#83707) 2023-04-18 21:18:46 -07:00
Jan Kotas 79d0d7cbfa Delete unmanaged type name parser from CoreCLR (#84159)
* Delete unmanaged type name parser from CoreCLR

* Improve naming and comments
2023-03-31 14:30:34 -07:00
Jan KotasandAaron Robinson 91b93eb22b Unify managed runtime type name parsers (#83484)
Contributes to #72833 and #77868

The performance effect of this change on typical use of `Type.GetType` like `Type.GetType("MyType, MyAssembly")` is in the noise range. The typical use of `Type.GetType` spends most of the time in assembly loader and type loader. The time spent by parsing the type name is small fraction of the total and the performance improvement is hardly noticeable.

When the type name parser performance is measured in isolation, it is several times faster compared to the existing unmanaged CoreCLR type name parser. For example:
```
Type.GetType("System.Object, System.Private.CoreLib",
       assemblyResolver: (an) => typeof(object).Assembly,
       typeResolver: (assembly, name, ignoreCase) => typeof(object));
```
is about 3x faster with this change on CoreCLR.

Co-authored-by: Aaron Robinson <arobins@microsoft.com>
2023-03-24 20:46:49 -07:00
Aaron Robinson 5a45085c15 Remove fragile NGen logic for precomputed hashcodes (#82563)
* Remove fragile NGen logic for precomputed hashcodes

Hashing was confirmed to offer minor performance wins
but not with lazy hash code generation. Pre hashing was needed
to have a benefit on start-up but even then it was minor.
2023-03-08 21:48:42 -05:00
Aaron RobinsonandJeremy Koritzinsky 665570877c Implement new ComWrappers APIs (#80402)
* Add TryGetComInstance and TryGetObject APIs

The ComWrappers API is being expanded to enable
users to get the underlying managed or unmanaged
object from the created wrappers.

* Add tagged interface for certainty in identifying
a wrapper is a ComWrappers impl.

Co-authored-by: Jeremy Koritzinsky <jkoritzinsky@gmail.com>
2023-01-20 10:52:37 -08:00
Vladimir Sadov d2dfabf45d Moving GetCurrentProcessorId() to shared (#80532)
* move GetCurrentProcessorId() to shared

* delete more native code

* PR feedback

* fix unix build

* unnecessary HAVE_SCHED_GETCPU
2023-01-12 16:25:57 -08:00