From 6d4fc1ad4725ca4cc77214b93bc1d37a6fa3553d Mon Sep 17 00:00:00 2001 From: Filip Navara Date: Sat, 17 Feb 2024 17:02:29 +0100 Subject: [PATCH] [NativeAOT] Add null checks into memcpy/memset helpers (#98547) --- .../Runtime/CompilerHelpers/MemoryHelpers.cs | 33 +++++++++++++++++++ .../src/System.Private.CoreLib.csproj | 1 + .../ILCompiler.Compiler/Compiler/JitHelper.cs | 4 +-- 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MemoryHelpers.cs diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MemoryHelpers.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MemoryHelpers.cs new file mode 100644 index 0000000000000..644fcf1a59940 --- /dev/null +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MemoryHelpers.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime; + +namespace Internal.Runtime.CompilerHelpers +{ + /// + /// These methods are used to implement memcpy and memset intrinsics with null checks. + /// + internal static class MemoryHelpers + { + private static unsafe void MemSet(ref byte dest, byte value, nuint size) + { + if (size > 0) + { + _ = dest; + SpanHelpers.Fill(ref dest, size, value); + } + } + + private static unsafe void MemCopy(ref byte dest, ref byte src, nuint size) + { + if (size > 0) + { + _ = dest; + _ = src; + Buffer.Memmove(ref dest, ref src, size); + } + } + } +} diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System.Private.CoreLib.csproj b/src/coreclr/nativeaot/System.Private.CoreLib/src/System.Private.CoreLib.csproj index 4ca91458c70e7..d6e8c3a7e9027 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System.Private.CoreLib.csproj +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System.Private.CoreLib.csproj @@ -100,6 +100,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs index 9e7285b751a3d..c55dc58175b05 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs @@ -134,10 +134,10 @@ public static void GetEntryPoint(TypeSystemContext context, ReadyToRunHelper id, break; case ReadyToRunHelper.MemCpy: - mangledName = "memcpy"; // TODO: Null reference handling + methodDesc = context.GetHelperEntryPoint("MemoryHelpers", "MemCopy"); break; case ReadyToRunHelper.MemSet: - mangledName = "memset"; // TODO: Null reference handling + methodDesc = context.GetHelperEntryPoint("MemoryHelpers", "MemSet"); break; case ReadyToRunHelper.GetRuntimeTypeHandle: