/
gc.c
1563 lines (1345 loc) · 41.4 KB
/
gc.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
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
/*
* metadata/gc.c: GC icalls.
*
* Author: Paolo Molaro <lupus@ximian.com>
*
* Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2012 Xamarin Inc (http://www.xamarin.com)
*/
#include <config.h>
#include <glib.h>
#include <string.h>
#include <errno.h>
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/mono-gc.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/mono-mlist.h>
#include <mono/metadata/threadpool.h>
#include <mono/metadata/threadpool-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/sgen-conf.h>
#include <mono/utils/mono-logger-internal.h>
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
#include <mono/metadata/attach.h>
#include <mono/metadata/console-io.h>
#include <mono/utils/mono-semaphore.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/dtrace.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/atomic.h>
#ifndef HOST_WIN32
#include <pthread.h>
#endif
typedef struct DomainFinalizationReq {
MonoDomain *domain;
HANDLE done_event;
} DomainFinalizationReq;
#ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
extern void (*__imp_GC_finalizer_notifier)(void);
#define GC_finalizer_notifier __imp_GC_finalizer_notifier
extern int __imp_GC_finalize_on_demand;
#define GC_finalize_on_demand __imp_GC_finalize_on_demand
#endif
static gboolean gc_disabled = FALSE;
static gboolean finalizing_root_domain = FALSE;
#define mono_finalizer_lock() mono_mutex_lock (&finalizer_mutex)
#define mono_finalizer_unlock() mono_mutex_unlock (&finalizer_mutex)
static mono_mutex_t finalizer_mutex;
static mono_mutex_t reference_queue_mutex;
static GSList *domains_to_finalize= NULL;
static MonoMList *threads_to_finalize = NULL;
static MonoInternalThread *gc_thread;
static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
static void reference_queue_proccess_all (void);
static void mono_reference_queue_cleanup (void);
static void reference_queue_clear_for_domain (MonoDomain *domain);
#ifndef HAVE_NULL_GC
static HANDLE pending_done_event;
static HANDLE shutdown_event;
#endif
GCStats gc_stats;
static void
add_thread_to_finalize (MonoInternalThread *thread)
{
mono_finalizer_lock ();
if (!threads_to_finalize)
MONO_GC_REGISTER_ROOT_SINGLE (threads_to_finalize);
threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
mono_finalizer_unlock ();
}
static gboolean suspend_finalizers = FALSE;
/*
* actually, we might want to queue the finalize requests in a separate thread,
* but we need to be careful about the execution domain of the thread...
*/
void
mono_gc_run_finalize (void *obj, void *data)
{
MonoObject *exc = NULL;
MonoObject *o;
#ifndef HAVE_SGEN_GC
MonoObject *o2;
#endif
MonoMethod* finalizer = NULL;
MonoDomain *caller_domain = mono_domain_get ();
MonoDomain *domain;
RuntimeInvokeFunction runtime_invoke;
o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
if (suspend_finalizers)
return;
domain = o->vtable->domain;
#ifndef HAVE_SGEN_GC
mono_domain_finalizers_lock (domain);
o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
mono_domain_finalizers_unlock (domain);
if (!o2)
/* Already finalized somehow */
return;
#endif
/* make sure the finalizer is not called again if the object is resurrected */
object_register_finalizer (obj, NULL);
if (o->vtable->klass == mono_defaults.internal_thread_class) {
MonoInternalThread *t = (MonoInternalThread*)o;
if (mono_gc_is_finalizer_internal_thread (t))
/* Avoid finalizing ourselves */
return;
if (t->threadpool_thread && finalizing_root_domain) {
/* Don't finalize threadpool threads when
shutting down - they're finalized when the
threadpool shuts down. */
add_thread_to_finalize (t);
return;
}
}
if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
/*
* These can't be finalized during unloading/shutdown, since that would
* free the native code which can still be referenced by other
* finalizers.
* FIXME: This is not perfect, objects dying at the same time as
* dynamic methods can still reference them even when !shutdown.
*/
return;
}
if (mono_runtime_get_no_exec ())
return;
/* speedup later... and use a timeout */
/* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
/* Use _internal here, since this thread can enter a doomed appdomain */
mono_domain_set_internal (mono_object_domain (o));
/* delegates that have a native function pointer allocated are
* registered for finalization, but they don't have a Finalize
* method, because in most cases it's not needed and it's just a waste.
*/
if (o->vtable->klass->delegate) {
MonoDelegate* del = (MonoDelegate*)o;
if (del->delegate_trampoline)
mono_delegate_free_ftnptr ((MonoDelegate*)o);
mono_domain_set_internal (caller_domain);
return;
}
finalizer = mono_class_get_finalizer (o->vtable->klass);
#ifndef DISABLE_COM
/* If object has a CCW but has no finalizer, it was only
* registered for finalization in order to free the CCW.
* Else it needs the regular finalizer run.
* FIXME: what to do about ressurection and suppression
* of finalizer on object with CCW.
*/
if (mono_marshal_free_ccw (o) && !finalizer) {
mono_domain_set_internal (caller_domain);
return;
}
#endif
/*
* To avoid the locking plus the other overhead of mono_runtime_invoke (),
* create and precompile a wrapper which calls the finalize method using
* a CALLVIRT.
*/
if (!domain->finalize_runtime_invoke) {
MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
domain->finalize_runtime_invoke = mono_compile_method (invoke);
}
runtime_invoke = domain->finalize_runtime_invoke;
mono_runtime_class_init (o->vtable);
if (G_UNLIKELY (MONO_GC_FINALIZE_INVOKE_ENABLED ())) {
MONO_GC_FINALIZE_INVOKE ((unsigned long)o, mono_object_get_size (o),
o->vtable->klass->name_space, o->vtable->klass->name);
}
runtime_invoke (o, NULL, &exc, NULL);
if (exc)
mono_internal_thread_unhandled_exception (exc);
mono_domain_set_internal (caller_domain);
}
void
mono_gc_finalize_threadpool_threads (void)
{
while (threads_to_finalize) {
MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
/* Force finalization of the thread. */
thread->threadpool_thread = FALSE;
mono_object_register_finalizer ((MonoObject*)thread);
mono_gc_run_finalize (thread, NULL);
threads_to_finalize = mono_mlist_next (threads_to_finalize);
}
}
gpointer
mono_gc_out_of_memory (size_t size)
{
/*
* we could allocate at program startup some memory that we could release
* back to the system at this point if we're really low on memory (ie, size is
* lower than the memory we set apart)
*/
mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
return NULL;
}
/*
* Some of our objects may point to a different address than the address returned by GC_malloc()
* (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
* This also means that in the callback we need to adjust the pointer to get back the real
* MonoObject*.
* We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
* since that, too, can cause the underlying pointer to be offset.
*/
static void
object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
{
MonoDomain *domain;
if (obj == NULL)
mono_raise_exception (mono_get_exception_argument_null ("obj"));
domain = obj->vtable->domain;
#if HAVE_BOEHM_GC
if (mono_domain_is_unloading (domain) && (callback != NULL))
/*
* Can't register finalizers in a dying appdomain, since they
* could be invoked after the appdomain has been unloaded.
*/
return;
mono_domain_finalizers_lock (domain);
if (callback)
g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
else
g_hash_table_remove (domain->finalizable_objects_hash, obj);
mono_domain_finalizers_unlock (domain);
mono_gc_register_for_finalization (obj, callback);
#elif defined(HAVE_SGEN_GC)
/*
* If we register finalizers for domains that are unloading we might
* end up running them while or after the domain is being cleared, so
* the objects will not be valid anymore.
*/
if (!mono_domain_is_unloading (domain))
mono_gc_register_for_finalization (obj, callback);
#endif
}
/**
* mono_object_register_finalizer:
* @obj: object to register
*
* Records that object @obj has a finalizer, this will call the
* Finalize method when the garbage collector disposes the object.
*
*/
void
mono_object_register_finalizer (MonoObject *obj)
{
/* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
object_register_finalizer (obj, mono_gc_run_finalize);
}
/**
* mono_domain_finalize:
* @domain: the domain to finalize
* @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
*
* Request finalization of all finalizable objects inside @domain. Wait
* @timeout msecs for the finalization to complete.
*
* Returns: TRUE if succeeded, FALSE if there was a timeout
*/
gboolean
mono_domain_finalize (MonoDomain *domain, guint32 timeout)
{
DomainFinalizationReq *req;
guint32 res;
HANDLE done_event;
MonoInternalThread *thread = mono_thread_internal_current ();
#if defined(__native_client__)
return FALSE;
#endif
if (mono_thread_internal_current () == gc_thread)
/* We are called from inside a finalizer, not much we can do here */
return FALSE;
/*
* No need to create another thread 'cause the finalizer thread
* is still working and will take care of running the finalizers
*/
#ifndef HAVE_NULL_GC
if (gc_disabled)
return TRUE;
mono_gc_collect (mono_gc_max_generation ());
done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (done_event == NULL) {
return FALSE;
}
req = g_new0 (DomainFinalizationReq, 1);
req->domain = domain;
req->done_event = done_event;
if (domain == mono_get_root_domain ())
finalizing_root_domain = TRUE;
mono_finalizer_lock ();
domains_to_finalize = g_slist_append (domains_to_finalize, req);
mono_finalizer_unlock ();
/* Tell the finalizer thread to finalize this appdomain */
mono_gc_finalize_notify ();
if (timeout == -1)
timeout = INFINITE;
while (TRUE) {
res = WaitForSingleObjectEx (done_event, timeout, TRUE);
/* printf ("WAIT RES: %d.\n", res); */
if (res == WAIT_IO_COMPLETION) {
if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
return FALSE;
} else if (res == WAIT_TIMEOUT) {
/* We leak the handle here */
return FALSE;
} else {
break;
}
}
CloseHandle (done_event);
if (domain == mono_get_root_domain ()) {
mono_thread_pool_cleanup ();
mono_gc_finalize_threadpool_threads ();
}
return TRUE;
#else
/* We don't support domain finalization without a GC */
return FALSE;
#endif
}
void
ves_icall_System_GC_InternalCollect (int generation)
{
mono_gc_collect (generation);
}
gint64
ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
{
MONO_ARCH_SAVE_REGS;
if (forceCollection)
mono_gc_collect (mono_gc_max_generation ());
return mono_gc_get_used_size ();
}
void
ves_icall_System_GC_KeepAlive (MonoObject *obj)
{
MONO_ARCH_SAVE_REGS;
/*
* Does nothing.
*/
}
void
ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
{
if (!obj)
mono_raise_exception (mono_get_exception_argument_null ("obj"));
object_register_finalizer (obj, mono_gc_run_finalize);
}
void
ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
{
if (!obj)
mono_raise_exception (mono_get_exception_argument_null ("obj"));
/* delegates have no finalizers, but we register them to deal with the
* unmanaged->managed trampoline. We don't let the user suppress it
* otherwise we'd leak it.
*/
if (obj->vtable->klass->delegate)
return;
/* FIXME: Need to handle case where obj has COM Callable Wrapper
* generated for it that needs cleaned up, but user wants to suppress
* their derived object finalizer. */
object_register_finalizer (obj, NULL);
}
void
ves_icall_System_GC_WaitForPendingFinalizers (void)
{
#ifndef HAVE_NULL_GC
if (!mono_gc_pending_finalizers ())
return;
if (mono_thread_internal_current () == gc_thread)
/* Avoid deadlocks */
return;
/*
If the finalizer thread is not live, lets pretend no finalizers are pending since the current thread might
be the one responsible for starting it up.
*/
if (gc_thread == NULL)
return;
ResetEvent (pending_done_event);
mono_gc_finalize_notify ();
/* g_print ("Waiting for pending finalizers....\n"); */
WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
/* g_print ("Done pending....\n"); */
#endif
}
void
ves_icall_System_GC_register_ephemeron_array (MonoObject *array)
{
#ifdef HAVE_SGEN_GC
if (!mono_gc_ephemeron_array_add (array))
mono_raise_exception (mono_object_domain (array)->out_of_memory_ex);
#endif
}
MonoObject*
ves_icall_System_GC_get_ephemeron_tombstone (void)
{
return mono_domain_get ()->ephemeron_tombstone;
}
#define mono_allocator_lock() mono_mutex_lock (&allocator_section)
#define mono_allocator_unlock() mono_mutex_unlock (&allocator_section)
static mono_mutex_t allocator_section;
static mono_mutex_t handle_section;
typedef enum {
HANDLE_WEAK,
HANDLE_WEAK_TRACK,
HANDLE_NORMAL,
HANDLE_PINNED
} HandleType;
static HandleType mono_gchandle_get_type (guint32 gchandle);
MonoObject *
ves_icall_System_GCHandle_GetTarget (guint32 handle)
{
return mono_gchandle_get_target (handle);
}
/*
* if type == -1, change the target of the handle, otherwise allocate a new handle.
*/
guint32
ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
{
if (type == -1) {
mono_gchandle_set_target (handle, obj);
/* the handle doesn't change */
return handle;
}
switch (type) {
case HANDLE_WEAK:
return mono_gchandle_new_weakref (obj, FALSE);
case HANDLE_WEAK_TRACK:
return mono_gchandle_new_weakref (obj, TRUE);
case HANDLE_NORMAL:
return mono_gchandle_new (obj, FALSE);
case HANDLE_PINNED:
return mono_gchandle_new (obj, TRUE);
default:
g_assert_not_reached ();
}
return 0;
}
void
ves_icall_System_GCHandle_FreeHandle (guint32 handle)
{
mono_gchandle_free (handle);
}
gpointer
ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
{
MonoObject *obj;
if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
return (gpointer)-2;
obj = mono_gchandle_get_target (handle);
if (obj) {
MonoClass *klass = mono_object_class (obj);
if (klass == mono_defaults.string_class) {
return mono_string_chars ((MonoString*)obj);
} else if (klass->rank) {
return mono_array_addr ((MonoArray*)obj, char, 0);
} else {
/* the C# code will check and throw the exception */
/* FIXME: missing !klass->blittable test, see bug #61134 */
if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
return (gpointer)-1;
return (char*)obj + sizeof (MonoObject);
}
}
return NULL;
}
MonoBoolean
ves_icall_Mono_Runtime_SetGCAllowSynchronousMajor (MonoBoolean flag)
{
return mono_gc_set_allow_synchronous_major (flag);
}
typedef struct {
guint32 *bitmap;
gpointer *entries;
guint32 size;
guint8 type;
guint slot_hint : 24; /* starting slot for search */
/* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
/* we alloc this only for weak refs, since we can get the domain directly in the other cases */
guint16 *domain_ids;
} HandleData;
/* weak and weak-track arrays will be allocated in malloc memory
*/
static HandleData gc_handles [] = {
{NULL, NULL, 0, HANDLE_WEAK, 0},
{NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
{NULL, NULL, 0, HANDLE_NORMAL, 0},
{NULL, NULL, 0, HANDLE_PINNED, 0}
};
#define lock_handles(handles) mono_mutex_lock (&handle_section)
#define unlock_handles(handles) mono_mutex_unlock (&handle_section)
static int
find_first_unset (guint32 bitmap)
{
int i;
for (i = 0; i < 32; ++i) {
if (!(bitmap & (1 << i)))
return i;
}
return -1;
}
static void*
make_root_descr_all_refs (int numbits, gboolean pinned)
{
#ifdef HAVE_SGEN_GC
if (pinned)
return NULL;
#endif
return mono_gc_make_root_descr_all_refs (numbits);
}
static guint32
alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
{
gint slot, i;
guint32 res;
lock_handles (handles);
if (!handles->size) {
handles->size = 32;
if (handles->type > HANDLE_WEAK_TRACK) {
handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, make_root_descr_all_refs (handles->size, handles->type == HANDLE_PINNED));
} else {
handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
}
handles->bitmap = g_malloc0 (handles->size / 8);
}
i = -1;
for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
if (handles->bitmap [slot] != 0xffffffff) {
i = find_first_unset (handles->bitmap [slot]);
handles->slot_hint = slot;
break;
}
}
if (i == -1 && handles->slot_hint != 0) {
for (slot = 0; slot < handles->slot_hint; ++slot) {
if (handles->bitmap [slot] != 0xffffffff) {
i = find_first_unset (handles->bitmap [slot]);
handles->slot_hint = slot;
break;
}
}
}
if (i == -1) {
guint32 *new_bitmap;
guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
/* resize and copy the bitmap */
new_bitmap = g_malloc0 (new_size / 8);
memcpy (new_bitmap, handles->bitmap, handles->size / 8);
g_free (handles->bitmap);
handles->bitmap = new_bitmap;
/* resize and copy the entries */
if (handles->type > HANDLE_WEAK_TRACK) {
gpointer *entries;
entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, make_root_descr_all_refs (new_size, handles->type == HANDLE_PINNED));
mono_gc_memmove_aligned (entries, handles->entries, sizeof (gpointer) * handles->size);
mono_gc_free_fixed (handles->entries);
handles->entries = entries;
} else {
gpointer *entries;
guint16 *domain_ids;
domain_ids = g_malloc0 (sizeof (guint16) * new_size);
entries = g_malloc0 (sizeof (gpointer) * new_size);
memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
for (i = 0; i < handles->size; ++i) {
MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
if (obj) {
mono_gc_weak_link_add (&(entries [i]), obj, track);
mono_gc_weak_link_remove (&(handles->entries [i]), track);
} else {
g_assert (!handles->entries [i]);
}
}
g_free (handles->entries);
g_free (handles->domain_ids);
handles->entries = entries;
handles->domain_ids = domain_ids;
}
/* set i and slot to the next free position */
i = 0;
slot = (handles->size + 1) / 32;
handles->slot_hint = handles->size + 1;
handles->size = new_size;
}
handles->bitmap [slot] |= 1 << i;
slot = slot * 32 + i;
handles->entries [slot] = NULL;
if (handles->type <= HANDLE_WEAK_TRACK) {
/*FIXME, what to use when obj == null?*/
handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
if (obj)
mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
} else {
handles->entries [slot] = obj;
}
#ifndef DISABLE_PERFCOUNTERS
mono_perfcounters->gc_num_handles++;
#endif
unlock_handles (handles);
/*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
res = (slot << 3) | (handles->type + 1);
mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_CREATED, handles->type, res, obj);
return res;
}
/**
* mono_gchandle_new:
* @obj: managed object to get a handle for
* @pinned: whether the object should be pinned
*
* This returns a handle that wraps the object, this is used to keep a
* reference to a managed object from the unmanaged world and preventing the
* object from being disposed.
*
* If @pinned is false the address of the object can not be obtained, if it is
* true the address of the object can be obtained. This will also pin the
* object so it will not be possible by a moving garbage collector to move the
* object.
*
* Returns: a handle that can be used to access the object from
* unmanaged code.
*/
guint32
mono_gchandle_new (MonoObject *obj, gboolean pinned)
{
return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
}
/**
* mono_gchandle_new_weakref:
* @obj: managed object to get a handle for
* @pinned: whether the object should be pinned
*
* This returns a weak handle that wraps the object, this is used to
* keep a reference to a managed object from the unmanaged world.
* Unlike the mono_gchandle_new the object can be reclaimed by the
* garbage collector. In this case the value of the GCHandle will be
* set to zero.
*
* If @pinned is false the address of the object can not be obtained, if it is
* true the address of the object can be obtained. This will also pin the
* object so it will not be possible by a moving garbage collector to move the
* object.
*
* Returns: a handle that can be used to access the object from
* unmanaged code.
*/
guint32
mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
{
guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
return handle;
}
static HandleType
mono_gchandle_get_type (guint32 gchandle)
{
guint type = (gchandle & 7) - 1;
return type;
}
/**
* mono_gchandle_get_target:
* @gchandle: a GCHandle's handle.
*
* The handle was previously created by calling mono_gchandle_new or
* mono_gchandle_new_weakref.
*
* Returns a pointer to the MonoObject represented by the handle or
* NULL for a collected object if using a weakref handle.
*/
MonoObject*
mono_gchandle_get_target (guint32 gchandle)
{
guint slot = gchandle >> 3;
guint type = (gchandle & 7) - 1;
HandleData *handles = &gc_handles [type];
MonoObject *obj = NULL;
if (type > 3)
return NULL;
lock_handles (handles);
if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
if (handles->type <= HANDLE_WEAK_TRACK) {
obj = mono_gc_weak_link_get (&handles->entries [slot]);
} else {
obj = handles->entries [slot];
}
} else {
/* print a warning? */
}
unlock_handles (handles);
/*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
return obj;
}
static void
mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
{
guint slot = gchandle >> 3;
guint type = (gchandle & 7) - 1;
HandleData *handles = &gc_handles [type];
MonoObject *old_obj = NULL;
if (type > 3)
return;
lock_handles (handles);
if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
if (handles->type <= HANDLE_WEAK_TRACK) {
old_obj = handles->entries [slot];
if (handles->entries [slot])
mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
if (obj)
mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
/*FIXME, what to use when obj == null?*/
handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
} else {
handles->entries [slot] = obj;
}
} else {
/* print a warning? */
}
/*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
unlock_handles (handles);
}
/**
* mono_gchandle_is_in_domain:
* @gchandle: a GCHandle's handle.
* @domain: An application domain.
*
* Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
*/
gboolean
mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
{
guint slot = gchandle >> 3;
guint type = (gchandle & 7) - 1;
HandleData *handles = &gc_handles [type];
gboolean result = FALSE;
if (type > 3)
return FALSE;
lock_handles (handles);
if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
if (handles->type <= HANDLE_WEAK_TRACK) {
result = domain->domain_id == handles->domain_ids [slot];
} else {
MonoObject *obj;
obj = handles->entries [slot];
if (obj == NULL)
result = TRUE;
else
result = domain == mono_object_domain (obj);
}
} else {
/* print a warning? */
}
unlock_handles (handles);
return result;
}
/**
* mono_gchandle_free:
* @gchandle: a GCHandle's handle.
*
* Frees the @gchandle handle. If there are no outstanding
* references, the garbage collector can reclaim the memory of the
* object wrapped.
*/
void
mono_gchandle_free (guint32 gchandle)
{
guint slot = gchandle >> 3;
guint type = (gchandle & 7) - 1;
HandleData *handles = &gc_handles [type];
if (type > 3)
return;
lock_handles (handles);
if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
if (handles->type <= HANDLE_WEAK_TRACK) {
if (handles->entries [slot])
mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
} else {
handles->entries [slot] = NULL;
}
handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
} else {
/* print a warning? */
}
#ifndef DISABLE_PERFCOUNTERS
mono_perfcounters->gc_num_handles--;
#endif
/*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
unlock_handles (handles);
mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_DESTROYED, handles->type, gchandle, NULL);
}
/**
* mono_gchandle_free_domain:
* @domain: domain that is unloading
*
* Function used internally to cleanup any GC handle for objects belonging
* to the specified domain during appdomain unload.
*/
void
mono_gchandle_free_domain (MonoDomain *domain)
{
guint type;
for (type = 0; type < 3; ++type) {
guint slot;
HandleData *handles = &gc_handles [type];
lock_handles (handles);
for (slot = 0; slot < handles->size; ++slot) {
if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
continue;
if (type <= HANDLE_WEAK_TRACK) {
if (domain->domain_id == handles->domain_ids [slot]) {
handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
if (handles->entries [slot])
mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
}
} else {
if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
handles->entries [slot] = NULL;
}
}
}
unlock_handles (handles);
}
}
MonoBoolean
GCHandle_CheckCurrentDomain (guint32 gchandle)
{
return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
}
#ifndef HAVE_NULL_GC
#ifdef MONO_HAS_SEMAPHORES
static MonoSemType finalizer_sem;
#endif
static HANDLE finalizer_event;
static volatile gboolean finished=FALSE;
void
mono_gc_finalize_notify (void)
{
#ifdef DEBUG
g_message ( "%s: prodding finalizer", __func__);
#endif
#ifdef MONO_HAS_SEMAPHORES
MONO_SEM_POST (&finalizer_sem);
#else
SetEvent (finalizer_event);
#endif
}
#ifdef HAVE_BOEHM_GC
static void
collect_objects (gpointer key, gpointer value, gpointer user_data)
{
GPtrArray *arr = (GPtrArray*)user_data;
g_ptr_array_add (arr, key);
}