Repository navigation
Description
Bug description
When running a xamarin forms app on an iOS device, while using pre-compilation, the MessagePackSerializer.Deserialize method throws an exception (System.NotImplementedException: byref delegate)
I've followed the readme https://github.com/neuecc/MessagePack-CSharp#aot-code-generation-support-for-unityxamarin and implemented the MS build task as described here https://github.com/neuecc/MessagePack-CSharp/blob/master/doc/msbuildtask.md to use pre-compiled types.
Repro steps
I've uploaded a small reproduction sample here: https://github.com/stefanbogaard86/MessagePack-iOS-sample,
this is the sample code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using MessagePack;
using Xamarin.Forms;
using MessagePack.Resolvers;
namespace MessagePackSample
{
[MessagePackObject]
public class CustomObject
{
[Key(0)]
public string Item1 { get; set; }
[Key(1)]
public DateTime Item2 { get;set; }
public override string ToString()
{
return $"[{Item1} - {Item2.ToShortDateString()}]";
}
}
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagePackSerializerOptions generatedResolverOptions =
MessagePackSerializerOptions.Standard
.WithResolver(
CompositeResolver.Create(
GeneratedResolver.Instance,
StandardResolver.Instance
));
var customObjects = new List<CustomObject>
{
new CustomObject() {Item1 = "Yesterday", Item2 = DateTime.Today.AddDays(-1)},
new CustomObject() {Item1 = "Today", Item2 = DateTime.Today},
new CustomObject() {Item1 = "Next week", Item2 = DateTime.Today.AddDays(7)}
};
var serializedObj = MessagePackSerializer.Serialize(customObjects, generatedResolverOptions);
try
{
var deserializedObj =
(IEnumerable<CustomObject>)MessagePackSerializer.Deserialize(typeof(IEnumerable<CustomObject>), serializedObj, generatedResolverOptions);
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
Expected behavior
The serialized object is deserialized when running a xamarin forms app on iOS.
Actual behavior
When trying to deserialize on xamarin forms iOS, an exception is thrown.
{System.NotImplementedException: byref delegate at System.Linq.Expressions.Interpreter.LightLambda.CreateCustomDelegate (System.Type delegateType) [0x001cf] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs:422 at System.Linq.Expressions.Interpreter.LightLambda.MakeDelegate (System.Type delegateType) [0x00012] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs:446 at System.Linq.Expressions.Interpreter.LightDelegateCreator.CreateDelegate (System.Runtime.CompilerServices.IStrongBox[] closure) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightDelegateCreator.cs:33 at System.Linq.Expressions.Interpreter.LightDelegateCreator.CreateDelegate () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightDelegateCreator.cs:28 at System.Linq.Expressions.Expression1[TDelegate].Compile (System.Boolean preferInterpretation) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs:211 at MessagePack.MessagePackSerializer+CompiledMethods..ctor (System.Type type) [0x0046d] in <e372d2478807460eabc86dc315aa3ac8>:0 at MessagePack.MessagePackSerializer+<>c.<.cctor>b__45_0 (System.Type t) [0x00000] in <e372d2478807460eabc86dc315aa3ac8>:0 at MessagePack.Internal.ThreadsafeTypeKeyHashTable1[TValue].AddToBuckets (MessagePack.Internal.ThreadsafeTypeKeyHashTable1+Entry[TValue][] buckets, System.Type newKey, MessagePack.Internal.ThreadsafeTypeKeyHashTable1+Entry[TValue] newEntryOrNull, System.Func2[T,TResult] valueFactory, TValue& resultingValue) [0x00045] in <e372d2478807460eabc86dc315aa3ac8>:0 at MessagePack.Internal.ThreadsafeTypeKeyHashTable1[TValue].TryAddInternal (System.Type key, System.Func2[T,TResult] valueFactory, TValue& resultingValue) [0x000d2] in <e372d2478807460eabc86dc315aa3ac8>:0 at MessagePack.Internal.ThreadsafeTypeKeyHashTable1[TValue].GetOrAdd (System.Type key, System.Func2[T,TResult] valueFactory) [0x0000d] in <e372d2478807460eabc86dc315aa3ac8>:0 at MessagePack.MessagePackSerializer.GetOrAdd (System.Type type) [0x00000] in <e372d2478807460eabc86dc315aa3ac8>:0 at MessagePack.MessagePackSerializer.Deserialize (System.Type type, System.ReadOnlyMemory1[T] bytes, MessagePack.MessagePackSerializerOptions options, System.Threading.CancellationToken cancellationToken) [0x00000] in :0 at MessagePackSample.MainPage.OnAppearing () [0x000f5] in C:\Projects\MessagePack-iOS-sample\MessagePackSample\MessagePackSample\MessagePackSample\MainPage.xaml.cs:54 }
- Version used:
Mono Framework MDK
Runtime:
Mono 6.12.0.140 (2020-02/51d876a041e) (64-bit)
Package version: 612000140
Xamarin.Forms 5.0.0.2125
MessagePack 2.3.85
MessagePack.MSBuild.Task 2.3.85
Additional context
It's working as expected on Android.
Activity
RemcoDEV commentedon Nov 9, 2021
We experience the same issue.
KazysNoobiys commentedon Feb 1, 2022
I have the same thing. Please fix it ASAP!
When I build the project locally, on my machine, everything works correctly. But if you build the project through Appcenter, the following error appears
The error occurs only in the release, in debug mode all is normal.
After researching, I found out that it was necessary to enable "enable mono interpreter" in the project settings. After that, everything works. Unfortunately, this is due to the increased package and other overhead.
Perhaps someone has a workaround?
EXCEPTION: System.IO.InvalidDataException: Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked. ---> System.IO.InvalidDataException: Deserializing object of the
SlideHiddenEventDtotype for 'argument' failed. ---> System.NotImplementedException: byref delegateat System.Linq.Expressions.Interpreter.LightLambda.CreateCustomDelegate (System.Type delegateType) <0x100feaf40 + 0x00720> in <59551ad1b0244c86ada93d710ff2e802#d2407fe79a8b45166ed88c1badc6898a>:0
at System.Linq.Expressions.Interpreter.LightLambda.MakeDelegate (System.Type delegateType) <0x100feb6b0 + 0x00047> in <59551ad1b0244c86ada93d710ff2e802#d2407fe79a8b45166ed88c1badc6898a>:0
at System.Linq.Expressions.Interpreter.LightDelegateCreator.CreateDelegate (System.Runtime.CompilerServices.IStrongBox[] closure) <0x100fe4280 + 0x00057> in <59551ad1b0244c86ada93d710ff2e802#d2407fe79a8b45166ed88c1badc6898a>:0
at System.Linq.Expressions.Interpreter.LightDelegateCreator.CreateDelegate () <0x100fe4250 + 0x00017> in <59551ad1b0244c86ada93d710ff2e802#d2407fe79a8b45166ed88c1badc6898a>:0
at System.Linq.Expressions.Expression
1[TDelegate].Compile (System.Boolean preferInterpretation) <0x100fb0260 + 0x00047> in <59551ad1b0244c86ada93d710ff2e802#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.MessagePackSerializer+CompiledMethods..ctor (System.Type type) <0x102aa4c20 + 0x00e7b> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.MessagePackSerializer+<>c.<.cctor>b__45_0 (System.Type t) <0x102aa7bd0 + 0x0002f> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.Internal.ThreadsafeTypeKeyHashTable1[TValue].AddToBuckets (MessagePack.Internal.ThreadsafeTypeKeyHashTable1+Entry[TValue][] buckets, System.Type newKey, MessagePack.Internal.ThreadsafeTypeKeyHashTable1+Entry[TValue] newEntryOrNull, System.Func2[T,TResult] valueFactory, TValue& resultingValue) <0x102af2df0 + 0x0019b> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.Internal.ThreadsafeTypeKeyHashTable1[TValue].TryAddInternal (System.Type key, System.Func2[T,TResult] valueFactory, TValue& resultingValue) <0x102af2a40 + 0x00303> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.Internal.ThreadsafeTypeKeyHashTable1[TValue].GetOrAdd (System.Type key, System.Func2[T,TResult] valueFactory) <0x102af3530 + 0x00117> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.MessagePackSerializer.GetOrAdd (System.Type type) <0x102aa4480 + 0x00053> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at MessagePack.MessagePackSerializer.Deserialize (System.Type type, MessagePack.MessagePackReader& reader, MessagePack.MessagePackSerializerOptions options) <0x102aa4030 + 0x0001b> in <e372d2478807460eabc86dc315aa3ac8#d2407fe79a8b45166ed88c1badc6898a>:0 at Microsoft.AspNetCore.SignalR.Protocol.DefaultMessagePackHubProtocolWorker.DeserializeObject (MessagePack.MessagePackReader& reader, System.Type type, System.String field) <0x102a649f0 + 0x00033> in <a3a64c71038647ea91c7630ffcbce0a0#d2407fe79a8b45166ed88c1badc6898a>:0 --- End of inner exception stack trace --- at Microsoft.AspNetCore.SignalR.Protocol.DefaultMessagePackHubProtocolWorker.DeserializeObject (MessagePack.MessagePackReader& reader, System.Type type, System.String field) <0x102a649f0 + 0x001e0> in <a3a64c71038647ea91c7630ffcbce0a0#d2407fe79a8b45166ed88c1badc6898a>:0 at Microsoft.AspNetCore.SignalR.Protocol.MessagePackHubProtocolWorker.BindArguments (MessagePack.MessagePackReader& reader, System.Collections.Generic.IReadOnlyList1[T] parameterTypes) <0x102a667d0 + 0x000ff> in <a3a64c71038647ea91c7630ffcbce0a0#d2407fe79a8b45166ed88c1badc6898a>:0--- End of inner exception stack trace ---
at Microsoft.AspNetCore.SignalR.Protocol.MessagePackHubProtocolWorker.BindArguments (MessagePack.MessagePackReader& reader, System.Collections.Generic.IReadOnlyList`1[T] parameterTypes) <0x102a667d0 + 0x00184> in <a3a64c71038647ea91c7630ffcbce0a0#d2407fe79a8b45166ed88c1badc6898a>:0
at Microsoft.AspNetCore.SignalR.Protocol.MessagePackHubProtocolWorker.CreateInvocationMessage (MessagePack.MessagePackReader& reader, Microsoft.AspNetCore.SignalR.IInvocationBinder binder, System.Int32 itemCount) <0x102a65570 + 0x000db> in <a3a64c71038647ea91c7630ffcbce0a0#d2407fe79a8b45166ed88c1badc6898a>:0
MaximMikhisor commentedon Apr 1, 2022
Source of bug
MessagePack has two places where it uses System.Linq.Expressions.Lambda().Compile() method with ref parameters:
https://github.com/neuecc/MessagePack-CSharp/blob/master/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs#L237
https://github.com/neuecc/MessagePack-CSharp/blob/master/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs#L252
Xamarin.iOS is using this implementation of System.Linq.Expressions:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\Xamarin.iOS\v1.0\System.Core.dll
This implementation of System.Linq.Expressions.Lambda().Compile() method has NotImplementedException exception along the path of execution:

Even current System.Linq.Expressions implementation does not implement case whith ref parameters:
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs#L351
Why MessagePack does work on Xamarin Android and .NetCore apps?
Because System.Linq.Expressions.Lambda().Compile() implementation on these platforms are using DynamicMethod class:
https://github.com/dotnet/runtime/blob/6fe49aadf44f8cf5091fcbbe84ad4a4adc95d9b2/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.cs#L72
On Xamarin iOS dynamic features are forbidden:
https://docs.microsoft.com/en-us/xamarin/ios/internals/limitations#no-dynamic-code-generation
How to fix it?
Fix for "System.NotImplementedException: byref delegate" #1461
I also used NET_STANDARD_2_0, though do not sure is it important or not.
One of possible way is to replace these files here:
C:\Users\maxim.nuget\packages\messagepack\2.1.90\lib\netcoreapp2.1
C:\Users\maxim.nuget\packages\messagepack\2.1.90\lib\netstandard2.0
C:\Users\maxim.nuget\packages\messagepack.annotations\2.1.90\lib\netstandard2.0
Do not forget also about
Generate code for AOT:
https://github.com/neuecc/MessagePack-CSharp#aot-code-generation-support-for-unityxamarin
https://github.com/neuecc/MessagePack-CSharp/blob/master/doc/msbuildtask.md
Set up option for MessagePack serialisation, something like this:
KazysNoobiys commentedon Jun 9, 2022
@AArnott
Continuing the discussion of AOT and ios from PR. Perhaps I did not say it correctly. AOT works. I was able to generate the necessary code. And it works correctly on android with AOT enabled and also on ios in debug mode. In the release I get an error at runtime. For ios to work in the release, I need to enable "mono interpreter" in the settings
AArnott commentedon Jun 9, 2022
Thanks for clarifying, @KazysNoobiys. It sounds like even though you're using AOT, messagepack is running code generation anyway. That's not expected. Are you using mpc directly or using the msbuild task package for your AOT? How are you hooking the generated code up at runtime?
MaximMikhisor commentedon Jun 10, 2022
Hi @AArnott ,
It is very sad, but for some resone code changes in this commit are corrupted: all lines that suppose to be deleted was not deleted. Do not know how this happened.
If you want I can create another commit with proper changes. Meanwhile I commented which exactly lines suppose to be deleted in that commit.
You wrote:
"The answer for iOS is to use AOT, per our README file. Let's have a discussion around whether that works for you before we make more code changes to the library."
Yes, I am using AOT from your README file.
AOT does not solve "byref delegate" exception.
"But as this never compiled, and it's unclear what this was trying to do and how it would work with the pre-existing code, I'm going to close the PR."
In above commit I created two additional methods:
SerializeSemiGenericandDeserializeSemiGenericBy using these methods instead of original one we avoid using System.Linq.Expressions.Lambda().Compile() method with ref parameters.
As result we have not "byref delegate" exception.
I described source of this bug in above comment: #1344 (comment)
MaximMikhisor commentedon Jun 10, 2022
@KazysNoobiys What exactly do you mean by "For ios to work in the release"?
Did you publish it to Apple Store and did it work from Apple Store?
KazysNoobiys commentedon Jun 10, 2022
@MaximMikhisor

By "release" I simply mean the configuration of the build.
In the screenshot below I have marked the option when I turn on which I do not get an error in runtime.
@AArnott
I tried both methods to generate code and mpc and msbuild task, the result did not change, still got "byref delegate" exception on ios in release.
There's a link to a test project in the header of this thread, you can easily replicate this error on it. Just build the project in visual studio in release.
AArnott commentedon Jun 14, 2022
@KazysNoobiys Thanks for drawing my attention to your repro repo. I had forgotten you'd included that. Your serialization step looks good. And evidently the exception is thrown after that at your deserialization step. Looking at your deserialization step then, I see you're using the Deserialize method overload that requires JIT compilation. Can you try with this change applied?
I believe that will avoid the callstack that throws.
KazysNoobiys commentedon Jun 15, 2022
@AArnott
The test application is not from me, it is from the creator of this thread. I ran into this problem myself when I tried to use MessagePack in SignalR
AArnott commentedon Jun 15, 2022
Ah right. Well, I wonder if @stefanbogaard86 can confirm the change I suggest works for them.
@KazysNoobiys, I don't know SignalR well at all. Can you make similar code changes to your project, or based on your code snippet it looks like maybe SignalR owns the calling code and you can't change it?
KazysNoobiys commentedon Jun 15, 2022
@AArnott
I changed the line where the deserialization happens, and indeed, the test project started working correctly!
I also found the place where deserialization occurs in Extensions.AddMessagePackProtocol.
https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/common/Protocols.MessagePack/src/Protocol/DefaultMessagePackHubProtocolWorker.cs#L23
In principle, it's possible to replace DefaultMessagePackHubProtocolWorker with its own implementation, only I can't figure out how to stop using methods from MessagePackSerializer.NonGeneric. If I understand correctly, the problem is that non-generic methods are used? Deserialization with generics has a different implementation and works correctly?
AArnott commentedon Jun 15, 2022
Yes, the non-generic methods use dynamic code-gen to invoke the generic methods. So generic methods are a shorter path and avoid the extra code that's failing on your iOS device in release mode without the mono interpreter.
What would make this difficult?
KazysNoobiys commentedon Jun 16, 2022
As you can see from the code that causes deserialization, we can' t do without reflection here. And reflection causes a problem on ios
AArnott commentedon Jun 16, 2022
Ya, that's unfortunate that the method signature is that way instead of as a generic method.
@MaximMikhisor If we revive your PR, we need to do it in a way that doesn't erode performance for all the non-iOS users. Do you think you can fix up your branch to actually delete the lines you meant to delete, and see if you believe it doesn't erode performance in other scenarios? Once that's done, I'll take another look at it.
KazysNoobiys commentedon Jun 27, 2022
@MaximMikhisor does not get in contact. I'm not qualified to fix this error myself. Maybe someone can deal with this problem? It still turns out now, in spite of the descriptions to the library, Xamarin.IOS is not supported.
AArnott commentedon Jun 27, 2022
Yes it is, but certain APIs don't work because iOS breaks them. As we demonstrated in earlier comments, using the NonGeneric APIs is problematic, but the generic ones work. The fact that you're using another library (SignalR) that is inflexible and calls the broken APIs doesn't mean we don't support iOS.
That said, we certainly may be able to fix this. But it honestly isn't a high priority for the library maintainers as your scenario is both low traffic and not one that we ourselves require. I'll review PRs as they come in. Or if you'd like me to fix this in a prioritized way, consider making a one-time donation via cryptocurrency or venmo, sponsoring me on github.
MaximMikhisor commentedon Jun 28, 2022
Hi @AArnott , sorry for late reply. Did not see email notification.
I fixed code and created another pull request: #1461
AArnott commentedon Jun 28, 2022
Great. I'll try to review it this week.
sandsad commentedon Jul 1, 2022
when run it on ios throw an exception.
The type initializer for 'MessagePack.Resolvers.StandardResolver' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Internal.StandardResolverHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.DynamicEnumResolver' threw an exception. ---> System.PlatformNotSupportedException: Operation is not supported on this platform.