Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/Csharpc/corelib/Interop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ internal static unsafe class Libc
[DllImport("__Internal")] public static extern int csrt_get_last_system_error();
[DllImport("__Internal")] public static extern void csrt_set_last_system_error(int error);
[DllImport("__Internal")] public static extern void* csrt_pinvoke_load_library(byte* name, byte throwOnError);
[DllImport("__Internal")] public static extern void* csrt_pinvoke_load_library_from(byte* name, byte throwOnError, byte appFirst);
[DllImport("__Internal")] public static extern void* csrt_native_library_get_export(void* handle, byte* entry, byte throwOnError);
[DllImport("__Internal")] public static extern void* csrt_pinvoke_resolve(byte* library, byte* entry);

Expand Down Expand Up @@ -608,6 +609,20 @@ public static IntPtr Load(string libraryPath)
return (IntPtr)handle;
}

// NativeLibrary.Load(name, assembly, searchPath) (#99): the DllImport search (the program's directory, then the system's), as
// csharpc's [DllImport]s get, unless searchPath leaves out AssemblyDirectory; every assembly is compiled in, so the assembly
// only has to be there. DllNotFoundException if absent.
public static IntPtr Load(string libraryName, System.Reflection.Assembly assembly, System.Runtime.InteropServices.DllImportSearchPath? searchPath)
{
if (libraryName == null) throw new ArgumentNullException("libraryName");
if (assembly == null) throw new ArgumentNullException("assembly");
byte* name = Utf8.ToNative(libraryName);
bool appFirst = searchPath is not { } paths || (paths & System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory) != 0;
void* handle = Libc.csrt_pinvoke_load_library_from(name, 1, appFirst ? (byte)1 : (byte)0);
Libc.free(name);
return (IntPtr)handle;
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

public static bool TryLoad(string libraryPath, out IntPtr handle)
{
byte* name = Utf8.ToNative(libraryPath);
Expand Down
5 changes: 5 additions & 0 deletions src/Csharpc/corelib/NativeIntMembers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ internal static class IntPtrMembers
[ShadowInstance] public static long ToInt64(nint value) => value;
[ShadowInstance] public static int ToInt32(nint value) => checked((int)value);
[ShadowInstance] public static unsafe void* ToPointer(nint value) => (void*)value;
// IntPtr.Add / Subtract (#99): an offset in bytes, unchecked like nint arithmetic.
public static nint Add(nint pointer, int offset) => pointer + offset;
public static nint Subtract(nint pointer, int offset) => pointer - offset;
}

[ShadowMembers("System.UIntPtr")]
Expand All @@ -25,6 +28,8 @@ internal static class UIntPtrMembers
// nuint.MaxValue (a property, not a constant: its width is the target's), which the framework's IL reads (Number.BigInteger).
public static nuint MaxValue => unchecked((nuint)(nint)(-1));
public static nuint MinValue => 0;
public static nuint Add(nuint pointer, int offset) => (nuint)((nint)pointer + offset);
public static nuint Subtract(nuint pointer, int offset) => (nuint)((nint)pointer - offset);
public static nuint LeadingZeroCount(nuint value) => (nuint)System.Numerics.BitOperations.LeadingZeroCount(value);
public static nuint BigMul(nuint left, nuint right, out nuint lower)
{
Expand Down
33 changes: 33 additions & 0 deletions src/Csharpc/corelib/OperatingSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,39 @@ public static bool IsWindowsVersionAtLeast(int major, int minor = 0, int build =
#endif
}

/// <summary>
/// OperatingSystem.IsMacOSVersionAtLeast (#99): false off macOS, else the running product version (kern.osproductversion,
/// what NSProcessInfo reports and .NET compares) field by field.
/// </summary>
public static bool IsMacOSVersionAtLeast(int major, int minor = 0, int build = 0)
{
#if CSHARPC_TARGET_MACOS
var (m, n, p) = MacProductVersion();
if (m != major) return m > major;
if (n != minor) return n > minor;
return p >= build;
#else
return false;
#endif
}

#if CSHARPC_TARGET_MACOS
[System.Runtime.InteropServices.DllImport("libc")]
private static extern unsafe int sysctlbyname(byte* name, byte* value, nuint* length, byte* newValue, nuint newLength);

private static unsafe (int, int, int) MacProductVersion()
{
byte* value = stackalloc byte[64];
nuint length = 64;
fixed (byte* name = "kern.osproductversion\0"u8)
if (sysctlbyname(name, value, &length, null, 0) != 0) return (0, 0, 0);
value[63] = 0;
string[] parts = Utf8.FromNative(value).Split('.');
int Part(int i) => parts.Length > i && int.TryParse(parts[i], out int v) ? v : 0;
return (Part(0), Part(1), Part(2));
}
#endif

/// <summary>.NET compares the name case-insensitively; macOS answers to "OSX" too.</summary>
public static bool IsOSPlatform(string platform)
{
Expand Down
5 changes: 5 additions & 0 deletions src/Csharpc/corelib/SecureString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ internal string ToPlainString()
[ShadowMembers("System.Runtime.InteropServices.Marshal")]
internal static unsafe class MarshalSecureStringMembers
{
// GetHRForException (#99): the exception's HResult (0 for null), as .NET on Unix; WriteInt16's char overloads write the char's code.
public static int GetHRForException(Exception e) => e?.HResult ?? 0;
public static void WriteInt16(IntPtr ptr, char val) => Marshal.WriteInt16(ptr, (short)val);
public static void WriteInt16(IntPtr ptr, int ofs, char val) => Marshal.WriteInt16(ptr, ofs, (short)val);

private static string PlainOf(SecureString s)
{
if (s == null) throw new ArgumentNullException("s");
Expand Down
7 changes: 7 additions & 0 deletions src/runtime/pinvoke.c
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,18 @@ static void* load_library(const char* name, bool throw_on_error, bool app_first)
}

void* csrt_pinvoke_load_library(const char* name, bool throw_on_error) { return load_library(name, throw_on_error, false); }
// NativeLibrary.Load(name, assembly, searchPath): next to the application first when the search includes
// DllImportSearchPath.AssemblyDirectory (the default), as a P/Invoke of that assembly would.
void* csrt_pinvoke_load_library_from(const char* name, bool throw_on_error, bool app_first) { return load_library(name, throw_on_error, app_first); }
static void* load_library_for_pinvoke(const char* name) { return load_library(name, true, true); }
#endif
#ifdef _WIN32
// LoadLibrary searches the application's directory itself.
static void* load_library_for_pinvoke(const char* name) { return csrt_pinvoke_load_library(name, true); }
void* csrt_pinvoke_load_library_from(const char* name, bool throw_on_error, bool app_first) {
(void)app_first; // LoadLibrary's own search starts in the application's directory
return csrt_pinvoke_load_library(name, throw_on_error);
}
#endif

/// Resolves `entry` in `library` (DllImport lazy binding); throws like .NET on failure.
Expand Down
1 change: 1 addition & 0 deletions tests/platform-skips.txt
Original file line number Diff line number Diff line change
Expand Up @@ -333,3 +333,4 @@ windows 1522_negotiate_gss_from_il known gap: X.509, RSA, ECC and TLS are serve
wasi 1522_negotiate_gss_from_il known gap: no OpenSSL or sockets for TLS on WebAssembly (WASI); csharpc's copies lack these members (#449)
wasi 1532_monitor_thin_lock_table needs threads: Thread.Start throws PlatformNotSupportedException on WebAssembly
wasi 1540_enum_negative_value_culture_sign .NET on WASI is globalization-invariant: CultureInfo("sv-SE") throws CultureNotFoundException
wasi 1553_interop_gap_members loads a shared library with NativeLibrary.Load: WASI has no dynamic libraries
30 changes: 30 additions & 0 deletions tests/samples/1553_interop_gap_members.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Interop members from #99: nint/nuint.Add/Subtract, Marshal.GetHRForException, Marshal.WriteInt16's char overloads,
// NativeLibrary.Load(name, assembly, searchPath) and OperatingSystem.IsMacOSVersionAtLeast.
using System;
using System.Runtime.InteropServices;

static class Program
{
static void Main()
{
Console.WriteLine($"{nint.Add(5, 3)} {nint.Subtract(5, 3)} {nint.Add(5, -7)} {nuint.Add(5, 3)} {nuint.Subtract(5, 3)}");
Console.WriteLine($"{Marshal.GetHRForException(new InvalidOperationException()):X} {Marshal.GetHRForException(new FormatException()):X} {Marshal.GetHRForException(null!)}");

IntPtr p = Marshal.AllocHGlobal(8);
Marshal.WriteInt16(p, 'A');
Marshal.WriteInt16(p, 2, '€');
Console.WriteLine($"{Marshal.ReadInt16(p)} {(char)Marshal.ReadInt16(p, 2)}");
Marshal.FreeHGlobal(p);

string library = OperatingSystem.IsWindows() ? "kernel32.dll" : OperatingSystem.IsMacOS() ? "libSystem.dylib" : "libc.so.6";
IntPtr handle = NativeLibrary.Load(library, typeof(Program).Assembly, null);
Console.WriteLine($"loaded: {handle != IntPtr.Zero}");
try { NativeLibrary.Load("csharpc-no-such-library", typeof(Program).Assembly, DllImportSearchPath.SafeDirectories); }
catch (Exception e) { Console.WriteLine(e.GetType().Name); }
try { NativeLibrary.Load(library, null!, null); }
catch (ArgumentNullException e) { Console.WriteLine(e.ParamName); }

bool mac = OperatingSystem.IsMacOS();
Console.WriteLine($"mac 10.0: {OperatingSystem.IsMacOSVersionAtLeast(10, 0) == mac} mac 999: {OperatingSystem.IsMacOSVersionAtLeast(999)}");
}
}
7 changes: 7 additions & 0 deletions tests/samples/1553_interop_gap_members.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
8 2 -2 8 2
80131509 80131537 0
65 €
loaded: True
DllNotFoundException
assembly
mac 10.0: True mac 999: False
Loading