Skip to content

Read-write memory-mapped files and UnmanagedMemoryAccessor - #293

Open
filipnavara wants to merge 74 commits into
jonathanperis:mainfrom
filipnavara:feat/mmap-read-write
Open

filipnavara wants to merge 74 commits into
jonathanperis:mainfrom
filipnavara:feat/mmap-read-write

Conversation

@filipnavara

@filipnavara filipnavara commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

csharpc's MemoryMappedFile covers the read-only subset System.Reflection.Metadata needs, and the view accessor has none of UnmanagedMemoryAccessor's members. So a program that keeps state in a mapped file fails twice:

  • CreateFromFile(..., MemoryMappedFileAccess.ReadWrite, ...) throws "csharpc supports read-only memory-mapped files only";
  • accessor.Read(0, out T) / accessor.Write(0, ref T) are "not supported" at compile time.

eM Client's Spotlight indexer is one such program: it keeps a checkpoint struct in a mapped file.

The change (corelib only; no new C)

  • MemoryMappedFile.CreateFromFile accepts ReadWrite and grows the file to the capacity first, as .NET does.
  • CreateViewAccessor maps writable views (Posix.MapView(..., writable)):
    • Unix: mmap with PROT_READ | PROT_WRITE, MAP_SHARED
    • Windows: PAGE_READWRITE / FILE_MAP_WRITE
    • WASI: a stub, unchanged (CanMapFiles is false)
  • A writable view of a read-only map is refused. The parameterless CreateViewAccessor() overloads give a read-only map a read view, as before.
  • New UnmanagedMemoryAccessor shadow, over the view's SafeBuffer:
    • Capacity, CanRead/CanWrite, Read<T>/Write<T>, ReadArray/WriteArray, and the scalar ReadXxx/Write overloads
    • MemoryMappedViewAccessor derives from it, as in .NET
  • Checks follow UnmanagedMemoryAccessor.cs in its order (closed, access, negative position, room) with its messages. All 15 error cases I tried match .NET exactly, including WriteArray leaving the room check to SafeBuffer ("Not enough space available in the buffer.").
  • Still NotSupportedException: copy-on-write and execute access, named maps, views as streams.

Tests

  • New sample 1345_memorymapped_read_write, recorded from .NET:
    • the file grows to the capacity
    • struct, scalar and array reads and writes; the bytes on disk afterwards
    • re-opening the file read-only
    • the bounds, access and disposal errors
  • CSHARPC_JOBS=6 tests/run.sh --all-opts 'io_|file|stream|safebuffer|safehandle|mapped|metadata': 42 passed.
  • tests/conformance.sh: 195/195.
  • Not run locally on Windows or WASI. For WASI, --target wasm32-wasip1 --emit llvm-ir compiles and lowers the corelib up to the point where the missing WASI clang stops it. CI covers both.

A fixed-size buffer field is the compiler's <name>e__FixedBuffer struct:
one element field and StructLayout.Size = FixedSize * sizeof(element).
The marshaller lays it out as at least that large, aligned as one element
marshalled with the container's CharSet (an ANSI char is one byte, so a
fixed char buffer of a default struct is byte-aligned; CharSet.Unicode
keeps it 2-byte aligned). SizeOf and OffsetOf now compute that layout
instead of refusing the struct.

Copying such a struct (PtrToStructure, StructureToPtr, DestroyStructure)
stays an explicit diagnostic: .NET's marshaller converts only the
buffer's first element and zeroes the rest, which is not modelled.

Sample 1304 is recorded from .NET.
…ings

Assembly.GetCustomAttributes(Type, bool), Enum.GetName(Type, object),
Marshal.SizeOf(Type) and RuntimeHelpers.GetUninitializedObject(Type) are
lowered for the one type their argument is, which had to be a typeof
expression: `Type t = typeof(A); asm.GetCustomAttributes(t, false)` was
rejected in both front-ends.

FunctionCodeGen.ExactTypeOf now also accepts a local that holds typeof(T)
wherever it is read: in source, declared = typeof(T) and never assigned,
deconstructed into, passed by ref/out or referenced with ref in its
member; in IL, a single stloc preceded by ldtoken T; call
GetTypeFromHandle and no ldloca. The flow-insensitive typeof lists that
keep reflection metadata are unchanged.

Sample 1306 is recorded from .NET.
…rs of typeof values assigned to them

ILLink applies a property's annotation to its setter's value parameter
and follows typeof values stored into annotated fields. csharpc read only
parameter annotations at call sites, and its source front-end saw neither
a property assignment (not an invocation there) nor an annotated field:
`info.BoxType = typeof(Box)` followed by
Activator.CreateInstance(info.BoxType) failed at run time because Box's
constructor was not kept (the IL front-end already handled fields).

- NoteDynamicallyAccessedArguments falls back to the property's
  annotation for a setter's value (both front-ends).
- The source front-end's simple assignment notes the setter's annotated
  value for a property target, and marks typeof values assigned to an
  annotated Type field, as the IL front-end's NoteDynamicallyAccessedField
  does.

Sample 1307 is recorded from .NET.
csharpc's Uri refused a relative reference with any character .NET would
escape, and an implicit file path likewise, so XmlReader.Create(path)
failed for any path with a space (XmlUrlResolver makes a relative Uri of
it, then an absolute one from Path.GetFullPath): on macOS that is every
file in an "X Y.app" bundle.

Spaces are now accepted in both: a relative reference keeps them as they
are in OriginalString and ToString(), as .NET does; an implicit file path
escapes them to %20 in the URI's path (AbsoluteUri, AbsolutePath,
Segments) and keeps them in LocalPath and ToString(). '%' stays refused,
so unescaping %20 for ToString() is exact; explicit file: URIs are
unchanged.

Sample 1308 is recorded from .NET.
MemoryMappedFile supported read-only maps only, and the view accessor had
none of UnmanagedMemoryAccessor's members, so Read<T>/Write<T> calls were
unsupported. Now:

- CreateFromFile accepts MemoryMappedFileAccess.ReadWrite, growing the
  file to the capacity first as .NET does; CreateViewAccessor maps a
  writable view (mmap PROT_READ|PROT_WRITE, MAP_SHARED; Windows
  PAGE_READWRITE/FILE_MAP_WRITE) and refuses one on a read-only map.
- UnmanagedMemoryAccessor (shadow): Capacity, CanRead/CanWrite, Read<T>/
  Write<T>, ReadArray/WriteArray and the scalar reads and writes, over
  the view's SafeBuffer, with .NET's checks in .NET's order (closed,
  access, negative position, room) and messages.
  MemoryMappedViewAccessor derives from it, as in .NET.
- Copy-on-write, execute access and named maps still throw
  NotSupportedException.

Sample 1309 is recorded from .NET.
filipnavara and others added 23 commits November 10, 2026 09:19
A delegate argument of a P/Invoke was refused ("use [UnmanagedCallersOnly]
+ function pointers"). It is now passed as .NET's marshaller passes it:
a native-callable pointer to the delegate, one of its type's reverse
thunks (the pointer Marshal.GetFunctionPointerForDelegate hands out),
null for null. The argument keeps the delegate alive for the call; a
callback kept past the call is the caller's to keep alive, as in .NET.
Generic delegate types stay refused.

Sample 1347 (libc's qsort and bsearch with a lambda, a method group, a
stored delegate and a closure) is recorded from .NET; on Windows, where
"libc" doesn't exist, it is recorded live like sample 286.
A SafeHandle argument of a P/Invoke was refused ("P/Invoke parameter of
reference type"). It is now marshalled as .NET's marshaller does: the
handle's value, DangerousAddRef for the call and DangerousRelease after
it. Every SafeHandle argument is checked first, in parameter order and
before anything is allocated or add-ref'ed, so a null handle throws
.NET's ArgumentNullException ("SafeHandle cannot be null.", pHandle) and
a closed one its ObjectDisposedException with nothing to undo. Returning
a SafeHandle and passing one by ref stay unsupported.

Sample 1348 (open/read/lseek on /dev/null through libc) is recorded from
.NET; it is live on Windows (no libc) and skipped on WASI (no /dev/null).
Marshal.GetFunctionPointerForDelegate and GetDelegateForFunctionPointer
refused a delegate with a struct parameter or result ("delegate 'X'
marshalled to native code: parameter 'p' of type 'S'"): the reverse
thunks passed values in LLVM's own representation, which is the C ABI
only for scalars. A struct needs the ABI's classification (System V
eightbytes, AAPCS64 composites and HFAs, byval copies, sret results),
which unmanaged function pointers and [UnmanagedCallersOnly] methods
already have (ModuleCodeGen.NativeCalls.cs).

Such a signature now reuses it: each pool slot's thunk takes the
managed structs, and an adapter with the native signature (NativeShapeOf,
the entry thunk's rebuilding of structs) is the pointer native code
gets; a delegate over a native pointer calls it through NativeCallStub.
Signatures without a struct by value are unchanged.

Sample 1349 is recorded from .NET.
A preserialized .resources (GenerateResourceUsePreserializedResources) stores a
user type in one of PreserializedResourceWriter's formats; csharpc created
format 3 (the TypeConverter's string) only. Format 2, the TypeConverter's
byte array (every image and icon a WinForms .resx embeds), and format 4, a
stream for the type's (Stream) constructor (a ResXFileRef), were "not
supported by csharpc yet" (jonathanperis#300):
- ResourcesFile reads their 7-bit length and bytes, as
  DeserializingResourceReader does;
- ResourceConverters generates ResourceObjectFromBytes (the type's converter,
  ConvertFrom(byte[])) and ResourceObjectFromStream (new T(stream), or .NET's
  MissingMethodException for a type without a public (Stream) constructor)
  for the types the .resx files name;
- ResourceManager.GetObject calls them, with a read-only MemoryStream for
  format 4 and TypeDescriptor's ArrayConverter for a byte[] in format 2, as
  .NET's DeserializingResourceReader.

The project test PreserializedBinary (against dotnet run) uses a type of the
program with a byte-array converter and a (Stream) constructor in place of
System.Drawing's Bitmap and Icon.
.NET creates a format-4 (stream) resource with Activator.CreateInstance(type,
stream). An exception from the constructor comes wrapped in a
TargetInvocationException, and a type with no (Stream) constructor gives a
MissingMethodException whose inner exception is the binder's "Member not
found.". A type or constructor the generated code cannot name gets no case,
so GetObject's explicit "not supported" error stays. The project test
gains a throwing (Stream) constructor and prints inner exceptions.
EmitExceptionConstructor bound the inner exception only from a parameter
named innerException (or e for UriFormatException). MissingMemberException,
MissingMethodException, MissingFieldException, TargetInvocationException,
RegexMatchTimeoutException and others call it inner, so their
InnerException read null. The SqlTypes exceptions call it e. The parameter
typed System.Exception is now the inner exception, whatever its name.

TypeInitializationException(fullTypeName, innerException) also gets .NET's
message, "The type initializer for 'X' threw an exception.", instead of
the default text.

Sample 1565_exception_inner_parameter_names, recorded from .NET.
Activator.CreateInstance(type, args) filters the constructors by arity
and then asks the default binder. When some constructor has the
arguments' count but none binds, the MissingMethodException carries the
binder's "Member not found." as its inner exception. When none has that
count, there is no inner exception.

Sample 1564_activator_missing_constructor_inner, recorded from .NET.
The generated format-4 case gave every type without a (Stream) constructor
the binder's inner exception. .NET adds it only when some public
constructor takes one argument; otherwise there is none. Abstract types
get no case, so GetObject's explicit error stays rather than a guessed
message. The project test gains a type with no one-argument constructor.
csharpc's System.IO.Pipes was a stand-in whose every pipe threw 'not
supported', so NamedPipeClientStream and NamedPipeServerStream could not
be used (jonathanperis#102). .NET's own System.IO.Pipes imports 17 libSystem.Native
entry points; the C# contract lacked 6. They are now exported, written
as pal_io.c and pal_uid.c do:
- FcntlSetFD, through pal_io.c's ConvertOpenFlags;
- FcntlCanGetSetPipeSz, FcntlGetPipeSz and FcntlSetPipeSz: F_GETPIPE_SZ
  and F_SETPIPE_SZ on Linux, ENOTSUP elsewhere;
- GetPeerID: SO_PEERCRED on Linux, getpeereid on macOS;
- SetEUid: seteuid.

macOS also gets GetPwUidR, converting its larger struct passwd. WASI gets
ENOTSUP stubs. The assembly is now compiled from IL on Linux and macOS;
the stand-in remains on Windows only, where Pipes calls Win32.

Sample 1567_named_pipes, recorded from .NET, covers:
- a named pipe's connect, byte and text exchange, and disconnect;
- an anonymous pipe;
- a client timing out with no server.
It is skipped on WASI (no Unix sockets) and is a known gap on Windows.
ValueType.ToString() is the type's full name, but csharpc formatted only
user structs that way, so interpolating a framework struct that does not
override ToString (CancellationToken, in System.IO.Pipes' IL) was 'not
supported'. A non-generic one now formats as its metadata name, with
Outer+Inner for nested types, as Type.FullName gives.

Sample 1568_library_struct_default_tostring, recorded from .NET.
An override may override only the setter (AnonymousPipeClientStream.ReadMode)
or only the getter. C# binds the missing accessor to the nearest overridden
property's, called virtually. csharpc reported reading a set-only property,
or found no backing field for a write. Both now walk the overridden
properties to the nearest accessor.

Sample 1569_property_setter_only_override, recorded from .NET.
A compound assignment through an override with one accessor
(d.Value += 1, ++) read the property's own getter and setter directly.
The captured path wrote a backing field that does not exist, and the
direct path threw a NullReferenceException in the compiler. Both now use
the nearest overridden accessor, called virtually, as plain reads and
writes already do. Sample 1569 adds compound assignments, including ++
through a base-typed variable holding a more derived object.
…ring

Two more of jonathanperis#93's hotspots grew with dispatches x types:
- NoteInterfaceDispatch: each new dispatch through one generic interface
  instantiation visited every method-table entry of that interface and
  recomputed each entry's InterfaceDispatchKey (a metadata-name string),
  and registering a table walked every dispatch. Entries and dispatched
  slots are now indexed by key, and the keys are cached.
- FindUniqueImplementation and InterfaceReimplementedBelow: each walked
  every hierarchy type's base chain. A one-time index of each type's
  descendants replaces that, through the types csharpc serves a library
  type with, as DerivesFromOrEqualsServed did (which it replaces). The
  hierarchy is complete before any method is lowered.

The indexed lists keep their insertion order and are merged back by it,
so the slots are requested in the order the full scans used. The emitted
module does not change: the LLVM IR of a 500-class program is
byte-identical before and after.

On a generator of N classes under one abstract base, each implementing
IComparable<T> and IEquatable<T> dispatched per instantiation, at -O0:
- compile time: 33.6/76.2/156.6 s before, 32.4/60.2/137.6 s after, for
  500/1000/2000 classes;
- peak memory: 862/1459/2685 MB before, 888/1487/2261 MB after;
- every output program prints the same result.
@jonathanperis

Copy link
Copy Markdown
Owner

Thanks, @filipnavara. I'm taking this through to merge. I've merged current main into the branch and marked it ready for review.

To avoid re-running CI on every PR after each merge, the open code PRs are stacked in merge order: #513 → #510 → #503 → #291 → #279 → #284 → #297 → #298 → #283 → #299 → #293. Each branch contains the PRs before it, so its diff shows them until they merge.

Local checks on the top of the stack, which contains all of them:

  • Build: clean.
  • Your samples, re-recorded from .NET on Linux: identical to your macOS recordings.
  • Nearby samples: 104 runs passed at -O0 and -O2, and 52 through the IL front-end.
  • Size budgets: passed.
  • Full -O2 suite: 869 of 869 passed.

main now maps views through SafeFileHandle's OS handle instead of the C runtime descriptor (#424). I moved your MapView(…, writable) overloads onto that handle on Linux, macOS and Windows.

On Windows, XmlReader.Create(Path.Combine("dir with space", "p.xml")) makes
a relative Uri of "dir with space\p.xml", which the space-only change still
refused. .NET keeps backslashes as they are in a relative reference's
OriginalString and ToString(), as it does spaces.

IsWellFormedOriginalString / IsWellFormedUriString now return false for a
relative reference with a space or a backslash, as .NET does (characters it
would have to escape); they returned true once spaces were accepted.
Resolving such a reference against a base stays NotSupportedException.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants