Skip to content

Latest commit

 

History

History
328 lines (266 loc) · 17.2 KB

capabilities.md

File metadata and controls

328 lines (266 loc) · 17.2 KB

CIL2CPP Capabilities

Last updated: 2026-03-21

This document describes what CIL2CPP can currently do. For development plans and progress, see roadmap.md.

中文版 (Chinese)

Overview

CIL2CPP is a C# → C++ AOT compiler (similar to Unity IL2CPP). Currently supports complete C# syntax (100% IL opcode coverage), BCL compiled from IL (Unity IL2CPP architecture), ~395 ICall entries. 1,291 C# + 595 C++ + 204 integration tests all passing. 15 NuGet packages validated (Newtonsoft.Json, DI+Logging+Console, Humanizer, Polly, Serilog+Console, Configuration+Binder, Hashids.net, GuardClauses, Slugify.Core, Stateless, FluentValidation). Regex, DateTime, Decimal BCL features validated. 3 real project validations (MiniCsvTool, TodoManager, HealthChecker).

Key Metrics

Metric Count
IL opcode coverage 100% (all ~230 ECMA-335 opcodes)
ICallRegistry entries ~395 (covering 30+ categories)
C# compiler tests 1,291 (xUnit)
C++ runtime tests 595 (Google Test, 18 test files)
End-to-end integration tests 204 (34 test projects)
Runtime headers 37

C# Feature Support Table

✅ Supported ⚠️ Partial support (BCL/runtime limitation) ❌ Not supported (missing icall or AOT limitation)

All C# syntax compiles to standard IL via Roslyn; the CIL instruction translation layer covers all opcodes. Status marks ⚠️/❌ reflect limitations at the BCL dependency chain or runtime icall level.

Basic Types

Feature Status Notes
int, long, float, double ✅ Maps to C++ int32_t, int64_t, float, double
bool, byte, sbyte, short, ushort, uint, ulong ✅ Complete primitive type mapping
char ✅ UTF-16 (char16_t)
string ✅ Immutable, UTF-16 encoding, literal interning pool
IntPtr, UIntPtr ✅ intptr_t, uintptr_t
Type conversions (all Conv_*) ✅ 13 basic + 20 checked
struct (value types) ✅ initobj/ldobj/stobj + boxing/unboxing + copy + ldind/stind
enum ✅ typedef + constexpr constants + TypeInfo
Boxing/Unboxing ✅ box<T>() / unbox<T>(), Nullable box unwrapping
Nullable<T> ✅ BCL IL compiled + box unwrapping + generic monomorphization
ValueTuple ✅ BCL IL compiled, supports >7 nesting
record / record struct ✅ Method synthesis (ToString/Equals/GetHashCode/Clone), with expressions

Object-Oriented

Feature Status Notes
Class definition / constructors ✅ Instance fields + static fields + methods + newobj
Static constructors (.cctor) ✅ _ensure_cctor() once-guard
Inheritance (single) ✅ Base class field copying + VTable inheritance
Virtual methods / polymorphism ✅ VTable dispatch
Properties ✅ get_/set_ method calls
Type casting (is/as) ✅ isinst → object_as(), castclass → object_cast()
Abstract classes/methods ✅ VTable correctly allocates slots
Interfaces ✅ InterfaceVTable dispatch
Generic classes/methods ✅ Monomorphization
Operator overloading ✅ op_Addition etc. static method calls
Finalizers / destructors ✅ TypeInfo.finalizer + BoehmGC registration
Default interface methods (DIM) ✅ Interface default implementations as VTable fallback
Generic covariance/contravariance ✅ ECMA-335 variance-aware checking

Control Flow

Feature Status Notes
if/else, while/for, do-while ✅ All conditional branch instructions
switch (IL switch table) ✅ C++ switch/goto jump table
Pattern matching (switch expressions) ✅ Roslyn compiles to standard IL
Range / Index (..) ✅ Index/Range structs
Checked arithmetic ✅ OverflowException throwing

Arrays

Feature Status Notes
Single-dimensional arrays ✅ newarr + ldelem/stelem all types + bounds checking
Array initializers ✅ RuntimeHelpers.InitializeArray → memcpy
Multi-dimensional arrays (T[,]) ✅ MdArray runtime
Span<T> / ReadOnlySpan<T> ✅ BCL IL compiled, ref struct

Exception Handling

Feature Status Notes
throw / try / catch / finally ✅ setjmp/longjmp macros
rethrow ✅ CIL2CPP_RETHROW
Exception filters (catch when) ✅ ECMA-335 Filter handler
Nested try/catch/finally ✅ Full multi-level nesting support
Custom exception types ✅ Inheriting Exception
Stack traces ✅ Windows: DbgHelp, POSIX: backtrace (Debug only)
using statements ✅ try/finally + IDisposable interface dispatch

Standard Library (BCL)

Feature Status Notes
System.Object ✅ ToString/GetHashCode/Equals/GetType
System.String ✅ Layout icall + BCL IL compiled (Concat/Format/Join/Split etc.)
Console.WriteLine/Write/ReadLine ✅ Full BCL IL chain compiled
System.Math / MathF ✅ ~40 icalls
List<T> / Dictionary<K,V> ✅ BCL IL compiled
LINQ ✅ Where/Select/OrderBy etc., BCL IL compiled
yield return / IEnumerable ✅ Iterator state machines
IAsyncEnumerable<T> ✅ await foreach
System.IO (File/Path/Directory) ✅ 22 ICalls, C++17 filesystem
System.IO.Compression ✅ GZipStream/DeflateStream via zlib (FetchContent), CompressionNative_* interop
System.Text.RegularExpressions ✅ Interpreter mode (non-Compiled). IsMatch/Match/Replace/Split, named groups, RegexOptions, timeout
System.DateTime / TimeSpan ✅ DateTime.Now/UtcNow/Parse/ToString, TimeSpan arithmetic, DateTimeOffset, formatting
System.Decimal ✅ Arithmetic, Parse/TryParse, ToString, Math.Round/Floor/Ceiling
System.Net (Socket/DNS/HTTP) ✅ Socket TCP loopback ✅, DNS resolution ✅, HttpClient HTTP GET ✅, HTTPS GET ✅ (Windows, via Winsock/SChannel P/Invoke). TLS via OS-provided SChannel.

Delegates & Events

Feature Status Notes
Delegates / multicast delegates ✅ delegate_create / Combine / Remove
Events ✅ add_/remove_ + Delegate.Combine
Lambda / closures ✅ Compiler-generated DisplayClass

Advanced Features

Feature Status Notes
async / await ✅ Thread pool + continuation + Task combinators
CancellationToken ✅ BCL IL compiled
Multithreading ✅ Thread/Monitor/Interlocked/lock/volatile
Reflection ✅ typeof/GetType/GetMethods/GetFields/MethodInfo.Invoke
Attributes ✅ Metadata storage + runtime query
unsafe (pointers/fixed/stackalloc) ✅ Pointer types + BoehmGC conservative scanning
P/Invoke / DllImport ✅ extern "C" + type marshaling + SetLastError
Span<T> ✅ ref struct + BCL IL compiled

ICallRegistry Breakdown (~395 entries)

Category Count Description
System.Math 28 Sqrt/Sin/Cos/Pow/Log/Floor/Ceiling etc. double versions
System.MathF 20 Corresponding float versions
System.ThrowHelper 17 Various exception throw helpers
System.Char 16 IsLetter/IsDigit/IsUpper/ToUpper/ToLower etc.
System.Threading.Interlocked 14 Increment/Decrement/Exchange/CompareExchange
System.Array 13 Copy/Clear/GetLength/GetLowerBound/Reverse/Sort
System.IO.File 12 Exists/ReadAllText/WriteAllText/ReadAllBytes/Delete/Copy/Move
System.String 12 FastAllocateString/get_Length/get_Chars/Comparison
System.Globalization.CompareInfo 11 Culture-aware string comparison
System.GC 11 Collect/WaitForPendingFinalizers/GetTotalMemory
System.IO.Path 8 GetFullPath/GetDirectoryName/GetFileName/GetExtension/GetTempPath
System.Threading.Monitor 8 Enter/Exit/TryEnter/Wait/Pulse/PulseAll
System.Environment 8 Exit/GetEnvironmentVariable/GetCommandLineArgs/ProcessorCount
System.Object 6 GetType/ToString/GetHashCode/Equals/MemberwiseClone
System.Threading.Thread 6 Start/Join/Sleep/CurrentThread/ManagedThreadId
System.Runtime.InteropServices.Marshal 6 AllocHGlobal/FreeHGlobal/AllocCoTaskMem/FreeCoTaskMem/GetLastPInvokeError
System.Buffer 5 BlockCopy/MemoryCopy/ByteLength
System.Delegate/MulticastDelegate 5 Combine/Remove/GetInvocationList
System.RuntimeHelpers 4 InitializeArray/IsReferenceOrContainsReferences
System.Runtime.InteropServices.GCHandle 4 Alloc/Free/Target/IsAllocated
System.ArgIterator 4 Varargs support
System.Globalization.OrdinalCasing 3 Ordinal case conversion
System.IO.Directory 2 Exists/CreateDirectory
System.Runtime.InteropServices.SafeHandle 8 .ctor/DangerousGetHandle/SetHandle/DangerousAddRef/DangerousRelease/IsClosed/SetHandleAsInvalid/Dispose
Other (Volatile, Enum, Type, HashCode, Marvin, NativeLibrary, ...) ~18 1-3 entries each

