forked from focus-creative-games/il2cpp_plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlatformInvoke.cpp
More file actions
528 lines (417 loc) · 20.7 KB
/
PlatformInvoke.cpp
File metadata and controls
528 lines (417 loc) · 20.7 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#include "il2cpp-config.h"
#include "il2cpp-object-internals.h"
#include "il2cpp-class-internals.h"
#include "PlatformInvoke.h"
#include "Exception.h"
#include "MetadataCache.h"
#include "Method.h"
#include "Object.h"
#include "Runtime.h"
#include "Type.h"
#include "Reflection.h"
#include "gc/WriteBarrier.h"
#include "os/LibraryLoader.h"
#include "os/MarshalStringAlloc.h"
#include "utils/Memory.h"
#include "utils/StringUtils.h"
#include "vm-utils/VmStringUtils.h"
#include "hybridclr/metadata/MetadataUtil.h"
#include "hybridclr/metadata/MetadataModule.h"
#include "hybridclr/interpreter/InterpreterModule.h"
#include <stdint.h>
#include <algorithm>
namespace il2cpp
{
namespace vm
{
void PlatformInvoke::SetFindPluginCallback(Il2CppSetFindPlugInCallback method)
{
os::LibraryLoader::SetFindPluginCallback(method);
}
Il2CppMethodPointer PlatformInvoke::Resolve(const PInvokeArguments& pinvokeArgs)
{
// Before resolving a P/Invoke, check against a hardcoded list of "known P/Invokes" that is different for every platform.
// This bit solves several different problems we have when P/Invoking into native system libraries from mscorlib.dll.
// Some platforms, like UWP, just don't allow you to load to load system libraries at runtime dynamically.
// On other platforms (THEY SHALL NOT BE NAMED :O), while the functions that mscorlib.dll wants to P/Invoke into exist,
// They exist in different system libraries than it is said in the DllImport attribute.
Il2CppMethodPointer function = os::LibraryLoader::GetHardcodedPInvokeDependencyFunctionPointer(pinvokeArgs.moduleName, pinvokeArgs.entryPoint, pinvokeArgs.charSet);
if (function != NULL)
return function;
Baselib_DynamicLibrary_Handle dynamicLibrary = Baselib_DynamicLibrary_Handle_Invalid;
std::string detailedLoadError;
if (utils::VmStringUtils::CaseSensitiveEquals(il2cpp::utils::StringUtils::NativeStringToUtf8(pinvokeArgs.moduleName.Str()).c_str(), "__InternalDynamic"))
dynamicLibrary = os::LibraryLoader::LoadDynamicLibrary(il2cpp::utils::StringView<Il2CppNativeChar>::Empty(), detailedLoadError);
else
dynamicLibrary = os::LibraryLoader::LoadDynamicLibrary(pinvokeArgs.moduleName, detailedLoadError);
if (dynamicLibrary == Baselib_DynamicLibrary_Handle_Invalid)
{
std::string message;
message += "Unable to load DLL '";
message += il2cpp::utils::StringUtils::NativeStringToUtf8(pinvokeArgs.moduleName.Str());
message += "'. Tried the load the following dynamic libraries: ";
message += detailedLoadError;
Exception::Raise(Exception::GetDllNotFoundException(message.c_str()));
}
std::string detailedGetFunctionError;
function = os::LibraryLoader::GetFunctionPointer(dynamicLibrary, pinvokeArgs, detailedGetFunctionError);
if (function == NULL)
{
std::string message;
message += "Unable to find an entry point named '";
message += pinvokeArgs.entryPoint.Str();
message += "' in '";
message += il2cpp::utils::StringUtils::NativeStringToUtf8(pinvokeArgs.moduleName.Str());
message += "'. Tried the following entry points: ";
message += detailedGetFunctionError;
Exception::Raise(Exception::GetEntryPointNotFoundException(message.c_str()));
}
return function;
}
void PlatformInvoke::MarshalFree(void* ptr)
{
if (ptr != NULL)
MarshalAlloc::Free(ptr);
}
char* PlatformInvoke::MarshalCSharpStringToCppString(Il2CppString* managedString)
{
if (managedString == NULL)
return NULL;
std::string utf8String = utils::StringUtils::Utf16ToUtf8(managedString->chars);
char* nativeString = MarshalAllocateStringBuffer<char>(utf8String.size() + 1);
strcpy(nativeString, utf8String.c_str());
return nativeString;
}
void PlatformInvoke::MarshalCSharpStringToCppStringFixed(Il2CppString* managedString, char* buffer, int numberOfCharacters)
{
if (managedString == NULL)
{
*buffer = '\0';
}
else
{
std::string utf8String = utils::StringUtils::Utf16ToUtf8(managedString->chars, numberOfCharacters - 1);
strcpy(buffer, utf8String.c_str());
}
}
Il2CppChar* PlatformInvoke::MarshalCSharpStringToCppWString(Il2CppString* managedString)
{
if (managedString == NULL)
return NULL;
int32_t stringLength = utils::StringUtils::GetLength(managedString);
Il2CppChar* nativeString = MarshalAllocateStringBuffer<Il2CppChar>(stringLength + 1);
for (int32_t i = 0; i < managedString->length; ++i)
nativeString[i] = managedString->chars[i];
nativeString[managedString->length] = '\0';
return nativeString;
}
void PlatformInvoke::MarshalCSharpStringToCppWStringFixed(Il2CppString* managedString, Il2CppChar* buffer, int numberOfCharacters)
{
if (managedString == NULL)
{
*buffer = '\0';
}
else
{
int32_t stringLength = std::min(utils::StringUtils::GetLength(managedString), numberOfCharacters - 1);
for (int32_t i = 0; i < stringLength; ++i)
buffer[i] = managedString->chars[i];
buffer[stringLength] = '\0';
}
}
il2cpp_hresult_t PlatformInvoke::MarshalCSharpStringToCppBStringNoThrow(Il2CppString* managedString, Il2CppChar** bstr)
{
IL2CPP_ASSERT(bstr);
if (managedString == NULL)
{
*bstr = NULL;
return IL2CPP_S_OK;
}
int32_t stringLength = utils::StringUtils::GetLength(managedString);
Il2CppChar* stringChars = utils::StringUtils::GetChars(managedString);
return os::MarshalStringAlloc::AllocateBStringLength(stringChars, stringLength, bstr);
}
Il2CppChar* PlatformInvoke::MarshalCSharpStringToCppBString(Il2CppString* managedString)
{
Il2CppChar* bstr;
const il2cpp_hresult_t hr = MarshalCSharpStringToCppBStringNoThrow(managedString, &bstr);
vm::Exception::RaiseIfFailed(hr, true);
return bstr;
}
Il2CppString* PlatformInvoke::MarshalCppStringToCSharpStringResult(const char* value)
{
if (value == NULL)
return NULL;
return String::New(value);
}
Il2CppString* PlatformInvoke::MarshalCppWStringToCSharpStringResult(const Il2CppChar* value)
{
if (value == NULL)
return NULL;
return String::NewUtf16(value, (int32_t)utils::StringUtils::StrLen(value));
}
Il2CppString* PlatformInvoke::MarshalCppBStringToCSharpStringResult(const Il2CppChar* value)
{
if (value == NULL)
return NULL;
int32_t length;
const il2cpp_hresult_t hr = os::MarshalStringAlloc::GetBStringLength(value, &length);
vm::Exception::RaiseIfFailed(hr, true);
return String::NewUtf16(value, length);
}
void PlatformInvoke::MarshalFreeBString(Il2CppChar* value)
{
const il2cpp_hresult_t hr = os::MarshalStringAlloc::FreeBString(value);
vm::Exception::RaiseIfFailed(hr, true);
}
char* PlatformInvoke::MarshalEmptyStringBuilder(Il2CppStringBuilder* stringBuilder, size_t& stringLength, std::vector<std::string>& utf8Chunks, std::vector<Il2CppStringBuilder*>& builders)
{
if (stringBuilder == NULL)
return NULL;
stringLength = 0;
Il2CppStringBuilder* currentBuilder = stringBuilder;
while (true)
{
if (currentBuilder == NULL)
break;
const Il2CppChar *str = (Il2CppChar*)il2cpp::vm::Array::GetFirstElementAddress(currentBuilder->chunkChars);
std::string utf8String = utils::StringUtils::Utf16ToUtf8(str, (int)currentBuilder->chunkChars->max_length);
utf8Chunks.push_back(utf8String);
builders.push_back(currentBuilder);
size_t lenToCount = std::max((size_t)currentBuilder->chunkChars->max_length, utf8String.size());
stringLength += lenToCount;
currentBuilder = currentBuilder->chunkPrevious;
}
char* nativeString = MarshalAllocateStringBuffer<char>(stringLength + 1);
// We need to zero out the memory because the chunkChar array lengh may have been larger than the chunkLength
// and when this happens we'll have a utf8String that is smaller than the the nativeString we allocated. When we go to copy the
// chunk utf8String into the nativeString it won't fill everything and we can end up with w/e junk value was in that memory before
memset(nativeString, 0, sizeof(char) * (stringLength + 1));
return nativeString;
}
char* PlatformInvoke::MarshalEmptyStringBuilder(Il2CppStringBuilder* stringBuilder)
{
size_t sizeLength;
std::vector<std::string> utf8Chunks;
std::vector<Il2CppStringBuilder*> builders;
return MarshalEmptyStringBuilder(stringBuilder, sizeLength, utf8Chunks, builders);
}
char* PlatformInvoke::MarshalStringBuilder(Il2CppStringBuilder* stringBuilder)
{
if (stringBuilder == NULL)
return NULL;
size_t stringLength;
std::vector<std::string> utf8Chunks;
std::vector<Il2CppStringBuilder*> builders;
char* nativeString = MarshalEmptyStringBuilder(stringBuilder, stringLength, utf8Chunks, builders);
if (stringLength > 0)
{
int offsetAdjustment = 0;
for (int i = (int)utf8Chunks.size() - 1; i >= 0; i--)
{
std::string utf8String = utf8Chunks[i];
const char* utf8CString = utf8String.c_str();
memcpy(nativeString + builders[i]->chunkOffset + offsetAdjustment, utf8CString, (int)utf8String.size());
offsetAdjustment += (int)utf8String.size() - builders[i]->chunkLength;
}
}
return nativeString;
}
Il2CppChar* PlatformInvoke::MarshalEmptyWStringBuilder(Il2CppStringBuilder* stringBuilder, size_t& stringLength)
{
if (stringBuilder == NULL)
return NULL;
stringLength = 0;
Il2CppStringBuilder* currentBuilder = stringBuilder;
while (true)
{
if (currentBuilder == NULL)
break;
stringLength += (size_t)currentBuilder->chunkChars->max_length;
currentBuilder = currentBuilder->chunkPrevious;
}
return MarshalAllocateStringBuffer<Il2CppChar>(stringLength + 1);
}
Il2CppChar* PlatformInvoke::MarshalEmptyWStringBuilder(Il2CppStringBuilder* stringBuilder)
{
size_t stringLength;
return MarshalEmptyWStringBuilder(stringBuilder, stringLength);
}
Il2CppChar* PlatformInvoke::MarshalWStringBuilder(Il2CppStringBuilder* stringBuilder)
{
if (stringBuilder == NULL)
return NULL;
size_t stringLength;
Il2CppChar* nativeString = MarshalEmptyWStringBuilder(stringBuilder, stringLength);
if (stringLength > 0)
{
Il2CppStringBuilder* currentBuilder = stringBuilder;
while (true)
{
if (currentBuilder == NULL)
break;
const Il2CppChar *str = (Il2CppChar*)il2cpp::vm::Array::GetFirstElementAddress(currentBuilder->chunkChars);
memcpy(nativeString + currentBuilder->chunkOffset, str, (int)currentBuilder->chunkChars->max_length * sizeof(Il2CppChar));
currentBuilder = currentBuilder->chunkPrevious;
}
}
nativeString[stringLength] = '\0';
return nativeString;
}
void PlatformInvoke::MarshalStringBuilderResult(Il2CppStringBuilder* stringBuilder, char* buffer)
{
if (stringBuilder == NULL || buffer == NULL)
return;
UTF16String utf16String = utils::StringUtils::Utf8ToUtf16(buffer);
IL2CPP_OBJECT_SETREF(stringBuilder, chunkChars, il2cpp::vm::Array::New(il2cpp_defaults.char_class, (int)utf16String.size() + 1));
for (int i = 0; i < (int)utf16String.size(); i++)
il2cpp_array_set(stringBuilder->chunkChars, Il2CppChar, i, utf16String[i]);
il2cpp_array_set(stringBuilder->chunkChars, Il2CppChar, (int)utf16String.size(), '\0');
stringBuilder->chunkLength = (int)utf16String.size();
stringBuilder->chunkOffset = 0;
IL2CPP_OBJECT_SETREF_NULL(stringBuilder, chunkPrevious);
}
void PlatformInvoke::MarshalWStringBuilderResult(Il2CppStringBuilder* stringBuilder, Il2CppChar* buffer)
{
if (stringBuilder == NULL || buffer == NULL)
return;
int len = (int)utils::StringUtils::StrLen(buffer);
IL2CPP_OBJECT_SETREF(stringBuilder, chunkChars, il2cpp::vm::Array::New(il2cpp_defaults.char_class, len + 1));
for (int i = 0; i < len; i++)
il2cpp_array_set(stringBuilder->chunkChars, Il2CppChar, i, buffer[i]);
il2cpp_array_set(stringBuilder->chunkChars, Il2CppChar, len, '\0');
stringBuilder->chunkLength = len;
stringBuilder->chunkOffset = 0;
IL2CPP_OBJECT_SETREF_NULL(stringBuilder, chunkPrevious);
}
static bool IsGenericInstance(const Il2CppType* type)
{
if (type->type == IL2CPP_TYPE_GENERICINST)
return true;
while (type->type == IL2CPP_TYPE_SZARRAY)
{
if (type->data.type->type == IL2CPP_TYPE_GENERICINST)
return true;
type = type->data.type;
}
return false;
}
static std::string TypeNameListFor(const Il2CppGenericInst* genericInst)
{
std::string typeNameList;
if (genericInst != NULL)
{
int numberOfTypeArguments = genericInst->type_argc;
for (int i = 0; i < numberOfTypeArguments; i++)
{
typeNameList += Type::GetName(genericInst->type_argv[i], IL2CPP_TYPE_NAME_FORMAT_FULL_NAME);
if (i != numberOfTypeArguments - 1)
typeNameList += ", ";
}
}
return typeNameList;
}
static Il2CppCallConvention GetDelegateCallConvention(Il2CppDelegate* d)
{
const Il2CppImage* image = d->object.klass->image;
Il2CppMetadataCustomAttributeHandle customAttributeHandle = MetadataCache::GetCustomAttributeTypeToken(image, d->object.klass->token);
if (!customAttributeHandle)
{
return IL2CPP_CALL_DEFAULT;
}
static Il2CppClass* umanagedFunctionPointerAttributeClass = nullptr;
if (umanagedFunctionPointerAttributeClass == nullptr)
{
umanagedFunctionPointerAttributeClass = Class::FromName(il2cpp_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
if (umanagedFunctionPointerAttributeClass == nullptr)
{
return IL2CPP_CALL_DEFAULT;
}
}
Il2CppObject* customAttribute = il2cpp::vm::Reflection::GetCustomAttribute(customAttributeHandle, umanagedFunctionPointerAttributeClass);
if (!customAttribute)
{
return IL2CPP_CALL_DEFAULT;
}
int32_t callConv = *(int32_t*)(customAttribute + 1);
IL2CPP_ASSERT(callConv >= 1 && callConv <= 5);
return (Il2CppCallConvention)(callConv - 1);
}
intptr_t PlatformInvoke::MarshalDelegate(Il2CppDelegate* d)
{
if (d == NULL)
return 0;
if (IsFakeDelegateMethodMarshaledFromNativeCode(d))
return reinterpret_cast<intptr_t>(d->delegate_trampoline);
const MethodInfo* method = d->method;
if (method && hybridclr::metadata::IsInterpreterImplement(method))
{
Il2CppCallConvention callConvention = GetDelegateCallConvention(d);
return reinterpret_cast<intptr_t>(hybridclr::interpreter::InterpreterModule::GetReversePInvokeWrapper(d->method->klass->image, method, callConvention));
}
Il2CppMethodPointer reversePInvokeWrapper = MetadataCache::GetReversePInvokeWrapper(d->method->klass->image, d->method);
if (reversePInvokeWrapper == NULL)
{
std::string methodName = il2cpp::vm::Method::GetFullName(d->method);
// Okay, we cannot marshal it for some reason. Figure out why.
if (Method::IsInstance(d->method))
{
std::string errorMessage = "IL2CPP does not support marshaling delegates that point to instance methods to native code. The method we're attempting to marshal is: " + methodName;
vm::Exception::Raise(vm::Exception::GetNotSupportedException(errorMessage.c_str()));
}
if (il2cpp::vm::Method::HasFullGenericSharingSignature(d->method))
{
std::string errorMessage = "IL2CPP does not support marshaling generic delegates when full generic sharing is enabled. The method we're attempting to marshal is: " + methodName;
errorMessage += "\nTo marshal this delegate, please add an attribute named 'MonoPInvokeCallback' to the method definition.";
errorMessage += "\nThis attribute should have a type argument which is a generic delegate with all of the types required for this generic instantiation:";
std::string genericTypeArguments = TypeNameListFor(d->method->genericMethod->context.class_inst);
if (!genericTypeArguments.empty())
errorMessage += "\nGeneric type arguments: " + genericTypeArguments;
std::string genericMethodArguments = TypeNameListFor(d->method->genericMethod->context.method_inst);
if (!genericMethodArguments.empty())
errorMessage += "\nGeneric method arguments: " + genericMethodArguments;
errorMessage += "\nThis C# code should work, for example:";
std::string maybeComma = !genericTypeArguments.empty() ? ", " : "";
errorMessage += "\n[MonoPInvokeCallback(typeof(System.Action<" + genericTypeArguments + maybeComma + genericMethodArguments + ">))]";
vm::Exception::Raise(vm::Exception::GetNotSupportedException(errorMessage.c_str()));
}
if (d->method->parameters != NULL)
{
for (int i = 0; i < d->method->parameters_count; ++i)
{
if (IsGenericInstance(d->method->parameters[i]))
{
std::string errorMessage = "Cannot marshal method '" + methodName + "' parameter '" + Method::GetParamName(d->method, i) + "': Generic types cannot be marshaled.";
vm::Exception::Raise(vm::Exception::GetMarshalDirectiveException(errorMessage.c_str()));
}
}
}
std::string errorMessage = "To marshal a managed method, please add an attribute named 'MonoPInvokeCallback' to the method definition. The method we're attempting to marshal is: " + methodName;
vm::Exception::Raise(vm::Exception::GetNotSupportedException(errorMessage.c_str()));
}
return reinterpret_cast<intptr_t>(reversePInvokeWrapper);
}
Il2CppDelegate* PlatformInvoke::MarshalFunctionPointerToDelegate(void* functionPtr, Il2CppClass* delegateType)
{
if (functionPtr == NULL)
return NULL;
if (!Class::HasParent(delegateType, il2cpp_defaults.delegate_class))
Exception::Raise(Exception::GetArgumentException("t", "Type must derive from Delegate."));
const Il2CppInteropData* interopData = delegateType->interopData;
Il2CppMethodPointer managedToNativeWrapperMethodPointer = interopData != NULL ? interopData->delegatePInvokeWrapperFunction : NULL;
if (managedToNativeWrapperMethodPointer == NULL)
Exception::Raise(Exception::GetMarshalDirectiveException(utils::StringUtils::Printf("Cannot marshal P/Invoke call through delegate of type '%s.%s'", Class::GetNamespace(delegateType), Class::GetName(delegateType)).c_str()));
const MethodInfo* invokeMethod = il2cpp::vm::Runtime::GetDelegateInvoke(delegateType);
Il2CppDelegate* delegate = (Il2CppDelegate*)il2cpp::vm::Object::New(delegateType);
Type::ConstructClosedDelegate(delegate, (Il2CppObject*)delegate, managedToNativeWrapperMethodPointer, invokeMethod);
delegate->delegate_trampoline = functionPtr;
return delegate;
}
// When a delegate is marshalled from native code via Marshal.GetDelegateForFunctionPointer
// It will store the native function pointer in delegate_trampoline
bool PlatformInvoke::IsFakeDelegateMethodMarshaledFromNativeCode(const Il2CppDelegate* d)
{
return d->delegate_trampoline != NULL;
}
} /* namespace vm */
} /* namespace il2cpp */