-
Notifications
You must be signed in to change notification settings - Fork 41
/
platform.c
607 lines (508 loc) · 18.8 KB
/
platform.c
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// Copyright 2020 Aaron R Robinson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "dnne.h"
// Must define the assembly name
#ifndef DNNE_ASSEMBLY_NAME
#error Target assembly name must be defined. Set 'DNNE_ASSEMBLY_NAME'.
#endif
// Include the official nethost API and indicate
// consumption should be as a static library.
#define NETHOST_USE_AS_STATIC
#include <nethost.h>
// Needed for dladdr() in non-macOS scenarios
#if !defined(DNNE_WINDOWS) && !defined(DNNE_OSX) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
// Modified copy of official hostfxr.h
#ifndef __HOSTFXR_H__
#ifdef DNNE_WINDOWS
#define HOSTFXR_CALLTYPE __cdecl
#else
#define HOSTFXR_CALLTYPE
#endif
enum hostfxr_delegate_type
{
hdt_com_activation,
hdt_load_in_memory_assembly,
hdt_winrt_activation,
hdt_com_register,
hdt_com_unregister,
hdt_load_assembly_and_get_function_pointer
};
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_main_fn)(const int argc, const char_t** argv);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_main_startupinfo_fn)(
const int argc,
const char_t** argv,
const char_t* host_path,
const char_t* dotnet_root,
const char_t* app_path);
typedef void(HOSTFXR_CALLTYPE* hostfxr_error_writer_fn)(const char_t* message);
typedef hostfxr_error_writer_fn(HOSTFXR_CALLTYPE* hostfxr_set_error_writer_fn)(hostfxr_error_writer_fn error_writer);
typedef void* hostfxr_handle;
typedef struct hostfxr_initialize_parameters
{
size_t size;
const char_t* host_path;
const char_t* dotnet_root;
} hostfxr_initialize_parameters;
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_initialize_for_dotnet_command_line_fn)(
int argc,
const char_t** argv,
const hostfxr_initialize_parameters* parameters,
/*out*/ hostfxr_handle* host_context_handle);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_initialize_for_runtime_config_fn)(
const char_t* runtime_config_path,
const hostfxr_initialize_parameters* parameters,
/*out*/ hostfxr_handle* host_context_handle);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_get_runtime_property_value_fn)(
const hostfxr_handle host_context_handle,
const char_t* name,
/*out*/ const char_t** value);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_set_runtime_property_value_fn)(
const hostfxr_handle host_context_handle,
const char_t* name,
const char_t* value);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_get_runtime_properties_fn)(
const hostfxr_handle host_context_handle,
/*inout*/ size_t* count,
/*out*/ const char_t** keys,
/*out*/ const char_t** values);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_run_app_fn)(const hostfxr_handle host_context_handle);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_get_runtime_delegate_fn)(
const hostfxr_handle host_context_handle,
enum hostfxr_delegate_type type,
/*out*/ void** delegate);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_close_fn)(const hostfxr_handle host_context_handle);
#endif // __HOSTFXR_H__
// Modified copy of official coreclr_delegates.h
#ifndef __CORECLR_DELEGATES_H__
#if defined(DNNE_WINDOWS)
#define CORECLR_DELEGATE_CALLTYPE __stdcall
#else
#define CORECLR_DELEGATE_CALLTYPE
#endif
#define UNMANAGEDCALLERSONLY_METHOD ((const char_t*)-1)
// Signature of delegate returned by coreclr_delegate_type::load_assembly_and_get_function_pointer
typedef int (CORECLR_DELEGATE_CALLTYPE *load_assembly_and_get_function_pointer_fn)(
const char_t *assembly_path /* Fully qualified path to assembly */,
const char_t *type_name /* Assembly qualified type name */,
const char_t *method_name /* Public static method name compatible with delegateType */,
const char_t *delegate_type_name /* Assembly qualified delegate type name or null
or UNMANAGEDCALLERSONLY_METHOD if the method is marked with
the UnmanagedCallersOnlyAttribute. */,
void *reserved /* Extensibility parameter (currently unused and must be 0) */,
/*out*/ void **delegate /* Pointer where to store the function pointer result */);
// Signature of delegate returned by load_assembly_and_get_function_pointer_fn when delegate_type_name == null (default)
typedef int (CORECLR_DELEGATE_CALLTYPE* component_entry_point_fn)(void* arg, int32_t arg_size_in_bytes);
#endif // __CORECLR_DELEGATES_H__
//
// Platform definitions
//
#ifndef NDEBUG
#define DNNE_DEBUG
#endif
#define DNNE_MAX_PATH 512
#define DNNE_ARRAY_SIZE(_array) (sizeof(_array) / sizeof(*_array))
#define DNNE_TOSTRING2(s) #s
#define DNNE_TOSTRING(s) DNNE_TOSTRING2(s)
typedef volatile long dnne_lock_handle;
#define DNNE_LOCK_OPEN (0)
#define DNNE_LOCK_TAKEN (-1)
#ifdef DNNE_WINDOWS
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#define DNNE_NORETURN __declspec(noreturn)
#define DNNE_DIR_SEPARATOR L'\\'
static void* load_library(const char_t* path)
{
assert(path != NULL);
HMODULE h = LoadLibraryW(path);
assert(h != NULL);
return (void*)h;
}
static void* get_export(void* h, const char* name)
{
assert(h != NULL && name != NULL);
void* f = GetProcAddress((HMODULE)h, name);
assert(f != NULL);
return f;
}
static int get_this_image_path(int32_t buffer_len, char_t* buffer, int32_t* written)
{
assert(0 < buffer_len && buffer != NULL && written != NULL);
HMODULE hmod;
if (FALSE == GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPWSTR)&get_this_image_path,
&hmod))
{
return (int)GetLastError();
}
DWORD len_local = GetModuleFileNameW(hmod, buffer, (DWORD)buffer_len);
if (len_local == 0)
{
return (int)GetLastError();
}
else if (len_local == buffer_len)
{
return ERROR_INSUFFICIENT_BUFFER;
}
*written = len_local;
return DNNE_SUCCESS;
}
static int get_current_error()
{
return (int)GetLastError();
}
static void set_current_error(int err)
{
SetLastError((DWORD)err);
}
static void enter_lock(dnne_lock_handle* lock)
{
while (InterlockedCompareExchange(lock, -1, DNNE_LOCK_OPEN) != DNNE_LOCK_OPEN)
{
Sleep(1 /* milliseconds */);
}
}
static void exit_lock(dnne_lock_handle* lock)
{
InterlockedExchange(lock, DNNE_LOCK_OPEN);
}
#else
#include <dlfcn.h>
#include <limits.h>
#include <string.h>
#include <sched.h>
#include <errno.h>
#define DNNE_NORETURN __attribute__((__noreturn__))
#define DNNE_DIR_SEPARATOR '/'
static void* load_library(const char_t* path)
{
assert(path != NULL);
void* h = dlopen(path, RTLD_LAZY | RTLD_LOCAL);
assert(h != NULL);
return h;
}
static void* get_export(void* h, const char* name)
{
assert(h != NULL && name != NULL);
void* f = dlsym(h, name);
assert(f != NULL);
return f;
}
static int get_this_image_path(int32_t buffer_len, char_t* buffer, int32_t* written)
{
assert(0 < buffer_len && buffer != NULL && written != NULL);
Dl_info info;
if (dladdr((void *)&get_this_image_path, &info) == 0)
return -1;
if (info.dli_fname == NULL)
return -2;
size_t len_local = strlen(info.dli_fname);
if (buffer_len <= len_local)
return ENOBUFS;
// Copy over the null as well.
memcpy(buffer, info.dli_fname, len_local + 1);
*written = (int32_t)len_local;
return DNNE_SUCCESS;
}
static int get_current_error()
{
return errno;
}
static void set_current_error(int err)
{
errno = err;
}
#ifdef __clang__
#pragma clang diagnostic push
#ifdef __arm__
// warning: large atomic operation may incur significant performance penalty; the access size (4 bytes) exceeds the max lock-free size (0 bytes)
#pragma clang diagnostic ignored "-Watomic-alignment"
#endif // __arm__
#endif // __clang__
static void enter_lock(dnne_lock_handle* lock)
{
#ifdef __arm__
// Cross compiling for arm32 platforms can cause issues using __atomic_compare_exchange_n().
// Instead of trying to special case them, always use the compiler (gcc/clang) intrinsic.
while (__sync_lock_test_and_set(lock, DNNE_LOCK_TAKEN) != DNNE_LOCK_OPEN)
{
(void)sched_yield(); // Yield instead of sleeping.
}
#else
long tmp = DNNE_LOCK_OPEN;
while (!__atomic_compare_exchange_n(lock, &tmp, DNNE_LOCK_TAKEN, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
{
(void)sched_yield(); // Yield instead of sleeping.
tmp = DNNE_LOCK_OPEN;
}
#endif // !__arm__
}
static void exit_lock(dnne_lock_handle* lock)
{
#ifdef __arm__
// Cross compiling for arm32 platforms can cause issues using __atomic_exchange_n().
// Instead of trying to special case them, always use the compiler (gcc/clang) intrinsic.
__sync_lock_release(lock);
assert(*lock == DNNE_LOCK_OPEN);
#else
__atomic_exchange_n(lock, DNNE_LOCK_OPEN, __ATOMIC_SEQ_CST);
#endif // !__arm__
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
#endif // !DNNE_WINDOWS
static failure_fn failure_fptr;
DNNE_EXTERN_C DNNE_API void DNNE_CALLTYPE set_failure_callback(failure_fn cb)
{
failure_fptr = cb;
}
// Provide mechanism for users to override default behavior of certain functions.
// - See https://stackoverflow.com/questions/51656838/attribute-weak-and-static-libraries
// - See https://devblogs.microsoft.com/oldnewthing/20200731-00/?p=104024
// - Use the MSC macro to enable Windows builds without MSVC.
#ifdef _MSC_VER
#define DNNE_DEFAULT_IMPL(methodName, ...) default_ ## methodName(__VA_ARGS__)
// List of overridable APIs
// Note the default calling convention is cdecl on x86 for DNNE_APIs.
// This means, on x86, we mangle the alternative name in the linker command.
#ifdef _M_IX86
#pragma comment(linker, "/alternatename:_dnne_abort=_default_dnne_abort")
#else
#pragma comment(linker, "/alternatename:dnne_abort=default_dnne_abort")
#endif
#else
#define DNNE_DEFAULT_IMPL(methodName, ...) __attribute__((weak)) methodName(__VA_ARGS__)
#endif
DNNE_EXTERN_C DNNE_API void DNNE_DEFAULT_IMPL(dnne_abort, enum failure_type type, int error_code)
{
abort();
}
DNNE_NORETURN static void noreturn_failure(enum failure_type type, int error_code)
{
if (failure_fptr)
failure_fptr(type, error_code);
// Nothing to do if the runtime failed to load.
dnne_abort(type, error_code);
// Don't trust anything the user can override.
abort();
}
static bool is_failure(int rc)
{
// The CLR hosting API uses the Win32 HRESULT scheme. This means
// the high order bit indicates an error and S_FALSE (1) can be returned
// and is _not_ a failure.
return (rc < DNNE_SUCCESS);
}
static int get_current_dir_filepath(int32_t buffer_len, char_t* buffer, int32_t filename_len, const char_t* filename, const char_t** result)
{
assert(buffer != NULL && filename != NULL && result != NULL);
int32_t written = 0;
int rc = get_this_image_path(buffer_len, buffer, &written);
if (is_failure(rc))
return rc;
char_t* filename_dest = buffer + written;
// Remove this image filename.
while (filename_dest != buffer)
{
if (*filename_dest == DNNE_DIR_SEPARATOR)
{
++filename_dest;
break;
}
--filename_dest;
}
int32_t remaining = buffer_len - (int32_t)(filename_dest - buffer);
if (remaining < filename_len)
return (-1);
// Append the new filename.
(void)memcpy(filename_dest, filename, filename_len * sizeof(char_t));
*result = buffer;
return DNNE_SUCCESS;
}
// Globals to hold hostfxr exports
static hostfxr_initialize_for_dotnet_command_line_fn init_self_contained_fptr;
static hostfxr_initialize_for_runtime_config_fn init_fptr;
static hostfxr_get_runtime_delegate_fn get_delegate_fptr;
static hostfxr_close_fn close_fptr;
static int load_hostfxr(const char_t* assembly_path)
{
// Discover the path to hostfxr.
char_t buffer[DNNE_MAX_PATH];
size_t buffer_size = DNNE_ARRAY_SIZE(buffer);
struct get_hostfxr_parameters params;
params.size = sizeof(params);
params.assembly_path = assembly_path;
params.dotnet_root = NULL;
int rc = get_hostfxr_path(buffer, &buffer_size, ¶ms);
if (is_failure(rc))
return rc;
// Load hostfxr and get desired exports.
void* lib = load_library(buffer);
init_self_contained_fptr = (hostfxr_initialize_for_dotnet_command_line_fn)get_export(lib, "hostfxr_initialize_for_dotnet_command_line");
init_fptr = (hostfxr_initialize_for_runtime_config_fn)get_export(lib, "hostfxr_initialize_for_runtime_config");
get_delegate_fptr = (hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate");
close_fptr = (hostfxr_close_fn)get_export(lib, "hostfxr_close");
assert(init_self_contained_fptr && init_fptr && get_delegate_fptr && close_fptr);
return DNNE_SUCCESS;
}
// Globals to hold runtime exports
static load_assembly_and_get_function_pointer_fn volatile get_managed_export_fptr;
static int init_dotnet(const char_t* assembly_path)
{
const char_t* config_path = NULL;
int rc;
#ifdef DNNE_SELF_CONTAINED_RUNTIME
// Self-contained scenario support is experimental and relies upon the application scenario
// entry-point. The logic here is to trick the hosting API into initializing as an application
// but call the "load assembly and get delegate" instead of "run main". This has impact
// on the TPA make-up and hence assembly loading in general since the TPA populates the default ALC.
config_path = assembly_path;
#else
char_t buffer[DNNE_MAX_PATH];
const char_t config_filename[] = DNNE_STR(DNNE_TOSTRING(DNNE_ASSEMBLY_NAME)) DNNE_STR(".runtimeconfig.json");
rc = get_current_dir_filepath(DNNE_ARRAY_SIZE(buffer), buffer, DNNE_ARRAY_SIZE(config_filename), config_filename, &config_path);
if (is_failure(rc))
return rc;
#endif
// Load .NET runtime
void* load_assembly_and_get_function_pointer = NULL;
hostfxr_handle cxt = NULL;
#ifdef DNNE_SELF_CONTAINED_RUNTIME
rc = init_self_contained_fptr(1, &config_path, NULL, &cxt);
#else
rc = init_fptr(config_path, NULL, &cxt);
#endif
if (is_failure(rc))
{
close_fptr(cxt);
return rc;
}
// Get the load assembly function pointer
rc = get_delegate_fptr(
cxt,
hdt_load_assembly_and_get_function_pointer,
&load_assembly_and_get_function_pointer);
if (is_failure(rc))
{
close_fptr(cxt);
return rc;
}
get_managed_export_fptr = (load_assembly_and_get_function_pointer_fn)load_assembly_and_get_function_pointer;
return DNNE_SUCCESS;
}
#define IF_FAILURE_RETURN_OR_ABORT(ret_maybe, type, rc, lock) \
{ \
if (is_failure(rc)) \
{ \
exit_lock(lock); \
if (ret_maybe) \
{ \
*ret_maybe = rc; \
return; \
} \
noreturn_failure(type, rc); \
} \
}
dnne_lock_handle _prepare_lock = DNNE_LOCK_OPEN;
static void prepare_runtime(int* ret)
{
// Lock and check if the needed export was already acquired.
enter_lock(&_prepare_lock);
if (!get_managed_export_fptr)
{
char_t buffer[DNNE_MAX_PATH];
const char_t assembly_filename[] = DNNE_STR(DNNE_TOSTRING(DNNE_ASSEMBLY_NAME)) DNNE_STR(".dll");
const char_t* assembly_path = NULL;
int rc = get_current_dir_filepath(DNNE_ARRAY_SIZE(buffer), buffer, DNNE_ARRAY_SIZE(assembly_filename), assembly_filename, &assembly_path);
IF_FAILURE_RETURN_OR_ABORT(ret, failure_load_runtime, rc, &_prepare_lock);
// Load HostFxr and get exported hosting functions.
rc = load_hostfxr(assembly_path);
IF_FAILURE_RETURN_OR_ABORT(ret, failure_load_runtime, rc, &_prepare_lock);
// Initialize and start the runtime.
rc = init_dotnet(assembly_path);
IF_FAILURE_RETURN_OR_ABORT(ret, failure_load_runtime, rc, &_prepare_lock);
assert(get_managed_export_fptr != NULL);
}
exit_lock(&_prepare_lock);
}
DNNE_EXTERN_C DNNE_API void DNNE_CALLTYPE preload_runtime(void)
{
prepare_runtime(NULL);
}
DNNE_EXTERN_C DNNE_API int DNNE_CALLTYPE try_preload_runtime(void)
{
int ret = DNNE_SUCCESS;
prepare_runtime(&ret);
return ret;
}
void* get_callable_managed_function(
const char_t* dotnet_type,
const char_t* dotnet_type_method,
const char_t* dotnet_delegate_type)
{
assert(dotnet_type && dotnet_type_method);
// Store the current error state to reset it when
// we exit this function. This being done because this
// API is an implementation detail of the export but
// can result in side-effects during export resolution.
int curr_error = get_current_error();
// Check if the runtime has already been prepared.
if (!get_managed_export_fptr)
{
prepare_runtime(NULL);
assert(get_managed_export_fptr != NULL);
}
char_t buffer[DNNE_MAX_PATH];
const char_t assembly_filename[] = DNNE_STR(DNNE_TOSTRING(DNNE_ASSEMBLY_NAME)) DNNE_STR(".dll");
const char_t* assembly_path = NULL;
int rc = get_current_dir_filepath(DNNE_ARRAY_SIZE(buffer), buffer, DNNE_ARRAY_SIZE(assembly_filename), assembly_filename, &assembly_path);
if (is_failure(rc))
noreturn_failure(failure_load_export, rc);
// Function pointer to managed function
void* func = NULL;
rc = get_managed_export_fptr(
assembly_path,
dotnet_type,
dotnet_type_method,
dotnet_delegate_type,
NULL,
&func);
if (is_failure(rc))
noreturn_failure(failure_load_export, rc);
// Now that the export has been resolved, reset
// the error state to hide this implementation detail.
set_current_error(curr_error);
return func;
}
void* get_fast_callable_managed_function(
const char_t* dotnet_type,
const char_t* dotnet_type_method)
{
return get_callable_managed_function(dotnet_type, dotnet_type_method, UNMANAGEDCALLERSONLY_METHOD);
}