System.IO Implementation Details

Architecture

System.IO uses ICall interception at the public API level, intercepting File/Path/Directory calls and using C++17 <filesystem> for cross-platform support.

Implemented ICalls (22)

File (12): Exists, ReadAllText (1/2 params), WriteAllText (1/2 params), ReadAllBytes, WriteAllBytes, Delete, Copy, Move, ReadAllLines, AppendAllText

Path (8): GetFullPath, GetDirectoryName, GetFileName, GetFileNameWithoutExtension, GetExtension, GetTempPath, Combine (2 params), Combine (3 params)

Directory (2): Exists, CreateDirectory

Streaming I/O (Windows)

FileStream / StreamReader / StreamWriter compile from BCL IL and work end-to-end on Windows (via kernel32 P/Invoke). Linux needs System.Native integration (Phase B.5).

Not Implemented

Feature Description
Directory enumeration No GetFiles / EnumerateFiles / Delete
File info No FileInfo / DirectoryInfo, no timestamps/attributes

P/Invoke Implementation Details

Supported

  • DllImport declarations (extern "C", auto-filters .NET internal modules)
  • Basic type marshaling (int/long/float/double/IntPtr passed directly)
  • String marshaling (Ansi: UTF-8, Unicode: zero-copy UTF-16)
  • Boolean marshaling (C# bool ↔ Win32 BOOL)
  • Blittable struct marshaling (SequentialLayout value types passed directly)
  • Callback delegates (function pointers: extract method_ptr → C function pointer)
  • SetLastError (TLS storage, clear before + capture after call)
  • Marshal.AllocHGlobal/FreeHGlobal/AllocCoTaskMem/FreeCoTaskMem

FIXME / Not Implemented

Feature Status Description
Calling conventions ✅ StdCall/FastCall/ThisCall emitted to extern declarations
CharSet.Auto ⚠️ Hard-coded to Unicode
SafeHandle methods ⚠️ 8 ICalls (.ctor/DangerousGetHandle/SetHandle/DangerousAddRef/DangerousRelease/IsClosed/SetHandleAsInvalid/Dispose), missing ReleaseHandle virtual dispatch
MarshalAs attribute ✅ Cecil MarshalInfo parsing, 21 type mappings (LPStr/LPWStr/Bool/integers etc.)
Out/In attributes ✅ PInvokeDirection fully parsed, bool* copy-back, blittable pointers write directly (C.7.2)
Array marshaling / Ref String ✅ LPArray direction-aware + SizeParamIndex debug assertion, ByValTStr/ByValArray inline arrays (C.7.3)

Known Limitations

Limitation Description
CLR internal type dependencies BCL IL references QCallTypeHandle / MetadataImport etc. → method bodies auto-stubbed
BCL deep dependency chains Middle layers stubbed → upper-level methods unavailable
System.Net (HTTPS edge cases) HttpClient HTTP/HTTPS GET working; complex scenarios (redirects, chunked encoding, auth) not yet validated
Regex Compiled mode Compiled mode uses Reflection.Emit (AOT incompatible); interpreter mode works
SIMD Requires platform-specific intrinsics, currently uses scalar fallback structs
32-bit targets Pointer size hardcoded to 8 bytes (64-bit only). ARM/x86 deferred to Phase F

Platform Compatibility Matrix

Compatibility levels: Full = identical to .NET | Functional = works with simplified metadata | Stub = returns placeholder values | N/A = not implemented

Feature Area Windows x64 Linux x64 macOS Notes
Console I/O Full Full Full BCL IL compiled
Math/MathF Full Full Full ~45 icalls, direct C++ stdlib
String operations Full Full Full BCL IL compiled, ICU globalization
Collections (List/Dict/LINQ) Full Full Full BCL IL compiled
async/await Full Full Full Custom thread pool + continuations
File I/O (FileStream) Full N/A N/A Windows: kernel32 P/Invoke. Linux: needs System.Native (Phase B.5)
File I/O (File.ReadAllText) Functional N/A N/A HACK: bypasses BCL IL, UTF-8 only. Will be removed (Phase H.3)
Socket (TCP) Full N/A N/A Windows: ws2_32 P/Invoke
DNS resolution Full N/A N/A Windows: GetAddrInfoW P/Invoke
HttpClient HTTP GET Full N/A N/A SocketsHttpHandler → Socket → ws2_32 P/Invoke
HttpClient HTTPS GET Full N/A N/A SslStream → SChannel (secur32/sspicli) P/Invoke
Reflection (GetType/typeof) Full Full Full TypeInfo-based
Reflection (GetMethods/GetFields) Functional Functional Functional Returns correct names, simplified attributes
Reflection (BindingFlags) Stub Stub Stub Returns hardcoded Public|Instance (0x14)
Reflection (TypeCode) Full Full Full 17 primitives mapped to correct TypeCode enum values (Phase H.1 ✅)
Reflection (IsPublic/visibility) Full Full Full TypeFlags::Public/NestedPublic from Cecil metadata (audit ✅)
Reflection (StackFrame) Stub Stub Stub Returns nullptr for method info
Reflection (Assembly metadata) Stub Stub Stub No assembly objects. Needs Phase D
Thread priority Stub Stub Stub No-op, returns Normal
Thread managed ID Full Full Full Unique atomic ID per thread (main=1, workers from 2). P0 fix: eliminated duplicate ID risk
P/Invoke (kernel32/ws2_32) Full N/A N/A Windows-specific
DLL symbol loading Full N/A N/A Windows: GetProcAddress. Linux: dlsym pending
SIMD execution N/A N/A N/A Scalar fallback structs only
Encoding (non-UTF-8) Stub N/A N/A File ICalls ignore Encoding param. Fix: remove ICalls (Phase H.3)

Reflection ICall Status

12 of 23 reflection icalls return simplified/placeholder values. Full reflection fidelity requires Phase D (NativeAOT metadata).

ICall Expected (.NET) Current (CIL2CPP) Fix Phase
Type.GetTypeCode Per-type enum (Int32→9, String→18, etc.) Correct ✅ (17 primitives mapped) H.1 Done
Type.IsPublic Actual visibility Correct ✅ (TypeFlags::Public) H.1 Done
Type.IsAbstract Actual flag Correct ✅ —
Type.IsValueType Actual flag Correct ✅ —
Type.IsArray Actual flag Correct ✅ —
Type.IsNestedPublic Nested visibility Correct ✅ (TypeFlags::NestedPublic) Audit Done
Type.IsEnumDefined Enum value lookup Always false D
Type.IsEquivalentTo Structural equiv Pointer equality only D
RuntimeTypeHandle.GetElementType Array/pointer element type Returns nullptr D
RuntimeTypeHandle.GetToken Metadata token Returns 0 D
RuntimeTypeHandle.GetAssembly Assembly object Returns nullptr D
RuntimeTypeHandle.IsByRefLike ref struct detection Always false D
MethodBase.IsVirtual Actual flag Always false D
MethodInfo.BindingFlags Actual flags Hardcoded 0x14 D
MethodInfo.GetGenericArguments Generic type args Returns nullptr D
MethodInfo.GetDeclaringType Declaring type Returns nullptr D
Delegate.get_Method Target MethodInfo Returns nullptr D
StackFrame.GetMethod Stack method info Returns nullptr F.4
GCHandle.CompareExchange Atomic table op Returns handle unchanged F.4

Test Coverage

C++ Runtime Tests (595, 18 files)

Module Test Count
Exception 71
Globalization 66
Reflection 53
String 52
Type System 48
Checked 34
Array 31
Collections 31
MemberInfo 29
Object 28
Boxing 26
Async 24
Unicode 40
Delegate 18
Threading 17
GC 16
TypedReference 11
Stubs 0
Total 595

End-to-End Integration Tests (204)

Full compilation pipeline: C# .csproj → codegen → CMake configure → C++ build → run → verify output. Parallel execution via ThreadPoolExecutor (default DOP=4, ~7 min; sequential ~21 min). Covers 34 test projects: HelloWorld, ArrayTest, FeatureTest, ArglistTest, MultiAssemblyTest, SystemIOTest, FileStreamTest, SocketTest, HttpGetTest, HttpTest, HttpsGetTest, DirTest, JsonSGTest, NuGetSimpleTest (Newtonsoft.Json), DITest (DI+Logging+Console), HumanizerTest, PollyTest, PInvokeTest, SerilogTest, ConfigTest, CompressionTest, ValidationApp, RegexTest, DateTimeTest, DecimalTest, HashidsTest, GuardClausesTest, SlugifyTest, StatelessTest (Stateless), MiniCsvTool, TodoManager, HealthChecker, FluentValidationTest (FluentValidation), MiniServiceApp.