-
Notifications
You must be signed in to change notification settings - Fork 533
/
monodroid-glue.cc
2237 lines (1845 loc) · 66.3 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 <stdlib.h>
#include <stdarg.h>
#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>
#include <dlfcn.h>
#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/metadata/profiler.h>
#include <mono/utils/mono-counters.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
#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 "unzip.h"
#include "ioapi.h"
#include "monodroid-glue.h"
#include "mkbundle-api.h"
#include "monodroid-glue-internal.hh"
#include "globals.hh"
#include "xamarin-app.h"
#ifndef WINDOWS
#include "xamarin_getifaddrs.h"
#endif
#define XA_LOG_COUNTERS (MONO_COUNTER_JIT | MONO_COUNTER_METADATA | MONO_COUNTER_GC | MONO_COUNTER_GENERICS)
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"
// TODO: all of these must be moved to some class
static pthread_mutex_t process_cmd_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t process_cmd_cond = PTHREAD_COND_INITIALIZER;
static int debugging_configured;
static int sdb_fd;
static int profiler_configured;
static int profiler_fd;
static char *profiler_description;
#if DEBUG && !defined (WINDOWS)
static int config_timedout;
static struct timeval wait_tv;
static struct timespec wait_ts;
#endif // def DEBUG
static MonoMethod* registerType;
/*
* If set, monodroid will spin in a loop until the debugger breaks the wait by
* clearing monodroid_gdb_wait.
*/
static int wait_for_gdb;
static volatile int monodroid_gdb_wait = TRUE;
static int android_api_level = 0;
static timing_period jit_time;
#include "config.include"
#include "machine.config.include"
/* Can be called by a native debugger to break the wait on startup */
MONO_API void
monodroid_clear_gdb_wait (void)
{
monodroid_gdb_wait = FALSE;
}
#ifdef WINDOWS
static const char* get_xamarin_android_msbuild_path (void);
const char *BasicAndroidSystem::SYSTEM_LIB_PATH = get_xamarin_android_msbuild_path();
#endif
/* !DO NOT REMOVE! Used by Mono BCL */
MONO_API int
_monodroid_get_android_api_level (void)
{
return android_api_level;
}
/* Invoked by System.Core.dll!System.IO.MemoryMappedFiles.MemoryMapImpl.getpagesize */
MONO_API int
monodroid_getpagesize (void)
{
#ifndef WINDOWS
return getpagesize ();
#else
SYSTEM_INFO info;
GetSystemInfo (&info);
return info.dwPageSize;
#endif
}
/* Invoked by:
- System.Core.dll!System.TimeZoneInfo.Android.GetDefaultTimeZoneName
- Mono.Android.dll!Android.Runtime.AndroidEnvironment.GetDefaultTimeZone
*/
MONO_API void
monodroid_free (void *ptr)
{
free (ptr);
}
MONO_API int
monodroid_get_system_property (const char *name, char **value)
{
return androidSystem.monodroid_get_system_property (name, value);
}
/* 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;
// This function could be improved if we somehow marked an apk containing just the bundled app as
// such - perhaps another __XA* environment variable? Would certainly make code faster.
static void
setup_bundled_app (const char *dso_name)
{
if (!application_config.is_a_bundled_app)
return;
static int dlopen_flags = RTLD_LAZY;
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 {
bool needs_free = false;
log_info (LOG_DEFAULT, "bundle app: normal mode");
char *bundle_path = androidSystem.get_full_dso_path_on_disk (dso_name, &needs_free);
log_info (LOG_DEFAULT, "bundle_path == %s", bundle_path ? bundle_path : "<nullptr>");
if (bundle_path == nullptr)
return;
log_info (LOG_BUNDLE, "Attempting to load bundled app from %s", bundle_path);
libapp = androidSystem.load_dso (bundle_path, dlopen_flags, TRUE);
if (needs_free)
delete[] bundle_path;
}
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> (dlsym (libapp, "initialize_mono_api"));
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> (dlsym (libapp, "mono_mkbundle_init"));
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);
}
typedef struct {
void *dummy;
} MonoDroidProfiler;
static MonoProfilerHandle profiler_handle;
static jclass TimeZone_class;
static constexpr bool is_running_on_desktop =
#if ANDROID
false;
#else
true;
#endif
MONO_API int
_monodroid_max_gref_get (void)
{
return static_cast<int>(androidSystem.get_max_gref_count ());
}
MONO_API int
_monodroid_gref_get (void)
{
return osBridge.get_gc_gref_count ();
}
MONO_API void
_monodroid_gref_log (const char *message)
{
osBridge._monodroid_gref_log (message);
}
MONO_API int
_monodroid_gref_log_new (jobject curHandle, char curType, jobject newHandle, char newType, const char *threadName, int threadId, const char *from, int from_writable)
{
return osBridge._monodroid_gref_log_new (curHandle, curType, newHandle, newType, threadName, threadId, from, from_writable);
}
MONO_API void
_monodroid_gref_log_delete (jobject handle, char type, const char *threadName, int threadId, const char *from, int from_writable)
{
osBridge._monodroid_gref_log_delete (handle, type, threadName, threadId, from, from_writable);
}
MONO_API void
_monodroid_weak_gref_new (jobject curHandle, char curType, jobject newHandle, char newType, const char *threadName, int threadId, const char *from, int from_writable)
{
osBridge._monodroid_weak_gref_new (curHandle, curType, newHandle, newType, threadName, threadId, from, from_writable);
}
MONO_API void
_monodroid_weak_gref_delete (jobject handle, char type, const char *threadName, int threadId, const char *from, int from_writable)
{
osBridge._monodroid_weak_gref_delete (handle, type, threadName, threadId, from, from_writable);
}
MONO_API void
_monodroid_lref_log_new (int lrefc, jobject handle, char type, const char *threadName, int threadId, const char *from, int from_writable)
{
osBridge._monodroid_lref_log_new (lrefc, handle, type, threadName, threadId, from, from_writable);
}
MONO_API void
_monodroid_lref_log_delete (int lrefc, jobject handle, char type, const char *threadName, int threadId, const char *from, int from_writable)
{
osBridge._monodroid_lref_log_delete (lrefc, handle, type, threadName, threadId, from, from_writable);
}
JNIEnv*
get_jnienv (void)
{
return osBridge.ensure_jnienv ();
}
/* The context (mapping to a Mono AppDomain) that is currently selected as the
* active context from the point of view of Java. We cannot rely on the value
* of `mono_domain_get` for this as it's stored per-thread and we want to be
* able to switch our different contexts from different threads.
*/
static int current_context_id = -1;
static void
thread_start (MonoProfiler *prof, 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 ((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
}
}
static void
thread_end (MonoProfiler *prof, 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
}
}
FILE *jit_log;
static void
log_jit_event (MonoMethod *method, const char *event_name)
{
jit_time.mark_end ();
if (!jit_log)
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, diff.sec, diff.ms, diff.ns);
free (name);
}
static void
jit_begin (MonoProfiler *prof, MonoMethod *method)
{
log_jit_event (method, "begin");
}
static void
jit_failed (MonoProfiler *prof, MonoMethod *method)
{
log_jit_event (method, "failed");
}
static void
jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo* jinfo)
{
log_jit_event (method, "done");
}
#ifndef RELEASE
MonoAssembly*
open_from_update_dir (MonoAssemblyName *aname, char **assemblies_path, void *user_data)
{
MonoAssembly *result = nullptr;
int found = 0;
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));
char *pname;
for (uint32_t oi = 0; oi < AndroidSystem::MAX_OVERRIDES; ++oi)
if (androidSystem.get_override_dir (oi) != nullptr && utils.directory_exists (androidSystem.get_override_dir (oi)))
found = 1;
if (!found)
return nullptr;
if (culture != nullptr && strlen (culture) > 0)
pname = utils.path_combine (culture, name);
else
pname = utils.strdup_new (name);
static const char *formats[] = {
"%s" MONODROID_PATH_SEPARATOR "%s",
"%s" MONODROID_PATH_SEPARATOR "%s.dll",
"%s" MONODROID_PATH_SEPARATOR "%s.exe",
};
for (size_t fi = 0; fi < sizeof (formats)/sizeof (formats [0]) && result == nullptr; ++fi) {
for (uint32_t oi = 0; oi < AndroidSystem::MAX_OVERRIDES; ++oi) {
char *fullpath;
if (androidSystem.get_override_dir (oi) == nullptr || !utils.directory_exists (androidSystem.get_override_dir (oi)))
continue;
fullpath = utils.monodroid_strdup_printf (formats [fi], androidSystem.get_override_dir (oi), pname);
log_info (LOG_ASSEMBLY, "open_from_update_dir: trying to open assembly: %s\n", fullpath);
if (utils.file_exists (fullpath))
result = mono_assembly_open_full (fullpath, nullptr, 0);
free (fullpath);
if (result) {
// TODO: register .mdb, .pdb file
break;
}
}
}
delete[] pname;
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
should_register_file (const char *filename)
{
#ifndef RELEASE
for (size_t i = 0; i < AndroidSystem::MAX_OVERRIDES; ++i) {
const char *odir = androidSystem.get_override_dir (i);
if (odir == nullptr)
continue;
char *p = utils.path_combine (odir, filename);
bool exists = utils.file_exists (p);
delete[] p;
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;
}
static void
gather_bundled_assemblies (JNIEnv *env, jstring_array_wrapper &runtimeApks, bool register_debug_symbols, size_t *out_user_assemblies_count)
{
#if defined(DEBUG) || !defined (ANDROID)
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
size_t prev_num_assemblies = 0;
for (int64_t i = static_cast<int64_t>(runtimeApks.get_length () - 1); i >= 0; --i) {
size_t cur_num_assemblies;
jstring_wrapper &apk_file = runtimeApks [static_cast<size_t>(i)];
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 monodroid_debug_connect (int sock, struct sockaddr_in addr) {
long flags = 0;
int res = 0;
fd_set fds;
struct timeval tv;
socklen_t len;
int val = 0;
flags = fcntl (sock, F_GETFL, nullptr);
flags |= O_NONBLOCK;
fcntl (sock, F_SETFL, flags);
res = connect (sock, (struct sockaddr *) &addr, sizeof (addr));
if (res < 0) {
if (errno == EINPROGRESS) {
while (1) {
tv.tv_sec = 2;
tv.tv_usec = 0;
FD_ZERO (&fds);
FD_SET (sock, &fds);
res = select (sock + 1, 0, &fds, 0, &tv);
if (res <= 0 && errno != EINTR) return -5;
len = sizeof (int);
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
monodroid_debug_accept (int sock, struct sockaddr_in addr)
{
char handshake_msg [128];
ssize_t res;
int accepted;
res = bind (sock, (struct sockaddr *) &addr, sizeof (addr));
if (res < 0)
return -1;
res = listen (sock, 1);
if (res < 0)
return -2;
accepted = accept (sock, nullptr, nullptr);
if (accepted < 0)
return -3;
sprintf (handshake_msg, "MonoDroid-Handshake\n");
do {
res = send (accepted, handshake_msg, strlen (handshake_msg), 0);
} while (res == -1 && errno == EINTR);
if (res < 0)
return -4;
return accepted;
}
#endif
JNIEXPORT jint JNICALL
JNI_OnLoad (JavaVM *vm, 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;
}
static void
parse_gdb_options (void)
{
char *val;
if (!(utils.monodroid_get_namespaced_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.
*/
long long v;
int do_wait = TRUE;
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)
typedef struct {
int debug;
int loglevel;
int64_t timeout_time;
char *host;
uint16_t sdb_port, out_port;
mono_bool server;
} RuntimeOptions;
static int
parse_runtime_args (char *runtime_args, RuntimeOptions *options)
{
char **args, **ptr;
if (!runtime_args)
return 1;
options->timeout_time = 0;
args = utils.monodroid_strsplit (runtime_args, ",", 0);
for (ptr = args; ptr && *ptr; ptr++) {
const char *arg = *ptr;
if (!strncmp (arg, "debug", 5)) {
char *host = nullptr;
int sdb_port = 1000, out_port = -1;
options->debug = 1;
if (arg[5] == '=') {
const char *sep, *endp;
arg += 6;
sep = strchr (arg, ':');
if (sep != nullptr) {
size_t arg_len = static_cast<size_t>(sep - arg);
size_t alloc_size = ADD_WITH_OVERFLOW_CHECK (size_t, arg_len, 1);
host = new char [alloc_size];
memset (host, 0x00, alloc_size);
strncpy (host, arg, arg_len);
arg = sep+1;
sdb_port = (int) strtol (arg, const_cast<char**> (&endp), 10);
if (endp == arg) {
log_error (LOG_DEFAULT, "Invalid --debug argument.");
continue;
} else if (*endp == ':') {
arg = endp+1;
out_port = (int) strtol (arg, const_cast<char**> (&endp), 10);
if ((endp == arg) || (*endp != '\0')) {
log_error (LOG_DEFAULT, "Invalid --debug argument.");
continue;
}
} else if (*endp != '\0') {
log_error (LOG_DEFAULT, "Invalid --debug argument.");
continue;
}
}
} else if (arg[5] != '\0') {
log_error (LOG_DEFAULT, "Invalid --debug argument.");
continue;
}
if (!host)
host = utils.strdup_new ("10.0.2.2");
if (sdb_port < 0 || sdb_port > USHRT_MAX) {
log_error (LOG_DEFAULT, "Invalid SDB port value %d", sdb_port);
continue;
}
if (out_port > USHRT_MAX) {
log_error (LOG_DEFAULT, "Invalid output port value %d", out_port);
continue;
}
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 (!strncmp (arg, "timeout=", 8)) {
char *endp;
arg += sizeof ("timeout");
options->timeout_time = strtoll (arg, &endp, 10);
if ((endp == arg) || (*endp != '\0'))
log_error (LOG_DEFAULT, "Invalid --timeout argument.");
continue;
} else if (!strncmp (arg, "server=", 7)) {
arg += sizeof ("server");
options->server = *arg == 'y' || *arg == 'Y';
continue;
} else if (!strncmp (arg, "loglevel=", 9)) {
char *endp;
arg += sizeof ("loglevel");
options->loglevel = static_cast<int>(strtol (arg, &endp, 10));
if ((endp == arg) || (*endp != '\0'))
log_error (LOG_DEFAULT, "Invalid --loglevel argument.");
} else {
log_error (LOG_DEFAULT, "Unknown runtime argument: '%s'", arg);
continue;
}
}
utils.monodroid_strfreev (args);
return 1;
}
#endif // def DEBUG && !WINDOWS
static void
set_debug_options (void)
{
if (utils.monodroid_get_namespaced_system_property (Debug::DEBUG_MONO_DEBUG_PROPERTY, nullptr) == 0)
return;
embeddedAssemblies.set_register_debug_symbols (true);
mono_debug_init (MONO_DEBUG_FORMAT_MONO);
}
#ifdef ANDROID
#ifdef DEBUG
static const char *soft_breakpoint_kernel_list[] = {
"2.6.32.21-g1e30168", nullptr
};
static int
enable_soft_breakpoints (void)
{
struct utsname name;
/* This check is to make debugging work on some old Samsung device which had
* a patched kernel that would abort the application after several segfaults
* (with the SIGSEGV being used for single-stepping in Mono)
*/
uname (&name);
for (const char** ptr = soft_breakpoint_kernel_list; *ptr; ptr++) {
if (!strcmp (name.release, *ptr)) {
log_info (LOG_DEBUGGER, "soft breakpoints enabled due to kernel version match (%s)", name.release);
return 1;
}
}
char *value;
/* Soft breakpoints are enabled by default */
if (utils.monodroid_get_namespaced_system_property (Debug::DEBUG_MONO_SOFT_BREAKPOINTS, &value) <= 0) {
log_info (LOG_DEBUGGER, "soft breakpoints enabled by default (%s property not defined)", Debug::DEBUG_MONO_SOFT_BREAKPOINTS);
return 1;
}
int ret;
if (strcmp ("0", value) == 0) {
ret = 0;
log_info (LOG_DEBUGGER, "soft breakpoints disabled (%s property set to %s)", Debug::DEBUG_MONO_SOFT_BREAKPOINTS, value);
} else {
ret = 1;
log_info (LOG_DEBUGGER, "soft breakpoints enabled (%s property set to %s)", Debug::DEBUG_MONO_SOFT_BREAKPOINTS, value);
}
delete[] value;
return ret;
}
#endif /* DEBUG */
#else /* !defined (ANDROID) */
#if defined (DEBUG) && !defined (WINDOWS)
#ifndef enable_soft_breakpoints
static int
enable_soft_breakpoints (void)
{
return 0;
}
#endif /* DEBUG */
#endif // enable_soft_breakpoints
#endif /* defined (ANDROID) */
static void
mono_runtime_init (char *runtime_args)
{
char *prop_val;
#if defined (DEBUG) && !defined (WINDOWS)
RuntimeOptions options;
int64_t cur_time;
memset(&options, 0, sizeof (options));
cur_time = time (nullptr);
if (!parse_runtime_args (runtime_args, &options)) {
log_error (LOG_DEFAULT, "Failed to parse runtime args: '%s'", runtime_args);
} 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) {
char *debug_arg;
char *debug_options [2];
embeddedAssemblies.set_register_debug_symbols (true);
debug_arg = utils.monodroid_strdup_printf ("--debugger-agent=transport=dt_socket,loglevel=%d,address=%s:%d,%sembedding=1", options.loglevel, options.host, options.sdb_port,
options.server ? "server=y," : "");
debug_options[0] = debug_arg;
log_warn (LOG_DEBUGGER, "Trying to initialize the debugger with options: %s", debug_arg);
if (options.out_port > 0) {
struct sockaddr_in addr;
int sock;
int r;
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);
}
memset(&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_port = htons (options.out_port);
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 (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 ();
}
#else
set_debug_options ();
#endif
bool log_methods = utils.should_log (LOG_TIMING) && !(log_timing_categories & LOG_TIMING_BARE);
if (XA_UNLIKELY (log_methods)) {
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);
delete[] 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);
}
}
/* Additional runtime arguments passed to mono_jit_parse_options () */
if (utils.monodroid_get_namespaced_system_property (Debug::DEBUG_MONO_RUNTIME_ARGS_PROPERTY, &prop_val) > 0) {
char **args, **ptr;
int argc;
log_warn (LOG_DEBUGGER, "passing '%s' as extra arguments to the runtime.\n", prop_val);
args = utils.monodroid_strsplit (prop_val, " ", 0);
argc = 0;
delete[] prop_val;
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
}
static MonoDomain*
create_domain (JNIEnv *env, jclass runtimeClass, jstring_array_wrapper &runtimeApks, jobject loader, bool is_root_domain)
{
MonoDomain *domain;
size_t user_assemblies_count = 0;;
gather_bundled_assemblies (env, runtimeApks, embeddedAssemblies.get_register_debug_symbols (), &user_assemblies_count);
if (!mono_mkbundle_init && user_assemblies_count == 0 && androidSystem.count_override_assemblies () == 0) {
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);
}
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 ();
char *domain_name = utils.monodroid_strdup_printf ("MonoAndroidDomain%d", android_api_level);
domain = utils.monodroid_create_appdomain (root_domain, domain_name, /*shadow_copy:*/ 1, /*shadow_directory:*/ androidSystem.get_override_dir (0));
free (domain_name);
}
if (is_running_on_desktop && is_root_domain) {