Skip to content

[Mono][Interpreter] Reverse P/Invoke / [UnmanagedCallersOnly] returning bool or char does not zero-extend return register on Apple ARM64 #136578

Description

@mattleibow

Description

When a reverse P/Invoke callback (such as an [UnmanagedCallersOnly] method or native function pointer callback) with a return type of bool (MONO_TYPE_BOOLEAN) or char (MONO_TYPE_CHAR) is executed by the Mono interpreter (<UseInterpreter>True</UseInterpreter>) on 64-bit targets, interp_frame_arg_to_data (index == -1) calls stackval_to_data_sign_ext (src/mono/mono/mini/interp/interp.c), which only handles MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_I4, and MONO_TYPE_U4, and falls through to stackval_to_data for MONO_TYPE_BOOLEAN and MONO_TYPE_CHAR.

Because stackval_to_data performs a narrow 1-byte store (*(guint8*)data = ..., strb on ARM64) or 2-byte store (*(guint16*)data = ..., strh on ARM64) directly into &ccontext->gregs[0] (x0 on ARM64 / rax on x64), the upper bytes (bits 8..63 for bool, bits 16..63 for char) of ccontext->gregs[0] are not cleared and retain the bytes of the first incoming argument (x0).

On Apple ARM64 (iOS, Mac Catalyst, tvOS, macOS under Darwin's ARM64 ABI), bool is a 1-byte type that must be zero-extended to 32 bits (w0) by the callee upon return (Apple ARM64 Function Calling Conventions). Consequently, Apple Clang compiles C/C++ callers checking a bool return value using 32-bit cbz w0 / cbnz w0 rather than testing only bit 0 (tbz w0, #0):

blr x8                  ; call bool (*callback)(void* s, void* context)
cbz w0, L_false         ; tests all 32 bits of w0!

When a managed [UnmanagedCallersOnly] callback returns false (0) under the Mono interpreter on iOS or Mac Catalyst (ARM64) and its first parameter (x0) has non-zero bits in bits 8..31 (for example, any pointer 0x000000016f...), w0 returns to native code as 0x6fxxxx00 instead of 0x00000000, and native C/C++ callers observe true instead of false.


Root Cause in src/mono/mono/mini/interp/interp.c

  1. On native-to-interpreter (n2i) exit, mono_arch_set_native_call_context_ret (src/mono/mono/mini/mini-arm64.c:2168) passes storage = arg_get_storage (ccontext, ainfo) (which points to &ccontext->gregs[ARMREG_R0]) to interp_cb->frame_arg_to_data ((MonoInterpFrameHandle)frame, sig, -1, storage):

    arg_set_val (ccontext, ainfo, storage);
    }
    }
    /* Set return value in the ccontext (for n2i return) */
    void
    mono_arch_set_native_call_context_ret (CallContext *ccontext, gpointer frame, MonoMethodSignature *sig, gpointer call_info, gpointer retp)
    {
    const MonoEECallbacks *interp_cb;
    CallInfo *cinfo = (CallInfo*)call_info;
    gpointer storage;
    ArgInfo *ainfo;
    if (sig->ret->type == MONO_TYPE_VOID)
    return;
    interp_cb = mini_get_interp_callbacks ();
    ainfo = &cinfo->ret;
    if (retp) {
    g_assert (ainfo->storage == ArgVtypeByRef);
    interp_cb->frame_arg_to_data ((MonoInterpFrameHandle)frame, sig, -1, retp);
    } else {
    g_assert (ainfo->storage != ArgVtypeByRef);
    int temp_size = arg_need_temp (ainfo);
    if (temp_size)
    storage = alloca (temp_size);
    else
    storage = arg_get_storage (ccontext, ainfo);
    interp_cb->frame_arg_to_data ((MonoInterpFrameHandle)frame, sig, -1, storage);
    if (temp_size)
    arg_set_val (ccontext, ainfo, storage);

  2. interp_frame_arg_to_data (src/mono/mono/mini/interp/interp.c:1691) calls stackval_to_data_sign_ext when index == -1:

    InterpFrame *iframe = (InterpFrame*)frame;
    InterpMethod *imethod = iframe->imethod;
    // If index == -1, we finished executing an InterpFrame and the result is at retval.
    if (index == -1)
    stackval_to_data_sign_ext (sig->ret, iframe->retval, data, sig->pinvoke && !sig->marshalling_disabled);
    else if (sig->hasthis && index == 0)

  3. stackval_to_data_sign_ext (src/mono/mono/mini/interp/interp.c:988-1028) sign-/zero-extends MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_I4, and MONO_TYPE_U4 to a full register (mono_i / mono_u), but omits MONO_TYPE_BOOLEAN and MONO_TYPE_CHAR:

    static void
    stackval_to_data_sign_ext (MonoType *type, stackval *val, void *data, gboolean pinvoke)
    {
    switch (type->type) {
    case MONO_TYPE_I1: {
    mono_i *p = (mono_i*)data;
    *p = (mono_i)((gint8)val->data.i);
    break;
    }
    case MONO_TYPE_U1: {
    mono_u *p = (mono_u*)data;
    *p = (mono_u)((guint8)val->data.i);
    break;
    }
    case MONO_TYPE_I2: {
    mono_i *p = (mono_i*)data;
    *p = (mono_i)((gint16)val->data.i);
    break;
    }
    case MONO_TYPE_U2: {
    mono_u *p = (mono_u*)data;
    *p = (mono_u)((guint16)val->data.i);
    break;
    }
    #if SIZEOF_VOID_P == 8
    case MONO_TYPE_I4: {
    mono_i *p = (mono_i*)data;
    *p = (mono_i)(val->data.i);
    break;
    }
    case MONO_TYPE_U4: {
    mono_u *p = (mono_u*)data;
    *p = (mono_u)((guint32)val->data.i);
    break;
    }
    #endif
    default:
    stackval_to_data (type, val, data, pinvoke);
    break;
    }
    }

    static void
    stackval_to_data_sign_ext (MonoType *type, stackval *val, void *data, gboolean pinvoke)
    {
    	switch (type->type) {
    		case MONO_TYPE_I1: {
    			mono_i *p = (mono_i*)data;
    			*p = (mono_i)((gint8)val->data.i);
    			break;
    		}
    		case MONO_TYPE_U1: {
    			mono_u *p = (mono_u*)data;
    			*p = (mono_u)((guint8)val->data.i);
    			break;
    		}
    		case MONO_TYPE_I2: {
    			mono_i *p = (mono_i*)data;
    			*p = (mono_i)((gint16)val->data.i);
    			break;
    		}
    		case MONO_TYPE_U2: {
    			mono_u *p = (mono_u*)data;
    			*p = (mono_u)((guint16)val->data.i);
    			break;
    		}
    #if SIZEOF_VOID_P == 8
    		case MONO_TYPE_I4: {
    			mono_i *p = (mono_i*)data;
    			*p = (mono_i)(val->data.i);
    			break;
    		}
    		case MONO_TYPE_U4: {
    			mono_u *p = (mono_u*)data;
    			*p = (mono_u)((guint32)val->data.i);
    			break;
    		}
    #endif
    		default:
    			stackval_to_data (type, val, data, pinvoke);
    			break;
    	}
    }
  4. Falling through to stackval_to_data (src/mono/mono/mini/interp/interp.c:878-896) writes only a guint8 (or guint16 for MONO_TYPE_CHAR):

    static int
    stackval_to_data (MonoType *type, stackval *val, void *data, gboolean pinvoke)
    {
    if (m_type_is_byref (type)) {
    gpointer *p = (gpointer*)data;
    *p = val->data.p;
    return MINT_STACK_SLOT_SIZE;
    }
    /* printf ("TODAT0 %p\n", data); */
    switch (type->type) {
    case MONO_TYPE_BOOLEAN:
    case MONO_TYPE_I1:
    case MONO_TYPE_U1: {
    guint8 *p = (guint8*)data;
    *p = GINT32_TO_UINT8 (val->data.i);
    return MINT_STACK_SLOT_SIZE;
    }
    case MONO_TYPE_I2:
    case MONO_TYPE_U2:

    	case MONO_TYPE_BOOLEAN:
    	case MONO_TYPE_I1:
    	case MONO_TYPE_U1: {
    		guint8 *p = (guint8*)data;
    		*p = GINT32_TO_UINT8 (val->data.i);
    		return MINT_STACK_SLOT_SIZE;
    	}

Disassembly From libmonosgen-2.0.dylib (.NET 10.0 Mac Catalyst / iOS ARM64)

In libmonosgen-2.0.dylib (net10.0-maccatalyst / net10.0-ios), _interp_frame_arg_to_data at index == -1 (0xed238) branches on sig->ret->type:

  • 0x04 (MONO_TYPE_I1) $\rightarrow$ ldrsb x8, [x8]; str x8, [x3] (64-bit sign-extended store into ccontext->gregs[0])
  • 0x05 (MONO_TYPE_U1) $\rightarrow$ ldrb w8, [x8]; str x8, [x3] (64-bit zero-extended store into ccontext->gregs[0])
  • 0x06 (MONO_TYPE_I2) $\rightarrow$ ldrsh x8, [x8]; str x8, [x3] (64-bit sign-extended store into ccontext->gregs[0])
  • 0x07 (MONO_TYPE_U2) $\rightarrow$ ldrh w8, [x8]; str x8, [x3] (64-bit zero-extended store into ccontext->gregs[0])
  • 0x02 (MONO_TYPE_BOOLEAN) and 0x03 (MONO_TYPE_CHAR) miss the 0x04..0x09 range and jump to _stackval_to_data (0xf6830), which emits:
    f6830: b9400288    ldr  w8, [x20]
    f6834: 39000268    strb w8, [x19]    ; <-- only overwrites byte 0 of ccontext->gregs[0]!
    

When the native-to-interp trampoline restores x0 from ccontext->gregs[0] (ldp x0, x1, [sp, ...]), bits 8..63 of x0/w0 still hold the first argument passed into the callback.


Suggested Fix

Add MONO_TYPE_BOOLEAN to the MONO_TYPE_U1 case and MONO_TYPE_CHAR to the MONO_TYPE_U2 case in stackval_to_data_sign_ext in src/mono/mono/mini/interp/interp.c:

		case MONO_TYPE_BOOLEAN:
		case MONO_TYPE_U1: {
			mono_u *p = (mono_u*)data;
			*p = (mono_u)((guint8)val->data.i);
			break;
		}
		case MONO_TYPE_CHAR:
		case MONO_TYPE_U2: {
			mono_u *p = (mono_u*)data;
			*p = (mono_u)((guint16)val->data.i);
			break;
		}

Reproduction & Context

  • Minimal standalone reproduction (without Skia): https://github.com/mattleibow/mono-interp-bool-return-repro
    • Tiny C library + .NET 10 Mac Catalyst (net10.0-maccatalyst, maccatalyst-arm64) console app with [assembly: DisableRuntimeMarshalling] and [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] callbacks returning bool (false), byte (0), char ('A'), and ushort ('A').
    • Passes ptr = 0x123456789ABCDEF0 in x0 (w0 = 0x9ABCDEF0).
    • Under <UseInterpreter>True</UseInterpreter>:
      Runtime: .NET 10.0.12 (maccatalyst-arm64)
      First arg (x0 / ptr): 0x123456789ABCDEF0 (low 32 bits w0 = 0x9ABCDEF0)
      
      === 1. [UnmanagedCallersOnly] returning bool (false) ===
        w0 observed by C caller : 0x9ABCDE00 (expected: 0x00000000)
        C `if (cb(ptr, ctx))`   : TRUE (111) <-- BUG!
      
      === 2. [UnmanagedCallersOnly] returning byte (0) [Workaround: MONO_TYPE_U1] ===
        w0 observed by C caller : 0x00000000 (expected: 0x00000000)
        C `if (cb(ptr, ctx))`   : false (222) [OK]
      
      === 3. [UnmanagedCallersOnly] returning char ('A' = 0x0041) ===
        w0 observed by C caller : 0x9ABC0041 (expected: 0x00000041)
        C `cb(ptr, ctx) == 'A'` : FALSE (222) <-- BUG!
      
      === 4. [UnmanagedCallersOnly] returning ushort (0x0041) [Workaround: MONO_TYPE_U2] ===
        w0 observed by C caller : 0x00000041 (expected: 0x00000041)
        C `cb(ptr, ctx) == 'A'` : true (111) [OK]
      
      RESULT: BUG REPRODUCED! Upper bytes of w0 were not zero-extended by the Mono interpreter.
      
    • Under <UseInterpreter>False</UseInterpreter> (Full AOT), all 4 cases pass (w0 = 0x00000000 for bool and w0 = 0x00000041 for char).
  • Discovered in mono/SkiaSharp#5464 (f76ba7c6b94) when C++ SkStreamPriv::RemainingLengthIsBelow on iOS and Mac Catalyst called a bool (*fHasLength)(const sk_stream_managedstream_t* s, void* context) [UnmanagedCallersOnly] callback that returned false (0):
    • C++ passed s (a non-null heap pointer 0x000000016f...) in x0.
    • Managed [UnmanagedCallersOnly] callback returned false (0).
    • Under <UseInterpreter>True</UseInterpreter>, strb wrote 0x00 to byte 0 of ccontext->gregs[0], leaving w0 non-zero (0x6fxxxx00).
    • Apple Clang's cbz w0 in RemainingLengthIsBelow evaluated hasLength() as true instead of false.
  • Workaround in C#: Declaring the [UnmanagedCallersOnly] method to return byte (MONO_TYPE_U1, 0 or 1) and casting the function pointer to delegate* unmanaged[Cdecl]<..., bool> routes through case MONO_TYPE_U1: in stackval_to_data_sign_ext and zero-extends x0/w0.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Interop-monountriaged

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions