-
Notifications
You must be signed in to change notification settings - Fork 528
/
monodroid-glue.cc
2099 lines (1736 loc) · 68.9 KB
/
monodroid-glue.cc
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <array>
#include <cstdlib>
#include <cstdarg>
#include <memory>
#include <jni.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#if defined (APPLE_OS_X)
#include <dlfcn.h>
#endif // def APPLE_OX_X
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/types.h>
#include <mono/jit/jit.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/mono-debug.h>
#include <mono/utils/mono-dl-fallback.h>
#include "mono_android_Runtime.h"
#if defined (DEBUG) && !defined (WINDOWS)
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#endif
#if defined (LINUX)
#include <sys/syscall.h>
#endif
#if defined (APPLE_OS_X)
#include <libgen.h>
#endif // defined(APPLE_OS_X)
#ifndef WINDOWS
#include <sys/mman.h>
#include <sys/utsname.h>
#else
#include <windef.h>
#include <winbase.h>
#include <shlobj.h>
#include <objbase.h>
#include <knownfolders.h>
#include <shlwapi.h>
#endif
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <pthread.h>
#include "java-interop-util.h"
#include "logger.hh"
#include "monodroid.h"
#include "util.hh"
#include "debug.hh"
#include "embedded-assemblies.hh"
#include "monodroid-glue.hh"
#include "mkbundle-api.h"
#include "monodroid-glue-internal.hh"
#include "globals.hh"
#include "xamarin-app.hh"
#include "timing.hh"
#include "xa-internal-api-impl.hh"
#ifndef WINDOWS
#include "xamarin_getifaddrs.h"
#endif
#include "cpp-util.hh"
#include "strings.hh"
#include "java-interop-dlfcn.h"
using namespace microsoft::java_interop;
using namespace xamarin::android;
using namespace xamarin::android::internal;
// This is below the above because we don't want to modify the header with our internal
// implementation details as it would prevent mkbundle from working
#include "mkbundle-api.h"
#include "config.include"
#include "machine.config.include"
std::mutex MonodroidRuntime::api_init_lock;
void *MonodroidRuntime::api_dso_handle = nullptr;
#ifdef WINDOWS
static const char* get_xamarin_android_msbuild_path (void);
const char *BasicAndroidSystem::SYSTEM_LIB_PATH = get_xamarin_android_msbuild_path();
#endif
/* Set of Windows-specific utility/reimplementation of Unix functions */
#ifdef WINDOWS
static char *msbuild_folder_path = nullptr;
static const char*
get_xamarin_android_msbuild_path (void)
{
const char *suffix = "MSBuild\\Xamarin\\Android";
char *base_path = nullptr;
wchar_t *buffer = nullptr;
if (msbuild_folder_path != nullptr)
return msbuild_folder_path;
// Get the base path for 'Program Files' on Windows
if (!SUCCEEDED (SHGetKnownFolderPath (FOLDERID_ProgramFilesX86, 0, nullptr, &buffer))) {
if (buffer != nullptr)
CoTaskMemFree (buffer);
// returns current directory if a global one couldn't be found
return ".";
}
// Compute the final path
base_path = utils.utf16_to_utf8 (buffer);
CoTaskMemFree (buffer);
msbuild_folder_path = utils.path_combine (base_path, suffix);
free (base_path);
return msbuild_folder_path;
}
static int
setenv(const char *name, const char *value, int overwrite)
{
return androidSystem.setenv (name, value, overwrite);
}
#endif // def WINDOWS
typedef void* (*mono_mkbundle_init_ptr) (void (*)(const MonoBundledAssembly **), void (*)(const char* assembly_name, const char* config_xml),void (*) (int mode));
mono_mkbundle_init_ptr mono_mkbundle_init;
typedef void (*mono_mkbundle_initialize_mono_api_ptr) (const BundleMonoAPI *info);
mono_mkbundle_initialize_mono_api_ptr mono_mkbundle_initialize_mono_api;
void
MonodroidRuntime::setup_bundled_app (const char *dso_name)
{
if (!application_config.is_a_bundled_app)
return;
static unsigned int dlopen_flags = JAVA_INTEROP_LIB_LOAD_LOCALLY;
void *libapp = nullptr;
if (androidSystem.is_embedded_dso_mode_enabled ()) {
log_info (LOG_DEFAULT, "bundle app: embedded DSO mode");
libapp = androidSystem.load_dso_from_any_directories (dso_name, dlopen_flags);
} else {
log_info (LOG_DEFAULT, "bundle app: normal mode");
dynamic_local_string<SENSIBLE_PATH_MAX> bundle_path;
if (!androidSystem.get_full_dso_path_on_disk (dso_name, bundle_path)) {
log_info (LOG_DEFAULT, "bundle %s not found on filesystem", dso_name);
return;
}
log_info (LOG_BUNDLE, "Attempting to load bundled app from %s", bundle_path.get ());
libapp = androidSystem.load_dso (bundle_path.get (), dlopen_flags, true);
}
if (libapp == nullptr) {
log_info (LOG_DEFAULT, "No libapp!");
if (!androidSystem.is_embedded_dso_mode_enabled ()) {
log_fatal (LOG_BUNDLE, "bundled app initialization error");
exit (FATAL_EXIT_CANNOT_LOAD_BUNDLE);
} else {
log_info (LOG_BUNDLE, "bundled app not found in the APK, ignoring.");
return;
}
}
mono_mkbundle_initialize_mono_api = reinterpret_cast<mono_mkbundle_initialize_mono_api_ptr> (java_interop_lib_symbol (libapp, "initialize_mono_api", nullptr));
if (!mono_mkbundle_initialize_mono_api)
log_error (LOG_BUNDLE, "Missing initialize_mono_api in the application");
mono_mkbundle_init = reinterpret_cast<mono_mkbundle_init_ptr> (java_interop_lib_symbol (libapp, "mono_mkbundle_init", nullptr));
if (!mono_mkbundle_init)
log_error (LOG_BUNDLE, "Missing mono_mkbundle_init in the application");
log_info (LOG_BUNDLE, "Bundled app loaded: %s", dso_name);
}
void
MonodroidRuntime::thread_start ([[maybe_unused]] MonoProfiler *prof, [[maybe_unused]] uintptr_t tid)
{
JNIEnv* env;
int r;
#ifdef PLATFORM_ANDROID
r = osBridge.get_jvm ()->AttachCurrentThread (&env, nullptr);
#else // ndef PLATFORM_ANDROID
r = osBridge.get_jvm ()->AttachCurrentThread (reinterpret_cast<void**>(&env), nullptr);
#endif // ndef PLATFORM_ANDROID
if (r != JNI_OK) {
#if DEBUG
log_fatal (LOG_DEFAULT, "ERROR: Unable to attach current thread to the Java VM!");
exit (FATAL_EXIT_ATTACH_JVM_FAILED);
#endif
}
}
void
MonodroidRuntime::thread_end ([[maybe_unused]] MonoProfiler *prof, [[maybe_unused]] uintptr_t tid)
{
int r;
r = osBridge.get_jvm ()->DetachCurrentThread ();
if (r != JNI_OK) {
#if DEBUG
/*
log_fatal (LOG_DEFAULT, "ERROR: Unable to detach current thread from the Java VM!");
*/
#endif
}
}
inline void
MonodroidRuntime::log_jit_event (MonoMethod *method, const char *event_name)
{
jit_time.mark_end ();
if (jit_log == nullptr)
return;
char* name = mono_method_full_name (method, 1);
timing_diff diff (jit_time);
fprintf (jit_log, "JIT method %6s: %s elapsed: %lis:%u::%u\n", event_name, name, static_cast<long int>(diff.sec), diff.ms, diff.ns);
free (name);
}
void
MonodroidRuntime::jit_begin ([[maybe_unused]] MonoProfiler *prof, MonoMethod *method)
{
monodroidRuntime.log_jit_event (method, "begin");
}
void
MonodroidRuntime::jit_failed ([[maybe_unused]] MonoProfiler *prof, MonoMethod *method)
{
monodroidRuntime.log_jit_event (method, "failed");
}
void
MonodroidRuntime::jit_done ([[maybe_unused]] MonoProfiler *prof, MonoMethod *method, [[maybe_unused]] MonoJitInfo* jinfo)
{
monodroidRuntime.log_jit_event (method, "done");
}
#ifndef RELEASE
MonoAssembly*
MonodroidRuntime::open_from_update_dir (MonoAssemblyName *aname, [[maybe_unused]] char **assemblies_path, [[maybe_unused]] void *user_data)
{
MonoAssembly *result = nullptr;
#ifndef ANDROID
// First check if there are any in-memory assemblies
if (designerAssemblies.has_assemblies ()) {
MonoDomain *domain = mono_domain_get ();
result = designerAssemblies.try_load_assembly (domain, aname);
if (result != nullptr) {
log_debug (LOG_ASSEMBLY, "Loaded assembly %s from memory in domain %d", mono_assembly_name_get_name (aname), mono_domain_get_id (domain));
return result;
}
log_debug (LOG_ASSEMBLY, "No in-memory data found for assembly %s", mono_assembly_name_get_name (aname));
} else {
log_debug (LOG_ASSEMBLY, "No in-memory assemblies detected", mono_assembly_name_get_name (aname));
}
#endif
const char *override_dir;
bool found = false;
for (uint32_t oi = 0; oi < AndroidSystem::MAX_OVERRIDES; ++oi) {
override_dir = androidSystem.get_override_dir (oi);
if (override_dir != nullptr && utils.directory_exists (override_dir)) {
found = true;
break;
}
}
if (!found)
return nullptr;
const char *culture = reinterpret_cast<const char*> (mono_assembly_name_get_culture (aname));
const char *name = reinterpret_cast<const char*> (mono_assembly_name_get_name (aname));
size_t culture_len;
if (culture != nullptr)
culture_len = strlen (culture);
else
culture_len = 0;
size_t name_len = strlen (name);
static_local_string<SENSIBLE_PATH_MAX> pname (name_len + culture_len);
if (culture_len > 0)
pname.append (culture, culture_len);
pname.append (name, name_len);
constexpr char dll_extension[] = ".dll";
constexpr size_t dll_extension_len = sizeof(dll_extension) - 1;
bool is_dll = utils.ends_with (name, dll_extension);
size_t file_name_len = pname.length () + 1;
if (!is_dll)
file_name_len += dll_extension_len;
for (uint32_t oi = 0; oi < AndroidSystem::MAX_OVERRIDES; ++oi) {
override_dir = androidSystem.get_override_dir (oi);
if (override_dir == nullptr || !utils.directory_exists (override_dir))
continue;
size_t override_dir_len = strlen (override_dir);
static_local_string<SENSIBLE_PATH_MAX> fullpath (override_dir_len + file_name_len);
utils.path_combine (fullpath, override_dir, override_dir_len, pname.get (), pname.length ());
if (!is_dll) {
fullpath.append (dll_extension, dll_extension_len);
}
log_info (LOG_ASSEMBLY, "open_from_update_dir: trying to open assembly: %s\n", fullpath.get ());
if (utils.file_exists (fullpath.get ()))
result = mono_assembly_open_full (fullpath.get (), nullptr, 0);
if (result != nullptr) {
// TODO: register .mdb, .pdb file
break;
}
}
if (result && utils.should_log (LOG_ASSEMBLY)) {
log_info_nocheck (LOG_ASSEMBLY, "open_from_update_dir: loaded assembly: %p\n", result);
}
return result;
}
#endif
bool
MonodroidRuntime::should_register_file ([[maybe_unused]] const char *filename)
{
#ifndef RELEASE
size_t filename_len = strlen (filename) + 1; // includes space for path separator
for (size_t i = 0; i < AndroidSystem::MAX_OVERRIDES; ++i) {
const char *odir = androidSystem.get_override_dir (i);
if (odir == nullptr)
continue;
size_t odir_len = strlen (odir);
static_local_string<SENSIBLE_PATH_MAX> p (odir_len + filename_len);
utils.path_combine (p, odir, odir_len, filename, filename_len);
bool exists = utils.file_exists (p.get ());
if (exists) {
log_info (LOG_ASSEMBLY, "should not register '%s' as it exists in the override directory '%s'", filename, odir);
return !exists;
}
}
#endif
return true;
}
inline void
MonodroidRuntime::gather_bundled_assemblies (jstring_array_wrapper &runtimeApks, size_t *out_user_assemblies_count)
{
#if defined(DEBUG) || !defined (ANDROID)
if (application_config.instant_run_enabled) {
for (size_t i = 0; i < AndroidSystem::MAX_OVERRIDES; ++i) {
const char *p = androidSystem.get_override_dir (i);
if (!utils.directory_exists (p))
continue;
log_info (LOG_ASSEMBLY, "Loading TypeMaps from %s", p);
embeddedAssemblies.try_load_typemaps_from_directory (p);
}
}
#endif
int64_t apk_count = static_cast<int64_t>(runtimeApks.get_length ());
size_t prev_num_assemblies = 0;
for (int64_t i = apk_count - 1; i >= 0; --i) {
jstring_wrapper &apk_file = runtimeApks [static_cast<size_t>(i)];
size_t cur_num_assemblies = embeddedAssemblies.register_from<should_register_file> (apk_file.get_cstr ());
if (strstr (apk_file.get_cstr (), "/Mono.Android.DebugRuntime") == nullptr &&
strstr (apk_file.get_cstr (), "/Mono.Android.Platform.ApiLevel_") == nullptr)
*out_user_assemblies_count += (cur_num_assemblies - prev_num_assemblies);
prev_num_assemblies = cur_num_assemblies;
}
}
#if defined (DEBUG) && !defined (WINDOWS)
int
MonodroidRuntime::monodroid_debug_connect (int sock, struct sockaddr_in addr)
{
long flags = fcntl (sock, F_GETFL, nullptr);
flags |= O_NONBLOCK;
fcntl (sock, F_SETFL, flags);
int res = connect (sock, (struct sockaddr *) &addr, sizeof (addr));
if (res < 0) {
if (errno == EINPROGRESS) {
while (true) {
timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
fd_set fds;
FD_ZERO (&fds);
FD_SET (sock, &fds);
res = select (sock + 1, 0, &fds, 0, &tv);
if (res <= 0 && errno != EINTR) return -5;
socklen_t len = sizeof (int);
int val = 0;
if (getsockopt (sock, SOL_SOCKET, SO_ERROR, &val, &len) < 0) return -3;
if (val) return -4;
break;
}
} else {
return -2;
}
}
flags = fcntl (sock, F_GETFL, nullptr);
flags &= (~O_NONBLOCK);
fcntl (sock, F_SETFL, flags);
return 1;
}
int
MonodroidRuntime::monodroid_debug_accept (int sock, struct sockaddr_in addr)
{
ssize_t res = bind (sock, (struct sockaddr *) &addr, sizeof (addr));
if (res < 0)
return -1;
res = listen (sock, 1);
if (res < 0)
return -2;
int accepted = accept (sock, nullptr, nullptr);
if (accepted < 0)
return -3;
constexpr const char handshake_msg [] = "MonoDroid-Handshake\n";
constexpr size_t handshake_length = sizeof (handshake_msg) - 1;
do {
res = send (accepted, handshake_msg, handshake_length, 0);
} while (res == -1 && errno == EINTR);
if (res < 0)
return -4;
return accepted;
}
#endif
inline jint
MonodroidRuntime::Java_JNI_OnLoad (JavaVM *vm, [[maybe_unused]] void *reserved)
{
JNIEnv *env;
androidSystem.init_max_gref_count ();
vm->GetEnv ((void**)&env, JNI_VERSION_1_6);
osBridge.initialize_on_onload (vm, env);
return JNI_VERSION_1_6;
}
void
MonodroidRuntime::parse_gdb_options ()
{
char *val;
if (!(androidSystem.monodroid_get_system_property (Debug::DEBUG_MONO_GDB_PROPERTY, &val) > 0))
return;
if (strstr (val, "wait:") == val) {
/*
* The form of the property should be: 'wait:<timestamp>', where <timestamp> should be
* the output of date +%s in the android shell.
* If this property is set, wait for a native debugger to attach by spinning in a loop.
* The debugger can break the wait by setting 'monodroid_gdb_wait' to 0.
* If the current time is later than <timestamp> + 10s, the property is ignored.
*/
bool do_wait = true;
long long v = atoll (val + strlen ("wait:"));
if (v > 100000) {
time_t secs = time (nullptr);
if (v + 10 < secs) {
log_warn (LOG_DEFAULT, "Found stale %s property with value '%s', not waiting.", Debug::DEBUG_MONO_GDB_PROPERTY, val);
do_wait = false;
}
}
wait_for_gdb = do_wait;
}
delete[] val;
}
#if defined (DEBUG) && !defined (WINDOWS)
bool
MonodroidRuntime::parse_runtime_args (dynamic_local_string<PROPERTY_VALUE_BUFFER_LEN> &runtime_args, RuntimeOptions *options)
{
if (runtime_args.length () == 0) {
log_warn (LOG_DEFAULT, "runtime args empty");
return true;
}
constexpr char ARG_DEBUG[] = "debug";
constexpr size_t ARG_DEBUG_LENGTH = sizeof(ARG_DEBUG) - 1;
constexpr char ARG_TIMEOUT[] = "timeout=";
constexpr size_t ARG_TIMEOUT_LENGTH = sizeof(ARG_TIMEOUT) - 1;
constexpr char ARG_SERVER[] = "server=";
constexpr size_t ARG_SERVER_LENGTH = sizeof(ARG_SERVER) - 1;
constexpr char ARG_LOGLEVEL[] = "loglevel=";
constexpr size_t ARG_LOGLEVEL_LENGTH = sizeof(ARG_LOGLEVEL) - 1;
bool ret = true;
string_segment token;
while (runtime_args.next_token (',', token)) {
if (token.starts_with (ARG_DEBUG, ARG_DEBUG_LENGTH)) {
char *host = nullptr;
int sdb_port = 1000, out_port = -1;
options->debug = true;
if (token.has_at ('=', ARG_DEBUG_LENGTH)) {
constexpr size_t arg_name_length = ARG_DEBUG_LENGTH + 1; // Includes the '='
static_local_string<SMALL_STRING_PARSE_BUFFER_LEN> hostport (token.length () - arg_name_length);
hostport.assign (token.start () + arg_name_length, token.length () - arg_name_length);
string_segment address;
size_t field = 0;
while (field < 3 && hostport.next_token (':', address)) {
switch (field) {
case 0: // host
if (address.empty ()) {
log_error (LOG_DEFAULT, "Invalid --debug argument for the host field (empty string)");
} else {
host = utils.strdup_new (address.start (), address.length ());
}
break;
case 1: // sdb_port
if (!address.to_integer (sdb_port)) {
log_error (LOG_DEFAULT, "Invalid --debug argument for the sdb_port field");
}
break;
case 2: // out_port
if (!address.to_integer (out_port)) {
log_error (LOG_DEFAULT, "Invalid --debug argument for the sdb_port field");
}
break;
}
field++;
}
} else if (!token.has_at ('\0', ARG_DEBUG_LENGTH)) {
log_error (LOG_DEFAULT, "Invalid --debug argument.");
ret = false;
continue;
}
if (sdb_port < 0 || sdb_port > USHRT_MAX) {
log_error (LOG_DEFAULT, "Invalid SDB port value %d", sdb_port);
ret = false;
continue;
}
if (out_port > USHRT_MAX) {
log_error (LOG_DEFAULT, "Invalid output port value %d", out_port);
ret = false;
continue;
}
if (host == nullptr)
host = utils.strdup_new ("10.0.2.2");
options->host = host;
options->sdb_port = static_cast<uint16_t>(sdb_port);
options->out_port = out_port == -1 ? 0 : static_cast<uint16_t>(out_port);
} else if (token.starts_with (ARG_TIMEOUT, ARG_TIMEOUT_LENGTH)) {
if (!token.to_integer (options->timeout_time, ARG_TIMEOUT_LENGTH)) {
log_error (LOG_DEFAULT, "Invalid --timeout argument.");
ret = false;
}
} else if (token.starts_with (ARG_SERVER, ARG_SERVER_LENGTH)) {
options->server = token.has_at ('y', ARG_SERVER_LENGTH) || token.has_at ('Y', ARG_SERVER_LENGTH);
} else if (token.starts_with (ARG_LOGLEVEL, ARG_LOGLEVEL_LENGTH)) {
if (!token.to_integer (options->loglevel, ARG_LOGLEVEL_LENGTH)) {
log_error (LOG_DEFAULT, "Invalid --loglevel argument.");
ret = false;
}
} else {
static_local_string<SMALL_STRING_PARSE_BUFFER_LEN> arg (token);
log_error (LOG_DEFAULT, "Unknown runtime argument: '%s'", arg.get ());
ret = false;
}
}
return ret;
}
#endif // def DEBUG && !WINDOWS
inline void
MonodroidRuntime::set_debug_options (void)
{
if (androidSystem.monodroid_get_system_property (Debug::DEBUG_MONO_DEBUG_PROPERTY, nullptr) == 0)
return;
embeddedAssemblies.set_register_debug_symbols (true);
mono_debug_init (MONO_DEBUG_FORMAT_MONO);
}
void
MonodroidRuntime::mono_runtime_init ([[maybe_unused]] dynamic_local_string<PROPERTY_VALUE_BUFFER_LEN>& runtime_args)
{
#if defined (DEBUG) && !defined (WINDOWS)
RuntimeOptions options{};
int64_t cur_time;
cur_time = time (nullptr);
if (!parse_runtime_args (runtime_args, &options)) {
log_error (LOG_DEFAULT, "Failed to parse runtime args: '%s'", runtime_args.get ());
} else if (options.debug && cur_time > options.timeout_time) {
log_warn (LOG_DEBUGGER, "Not starting the debugger as the timeout value has been reached; current-time: %lli timeout: %lli", cur_time, options.timeout_time);
} else if (options.debug && cur_time <= options.timeout_time) {
embeddedAssemblies.set_register_debug_symbols (true);
int loglevel;
if (debug.have_debugger_log_level ())
loglevel = debug.get_debugger_log_level ();
else
loglevel = options.loglevel;
char *debug_arg = utils.monodroid_strdup_printf (
"--debugger-agent=transport=dt_socket,loglevel=%d,address=%s:%d,%sembedding=1",
loglevel,
options.host,
options.sdb_port,
options.server ? "server=y," : ""
);
char *debug_options [2] = {
debug_arg,
nullptr
};
// this text is used in unit tests to check the debugger started
// do not change it without updating the test.
log_warn (LOG_DEBUGGER, "Trying to initialize the debugger with options: %s", debug_arg);
if (options.out_port > 0) {
int sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
log_fatal (LOG_DEBUGGER, "Could not construct a socket for stdout and stderr; does your app have the android.permission.INTERNET permission? %s", strerror (errno));
exit (FATAL_EXIT_DEBUGGER_CONNECT);
}
sockaddr_in addr;
memset (&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_port = htons (options.out_port);
int r;
if ((r = inet_pton (AF_INET, options.host, &addr.sin_addr)) != 1) {
log_error (LOG_DEBUGGER, "Could not setup a socket for stdout and stderr: %s",
r == -1 ? strerror (errno) : "address not parseable in the specified address family");
exit (FATAL_EXIT_DEBUGGER_CONNECT);
}
if (options.server) {
int accepted = monodroid_debug_accept (sock, addr);
log_warn (LOG_DEBUGGER, "Accepted stdout connection: %d", accepted);
if (accepted < 0) {
log_fatal (LOG_DEBUGGER, "Error accepting stdout and stderr (%s:%d): %s",
options.host, options.out_port, strerror (errno));
exit (FATAL_EXIT_DEBUGGER_CONNECT);
}
dup2 (accepted, 1);
dup2 (accepted, 2);
} else {
if (monodroid_debug_connect (sock, addr) != 1) {
log_fatal (LOG_DEBUGGER, "Error connecting stdout and stderr (%s:%d): %s",
options.host, options.out_port, strerror (errno));
exit (FATAL_EXIT_DEBUGGER_CONNECT);
}
dup2 (sock, 1);
dup2 (sock, 2);
}
}
if (debug.enable_soft_breakpoints ()) {
constexpr char soft_breakpoints[] = "--soft-breakpoints";
debug_options[1] = const_cast<char*> (soft_breakpoints);
mono_jit_parse_options (2, debug_options);
} else {
mono_jit_parse_options (1, debug_options);
}
mono_debug_init (MONO_DEBUG_FORMAT_MONO);
} else {
set_debug_options ();
}
delete[] options.host;
#else
set_debug_options ();
#endif
// TESTING ASAN: use-after-free
// char *x = new char[10]{};
// delete[] x;
// log_warn (LOG_DEFAULT, "x == %s", x);
// TESTING UBSAN: integer overflow
//log_warn (LOG_DEFAULT, "Let us have an overflow: %d", INT_MAX + 1);
bool log_methods = utils.should_log (LOG_TIMING) && !(log_timing_categories & LOG_TIMING_BARE);
if (XA_UNLIKELY (log_methods)) {
simple_pointer_guard<char[]> jit_log_path = utils.path_combine (androidSystem.get_override_dir (0), "methods.txt");
jit_log = utils.monodroid_fopen (jit_log_path, "a");
utils.set_world_accessable (jit_log_path);
}
profiler_handle = mono_profiler_create (nullptr);
mono_profiler_set_thread_started_callback (profiler_handle, thread_start);
mono_profiler_set_thread_stopped_callback (profiler_handle, thread_end);
if (XA_UNLIKELY (log_methods)) {
jit_time.mark_start ();
mono_profiler_set_jit_begin_callback (profiler_handle, jit_begin);
mono_profiler_set_jit_done_callback (profiler_handle, jit_done);
mono_profiler_set_jit_failed_callback (profiler_handle, jit_failed);
}
parse_gdb_options ();
if (wait_for_gdb) {
log_warn (LOG_DEFAULT, "Waiting for gdb to attach...");
while (monodroid_gdb_wait) {
sleep (1);
}
}
dynamic_local_string<PROPERTY_VALUE_BUFFER_LEN> prop_val;
/* Additional runtime arguments passed to mono_jit_parse_options () */
if (androidSystem.monodroid_get_system_property (Debug::DEBUG_MONO_RUNTIME_ARGS_PROPERTY, prop_val) > 0) {
char **ptr;
log_warn (LOG_DEBUGGER, "passing '%s' as extra arguments to the runtime.\n", prop_val.get ());
char **args = utils.monodroid_strsplit (prop_val.get (), " ", 0);
int argc = 0;
for (ptr = args; *ptr; ptr++)
argc ++;
mono_jit_parse_options (argc, args);
}
mono_set_signal_chaining (1);
mono_set_crash_chaining (1);
osBridge.register_gc_hooks ();
if (mono_mkbundle_initialize_mono_api) {
BundleMonoAPI bundle_mono_api = {
.mono_register_bundled_assemblies = mono_register_bundled_assemblies,
.mono_register_config_for_assembly = mono_register_config_for_assembly,
.mono_jit_set_aot_mode = reinterpret_cast<void (*)(int)>(mono_jit_set_aot_mode),
.mono_aot_register_module = mono_aot_register_module,
.mono_config_parse_memory = mono_config_parse_memory,
.mono_register_machine_config = reinterpret_cast<void (*)(const char *)>(mono_register_machine_config),
};
/* The initialization function copies the struct */
mono_mkbundle_initialize_mono_api (&bundle_mono_api);
}
if (mono_mkbundle_init)
mono_mkbundle_init (mono_register_bundled_assemblies, mono_register_config_for_assembly, reinterpret_cast<void (*)(int)>(mono_jit_set_aot_mode));
/*
* Assembly preload hooks are invoked in _reverse_ registration order.
* Looking for assemblies from the update dir takes precedence over
* everything else, and thus must go LAST.
*/
embeddedAssemblies.install_preload_hooks ();
#ifndef RELEASE
mono_install_assembly_preload_hook (open_from_update_dir, nullptr);
#endif
}
MonoDomain*
MonodroidRuntime::create_domain (JNIEnv *env, jstring_array_wrapper &runtimeApks, bool is_root_domain)
{
size_t user_assemblies_count = 0;
gather_bundled_assemblies (runtimeApks, &user_assemblies_count);
if (!mono_mkbundle_init && user_assemblies_count == 0 && androidSystem.count_override_assemblies () == 0 && !is_running_on_desktop) {
log_fatal (LOG_DEFAULT, "No assemblies found in '%s' or '%s'. Assuming this is part of Fast Deployment. Exiting...",
androidSystem.get_override_dir (0),
(AndroidSystem::MAX_OVERRIDES > 1 && androidSystem.get_override_dir (1) != nullptr) ? androidSystem.get_override_dir (1) : "<unavailable>");
exit (FATAL_EXIT_NO_ASSEMBLIES);
}
MonoDomain *domain;
if (is_root_domain) {
domain = mono_jit_init_version (const_cast<char*> ("RootDomain"), const_cast<char*> ("mobile"));
} else {
MonoDomain* root_domain = mono_get_root_domain ();
constexpr char DOMAIN_NAME[] = "MonoAndroidDomain";
constexpr size_t DOMAIN_NAME_LENGTH = sizeof(DOMAIN_NAME) - 1;
constexpr size_t DOMAIN_NAME_TOTAL_SIZE = DOMAIN_NAME_LENGTH + MAX_INTEGER_DIGIT_COUNT_BASE10;
static_local_string<DOMAIN_NAME_TOTAL_SIZE + 1> domain_name (DOMAIN_NAME_TOTAL_SIZE);
domain_name.append (DOMAIN_NAME);
domain_name.append (android_api_level);
domain = utils.monodroid_create_appdomain (root_domain, domain_name.get (), /*shadow_copy:*/ 1, /*shadow_directory:*/ androidSystem.get_override_dir (0));
}
if constexpr (is_running_on_desktop) {
if (is_root_domain) {
// Check that our corlib is coherent with the version of Mono we loaded otherwise
// tell the IDE that the project likely need to be recompiled.
simple_pointer_guard<char, false> corlib_error_message_guard = const_cast<char*>(mono_check_corlib_version ());
char *corlib_error_message = corlib_error_message_guard.get ();
if (corlib_error_message == nullptr) {
if (!androidSystem.monodroid_get_system_property ("xamarin.studio.fakefaultycorliberrormessage", &corlib_error_message)) {
corlib_error_message = nullptr;
}
}
if (corlib_error_message != nullptr) {
jclass ex_klass = env->FindClass ("mono/android/MonoRuntimeException");
env->ThrowNew (ex_klass, corlib_error_message);
return nullptr;
}
// Load a basic environment for the RootDomain if run on desktop so that we can unload
// and reload most assemblies including Mono.Android itself
MonoAssemblyName *aname = mono_assembly_name_new ("System");
mono_assembly_load_full (aname, nullptr, nullptr, 0);
mono_assembly_name_free (aname);
}
}
return domain;
}
inline int
MonodroidRuntime::LocalRefsAreIndirect (JNIEnv *env, jclass runtimeClass, int version)
{
if (version < 14) {
java_System = nullptr;
java_System_identityHashCode = 0;
return 0;
}
java_System = utils.get_class_from_runtime_field(env, runtimeClass, "java_lang_System", true);
java_System_identityHashCode = env->GetStaticMethodID (java_System, "identityHashCode", "(Ljava/lang/Object;)I");
return 1;
}
inline void
MonodroidRuntime::lookup_bridge_info (MonoDomain *domain, MonoImage *image, const OSBridge::MonoJavaGCBridgeType *type, OSBridge::MonoJavaGCBridgeInfo *info)
{
info->klass = utils.monodroid_get_class_from_image (domain, image, type->_namespace, type->_typename);
info->handle = mono_class_get_field_from_name (info->klass, const_cast<char*> ("handle"));
info->handle_type = mono_class_get_field_from_name (info->klass, const_cast<char*> ("handle_type"));
info->refs_added = mono_class_get_field_from_name (info->klass, const_cast<char*> ("refs_added"));
info->weak_handle = mono_class_get_field_from_name (info->klass, const_cast<char*> ("weak_handle"));
if (info->klass == NULL || info->handle == NULL || info->handle_type == NULL ||
info->refs_added == NULL || info->weak_handle == NULL) {
log_fatal (LOG_DEFAULT, "The type `%s.%s` is missing required instance fields! handle=%p handle_type=%p refs_added=%p weak_handle=%p",
type->_namespace, type->_typename,
info->handle,
info->handle_type,
info->refs_added,
info->weak_handle);
exit (FATAL_EXIT_MONO_MISSING_SYMBOLS);
}
}
void
MonodroidRuntime::init_android_runtime (MonoDomain *domain, JNIEnv *env, jclass runtimeClass, jobject loader)
{
mono_add_internal_call ("Java.Interop.TypeManager::monodroid_typemap_java_to_managed", reinterpret_cast<const void*>(typemap_java_to_managed));
mono_add_internal_call ("Android.Runtime.JNIEnv::monodroid_typemap_managed_to_java", reinterpret_cast<const void*>(typemap_managed_to_java));
struct JnienvInitializeArgs init = {};
init.javaVm = osBridge.get_jvm ();
init.env = env;
init.logCategories = log_categories;
init.version = env->GetVersion ();
init.androidSdkVersion = android_api_level;
init.localRefsAreIndirect = LocalRefsAreIndirect (env, runtimeClass, init.androidSdkVersion);
init.isRunningOnDesktop = is_running_on_desktop ? 1 : 0;
init.brokenExceptionTransitions = application_config.broken_exception_transitions ? 1 : 0;
init.packageNamingPolicy = static_cast<int>(application_config.package_naming_policy);
init.boundExceptionType = application_config.bound_exception_type;
init.jniAddNativeMethodRegistrationAttributePresent = application_config.jni_add_native_method_registration_attribute_present ? 1 : 0;
// GC threshold is 90% of the max GREF count
init.grefGcThreshold = static_cast<int>(androidSystem.get_gref_gc_threshold ());
log_warn (LOG_GC, "GREF GC Threshold: %i", init.grefGcThreshold);
init.grefClass = utils.get_class_from_runtime_field (env, runtimeClass, "java_lang_Class", true);
Class_getName = env->GetMethodID (init.grefClass, "getName", "()Ljava/lang/String;");
init.Class_forName = env->GetStaticMethodID (init.grefClass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
MonoAssembly *assm = utils.monodroid_load_assembly (domain, "Mono.Android");
MonoImage *image = mono_assembly_get_image (assm);
uint32_t i = 0;
for ( ; i < OSBridge::NUM_XA_GC_BRIDGE_TYPES; ++i) {
lookup_bridge_info (domain, image, &osBridge.get_java_gc_bridge_type (i), &osBridge.get_java_gc_bridge_info (i));
}
// TODO: try looking up the method by its token
MonoClass *runtime = utils.monodroid_get_class_from_image (domain, image, "Android.Runtime", "JNIEnv");
MonoMethod *method = mono_class_get_method_from_name (runtime, "Initialize", 1);
if (method == nullptr) {
log_fatal (LOG_DEFAULT, "INTERNAL ERROR: Unable to find Android.Runtime.JNIEnv.Initialize!");
exit (FATAL_EXIT_MISSING_INIT);
}
MonoAssembly *ji_assm = utils.monodroid_load_assembly (domain, "Java.Interop");
MonoImage *ji_image = mono_assembly_get_image (ji_assm);
for ( ; i < OSBridge::NUM_XA_GC_BRIDGE_TYPES + OSBridge::NUM_JI_GC_BRIDGE_TYPES; ++i) {
lookup_bridge_info (domain, ji_image, &osBridge.get_java_gc_bridge_type (i), &osBridge.get_java_gc_bridge_info (i));
}
/* If running on desktop, we may be swapping in a new Mono.Android image when calling this
* so always make sure we have the freshest handle to the method.
*/
if (registerType == nullptr || is_running_on_desktop) {
registerType = mono_class_get_method_from_name (runtime, "RegisterJniNatives", 5);
}
if (registerType == nullptr) {
log_fatal (LOG_DEFAULT, "INTERNAL ERROR: Unable to find Android.Runtime.JNIEnv.RegisterJniNatives!");
exit (FATAL_EXIT_CANNOT_FIND_JNIENV);
}
MonoClass *android_runtime_jnienv = runtime;
MonoClassField *bridge_processing_field = mono_class_get_field_from_name (runtime, const_cast<char*> ("BridgeProcessing"));
if (android_runtime_jnienv ==nullptr || bridge_processing_field == nullptr) {
log_fatal (LOG_DEFAULT, "INTERNAL_ERROR: Unable to find Android.Runtime.JNIEnv.BridgeProcessing");
exit (FATAL_EXIT_CANNOT_FIND_JNIENV);
}
jclass lrefLoaderClass = env->GetObjectClass (loader);
init.Loader_loadClass = env->GetMethodID (lrefLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
env->DeleteLocalRef (lrefLoaderClass);
init.grefLoader = env->NewGlobalRef (loader);
init.grefIGCUserPeer = utils.get_class_from_runtime_field (env, runtimeClass, "mono_android_IGCUserPeer", true);
osBridge.initialize_on_runtime_init (env, runtimeClass);
log_info (LOG_DEFAULT, "Calling into managed runtime init");