未验证 提交 15cb3732 编写于 作者: R Robin Lindner 提交者: GitHub

[API Implementation]: SafeFileHandle overloads for SetCreationTime,...

[API Implementation]: SafeFileHandle overloads for SetCreationTime, SetLastAccessTime, SetLastWriteTime (#60507)

* Implement proposal

* Undo auto-reformat

* Add ref

* Fix Parameter Naming in FileSystem.Unix.cs

* Partial test implementation

* Fix typo

* Fix parameter naming

* Naming fix and remove unnessecary method

* Add more test cases

* Implement usage of Kernel32 Method GetFileInformationByHandle and struct BY_HANDLE_FILE_INFORMATION

* Fix Test SetLastWriteTimeTicks_SafeFileHandle

* Disable SafeFileHandle specific-tests on other platforms than Windows

* Add Common reference to project file of System.IO.AccessControl

* fix

* Add preprocessor variable check

* Add check for preprocessor var

* Fix CS0649

* Remove preprozessor variable checks

* Fix tab/spaces conflict in Interop.BY_HANDLE_FILE_INFORMATION

* Fix misplaced StructLayoutAttribute

* Fix project file identation

* Remove preprocessor variable checks for GetSetAttributes test

* Use ThrowHelper instead of direct throwing

* Use ThrowHelper instead of direct throwing

* Add null-forgiving operator to fix build-failures

* Fix build failures

* Win32 interop improvements

* Specify FileAccess in File.OpenHandle calls for testing purposes

* Implement GetLastWin32Error proposal / @Jozkee
Co-authored-by: NDavid Cantú <dacantu@microsoft.com>

* Fix build

* Usage of kernel32.dll!SetFileInformationByHandle in FileSystem.SetFileTime

* Usage of access parameter in GetSetTimes tests

* Remove auto-generated trash

* Add localization string to NativeAOT Strings.resx

* Unix Implementation of GetAttributes, SetAttributes, GetCreationTime, GetLastAccessTime and GetLastWriteTime

* Unix Implementation SetLastAccessTime and SetLastWriteTime

* Add error handling to FChMod call

* Revert "Unix Implementation SetLastAccessTime and SetLastWriteTime"

This reverts commit bce7faadb52bf308e6258864d464334448a4bda3.

* Unix Implementation SetLastAccessTime and SetLastWriteTime

* Move SafeHandle implementation to FileStatus.

* `SafeFileHandle` `FileStatus` (#4)

* [RateLimiting] Dequeue items when queuing with NewestFirst (#63377)

* Don't reuse registers in Debug mode (#63698)
Co-authored-by: NBruce Forstall <brucefo@microsoft.com>

* Add IsKnownConstant jit helper and optimize 'str == ""' with str.StartsWith('c') (#63734)
Co-authored-by: NMiha Zupan <mihazupan.zupan1@gmail.com>
Co-authored-by: NSingleAccretion <62474226+SingleAccretion@users.noreply.github.com>

* - mono_wasm_new_external_root for roots on stack (#63997)

- temp_malloc helper via linear buffer in js
- small refactorings
Co-authored-by: NKatelyn Gadd <kg@luminance.org>

* [Arm64] Don't use D-copies in CopyBlock (#63588)

* Increase the maximum number of internal registers allowd per node in src/coreclr/jit/lsra.h

* Based on discussion in https://github.com/dotnet/runtime/issues/63453 don't allocate a SIMD register pair if the JIT won't be able to use Q-copies in src/coreclr/jit/lsraarmarch.cpp

* Update CodeGen to reflect that Q-copies should be used only when size >= 2 * FP_REGSIZE_BYTES and using of them makes the instruction sequence shorter in src/coreclr/jit/codegenarmarch.cpp

* Update comment - we don't use D-copies after that change in src/coreclr/jit/codegenarmarch.cpp

* Disable hot reload tests for AOT configurations (#64006)

* Bump Explicit-layout value types with no fields to at minimum 1 byte size. (#63975)

* Add runtime-extra-platforms pipeline to have matching runtime PR and Rolling builds (#62564)

* Add runtime-extended-platforms pipeline to have matching runtime PR and Rolling builds

* Fix evaluate changed paths condition for the extra pipeline

* PR Feedback and fix condition

* Move MacCatalyst back to staging, disable tvOS tests

* Disable browser wasm windows legs

* Make ILStubGenerated event log ModuleID corresponding to that on other events (#63974)

* Retries for flaky WMI test (#64008)

* [arm64] JIT: Redundant zero/sign extensions after ldrX/ldrsX (#62630)

* JIT: fix up switch map for out-of-loop predecessor (#64014)

If we have a loop where some of the non-loop predecessors are switchs, and
we add pre-header to the loop, we need to update the switch map for those
predecessors.

Fixes #63982.

* Update StructMarshalling design now that DisableRuntimeMarshallingAttribute is approved (#63765)
Co-authored-by: NElinor Fung <elfung@microsoft.com>

* Fix Crossgen2 bug #61104 and add regression test (#63956)

The issue tracks the runtime regression failure where
Crossgen2-compiled app is unable to locate a type with non-ASCII
characters in its name. The failure was caused by the fact that
Crossgen2 was incorrectly zero-extending the individual UTF8 characters
when calculating the hash whereas runtime is sign-extending them.

Thanks

Tomas

* Fix invalid threading of nodes in rationalization (#64012)

The code in question assumes that the ASG will be
reversed and thus threads "simdTree" before "location"
in the linear order. That dependency, while valid,
because "gtSetEvalOrder" will always reverse ASGs
with locals on the LHS, is unnecessary and incorrect
from the IR validity point of view.

Fix this by using "InsertAfter" instead of manual
node threading.

* Check if the child object is in the heap range before get_region_plan_gen_num (#63828)

* Check if the child object is in the heap range before object_gennum (#63970)

* 'cmeq' and 'fcmeq' Vector64<T>.Zero/Vector128<T>.Zero ARM64 containment optimizations (#62933)

* Initial work

* Added a comma to display

* Cleanup

* Fixing build

* More cleanup

* Update comment

* Update comment

* Added CompareEqual Vector64/128 with Zero tests

* Do not contain op1 for now

* Wrong intrinsic id used

* Removing generated tests

* Removing generated tests

* Added CompareEqual tests

* Supporting containment for first operand

* Fix test build

* Passing correct register

* Check IsVectorZero before not allocing a register

* Update comment

* Fixing test

* Minor format change

* Fixed formatting

* Renamed test

* Adding AdvSimd_Arm64 tests:

* Adding support for rest of 'cmeq' and 'fcmeq' instructions

* Removing github csproj

* Minor test fix

* Fixed tests

* Fix print

* Minor format change

* Fixing test

* Added some emitter tests

* Feedback

* Update emitarm64.cpp

* Feedback

* [Arm64] Keep unrolling InitBlock and CopyBlock up to 128 bytes (#63422)

* Add INITBLK_LCL_UNROLL_LIMIT and CPBLK_LCL_UNROLL_LIMIT of 128 bytes in src/coreclr/jit/targetarm64.h

* Keep unrolling InitBlock up to INITBLK_LCL_UNROLL_LIMIT bytes when dstAddr points to the stack in src/coreclr/jit/lowerarmarch.cpp

* Keep unrolling CopyBlock up to CPBLK_LCL_UNROLL_LIMIT bytes when both srcAddr and dstAddr point to the stack in src/coreclr/jit/lowerarmarch.cpp

* Add ProcessLinkerXmlBase to NativeAOT (#63666)

Add Xml Parsing linker files as a reference source to NativeAOT
Rename NativeAOT ProcessLinkerXmlBase version to ProcessXmlBase (uses XmlReader) 
Add ProcessLinkerXmlBase from linker and fix it so it can be used in NativeAOT (uses XPath)

* Fix gc_heap::remove_ro_segment (#63473)

* Fix OpenSSL version check in GetAlpnSupport

The previous check failed 3.0.0 because the Minor was 0 and Build was 0.

It could probably be rewritten to be `>= new Version(1, 0, 2)`, but that'd require more thinking.

* Fix issues with verify_regions, clear_batch_mark_array_bits. (#63798)

Details:
- we cannot verify the tail of the region list from background GC, as it may be updated by threads allocating.
- fix case in clear_batch_mark_array_bits where end is equal to the very end of a segment and we write into uncommitted memory in the mark_array.
-  bgc_clear_batch_mark_array_bits did some checks and then called clear_batch_mark_array_bits which repeated the exact same checks. Renamed clear_batch_mark_array_bits to bgc_batch_mark_array_bits and removed the old copy, removed the declaration for clear_batch_mark_array_bits.

* [debugger][wasm] Added support for non user code attribute (#63876)

* Hidden methods and step through methods behave the same way.

* Perpared flow for setting JustMyCode in the future.

* Tests for JustMyCode setting before debug launch.

* Transformed into dynamic JustMyCode change flow.

* JustMyCode disabled, first 3 cases solved.

* Finished behavior for JMC disabled (with 1 difference).

* JMC enabled: stepIn np bp + stepIn bp + resume bp.

* Functional version (with minor deviations from expected behavior).

* Refactoring.

* All tests for NonUserCode work.

* Fix line number after adding code above.

* Fix error in merge.

* Removing duplicated tests.

* [wasm][debugger] Added support for stepper boundary attribute (#63991)

* Hidden methods and step through methods behave the same way.

* Perpared flow for setting JustMyCode in the future.

* Tests for JustMyCode setting before debug launch.

* Transformed into dynamic JustMyCode change flow.

* JustMyCode disabled, first 3 cases solved.

* Finished behavior for JMC disabled (with 1 difference).

* JMC enabled: stepIn np bp + stepIn bp + resume bp.

* Functional version (with minor deviations from expected behavior).

* Refactoring.

* All tests for NonUserCode work.

* Fix line number after adding code above.

* Stepper boundary with tests.

* Save information about multiple decorators.

* Fix error in merge.

* Polish the PR build doc (#64036)

* [wasm] WebSocket tests on NodeJS (#63441)

- NPM package with WS.
- Restore npm during build.
- Load npm modules in test-main.js.
Co-authored-by: NPavel Savara <pavel.savara@gmail.com>

* Fix dependency in runtime-official.yml (#64040)

After https://github.com/dotnet/runtime/pull/62564 the `hostedOs` value is included in the job name.

* [API Implementation]: System.Diagnostics.CodeAnalysis.StringSyntaxAttribute (#62995)

* Add StringSyntaxAttribute

* Fix attribute declaration and add usage

* Address PR feedback
Co-authored-by: NStephen Toub <stoub@microsoft.com>

* Reduce the memory footprint of HttpHeaders (#62981)

* Change HttpHeaders backing store to an array

* Reduce the size of HeaderDescriptor to 1 object

* Update UnitTests, fix GetOrCreateHeaderInfo

* Switch to a dictionary after ArrayThreshold headers

* Add unit tests

* Use storeValueRef naming consistently

* Workaround field layout regression (#63005)

* Mark _descriptor on HeaderDescriptor as nullable

* Remove HeaderDescriptor.Descriptor and add HasValue, IsKnownHeader, Equals

* Simplify HttpHeaderParser.Separator logic

* Add comments on HasValue checks

* Lazily group headers by name

* Add a header ordering+grouping test

* Make use of the _count field

* Revert all HeaderDescriptor changes from PR

* Switch back to always grouping by name

* Assert that the collection is not empty in GetEnumeratorCore

* Optimize AddHeaders for empty collections

* Reference the Roslyn bug issue

* Assert that multiValues are never empty

* Don't preserve a Dictionary across Clear

* Add comment about why a custom HeaderEntry type is used

* Disable DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsException (#64044)

* Add test coverage for frozen objects and GC interaction (#64030)

* Test coverage for frozen objects and GC interaction

* Update Preinitialization.cs

* Remove Type.MakeGenericType dependency from source generation (#64004)

* Remove Type.MakeGenericType dependency from srcgen

* address feedback

* add trimmer warning suppression

* address feedback

* Add ns2.0 support to System.Formats.Cbor (#62872)

* Add ns2.0 support to System.Formats.Cbor

* Add NetFrameworkMinimum to tfms

* Add ReadHalf and WriteHalf to compatibility suppressions

* Remove unwanted comment

* Exception sets: debug checker & fixes (#63539)

* Add a simple exception sets checker

* Add asserts to catch missing nodes

* Fix normal VN printing

* Fix JTRUE VNs

* Fix PHI VNs

* Update VNs for "this" ARGPLACE node

* Tolerate missing VNs on PHI_ARGs

We do not update them after numbering the loops.

(Though perhaps we should)

* Tolerate unreachable blocks

* Fix exception sets for VNF_PtrTo VNFuncs

* Add VNUniqueWithExc

* Add VNPUniqueWithExc

* Fix arrays

* Consistently give location nodes VNForVoid

And always add exception sets for them.
This will simplify the exception set
propagation code for assignments.

* Fix CSE

* Fix GT_RETURN

* Fix LCLHEAP

* Fix GT_ARR_ELEM

* Fix unique HWI

* Fix unique SIMD

* Fix GT_SWITCH

* Fix CKFINITE

* Fix HWI loads

* Fix fgValueNumberAddExceptionSetForIndirection

The method does not need to add the exception set for
the base address. Additionally, the way it did add the
sets, by unioning with normal value numbers, lost all
exceptions not coming from the base address.

This was fine for the unary loads, but broke the HWI loads
that could have exceptions coming from not just the address.

* Fix GT_RETFILT

* Fix INIT_VAL

* Fix DYN_BLK

* Fix FIELD_LIST

* De-pessimize CkFinite

* Add a test for HWIs

* Add a test for LCLHEAP

* Change test to check for store block operators (#60878)

* Update XUnit to 2.4.2-pre.22 (#63948)

* Update to Xunit build 2.4.2-pre.13

Also pick up latest pre-release of analyzers

* Disambiguate calls to Assert.Equals(double,double,int)

Xunit added a new Assert overload that caused a lot of ambiguous calls.
https://github.com/xunit/xunit/issues/2393

Workaround by casting to double.

* Fix new instances of xUnit2000 diagnostic

* Workaround xUnit2002 issue with implicit cast

Works around https://github.com/xunit/xunit/issues/2395

* Disable xUnit2014 diagnostic

This diagnostic forces the use of Assert.ThrowsAsync for any async method,
however in our case we may want to test that a method will throw
synchronously to avoid regressing that behavior by moving to the async
portion of the method.

* Use AssertExtensions to test for null ArgumentException.ParamName

Workaround https://github.com/xunit/xunit/issues/2396

* Update to Xunit 2.4.2-pre.22

* Fix another ArugmentException.ParamName == null assert

* Preserve OBJ/BLK on the RHS of ASG (#63268)

One of my upcoming changes will need this information to
accurately detect type mismatch in "fgValueNumberBlockAssignment".

* Revert "Temporarily disable coredumps during library testing on macOS (#63742)" (#64057)

This reverts commit 2c28e63f.

Fixes #63761

* Performance: Fix Browser Wasm job not being found for dependent jobs (#64058)

* Figure out the name that browser wasm now uses.

*  linux to the Browser wasm depends on name.

Update the browser wasm dependson name to match the new one found in the pipeline.

* Fix exception propagation over HW exception frame on macOS arm64 (#63596)

* Fix exception propagation over HW exception frame on macOS arm64

There is a problem unwinding over the PAL_DispatchExceptionWrapper
to the actual hardware exception location. The unwinder is unable
to get distinct LR and PC in that frame and sets both of them to
the same value. This is caused by the fact that the
PAL_DispatchExceptionWrapper is just an injected fake frame and
there was no real call. Calls always return with LR and PC set
to the same value.

The fix unifies the hardware exception frame unwinding with Linux
where we had problems unwinding over signal handler trampoline, so
PAL_VirtualUnwind skips the trampoline and now also the
PAL_DispatchExceptionWrapper frame by copying the context of
the exception as the unwound context.

* Reenable DllImportGenerator.Unit.Tests

* Add StringSyntax attribute to Regex.pattern field (#64063)

I missed adding this one in my initial audit.  It'll be exceedingly rare for a developer to manually write code that assigns a string to this protected field, but every source-generated regex does so, and thus any colorization VS provides will benefit looking at the source-generated code.

* Sync shared code from aspnetcore (#64059)
Co-authored-by: NJamesNK <JamesNK@users.noreply.github.com>

* Read the System.GC.CpuGroup settings in runtimeconfig.json (#64067)

* Log message of unexpected exception in ThrowsAny (#64064)

* Log message of unexpected exception in ThrowsAny

* Update AssertExtensions.cs

* Enable some browser legs on the extra-platforms pipeline (#64065)

* Enable some browser legs on the extra-platforms pipeline

* Flow platform parameter from helix queues templates

* Fix another condition

* Allow CreateScalarUnsafe to be directly contained by hwintrinsics that support scalar loads (#62407)

* Ensure that floating-point constants can be contained by hardware intrinsics

* Allow CreateScalarUnsafe to be directly contained by hwintrinsics that support scalar loads

* Rename IsContainableHWIntrinsicOp to TryGetContainableHWIntrinsicOp and improve handling

* Ensure that NI_AVX2_BroadcastScalarToVector128/256 are properly tracked as MaybeMemoryLoad

* Applying formatting patch

* Ensure a few other "maybe memory" and special memory operand size cases are handled

* Applying formatting patch

* Remove commented code (#63869)

* Add pmi_path argument to superpmi.py script and use it in the superpmi-collect pipeline. (#63983)

* Add -pmi_path argument to superpmi.py collect command and use it to set PMIPATH environment variable in src/coreclr/scripts/superpmi.py

* Set pmi_path to $(SuperPMIDirectory)\crossgen2

* Print a warning if -pmi_path or -pmi_location is specified while --pmi is not in src/coreclr/scripts/superpmi.py

* Move setting of PMIPATH environment variable under `if self.coreclr_args.pmi is True:` in src/coreclr/scripts/superpmi.py

* Move pmi argument validation to setup_args() in src/coreclr/scripts/superpmi.py

* Clone root_env if we are going to set PMIPATH environment variable in src/coreclr/scripts/superpmi.py

* Update the macOS CoreCLR building documentation. (#63932)

This updates the documentation to refer to the up-to-date location of
requirements and prerequisites.

* Introduce RandomAccess.SetLength (#63992)

* don't Flush readonly MemoryMappedViewAccessor on disposal (#63794)

* don't Flush if it's impossible to write

* address code review feedback: apply same optimization to MemoryMappedViewStream

* Implement System.Runtime.CompilerServices.DisabledRuntimeMarshallingAttribute on CoreCLR-family of runtimes/type systems (#63320)

* Add the DisableRuntimeMarshallingAttribute to the build.

* Add initial test suite

* Implement support in IL stubs for the "disabled runtime marshalling" feature.

* Add testing for inlining IL stubs.

* Block SetLastError and LCID support when DisableRuntimeMarshallingAttribute is applied.

* Bump NativeAOT-only R2R version header (missed previously)

* Implement support in crossgen2 and NativeAOT

* Clean up the test tree and update the tests to fail more reliably when bugs are present.

Fix a bug that was uncovered when the tests were refactored.

* Fix NativeAOT and clean up crossgen2

* Add a test for NoPreserveSig with DisableRuntimeMarshalling

* Assign hr in SUCCEEDED macro.

* PR feedback.

* Block varargs in disabled marshalling mode.

* Fix typo

* Block types that have a field that is auto-layout somewhere in their layout.

* Fix typo

* Revert the AutoLayoutOrHasAutoLayoutFIeld check in the "marshalling enabled" case

* Only set scope when it isn't null (it's null for some cases).

* Fix narrowing conversion failure.

* First pass simple implementation in Mono

* Fix assert to still work for the built-in marshalling system

* S_FALSE is a thing

* Fix type load failures caused by eager type handle loading.

* Get MethodILScope from the calling method when available (this covers all cases where we need it)

* Add const modifier.

* Try 2 to fix const modifiers

* Fix compilation of NativeAOT jitinterface

* Fix type lookup in Mono

* Use try_get model for getting the attribute type in the case of failure. Fix mono implementation for looking up the attribute.

* Handle void and generic instantiations

* Update auto-layout check to check recursively in layout.

* Enhance test suite with more tests for UnmanagedCallersOnly, generics, and the like. Fix AutoLayout test.

* Fix IL and a few typos

* Set a value in the padding for easier debugging.

* Create sig->marshalling_disabled to track when marshalling is disabled, which is separate from the concept of "is this signature a P/Invoke"

* Fix running test suite on Mono + Mini JIT

* Fix recursive type load failure by only checking the "has auto-layout or field with auto-layout" for value types.

* Fix mono windows build.

* Feedback from Michal.

* Fix bug in EcmaAssembly.HasAssemblyCustomAttribute

* Make the runtime flavor check in the wrapper generator case-invariant

* Use helper method since various different platforms/configurations throw different exceptions for these scenarios.

* Fix AutoLayout test refactor and use a dummy value for the padding field in both enabled and disabled scenarios.

* Add an explicit test for using enums as they're a little weird and needed some special-casing.

* Fix build-time test filtering in xunit wrapper generator.

* Fix some x86-specific issues

* Add a nice big comment block.

* Fix x86

* Refactor tests so we can skip one on Mono since Char->char lossy conversion is not supported.

* Disable test in issues.targets until an alternative solution is reached.

* Add another SkipOnMono attribute in the "Enabled" test suite.

* Apply UnmangedFunctionPointerAttribute to help hint to the Mono LLVM AOT compiler to compile the managed->native thunks at aot-time

* Unify on "runtime marshalling" terminology

* Clean up unused usings.

* Address Jan's feedback except for applying the attribute to CoreLib.

* PR feedback.

* Mono throws an InvalidProgramException for varargs

* Fix copy-paste issue.

* Make sure we use the P/Invoke's Module and not the caller's module when deciding if runtime marshalling is enabled for a varargs P/Invoke call.

* Handle how LLVM AOT reports the failure to handle varargs (EEE)

* Make ILLink validation steps in libs incrementally buildable (#64041)

* Make ILLink validation steps in libs incrementally buildable

Both the illink-oob and the illink-sharedframework targets don't define Inputs and Outputs which makes them run during no-op incremental builds. This change defines Inputs and Outputs based on what's used during the target's execution so that if the input assemblies or the illink assembly itself haven't changed, the step will be skipped.

Also renaming properties and items to make them more readable and consistent. As these target files are "extensions" of the src.proj file and aren't shared anywhere, they can be treated like logic inside a project file and hence prefixing properties and items with an underscore "_" isn't necessary.

* Fix broken callstacks in interpreter on MonoVM. (#60338)

* Fix some broken callstacks in interpreter.

* Fix build error.

* Initial WASI support prototype (#63890)

* Add StringSyntaxAttribute.Json (#64081)

* [main] Update dependencies from 5 repositories (#64002)
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>
Co-authored-by: NPřemek Vysoký <premek.vysoky@microsoft.com>

* Fix crash when VS4Mac is debugging VS4Mac arm64 (#64085)

Fix crash when VS4Mac is debugging VS4Mac arm64

Issue: https://github.com/dotnet/runtime/issues/64011

* ILVerify: Handle readonly references in ldfld (#64077)

* ILVerify: Handle readonly references in ldfld

Fixes #63953

* Fix test name
Co-authored-by: NMichal Strehovský <MichalStrehovsky@users.noreply.github.com>

* Avoid additional local created for delegate invocations (#63796)

Very often 'this' is already a local and we can avoid creating another
local.

* [wasm][debugger] Apply changes on wasm using sdb protocol. (#63705)

* Apply changes on wasm using sdb protocol.

* conflict

* Merge conflict.

* Fix merge

* Fix compilation error.

* Fixed IsFloatPositiveZero from returning 'true' on non-constant double operands (#64083)

* Fixed IsFloatPositiveZero from returning 'true' on non-constant double operands

* Update src/coreclr/jit/gentree.h
Co-authored-by: NEgor Bogatov <egorbo@gmail.com>
Co-authored-by: NEgor Bogatov <egorbo@gmail.com>

* Ensure several helper intrinsics are correctly imported and handled (#63972)

* Ensure several helper intrinsics are correctly imported and handled

* Ensure that Sum for TYP_INT/UINT on Arm64 is correctly handled

* Respond to PR feedback and ensure ExtractMostSignificantBits for Vector64<int/uint> on Arm64 also uses AddPairwise

* Applying formatting patch

* Ensure the clsHnd is correct

* Fix the remaining musl failures

* Ensure that we aren't sign-extending TYP_BYTE (System.SByte) for ExtractMostSignificantBits

* Ensure an assert is correct on x64

* Ensure Vector64<int/uint>.Dot on Arm64 uses AddPairwise, not AddAcross

* Apply formatting patch

* RegexNode cleanup (#64074)

No functional changes, just code cleanup:
- Move node types into a RegexNodeKind enum
- Rename some of the kinds to make them more descriptive
- Rename node.Next to node.Parent to better describe its purpose
- Add a bunch of comments about node kinds

* Refactor optimizing morph for commutative operations (#63251)

* Create "fgOptimizeCommutativeArithmetic"

And just move code from "fgMorphSmpOp" to it.

Just one diff: better comma throw propagation in an ILGEN method.

* Refactor the function

Split it into specialized variants for each operator,
delete redundant code, fix up one case of wrong typing
for a constant in the MUL -> SHIFT optimization.

One CSE diff due to different VNs because of the typing
change for the constant (int -> long).

Many text diffs: "mov x3, 5" => "mov w3, 5".

* Do not set GTF_NO_CSE for sources of block copies (#63462)

It is not necessary, the compiler fully supports locals
on the RHS of a struct assignment. Not marking these results
in a CQ improvement, from struct (including SIMD) CSEs and
global constant propagation into promoted fields.

* Handle embedded assignments in copy propagation (#63447)

* Clean things up a little

Delete redundant conditions, use "LclVarDsc*", rename locals for clarity.

* Delete a redundant condition

For actual def nodes, GTF_VAR_CAST will never be set, it is
only set in "optNarrowTree" for uses.

For "def nodes" that are actually uses (parameters), the VNs
will never match anyway.

* Handle embedded assignments in copy propagation

Previously, as the comments in copy propagation tell us, it
did not handle "intervening", or not-top-level definitions of
locals, instead opting to maintain a dedicated kill set of them.

This is obviously a CQ problem, but also a TP one, as it meant
there had to be a second pass over the statement's IR, where
the definitions would be pushed on the stack.

This change does away with that, instead pushing new definitions
as they are encountered in execution order, and simultaneously
propagating on uses. Notably, this means the code now needs to
look at the real definition nodes, i. e. ASGs, not the LHS locals,
as those are encountered first in canonical execution order, i. e.
for a tree like:

```
  ASG
    LCL_VAR V00 "def"
    ADD
      LCL_VAR V00
      LCL_VAR V00
```

Were we to use the "def" as the definition point, we would wrongly
push it as the definition on the stack, even as the assignments
itself hasn't happened yet at that point.

There are nice diffs with this change, all resulting from unblocked
propagations, and mostly coming from setup arguments under calls.

* Simplify optIsSsaLocal

* Update format script permissions so it can be called on Unix systems directly. (#64107)

* Revert "Enable System.Text.Json tests on netfx (#63803)" (#64108)

This reverts commit 34794bc5.

* Make ApiCompat.proj incrementally buildable (#64037)

* Make ApiCompat.proj incrementally buildable

In https://github.com/dotnet/runtime/pull/64000, I noticed that ApiCompat.proj never builds incrementally. Even though the RunApiCompat target has Inputs and Outputs, those aren't defined too late inside the target to have any effect. Moving them out and declare the generated response file as an output.

Also simplifying some msbuild logic and renaming some properties as underscore prefixes in project files don't make sense if the property isn't reserved in any way.

* Update ApiCompat.proj

* Remove enable drawing on unix switch (#64084)

* Remove enable drawing on unix switch

* Update some tests and not run tests that need Drawing on non Windows

* PR Feedback, just turn off the switch

* Address-expose locals under complex local addresses in block morphing (#63100)

* Handle complex local addresses in block morphing

In block morphing, "addrSpill" is used when the destination or source
represent indirections of "complex" addresses. Unfortunately, some trees
in the form of "IND(ADDR(LCL))" fall into this category.

If such an "ADDR(LCL)" is used as an "addrSpill", the underlying local
*must* be marked as address-exposed. Block morphing was using a very
simplistic test for when that needs to happen, essentially only recognizing
"ADDR(LCL_VAR/FLD)". But it is possible to have a more complicated pattern
as "PrepareDst/Src" uses "IsLocalAddrExpr" to recognize indirect stores
to locals.

Currently it appears impossible to get a mismatch here as morph transforms
"IND(ADD(ADDR(LCL_VAR), OFFSET))" into "LCL_FLD" (including for TYP_STRUCT
indirections), but this is a very fragile invariant. Transforming TYP_STRUCT
GT_FIELDs into GT_OBJs instead of GT_INDs breaks it, for example.

Fix this by address-exposing the local obtained via "IsLocalAddrExpr".

* Add a TODO-CQ for LCL_FLD usage

* [Group 2] Enable nullable annotations for `Microsoft.Extensions.DependencyInjection` (#63836)

* Annotate src

* Update ResolverBuilder.Build

* Update RunOnEmptyStackCore

* ILEmitResolverBuilderContext constructor

* Remove setter

* Add assert

* Enable nullable annotations for Microsoft.Extensions.Configuration.UserSecrets (#63700)

* [mono] Cleanup trailing whitespace. (#64112)

* Delete `GT_DYN_BLK` (#63026)

* Import GT_STORE_DYN_BLK directly

* Delete GT_DYN_BLK

* DynBlk -> StoreDynBlk

* Add some tests

* Mark tests Pri-1

* Rebase and fix build

* Bring back the odd early return

* Ignore conversion exceptions during dictionary construction (#63792)

* Extract SuperPMI into a separate component (#64035)

Allows building the runtime without SPMI.

`build.cmd clr` will still build SPMI.
`build.cmd clr.native` will still build SPMI.
`build.cmd clr.runtime` will no longer build SPMI.

This is mostly motivated by NativeAOT subset builds where SPMI contributes to 10% of the native build time (nativeaot CorecLR subset builds pretty quickly compared to full CoreCLR).

* Add COMWrappers to crossgen (#63969)

* pipelines: Add wasm jobs (#64109)

* Fixing update issue with multivalued properties #34267 (#56696)

* Add custom attribute test

* Adding test demonstrating issue #34267

* Solution for issue #34267

Replacing all values in property with the new collection, instead of just
appending new values, leaving old values in place.

* Incorporate review feedback

Changing the variable name

* Relax assert in ApplyEditAndContinue (#64132)

Fixes #64070

* Disable NJulianRuleTest test crashing in CI (#64142)

* Updating unit tests for DirectoryServices.AccountManagement (#56670)

Removing old, redundant unit tests that were actually never executed

Migrating old tests to new test infrastructure with configurable LDAP/AD
connections

* Fix MultiByteToWideChar call in pal (#64146)

* Extra tests for assembly name parser. (#64022)

* Dead code in native assembly name parsing

* disallow `\u` escaping in assembly names

* misc cleanup

* forward slash is illegal escaped or not

* ignore "language" attribute in assembly name ("culture" must be used)

* duplicate attributes are ok if unrecognized (just add tests)

* drop support for "custom" blob attribute

* drop support for publickey[token]=neutral ("null" must be used)

* ignore unknown assembly name attributes in mono (compat)

* disallow \0 anywhere in the assembly name

* disallow \0 in assembly names on mono (compat)

* only check for embedded nulls when parsing

* fix mono build

* make GCC happy

* couple test scenarios for publickey vs. publickeytoken (CoreRT parser might trip on these)

* produce errors on duplicate known attributes in mono

* Dispose LdapConnections used by ValidateCredentials (#62036)

Ensure that cached LdapConnection instances created by
PrincipalContext.ValidateCredentials are disposed when
the corresponding PrincipalContext is disposed.

Fix #62035

* Add runtime support for `ref` fields (#63985)

* Add mono and coreclr runtime support for ref fields

* Update Reflection.Emit tests to validate ref fields.

Add test for TypedReference as a ref field.

* Spmi replay asmdiffs mac os arm64 (#64119)

* Split unix-arm64 into linux-arm64 and osx-arm64 in src/coreclr/scripts/superpmi-replay.proj

* Split unix-arm64 into linux-arm64 and osx-arm64 in src/coreclr/scripts/superpmi-asmdiffs.proj

* Add all subdirectories of $(SuperPMIDirectory) as PMIPATH in src/coreclr/scripts/superpmi-collect.proj

* Update NativeAOT codegen and Crossgen2 for CreateSpan (#63977)

- Make sure FieldRVA pointers remain aligned as required by the code generator
  - Use the same Packing Size approach as the IL Linker will use (See jbevain/cecil#817 for details)
  - Compilers that generate CreateSpan will need to follow that trick to be compatible with rewriters.
- Provide ECMA spec augment describing packing size detail

* Add alignment to mapped field stream (#63305)

* Align MappeFieldDataStream at 8 byte boundary

* Add test to verify that the mapped field rva data blob is aligned to ManagedPEBuilder.MappedFieldDataAlignment

* Only align when the mapped field data is of size not equal to 0

* Implement hash and HMAC stream one shots 

This implements hashing and HMAC statics for streams. Additionally,
"LiteHmac" and "LiteHash" were introduced. The existing HMAC and hash
provider functionality do some bookkeeping we don't need for resetting.
Since we do not need to use these hash handles after the digest has
been finalized, resetting is unnecessary work. For HMAC, that also means
keeping a copy of the key around for some implementations which we don't
need to do.

The LiteHash and LiteHmac types are implemented as structs with a common
interface. To avoid boxing, generics are used and constrained to the interface
where possible.

The Browser implementation just defers to the existing HashDispenser rather
than do anything novel.

The HashProviderCng is somewhat specialized in its ability to reset. It did
up-front check to determine if the platform supported reusable hash providers,
and further had a single implementation for HMAC and Digests. The current
Lite hash design requires that they remain separate types.

* Title and message resources should be enforced to exist to prevent printing empty messages (#64151)

Sync ILLink.Shared folder with the latest version in dotnet/linker main branch

List of changes include:
- Enforce title and message resources to exist to prevent printing empty messages
- All diagnostics produced by linker now have a DiagnosticId, a title and a message
- Schema for xml link attributes file

- Added a readme file to the ILLink.Shared project to keep track of the commit is being used from dotnet/linker

* Allow generating Dwarf version 5 (#63988)

Contributes to https://github.com/dotnet/runtimelab/issues/1738.

* Re-enable failing long path test (#64113)

* Port MD4 managed implementation from mono/mono (#62074)

Porting MD4 managed implementation from mono/mono (MD4.cs and MD4Managed.cs). 
  
It adds:  
- an internal class in the System.Net.Security with a single HashData method for now;  
- a set of related MD 4 unit tests to System.Net.Security.Unit.Tests project.

* Fix one source of perf regression in GCHeap::Alloc. This impacts the System.Collections.CtorFromCollectionNonGeneric<Int32> family of benchmarks. (#64091)

These benchmarks manage to make GCHeap::Alloc into a hotspot, so the call to IsHeapPointer() at the end matters for performance.

* Add blsr (#63545)

* Fix FileSystemAclExtensions.Create when passing a null FileSecurity (#61297)

* Make FileSecurity parameter nullable.

* Add missing ArgumentException message for FileMode.Append.

* Refactor tests to ensure FileSecurity is tested with all FileMode and FileSystemRights combinations. Separate special cases.

* Remove exception that throws when FileSecurity is null.
Ensure we have logic that can create a FileHandle when FileSecurity is null.
Fix bug where FileShare.Inheritable causes IOException because it is being unexpectedly passed to the P/Invoke (it should just be saved in the SECURITY_ATTRIBUTES struct).
Add documentation to mention this parameter as optional.
Ensure all exceptions match exactly what we have in .NET Framework, with simpler logic.

* Address suggestions
Co-authored-by: Ncarlossanlop <carlossanlop@users.noreply.github.com>

* Tune FP CSEs live across a call better (#63903)

The problem was that the comparison of a weighted refcount,
which usually has the order of hundreds or tens, with a small
digit like "4" was too weak and missed some cases where we
were still trying to CSE cheaps floats across calls and ending
up with lots of stack shuffling.

Fix this by using different tuning parameters, namely the costs
estimated for the uses and defs (increase them to account for
the spills and reloads).

* [main] Update dependencies from dotnet/arcade dotnet/icu dotnet/xharness dotnet/emsdk (#64098)
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>

* Update zip extraction to never throw any exceptions when the LastWriteTime update fails (#63912)

* Use kebab-case in FB automation labels (#64048)

* Onboard new Triage & PR Boards (#64198)

* Exclusively use GitHub teams for Libraries area mentions (#64199)

* Reduce buffer size used in XmlReader when using Async mode (#63459)

The current choice of AsyncBufferSize resulted in the character buffer in the XmlTextReader being allocated on the Large Object Heap (LOH)

Fixes https://github.com/dotnet/runtime/issues/61459

* Ignoring leading dot when comparing cookie domains (#64038)

* ignoring leading dot when comparin cookie domain

* Simplify cookie comparing logic to equality and moving it to CookieComparer to fix the build

* Domain comparing optimizarion and more unit tests

* small check optimization

* Renaming method

* Add missing handle function enter/return macros (#64061)

The mono_field_static_get_value method uses a handle, but did not set up
enter/exit macros properly, so this handle was leaked.

Some code in Unity calls this embedding API method pretty often, which
can lead to the mark stack overflowing in the GC code.

* Drop support for .NET 5 SDK (#64186)

We had to duplicate a lot of Microsoft.NET.ILLink.targets logic.

* Implement IEquatable<T> on value types overriding Equals (and enable CA1066/1077) (#63690)

* [mono] Temporarily disable two tests that fail on arm64 LLVM FullAOT. (#64180)

* Delete stale reference in System.Drawing.Primitives (#64202)

* Respond to feedback in GenerateMultiTargetRoslynComponentTargetsFile (#63943)

* Respond to feedback in GenerateMultiTargetRoslynComponentTargetsFile

Two small follow up changes from #58446

- Fix a type-o that breaks incremental build. Forgot to use MSBuild property syntax
- Instead of having the infrastructure hard-code removing 'Abstractions', packages can set their own Disable source gen property name.

* PR feedback

* Use the static HashData(Stream) method in more places

* Add executable bit to tizen sh files (#64216)

* Bump Intellisensense package version to latest from `dotnet7-transport` (#63352)

* Ensure that we aren't accidentally generating instructions for unsupported ISAs (#64140)

* Assert that the ISA of the set intrinsic ID is supported

* Ensure gtNewSimdCmpOpAllNode and gtNewSimdCmpOpAnyNode don't generate AVX2 instructions when not supported

* Ensure codegen for Vector128.Dot when SSSE3 is disabled is correct

* Update src/coreclr/jit/hwintrinsiccodegenarm64.cpp
Co-authored-by: NJan Kotas <jkotas@microsoft.com>

* Ensure Vector256.Sum has a check for AVX2
Co-authored-by: NJan Kotas <jkotas@microsoft.com>

* Don't reference .NETFramework shims in libraries product or test composition (#64193)

* Don't reference .NETFramework shims

Stop referencing .NETFramework shims in libraries ref or source projects as those are supplementary and shouldn't impact the product composition.

* [Android][libs] Enable Internal.Console.Write in System.Private.CoreLib (#63949)

* [Android][libs] Enable Internal.Console.Write in System.Private.CoreLib

* [docs] Add debugging System.Private.CoreLib Internal.Console.Write

* Elaborate on debugging corelib log

* Address feedback

* Install v8 and Prebuild wasm (#64100)

* Port Mono to Raspberry Pi, ship as new linux-armv6 RID (#62594)

* Initial ARMv6 arch addition. Builds mono runtime, not CoreCLR (Mono already supports the CPU arch subset used by Raspberry Pi, whilst porting CoreCLR to e.g. VFPv2 would be major work)
* Build small clr subset on ARMv6, it's needed for SDK and we want to check it works

* Fix remote unwind (#64220)

The _OOP_find_proc_info was setting only a couple of members of the
unw_dyn_info_t instance on stack. So the remaining ones had random
values. The load_offset was a recently added member to the struct.
When we have updated libunwind, this change came in. The load_offset was
random and that has broken unwindign as this offset is subtracted from
the IP when looking up unwind info.

The fix clears the whole struct. I have verified that the issue we had no
longer happens with the fix.

* Put back FindCaseSensitivePrefix regex alternation support (#64204)

* Put back FindCaseSensitivePrefix alternation support

* Fix the bug from the initial version, and add more comments

* Update tests to expect RemoteExecutor to check exit code (#64133)

* update generation_allocation_size correctly for SIP regions (#64176)

SIP regions need to update the corresponding generation's generation_allocation_size and since this can be more than 1 gen older than the region's gen, we need to make all generation's alloc size get updated.

* Android remove backward timezones (#64028)

Fixes #63693

It was discovered that Android produces duplicate TimeZone DisplayNames among all timezone IDs in GetSystemTimeZones. These duplicate DisplayNames occur across TimeZone IDs that are aliases, where all except one are backward timezone IDs.

If a name is changed, put its old spelling in the 'backward' file

From the Android TimeZone data file tzdata, it isn't obvious which TimeZone IDs are backward (I find it strange that they're included in the first place), however we discovered that on some versions of Android, there is an adjacent file tzlookup.xml that can aid us in determining which TimeZone IDs are "current" (not backward).

This PR aims to utilize tzlookup.xml when it exists and post-filter's the Populated TimeZone IDs in the AndroidTzData instance by removing IDs and their associated information (byteoffset and length) from the AndroidTzData instance if it is not found in tzlookup.xml. This is using the assumption that all non-backward TimeZone IDs make it to the tzlookup.xml file.

This PR also adds a new TimeZoneInfo Test to check whether or not there are duplicate DisplayNames in GetSystemTimeZones

* Update main branding to preview2 (#64219)

* Catch UnicodeEncodeErrors (#64251)

* Make XmlSerializer.Generator targets incremental (#64191)

* Make XmlSerializer.Generator targets incremental

Adding inputs and outputs to make XmlSerializer.Generator incremental

* Make sure that shared memory object name meets the length requirements (#64099)
Co-authored-by: NStephen Toub <stoub@microsoft.com>

* Fix PAL_wprintf for wide characters (#64181)

* [main] Update dependencies from dotnet/runtime dotnet/llvm-project (#64205)

* Update dependencies from https://github.com/dotnet/runtime build 20220123.5

Microsoft.NETCore.ILAsm , Microsoft.NETCore.DotNetHostPolicy , Microsoft.NETCore.DotNetHost , Microsoft.NETCore.App.Runtime.win-x64 , System.Runtime.CompilerServices.Unsafe , runtime.native.System.IO.Ports , Microsoft.NET.Sdk.IL , System.Text.Json
 From Version 7.0.0-alpha.1.22066.4 -> To Version 7.0.0-alpha.1.22073.5

* Update dependencies from https://github.com/dotnet/llvm-project build 20220123.1

runtime.win-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.win-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.osx.11.0-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-musl-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-musl-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-arm64.Microsoft.NETCore.Runtime.ObjWriter
 From Version 1.0.0-alpha.1.22070.1 -> To Version 1.0.0-alpha.1.22073.1
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>

* Delete unused ApiCompat baseline files (#64190)

* Delete unused ApiCompat baseline files

* Delete ApiCompatBaseline.netfx.netstandardOnly.txt

* Remove manual .NETFramework baseline validation

* Delete ApiCompatBaseline.netcoreapp.netfx461.ignore.txt

* Delete ApiCompatBaseline.netcoreapp.netfx461.txt

* Improve Regex handling of anchors (#64177)

* Improve Regex handling of anchors

- Extend search for leading anchor to support alternations.  This means that an expression like `^abc|^def` will now observe the leading `^` whereas previously it didn't.
- Add a FindFirstChar optimization that jumps to the right position for a pattern that matches a computeable max length and ends with an end anchor.

* Address PR feedback

* Add the exception set for `ObjGetType` (#64106)

* Model NRE for ObjGetType

* Add tests

* [ILVerify] Fix casting check for arrays of generic parameters with class constraints (#64259)

Fixes #63999

* Use lower call count threshold for tiering in debug builds (#60945)

* Use lower call count threshold for tiering in debug builds

To exercise more paths during tests, see https://github.com/dotnet/runtime/pull/60886

* Skip tests using AsyncIO in FileSystemAclExtensionsTests where it's not supported (#64212)

The mono runtime does not yet support AsyncIO on Windows and there were some tests failing on CI because of it.
Fixes #64221

* Correct JsonNode.Root doc (#64238)

* Take ARMv6 out of PlatformGroup All (#64267)

* Take ARMv6 out of PlatformGroup All, CoreCLR assumes this means full support
Co-authored-by: NAlexander Köplinger <alex.koeplinger@outlook.com>

* Only send to Helix for rolling build, due to small Helix queue (#64274)

* Add ref field runtime feature indication (#64167)

* Add ref field runtime feature indication
Co-authored-by: NStephen Toub <stoub@microsoft.com>

* Faster IndexOf for substrings (#63285)

* Improve "lastChar == firstChar" case, also, use IndexOf directly if value.Length == 1

* Try plain IndexOf first, to optimize cases where even first char of value is never met

* add 1-byte implementation

* copyrights

* fix copy-paste mistake

* Initial LastIndexOf impl

* More efficient LastIndexOf

* fix bug in Char version (we need two clear two lowest bits in the mask) & temporarily remove AdvSimd impl

* use ResetLowestSetBit

* Fix bug

* Add two-byte LastIndexOf

* Fix build

* Minor optimizations

* optimize cases with two-byte/two-char values

* Remove gotos, fix build

* fix bug in LastIndexOf

* Make sure String.LastIndexOf is optimized

* Use xplat simd helpers - implicit ARM support

* fix arm

* Delete \

* Use Vector128.IsHardwareAccelerated

* Fix build

* Use IsAllZero

* Address feedback

* Address feedback

* micro-optimization, do-while is better here since mask is guaranteed to be non-zero

* Address feedabc

* Use clever trick I borrowed from IndexOfAny for trailing elements

* give up on +1 bump for SequenceCompare

* Clean up

* Clean up

* fix build

* Add debug asserts

* Clean up: give up on the unrolled trick - too little value from code bloat

* Add a test

* Fix build

* Add byte-specific test

* Fix build

* Update IndexOfSequence.byte.cs

* [main] Update dependencies from dotnet/arcade dotnet/xharness dotnet/icu dotnet/hotreload-utils dotnet/llvm-project (#64265)

* Update dependencies from https://github.com/dotnet/arcade build 20220124.13

Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.TargetFramework.Sdk , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.ApiCompat , Microsoft.DotNet.XUnitExtensions , Microsoft.DotNet.GenAPI , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.GenFacades , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.Helix.Sdk
 From Version 2.5.1-beta.22071.6 -> To Version 2.5.1-beta.22074.13

* Update dependencies from https://github.com/dotnet/xharness build 20220124.1

Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit
 From Version 1.0.0-prerelease.22071.1 -> To Version 1.0.0-prerelease.22074.1

* Update dependencies from https://github.com/dotnet/icu build 20220124.5

Microsoft.NETCore.Runtime.ICU.Transport
 From Version 7.0.0-preview.2.22071.2 -> To Version 7.0.0-preview.2.22074.5

* Update dependencies from https://github.com/dotnet/hotreload-utils build 20220124.1

Microsoft.DotNet.HotReload.Utils.Generator.BuildTool
 From Version 1.0.2-alpha.0.22069.1 -> To Version 1.0.2-alpha.0.22074.1

* Update dependencies from https://github.com/dotnet/llvm-project build 20220124.2

runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools
 From Version 11.1.0-alpha.1.22067.2 -> To Version 11.1.0-alpha.1.22074.2
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>

* Add CancellationToken to TextReader.ReadXAsync (#61898)
Co-authored-by: NAdam Sitnik <adam.sitnik@gmail.com>
Co-authored-by: NStephen Toub <stoub@microsoft.com>

* Restrict parallelism in LLVM FullAOT compile, to prevent OOM (#63800)

* Restrict parallelism in FullAOT compile, to prevent OOM

* Reduce parallelism further, due to more OOM

* Moved AssemblyName helpers to managed (#62866)

* Moved ComputePublicKeyToken to managed

* Managed assembly name parsing (adapted from nativeaot)

* Fix for HostActivation failures.

* PR feedback (RuntimeAssemblyName is back to CoreRT + other comments)

* remove AssemblyNameNative::Init form the .hpp

* remove AppX compat ifdef

* renamed instance fields to convention used in C#

* `Argument_InvalidAssemblyName`   should be   `InvalidAssemblyName`. Majority of use is `FileLoadException`.

* remove `this.`

* PR feedback (assign to fileds, bypass properties)

* missed this change in the rebase

* "low-hanging fruit" perf tweaks.

* move one-user helpers to where they are used.

* removed ActiveIssue for #45032

* remove AssemblyNameHelpers.cs form corelib

* Remove the List when detecting duplicates. Support PublicKey.

* whitespace

* Fix managed implementation to match the new tests.

* Some minor cleanup.

* Do not validate culture too early

* PR feedback

* use SR.InvalidAssemblyName

* Report the input string when throwing FileLoadException

* tweaked couple comments

* Disable RegexReductionTests tests on browser

* Fix formatting of resource string where excess arguments are passed (#63824)

* Fix formatting of resource string where excess arguments are passed. #63607

* Fix BuildCharExceptionArgs and ECCurve.Validate

* Fix CA2208

* Fix CA2208. Remove paramName becaus it is in error message

* Code review fixes

* Code review fixes

* Add Regex.Count string overloads (#64289)

* Clarify purpose of PDB Document hashing (#64306)

Fixes #63505

* Fix arm64/PInvoke so that NESTED_ENTRY/NESTED_END labels match. (#64296)

This was exposed by building on arm64 with gcc-12,
wherein the assembler complained about not being able
to evaluate the constant expression for .size for the symbol
on NESTED_END.  Since the symbol on NESTED_END is not
referenced anywhere else in the code base,
I concluded that it was wrong, and NESTED_ENTRY was right.

I have not tested this on anything but arm64 + gcc-12

* When decommitting, leaving one instead of two pages in regions case. (#64243)

* Ensure that canceled Task.Delays invoke continuations asynchronously from Cancel (#64217)

* Add gen folder moving gen projects from src folder (#64231)

* Fix minor typos in GC documentation. (#64298)

* Explicitly specify four subdirectories to use as part of the paths for -pmi_path arguments and expand the paths on a remote machine in src/coreclr/scripts/superpmi-collect.proj (#64308)

* Disable RegexReductionTests on browser (#64312)

* Add UnreachableException (#63922)

* [mono] Recognize new names for Xamarin.iOS etc assemblies (#64278)

They are being renamed in https://github.com/xamarin/xamarin-macios/pull/13847

* Remove usage of codecvt from corerun (#64157)

* Remove usage of codecvt from corerun

* Update src/coreclr/hosts/corerun/corerun.cpp
Co-authored-by: NAaron Robinson <arobins@microsoft.com>
Co-authored-by: NAaron Robinson <arobins@microsoft.com>

* Refactor FileStatus.Unix. (#62721)

* Refactor FileStatus.Unix.

- Moves InitiallyDirectory out of FileStatus into FileSystemInfo.
In FileSystemInfo it can be a readonly field making its usage clearer.
And FileStatus can then directly be used to implement some FileSystem methods
without allocating an intermediate FileInfo/DirectoryInfo.

- Treat not exists/exist as initialized states to avoid wrongly assuming
initialized means the file cache is valid, which isn't so when the file does
not exist.

- Use 0 for tracking uninitialized to make default(FileStatus) uninitialized.

* Fix unique VNs for `ADDR`s (#64230)

* Add the test

* Fix unique VNs for ADDRs

They need to keep the exception sets.

* Implemented hierarchy of attributes. (#64201)

* Implemented hierarchy of attributes.

* Shortened.

* Fixed overlooked test naming and simplified.

* Partial refactor.

* Update the managed type system to more gracefully fail when calling a varargs method. (#64286)

* Update the managed type system to more gracefully fail when calling a varargs method.

* Use ThrowHelper instead of manually throwing the exception.

* Update src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureParser.cs
Co-authored-by: NJan Kotas <jkotas@microsoft.com>

* [mono] Add some missing Internal.Runtime.CompilerServices.Unsafe intrinsics. (#64314)

* Remove usage of FEATURE_CORESYSTEM (#63850)

* Remove usage of FEATURE_CORESYSTEM from coreclr.

* [main] Update dependencies from dotnet/arcade dotnet/runtime-assets (#64331)

* Update dependencies from https://github.com/dotnet/arcade build 20220125.6

Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.TargetFramework.Sdk , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.ApiCompat , Microsoft.DotNet.XUnitExtensions , Microsoft.DotNet.GenAPI , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.GenFacades , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.Helix.Sdk
 From Version 2.5.1-beta.22074.13 -> To Version 2.5.1-beta.22075.6

* Update dependencies from https://github.com/dotnet/runtime-assets build 20220125.1

Microsoft.DotNet.CilStrip.Sources , System.ComponentModel.TypeConverter.TestData , System.Drawing.Common.TestData , System.IO.Compression.TestData , System.IO.Packaging.TestData , System.Net.TestData , System.Private.Runtime.UnicodeData , System.Runtime.Numerics.TestData , System.Runtime.TimeZoneData , System.Security.Cryptography.X509Certificates.TestData , System.Text.RegularExpressions.TestData , System.Windows.Extensions.TestData
 From Version 7.0.0-beta.22060.1 -> To Version 7.0.0-beta.22075.1
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>

* Fixes bad log method generation in certain cases. (#64311)

In certain cases when developer by mistake places ILogger, Exception, or LogLevel in the message template,  the code generator will produce the expected warning and makes sure the code will indeed compile and run correctly.

Prior to this fix, the code generator would fail to compile with when either of ILogger, Exception or LogLevel were placed in message template incorrectly.

Fixes #64310

* Fix IsMutuallyAuthenticated on Linux and OSX (#63945)

* WIP - prepared a failing test

* Fix IsMutuallyAuthenticated on Linux

* Fix failing unit tests

* Minor cleanup

* Port changes to OSX

* Fix comment

* Invoke cert selection inline, don't allocate new credentials on Linux/OSX

* Fix tests on OSX

* Code review feedback

* Move tests to separate file

* Fix build

* Fix Failing tests

* Support {Last}IndexOfAny with sets after {lazy} loops (#64254)

When emitting backtracking loops, the loop consumes as much and then backtracks through the consumed input.  Rather than doing this one character by one character, we previously added use of LastIndexOf to search for the next place the literal after the loop matches.  We can also augment that to use IndexOfAny to search for a small set that comes after a loop instead of a literal.

Similarly when emitting backtracking lazy loops, rather than consuming one character and trying the rest of the expression and then consuming another character and trying the rest of the expression, we previously added an optimization to use IndexOf{Any} to find the next possible location of a match based on the literal that comes after the lazy loop.  And we can similarly augment that to support a small set after the lazy loop.

This is particularly helpful for IgnoreCase, as we're on a path to replacing literals with sets that contain all equivalent casings of that character.

* Fix race conditions in SystemEvents shutdown logic (#62773)

* Fix race conditions in SystemEvents shutdown logic

When the application is terminated through Restart Manager the event broadcasting window will get the `WM_CLOSE` message. The message gets handled by passing it to `DefWndProc` which calls `DestroyWindow` on the window itself thus making the window handle invalid. The `Shutdown` method expects the window handle to be valid to post `WM_QUIT` message to terminate the thread running the message loop but that's no longer possible under these conditions.

Additionally there's second race condition with the `s_eventThreadTerminated` event that is created during shutdown and set conditionally. A race condition between the threads could cause it to be created when the window message thread is already shutting down and thus it would never be set. Waiting for it in the `Shutdown` method would be cause a deadlock. This thread is also completely unnecessary since a `Join` is performed on the thread itself.

The fix has several changes that act together:
- `s_eventThreadTerminated` event is removed completely in favor of only relying on `Thread.Join`
- `WM_DESTROY` message is detected (which happens as a result of WM_CLOSE calling `DefWndProc` which in turn calls `DestroyWindow`) and handled by shutting down the message loop thread
- The message loop itself is rewritten to use standard `GetMessageW` loop. The reasoning on why it was not used seems not to be valid anymore since AppDomain shutdowns are performed differently

* Add unit test.

* Add braces

* Add marshaller for TypeLoad failure cases (#64317)

This is marshaller used when there incorrect configuration of marshaller applied to fields mostly

* Add additional loop table asserts (#64126)

1. Assert that top-level loops are basic block disjoint
2. Assert LPFLG_ITER related flags are legal

In addition:
1. Create a `optClearLoopIterInfo` phase to clear various bits in the loop
table that are known to no longer be valid, to prevent bad asserts or JitDump
output on their values.
2. Move the EndPhase call in Phase::PostPhase happens early, not late.
This causes any subsequent asserts due to post-phase checking to be
marked with the correct phase, in cases where there was a nested phase
executed (such as liveness re-computation).
3. Convert PHASE_INSERT_GC_POLLS to use EndPhase checking
4. Convert fgDetermineFirstCodeBlock to return a PhaseStatus
5. Some minor cleanup in optUpdateLoopsBeforeRemoveBlock()
(this was extracted from some bigger changes)

* Moved AssemblyName helpers to managed (part 2) (#63915)

* implement GetAssemblyName via dynamic call to MetadataReader

* A few more file-locking tests.

* fix #28153

* no need for version when getting MetadataReader

* rename the argument to match AssemblyName

* perf tweaks

* use memory-mapped file to read metadata

* adjust tests for the new implementation

* use "bufferSize: 1" when stream is going to be mapped.

* null-conditional operator.

* do Dispose before re-throwing

* get rid of the platform-specific/native stuff

* remove assemblyname.hpp

* remove `VerifyIsAssembly()`

* PR feedback

* put back gStdMngIEnumerableFuncs and the others

* Fix several bugs in NullabilityInfoContext. (#64143)

* Fix several bugs in NullabilityInfoContext.

* Reverse ASG(CLS_VAR, ...) (#63957)

This helps with register allocation. Consider:
```
***** BB01
STMT00001 ( 0x000[E-] ... ??? )
N003 ( 18, 10) [000003] -ACXG-------              *  ASG       ref    $c0
N001 (  3,  4) [000002] ----G--N----              +--*  CLS_VAR   ref    Hnd=0x8fec230 Fseq[hackishFieldName]
N002 ( 14,  5) [000000] --CXG-------              \--*  CALL      ref    CscBench.GetMscorlibPathCore $c0
```
The rationalizer will rewrite it to what is effectively:
```
***** BB01
STMT00001 ( 0x000[E-] ... ??? )
N004 ( 18, 12) [000003] -ACXG---R---              *  ASG       ref
N003 (  3,  6) [000002] n---G--N----              +--*  IND       ref
N002 (  1,  4) [000006] H-----------              |  \--*  CLS_VAR_ADDR byref  Hnd=0x8fec230
N001 ( 14,  5) [000000] --CXG-------              \--*  CALL      ref    CscBench.GetMscorlibPathCore
```
And the final LIR will look like:
```
               [000006] ------------                 IL_OFFSET void   INLRT @ 0x000[E-]
N001 (  3,  4) [000002] ----G--N----         t2 =    CLS_VAR_ADDR byref  Hnd=0x8fec230
N002 ( 14,  5) [000000] --CXG-------         t0 =    CALL      ref    CscBench.GetMscorlibPathCore $c0
                                                  /--*  t2     byref
                                                  +--*  t0     ref
N003 ( 18, 10) [000003] -A-XG-------              *  STOREIND  ref
               [000007] ------------                 IL_OFFSET void   INLRT @ 0x00A[E-]
N001 (  0,  0) [000004] ------------                 RETURN    void   $180
```
Since this store must use a barrier, `CLS_VAR_ADDR` won't be contained and will have to be evaludated
separately. Because its value is live across a call, it'll get spilled and reloaded. Reversing the ASG
fixes the problem:
```
------------ BB01 [000..00B) (return), preds={} succs={}
               [000006] ------------                 IL_OFFSET void   INLRT @ 0x000[E-]
N001 ( 14,  5) [000000] --CXG-------         t0 =    CALL      ref    CscBench.GetMscorlibPathCore $c0
N002 (  3,  4) [000002] ----G--N----         t2 =    CLS_VAR_ADDR byref  Hnd=0x8fec230
                                                  /--*  t2     byref
                                                  +--*  t0     ref
N003 ( 18, 10) [000003] -A-XG-------              *  STOREIND  ref
               [000007] ------------                 IL_OFFSET void   INLRT @ 0x00A[E-]
N001 (  0,  0) [000004] ------------                 RETURN    void   $180
```

* Fixes a few issues for dprintf on OSX (#64076)

* [Codespaces] Make it possible to run wasm samples in the browser (#64277)

With these changes, running the following in the Codespace will open the local browser to a page served from the codespace hosting the WASM sample:

```console
cd src/mono/sample/wasm/browser
make
make run-browser
```


* Set EMSDK_PATH in .devcontainer.json

   We provision Emscripten as part of the devcontainer prebuild.

   Set EMSDK_PATH to allow rebuilding the wasm runtime to work without any additional ceremony

* Install dotnet-serve into .dotnet-tools-global

* [wasm] Don't try to open browser if running in Codespaces

* .devcontainer: add global tools dir to PATH

* .devcontainer: forward port 8000

   This enables running the mono wasm samples in the local browser:

* [wasm] samples: also check for dotnet-serve on the path

   On Codespaces we install dotnet-se…

* Revert "`SafeFileHandle` `FileStatus` (#4)" (#5)

This reverts commit 6a3e1317c75af02e6a4d3d1cb336ed79b86e59df.

* Usage of `GetHandlePath`
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>

* Usage of `CULong`
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>

* Usage of `CULong`
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>

* Add SystemNative_FChflags

* Fix `OpenHandle` calls in test

* Add symlink resolving in `TimeFunctions` tests

* Use `futimes` fallback for `futimens`

* Use right preprocessor var

* Add new line at EOF in `Interop.BY_HANDLE_FILE_INFORMATION`

* Remove `FileOptions.DeleteOnClose` in Test cases for post-disposal tests

* Add non linux condition to `SetDateTimeMax_SafeFileHandle` test

* Exclude pagefile.sys tests for `SafeFileHandle`

* Fix `BaseGetSetTimes` tests

* Use `GeneratedDllImport` over `DllImport`

* Remove redundant charset spec. from `Interop.UTimensat`

* Remove extra line

* Add explicit parameter names
Co-Authored-By: NDan Moseley <danmose@microsoft.com>

* Add explanatory comment to `TimeFunctions`

* Improve test cases

* Remove more redundant charset specifications

* Refactoring Tests

* Refactor Tests

* Fix tests

* Improve test structure

* Remove `ExactSpelling`

* Rename `GeneratedDllImportAttribute` to `LibraryImportAttribute`

See PR #66307

/cc @elinor-fung

* Apply suggestions
Co-Authored-By: NStephen Toub <2642209+stephentoub@users.noreply.github.com>

* Reduce code duplication in `FileSystem.Windows.cs`

* Fix tests

* Address feedback
Co-Authored-By: NStephen Toub <2642209+stephentoub@users.noreply.github.com>
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Address more feedback
Co-Authored-By: NStephen Toub <2642209+stephentoub@users.noreply.github.com>
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Apply suggestions & try to avoid reordering
Co-Authored-By: NDan Moseley <danmose@microsoft.com>
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Fix tests

* Fix tests

* Refactor `BaseGetSetTimes`
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Merge branch 'main' into issue-20234

* Test style changes
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Don't try to verify link properties don't change when we can't retrieve them.

* Apply suggestions
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Regenerate reference source

* Merge branch 'main' into issue-20234

* Apply suggestions
Co-Authored-By: NDan Moseley <danmose@microsoft.com>

* Reorder project items

* Apply suggestions
Co-Authored-By: NDavid Cantú <jozkyy@gmail.com>

* Apply suggestions
Co-Authored-By: NDavid Cantú <jozkyy@gmail.com>

* Apply suggestions
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Fix `fsetattrlist`

* Apply suggestions
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Fix error path resolution

* Merge branch 'main' into issue-20234

* (Try to) fix OSX failures

* Fix OSX method signature

* Apply suggestions
Co-Authored-By: NTom Deseyn <tom.deseyn@gmail.com>

* Apply suggestions (using GitHub UI)
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>

* Apply suggestions (using GitHub UI)
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>

* FileStatus: avoid ToString allocation for setattrlist

* Remove unnecessary message

* Apply suggestions

* Merge branch 'main' into issue-20234

* Fix corruption due merge

* Apply suggestions
Co-Authored-By: NDavid Cantú <jozkyy@gmail.com>

* Fix Unix tests

* Merge branch 'main' into issue-20234

* Fix tests

* Update src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>

* Fix Unix test failures.

* Sfh fix tests (#8)

* Use the signature types when building ABI info (#70635)

* Use signature types when building the ABI info

This will allow us to let "mismatched" struct types as call arguments,
which in turn is expected to simplify and de-pessimize much of the code
working around the need to keep precise handles on struct nodes.

Credit to @jakobbotsch for being able to make this change.

* Work around the "InferOpSizeAlign" problem

Handling it generally requires solving a larger problem
of "eeGetArgSizeAlignment" not working well on ARM.

(See also the use of "eeGetArgSizeAlignment" in "lvaInitUserArgs")

* [wasm] Build WasmAppHost with UseAppHost=false (#70606)

* [wasm] Build WasmAppHost with UseAppHost=false

- WasmAppHost is included in the WebAssembly.Sdk pack, and doesn't have a
platform specific package.
- Since, this is being built for x64, the build defaults to using the
app host, which means that we get a single binary file that can be run
directly.
    - But this also means that the binary included in the
    WebAssembly.Sdk platform-agnostic package will target the platform
    where it was built.

- Instead, build with UseAppHost=false, and update the wasm host to use
the managed assembly instead.

And update the RunCommand to use `dotnet exec WasmAppHost.dll`.

* fix

* JIT: Optimize expansion of indir cell addresses for CFG (#70491)

On ARM64 it is expensive to materialize the address of an indirection
cell since that requires multiple instructions. This is particular a
problem when CFG is enabled where validation + call uses the indir cell
twice. This changes the CFG logic to create a local in this case.

We also were forcing the indir cell argument node into the register.
This is not ideal for this particular case, so remove this logic and let
LSRA deal with it. ARM still needs this logic.

Fix #65076

* Handle mis-sized structs in XARCH `PUTARG_STK` codegen (#68611)

* Handle "mis-sized" structs in XARCH PUTARG_STK codegen

Previously, for structs which were not a multiple of TARGET_POINTER_SIZE
in size:

1) On x86, we copied them to a local in morph. This was a small CQ issue.
2) On Unix x64, we didn't handle them at all and could read out of bounds
   in "genStructPutArgUnroll".

This change fixes both issues by properly detecting cases where we need to
be careful and updating codegen to use correct load sizes.

* Add a test

* Improve distribution of CoseHeaderLabel hash codes (#70695)

* Implement digest one shots for browser implementation

* [wasm] Don't use a fixed listening port for the proxy (#70681)

Fixes https://github.com/dotnet/runtime/issues/70670 .

* Fix SOS tests on 7.0 (#70677)

The wcscpy_s in ClrDataAccess::GetRegisterName was failing with an invalid parameter exception because
the prefixLen and regLen didn't include the terminating null wchar.

* [wasm] Enable some previously failing WBT/AOT tests on windows (#70595)

* [wasm] Enable some previously failing WBT/AOT tests on windows

Fixes https://github.com/dotnet/runtime/issues/61725 .

* [wasm] WBT: Fix a failing satellite assembly test

The test fails because it is trying to find the string `got: こんにちは`
in the app output, but it sees `?????`. This is due to xharness not
setting the console output to UTF8, and then the tests not doing the
same.

Instead of that, we can move the check to be in the app itself, thus
removing the need for any of this.

Fixes https://github.com/dotnet/runtime/issues/58709 .

* List other architectures and DOTNET_ROOT environment variables in dotnet --info (#70403)

* [mono] Remove dead code. (#70671)

A variable initialized to false and never modified means we can remove the
variable and any code that depends on that variable not being false.

This is a consequence of 15ab9f98, where code
that assigned the variable was removed.

* Avoid throwing Win32Exception from HTTP authentication (#70474)

* Avoid throwing Win32Exception from HTTP authentication

When server sends malformed NTLM challenge the NT authentication processing
would throw an unexpected Win32Exception from HttpClientHandler.Send[Async]
calls. This aligns the behavior to WinHTTP handler where the Unauthorized
reply with challenge token is returned back to the client.

Similarly, failure to validate the last MIC token in Negotiate scheme could
result in Win32Exception. Handle it by throwing HttpRequestException instead.

* Make the unit test more resilient

* Add trace to Negotiate authentication

* Dispose connection instead of draining the response

* Remove outdated ActiveIssue

* Fix usage of GSS_KRB5_CRED_NO_CI_FLAGS_X (#70447)

* Fix build detection of GSS_KRB5_CRED_NO_CI_FLAGS_X

* Don't use GSS_KRB5_CRED_NO_CI_FLAGS_X on NTLM

* Handle GSS_S_UNAVAILABLE error from gss_set_cred_option (NTLM wrapped in Negotiate)

* Make the GSSAPI shim work with krb5 1.13

* Preserve the gss_acquire_cred minor status

* Use IndexOf in WebUtility (#70700)

The IndexOfHtmlDecodingChars method was iterating character by character looking for either a `&` or a surrogate, but then the slow path if one of those is found doesn't special-case surrogates.  So, we can just collapse this to a vectorized `IndexOf('&')`, which makes the fast path of detecting whether there's anything to decode much faster if there's any meaningful amount of input prior to a `&`. (I experimented with also using `IndexOf('&')` in the main routine, but it made cases with lots of entities slower, and so I'm not including that here.)

* Hoist the invariants out of multi-level nested loops (#68061)

* first working version

* Skip check of VN hoisting

* Account for duplicate blocks

* clean up

* wip

* isCommaTree && hasExcep

* revert lsra changes

* Update hoisting condition

- Only update if node to be hoisted has side-effects and the sibling that is before that throws exception

* Change to BasicBlockList

* organize preheaders

* update hoistedInCurLoop and hoistedInSiblingLoop

* Reverse the loop order

* cleanup and jit-format

* Revert "Minor fix to display IG01 weight correctly"

This reverts commit 757120e863b2da188db2593da1b7142fd1ecf191.

* simplify code

* Remove m_hoistedVNInSiblingLoop

* Add back ResetHoistedInCurLoop

Fix igWeight

* Remove reversal of loop processing order

* jit format

* Experimental: Also generate PerfScore:

* review feedback

* fix the superpmi script

* Revert superpmi asmdiffs change

* Rename method

* Add a comment

* Delete GTF_ASSERTION_PROP_LONG (#70521)

* Convert exception help context parsing to managed (#70251)

* Move help link parsing to managed

* Cleanup wtoi and nativeIsDigit

* Fix metasig declaration

* Guard GetHelpContext under FEATURE_COMINTEROP

* Remove definition of GetHelpLink and guard more methods under cominterop

* DWORD should be uint

* Add help context marshaling test

* Adjust marshaling test

* Fix #ifdef with ILLink

* Fix method signature mismatch

* Specify string marshaling

* Throwing test should not test successful HRESULT

* Implement ISupportErrorInfo

* Test interface in InterfaceSupportsErrorInfo

* Delete tests for .NET Framework Xsltc.exe tool (#70706)

* Use regex matching for Xsltc test baseline files

* Delete xsltc.exe tests entirely

* Reenable C4244 in repo (#70026)

* Reenable 4244 warning for Mono.

* Enable compiler errors for gcc/clang.

* Fix issues enabling -Werror=implicit-int-conversion

* Revert turning on implicit-int-conversion as error.
  This check was triggering failures on parts of the PAL that
  require additional scrutiny beyond the scope of this work.

* Add SlidingWindow and FixedWindow to RateLimitPartition (#68782)

* align GC memory load calculation on Linux with Docker and Kubernetes (#64128)

* align memory load calculation in GC with Docker and Kubernetes

* pass inactive file field name as a parameter

* [wasm] Fix Debug configuration builds (#70683)

* Fix cmake error

   ```
   Manually-specified variables were not used by the project:
   CONFIGURATION_WASM_OPT_FLAGS
   ```

* Build the interpreter with -O1 on Wasm in Debug configs

   Otherwise `interp_exec_method` and `generate_code` can easily overflow the stack in some browsers with even a few recursive calls (for example during .cctor initializaiton)

* [wasm] Make runtime_is_initialized promise callbacks one-shot (#70694)

* [wasm] Make runtime_is_initialized promise callbacks one-shot

Throw if runtime_is_initialized_resolve or runtime_is_initialized_reject is called more than once

* Add a slightly generalized GuardedPromise<T> object

   Protects against multiple-resolve, multiple-reject, reject after resolve and resolve after reject.

  Does not protect against the executor throwing.

* Do not use ExecutableMemoryAllocator on 64 bit platforms if default base address usage is requested (#70563)

* [wasm][debugger] Implement get bytes from loaded_files using debugger protocol. (#69072)

* Implement get bytes from loaded_files using debugger protocol.

* fix pdb size == nul

* Adressing @radical comments.

* Fix build.

* fix compilation

* Addressing @radical comments.
Co-authored-by: NAnkit Jain <radical@gmail.com>

* Add doc on Unix temporary file security practice (#70585)

* Add doc on Unix temporary file security practice

* Update unix-tmp.md

* Update unix-tmp.md

* Add example permissions encoding

* Update docs/design/security/unix-tmp.md
Co-authored-by: NDan Moseley <danmose@microsoft.com>

* Update unix-tmp.md
Co-authored-by: NDan Moseley <danmose@microsoft.com>

* ConfigurationBinder.Bind on virtual properties duplicates elements (#70592)

* ConfigurationBinder.Bind on virtual properties duplicates elements

* simplify GetAllProperties

* return array instead of list

* Obsolete AssemblyName.CodeBase, AssemblyName.EscapedCodeBase (#70534)

* JIT: Enable JitConsumeProfileForCasts by default (#69869)

* Fix AttributePresence in composite mode (#70737)

According to my comparative perf measurements composite framework
spends about 5M more instructions in the method

coreclr.dll!CMiniMdTemplate<CMiniMd>::SearchTableForMultipleRows(CMiniColDef sColumn)

I tracked this down to the R2R table AttributePresence which is
used to speed up attribute queries against the ECMA metadata model.
In composite mode we were putting the table in the image header,
not component header, and so the runtime was unable to locate it.
This change fixes generation of the table in Crossgen2; I have
verified that with this change I no longer see the 5M outlier.

Thanks

Tomas

* Handle mis-sized structs in ARM/64 `PUTARG_SPLIT` codegen (#70249)

* Add a test

* Fix out-of-bounds loads in ARM/64's "genPutArgSplit"

* Split the test out

* Refactor how implicit byrefs are morphed (#70243)

* Refactor implicit by-refs morphing

Move it to "fgMorphLocal".

Enabled folding in "LocalAddressVisitor".

* Add FEATURE_IMPLICIT_BYREFS

And use it in all the necessary places.

Resolves the TP regression on Unix x64, turning it into a TP improvement.

* Add a zero-diff quirk

* Do not change `gtRetClsHnd` in `impNormStructVal` (#70699)

* Do not change "gtRetClsHdl" in "impNormStructVal"

Doing so leads breaking the proper ABI handling for the call.

* Add a test

* Support `PUTARG_STK(STRUCT LCL_VAR/LCL_FLD)` on ARM/64 (#70256)

* Separate out LowerPutArgStk

Call it from "LowerArg" instead of "ContainCheckCallOperands",
as it does more than just containment analysis.

* Support "PUTARG_STK(STRUCT LCL_VAR/LCL_FLD)" on ARM/64

To test this, transform "OBJ(LCL_VAR|FLD_ADDR)" to "LCL_FLD" on lowering.

This additionally simplified the codegen code as it doesn't have to support
two representations of the same thing.

* Support `PUTARG_STK(STRUCT LCL_VAR/LCL_FLD)` on x86/Unix x64 (#70702)

* Add GenTree::GetLayout

* x86/Unix x64: lowering

* x86/Unix x64: "genConsumePutStructArgStk"

* x86/Unix x64: "genStructPutArgUnroll"

* x86/Unix x64: codegen asserts

* x86: "genStructPutArgPush"

* Unix x64: "genStructPutArgPartialRepMovs"

* Allow `TYP_STRUCT` `LCL_FLD` on the RHS of block copies (#70633)

* Delete the unused "GTF_USE_FLAGS"

It used to indicate that a branch operation didn't
need to materialize its operand and could just "use
flags" instead, but that purpose has long been lost
now that we have explicit SETCC nodes in lowering.

* Make GTF_DONT_EXTEND a shared flag

So that it can be used for "LCL_FLD" as well as "GT_IND".

No diffs.

* Enable TYP_STRUCT on the RHS

* fgMorphBlockOperand

* Tweak TYP_STRUCT LCL_FLD costs

Model it as two load, like OBJ.

Note we could be more precise here, by using the
register type of the layout. For now, we defer.

* Block CSE

Preserve previous behavior to avoid diffs.

* Revert "Fix usage of GSS_KRB5_CRED_NO_CI_FLAGS_X (#70447)" (#70747)

This reverts commit 84f7cad0.

* Add note about backward branch constraints to ECMA-335 augments (#70760)

* [NativeAOT] Enabling return address hijacking on ARM64 Windows (#70740)

* Enabling return address hijacking on ARM64 Windows

* pass right flags to the GcInfoDecoder

* Fix value numbering of HWI loads (#70621)

* Fix numbering of HWI loads

Take into account all operands and describe the exception sets precisely.

* Add a test

* Recast the check

* Small MsQuicStream refactorings (#70433)

* Inline state transition helpers

Fixes #55437

* Add high level comments for HandleEventReceive and ReadAsync

* Updating HWIntrinsicInfo::lookupId to not accelerate Vector256 APIs when AVX2 is unsupported (#70686)

* Updating HWIntrinsicINfo::lookupId to not accelerate Vector256 APIs when AVX2 is unsupported

* Fixing a check in lookupId to properly negate the condition

* Ensure the special-cased EA_32BYTE constants only happen when AVX/AVX2 are supported

* Fixing a bad assert in morph

* Dsiable CertificateValidationRemoteServer.ConnectWithRevocation_WithCallback on Android (#70768)

* NativeAOT Unlock assignability comparison in reflection-free (#70726)

* NativeAOT Unlock assignability comparison in reflection-free
Closes #69960

* Document support for `IsAssignableFrom`

* Document support for `IsInstanceOfType`

* Document `IsAssignableTo`

* Add suggestion from Michal

* Update src/coreclr/nativeaot/System.Private.DisabledReflection/src/Internal/Reflection/RuntimeTypeInfo.cs
Co-authored-by: NMichal Strehovský <MichalStrehovsky@users.noreply.github.com>

* Remove whitespaces
Co-authored-by: NMichal Strehovský <MichalStrehovsky@users.noreply.github.com>

* [Mono] Fix C4018 round I (#70417)

* First round of change of fixing C4018

* Address part of review feedback

* Change the type of idx to unsigned for `effective_table_slow`

* Add idx range check after the type was changed

* Address review feedback for `class-init.c`

* Change the return type of `*table_num_rows*` to `guint32`. Deal with the consequence of return type change of `table_info_get_rows`. Correct the type of a few local variables which store the return of `mono_metadata_token_index`.

* Update return type

* Address review feedbacks of metadata.c

* Fix native crash

* Make counter private to for-loop

* Address review feedbacks

* Address review feedbacks

* Fix race condition in LoaderAllocator::CompareExchangeValueInHandle (#70765)

The method was not actually using interlocked operation. It made it possible for multiple different values to win.

Fixes #70742

* Enable redirection on arm64 (#70769)

* Handle HW exceptions on Windows without redirection (#70428)

This change modifies the way hardware exceptions are propagated from the
vectored exception handler. Until now, runtime was returning from the
vectored exception handler with instruction pointer in the context set
to an asm helper. That redirected the thread to that helper and we have
raised an exception from its call chain.
While working on CET support, it was found that propagating exceptions
from the vectored exception handler directly works just fine. So this
change makes it work that way for all Windows targets.

* Predicate for valid Tracker Reference is inverted (#70709)

* Predicate for valid Tracker Reference is inverted

* Fix test to not inline wrapper creation function.

* JIT: Enable addressing modes for gc types (#70749)

* JIT: Faster long->int overflow checks (#69865)

* Update .net version for asp.net spmi collection script (#70778)

* Enable IlcTrimMetadata by default (#70201)

Enables more aggressive metadata stripping by default. In this mode, the AOT compiler only generates reflection metadata for artifacts that were deemed reflection-visible by either dataflow analysis, or user inputs. Previously we would consider everything that got generated reflection-visible.

* Change the defaults within the compiler (making the conservative mode opt-in).
* Add tests for scenarios in https://github.com/dotnet/runtimelab/issues/656 (resolves dotnet/runtimelab#656).
* Update tests
* Do more marking where it was necessary

* Remove GSS_KRB5_CRED_NO_CI_FLAGS_X code (#70772)

The support for building with GSS_KRB5_CRED_NO_CI_FLAGS_X was broken for quite some time. Attempts to reenable it failed due to bug in the krb5 GSSAPI implementation resulting in invalid memory accesses.

* Make ConnectWithRevocation_StapledOcsp more resilient to being slow

* Upgrade SDK to Preview 5 (#70117)

Upgrade to released Preview 5 build

* Find&replace FastInterlock* with Interlocked* (#70784)

FastInterlock* operations were #defined as aliases to regular Interlock* operations. Deleted the FastInterlock* aliases and replaced usage with Interlocked* operations.

* JIT: rework optCanonicalizeLoop (#70792)

Rework loop canonicalization in anticipation of extending it to handle
non-loop edges like those seen in #70802 (details in #70569).

The code to fix up flow out of `h` was not needed and has been removed.
We now assert upstream that no such fix up will be needed.

* Avoid infinite loop in case of heap corruption (#70759)
Co-authored-by: NJuan Hoyos <juan.hoyos@microsoft.com>
Co-authored-by: NNoah Falk <noahfalk@users.noreply.github.com>

* [wasm][debugger] Remove workaround to get pauseOnExceptions setting (#70748)

* Add SubstitutionParser that uses XPath Navigator into NativeAOT (#64671)

* Add end-to-end test for NTLM/Negotiate authentication against fake server (#70630)

* Add end-to-end test for NTLM/Negotiate authentication against fake server

* Simplify the test since HttpClientHandler is always SocketsHttpHandler for the test environment

* Fix test condition

* Remove extra comment

* Enable ThreadAbort with CET enabled via the QueueUserAPC2 (#70803)

This change makes ThreadAbort work when CET is enabled. Instead of
thread redirection, it uses the new user mode APC mechanism to get a
thread to a handler and then throws the ThreadAbortException from there
if the thread was interrupted at a safe location.

I have verified it works using mdbg tests and also by manual testing in
the Visual Studio 2022 using a test app that creates an instance of
classes with properties containing infinite loop, wait on a lock, wait
on a handle, infinite loop inside of a lock and infinite loop in
finally.
For the testing, I've enabled this separately from the CET so that the
missing support for CET in the debugger code doesn't cause troubles.

So we could enable this without CET enabled too, but I'd prefer doing
that separately.

* Test additional NativeAOT Lib testing (#70212)

* Test additional NativeAOT Lib testing

* more libraries to un nativeaot rolling build

* FB

* FB2

* only write results file if specified in args

* excluding failing tests

* oops, missed pull before a forced push

* excluding some recently added tests that fail

* fix typo with end element

* FB

* Fix emitDispJumpList for Arm64 (#70542)

* fix jitdump

* Fix arm build

* Another format

* Fix regression in runtime-jit-experimental (#70797)

The newly-introduced `emitRemoveJumpToNextInst` optimization caused
a regression when hot/cold-splitting, where jumps from the last hot
instruction to the first cold instruction were erroneously removed.
This is fixed by disabling the `isRemovableJmpCandidate` flag for
branches between hot/cold sections.

On an unrelated note, a JIT dump message has been added to indicate
stress-splitting is occurring.

* JIT: relax fwd sub restriction on changing class handle (#70587)

For HW SIMD types, at least.

Fixes #64879.

* Use LastIndexOf in ZipArchiveEntry.GetFileName_Unix (#70701)

There's not particularly good reason to open-code the loop here.

* Update dogfooding instructions (#70833)

- Delete note about multilevel lookup. It is not relevant anymore.
- Fix nightly feed url to net7
- Replace .NET Core with just .NET

* Add icon to dotnet.exe on Windows (#70578)

* Add two new stages to prepare for our new custom type marshalling design. (#70598)

* Simplify `Environment.IsWindows8OrAbove`. (#70818)

* Simplify Environment.IsWindows8OrAbove.
Since .NET 5, the regular Windows version detecton code always returns the correct version.

* Remove two unused interop files.

* Delete redundant aliases for primitive types (#70805)

* Add limited support for LocalCertificateSelectionCallback for QUIC (#70716)

* Inline state transition helpers

Fixes #55437

* Add high level comments for HandleEventReceive and ReadAsync

* [QUIC] Call `LocalCertificateSelectionCallback` to get client certificate

* Code review feedback

* JIT: Optimize range checks for X >> CNS and for short/byte indices  (#67141)
Co-authored-by: NSingleAccretion <62474226+SingleAccretion@users.noreply.github.com>

* Tighten checks in `areArgumentsContiguous` (#70829)

* Tighten checks in "areArgumentsContiguous"

* Add a test

* Narrow cast fix (#70518)

* Added genActualTypeSize. Remove narrow cast if the actual type sizes are the same

* Trying to fix build

* Fixing build

* Removed genActualTypeSize. Using genActualType instead

* Added helper function

* Comments

* Moving back to morph

* Removing part of the test

* Added fgOptimizeCastOnAssignment

* Fixing build

* Removing extra bits

* Removed fgIsSafeToRemoveIntToIntCastOnAssignment, inlining the implementation, adding extra logic when actual types are not the same

* [wasm] Disable WBT test failing on windows (#70808)

Issue: https://github.com/dotnet/runtime/issues/70675

* Enable IDE1005 (Delegate invocation can be simplified) (#70522)

* Disable long running test (#70843)

* [wasm] Enabled WriteToReadOnly tests - emscripten bug got fixed (#70814)

Fixes #53021.

Enabled tests from #53021 - they are passing now because issue reported by @radekdoulik got fixed: https://github.com/emscripten-core/emscripten/issues/14299.

* Use IndexOf{Any} in a few more places (#70176)

* Use IndexOf{Any} in a few more places

* Address PR feedback

* Fix corerun for assemblies with mismatched filename (#70800)

corerun gracefully handled filename not matching the assembly name. Handling of this case regressed in #68186. This change is fixing the regression.

Fixes #68455

* Fix a few Stream-related issues in System.Net.Http (#70731)

* Fix a few Stream-related issues in System.Net.Http

* Put back WriteTimeout

* Fix tests

* Catch (more) mismatched args in `fgMorphArgs` (#70846)

* Catch (more) mismatched args in "fgMorphArgs"

* Add a test

* [coop] fix coop suspend timeout cue card (#70828)

the BLOCKING_SUSPEND_REQUESTED state is treated as suspend in full
coop mode (the thread keeps running, but by definition it's not
allowed to access managed resources and it will self-suspend if it
tries to enter GC Unsafe mode by calling a runtime API or managed
code).
It is bad in hybrid suspend mode (the thread should be preemptively
suspended, but we timed out before the signal handler had a chance to
run).

The corresponding suspension logic in the code is:

https://github.com/dotnet/runtime/blob/3fc61ebb562afc327a8fc6de5c82d76e86bf6f5d/src/mono/mono/utils/mono-threads.c#L1149-L1158

* Fixing the handling of Positive NaN in Math.Min for float/double (#70795)

* Adding tests validating Positive NaN for Max, MaxMagnitude, Min, and MinMagnitude

* Fixing the handling of Positive NaN in Math.Min for float/double

* Fixing the Max/Min code comments to use greater and lesser

* Adding a code comment clarifying the sign toggling behavior

* JIT: break loop canonicalization into two stages (#70809)

For a given loop, we need to separate out the true backedge, any
non-loop backedges, and any inner loop backedges so that they all
target distinct blocks.

Otherwise, we may violate assumptions that the loop entry dominates
all blocks in the loop and that all backedges that reach top come
from within the loop.

This seems simplest to do with two rounds of canonicalization, one
that moves the non-loop edges, and another that moves the true backedge.

Fixes #70802.

* Use `Array.Empty()` in `System.Reflection.Metadata`. (#70862)

It is now available in all frameworks it targets.

* Delete StaticallyLinked property from Microsoft.NETCore.Native.Unix.props (#70854)

This option has many issues. Anybody trying to experiment with static linking can add `<LinkerArg Include="-static" />` into the local file.

* Restore ArchivingUtils.AttemptSetLastWriteTime (#70617)

* Fix GC stress failure in LoaderAllocator::CompareExchangeValueInHandle (#70832)

InterlockedCompareExchangeT has to be called on a raw Object* to make the GC stress infrastructure happy.

* Small performance cleanups in S.S.Cryptography

* ARM64 - Optimize `i % 2` (#70599)

* Assign proper VNs to "shared constant" CSE defs (#70852)

* Assign proper VNs to shared CSE defs

They must be those of the original expression, not the "base" constant CSE creates.

* Add a test

* Enable IDE0054 (Use compound assignment) (#70564)

* Enable IDE0054 (Use compound assignment)

* Update src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs
Co-authored-by: NTanner Gooding <tagoo@outlook.com>
Co-authored-by: NTanner Gooding <tagoo@outlook.com>

* Use new byte[] span optimization in a few more places (#70665)

* Use new byte[] span optimization in a few more places

Separated out of larger change to use CreateSpan (these don't rely on that).

* Address PR feedback

* Improve TLS1.3 detection in registry for QUIC (#70730)

* Improve TLS1.3 detection in registry for QUIC

* Split client and server detection

* Code review feedback

* Generate method bodies for delegate Invoke methods (#70883)


There is a dataflow warning suppression in System.Linq.Expressions that assumes we'll always have an invocable method body for delegate Invoke method. We need one in IL. We don't in native code.

Emulate what IL Linker does and generate a method body. This is a size regression.

Suppression: https://github.com/dotnet/runtime/blob/3b2883b097a773715ca84056885e0ca1488da36e/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/TypeUtils.cs#L906-L912

Fixes #70880.

* Avoid crashing on unresolved dependencies (#70871)

Fixes #70815.

* Enable IDE0020 (Use pattern matching) (#70523)

* Enable IDE0020 (Use pattern matching)

* Update src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs
Co-authored-by: NBuyaa Namnan <buyankhishig.namnan@microsoft.com>

* Update variable naming
Co-authored-by: NBuyaa Namnan <buyankhishig.namnan@microsoft.com>

* Fix failure building two libraries tests (#70881)

Microsoft.CSharp was hitting an issue due to a vararg constructor. We don't support varargs. They shouldn't make it into the dependency graph. We are already checking in many places. We were erroneously thinking a vararg constructor with no mandatory arguments is a default constructor.

Runtime.InteropServices were crashing because we got a MulticastDelegate type into a codepath that expects a MulticastDelegate descendant.

* Use hash/hmac one shots in NTLM (#70857)
Co-authored-by: NStephen Toub <stoub@microsoft.com>

* Unpin locals, attempt 2 (#70655)

Contributes to #40553

* Replace a few instances of PtrToStructure with more efficient marshalling (#70866)

* Fix for timer scheduling happening on the incorrect thread when wasm threading is enabled (#70863)

* Add event to capture min/max threads (#70063)

Event ThreadPoolMinMaxThreads added. 

Parameters are:
            ushort MinWorkerThreads
            ushort MaxWorkerThreads
            ushort MinIOCompletionThreads
            ushort MaxIOCompletionThreads
            ushort ClrInstanceID

It is fired in the ThreadPool constructor and in the SetMinThreads/SetMaxThreads functions.

* [wasm] Add support for per-project customization of helix work items (#70461)

* [wasm] Add support for per-project customization of helix work items

Currently, for sending tests to helix:
1. the project binaries are zipped, as part of the project build
2. then separate helix targets files build that adds helix items for
   those zip files.
    - for wasm, we test with multiple 'scenarios' - like v8, browser, and
    nodejs.
    - so, 3 helix work items are submitted per zip file

- If a test project needs to have any customizations, for example, for
  testing crypto with a managed implementation, and subtlecrypto, which
  would require:
  - passing different arguments to xharness, in case of managed, and
    subtlecrypto
  - and this should be done only for the browser case
  - Currently, this would need this would need to be done in
  `sendtohelix-wasm.targets` special casing for the test project, and
  scenario.

- We add support for importing `$(ProjectName).helix.targets`, and
  calling a special target in that to add helix items, as needed.

- This targets file can be set in the test project like:
```xml
<HelixTargetsFile Condition="'$(TargetOS)' == 'Browser'">wasm.helix.targets</HelixTargetsFile>
```
  - it will get deployed next to the zip file, and picked up automatically

```xml
<Project>
  <PropertyGroup>
    <_CryptoProjectName>System.Security.Cryptography.Tests</_CryptoProjectName>
    <System_Security_Cryptography_Tests_TargetName Condition="'$(Scenario))' == 'WasmTestOnBrowser'">System_Security_Cryptography_Tests_Targ
et</System_Security_Cryptography_Tests_TargetName>
  </PropertyGroup>

  <Target Name="System_Security_Cryptography_Tests_Target">
    <ItemGroup>
      <HelixWorkItem Include="$(Scenario)-managed-$(_CryptoProjectName)">
        <PayloadArchive>$(TestArchiveTestsDir)$(_CryptoProjectName).zip</PayloadArchive>
        <Command>$(HelixCommand)</Command>
        <Timeout>$(_workItemTimeout)</Timeout>
      </HelixWorkItem>

      <HelixWorkItem Include="$(Scenario)-subtlecrypto-System.Security.Cryptography.Tests">
        <PayloadArchive>$(TestArchiveTestsDir)$(_CryptoProjectName).zip</PayloadArchive>
        <Command>$(HelixCommand)</Command>
        <Timeout>$(_workItemTimeout)</Timeout>

        <PreCommands Condition="'$(OS)' == 'Windows_NT'">set &quot;WasmXHarnessArgs=--web-server-use-cors&quot;</PreCommands>
        <PreCommands Condition="'$(OS)' != 'Windows_NT'">export &quot;WasmXHarnessArgs=--web-server-use-cors&quot;</PreCommands>
      </HelixWorkItem>
    </ItemGroup>
  </Target>
```

- The targets file *must* have these:
    - a property named like `System_Security_Cryptography_Tests_TargetName`, for a
      test project named `System.Security.Cryptography.Tests`
    - if this property is not set, then the default behavior of adding
      work items will run
    - The target should add any items it needs to to `@(HelixWorkItem)`.
      - Examples of adding these can be seen in `sendtohelix*` project files

- Remember that all these properties, and targets get imported into the
  msbuild *global* namespace, so make sure to use unique names to avoid
  conflicts with other test projects.

Future work: this commit only enables it for wasm/library tests, but it should
be easy to extract it out, but needs some testing.

* [wasm] Helix: test with, and without subtle crypto

* disable non-wasm builds

* address review feedback

* Address review feedback

* Fix typo

* Revert "disable non-wasm builds"

This reverts commit 7ef99e81f82200189dd3f61eeaf00d6ca4ced6d4.

* Update src/libraries/System.Security.Cryptography/tests/wasm.helix.targets
Co-authored-by: NEric Erhardt <eric.erhardt@microsoft.com>

* Address review feedback

* remove debug spew

* Change the way helix extension targets are discovered.

The new approach:

To run a custom project specific target for adding/editing @(HelixWorkItem):

- In the project add:
    `<HelixTargetsFile Condition="'$(TargetOS)' == 'Browser'">wasm.helix.targets</HelixTargetsFile>`

    - This file gets copied next to the test archive as $(MSBuildProjectName).helix.targets

- In this `wasm.helix.targets` file, add to $(HelixExtensionTargets) to run your custom target

```xml
  <PropertyGroup Condition="'$(IsRunningLibraryTests)' == 'true' and '$(Scenario)' == 'WasmTestOnBrowser'">
    <HelixExtensionTargets>$(HelixExtensionTargets);_AddHelixCrypoItems</HelixExtensionTargets>
```

- The extension target will be called after the default items are added
  to `@(HelixWorkItem)`.
- Useful properties to condition on: $(Scenario), $(IsRunningLibraryTests)
- And add to, change, or remove from @(HelixWorkItem)

Example:
```xml
  <Target Name="_AddHelixCrypoItems">
    <ItemGroup>
      <!-- remove the existing item -->
      <HelixWorkItem Remove="@(HelixWorkItem)" Condition="'%(OriginalFileName)' == '$(_CryptoProjectName)'" />

        <!-- add two new ones - managed, and subtylecrypto -->
      <HelixWorkItem Include="$(WorkItemPrefix)managed-$(_CryptoProjectName)">
        <PayloadArchive>$(TestArchiveTestsDir)$(_CryptoProjectName).zip</PayloadArchive>
        <Command>$(HelixCommand)</Command>
        <Timeout>$(_workItemTimeout)</Timeout>
        <OriginalFileName>$(_CryptoProjectName)</OriginalFileName>
      </HelixWorkItem>

      <HelixWorkItem Include="$(WorkItemPrefix)subtlecrypto-$(_CryptoProjectName)">
        <PayloadArchive>$(TestArchiveTestsDir)$(_CryptoProjectName).zip</PayloadArchive>
        <Command>$(HelixCommand)</Command>
        <Timeout>$(_workItemTimeout)</Timeout>
        <OriginalFileName>$(_CryptoProjectName)</OriginalFileName>

        <PreCommands Condition="'$(OS)' == 'Windows_NT'">set &quot;WasmXHarnessArgs=%WasmXHarnessArgs% --web-server-use-cop&quot;</PreCommands>
        <PreCommands Condition="'$(OS)' != 'Windows_NT'">export &quot;WasmXHarnessArgs=$WasmXHarnessArgs --web-server-use-cop&quot;</PreCommands>
      </HelixWorkItem>

      <_CryptoHelixItem Include="@(HelixWorkItem)"
                        Condition="$([System.String]::new('%(HelixWorkItem.Identity)').EndsWith('-$(_CryptoProjectName)'))" />
    </ItemGroup>

    <Error Text="Something went wrong. Expected to have only two work items for $(_CryptoProjectName). But got @(_CryptoHelixItem)"
           Condition="@(_CryptoHelixItem->Count()) != 2" />
  </Target>
```

* cleanup

* Move WBT specific stuff into the target too. This will make it simpler to move it off into a targets file later

* fix build

* fix libtests

* fix wbt

* [wasm] Bump helix timeout to 90mins for debugger tests on windows
Co-authored-by: NEric Erhardt <eric.erhardt@microsoft.com>

* Fix bug in Tar preventing extraction of hardlinks or entries starting with `.\` (#70853)

* Add PlatformDetection.SupportsHardLinkCreation property.

* Fix how paths are combined/joined and sanitized on extraction, to ensure paths with redundant segments get properly handled.

* Add tests that verify archives with entries whose paths start with .\, including the root folder itself.

* Re-enable the hardlink test, condition it to not run if platform does not support extraction of hardlinks.

* Remove unnecessary test - This same code is already being tested by TarReader_ExtractToFile_Tests.ExtractEntriesWithSlashDotPrefix

* Reuse test code that retrieves memory stream.

* Bump test data package version

* Add missing typeof(PlatformDetection) in ConditionalFact
Co-authored-by: Ncarlossanlop <carlossanlop@users.noreply.github.com>

* Remove #define Sleep (#70868)

* Remove #define Sleep

* Fix ICorDebugFunction2::GetVersionNumber for arm32. (#69901)

* Replace the remaining uses of Marshal.PtrToStructure in core networking (#70900)

* Rename ICMP interop to match Windows SDK names

* Add support for delegate GDV and method-based vtable GDV (#68703)

Add support for instrumenting delegate calls and vtable calls into method handle histograms. Use these histograms to do GDV for delegate calls and also support method-based GDV for vtable calls.

For instrumentation we now support class probes at interface call sites, method probes at delegate call sites and both class probes and method probes at vtable call sites. For vtable calls, when turned on, instrumentation produces both histograms as PGO data so that the JIT can later make the choice about what is the best form of guard to use at that site.

For guarding, there are some things to take into account. Delegate calls currently (practically) always point to precode, so this PR is just guarding on getFunctionFixedEntryPoint which returns the precode address, and this is generally quite cheap (same cost as class-based GDV). That's the case for delegates pointing to instance methods anyway, this PR does not support static methods yet -- those will be more expensive.

For vtable calls the runtime will backpatch the slots when tiering, so the JIT guards the address retrieved from the vtable against an indirection of the slot, which is slightly more expensive than a class-based guard.

Currently the instrumentation is enabled conditionally with COMPlus_JitDelegateProfiling=1 (for delegates) and COMPlus_JitVTableProfiling=1 (for vtable calls). Currently delegate profiling is turned on by default while vtable profiling is off by default.

* Use ArgumentNullException.ThrowIfNull in a few more places (#70897)

* Append the function pointer type (#70923)

The issue here was the recursion into PrettyPrintSigWorkerInternal
that would reset the buffer. Now, we pass in a new buffer and append
it when we return.

* [main] Update dependencies from dotnet/runtime dotnet/icu dotnet/xharness dotnet/runtime-assets dotnet/emsdk dotnet/roslyn-analyzers (#70476)

* Update dependencies from https://github.com/dotnet/runtime-assets build 20220608.1

Microsoft.DotNet.CilStrip.Sources , System.ComponentModel.TypeConverter.TestData , System.Drawing.Common.TestData , System.Formats.Tar.TestData , System.IO.Compression.TestData , System.IO.Packaging.TestData , System.Net.TestData , System.Private.Runtime.UnicodeData , System.Runtime.Numerics.TestData , System.Runtime.TimeZoneData , System.Security.Cryptography.X509Certificates.TestData , System.Text.RegularExpressions.TestData , System.Windows.Extensions.TestData
 From Version 7.0.0-beta.22281.1 -> To Version 7.0.0-beta.22308.1

* Update dependencies from https://github.com/dotnet/emsdk build 20220608.2

Microsoft.NET.Workload.Emscripten.Manifest-7.0.100
 From Version 7.0.0-preview.6.22281.1 -> To Version 7.0.0-preview.6.22308.2

* Update dependencies from https://github.com/dotnet/xharness build 20220610.1

Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit
 From Version 1.0.0-prerelease.22305.1 -> To Version 1.0.0-prerelease.22310.1

* Revert "Update dependencies from https://github.com/dotnet/emsdk build 20220608.2"

This reverts commit bbb4e156.

* Update dependencies from https://github.com/dotnet/icu build 20220609.1

Microsoft.NETCore.Runtime.ICU.Transport
 From Version 7.0.0-preview.6.22306.1 -> To Version 7.0.0-preview.6.22309.1

* Update dependencies from https://github.com/dotnet/emsdk build 20220608.2

Microsoft.NET.Workload.Emscripten.Manifest-7.0.100
 From Version 7.0.0-preview.6.22281.1 -> To Version 7.0.0-preview.6.22308.2

* Update dependencies from https://github.com/dotnet/runtime-assets build 20220610.1

Microsoft.DotNet.CilStrip.Sources , System.ComponentModel.TypeConverter.TestData , System.Drawing.Common.TestData , System.Formats.Tar.TestData , System.IO.Compression.TestData , System.IO.Packaging.TestData , System.Net.TestData , System.Private.Runtime.UnicodeData , System.Runtime.Numerics.TestData , System.Runtime.TimeZoneData , System.Security.Cryptography.X509Certificates.TestData , System.Text.RegularExpressions.TestData , System.Windows.Extensions.TestData
 From Version 7.0.0-beta.22281.1 -> To Version 7.0.0-beta.22310.1

* Update dependencies from https://github.com/dotnet/roslyn-analyzers build 20220610.1

Microsoft.CodeAnalysis.NetAnalyzers
 From Version 7.0.0-preview1.22302.1 -> To Version 7.0.0-preview1.22310.1

* Update dependencies from https://github.com/dotnet/runtime build 20220612.5

Microsoft.NET.Sdk.IL , Microsoft.NETCore.App.Runtime.win-x64 , Microsoft.NETCore.DotNetHost , Microsoft.NETCore.DotNetHostPolicy , Microsoft.NETCore.ILAsm , runtime.native.System.IO.Ports , System.Text.Json
 From Version 7.0.0-preview.6.22305.4 -> To Version 7.0.0-preview.6.22312.5

* Update dependencies from https://github.com/dotnet/icu build 20220613.1

Microsoft.NETCore.Runtime.ICU.Transport
 From Version 7.0.0-preview.6.22306.1 -> To Version 7.0.0-preview.6.22313.1

* Update dependencies from https://github.com/dotnet/xharness build 20220613.1

Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit
 From Version 1.0.0-prerelease.22310.1 -> To Version 1.0.0-prerelease.22313.1

* Update dependencies from https://github.com/dotnet/runtime-assets build 20220613.1

Microsoft.DotNet.CilStrip.Sources , System.ComponentModel.TypeConverter.TestData , System.Drawing.Common.TestData , System.Formats.Tar.TestData , System.IO.Compression.TestData , System.IO.Packaging.TestData , System.Net.TestData , System.Private.Runtime.UnicodeData , System.Runtime.Numerics.TestData , System.Runtime.TimeZoneData , System.Security.Cryptography.X509Certificates.TestData , System.Text.RegularExpressions.TestData , System.Windows.Extensions.TestData
 From Version 7.0.0-beta.22281.1 -> To Version 7.0.0-beta.22313.1

* Update dependencies from https://github.com/dotnet/emsdk build 20220613.1

Microsoft.NET.Workload.Emscripten.Manifest-7.0.100
 From Version 7.0.0-preview.6.22281.1 -> To Version 7.0.0-preview.6.22313.1

* [wasm] Wasm.Build.Tests: Disable strict version checks for emcc

Due to the way we have to update `dotnet/emsdk`, and get the update PRs
in `runtime`, the emsdk version can be mismatched. For example, if
`dotnet/emsdk` has already updated to `3.1.12`, but `dotnet/runtime` is
still on `3.1.7`. This is an expected scenario while working on updating
to a newer emscripten.

The version mismatch will still show up, but as a warning now.

* Update dependencies from https://github.com/dotnet/xharness build 20220614.1

Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit
 From Version 1.0.0-prerelease.22310.1 -> To Version 1.0.0-prerelease.22314.1

* [wasm] Wasm.Build.Tests: Update Skiasharp reference

The skiasharp dependent tests fail with:
`error : undefined symbol: _ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv`.

Update the reference to the latest package which added a binary compiled
for `3.1.7`.

* [wasm] Workaround a test failure in WBT

Currently, there is a mismatch between emsdk versions with the workload
emscripten packs using `3.1.12`, and the runtime being built with
`3.1.7`. And that is causing
`Wasm.Build.Tests.NativeLibraryTests.ProjectUsingSkiaSharp` to fail with:

```
EXEC : error : undefined symbol: _ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv (referenced by top-level compiled C/C++ code) [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
EXEC : warning : Link with `-sLLD_REPORT_UNDEFINED` to get more information on undefined symbols [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
EXEC : warning : To disable errors for undefined symbols use `-sERROR_ON_UNDEFINED_SYMBOLS=0` [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
EXEC : warning : __ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv may need to be added to EXPORTED_FUNCTIONS if it arrives from a system library [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
EXEC : error : undefined symbol: _ZNKSt3__221__basic_string_commonILb1EE20__throw_length_errorEv (referenced by top-level compiled C/C++ code) [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
EXEC : warning : __ZNKSt3__221__basic_string_commonILb1EE20__throw_length_errorEv may need to be added to EXPORTED_FUNCTIONS if it arrives from a system library [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
EXEC : error : Aborting compilation due to previous errors [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
emcc : error : '/datadisks/disk1/work/B1420981/w/ACC90933/e/dotnet-workload/packs/Microsoft.NET.Runtime.Emscripten.3.1.12.Node.linux-x64/7.0.0-preview.6.22313.1/tools/bin/node /datadisks/disk1/work/B1420981/w/ACC90933/e/dotnet-workload/packs/Microsoft.NET.Runtime.Emscripten.3.1.12.Sdk.linux-x64/7.0.0-preview.6.22313.1/tools/emscripten/src/compiler.js /datadisks/disk1/work/B1420981/t/tmp44tn7y2d.json' failed (returned 1) [/datadisks/disk1/work/B1420981/w/ACC90933/e/blz_nativeref_aot_Debug/blz_nativeref_aot_Debug.csproj]
```

This commit adds a temporary workaround to ignore the undefined symbols
for this specific test. And this should be removed when runtime is
updated to `3.1.12` .
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>
Co-authored-by: NAlexander Köplinger <alex.koeplinger@outlook.com>
Co-authored-by: NLarry Ewing <lewing@microsoft.com>
Co-authored-by: NAnkit Jain <radical@gmail.com>

* Harden for null byrefs (#70317)

* Remove enum_flag_Unrestored usage in boxing stubs.

* Add AND instruction (21h) to x86 decoder.

* Update mono for null ref in interpreter paths.

* Disable test on llvmfullaot and wasm

* Handle null destination for intrinsics.

* Use u8 in a few more places (#70894)

* Use u8 in a few more places

* A few more u8s

* Enable lib tests that used to fail with GC issues (#70831)

* enable lib tests that used to fail with GC issues

* excluding linq parallel test since that doesn't build

* Threading.Thread tests have issues

* Excluding new test failures

* Remove some dead code / branches (#70146)

* Remove some dead code / branches

Some signal amidst the noise in an lgtm.com report.

* Address PR feedback

* superpmi.py: Add `-jitoption` for asmdiffs (#70939)

The new `-jitoption` option passes the argument options to both baseline and diff
compilers. This is a convenience option: there already is `-base_jit_option` and
`-diff_jit_option` to specify passing options to either baseline or diff.

The name of the option is the same as that used for `replay`.

* EventLogException is missing the original win32 error code (#70629)

* Enable IDE0071 (Simplify interpolation) (#70918)

* Enable IDE0100 (Remove redundant equality) (#70896)

* Enable IDE0065 (Misplaced using directive) (#70919)

* Optimization for full range checks (#70145) (#70222)

* Update C# compiler (#70947)

Brings in support for required members

* Allow ValueListBuilder to work with empty scratch spans (#70917)

* Enable IDE0030 (Use coalesce expression) (#70948)

* Do not reuse implicit byrefs for by-value args (#70955)

* Do not reuse implicit byrefs for by-value args

* Add a test

* Enable `TYP_STRUCT` `LCL_VAR/LCL_FLD` call args on Windows x64 (#70777)

* Fix forward sub

* Enable folding in local morph

* Morph: TYP_STRUCT LCL_FLD

* Make SuperPMI more explicit about JIT in error messages (#70938)

This makes it easier to figure out which JIT failed in asmdiffs scenarios.

e.g.,
```
[10:40:50] ERROR: Method 3673 of size 3107 failed to load and compile correctly by JIT2 (C:\gh\runtime\artifacts\tests\coreclr\windows.x64.Checked\Tests\Core_Root\clrjit_universal_arm64_x64.dll).
[10:40:50] ERROR: Method 3673 of size 3107 failed to load and compile correctly by JIT1 (C:\gh\runtime2\artifacts\tests\coreclr\windows.x64.Checked\Tests\Core_Root\clrjit_universal_arm64_x64.dll).
```

* Fix illumos-x64 build (#70956)

* Disable W^X on macOS under Rosetta emulation (#70912)

* Disable W^X on macOS under Rosetta emulation

Apple has informed us that double mapping doesn't work properly
on Rosetta emulation. This change disables W^X if Rosetta is detected.

* Reflect PR feedback

* Add support for randomized guard stack cookies (#70806)

The compiler was generating GS cookies, but the cookie was always an ASCII encoding of "Hi, mom!".

Make the cookie properly per-process randomized.

The randomization algorithm is same as in the CoreCLR VM.

Fixes #70071.

* Fixes #64159 - JsonSerializerContext source generation fails with keyword identifiers (#66876)

* Fixes #64159 - initial implementation

* Tidy up, and add test for ignored reserved-keyword-named property

* PR feedback - use same approach as logging generator

* PR feedback

* Update src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs
Co-authored-by: NAdeel Mujahid <3840695+am11@users.noreply.github.com>

* PR feedback - rename ExactNameSpecifiedInSourceCode

* PR feedback - use extracted (and renamed) local variable

* Remove commented code

* Added `IsVerbatimName` as extension method

* Support fields with verbatim names (@)

* Use alternative method for checking for verbatim names

* Uses `SyntaxFacts` to determine if escaping is needed

* Remove extension method

* Modified source generator test to include a verbatim field

* Minor typo
Co-authored-by: NAdeel Mujahid <3840695+am11@users.noreply.github.com>

* [main] Update dependencies from dotnet/arcade (#70662)
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>

* Enable IDE0031 (Use null propagation) (#70965)

* Fix nullable annotations on MailAddress.TryCreate (#70943)

* [QUIC] Removes abstract providers and mock from S.N.Quic (#70421)

* Removed abstract providers and mock from S.N.Quic

* Removed provider and replaced with statics on Listener and Connection

* Added assert

* Stop wrapping SIMD nodes in OBJs (#70888)

* Upstream coreclr and pal changes to support powerpc (ppc64le) architecture  (#69105)

* coreclr pal layer chanegs.

* Updated the system arch for power architecture.

* Fixed the failing PAL SXS exception_handling test case

* replaced gint with gint64 to avoid overflow and this has fixed the segmentation fault issue.

* coreclr pal layer chanegs.

* Fixed the failing PAL SXS exception_handling test case

* coreclr pal layer chanegs.

* Updated the system arch for power architecture.

* Fixed the failing PAL SXS exception_handling test case

* replaced gint with gint64 to avoid overflow and this has fixed the segmentation fault issue.

* coreclr pal layer chanegs.

* Fixed the failing PAL SXS exception_handling test case

* Removing intsafe.h file as main does not have this file now.(Already removed in commit 27195f67)
Co-authored-by: NAlhad Deshpande <Alhad.Deshpande1@ibm.com>

* Collections contain stale object IDs (#70924)

It looks like the collections contain stale
ObjectID values. These collection should
be purged between GCs.

* Minor refactoring for `UpgradeToRegexGeneratorAnalyzer` (#70767)

* Fix arm64 funclet frame type 5 (#70922)

* Fix arm64 funclet frame type 5

* Add code to stress arm64 funclet frame type 5

This can be forced using `COMPlus_JitSaveFpLrWithCalleeSavedRegisters=3`,
or will be enabled under stress.

* Add a regression test

* Fix funclet frame type 5 alignment calculation

* Fix a couple bugs; improve documentation

1. Improve the frame shape pictures, especially for arm64 funclet frames. Include the
MonitorAcquired element and OSR pad.
2. Fix bug for `SP_to_PSP_slot_delta` for funclet frame type 4 for OSR: don't include osrPad.
3. Fix bug with funclet frame type 5 for `SP_to_FPLR_save_delta` using wrong aligned func size;
would be incorrect if one and two SP adjustment full frame aligned sizes are different (e.g.,
if two SP adjustment required two alignment slots and one SP adjustment thus required none).

* Fix default log color behavior when console is redirected (#70504)

* JIT: Model string literal objects as invariant and non-GLOB_REF (#70986)

* Model string literals as invariant/non GLOB_REF

* String literals are never null

* Add support for cross module inlining and cross module generic compilation to Crossgen2 (#68919)

* Add support for cross module inlining and cross module generic compilation to Crossgen2
- Refactor Module into ModuleBase and Module
  - The goal is to have allow a subset version of Module which can only hold refs, this is to be used by the manifest module in an R2R image to allow for version resilient cross module references.
  - Update handling of ModuleBase so that its used everywhere that tokens are parsed from R2R
  - Remove ENCODE_MODULE_ID_FOR_STATICS and ENCODE_ACTIVE_DEPENDENCY
    - These were only used for NGEN, and conflict with easy impelmentation for the ModuleBase concept
  - Remove locking in ENCODE_STRING_HANDLE processing, and tweak comments. Comments applied to the removed ngen based code, and the lock was only necessary for the old ngen thing.
  - Adjust ComputeLoaderModuleWorker for locating loader module
    - Follow comment more accurately, to avoid putting every generic into its definition module. This will make R2R function lookup able to find compiled instantiations in some cases. This may be what we want long term, it may not.
  - Remove MemberRefToDesc map and replace with LookupMap like the other token types. We no longer make use of the hot table, so this is more efficient
    - Also reduces complexity of implementation of ModuleBase

- Build fixup to describe a single method as a standalone blob of data
  - There are parallel implementations in Crossgen2 and in the runtime
  - They produce binary identical output
  - Basic R2RDump support for new fixup

- Adjust module indices used within the R2R format to support a module index which refers to the R2R manifest metadata. This requires bumping the R2R version to 6.2
  - Add a module index between the set of assembly refs in the index 0 module and the set of assembly refs in the R2R manifest metadata

- Adjust compilation dependency rules to include a few critical AsyncStateMachineBox methods

- Remove PEImage handling of native metadata which was duplicative

- Do not enable any more devirtualization than was already in use, even in the cross module compilation scenario. In particular, do not enable devirtualization of methods where the decl method isn't within the version bubble, even if the decl method could be represented with a cross-module reference token. (This could be fixed, but is out of scope for this initial investigation)

Make the compilation deterministic in this new model, even though we are generating new tokens on demand
  - Implement this by detecting when we need new tokens during a compile, and recompiling with new tokens when necessary
  - This may result in compiling the same code as much as twice

Compile the right set of methods with cross module inlining enabled
- Add support for compiling the called virtual methods on generic types
  - This catches the List<T> and Dictionary<TKey,TValue> scenarios

- Add command line switches to enable/disable the new behavior
  - By default the new behavior is not enabled

* Implement Vector128 version of System.Buffers.Text.Base64 DecodeFromUtf8 and EncodeToUtf8 (#70654)

* Implement Vector128 version of System.Buffers.Text.Base64.DecodeFromUtf8

Rework the SS3 into a Vector128 version, and add Arm64 support.

* SSE3 improvements

* Remove superfluous bitwise And

* Add comment to SimdShuffle

* Inline SimdShuffle

* Implement Vector128 version of System.Buffers.Text.Base64.EncodeToUtf8

* Ensure masking on SSE3

Change-Id: I319f94cfc51d0542ae4eb11a8d48b3eb8180553f
CustomizedGitHooks: yes

* Restore asserts and move zero inside the loop

* Neater C# code

Change-Id: I2cbe14f4228f8035e7d213b5b58815c4eee35563
CustomizedGitHooks: yes

* Make SimdShuffle consistent across X64 and Arm64

* Better looking multiply

* Use `gtEffectiveVal` for `GT_ADD` op1 in `optCreateAssertion` (#70228)

* Initial work for comma hoisting in cse

* Formatting

* Adding more ops to comma hoisting

* Set regnum

* Update optcse.cpp

* Using effectiveval instead

* Convert fallback path of GetCommandLineArgs to managed (#70608)

* P/Invoke definition

* Use P/Invoke in managed code

* Update managed call site

* Add test using private reflection

* Native command line should be superset of managed
Co-authored-by: NJan Kotas <jkotas@microsoft.com>

* [wasm] Enabled WasmTestOnBrowser run on Windows for Browser. (#70890)

* Enabled tests - no timeout with new ems. Keeping disabled tests failing from other reasons.

* Added @radical's suggestion.

* Test CI- enable test that are throwing in Debug.

* [wasm][debugger] Fix side effect on Firefox of getting bytes from loaded_files using debugger protocol (#70990)

* Fix 70983

* fix typo

* Fix compilation

* Add AddSystemd() and AddWindowsService() IServiceCollection extension methods (#68580)

* Add AddSystemd() IServiceCollection extension method

* Add AddWindowsService() IServiceCollection extension method

* Don't default to CWD if in C:\Windows\system32
- instead, when CWD is C:\Windows\system32 Hosting will use AppContext.BaseDirectory. This way Windows apps and services that are launched will work by default. HostApplicationBuilder.ContentRootPath can't be changed after construction, so setting it to a workable default for Windows apps.
Co-authored-by: NEric Erhardt <eric.erhardt@microsoft.com>
Co-authored-by: NMartin Costello <martin@martincostello.com>

* Use RemoteExecutor

* Update src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/HostTests.cs

* Skip test on Windows nano server

* Respond to PR feedback
Co-authored-by: NEric Erhardt <eric.erhardt@microsoft.com>
Co-authored-by: NMartin Costello <martin@martincostello.com>

* [main] Update dependencies from dotnet/runtime dotnet/xharness dotnet/icu dotnet/emsdk (#70991)

* Update dependencies from https://github.com/dotnet/runtime build 20220619.5

Microsoft.NET.Sdk.IL , Microsoft.NETCore.App.Runtime.win-x64 , Microsoft.NETCore.DotNetHost , Microsoft.NETCore.DotNetHostPolicy , Microsoft.NETCore.ILAsm , runtime.native.System.IO.Ports , System.Text.Json
 From Version 7.0.0-preview.6.22312.5 -> To Version 7.0.0-preview.6.22319.5

* Update dependencies from https://github.com/dotnet/xharness build 20220620.1

Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit
 From Version 1.0.0-prerelease.22314.1 -> To Version 1.0.0-prerelease.22320.1

* Update dependencies from https://github.com/dotnet/icu build 20220620.2

Microsoft.NETCore.Runtime.ICU.Transport
 From Version 7.0.0-preview.6.22313.1 -> To Version 7.0.0-preview.6.22320.2

* Update dependencies from https://github.com/dotnet/emsdk build 20220620.1

Microsoft.NET.Workload.Emscripten.Manifest-7.0.100
 From Version 7.0.0-preview.6.22313.1 -> To Version 7.0.0-preview.6.22320.1
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>

* Windows/Arm64: Use 8.1 atomic instructions if they are available (#70921)

* Use Fast compareexchange, acquire/release

* working windows version

* remove printf

* some more #ifdef

* fix some #ifdef

* optimize EnterObjMonitorHelperSpin

* Remove FastInterlockedCompareExchange64 for now

* Add ZipArchiveEntry.IsEncrypted for password-protection detection (#70036)

* Add ZipArchiveEntry.IsEncrypted for password-protection detection

* Apply suggestions from code review
Co-authored-by: NDavid Cantú <dacantu@microsoft.com>

* Run GenerateReferenceAssemblySource for System.IO.Compression

* Revert WriteAsync default parameter value removal

* Update DeflateStream.WriteAsync to include the default param value

* Revert unrelated change from GenerateReferenceAssemblySource

* Revert unrelated change after syncing with GenerateReferenceAssemblySource
Co-authored-by: NDavid Cantú <dacantu@microsoft.com>

* Exposing IRootFunctions.Hypot and IRootFunctions.Root (#71010)

* Exposing IRootFunctions.Hypot and IRootFunctions.Root

* Adding tests for IRootFunctions.Hypot and IRootFunctions.Root

* Add TarEntry conversion constructors (#70325)

* ref: Conversion constructors

* src: Conversion constructors

* tests: Conversion constructors

* [wasm] Wasm.Build.Tests: disable tests failing on CI (#71020)

* [wasm] Wasm.Build.Tests: disable tests failing on CI

.. due to being oomkill'ed.

* [wasm] Don't fail the job when firefox tests fail, as they are known to be unstable

* Remove allocation in ImmutableArray Builder Sort (#70850)

* Remove allocation in ImmutableArray Builder Sort

`ImmutableArray<T>.Builder.Sort(Comparison<T> comparison)` allocates a new instance of `Comparer<T>` using `comparison`. Then `ArraySort` allocates a new delegate from `comparer.Compare`. Both allocations can be eliminated by calling `Array.Sort<T>(T[] array, Comparison<T> comparison)` directly.

* Sort only valid range of array

* Use MemoryExtensions.Sort where available.

* Update src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs

Fix spelling mistake.
Co-authored-by: NEirik Tsarpalis <eirik.tsarpalis@gmail.com>
Co-authored-by: NEirik Tsarpalis <eirik.tsarpalis@gmail.com>

* [Android] Make sure AdditionalTimeZoneChecks trait is added to xunit-excludes (#70974)

The trait is supposed to be included in System.Runtime tests by default, but wasn't because the _withoutCategories property was in tests.props. As a result, the property was resolved before the .csproj properties. This fix moves the property definition to tests.targets.

Fixes #70482

* Use LastIndexOfAny in GetFileName_Windows (#71032)

* Avoid unnecessary allocations in SanitizeEntryFilePath (#71034)

* Fix Ordinal Ignore Case string compare (#71022)

* Move allocation of command line argument array to C# (#71021)

Also, avoid redundant allocation of managed string for each command line argument.

* Add markdown readme for System.Reflection.MetadataLoadContext (#70610)

* Create README.md

* set red zone size 512 for powerpc64. (#70885)

* Ensure consistent reflectability for generic methods (#70977)

If we have a method body for `SomeMethod<Foo>` and `SomeMethod<T>` was decided to be reflection-visible, ensure `SomeMethod<Foo>` is also reflection-visible.

* Implement NegotiateAuthentication API (#70720)

* WIP: Add implementation of NegotiateAuthentication

Switch System.Net.Http to use NegotiateAuthentication
Fix IsCompleted in managed NTLM implementation

* WIP: Update error code mapping

* Spanify input of GetOutgoingBlob

* Update comments

* Move NegotiateStreamPal.Encrypt/Decrypt to shared sources. Unix implementation already had them and they get trimmed anyway.

* Revert accidental change

* Build fixes.

* Fix error handling condition

* Update error mapping based on HttpListener usage.

* WIP: HttpListener test

* Move workaround from HttpListener to low-level SSPI code

* Fix build

* Clean up

* Revert "WIP: HttpListener test"

This…

* Revert "Sfh fix tests (#8)" (#9)

This reverts commit 5776aad0f1b35b6fdce1bca9407bcda4ed73e17f.

* Apply interop suggestions

* Verify non-nullability either of handle or path

* Small syntax fix

* Add null-validation

* Move population into private helper method

See comment by @stephentoub

* Fix null-handling

* Add more debug assertions
Co-Authored-By: NDavid Cantú <jozkyy@gmail.com>

* Add code documentation

Adapted from MSDN

* Address documentation feedback
Co-Authored-By: NDavid Cantú <jozkyy@gmail.com>

* Update src/libraries/System.Private.CoreLib/src/System/IO/File.cs
Co-authored-by: NDavid Cantú <dacantu@microsoft.com>
Co-authored-by: NTom Deseyn <tom.deseyn@gmail.com>
Co-authored-by: NBrennan <brecon@microsoft.com>
Co-authored-by: NEgor Bogatov <egorbo@gmail.com>
Co-authored-by: NBruce Forstall <brucefo@microsoft.com>
Co-authored-by: NMiha Zupan <mihazupan.zupan1@gmail.com>
Co-authored-by: NSingleAccretion <62474226+SingleAccretion@users.noreply.github.com>
Co-authored-by: NPavel Savara <pavelsavara@microsoft.com>
Co-authored-by: NEgor Chesakov <Egor.Chesakov@microsoft.com>
Co-authored-by: NAnkit Jain <radical@gmail.com>
Co-authored-by: NJeremy Koritzinsky <jekoritz@microsoft.com>
Co-authored-by: NSantiago Fernandez Madero <safern@microsoft.com>
Co-authored-by: NElinor Fung <elfung@microsoft.com>
Co-authored-by: NDan Moseley <danmose@microsoft.com>
Co-authored-by: NAndy Ayers <andya@microsoft.com>
Co-authored-by: NTomáš Rylek <trylek@microsoft.com>
Co-authored-by: NAndrew Au <andrewau@microsoft.com>
Co-authored-by: NWill Smith <lol.tihan@gmail.com>
Co-authored-by: NTlakaelel Axayakatl Ceja <tlakaelel.ceja@microsoft.com>
Co-authored-by: NJeremy Barton <jbarton@microsoft.com>
Co-authored-by: NPeter Sollich <petersol@microsoft.com>
Co-authored-by: NIlona Tomkowicz <32700855+ilonatommy@users.noreply.github.com>
Co-authored-by: NMaxim Lipnin <v-maxlip@microsoft.com>
Co-authored-by: NMarek Fišera <mara@neptuo.com>
Co-authored-by: NPavel Savara <pavel.savara@gmail.com>
Co-authored-by: NAlexander Köplinger <alex.koeplinger@outlook.com>
Co-authored-by: NStephen Toub <stoub@microsoft.com>
Co-authored-by: NMichal Strehovský <MichalStrehovsky@users.noreply.github.com>
Co-authored-by: NEirik Tsarpalis <eirik.tsarpalis@gmail.com>
Co-authored-by: Nyowl <scott.waye@hubse.com>
Co-authored-by: NEric StJohn <ericstj@microsoft.com>
Co-authored-by: NJan Kotas <jkotas@microsoft.com>
Co-authored-by: NParker Bibus <parkerbibus@microsoft.com>
Co-authored-by: NJan Vorlicek <jan.vorlicek@volny.cz>
Co-authored-by: Ngithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: NJamesNK <JamesNK@users.noreply.github.com>
Co-authored-by: NTanner Gooding <tagoo@outlook.com>
Co-authored-by: NWrzucher <maarraa@mail.ru>
Co-authored-by: NKevin Jones <kevin@vcsjones.com>
Co-authored-by: NAdam Sitnik <adam.sitnik@gmail.com>
Co-authored-by: NViktor Hofer <viktor.hofer@microsoft.com>
Co-authored-by: NJohan Lorensson <lateralusx.github@gmail.com>
Co-authored-by: NSteve Sanderson <SteveSandersonMS@users.noreply.github.com>
Co-authored-by: Ndotnet-maestro[bot] <42748379+dotnet-maestro[bot]@users.noreply.github.com>
Co-authored-by: Ndotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>
Co-authored-by: NPřemek Vysoký <premek.vysoky@microsoft.com>
Co-authored-by: NMike McLaughlin <mikem@microsoft.com>
Co-authored-by: NJakob Botsch Nielsen <Jakob.botsch.nielsen@gmail.com>
Co-authored-by: NThays Grazia <thaystg@gmail.com>
Co-authored-by: NAndy Gocke <angocke@microsoft.com>
Co-authored-by: NMaksym Koshovyi <maximkoshevoi61@gmail.com>
Co-authored-by: NZoltan Varga <vargaz@gmail.com>
Co-authored-by: NPavel Ivanov <ivanovpavelalex45@gmail.com>
Co-authored-by: NFloris Westerman <me@floriswesterman.nl>
Co-authored-by: NAdeel Mujahid <3840695+am11@users.noreply.github.com>
Co-authored-by: NVladimir Sadov <vsadov@microsoft.com>
Co-authored-by: NJulius Hardt <julius@postfach-hardt.de>
Co-authored-by: NAaron Robinson <arobins@microsoft.com>
Co-authored-by: NDavid Wrighton <davidwr@microsoft.com>
Co-authored-by: NWraith <wraith2@gmail.com>
Co-authored-by: NCarlos Sanchez <1175054+carlossanlop@users.noreply.github.com>
Co-authored-by: Ncarlossanlop <carlossanlop@users.noreply.github.com>
Co-authored-by: NEaton Zveare <eaton@eaton-works.com>
Co-authored-by: NJeff Handley <jeffhandley@users.noreply.github.com>
Co-authored-by: NChristopher Moore <chrisdcmoore@users.noreply.github.com>
Co-authored-by: NKatya Sokolova <esokolov@microsoft.com>
Co-authored-by: NJoshua Peterson <joshuap@unity3d.com>
Co-authored-by: Nimhameed <imhameed@microsoft.com>
Co-authored-by: NEric Erhardt <eric.erhardt@microsoft.com>
Co-authored-by: NGleb Balykov <g.balykov@samsung.com>
Co-authored-by: NMitchell Hwang <16830051+mdh1418@users.noreply.github.com>
Co-authored-by: NFan Yang <52458914+fanyang-mono@users.noreply.github.com>
Co-authored-by: NJo Shields <directhex@apebox.org>
Co-authored-by: NMaoni Stephens <Maoni0@users.noreply.github.com>
Co-authored-by: NKunal Pathak <Kunal.Pathak@microsoft.com>
Co-authored-by: NKoundinya Veluri <kouvel@users.noreply.github.com>
Co-authored-by: NSteve Pfister <steveisok@users.noreply.github.com>
Co-authored-by: NSteve Harter <steveharter@users.noreply.github.com>
Co-authored-by: NBradley Grainger <bgrainger@gmail.com>
Co-authored-by: NRoman Marusyk <Marusyk@users.noreply.github.com>
Co-authored-by: NRobert Henry <robhenry@microsoft.com>
Co-authored-by: NMaryam Ariyan <maryam.ariyan@microsoft.com>
Co-authored-by: NBar Arnon <i3arnon@gmail.com>
Co-authored-by: NRadek Zikmund <32671551+rzikm@users.noreply.github.com>
Co-authored-by: NFilip Navara <filip.navara@gmail.com>
Co-authored-by: NAndrii Kurdiumov <kant2002@gmail.com>
Co-authored-by: Nmadelson <1269046+madelson@users.noreply.github.com>
Co-authored-by: NAleksey Kliger (λgeek) <alklig@microsoft.com>
Co-authored-by: NVladimir Djurić <vladimir@djuric.si>
Co-authored-by: Nvdjuric <vladimir@LEGION21.localdomain>
Co-authored-by: NMarie Píchová <11718369+ManickaP@users.noreply.github.com>
Co-authored-by: NMeri Khamoyan <96171496+mkhamoyan@users.noreply.github.com>
Co-authored-by: NLarry Ewing <lewing@microsoft.com>
Co-authored-by: NFred Silberberg <frsilb@microsoft.com>
Co-authored-by: NTarek Mahmoud Sayed <tarekms@microsoft.com>
Co-authored-by: NNoah Falk <noahfalk@users.noreply.github.com>
Co-authored-by: NTomas Weinfurt <tweinfurt@yahoo.com>
Co-authored-by: NMarek Safar <marek.safar@gmail.com>
Co-authored-by: NTheodore Tsirpanis <teo@tsirpanis.gr>
Co-authored-by: NRolf Bjarne Kvinge <rolf@xamarin.com>
Co-authored-by: NKatelyn Gadd <kg@luminance.org>
Co-authored-by: NShubhanshu Saxena <54344426+shubhanshu02@users.noreply.github.com>
Co-authored-by: NStephen Toub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: NDavid Cantú <jozkyy@gmail.com>
Co-authored-by: NLevi Broderick <GrabYourPitchforks@users.noreply.github.com>
Co-authored-by: NFilip Navara <navara@emclient.com>
Co-authored-by: NHuo Yaoyuan <huoyaoyuan@hotmail.com>
Co-authored-by: NDennis Yemelyanov <10681271+dennis-yemelyanov@users.noreply.github.com>
Co-authored-by: NBadre BSAILA <54767641+pedrobsaila@users.noreply.github.com>
Co-authored-by: NBuyaa Namnan <bunamnan@microsoft.com>
Co-authored-by: NJuan Hoyos <juan.hoyos@microsoft.com>
Co-authored-by: NTlakaelel Axayakatl Ceja <tlakaelel_axayakatl@outlook.com>
Co-authored-by: NJan Vorlicek <janvorli@microsoft.com>
Co-authored-by: NLakshan Fernando <lakshanf@hotmail.com>
Co-authored-by: NAman Khalid <t-amankhalid@microsoft.com>
Co-authored-by: NBuyaa Namnan <buyankhishig.namnan@microsoft.com>
Co-authored-by: NJoni Aromaa <me@joniaromaa.fi>
Co-authored-by: NEduardo Velarde <32459232+eduardo-vp@users.noreply.github.com>
Co-authored-by: NMikhail Kurinnoi <m.kurinnoi@samsung.com>
Co-authored-by: NSychev Vadim <svd-main@outlook.com>
Co-authored-by: NSteve Dunn <steve@dunnhq.com>
Co-authored-by: NVikas Gupta <93921236+vikasgupta8@users.noreply.github.com>
Co-authored-by: NAlhad Deshpande <Alhad.Deshpande1@ibm.com>
Co-authored-by: NYoussef Victor <youssefvictor00@gmail.com>
Co-authored-by: NAlan Hayward <a74nh@users.noreply.github.com>
Co-authored-by: NStephen Halter <halter73@gmail.com>
Co-authored-by: NMartin Costello <martin@martincostello.com>
Co-authored-by: NGregory Bell <65985703+grbell-ms@users.noreply.github.com>
Co-authored-by: NMSDN.WhiteKnight <35516665+MSDN-WhiteKnight@users.noreply.github.com>
Co-authored-by: NAnton Firszov <antonfir@gmail.com>
Co-authored-by: NIvan Povazan <55002338+ivanpovazan@users.noreply.github.com>
Co-authored-by: NJérôme Laban <jerome.laban@nventive.com>
Co-authored-by: NHyungju Lee <leee.lee@samsung.com>
Co-authored-by: NVlad Brezae <brezaevlad@gmail.com>
Co-authored-by: Ndependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: NKrzysztof Wicher <mordotymoja@gmail.com>
Co-authored-by: Npanguye <105525993+panguye@users.noreply.github.com>
Co-authored-by: NWilliam Godbe <wigodbe@microsoft.com>
上级 82ca829e
......@@ -27,5 +27,22 @@ internal struct AttrList
internal static unsafe partial int setattrlist(string path, AttrList* attrList, void* attrBuf, nint attrBufSize, CULong options);
internal const uint FSOPT_NOFOLLOW = 0x00000001;
[LibraryImport(Libraries.libc, EntryPoint = "fsetattrlist", SetLastError = true)]
private static unsafe partial int fsetattrlist(int fd, AttrList* attrList, void* attrBuf, nint attrBufSize, CULong options);
internal static unsafe int fsetattrlist(SafeHandle handle, AttrList* attrList, void* attrBuf, nint attrBufSize, CULong options)
{
bool refAdded = false;
try
{
handle.DangerousAddRef(ref refAdded);
return fsetattrlist(handle.DangerousGetHandle().ToInt32(), attrList, attrBuf, attrBufSize, options);
}
finally
{
if (refAdded)
handle.DangerousRelease();
}
}
}
}
......@@ -17,6 +17,9 @@ internal enum UserFlags : uint
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_LChflags", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
internal static partial int LChflags(string path, uint flags);
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_FChflags", SetLastError = true)]
internal static partial int FChflags(SafeHandle fd, uint flags);
internal static readonly bool CanSetHiddenFlag = (LChflagsCanSetHiddenFlag() != 0);
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_LChflagsCanSetHiddenFlag")]
......
......@@ -24,5 +24,8 @@ internal struct TimeSpec
/// </returns>
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_UTimensat", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
internal static unsafe partial int UTimensat(string path, TimeSpec* times);
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_FUTimens", SetLastError = true)]
internal static unsafe partial int FUTimens(SafeHandle fd, TimeSpec* times);
}
}
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Kernel32
{
[StructLayout(LayoutKind.Sequential)]
internal struct BY_HANDLE_FILE_INFORMATION
{
internal uint dwFileAttributes;
internal FILE_TIME ftCreationTime;
internal FILE_TIME ftLastAccessTime;
internal FILE_TIME ftLastWriteTime;
internal uint dwVolumeSerialNumber;
internal uint nFileSizeHigh;
internal uint nFileSizeLow;
internal uint nNumberOfLinks;
internal uint nFileIndexHigh;
internal uint nFileIndexLow;
}
}
}
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Kernel32
{
[LibraryImport(Libraries.Kernel32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static unsafe partial bool GetFileInformationByHandle(SafeFileHandle hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
}
}
......@@ -25,12 +25,14 @@ public void InvalidParameters()
[Theory, MemberData(nameof(TrailingCharacters))]
public void SetAttributes_MissingFile(char trailingChar)
{
if (!CanBeReadOnly) return;
Assert.Throws<FileNotFoundException>(() => SetAttributes(GetTestFilePath() + trailingChar, FileAttributes.ReadOnly));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void SetAttributes_MissingDirectory(char trailingChar)
{
if (!CanBeReadOnly) return;
Assert.Throws<DirectoryNotFoundException>(() => SetAttributes(Path.Combine(GetTestFilePath(), "file" + trailingChar), FileAttributes.ReadOnly));
}
......
......@@ -7,6 +7,7 @@ namespace System.IO.Tests
{
public abstract class BaseGetSetAttributes : FileSystemTest
{
protected abstract bool CanBeReadOnly { get; }
protected abstract FileAttributes GetAttributes(string path);
protected abstract void SetAttributes(string path, FileAttributes attributes);
......
......@@ -28,6 +28,9 @@ public abstract class BaseGetSetTimes<T> : FileSystemTest
protected abstract T CreateSymlink(string path, string pathToTarget);
// When the item is a link, indicates whether the .NET API will get/set the link itself, or its target.
protected virtual bool ApiTargetsLink => true;
protected T CreateSymlinkToItem(T item)
{
// Creates a Symlink to 'item' (target may or may not exist)
......@@ -37,6 +40,7 @@ protected T CreateSymlinkToItem(T item)
protected abstract string GetItemPath(T item);
// requiresRoundtripping defines whether to convert DateTimeFormat 'a' to 'b' and then back to 'a' to verify the DateTimeFormat-conversion
public abstract IEnumerable<TimeFunction> TimeFunctions(bool requiresRoundtripping = false);
public class TimeFunction : Tuple<SetTime, GetTime, DateTimeKind>
......@@ -52,17 +56,27 @@ public static TimeFunction Create(SetTime setter, GetTime getter, DateTimeKind k
public SetTime Setter => Item1;
public GetTime Getter => Item2;
public DateTimeKind Kind => Item3;
public override string ToString()
{
return $"TimeFunction DateTimeKind.{Kind} Setter: {Setter.Method.Name} Getter: {Getter.Method.Name}";
}
}
private void SettingUpdatesPropertiesCore(T item)
private void SettingUpdatesPropertiesCore(T item, T? linkTarget = default)
{
Assert.All(TimeFunctions(requiresRoundtripping: true), (function) =>
{
bool isLink = linkTarget is not null;
// Checking that milliseconds are not dropped after setter.
// Emscripten drops milliseconds in Browser
DateTime dt = new DateTime(2014, 12, 1, 12, 3, 3, LowTemporalResolution ? 0 : 321, function.Kind);
function.Setter(item, dt);
DateTime result = function.Getter(item);
T getTarget = !isLink || ApiTargetsLink ? item : linkTarget;
DateTime result = function.Getter(getTarget);
Assert.Equal(dt, result);
Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());
......@@ -102,7 +116,7 @@ public void SettingUpdatesPropertiesWhenReadOnly()
[PlatformSpecific(~TestPlatforms.Browser)] // Browser is excluded as it doesn't support symlinks
[InlineData(false)]
[InlineData(true)]
public void SettingUpdatesPropertiesOnSymlink(bool targetExists)
public void SettingPropertiesOnSymlink(bool targetExists)
{
// This test is in this class since it needs all of the time functions.
// This test makes sure that the times are set on the symlink itself.
......@@ -119,25 +133,37 @@ public void SettingUpdatesPropertiesOnSymlink(bool targetExists)
T link = CreateSymlinkToItem(target);
if (!targetExists)
{
SettingUpdatesPropertiesCore(link);
// Don't check when settings update the target.
if (ApiTargetsLink)
{
SettingUpdatesPropertiesCore(link, target);
}
}
else
{
// Get the target's initial times
IEnumerable<TimeFunction> timeFunctions = TimeFunctions(requiresRoundtripping: true);
DateTime[] initialTimes = timeFunctions.Select((funcs) => funcs.Getter(target)).ToArray();
// When properties update link, verify the target properties don't change.
IEnumerable<TimeFunction>? timeFunctions = null;
DateTime[]? initialTimes = null;
if (ApiTargetsLink)
{
timeFunctions = TimeFunctions(requiresRoundtripping: true);
initialTimes = timeFunctions.Select((funcs) => funcs.Getter(target)).ToArray();
}
SettingUpdatesPropertiesCore(link);
SettingUpdatesPropertiesCore(link, target);
// Ensure that we have the latest times.
if (target is FileSystemInfo fsi)
// Ensure target properties haven't changed.
if (ApiTargetsLink)
{
fsi.Refresh();
// Ensure that we have the latest times.
if (target is FileSystemInfo fsi)
{
fsi.Refresh();
}
DateTime[] updatedTimes = timeFunctions.Select((funcs) => funcs.Getter(target)).ToArray();
Assert.Equal(initialTimes, updatedTimes);
}
// Ensure the target's times haven't changed.
DateTime[] updatedTimes = timeFunctions.Select((funcs) => funcs.Getter(target)).ToArray();
Assert.Equal(initialTimes, updatedTimes);
}
}
......
......@@ -8,14 +8,21 @@ namespace System.IO.Tests
// Tests that are valid for File and FileInfo
public abstract class FileGetSetAttributes : BaseGetSetAttributes
{
[Theory]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SettingAttributes_Unix(FileAttributes attributes)
public void SettingAttributes_Unix_Normal()
{
string path = CreateItem();
AssertSettingAttributes(path, attributes);
AssertSettingAttributes(path, FileAttributes.Normal);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SettingAttributes_Unix_ReadOnly()
{
if (!CanBeReadOnly) return;
string path = CreateItem();
AssertSettingAttributes(path, FileAttributes.ReadOnly);
}
[Theory]
......@@ -28,13 +35,11 @@ public void SettingAttributes_OSXAndFreeBSD(FileAttributes attributes)
}
[Theory]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.System)]
[InlineData(FileAttributes.Archive)]
[InlineData(FileAttributes.Normal)]
[InlineData(FileAttributes.Temporary)]
[InlineData(FileAttributes.ReadOnly | FileAttributes.Hidden)]
[PlatformSpecific(TestPlatforms.Windows)]
public void SettingAttributes_Windows(FileAttributes attributes)
{
......@@ -42,6 +47,17 @@ public void SettingAttributes_Windows(FileAttributes attributes)
AssertSettingAttributes(path, attributes);
}
[Theory]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.ReadOnly | FileAttributes.Hidden)]
[PlatformSpecific(TestPlatforms.Windows)]
public void SettingAttributes_Windows_ReadOnly(FileAttributes attributes)
{
if (!CanBeReadOnly) return;
string path = CreateItem();
AssertSettingAttributes(path, attributes);
}
private void AssertSettingAttributes(string path, FileAttributes attributes)
{
SetAttributes(path, attributes);
......
......@@ -15,6 +15,7 @@ protected override string CreateItem(string path = null, [CallerMemberName] stri
protected override DirectoryInfo CreateInfo(string path) => new DirectoryInfo(path);
protected override void DeleteItem(string path) => Directory.Delete(path);
protected override bool IsDirectory => true;
protected override bool CanBeReadOnly => true;
[Theory]
[InlineData(FileAttributes.ReadOnly)]
......
......@@ -9,6 +9,7 @@ public class File_GetSetAttributes : BaseGetSetAttributes
{
protected override FileAttributes GetAttributes(string path) => File.GetAttributes(path);
protected override void SetAttributes(string path, FileAttributes attributes) => File.SetAttributes(path, attributes);
protected override bool CanBeReadOnly => false;
// Getting only throws for File, not FileInfo
[Theory, MemberData(nameof(TrailingCharacters))]
......
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.IO.Tests
{
public class GetSetAttributes_SafeFileHandle : FileGetSetAttributes
{
protected virtual SafeFileHandle OpenFileHandle(string path, FileAccess fileAccess) =>
File.OpenHandle(
path,
FileMode.OpenOrCreate,
fileAccess,
FileShare.None);
protected override bool CanBeReadOnly => false;
protected override FileAttributes GetAttributes(string path)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetAttributes(fileHandle);
}
protected override void SetAttributes(string path, FileAttributes attributes)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetAttributes(fileHandle, attributes);
}
[Fact]
public void NullArgumentValidation()
{
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetAttributes(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetAttributes(default(SafeFileHandle)!, (FileAttributes)0));
}
}
}
......@@ -4,9 +4,10 @@
namespace System.IO.Tests
{
// Concrete class to run common file attributes tests on the File class
public class File_GetSetAttributesCommon : FileGetSetAttributes
public sealed class File_GetSetAttributes_String : FileGetSetAttributes
{
protected override FileAttributes GetAttributes(string path) => File.GetAttributes(path);
protected override void SetAttributes(string path, FileAttributes attributes) => File.SetAttributes(path, attributes);
protected override bool CanBeReadOnly => true;
}
}
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public class File_GetSetTimes : StaticGetSetTimes
public abstract class File_GetSetTimes : StaticGetSetTimes
{
protected override bool CanBeReadOnly => true;
// OSX has the limitation of setting upto 2262-04-11T23:47:16 (long.Max) date.
// 32bit Unix has time_t up to ~ 2038.
private static bool SupportsLongMaxDateTime => PlatformDetection.IsWindows || (!PlatformDetection.Is32BitProcess && !PlatformDetection.IsOSXLike);
protected static bool SupportsLongMaxDateTime => PlatformDetection.IsWindows || (!PlatformDetection.Is32BitProcess && !PlatformDetection.IsOSXLike);
protected override bool CanBeReadOnly => true;
protected override string GetExistingItem(bool readOnly = false)
{
......@@ -32,6 +30,31 @@ protected override string GetExistingItem(bool readOnly = false)
protected override string CreateSymlink(string path, string pathToTarget) => File.CreateSymbolicLink(path, pathToTarget).FullName;
protected abstract void SetCreationTime(string path, DateTime creationTime);
protected abstract DateTime GetCreationTime(string path);
protected abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc);
protected abstract DateTime GetCreationTimeUtc(string path);
protected abstract void SetLastAccessTime(string path, DateTime lastAccessTime);
protected abstract DateTime GetLastAccessTime(string path);
protected abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc);
protected abstract DateTime GetLastAccessTimeUtc(string path);
protected abstract void SetLastWriteTime(string path, DateTime lastWriteTime);
protected abstract DateTime GetLastWriteTime(string path);
protected abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
protected abstract DateTime GetLastWriteTimeUtc(string path);
[Fact]
[PlatformSpecific(TestPlatforms.Linux)]
public void BirthTimeIsNotNewerThanLowestOfAccessModifiedTimes()
......@@ -42,11 +65,12 @@ public void BirthTimeIsNotNewerThanLowestOfAccessModifiedTimes()
// Set different values for all three
// Status changed time will be when the file was first created, in this case)
string path = GetExistingItem();
File.SetLastWriteTime(path, DateTime.Now.AddMinutes(1));
File.SetLastAccessTime(path, DateTime.Now.AddMinutes(2));
SetLastWriteTime(path, DateTime.Now.AddMinutes(1));
SetLastAccessTime(path, DateTime.Now.AddMinutes(2));
// Assert.InRange is inclusive.
Assert.InRange(File.GetCreationTimeUtc(path), DateTime.MinValue, File.GetLastWriteTimeUtc(path));
Assert.InRange(GetCreationTimeUtc(path), DateTime.MinValue, GetLastWriteTimeUtc(path));
}
[Fact]
......@@ -62,12 +86,12 @@ public async Task CreationTimeSet_GetReturnsExpected_WhenNotInFuture()
// Set the creation time to a value in the past that is between ctime and now.
await Task.Delay(600);
DateTime newCreationTimeUTC = System.DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(300));
File.SetCreationTimeUtc(path, newCreationTimeUTC);
DateTime newCreationTimeUtc = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(300));
Assert.Equal(newCreationTimeUTC, File.GetLastWriteTimeUtc(path));
SetCreationTimeUtc(path, newCreationTimeUtc);
Assert.Equal(newCreationTimeUTC, File.GetCreationTimeUtc(path));
Assert.Equal(newCreationTimeUtc, GetLastWriteTimeUtc(path));
Assert.Equal(newCreationTimeUtc, GetCreationTimeUtc(path));
}
public override IEnumerable<TimeFunction> TimeFunctions(bool requiresRoundtripping = false)
......@@ -75,60 +99,44 @@ public override IEnumerable<TimeFunction> TimeFunctions(bool requiresRoundtrippi
if (IOInputs.SupportsGettingCreationTime && (!requiresRoundtripping || IOInputs.SupportsSettingCreationTime))
{
yield return TimeFunction.Create(
((path, time) => File.SetCreationTime(path, time)),
((path) => File.GetCreationTime(path)),
SetCreationTime,
GetCreationTime,
DateTimeKind.Local);
yield return TimeFunction.Create(
((path, time) => File.SetCreationTimeUtc(path, time)),
((path) => File.GetCreationTimeUtc(path)),
SetCreationTimeUtc,
GetCreationTimeUtc,
DateTimeKind.Unspecified);
yield return TimeFunction.Create(
((path, time) => File.SetCreationTimeUtc(path, time)),
((path) => File.GetCreationTimeUtc(path)),
SetCreationTimeUtc,
GetCreationTimeUtc,
DateTimeKind.Utc);
}
yield return TimeFunction.Create(
((path, time) => File.SetLastAccessTime(path, time)),
((path) => File.GetLastAccessTime(path)),
SetLastAccessTime,
GetLastAccessTime,
DateTimeKind.Local);
yield return TimeFunction.Create(
((path, time) => File.SetLastAccessTimeUtc(path, time)),
((path) => File.GetLastAccessTimeUtc(path)),
SetLastAccessTimeUtc,
GetLastAccessTimeUtc,
DateTimeKind.Unspecified);
yield return TimeFunction.Create(
((path, time) => File.SetLastAccessTimeUtc(path, time)),
((path) => File.GetLastAccessTimeUtc(path)),
SetLastAccessTimeUtc,
GetLastAccessTimeUtc,
DateTimeKind.Utc);
yield return TimeFunction.Create(
((path, time) => File.SetLastWriteTime(path, time)),
((path) => File.GetLastWriteTime(path)),
SetLastWriteTime,
GetLastWriteTime,
DateTimeKind.Local);
yield return TimeFunction.Create(
((path, time) => File.SetLastWriteTimeUtc(path, time)),
((path) => File.GetLastWriteTimeUtc(path)),
SetLastWriteTimeUtc,
GetLastWriteTimeUtc,
DateTimeKind.Unspecified);
yield return TimeFunction.Create(
((path, time) => File.SetLastWriteTimeUtc(path, time)),
((path) => File.GetLastWriteTimeUtc(path)),
SetLastWriteTimeUtc,
GetLastWriteTimeUtc,
DateTimeKind.Utc);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't read root in appcontainer
[PlatformSpecific(TestPlatforms.Windows)]
public void PageFileHasTimes()
{
// Typically there is a page file on the C: drive, if not, don't bother trying to track it down.
string pageFilePath = Directory.EnumerateFiles(@"C:\", "pagefile.sys").FirstOrDefault();
if (pageFilePath != null)
{
Assert.All(TimeFunctions(), (item) =>
{
var time = item.Getter(pageFilePath);
Assert.NotEqual(DateTime.FromFileTime(0), time);
});
}
}
[Fact]
public void SetLastWriteTimeTicks()
{
......@@ -138,9 +146,9 @@ public void SetLastWriteTimeTicks()
File.WriteAllText(firstFile, "");
File.WriteAllText(secondFile, "");
File.SetLastAccessTimeUtc(secondFile, DateTime.UtcNow);
long firstFileTicks = File.GetLastWriteTimeUtc(firstFile).Ticks;
long secondFileTicks = File.GetLastWriteTimeUtc(secondFile).Ticks;
SetLastAccessTimeUtc(firstFile, DateTime.UtcNow);
long firstFileTicks = GetLastWriteTimeUtc(firstFile).Ticks;
long secondFileTicks = GetLastWriteTimeUtc(secondFile).Ticks;
Assert.True(firstFileTicks <= secondFileTicks, $"First File Ticks\t{firstFileTicks}\nSecond File Ticks\t{secondFileTicks}");
}
......@@ -151,10 +159,11 @@ public void SetUptoNanoseconds()
File.WriteAllText(file, "");
DateTime dateTime = DateTime.UtcNow;
File.SetLastWriteTimeUtc(file, dateTime);
long ticks = File.GetLastWriteTimeUtc(file).Ticks;
Assert.Equal(dateTime, File.GetLastWriteTimeUtc(file));
SetLastWriteTimeUtc(file, dateTime);
long ticks = GetLastWriteTimeUtc(file).Ticks;
Assert.Equal(dateTime, GetLastWriteTimeUtc(file));
Assert.Equal(ticks, dateTime.Ticks);
}
......@@ -166,11 +175,11 @@ public void SetDateTimeMax()
string file = GetTestFilePath();
File.WriteAllText(file, "");
DateTime dateTime = new DateTime(9999, 4, 11, 23, 47, 17, 21, DateTimeKind.Utc);
File.SetLastWriteTimeUtc(file, dateTime);
long ticks = File.GetLastWriteTimeUtc(file).Ticks;
DateTime dateTime = new(9999, 4, 11, 23, 47, 17, 21, DateTimeKind.Utc);
SetLastWriteTimeUtc(file, dateTime);
long ticks = GetLastWriteTimeUtc(file).Ticks;
Assert.Equal(dateTime, File.GetLastWriteTimeUtc(file));
Assert.Equal(dateTime, GetLastWriteTimeUtc(file));
Assert.Equal(ticks, dateTime.Ticks);
}
......@@ -183,9 +192,9 @@ public void SetLastAccessTimeTicks()
File.WriteAllText(firstFile, "");
File.WriteAllText(secondFile, "");
File.SetLastWriteTimeUtc(secondFile, DateTime.UtcNow);
long firstFileTicks = File.GetLastAccessTimeUtc(firstFile).Ticks;
long secondFileTicks = File.GetLastAccessTimeUtc(secondFile).Ticks;
SetLastWriteTimeUtc(firstFile, DateTime.UtcNow);
long firstFileTicks = GetLastAccessTimeUtc(firstFile).Ticks;
long secondFileTicks = GetLastAccessTimeUtc(secondFile).Ticks;
Assert.True(firstFileTicks <= secondFileTicks, $"First File Ticks\t{firstFileTicks}\nSecond File Ticks\t{secondFileTicks}");
}
}
......
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.IO.Tests
{
public class File_GetSetTimes_SafeFileHandle : File_GetSetTimes
{
protected virtual SafeFileHandle OpenFileHandle(string path, FileAccess fileAccess) =>
File.OpenHandle(
path,
FileMode.OpenOrCreate,
fileAccess,
FileShare.ReadWrite);
protected override bool CanBeReadOnly => false;
protected override bool ApiTargetsLink => false;
protected override void SetCreationTime(string path, DateTime creationTime)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetCreationTime(fileHandle, creationTime);
}
protected override DateTime GetCreationTime(string path)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetCreationTime(fileHandle);
}
protected override void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetCreationTimeUtc(fileHandle, creationTimeUtc);
}
protected override DateTime GetCreationTimeUtc(string path)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetCreationTimeUtc(fileHandle);
}
protected override void SetLastAccessTime(string path, DateTime lastAccessTime)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetLastAccessTime(fileHandle, lastAccessTime);
}
protected override DateTime GetLastAccessTime(string path)
{
using var fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetLastAccessTime(fileHandle);
}
protected override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetLastAccessTimeUtc(fileHandle, lastAccessTimeUtc);
}
protected override DateTime GetLastAccessTimeUtc(string path)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetLastAccessTimeUtc(fileHandle);
}
protected override void SetLastWriteTime(string path, DateTime lastWriteTime)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetLastWriteTime(fileHandle, lastWriteTime);
}
protected override DateTime GetLastWriteTime(string path)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetLastWriteTime(fileHandle);
}
protected override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.ReadWrite);
File.SetLastWriteTimeUtc(fileHandle, lastWriteTimeUtc);
}
protected override DateTime GetLastWriteTimeUtc(string path)
{
using SafeFileHandle fileHandle = OpenFileHandle(path, FileAccess.Read);
return File.GetLastWriteTimeUtc(fileHandle);
}
[Fact]
public void NullArgumentValidation()
{
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetCreationTime(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetCreationTime(default(SafeFileHandle)!, DateTime.Now));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetCreationTimeUtc(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetCreationTimeUtc(default(SafeFileHandle)!, DateTime.Now));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetLastAccessTime(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetLastAccessTime(default(SafeFileHandle)!, DateTime.Now));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetLastAccessTimeUtc(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetLastAccessTimeUtc(default(SafeFileHandle)!, DateTime.Now));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetLastWriteTime(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetLastWriteTime(default(SafeFileHandle)!, DateTime.Now));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.GetLastWriteTimeUtc(default(SafeFileHandle)!));
Assert.Throws<ArgumentNullException>("fileHandle", static () => File.SetLastWriteTimeUtc(default(SafeFileHandle)!, DateTime.Now));
}
}
}
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
namespace System.IO.Tests
{
public sealed class File_GetSetTimes_SafeFileHandle_Pathless : File_GetSetTimes_SafeFileHandle
{
protected override SafeFileHandle OpenFileHandle(string path, FileAccess fileAccess)
{
SafeFileHandle originHandle = base.OpenFileHandle(path, fileAccess);
// Create handle by ptr to force that `SafeFileHandle.Path` is `null`
SafeFileHandle newHandle = new(originHandle.DangerousGetHandle(), true);
originHandle.SetHandleAsInvalid();
return newHandle;
}
}
}
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using Xunit;
namespace System.IO.Tests
{
public class File_GetSetTimes_String : File_GetSetTimes
{
protected override bool CanBeReadOnly => true;
protected override string CreateSymlink(string path, string pathToTarget) => File.CreateSymbolicLink(path, pathToTarget).FullName;
protected override void SetCreationTime(string path, DateTime creationTime) => File.SetCreationTime(path, creationTime);
protected override DateTime GetCreationTime(string path) => File.GetCreationTime(path);
protected override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) => File.SetCreationTimeUtc(path, creationTimeUtc);
protected override DateTime GetCreationTimeUtc(string path) => File.GetCreationTimeUtc(path);
protected override void SetLastAccessTime(string path, DateTime lastAccessTime) => File.SetLastAccessTime(path, lastAccessTime);
protected override DateTime GetLastAccessTime(string path) => File.GetLastAccessTime(path);
protected override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) => File.SetLastAccessTimeUtc(path, lastAccessTimeUtc);
protected override DateTime GetLastAccessTimeUtc(string path) => File.GetLastAccessTimeUtc(path);
protected override void SetLastWriteTime(string path, DateTime lastWriteTime) => File.SetLastWriteTime(path, lastWriteTime);
protected override DateTime GetLastWriteTime(string path) => File.GetLastWriteTime(path);
protected override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) => File.SetLastWriteTimeUtc(path, lastWriteTimeUtc);
protected override DateTime GetLastWriteTimeUtc(string path) => File.GetLastWriteTimeUtc(path);
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't read root in appcontainer
[PlatformSpecific(TestPlatforms.Windows)]
public void PageFileHasTimes()
{
// Typically there is a page file on the C: drive, if not, don't bother trying to track it down.
string pageFilePath = Directory.EnumerateFiles(@"C:\", "pagefile.sys", new EnumerationOptions
{
AttributesToSkip = 0
}).FirstOrDefault();
if (pageFilePath != null)
{
Assert.All(TimeFunctions(), (item) =>
{
var time = item.Getter(pageFilePath);
Assert.NotEqual(DateTime.FromFileTime(0), time);
});
}
}
}
}
......@@ -7,6 +7,7 @@ namespace System.IO.Tests
{
public class FileInfo_GetSetAttributes : InfoGetSetAttributes<FileInfo>
{
protected override bool CanBeReadOnly => true;
protected override FileAttributes GetAttributes(string path) => new FileInfo(path).Attributes;
protected override void SetAttributes(string path, FileAttributes attributes) => new FileInfo(path).Attributes = attributes;
protected override FileInfo CreateInfo(string path) => new FileInfo(path);
......
......@@ -6,6 +6,7 @@ namespace System.IO.Tests
// Concrete class to run common file attributes tests on the FileInfo class
public class FileInfo_GetSetAttributesCommon : FileGetSetAttributes
{
protected override bool CanBeReadOnly => true;
protected override FileAttributes GetAttributes(string path) => new FileInfo(path).Attributes;
protected override void SetAttributes(string path, FileAttributes attributes) => new FileInfo(path).Attributes = attributes;
}
......
......@@ -34,7 +34,11 @@
<Compile Include="FileStream\LockUnlock.cs" />
<Compile Include="FileSystemTest.cs" />
<Compile Include="File\EncryptDecrypt.cs" />
<Compile Include="File\GetSetAttributesCommon.cs" />
<Compile Include="File\GetSetAttributes_String.cs" />
<Compile Include="File\GetSetAttributes_SafeFileHandle.cs" />
<Compile Include="File\GetSetTimes.cs" />
<Compile Include="File\GetSetTimes_SafeFileHandle.cs" />
<Compile Include="File\GetSetTimes_SafeFileHandle_Pathless.cs" />
<Compile Include="File\GetSetUnixFileMode.cs" />
<Compile Include="File\GetSetUnixFileMode_SafeFileHandle.cs" />
<Compile Include="File\Replace.cs" />
......@@ -99,6 +103,8 @@
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateFile.cs" Link="Common\Interop\Windows\Interop.CreateFile.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FILE_STANDARD_INFO.cs" Link="Common\Interop\Windows\Interop.FILE_STANDARD_INFO.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileInformationByHandleEx.cs" Link="Common\Interop\Windows\Interop.GetFileInformationByHandleEx.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FILE_TIME.cs" Link="Common\Interop\Windows\Interop.FILE_TIME.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.BY_HANDLE_FILE_INFORMATION.cs" Link="Common\Interop\Windows\Interop.BY_HANDLE_FILE_INFORMATION.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFinalPathNameByHandle.cs" Link="Common\Interop\Windows\Interop.GetFinalPathNameByHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.MemOptions.cs" Link="Common\Interop\Windows\Interop.MemOptions.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\Interop\Windows\Interop.SECURITY_ATTRIBUTES.cs" />
......@@ -202,7 +208,7 @@
<Compile Include="File\ChangeExtension.cs" />
<Compile Include="File\Copy.cs" />
<Compile Include="File\Exists.cs" />
<Compile Include="File\GetSetTimes.cs" />
<Compile Include="File\GetSetTimes_String.cs" />
<Compile Include="File\Open.cs" />
<Compile Include="File\OpenHandle.cs" />
<Compile Include="FileInfo\Create.cs" />
......
......@@ -1493,6 +1493,9 @@
<Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.RtlNtStatusToDosError.cs">
<Link>Common\Interop\Windows\NtDll\Interop.RtlNtStatusToDosError.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.BY_HANDLE_FILE_INFORMATION.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.BY_HANDLE_FILE_INFORMATION.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.DeleteFile.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.DeleteFile.cs</Link>
</Compile>
......@@ -1589,6 +1592,9 @@
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileAttributesEx.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.GetFileAttributesEx.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileInformationByHandle.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.GetFileInformationByHandle.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileInformationByHandleEx.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.GetFileInformationByHandleEx.cs</Link>
</Compile>
......@@ -2002,6 +2008,9 @@
<Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.ChMod.cs">
<Link>Common\Interop\Unix\System.Native\Interop.ChMod.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.FChMod.cs">
<Link>Common\Interop\Unix\System.Native\Interop.FChMod.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.Close.cs">
<Link>Common\Interop\Unix\System.Native\Interop.Close.cs</Link>
</Compile>
......@@ -2017,9 +2026,6 @@
<Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.UnixFileSystemTypes.cs">
<Link>Common\Interop\Unix\System.Native\Interop.UnixFileSystemTypes.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.FChMod.cs">
<Link>Common\Interop\Unix\System.Native\Interop.FChMod.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.FLock.cs">
<Link>Common\Interop\Unix\System.Native\Interop.FLock.cs</Link>
</Compile>
......
......@@ -2,13 +2,24 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
internal partial struct FileStatus
{
internal void SetCreationTime(string path, DateTimeOffset time, bool asDirectory)
=> SetCreationTime(handle: null, path, time, asDirectory);
internal void SetCreationTime(SafeFileHandle handle, DateTimeOffset time, bool asDirectory)
=> SetCreationTime(handle, handle.Path, time, asDirectory);
private void SetCreationTime(SafeFileHandle? handle, string? path, DateTimeOffset time, bool asDirectory)
{
// Either `handle` or `path` must not be null
Debug.Assert(handle is not null || path is not null);
// Try to set the attribute on the file system entry using setattrlist,
// if we get ENOTSUP then it means that "The volume does not support
// setattrlist()", so we fall back to the method used on other unix
......@@ -19,7 +30,7 @@ internal void SetCreationTime(string path, DateTimeOffset time, bool asDirectory
// great care.
long seconds = time.ToUnixTimeSeconds();
long nanoseconds = UnixTimeSecondsToNanoseconds(time, seconds);
Interop.Error error = SetCreationTimeCore(path, seconds, nanoseconds);
Interop.Error error = SetCreationTimeCore(handle, path, seconds, nanoseconds);
if (error == Interop.Error.SUCCESS)
{
......@@ -27,7 +38,7 @@ internal void SetCreationTime(string path, DateTimeOffset time, bool asDirectory
}
else if (error == Interop.Error.ENOTSUP)
{
SetAccessOrWriteTimeCore(path, time, isAccessTime: false, checkCreationTime: false, asDirectory);
SetAccessOrWriteTimeCore(handle, path, time, isAccessTime: false, checkCreationTime: false, asDirectory);
}
else
{
......@@ -35,8 +46,9 @@ internal void SetCreationTime(string path, DateTimeOffset time, bool asDirectory
}
}
private static unsafe Interop.Error SetCreationTimeCore(string path, long seconds, long nanoseconds)
private static unsafe Interop.Error SetCreationTimeCore(SafeFileHandle? handle, string? path, long seconds, long nanoseconds)
{
Debug.Assert(handle is not null || path is not null);
Interop.Sys.TimeSpec timeSpec = default;
timeSpec.TvSec = seconds;
......@@ -46,15 +58,16 @@ private static unsafe Interop.Error SetCreationTimeCore(string path, long second
attrList.bitmapCount = Interop.libc.AttrList.ATTR_BIT_MAP_COUNT;
attrList.commonAttr = Interop.libc.AttrList.ATTR_CMN_CRTIME;
Interop.Error error =
Interop.libc.setattrlist(path, &attrList, &timeSpec, sizeof(Interop.Sys.TimeSpec), new CULong(Interop.libc.FSOPT_NOFOLLOW)) == 0 ?
int result = handle is not null
? Interop.libc.fsetattrlist(handle, &attrList, &timeSpec, sizeof(Interop.Sys.TimeSpec), new CULong(Interop.libc.FSOPT_NOFOLLOW))
: Interop.libc.setattrlist(path!, &attrList, &timeSpec, sizeof(Interop.Sys.TimeSpec), new CULong(Interop.libc.FSOPT_NOFOLLOW));
return result == 0 ?
Interop.Error.SUCCESS :
Interop.Sys.GetLastErrorInfo().Error;
return error;
}
private void SetAccessOrWriteTime(string path, DateTimeOffset time, bool isAccessTime, bool asDirectory) =>
SetAccessOrWriteTimeCore(path, time, isAccessTime, checkCreationTime: true, asDirectory);
private void SetAccessOrWriteTime(SafeFileHandle? handle, string? path, DateTimeOffset time, bool isAccessTime, bool asDirectory) =>
SetAccessOrWriteTimeCore(handle, path, time, isAccessTime, checkCreationTime: true, asDirectory);
}
}
......@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
......@@ -10,11 +11,14 @@ internal partial struct FileStatus
internal void SetCreationTime(string path, DateTimeOffset time, bool asDirectory) =>
SetLastWriteTime(path, time, asDirectory);
private void SetAccessOrWriteTime(string path, DateTimeOffset time, bool isAccessTime, bool asDirectory) =>
SetAccessOrWriteTimeCore(path, time, isAccessTime, checkCreationTime: false, asDirectory);
internal void SetCreationTime(SafeFileHandle handle, DateTimeOffset time, bool asDirectory) =>
SetLastWriteTime(handle, time, asDirectory);
private void SetAccessOrWriteTime(SafeFileHandle? handle, string? path, DateTimeOffset time, bool isAccessTime, bool asDirectory) =>
SetAccessOrWriteTimeCore(handle, path, time, isAccessTime, checkCreationTime: false, asDirectory);
// This is not used on these platforms, but is needed for source compat
private static Interop.Error SetCreationTimeCore(string path, long seconds, long nanoseconds) =>
private static Interop.Error SetCreationTimeCore(SafeFileHandle? handle, string? path, long seconds, long nanoseconds) =>
throw new InvalidOperationException();
}
}
......@@ -184,8 +184,15 @@ internal bool IsSymbolicLink(ReadOnlySpan<char> path, bool continueOnError = fal
}
internal FileAttributes GetAttributes(ReadOnlySpan<char> path, ReadOnlySpan<char> fileName, bool continueOnError = false)
=> GetAttributes(handle: null, path, fileName, continueOnError);
internal FileAttributes GetAttributes(SafeFileHandle handle, bool continueOnError = false)
=> GetAttributes(handle, handle.Path, Path.GetFileName(handle.Path), continueOnError);
private FileAttributes GetAttributes(SafeFileHandle? handle, ReadOnlySpan<char> path, ReadOnlySpan<char> fileName, bool continueOnError = false)
{
EnsureCachesInitialized(path, continueOnError);
Debug.Assert(handle is not null || path.Length > 0);
EnsureCachesInitialized(handle, path, continueOnError);
if (!EntryExists)
return (FileAttributes)(-1);
......@@ -208,6 +215,12 @@ internal FileAttributes GetAttributes(ReadOnlySpan<char> path, ReadOnlySpan<char
}
internal void SetAttributes(string path, FileAttributes attributes, bool asDirectory)
=> SetAttributes(handle: null, path, attributes, asDirectory);
internal void SetAttributes(SafeFileHandle handle, FileAttributes attributes, bool asDirectory)
=> SetAttributes(handle, handle.Path, attributes, asDirectory);
private void SetAttributes(SafeFileHandle? handle, string? path, FileAttributes attributes, bool asDirectory)
{
// Validate that only flags from the attribute are being provided. This is an
// approximation for the validation done by the Win32 function.
......@@ -224,22 +237,21 @@ internal void SetAttributes(string path, FileAttributes attributes, bool asDirec
throw new ArgumentException(SR.Arg_InvalidFileAttrs, "Attributes");
}
EnsureCachesInitialized(path);
EnsureCachesInitialized(handle, path);
if (!EntryExists)
FileSystemInfo.ThrowNotFound(path);
if (Interop.Sys.CanSetHiddenFlag)
{
if ((attributes & FileAttributes.Hidden) != 0 && (_fileCache.UserFlags & (uint)Interop.Sys.UserFlags.UF_HIDDEN) == 0)
bool hidden = (attributes & FileAttributes.Hidden) != 0;
if (hidden ^ HasHiddenFlag)
{
// If Hidden flag is set and cached file status does not have the flag set then set it
Interop.CheckIo(Interop.Sys.LChflags(path, (_fileCache.UserFlags | (uint)Interop.Sys.UserFlags.UF_HIDDEN)), path, asDirectory);
}
else if (HasHiddenFlag)
{
// If Hidden flag is not set and cached file status does have the flag set then remove it
Interop.CheckIo(Interop.Sys.LChflags(path, (_fileCache.UserFlags & ~(uint)Interop.Sys.UserFlags.UF_HIDDEN)), path, asDirectory);
uint flags = hidden ? _fileCache.UserFlags | (uint)Interop.Sys.UserFlags.UF_HIDDEN :
_fileCache.UserFlags & ~(uint)Interop.Sys.UserFlags.UF_HIDDEN;
int rv = handle is not null ? Interop.Sys.FChflags(handle, flags) :
Interop.Sys.LChflags(path!, flags);
Interop.CheckIo(rv, path, asDirectory);
}
}
......@@ -261,7 +273,9 @@ internal void SetAttributes(string path, FileAttributes attributes, bool asDirec
// Change the permissions on the file
if (newMode != oldMode)
{
Interop.CheckIo(Interop.Sys.ChMod(path, newMode), path, asDirectory);
int rv = handle is not null ? Interop.Sys.FChMod(handle, newMode) :
Interop.Sys.ChMod(path!, newMode);
Interop.CheckIo(rv, path, asDirectory);
}
InvalidateCaches();
......@@ -274,8 +288,14 @@ internal bool GetExists(ReadOnlySpan<char> path, bool asDirectory)
}
internal DateTimeOffset GetCreationTime(ReadOnlySpan<char> path, bool continueOnError = false)
=> GetCreationTime(handle: null, path, continueOnError);
internal DateTimeOffset GetCreationTime(SafeFileHandle handle, bool continueOnError = false)
=> GetCreationTime(handle, handle.Path, continueOnError);
private DateTimeOffset GetCreationTime(SafeFileHandle? handle, ReadOnlySpan<char> path, bool continueOnError = false)
{
EnsureCachesInitialized(path, continueOnError);
EnsureCachesInitialized(handle, path, continueOnError);
if (!EntryExists)
return new DateTimeOffset(DateTime.FromFileTimeUtc(0));
......@@ -292,8 +312,14 @@ internal DateTimeOffset GetCreationTime(ReadOnlySpan<char> path, bool continueOn
}
internal DateTimeOffset GetLastAccessTime(ReadOnlySpan<char> path, bool continueOnError = false)
=> GetLastAccessTime(handle: null, path, continueOnError);
internal DateTimeOffset GetLastAccessTime(SafeFileHandle handle, bool continueOnError = false)
=> GetLastAccessTime(handle, handle.Path, continueOnError);
private DateTimeOffset GetLastAccessTime(SafeFileHandle? handle, ReadOnlySpan<char> path, bool continueOnError = false)
{
EnsureCachesInitialized(path, continueOnError);
EnsureCachesInitialized(handle, path, continueOnError);
if (!EntryExists)
return new DateTimeOffset(DateTime.FromFileTimeUtc(0));
......@@ -302,11 +328,23 @@ internal DateTimeOffset GetLastAccessTime(ReadOnlySpan<char> path, bool continue
}
internal void SetLastAccessTime(string path, DateTimeOffset time, bool asDirectory)
=> SetAccessOrWriteTime(path, time, isAccessTime: true, asDirectory);
=> SetLastAccessTime(handle: null, path, time, asDirectory);
internal void SetLastAccessTime(SafeFileHandle handle, DateTimeOffset time, bool asDirectory)
=> SetLastAccessTime(handle, handle.Path, time, asDirectory);
private void SetLastAccessTime(SafeFileHandle? handle, string? path, DateTimeOffset time, bool asDirectory)
=> SetAccessOrWriteTime(handle, path, time, isAccessTime: true, asDirectory);
internal DateTimeOffset GetLastWriteTime(ReadOnlySpan<char> path, bool continueOnError = false)
=> GetLastWriteTime(handle: null, path, continueOnError);
internal DateTimeOffset GetLastWriteTime(SafeFileHandle handle, bool continueOnError = false)
=> GetLastWriteTime(handle, handle.Path, continueOnError);
private DateTimeOffset GetLastWriteTime(SafeFileHandle? handle, ReadOnlySpan<char> path, bool continueOnError = false)
{
EnsureCachesInitialized(path, continueOnError);
EnsureCachesInitialized(handle, path, continueOnError);
if (!EntryExists)
return new DateTimeOffset(DateTime.FromFileTimeUtc(0));
......@@ -315,14 +353,20 @@ internal DateTimeOffset GetLastWriteTime(ReadOnlySpan<char> path, bool continueO
}
internal void SetLastWriteTime(string path, DateTimeOffset time, bool asDirectory)
=> SetAccessOrWriteTime(path, time, isAccessTime: false, asDirectory);
=> SetLastWriteTime(handle: null, path, time, asDirectory);
internal void SetLastWriteTime(SafeFileHandle handle, DateTimeOffset time, bool asDirectory)
=> SetLastWriteTime(handle, handle.Path, time, asDirectory);
internal void SetLastWriteTime(SafeFileHandle? handle, string? path, DateTimeOffset time, bool asDirectory)
=> SetAccessOrWriteTime(handle, path, time, isAccessTime: false, asDirectory);
private static DateTimeOffset UnixTimeToDateTimeOffset(long seconds, long nanoseconds)
{
return DateTimeOffset.FromUnixTimeSeconds(seconds).AddTicks(nanoseconds / NanosecondsPerTick);
}
private unsafe void SetAccessOrWriteTimeCore(string path, DateTimeOffset time, bool isAccessTime, bool checkCreationTime, bool asDirectory)
private unsafe void SetAccessOrWriteTimeCore(SafeFileHandle? handle, string? path, DateTimeOffset time, bool isAccessTime, bool checkCreationTime, bool asDirectory)
{
// This api is used to set creation time on non OSX platforms, and as a fallback for OSX platforms.
// The reason why we use it to set 'creation time' is the below comment:
......@@ -338,7 +382,7 @@ private unsafe void SetAccessOrWriteTimeCore(string path, DateTimeOffset time, b
// force a refresh so that we have an up-to-date times for values not being overwritten
InvalidateCaches();
EnsureCachesInitialized(path);
EnsureCachesInitialized(handle, path);
if (!EntryExists)
FileSystemInfo.ThrowNotFound(path);
......@@ -370,7 +414,10 @@ private unsafe void SetAccessOrWriteTimeCore(string path, DateTimeOffset time, b
buf[1].TvNsec = nanoseconds;
}
#endif
Interop.CheckIo(Interop.Sys.UTimensat(path, buf), path, asDirectory);
int rv = handle is not null
? Interop.Sys.FUTimens(handle, buf)
: Interop.Sys.UTimensat(path!, buf);
Interop.CheckIo(rv, path, asDirectory);
// On OSX-like platforms, when the modification time is less than the creation time (including
// when the modification time is already less than but access time is being set), the creation
......@@ -387,7 +434,7 @@ private unsafe void SetAccessOrWriteTimeCore(string path, DateTimeOffset time, b
if (updateCreationTime)
{
Interop.Error error = SetCreationTimeCore(path, _fileCache.BirthTime, _fileCache.BirthTimeNsec);
Interop.Error error = SetCreationTimeCore(handle, path, _fileCache.BirthTime, _fileCache.BirthTimeNsec);
if (error != Interop.Error.SUCCESS && error != Interop.Error.ENOTSUP)
{
Interop.CheckIo(error, path, asDirectory);
......
......@@ -600,9 +600,15 @@ public static FileAttributes GetAttributes(string fullPath)
return attributes;
}
public static FileAttributes GetAttributes(SafeFileHandle fileHandle)
=> default(FileStatus).GetAttributes(fileHandle);
public static void SetAttributes(string fullPath, FileAttributes attributes)
=> default(FileStatus).SetAttributes(fullPath, attributes, asDirectory: false);
public static void SetAttributes(SafeFileHandle fileHandle, FileAttributes attributes)
=> default(FileStatus).SetAttributes(fileHandle, attributes, asDirectory: false);
public static UnixFileMode GetUnixFileMode(string fullPath)
{
UnixFileMode mode = default(FileStatus).GetUnixFileMode(fullPath);
......@@ -625,21 +631,39 @@ public static void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode)
public static DateTimeOffset GetCreationTime(string fullPath)
=> default(FileStatus).GetCreationTime(fullPath).UtcDateTime;
public static DateTimeOffset GetCreationTime(SafeFileHandle fileHandle)
=> default(FileStatus).GetCreationTime(fileHandle).UtcDateTime;
public static void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> default(FileStatus).SetCreationTime(fullPath, time, asDirectory);
public static void SetCreationTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> default(FileStatus).SetCreationTime(fileHandle, time, asDirectory: false);
public static DateTimeOffset GetLastAccessTime(string fullPath)
=> default(FileStatus).GetLastAccessTime(fullPath).UtcDateTime;
public static DateTimeOffset GetLastAccessTime(SafeFileHandle fileHandle)
=> default(FileStatus).GetLastAccessTime(fileHandle).UtcDateTime;
public static void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> default(FileStatus).SetLastAccessTime(fullPath, time, asDirectory);
public static unsafe void SetLastAccessTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> default(FileStatus).SetLastAccessTime(fileHandle, time, asDirectory: false);
public static DateTimeOffset GetLastWriteTime(string fullPath)
=> default(FileStatus).GetLastWriteTime(fullPath).UtcDateTime;
public static DateTimeOffset GetLastWriteTime(SafeFileHandle fileHandle)
=> default(FileStatus).GetLastWriteTime(fileHandle).UtcDateTime;
public static void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> default(FileStatus).SetLastWriteTime(fullPath, time, asDirectory);
public static unsafe void SetLastWriteTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> default(FileStatus).SetLastWriteTime(fileHandle, time, asDirectory: false);
public static string[] GetLogicalDrives()
{
return DriveInfoInternal.GetLogicalDrives();
......
......@@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Buffers;
using System.ComponentModel;
namespace System.IO
{
......@@ -107,25 +108,17 @@ public static void DeleteFile(string fullPath)
}
}
public static FileAttributes GetAttributes(string fullPath)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
public static FileAttributes GetAttributes(string fullPath) =>
(FileAttributes)GetAttributeData(fullPath, returnErrorOnNotFound: true).dwFileAttributes;
return (FileAttributes)data.dwFileAttributes;
}
public static FileAttributes GetAttributes(SafeFileHandle fileHandle) =>
(FileAttributes)GetAttributeData(fileHandle).dwFileAttributes;
public static DateTimeOffset GetCreationTime(string fullPath)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
public static DateTimeOffset GetCreationTime(string fullPath) =>
GetAttributeData(fullPath).ftCreationTime.ToDateTimeOffset();
return data.ftCreationTime.ToDateTimeOffset();
}
public static DateTimeOffset GetCreationTime(SafeFileHandle fileHandle) =>
GetAttributeData(fileHandle).ftCreationTime.ToDateTimeOffset();
public static FileSystemInfo GetFileSystemInfo(string fullPath, bool asDirectory)
{
......@@ -134,24 +127,57 @@ public static FileSystemInfo GetFileSystemInfo(string fullPath, bool asDirectory
(FileSystemInfo)new FileInfo(fullPath, null);
}
public static DateTimeOffset GetLastAccessTime(string fullPath)
public static DateTimeOffset GetLastAccessTime(string fullPath) =>
GetAttributeData(fullPath).ftLastAccessTime.ToDateTimeOffset();
public static DateTimeOffset GetLastAccessTime(SafeFileHandle fileHandle) =>
GetAttributeData(fileHandle).ftLastAccessTime.ToDateTimeOffset();
public static DateTimeOffset GetLastWriteTime(string fullPath) =>
GetAttributeData(fullPath).ftLastWriteTime.ToDateTimeOffset();
public static DateTimeOffset GetLastWriteTime(SafeFileHandle fileHandle) =>
GetAttributeData(fileHandle).ftLastWriteTime.ToDateTimeOffset();
internal static Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA GetAttributeData(string fullPath, bool returnErrorOnNotFound = false)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
return data.ftLastAccessTime.ToDateTimeOffset();
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound);
return errorCode != Interop.Errors.ERROR_SUCCESS
? throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath)
: data;
}
public static DateTimeOffset GetLastWriteTime(string fullPath)
internal static Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA GetAttributeData(SafeFileHandle fileHandle)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false);
if (errorCode != 0)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
int errorCode = FillAttributeInfo(fileHandle, ref data);
return errorCode != Interop.Errors.ERROR_SUCCESS
? throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileHandle.Path)
: data;
}
return data.ftLastWriteTime.ToDateTimeOffset();
private static int FillAttributeInfo(SafeFileHandle fileHandle, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data)
{
if (!Interop.Kernel32.GetFileInformationByHandle(
fileHandle,
out Interop.Kernel32.BY_HANDLE_FILE_INFORMATION fileInformationData))
{
return Marshal.GetLastWin32Error();
}
PopulateAttributeData(ref data, fileInformationData);
return Interop.Errors.ERROR_SUCCESS;
}
private static void PopulateAttributeData(ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, in Interop.Kernel32.BY_HANDLE_FILE_INFORMATION fileInformationData)
{
data.dwFileAttributes = (int)fileInformationData.dwFileAttributes;
data.ftCreationTime = fileInformationData.ftCreationTime;
data.ftLastAccessTime = fileInformationData.ftLastAccessTime;
data.ftLastWriteTime = fileInformationData.ftLastWriteTime;
data.nFileSizeHigh = fileInformationData.nFileSizeHigh;
data.nFileSizeLow = fileInformationData.nFileSizeLow;
}
private static void MoveDirectory(string sourceFullPath, string destFullPath, bool isCaseSensitiveRename)
......@@ -412,17 +438,36 @@ private static void RemoveDirectoryInternal(string fullPath, bool topLevel, bool
public static void SetAttributes(string fullPath, FileAttributes attributes)
{
if (!Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes))
if (Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER)
throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes));
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
return;
}
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER)
throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes));
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
// Default values indicate "no change". Use defaults so that we don't force callsites to be aware of the default values
private static unsafe void SetFileTime(
public static unsafe void SetAttributes(SafeFileHandle fileHandle, FileAttributes attributes)
{
var basicInfo = new Interop.Kernel32.FILE_BASIC_INFO
{
FileAttributes = (uint)attributes
};
if (!Interop.Kernel32.SetFileInformationByHandle(
fileHandle,
Interop.Kernel32.FileBasicInfo,
&basicInfo,
(uint)sizeof(Interop.Kernel32.FILE_BASIC_INFO)))
{
throw Win32Marshal.GetExceptionForLastWin32Error(fileHandle.Path);
}
}
// Default values indicate "no change". Use defaults so that we don't force callsites to be aware of the default values
private static void SetFileTime(
string fullPath,
bool asDirectory,
long creationTime = -1,
......@@ -431,33 +476,52 @@ public static void SetAttributes(string fullPath, FileAttributes attributes)
long changeTime = -1,
uint fileAttributes = 0)
{
using (SafeFileHandle handle = OpenHandleToWriteAttributes(fullPath, asDirectory))
using SafeFileHandle handle = OpenHandleToWriteAttributes(fullPath, asDirectory);
SetFileTime(handle, fullPath, creationTime, lastAccessTime, lastWriteTime, changeTime, fileAttributes);
}
private static unsafe void SetFileTime(
SafeFileHandle fileHandle,
string? fullPath = null,
long creationTime = -1,
long lastAccessTime = -1,
long lastWriteTime = -1,
long changeTime = -1,
uint fileAttributes = 0)
{
var basicInfo = new Interop.Kernel32.FILE_BASIC_INFO
{
var basicInfo = new Interop.Kernel32.FILE_BASIC_INFO()
{
CreationTime = creationTime,
LastAccessTime = lastAccessTime,
LastWriteTime = lastWriteTime,
ChangeTime = changeTime,
FileAttributes = fileAttributes
};
if (!Interop.Kernel32.SetFileInformationByHandle(handle, Interop.Kernel32.FileBasicInfo, &basicInfo, (uint)sizeof(Interop.Kernel32.FILE_BASIC_INFO)))
{
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath);
}
CreationTime = creationTime,
LastAccessTime = lastAccessTime,
LastWriteTime = lastWriteTime,
ChangeTime = changeTime,
FileAttributes = fileAttributes
};
if (!Interop.Kernel32.SetFileInformationByHandle(fileHandle, Interop.Kernel32.FileBasicInfo, &basicInfo, (uint)sizeof(Interop.Kernel32.FILE_BASIC_INFO)))
{
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath ?? fileHandle.Path);
}
}
public static void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> SetFileTime(fullPath, asDirectory, creationTime: time.ToFileTime());
public static void SetCreationTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> SetFileTime(fileHandle, creationTime: time.ToFileTime());
public static void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> SetFileTime(fullPath, asDirectory, lastAccessTime: time.ToFileTime());
public static void SetLastAccessTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> SetFileTime(fileHandle, lastAccessTime: time.ToFileTime());
public static void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> SetFileTime(fullPath, asDirectory, lastWriteTime: time.ToFileTime());
public static void SetLastWriteTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> SetFileTime(fileHandle, lastWriteTime: time.ToFileTime());
public static string[] GetLogicalDrives()
=> DriveInfoInternal.GetLogicalDrives();
......
......@@ -75,7 +75,12 @@ public void Refresh()
_fileStatus.RefreshCaches(FullPath);
}
internal static void ThrowNotFound(string path)
internal static void ThrowNotFound(ReadOnlySpan<char> path)
{
ThrowNotFound(path.Length == 0 ? default : path.ToString());
}
internal static void ThrowNotFound(string? path)
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
......@@ -84,8 +89,7 @@ internal static void ThrowNotFound(string path)
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundException.
bool directoryError = !Directory.Exists(Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(path)));
bool directoryError = path is not null && !FileSystem.DirectoryExists(Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(path.AsSpan())));
throw Interop.GetExceptionForIoErrno(new Interop.ErrorInfo(Interop.Error.ENOENT), path, directoryError);
}
......
......@@ -9512,12 +9512,19 @@ public static partial class File
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void Encrypt(string path) { }
public static bool Exists([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] string? path) { throw null; }
public static System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.IO.FileAttributes GetAttributes(string path) { throw null; }
public static System.DateTime GetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.DateTime GetCreationTime(string path) { throw null; }
public static System.DateTime GetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.DateTime GetCreationTimeUtc(string path) { throw null; }
public static System.DateTime GetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.DateTime GetLastAccessTime(string path) { throw null; }
public static System.DateTime GetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.DateTime GetLastAccessTimeUtc(string path) { throw null; }
public static System.DateTime GetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.DateTime GetLastWriteTime(string path) { throw null; }
public static System.DateTime GetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
public static System.DateTime GetLastWriteTimeUtc(string path) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("windows")]
public static System.IO.UnixFileMode GetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle) { throw null; }
......@@ -9550,12 +9557,19 @@ public static partial class File
public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName) { }
public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors) { }
public static System.IO.FileSystemInfo? ResolveLinkTarget(string linkPath, bool returnFinalTarget) { throw null; }
public static void SetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.FileAttributes fileAttributes) { }
public static void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { }
public static void SetCreationTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTime) { }
public static void SetCreationTime(string path, System.DateTime creationTime) { }
public static void SetCreationTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime creationTimeUtc) { }
public static void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { }
public static void SetLastAccessTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTime) { }
public static void SetLastAccessTime(string path, System.DateTime lastAccessTime) { }
public static void SetLastAccessTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastAccessTimeUtc) { }
public static void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { }
public static void SetLastWriteTime(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTime) { }
public static void SetLastWriteTime(string path, System.DateTime lastWriteTime) { }
public static void SetLastWriteTimeUtc(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.DateTime lastWriteTimeUtc) { }
public static void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("windows")]
public static void SetUnixFileMode(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, System.IO.UnixFileMode mode) { }
......@@ -112,6 +112,7 @@ static const Entry s_sysNative[] =
DllImportEntry(SystemNative_LockFileRegion)
DllImportEntry(SystemNative_LChflags)
DllImportEntry(SystemNative_LChflagsCanSetHiddenFlag)
DllImportEntry(SystemNative_FChflags)
DllImportEntry(SystemNative_CanGetHiddenFlag)
DllImportEntry(SystemNative_ReadProcessStatusInfo)
DllImportEntry(SystemNative_Log)
......@@ -242,6 +243,7 @@ static const Entry s_sysNative[] =
DllImportEntry(SystemNative_Exit)
DllImportEntry(SystemNative_Abort)
DllImportEntry(SystemNative_UTimensat)
DllImportEntry(SystemNative_FUTimens)
DllImportEntry(SystemNative_GetTimestamp)
DllImportEntry(SystemNative_GetCpuUtilization)
DllImportEntry(SystemNative_GetPwUidR)
......
......@@ -1672,6 +1672,19 @@ int32_t SystemNative_LChflags(const char* path, uint32_t flags)
#endif
}
int32_t SystemNative_FChflags(intptr_t fd, uint32_t flags)
{
#if HAVE_LCHFLAGS
int32_t result;
while ((result = fchflags(ToFileDescriptor(fd), flags)) < 0 && errno == EINTR);
return result;
#else
(void)fd, (void)flags;
errno = ENOTSUP;
return -1;
#endif
}
int32_t SystemNative_LChflagsCanSetHiddenFlag(void)
{
#if HAVE_LCHFLAGS
......
......@@ -758,6 +758,13 @@ PALEXPORT int32_t SystemNative_LockFileRegion(intptr_t fd, int64_t offset, int64
*/
PALEXPORT int32_t SystemNative_LChflags(const char* path, uint32_t flags);
/**
* Changes the file flags of the file "fd".
*
* Returns 0 for success, -1 for failure. Sets errno for failure.
*/
PALEXPORT int32_t SystemNative_FChflags(intptr_t fd, uint32_t flags);
/**
* Determines if the current platform supports setting UF_HIDDEN (0x8000) flag
*
......
......@@ -53,6 +53,33 @@ int32_t SystemNative_UTimensat(const char* path, TimeSpec* times)
return result;
}
int32_t SystemNative_FUTimens(intptr_t fd, TimeSpec* times)
{
int32_t result;
#if HAVE_FUTIMENS
struct timespec updatedTimes[2];
updatedTimes[0].tv_sec = (time_t)times[0].tv_sec;
updatedTimes[0].tv_nsec = (long)times[0].tv_nsec;
updatedTimes[1].tv_sec = (time_t)times[1].tv_sec;
updatedTimes[1].tv_nsec = (long)times[1].tv_nsec;
while (CheckInterrupted(result = futimens(ToFileDescriptor(fd), updatedTimes)));
#else
// Fallback on unsupported platforms (e.g. iOS, tvOS, watchOS)
// to futimes (lower precision)
struct timeval updatedTimes[2];
updatedTimes[0].tv_sec = (long)times[0].tv_sec;
updatedTimes[0].tv_usec = (int)times[0].tv_nsec / 1000;
updatedTimes[1].tv_sec = (long)times[1].tv_sec;
updatedTimes[1].tv_usec = (int)times[1].tv_nsec / 1000;
while (CheckInterrupted(result = futimes(ToFileDescriptor(fd), updatedTimes)));
#endif
return result;
}
uint64_t SystemNative_GetTimestamp()
{
#if HAVE_CLOCK_GETTIME_NSEC_NP
......
......@@ -27,6 +27,13 @@ typedef struct ProcessCpuInformation
*/
PALEXPORT int32_t SystemNative_UTimensat(const char* path, TimeSpec* times);
/**
* Sets the last access and last modified time of a file
*
* Returns 0 on success; otherwise, returns -1 and errno is set.
*/
PALEXPORT int32_t SystemNative_FUTimens(intptr_t fd, TimeSpec* times);
/**
* Gets a high-resolution timestamp that can be used for time-interval measurements.
*/
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册