1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.Interop.MarshallerHelpers;
namespace Microsoft.Interop
{
public sealed class Utf16StringMarshaller : ConditionalStackallocMarshallingGenerator
{
// [Compat] Equivalent of MAX_PATH on Windows to match built-in system
// The assumption is file paths are the most common case for marshalling strings,
// so the threshold for optimized allocation is based on that length.
private const int StackAllocBytesThreshold = 260 * sizeof(ushort);
private static readonly TypeSyntax NativeType = PointerType(PredefinedType(Token(SyntaxKind.UShortKeyword)));
private static string PinnedIdentifier(string nativeIdentifier) => $"{nativeIdentifier}__pinned";
public override ArgumentSyntax AsArgument(TypePositionInfo info, StubCodeContext context)
{
string identifier = context.GetIdentifiers(info).native;
if (info.IsByRef)
{
// &<nativeIdentifier>
return Argument(
PrefixUnaryExpression(
SyntaxKind.AddressOfExpression,
IdentifierName(identifier)));
}
else if (context.SingleFrameSpansNativeContext)
{
// (ushort*)<pinned>
return Argument(
CastExpression(
AsNativeType(info),
IdentifierName(PinnedIdentifier(identifier))));
}
// <nativeIdentifier>
return Argument(IdentifierName(identifier));
}
public override TypeSyntax AsNativeType(TypePositionInfo info)
{
// ushort*
return NativeType;
}
public override ParameterSyntax AsParameter(TypePositionInfo info)
{
// ushort**
// or
// ushort*
var type = info.IsByRef
? PointerType(AsNativeType(info))
: AsNativeType(info);
return Parameter(Identifier(info.InstanceIdentifier))
.WithType(type);
}
public override IEnumerable<StatementSyntax> Generate(TypePositionInfo info, StubCodeContext context)
{
(string managedIdentifier, string nativeIdentifier) = context.GetIdentifiers(info);
if (context.SingleFrameSpansNativeContext && !info.IsByRef && !info.IsManagedReturnPosition)
{
if (context.CurrentStage == StubCodeContext.Stage.Pin)
{
// fixed (char* <pinned> = <managedIdentifier>)
yield return FixedStatement(
VariableDeclaration(
PointerType(PredefinedType(Token(SyntaxKind.CharKeyword))),
SingletonSeparatedList(
VariableDeclarator(Identifier(PinnedIdentifier(nativeIdentifier)))
.WithInitializer(EqualsValueClause(IdentifierName(managedIdentifier))))),
EmptyStatement());
}
yield break;
}
switch (context.CurrentStage)
{
case StubCodeContext.Stage.Setup:
if (TryGenerateSetupSyntax(info, context, out StatementSyntax conditionalAllocSetup))
yield return conditionalAllocSetup;
break;
case StubCodeContext.Stage.Marshal:
if (info.RefKind != RefKind.Out)
{
foreach (var statement in GenerateConditionalAllocationSyntax(
info,
context,
StackAllocBytesThreshold))
{
yield return statement;
}
}
break;
case StubCodeContext.Stage.Unmarshal:
if (info.IsManagedReturnPosition || (info.IsByRef && info.RefKind != RefKind.In))
{
// <managed> = <native> == null ? null : new string((char*)<native>);
yield return ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(managedIdentifier),
ConditionalExpression(
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName(nativeIdentifier),
LiteralExpression(SyntaxKind.DefaultLiteralExpression)),
LiteralExpression(SyntaxKind.NullLiteralExpression),
ObjectCreationExpression(
PredefinedType(Token(SyntaxKind.StringKeyword)),
ArgumentList(SingletonSeparatedList<ArgumentSyntax>(
Argument(
CastExpression(
PointerType(PredefinedType(Token(SyntaxKind.CharKeyword))),
IdentifierName(nativeIdentifier))))),
initializer: null))));
}
break;
case StubCodeContext.Stage.Cleanup:
yield return GenerateConditionalAllocationFreeSyntax(info ,context);
break;
}
}
public override bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => true;
public override bool SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, StubCodeContext context) => false;
protected override ExpressionSyntax GenerateAllocationExpression(
TypePositionInfo info,
StubCodeContext context,
SyntaxToken byteLengthIdentifier,
out bool allocationRequiresByteLength)
{
allocationRequiresByteLength = false;
return CastExpression(
AsNativeType(info),
StringMarshaller.AllocationExpression(CharEncoding.Utf16, context.GetIdentifiers(info).managed));
}
protected override ExpressionSyntax GenerateByteLengthCalculationExpression(TypePositionInfo info, StubCodeContext context)
{
// +1 for null terminator
// *2 for number of bytes per char
// int <byteLen> = (<managed>.Length + 1) * 2;
return
BinaryExpression(
SyntaxKind.MultiplyExpression,
ParenthesizedExpression(
BinaryExpression(
SyntaxKind.AddExpression,
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(context.GetIdentifiers(info).managed),
IdentifierName("Length")),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)));
}
protected override StatementSyntax GenerateStackallocOnlyValueMarshalling(
TypePositionInfo info,
StubCodeContext context,
SyntaxToken byteLengthIdentifier,
SyntaxToken stackAllocPtrIdentifier)
{
// ((ReadOnlySpan<char>)<managed>).CopyTo(new Span<char>(<stackAllocPtr>, <managed>.Length + 1));
return
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
ParenthesizedExpression(
CastExpression(
GenericName(Identifier("System.ReadOnlySpan"),
TypeArgumentList(SingletonSeparatedList<TypeSyntax>(
PredefinedType(Token(SyntaxKind.CharKeyword))))),
IdentifierName(context.GetIdentifiers(info).managed))),
IdentifierName("CopyTo")),
ArgumentList(
SeparatedList(new [] {
Argument(
ObjectCreationExpression(
GenericName(Identifier(TypeNames.System_Span),
TypeArgumentList(SingletonSeparatedList<TypeSyntax>(
PredefinedType(Token(SyntaxKind.CharKeyword))))),
ArgumentList(
SeparatedList(new []{
Argument(IdentifierName(stackAllocPtrIdentifier)),
Argument(IdentifierName(byteLengthIdentifier))})),
initializer: null))}))));
}
protected override ExpressionSyntax GenerateFreeExpression(
TypePositionInfo info,
StubCodeContext context)
{
return StringMarshaller.FreeExpression(context.GetIdentifiers(info).native);
}
}
}
|