Thu Dec 19 14:19:42 CET 2002 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / metadata / class.c
1 /*
2  * class.c: Class management for the Mono runtime
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  *
9  * Possible Optimizations:
10  *     in mono_class_create, do not allocate the class right away,
11  *     but wait until you know the size of the FieldMap, so that
12  *     the class embeds directly the FieldMap after the vtable.
13  *
14  * 
15  */
16 #include <config.h>
17 #include <glib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
22 #include <mono/metadata/image.h>
23 #include <mono/metadata/cil-coff.h>
24 #include <mono/metadata/metadata.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/tokentype.h>
27 #include <mono/metadata/class.h>
28 #include <mono/metadata/object.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/mono-endian.h>
31 #include <mono/metadata/debug-helpers.h>
32 #include <mono/os/gc_wrapper.h>
33
34 #define CSIZE(x) (sizeof (x) / 4)
35
36 MonoStats mono_stats;
37
38 gboolean mono_print_vtable = FALSE;
39
40 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
41
42 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
43
44 MonoClass *
45 mono_class_from_typeref (MonoImage *image, guint32 type_token)
46 {
47         guint32 cols [MONO_TYPEREF_SIZE];
48         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
49         guint32 idx;
50         const char *name, *nspace;
51         MonoClass *res;
52
53         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
54
55         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
56         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
57         
58         idx = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
59         switch (cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK) {
60         case RESOLTION_SCOPE_MODULE:
61                 if (!idx)
62                         g_error ("null ResolutionScope not yet handled");
63                 /* a typedef in disguise */
64                 return mono_class_from_name (image, nspace, name);
65         case RESOLTION_SCOPE_MODULEREF:
66                 return mono_class_from_name (image->assembly->modules [idx - 1], nspace, name);
67         case RESOLTION_SCOPE_TYPEREF: {
68                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
69                 GList *tmp;
70                 mono_class_init (enclosing);
71                 for (tmp = enclosing->nested_classes; tmp; tmp = tmp->next) {
72                         res = tmp->data;
73                         if (strcmp (res->name, name) == 0)
74                                 return res;
75                 }
76                 g_warning ("TypeRef ResolutionScope not yet handled (%d)", idx);
77                 return NULL;
78         }
79         case RESOLTION_SCOPE_ASSEMBLYREF:
80                 break;
81         }
82
83         if (!image->references ||  !image->references [idx-1]) {
84                 /* 
85                  * detected a reference to mscorlib, we simply return a reference to a dummy 
86                  * until we have a better solution.
87                  */
88                 fprintf(stderr, "Sending dummy where %s.%s expected\n", mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]), mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME])); 
89                 
90                 res = mono_class_from_name (image, "System", "MonoDummy");
91                 /* prevent method loading */
92                 res->dummy = 1;
93                 /* some storage if the type is used  - very ugly hack */
94                 res->instance_size = 2*sizeof (gpointer);
95                 return res;
96         }       
97
98         /* load referenced assembly */
99         image = image->references [idx-1]->image;
100
101         return mono_class_from_name (image, nspace, name);
102 }
103
104 MonoMarshalType *
105 mono_marshal_load_type_info (MonoClass* klass)
106 {
107         int i, j, count = 0;
108         MonoMarshalType *info;
109         guint32 layout;
110
111         g_assert (klass != NULL);
112
113         if (klass->marshal_info)
114                 return klass->marshal_info;
115
116         if (!klass->inited)
117                 mono_class_init (klass);
118         
119         for (i = 0; i < klass->field.count; ++i) {
120                 if (klass->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
121                         continue;
122                 count++;
123         }
124
125         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
126
127         klass->marshal_info = info = g_malloc0 (sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
128         info->num_fields = count;
129         
130         if (klass->parent)
131                 info->native_size = mono_class_native_size (klass->parent, NULL);
132
133         for (j = i = 0; i < klass->field.count; ++i) {
134                 int size, align;
135                 
136                 if (klass->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
137                         continue;
138
139                 if (klass->fields [i].type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
140                         mono_metadata_field_info (klass->image, klass->field.first + i, 
141                                                   NULL, NULL, &info->fields [j].mspec);
142
143                 info->fields [j].field = &klass->fields [i];
144
145                 switch (layout) {
146                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
147                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
148                         size = mono_marshal_type_size (klass->fields [i].type, info->fields [j].mspec, 
149                                                        &align, TRUE, klass->unicode);
150                         align = klass->packing_size ? MIN (klass->packing_size, align): align;  
151                         info->fields [j].offset = info->native_size;
152                         info->fields [j].offset += align - 1;
153                         info->fields [j].offset &= ~(align - 1);
154                         info->native_size = info->fields [j].offset + size;
155                         break;
156                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
157                         /* FIXME: */
158                         info->fields [j].offset = klass->fields [i].offset - sizeof (MonoObject);
159                         info->native_size = klass->instance_size - sizeof (MonoObject);
160                         break;
161                 }       
162                 j++;
163         }
164
165         if (info->native_size & (klass->min_align - 1)) {
166                 info->native_size += klass->min_align - 1;
167                 info->native_size &= ~(klass->min_align - 1);
168         }
169
170         return klass->marshal_info;
171 }
172
173 /** 
174  * class_compute_field_layout:
175  * @m: pointer to the metadata.
176  * @class: The class to initialize
177  *
178  * Initializes the class->fields.
179  *
180  * Currently we only support AUTO_LAYOUT, and do not even try to do
181  * a good job at it.  This is temporary to get the code for Paolo.
182  */
183 static void
184 class_compute_field_layout (MonoClass *class)
185 {
186         MonoImage *m = class->image; 
187         const int top = class->field.count;
188         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
189         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
190         int i, blittable = TRUE;
191         guint32 rva;
192         guint32 packing_size = 0;
193
194         if (class->size_inited)
195                 return;
196
197         if (class->parent) {
198                 if (!class->parent->size_inited)
199                         class_compute_field_layout (class->parent);
200                 class->instance_size += class->parent->instance_size;
201                 class->class_size += class->parent->class_size;
202                 class->min_align = class->parent->min_align;
203         } else {
204                 class->instance_size = sizeof (MonoObject);
205                 class->min_align = 1;
206         }
207
208         if (mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &class->instance_size)) {
209                 class->instance_size += sizeof (MonoObject);
210         }
211
212         g_assert ((packing_size & 0xfffffff0) == 0);
213         class->packing_size = packing_size;
214
215         if (!top) {
216                 class->size_inited = 1;
217                 return;
218         }
219
220         class->fields = g_new0 (MonoClassField, top);
221
222         /*
223          * Fetch all the field information.
224          */
225         for (i = 0; i < top; i++){
226                 const char *sig;
227                 guint32 cols [MONO_FIELD_SIZE];
228                 int idx = class->field.first + i;
229                 
230                 mono_metadata_decode_row (t, idx, cols, CSIZE (cols));
231                 /* The name is needed for fieldrefs */
232                 class->fields [i].name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
233                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
234                 mono_metadata_decode_value (sig, &sig);
235                 /* FIELD signature == 0x06 */
236                 g_assert (*sig == 0x06);
237                 class->fields [i].type = mono_metadata_parse_field_type (
238                         m, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
239
240                 if (!(class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)) {
241                         if (class->fields [i].type->byref) {
242                                 blittable = FALSE;
243                         } else {
244                                 MonoClass *field_class = mono_class_from_mono_type (class->fields [i].type);
245                                 if (!field_class->blittable)
246                                         blittable = FALSE;
247                         }
248                 }
249                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
250                         mono_metadata_field_info (m, idx, &class->fields [i].offset, NULL, NULL);
251                         if (class->fields [i].offset == (guint32)-1)
252                                 g_warning ("%s not initialized correctly (missing field layout info for %s)", class->name, class->fields [i].name);
253                 }
254
255                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
256                         mono_metadata_field_info (m, idx, NULL, &rva, NULL);
257                         if (!rva)
258                                 g_warning ("field %s in %s should have RVA data, but hasn't", class->fields [i].name, class->name);
259                         class->fields [i].data = mono_cli_rva_map (class->image->image_info, rva);
260                 }
261
262                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC)) {
263                         class->enum_basetype = class->fields [i].type;
264                         class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
265                         blittable = class->element_class->blittable;
266                 }
267         }
268
269         if (class == mono_defaults.string_class)
270                 blittable = FALSE;
271
272         class->blittable = blittable;
273
274         if (class->enumtype && !class->enum_basetype) {
275                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
276                         G_BREAKPOINT ();
277         }
278         mono_class_layout_fields (class);
279 }
280
281 void
282 mono_class_layout_fields (MonoClass *class)
283 {
284         int i;
285         const int top = class->field.count;
286         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
287
288         /*
289          * Compute field layout and total size (not considering static fields)
290          */
291         switch (layout) {
292         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
293         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
294                 for (i = 0; i < top; i++){
295                         int size, align;
296                         
297                         if (class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
298                                 continue;
299
300                         size = mono_type_size (class->fields [i].type, &align);
301                         
302                         /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
303                         align = class->packing_size ? MIN (class->packing_size, align): align;
304                         class->min_align = MAX (align, class->min_align);
305                         class->fields [i].offset = class->instance_size;
306                         class->fields [i].offset += align - 1;
307                         class->fields [i].offset &= ~(align - 1);
308                         class->instance_size = class->fields [i].offset + size;
309
310                 }
311        
312                 if (class->instance_size & (class->min_align - 1)) {
313                         class->instance_size += class->min_align - 1;
314                         class->instance_size &= ~(class->min_align - 1);
315                 }
316                 break;
317         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
318                 for (i = 0; i < top; i++) {
319                         int size, align;
320
321                         /*
322                          * There must be info about all the fields in a type if it
323                          * uses explicit layout.
324                          */
325
326                         if (class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
327                                 continue;
328
329                         size = mono_type_size (class->fields [i].type, &align);
330                         
331                         /*
332                          * When we get here, class->fields [i].offset is already set by the
333                          * loader (for either runtime fields or fields loaded from metadata).
334                          * The offset is from the start of the object: this works for both
335                          * classes and valuetypes.
336                          */
337                         class->fields [i].offset += sizeof (MonoObject);
338                         /*
339                          * Calc max size.
340                          */
341                         class->instance_size = MAX (class->instance_size, size + class->fields [i].offset);
342                 }
343                 break;
344         }
345
346         class->size_inited = 1;
347
348         /*
349          * Compute static field layout and size
350          */
351         switch (layout) {
352         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
353         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
354                 for (i = 0; i < top; i++){
355                         int size, align;
356                         
357                         if (!(class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC))
358                                 continue;
359                         
360                         size = mono_type_size (class->fields [i].type, &align);
361                         class->fields [i].offset = class->class_size;
362                         class->fields [i].offset += align - 1;
363                         class->fields [i].offset &= ~(align - 1);
364                         class->class_size = class->fields [i].offset + size;
365                 }
366                 break;
367         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
368                 for (i = 0; i < top; i++){
369                         int size, align;
370
371                         /*
372                          * There must be info about all the fields in a type if it
373                          * uses explicit layout.
374                          */
375
376                         
377                         if (!(class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC))
378                                 continue;
379
380                         size = mono_type_size (class->fields [i].type, &align);
381                         class->fields [i].offset = class->class_size;
382                         class->fields [i].offset += align - 1;
383                         class->fields [i].offset &= ~(align - 1);
384                         class->class_size = class->fields [i].offset + size;
385                 }
386                 break;
387         }
388 }
389
390 static void
391 init_properties (MonoClass *class)
392 {
393         guint startm, endm, i, j;
394         guint32 cols [MONO_PROPERTY_SIZE];
395         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_PROPERTY];
396         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
397
398         class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->property.last);
399         class->property.count = class->property.last - class->property.first;
400
401         class->properties = g_new0 (MonoProperty, class->property.count);
402         for (i = class->property.first; i < class->property.last; ++i) {
403                 mono_metadata_decode_row (pt, i, cols, MONO_PROPERTY_SIZE);
404                 class->properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
405                 class->properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
406
407                 startm = mono_metadata_methods_from_property (class->image, i, &endm);
408                 for (j = startm; j < endm; ++j) {
409                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
410                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
411                         case METHOD_SEMANTIC_SETTER:
412                                 class->properties [i - class->property.first].set = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
413                                 break;
414                         case METHOD_SEMANTIC_GETTER:
415                                 class->properties [i - class->property.first].get = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
416                                 break;
417                         default:
418                                 break;
419                         }
420                 }
421         }
422 }
423
424 static void
425 init_events (MonoClass *class)
426 {
427         guint startm, endm, i, j;
428         guint32 cols [MONO_EVENT_SIZE];
429         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_EVENT];
430         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
431
432         class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->event.last);
433         class->event.count = class->event.last - class->event.first;
434
435         class->events = g_new0 (MonoEvent, class->event.count);
436         for (i = class->event.first; i < class->event.last; ++i) {
437                 mono_metadata_decode_row (pt, i, cols, MONO_EVENT_SIZE);
438                 class->events [i - class->event.first].attrs = cols [MONO_EVENT_FLAGS];
439                 class->events [i - class->event.first].name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
440
441                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
442                 for (j = startm; j < endm; ++j) {
443                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
444                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
445                         case METHOD_SEMANTIC_ADD_ON:
446                                 class->events [i - class->event.first].add = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
447                                 break;
448                         case METHOD_SEMANTIC_REMOVE_ON:
449                                 class->events [i - class->event.first].remove = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
450                                 break;
451                         case METHOD_SEMANTIC_FIRE:
452                                 class->events [i - class->event.first].raise = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
453                                 break;
454                         case METHOD_SEMANTIC_OTHER: /* don't care for now */
455                         default:
456                                 break;
457                         }
458                 }
459         }
460 }
461
462 static guint
463 mono_get_unique_iid (MonoClass *class)
464 {
465         static GHashTable *iid_hash = NULL;
466         static guint iid = 0;
467
468         char *str;
469         gpointer value;
470         
471         g_assert (class->flags & TYPE_ATTRIBUTE_INTERFACE);
472
473         if (!iid_hash)
474                 iid_hash = g_hash_table_new (g_str_hash, g_str_equal);
475
476         str = g_strdup_printf ("%s|%s.%s\n", class->image->name, class->name_space, class->name);
477
478         if (g_hash_table_lookup_extended (iid_hash, str, NULL, &value)) {
479                 g_free (str);
480                 return (guint)value;
481         } else {
482                 g_hash_table_insert (iid_hash, str, (gpointer)iid);
483                 ++iid;
484         }
485
486         return iid - 1;
487 }
488
489 void
490 mono_class_setup_vtable (MonoClass *class)
491 {
492         MonoClass *k, *ic;
493         MonoMethod **vtable;
494         int i, onum = 0, max_vtsize = 0, max_iid, cur_slot = 0;
495         MonoMethod **overrides;
496
497         /* setup_vtable() must be called only once on the type */
498         if (class->interface_offsets) {
499                 g_warning ("vtable already computed in %s.%s", class->name_space, class->name);
500                 return;
501         }
502
503         for (i = 0; i < class->interface_count; i++) 
504                 max_vtsize += class->interfaces [i]->method.count;
505         
506         if (class->parent) {
507                 max_vtsize += class->parent->vtable_size;
508                 cur_slot = class->parent->vtable_size;
509         }
510
511         max_vtsize += class->method.count;
512
513         vtable = alloca (sizeof (gpointer) * max_vtsize);
514         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
515
516         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
517
518         /* compute maximum number of slots and maximum interface id */
519         max_iid = 0;
520         for (k = class; k ; k = k->parent) {
521                 for (i = 0; i < k->interface_count; i++) {
522                         ic = k->interfaces [i];
523
524                         if (!ic->inited)
525                                 mono_class_init (ic);
526
527                         if (max_iid < ic->interface_id)
528                                 max_iid = ic->interface_id;
529                 }
530         }
531         
532         class->max_interface_id = max_iid;
533         /* compute vtable offset for interfaces */
534         class->interface_offsets = g_malloc (sizeof (gpointer) * (max_iid + 1));
535
536         for (i = 0; i <= max_iid; i++)
537                 class->interface_offsets [i] = -1;
538
539         for (i = 0; i < class->interface_count; i++) {
540                 ic = class->interfaces [i];
541                 class->interface_offsets [ic->interface_id] = cur_slot;
542                 cur_slot += ic->method.count;
543         }
544
545         for (k = class->parent; k ; k = k->parent) {
546                 for (i = 0; i < k->interface_count; i++) {
547                         ic = k->interfaces [i]; 
548                         if (class->interface_offsets [ic->interface_id] == -1) {
549                                 int io = k->interface_offsets [ic->interface_id];
550
551                                 g_assert (io >= 0);
552                                 g_assert (io <= max_vtsize);
553
554                                 class->interface_offsets [ic->interface_id] = io;
555                         }
556                 }
557         }
558
559         if (class->parent && class->parent->vtable_size)
560                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
561
562         overrides = mono_class_get_overrides (class->image, class->type_token, &onum);
563
564         /* override interface methods */
565         for (i = 0; i < onum; i++) {
566                 MonoMethod *decl = overrides [i*2];
567                 if (decl->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
568                         int dslot;
569                         g_assert (decl->slot != -1);
570                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
571                         vtable [dslot] = overrides [i*2 + 1];
572                 }
573         }
574
575         for (k = class; k ; k = k->parent) {
576                 for (i = 0; i < k->interface_count; i++) {
577                         int j, l, io;
578
579                         ic = k->interfaces [i];
580                         io = k->interface_offsets [ic->interface_id];
581                         
582                         g_assert (io >= 0);
583                         g_assert (io <= max_vtsize);
584
585                         if (k == class) {
586                                 for (l = 0; l < ic->method.count; l++) {
587                                         MonoMethod *im = ic->methods [l];                                               
588                                         for (j = 0; j < class->method.count; ++j) {
589                                                 MonoMethod *cm = class->methods [j];
590                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
591                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC) ||
592                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
593                                                         continue;
594                                                 if (!strcmp(cm->name, im->name) && 
595                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
596                                                         g_assert (io + l <= max_vtsize);
597                                                         vtable [io + l] = cm;
598                                                 }
599                                         }
600                                 }
601                         } else {
602                                 /* already implemented */
603                                 if (io >= k->vtable_size)
604                                         continue;
605                         }
606                                 
607                         for (l = 0; l < ic->method.count; l++) {
608                                 MonoMethod *im = ic->methods [l];                                               
609                                 MonoClass *k1;
610
611                                 g_assert (io + l <= max_vtsize);
612
613                                 if (vtable [io + l])
614                                         continue;
615                                         
616                                 for (k1 = class; k1; k1 = k1->parent) {
617                                         for (j = 0; j < k1->method.count; ++j) {
618                                                 MonoMethod *cm = k1->methods [j];
619
620                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
621                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
622                                                         continue;
623                                                 
624                                                 if (!strcmp(cm->name, im->name) && 
625                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
626                                                         g_assert (io + l <= max_vtsize);
627                                                         vtable [io + l] = cm;
628                                                         break;
629                                                 }
630                                                 
631                                         }
632                                         g_assert (io + l <= max_vtsize);
633                                         if (vtable [io + l])
634                                                 break;
635                                 }
636                         }
637
638                         for (l = 0; l < ic->method.count; l++) {
639                                 MonoMethod *im = ic->methods [l];                                               
640                                 char *qname, *fqname;
641                                 MonoClass *k1;
642                                 
643                                 if (vtable [io + l])
644                                         continue;
645                                         
646                                 qname = g_strconcat (ic->name, ".", im->name, NULL); 
647                                 if (ic->name_space && ic->name_space [0])
648                                         fqname = g_strconcat (ic->name_space, ".", ic->name, ".", im->name, NULL);
649                                 else
650                                         fqname = NULL;
651
652                                 for (k1 = class; k1; k1 = k1->parent) {
653                                         for (j = 0; j < k1->method.count; ++j) {
654                                                 MonoMethod *cm = k1->methods [j];
655
656                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
657                                                         continue;
658                                         
659                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
660                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
661                                                         g_assert (io + l <= max_vtsize);
662                                                         vtable [io + l] = cm;
663                                                         break;
664                                                 }
665                                         }
666                                 }
667                                 g_free (qname);
668                                 g_free (fqname);
669                         }
670
671                         
672                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
673                                 for (l = 0; l < ic->method.count; l++) {
674                                         char *msig;
675                                         MonoMethod *im = ic->methods [l];
676                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
677                                                         continue;
678                                         g_assert (io + l <= max_vtsize);
679                                         if (!(vtable [io + l])) {
680                                                 for (j = 0; j < onum; ++j) {
681                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
682                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
683                                                 }
684                                                 msig = mono_signature_get_desc (im->signature, FALSE);
685                                                 printf ("no implementation for interface method %s.%s::%s(%s) in class %s.%s\n",
686                                                         ic->name_space, ic->name, im->name, msig, class->name_space, class->name);
687                                                 g_free (msig);
688                                                 for (j = 0; j < class->method.count; ++j) {
689                                                         MonoMethod *cm = class->methods [j];
690                                                         msig = mono_signature_get_desc (cm->signature, FALSE);
691                                                         
692                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
693                                                         g_free (msig);
694                                                 }
695                                                 g_assert_not_reached ();
696                                         }
697                                 }
698                         }
699                 
700                         for (l = 0; l < ic->method.count; l++) {
701                                 MonoMethod *im = vtable [io + l];
702
703                                 if (im) {
704                                         g_assert (io + l <= max_vtsize);
705                                         if (im->slot < 0) {
706                                                 /* FIXME: why do we need this ? */
707                                                 im->slot = io + l;
708                                                 /* g_assert_not_reached (); */
709                                         }
710                                 }
711                         }
712                 }
713         } 
714
715         for (i = 0; i < class->method.count; ++i) {
716                 MonoMethod *cm;
717                
718                 cm = class->methods [i];
719
720                 
721 #if 0
722                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
723                     (cm->slot >= 0))
724                         continue;
725 #else  /* EXT_VTABLE_HACK */
726                 if (cm->slot >= 0)
727                         continue;
728 #endif
729
730                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && (cm->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
731                         for (k = class->parent; k ; k = k->parent) {
732                                 int j;
733                                 for (j = 0; j < k->method.count; ++j) {
734                                         MonoMethod *m1 = k->methods [j];
735                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
736                                                 continue;
737                                         if (!strcmp(cm->name, m1->name) && 
738                                             mono_metadata_signature_equal (cm->signature, m1->signature)) {
739                                                 cm->slot = k->methods [j]->slot;
740                                                 g_assert (cm->slot < max_vtsize);
741                                                 break;
742                                         }
743                                 }
744                                 if (cm->slot >= 0) 
745                                         break;
746                         }
747                 }
748
749                 if (cm->slot < 0)
750                         cm->slot = cur_slot++;
751
752                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
753                         vtable [cm->slot] = cm;
754         }
755
756         /* override non interface methods */
757         for (i = 0; i < onum; i++) {
758                 MonoMethod *decl = overrides [i*2];
759                 if (!(decl->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
760                         g_assert (decl->slot != -1);
761                         vtable [decl->slot] = overrides [i*2 + 1];
762                 }
763         }
764        
765         g_free (overrides);
766
767         class->vtable_size = cur_slot;
768         class->vtable = g_malloc0 (sizeof (gpointer) * class->vtable_size);
769         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
770
771         if (mono_print_vtable) {
772                 int icount = 0;
773
774                 for (i = 0; i <= max_iid; i++)
775                         if (class->interface_offsets [i] != -1)
776                                 icount++;
777
778                 printf ("VTable %s.%s (size = %d, interfaces = %d)\n", class->name_space, 
779                         class->name, class->vtable_size, icount); 
780
781                 for (i = 0; i < class->vtable_size; ++i) {
782                         MonoMethod *cm;
783                
784                         cm = vtable [i];
785                         if (cm) {
786                                 printf ("  slot %03d(%03d) %s.%s:%s\n", i, cm->slot,
787                                         cm->klass->name_space, cm->klass->name,
788                                         cm->name);
789                         }
790                 }
791
792
793                 if (icount) {
794                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
795                                 class->name, max_iid);
796         
797                         for (i = 0; i < class->interface_count; i++) {
798                                 ic = class->interfaces [i];
799                                 printf ("  slot %03d(%03d) %s.%s\n",  
800                                         class->interface_offsets [ic->interface_id],
801                                         ic->method.count, ic->name_space, ic->name);
802                         }
803
804                         for (k = class->parent; k ; k = k->parent) {
805                                 for (i = 0; i < k->interface_count; i++) {
806                                         ic = k->interfaces [i]; 
807                                         printf ("  slot %03d(%03d) %s.%s\n", 
808                                                 class->interface_offsets [ic->interface_id],
809                                                 ic->method.count, ic->name_space, ic->name);
810                                 }
811                         }
812                 }
813         }
814
815 }
816
817 /**
818  * mono_class_init:
819  * @class: the class to initialize
820  *
821  * compute the instance_size, class_size and other infos that cannot be 
822  * computed at mono_class_get() time. Also compute a generic vtable and 
823  * the method slot numbers. We use this infos later to create a domain
824  * specific vtable.  
825  */
826 void
827 mono_class_init (MonoClass *class)
828 {
829         int i;
830         static MonoMethod *default_ghc = NULL;
831         static MonoMethod *default_finalize = NULL;
832         static int finalize_slot = -1;
833         static int ghc_slot = -1;
834
835         g_assert (class);
836
837         if (class->inited)
838                 return;
839
840         if (class->init_pending) {
841                 /* this indicates a cyclic dependency */
842                 g_error ("pending init %s.%s\n", class->name_space, class->name);
843         }
844
845         class->init_pending = 1;
846
847         mono_stats.initialized_class_count++;
848
849         if (class->parent && !class->parent->inited)
850                 mono_class_init (class->parent);
851
852         /*
853          * Computes the size used by the fields, and their locations
854          */
855         if (!class->size_inited)
856                 class_compute_field_layout (class);
857
858         /* initialize method pointers */
859         class->methods = g_new (MonoMethod*, class->method.count);
860         for (i = 0; i < class->method.count; ++i)
861                 class->methods [i] = mono_get_method (class->image,
862                         MONO_TOKEN_METHOD_DEF | (i + class->method.first + 1), class);
863
864         init_properties (class);
865         init_events (class);
866
867         i = mono_metadata_nesting_typedef (class->image, class->type_token);
868         while (i) {
869                 MonoClass* nclass;
870                 guint32 cols [MONO_NESTED_CLASS_SIZE];
871                 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
872                 if (cols [MONO_NESTED_CLASS_ENCLOSING] != mono_metadata_token_index (class->type_token))
873                         break;
874                 nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
875                 class->nested_classes = g_list_prepend (class->nested_classes, nclass);
876                 ++i;
877         }
878
879         if (class->flags & TYPE_ATTRIBUTE_INTERFACE) {
880                 for (i = 0; i < class->method.count; ++i)
881                         class->methods [i]->slot = i;
882                 class->init_pending = 0;
883                 class->inited = 1;
884                 return;
885         }
886
887         mono_class_setup_vtable (class);
888
889         class->inited = 1;
890         class->init_pending = 0;
891
892         if (!default_ghc) {
893                 if (class == mono_defaults.object_class) { 
894                        
895                         for (i = 0; i < class->vtable_size; ++i) {
896                                 MonoMethod *cm = class->vtable [i];
897                
898                                 if (!strcmp (cm->name, "GetHashCode")) {
899                                         ghc_slot = i;
900                                         break;
901                                 }
902                         }
903
904                         g_assert (ghc_slot > 0);
905
906                         default_ghc = class->vtable [ghc_slot];
907                 }
908         }
909         
910         class->ghcimpl = 1;
911         if (class->parent) { 
912
913                 if (class->vtable [ghc_slot] == default_ghc) {
914                         class->ghcimpl = 0;
915                 }
916         }
917
918         if (!default_finalize) {
919                 if (class == mono_defaults.object_class) { 
920                        
921                         for (i = 0; i < class->vtable_size; ++i) {
922                                 MonoMethod *cm = class->vtable [i];
923                
924                                 if (!strcmp (cm->name, "Finalize")) {
925                                         finalize_slot = i;
926                                         break;
927                                 }
928                         }
929
930                         g_assert (finalize_slot > 0);
931
932                         default_finalize = class->vtable [finalize_slot];
933                 }
934         }
935
936         /* Object::Finalize should have empty implemenatation */
937         class->has_finalize = 0;
938         if (class->parent) { 
939                 if (class->vtable [finalize_slot] != default_finalize)
940                         class->has_finalize = 1;
941         }
942
943         if (mono_debugger_class_init_func)
944                 mono_debugger_class_init_func (class);
945 }
946
947
948 /*
949  * Compute a relative numbering of the class hierarchy as described in
950  * "Java for Large-Scale Scientific Computations?"
951  */
952 static void
953 mono_compute_relative_numbering (MonoClass *class, int *c)
954 {
955         GList *s;
956
957         (*c)++;
958
959         class->baseval = *c;
960
961         for (s = class->subclasses; s; s = s->next)
962                 mono_compute_relative_numbering ((MonoClass *)s->data, c); 
963         
964         class->diffval = *c -  class->baseval;
965 }
966
967 void
968 mono_class_setup_mono_type (MonoClass *class)
969 {
970         const char *name = class->name;
971         const char *nspace = class->name_space;
972
973         if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
974                 class->interface_id = mono_get_unique_iid (class);
975
976         class->this_arg.byref = 1;
977         class->this_arg.data.klass = class;
978         class->this_arg.type = MONO_TYPE_CLASS;
979         class->byval_arg.data.klass = class;
980         class->byval_arg.type = MONO_TYPE_CLASS;
981
982         if (!strcmp (nspace, "System")) {
983                 if (!strcmp (name, "ValueType")) {
984                         /*
985                          * do not set the valuetype bit for System.ValueType.
986                          * class->valuetype = 1;
987                          */
988                 } else if (!strcmp (name, "Enum")) {
989                         /*
990                          * do not set the valuetype bit for System.Enum.
991                          * class->valuetype = 1;
992                          */
993                         class->valuetype = 0;
994                         class->enumtype = 0;
995                 } else if (!strcmp (name, "Object")) {
996                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
997                 } else if (!strcmp (name, "String")) {
998                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
999                 }
1000         }
1001         
1002         if (class->valuetype) {
1003                 int t = MONO_TYPE_VALUETYPE;
1004                 if (!strcmp (nspace, "System")) {
1005                         switch (*name) {
1006                         case 'B':
1007                                 if (!strcmp (name, "Boolean")) {
1008                                         t = MONO_TYPE_BOOLEAN;
1009                                 } else if (!strcmp(name, "Byte")) {
1010                                         t = MONO_TYPE_U1;
1011                                         class->blittable = TRUE;                                                
1012                                 }
1013                                 break;
1014                         case 'C':
1015                                 if (!strcmp (name, "Char")) {
1016                                         t = MONO_TYPE_CHAR;
1017                                 }
1018                                 break;
1019                         case 'D':
1020                                 if (!strcmp (name, "Double")) {
1021                                         t = MONO_TYPE_R8;
1022                                         class->blittable = TRUE;                                                
1023                                 }
1024                                 break;
1025                         case 'I':
1026                                 if (!strcmp (name, "Int32")) {
1027                                         t = MONO_TYPE_I4;
1028                                         class->blittable = TRUE;
1029                                 } else if (!strcmp(name, "Int16")) {
1030                                         t = MONO_TYPE_I2;
1031                                         class->blittable = TRUE;
1032                                 } else if (!strcmp(name, "Int64")) {
1033                                         t = MONO_TYPE_I8;
1034                                         class->blittable = TRUE;
1035                                 } else if (!strcmp(name, "IntPtr")) {
1036                                         t = MONO_TYPE_I;
1037                                         class->blittable = TRUE;
1038                                 }
1039                                 break;
1040                         case 'S':
1041                                 if (!strcmp (name, "Single")) {
1042                                         t = MONO_TYPE_R4;
1043                                         class->blittable = TRUE;                                                
1044                                 } else if (!strcmp(name, "SByte")) {
1045                                         t = MONO_TYPE_I1;
1046                                         class->blittable = TRUE;
1047                                 }
1048                                 break;
1049                         case 'U':
1050                                 if (!strcmp (name, "UInt32")) {
1051                                         t = MONO_TYPE_U4;
1052                                         class->blittable = TRUE;
1053                                 } else if (!strcmp(name, "UInt16")) {
1054                                         t = MONO_TYPE_U2;
1055                                         class->blittable = TRUE;
1056                                 } else if (!strcmp(name, "UInt64")) {
1057                                         t = MONO_TYPE_U8;
1058                                         class->blittable = TRUE;
1059                                 } else if (!strcmp(name, "UIntPtr")) {
1060                                         t = MONO_TYPE_U;
1061                                         class->blittable = TRUE;
1062                                 }
1063                                 break;
1064                         case 'V':
1065                                 if (!strcmp (name, "Void")) {
1066                                         t = MONO_TYPE_VOID;
1067                                 }
1068                                 break;
1069                         default:
1070                                 break;
1071                         }
1072                 }
1073                 class->this_arg.type = class->byval_arg.type = t;
1074         }
1075 }
1076
1077 void
1078 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
1079 {
1080         gboolean system_namespace;
1081
1082         system_namespace = !strcmp (class->name_space, "System");
1083
1084         /* if root of the hierarchy */
1085         if (system_namespace && !strcmp (class->name, "Object")) {
1086                 class->parent = NULL;
1087                 class->instance_size = sizeof (MonoObject);
1088                 return;
1089         }
1090         if (!strcmp (class->name, "<Module>")) {
1091                 class->parent = NULL;
1092                 class->instance_size = 0;
1093                 return;
1094         }
1095
1096         if (!(class->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1097                 int rnum = 0;
1098                 class->parent = parent;
1099
1100                 if (!parent)
1101                         g_assert_not_reached (); /* FIXME */
1102
1103                 class->marshalbyref = parent->marshalbyref;
1104                 class->contextbound  = parent->contextbound;
1105                 class->delegate  = parent->delegate;
1106                 
1107                 if (system_namespace) {
1108                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
1109                                 class->marshalbyref = 1;
1110
1111                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
1112                                 class->contextbound  = 1;
1113
1114                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
1115                                 class->delegate  = 1;
1116                 }
1117
1118                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
1119                                                 (strcmp (class->parent->name_space, "System") == 0)))
1120                         class->valuetype = 1;
1121                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
1122                         class->valuetype = class->enumtype = 1;
1123                 }
1124                 /*class->enumtype = class->parent->enumtype; */
1125                 class->parent->subclasses = g_list_prepend (class->parent->subclasses, class);
1126                 mono_compute_relative_numbering (mono_defaults.object_class, &rnum);
1127         } else {
1128                 class->parent = NULL;
1129         }
1130
1131 }
1132
1133 /**
1134  * @image: context where the image is created
1135  * @type_token:  typedef token
1136  */
1137 static MonoClass *
1138 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
1139 {
1140         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
1141         MonoClass *class, *parent = NULL;
1142         guint32 cols [MONO_TYPEDEF_SIZE];
1143         guint32 cols_next [MONO_TYPEDEF_SIZE];
1144         guint tidx = mono_metadata_token_index (type_token);
1145         const char *name, *nspace;
1146         guint icount = 0; 
1147         MonoClass **interfaces;
1148
1149         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) 
1150                 return class;
1151
1152         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
1153         
1154         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
1155         
1156         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1157         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1158
1159         if (cols [MONO_TYPEDEF_EXTENDS])
1160                 parent = mono_class_get (image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]));
1161         interfaces = mono_metadata_interfaces_from_typedef (image, type_token, &icount);
1162
1163         class = g_malloc0 (sizeof (MonoClass));
1164                            
1165         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
1166
1167         class->interfaces = interfaces;
1168         class->interface_count = icount;
1169
1170         class->name = name;
1171         class->name_space = nspace;
1172
1173         class->image = image;
1174         class->type_token = type_token;
1175         class->flags = cols [MONO_TYPEDEF_FLAGS];
1176
1177         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
1178                 class->unicode = 1;
1179         /* fixme: maybe we must set this on windows 
1180         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
1181                 class->unicode = 1;
1182         */
1183
1184         class->cast_class = class->element_class = class;
1185
1186         /*g_print ("Init class %s\n", name);*/
1187
1188         mono_class_setup_parent (class, parent);
1189
1190         mono_class_setup_mono_type (class);
1191
1192         /*
1193          * Compute the field and method lists
1194          */
1195         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
1196         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
1197
1198         if (tt->rows > tidx){           
1199                 mono_metadata_decode_row (tt, tidx, cols_next, CSIZE (cols_next));
1200                 class->field.last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1201                 class->method.last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1202         } else {
1203                 class->field.last  = image->tables [MONO_TABLE_FIELD].rows;
1204                 class->method.last = image->tables [MONO_TABLE_METHOD].rows;
1205         }
1206
1207         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
1208             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
1209                 class->field.count = class->field.last - class->field.first;
1210         else
1211                 class->field.count = 0;
1212
1213         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
1214                 class->method.count = class->method.last - class->method.first;
1215         else
1216                 class->method.count = 0;
1217
1218         /* reserve space to store vector pointer in arrays */
1219         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
1220                 class->instance_size += 2 * sizeof (gpointer);
1221                 g_assert (class->field.count == 0);
1222         }
1223
1224         if (class->enumtype)
1225                 class_compute_field_layout (class);
1226
1227         if ((type_token = mono_metadata_nested_in_typedef (image, type_token)))
1228                 class->nested_in = mono_class_create_from_typedef (image, type_token);
1229
1230         return class;
1231 }
1232
1233 MonoClass *
1234 mono_ptr_class_get (MonoType *type)
1235 {
1236         MonoClass *result;
1237         MonoClass *el_class;
1238         static GHashTable *ptr_hash = NULL;
1239
1240         if (!ptr_hash)
1241                 ptr_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
1242         el_class = mono_class_from_mono_type (type);
1243         if ((result = g_hash_table_lookup (ptr_hash, el_class)))
1244                 return result;
1245         result = g_new0 (MonoClass, 1);
1246
1247         result->parent = NULL; /* no parent for PTR types */
1248         result->name = "System";
1249         result->name_space = "MonoPtrFakeClass";
1250         result->image = el_class->image;
1251         result->inited = TRUE;
1252         /* Can pointers get boxed? */
1253         result->instance_size = sizeof (gpointer);
1254         /*
1255          * baseval, diffval: need them to allow casting ?
1256          */
1257         result->cast_class = result->element_class = el_class;
1258         result->enum_basetype = &result->element_class->byval_arg;
1259
1260         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
1261         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
1262         result->this_arg.byref = TRUE;
1263
1264         g_hash_table_insert (ptr_hash, el_class, result);
1265
1266         return result;
1267 }
1268
1269 MonoClass *
1270 mono_class_from_mono_type (MonoType *type)
1271 {
1272         switch (type->type) {
1273         case MONO_TYPE_OBJECT:
1274                 return mono_defaults.object_class;
1275         case MONO_TYPE_VOID:
1276                 return mono_defaults.void_class;
1277         case MONO_TYPE_BOOLEAN:
1278                 return mono_defaults.boolean_class;
1279         case MONO_TYPE_CHAR:
1280                 return mono_defaults.char_class;
1281         case MONO_TYPE_I1:
1282                 return mono_defaults.sbyte_class;
1283         case MONO_TYPE_U1:
1284                 return mono_defaults.byte_class;
1285         case MONO_TYPE_I2:
1286                 return mono_defaults.int16_class;
1287         case MONO_TYPE_U2:
1288                 return mono_defaults.uint16_class;
1289         case MONO_TYPE_I4:
1290                 return mono_defaults.int32_class;
1291         case MONO_TYPE_U4:
1292                 return mono_defaults.uint32_class;
1293         case MONO_TYPE_I:
1294                 return mono_defaults.int_class;
1295         case MONO_TYPE_U:
1296                 return mono_defaults.uint_class;
1297         case MONO_TYPE_I8:
1298                 return mono_defaults.int64_class;
1299         case MONO_TYPE_U8:
1300                 return mono_defaults.uint64_class;
1301         case MONO_TYPE_R4:
1302                 return mono_defaults.single_class;
1303         case MONO_TYPE_R8:
1304                 return mono_defaults.double_class;
1305         case MONO_TYPE_STRING:
1306                 return mono_defaults.string_class;
1307         case MONO_TYPE_ARRAY:
1308                 return mono_array_class_get (type->data.array->type, type->data.array->rank);
1309         case MONO_TYPE_PTR:
1310                 return mono_ptr_class_get (type->data.type);
1311         case MONO_TYPE_SZARRAY:
1312                 return mono_array_class_get (type->data.type, 1);
1313         case MONO_TYPE_CLASS:
1314         case MONO_TYPE_VALUETYPE:
1315                 return type->data.klass;
1316         default:
1317                 g_warning ("implement me %02x\n", type->type);
1318                 g_assert_not_reached ();
1319         }
1320         
1321         return NULL;
1322 }
1323
1324 /**
1325  * @image: context where the image is created
1326  * @type_spec:  typespec token
1327  */
1328 static MonoClass *
1329 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec)
1330 {
1331         MonoType *type;
1332         MonoClass *class;
1333
1334         type = mono_type_create_from_typespec (image, type_spec);
1335
1336         switch (type->type) {
1337         case MONO_TYPE_ARRAY:
1338                 class = mono_array_class_get (type->data.array->type, type->data.array->rank);
1339                 break;
1340         case MONO_TYPE_SZARRAY:
1341                 class = mono_array_class_get (type->data.type, 1);
1342                 break;
1343         case MONO_TYPE_PTR:
1344                 class = mono_class_from_mono_type (type->data.type);
1345                 break;
1346         default:
1347                 /* it seems any type can be stored in TypeSpec as well */
1348                 class = mono_class_from_mono_type (type);
1349                 break;
1350         }
1351
1352         mono_metadata_free_type (type);
1353         
1354         return class;
1355 }
1356
1357 /**
1358  * mono_array_class_get:
1359  * @element_type: element type 
1360  * @rank: the dimension of the array class
1361  *
1362  * Returns: a class object describing the array with element type @element_type and 
1363  * dimension @rank. 
1364  */
1365 MonoClass *
1366 mono_array_class_get (MonoType *element_type, guint32 rank)
1367 {
1368         MonoClass *eclass;
1369         MonoImage *image;
1370         MonoClass *class;
1371         MonoClass *parent = NULL;
1372         GSList *list;
1373         int rnum = 0, nsize;
1374         char *name;
1375
1376         eclass = mono_class_from_mono_type (element_type);
1377         g_assert (rank <= 255);
1378
1379         parent = mono_defaults.array_class;
1380
1381         if (!parent->inited)
1382                 mono_class_init (parent);
1383
1384         image = eclass->image;
1385
1386         if ((list = g_hash_table_lookup (image->array_cache, element_type))) {
1387                 for (; list; list = list->next) {
1388                         class = list->data;
1389                         if (class->rank == rank)
1390                                 return class;
1391                 }
1392         }
1393         
1394         class = g_malloc0 (sizeof (MonoClass) + parent->vtable_size * sizeof (gpointer));
1395
1396         class->image = image;
1397         class->name_space = eclass->name_space;
1398         nsize = strlen (eclass->name);
1399         name = g_malloc (nsize + 2 + rank);
1400         memcpy (name, eclass->name, nsize);
1401         name [nsize] = '[';
1402         if (rank > 1)
1403                 memset (name + nsize + 1, ',', rank - 1);
1404         name [nsize + rank] = ']';
1405         name [nsize + rank + 1] = 0;
1406         class->name = name;
1407         class->type_token = 0;
1408         class->flags = TYPE_ATTRIBUTE_CLASS;
1409         class->parent = parent;
1410         class->instance_size = mono_class_instance_size (class->parent);
1411         class->class_size = 0;
1412         class->vtable_size = parent->vtable_size;
1413         class->parent->subclasses = g_list_prepend (class->parent->subclasses, class);
1414         mono_compute_relative_numbering (mono_defaults.object_class, &rnum);
1415
1416         class->rank = rank;
1417         
1418         if (eclass->enumtype)
1419                 class->cast_class = eclass->element_class;
1420         else
1421                 class->cast_class = eclass;
1422
1423         class->element_class = eclass;
1424         
1425         if (rank > 1) {
1426                 MonoArrayType *at = g_new0 (MonoArrayType, 1);
1427                 class->byval_arg.type = MONO_TYPE_ARRAY;
1428                 class->byval_arg.data.array = at;
1429                 at->type = &eclass->byval_arg;
1430                 at->rank = rank;
1431                 /* FIXME: complete.... */
1432         } else {
1433                 /* FIXME: this is not correct. the lbound could be >0 */
1434                 class->byval_arg.type = MONO_TYPE_SZARRAY;
1435                 class->byval_arg.data.type = &eclass->byval_arg;
1436         }
1437         class->this_arg = class->byval_arg;
1438         class->this_arg.byref = 1;
1439
1440         list = g_slist_append (list, class);
1441         g_hash_table_insert (image->array_cache, &class->element_class->byval_arg, list);
1442         return class;
1443 }
1444
1445 /**
1446  * mono_class_instance_size:
1447  * @klass: a class 
1448  * 
1449  * Returns: the size of an object instance
1450  */
1451 gint32
1452 mono_class_instance_size (MonoClass *klass)
1453 {
1454         
1455         if (!klass->size_inited)
1456                 mono_class_init (klass);
1457
1458         return klass->instance_size;
1459 }
1460
1461 /**
1462  * mono_class_native_size:
1463  * @klass: a class 
1464  * 
1465  * Returns: the native size of an object instance (when marshaled 
1466  * to unmanaged code) 
1467  */
1468 gint32
1469 mono_class_native_size (MonoClass *klass, guint32 *align)
1470 {
1471         
1472         if (!klass->marshal_info)
1473                 mono_marshal_load_type_info (klass);
1474
1475         if (align)
1476                 *align = klass->min_align;
1477
1478         return klass->marshal_info->native_size;
1479 }
1480
1481 /**
1482  * mono_class_min_align:
1483  * @klass: a class 
1484  * 
1485  * Returns: minimm alignment requirements 
1486  */
1487 gint32
1488 mono_class_min_align (MonoClass *klass)
1489 {
1490         
1491         if (!klass->size_inited)
1492                 mono_class_init (klass);
1493
1494         return klass->min_align;
1495 }
1496
1497 /**
1498  * mono_class_value_size:
1499  * @klass: a class 
1500  *
1501  * This function is used for value types, and return the
1502  * space and the alignment to store that kind of value object.
1503  *
1504  * Returns: the size of a value of kind @klass
1505  */
1506 gint32
1507 mono_class_value_size      (MonoClass *klass, guint32 *align)
1508 {
1509         gint32 size;
1510
1511         /* fixme: check disable, because we still have external revereces to
1512          * mscorlib and Dummy Objects 
1513          */
1514         /*g_assert (klass->valuetype);*/
1515
1516         size = mono_class_instance_size (klass) - sizeof (MonoObject);
1517
1518         if (align)
1519                 *align = klass->min_align;
1520
1521         return size;
1522 }
1523
1524 /**
1525  * mono_class_data_size:
1526  * @klass: a class 
1527  * 
1528  * Returns: the size of the static class data
1529  */
1530 gint32
1531 mono_class_data_size (MonoClass *klass)
1532 {
1533         
1534         if (!klass->inited)
1535                 mono_class_init (klass);
1536
1537         return klass->class_size;
1538 }
1539
1540 /*
1541  * Auxiliary routine to mono_class_get_field
1542  *
1543  * Takes a field index instead of a field token.
1544  */
1545 static MonoClassField *
1546 mono_class_get_field_idx (MonoClass *class, int idx)
1547 {
1548         if (class->field.count){
1549                 if ((idx >= class->field.first) && (idx < class->field.last)){
1550                         return &class->fields [idx - class->field.first];
1551                 }
1552         }
1553
1554         if (!class->parent)
1555                 return NULL;
1556         
1557         return mono_class_get_field_idx (class->parent, idx);
1558 }
1559
1560 /**
1561  * mono_class_get_field:
1562  * @class: the class to lookup the field.
1563  * @field_token: the field token
1564  *
1565  * Returns: A MonoClassField representing the type and offset of
1566  * the field, or a NULL value if the field does not belong to this
1567  * class.
1568  */
1569 MonoClassField *
1570 mono_class_get_field (MonoClass *class, guint32 field_token)
1571 {
1572         int idx = mono_metadata_token_index (field_token);
1573
1574         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
1575
1576         return mono_class_get_field_idx (class, idx - 1);
1577 }
1578
1579 MonoClassField *
1580 mono_class_get_field_from_name (MonoClass *klass, const char *name)
1581 {
1582         int i;
1583
1584         while (klass) {
1585                 for (i = 0; i < klass->field.count; ++i) {
1586                         if (strcmp (name, klass->fields [i].name) == 0)
1587                                 return &klass->fields [i];
1588                 }
1589                 klass = klass->parent;
1590         }
1591         return NULL;
1592 }
1593
1594 MonoProperty*
1595 mono_class_get_property_from_name (MonoClass *klass, const char *name)
1596 {
1597         int i;
1598
1599         while (klass) {
1600                 for (i = 0; i < klass->property.count; ++i) {
1601                         if (strcmp (name, klass->properties [i].name) == 0)
1602                                 return &klass->properties [i];
1603                 }
1604                 klass = klass->parent;
1605         }
1606         return NULL;
1607 }
1608
1609 /**
1610  * mono_class_get:
1611  * @image: the image where the class resides
1612  * @type_token: the token for the class
1613  * @at: an optional pointer to return the array element type
1614  *
1615  * Returns: the MonoClass that represents @type_token in @image
1616  */
1617 MonoClass *
1618 mono_class_get (MonoImage *image, guint32 type_token)
1619 {
1620         MonoClass *class;
1621
1622         if (image->assembly->dynamic) {
1623                 MonoDynamicAssembly *assembly = image->assembly->dynamic;
1624                 MonoObject *obj;
1625
1626                 obj = g_hash_table_lookup (assembly->tokens, 
1627                                                                   GUINT_TO_POINTER (type_token));
1628                 g_assert (obj);
1629                 if (obj->vtable->klass == mono_defaults.monotype_class) {
1630                         MonoReflectionType *tb = (MonoReflectionType*)obj;
1631                         class = tb->type->data.klass;
1632                         g_assert (class);
1633                         return class;
1634                 }
1635                 else
1636                         printf("KLASS: %s.\n", obj->vtable->klass->name);
1637         }
1638
1639         switch (type_token & 0xff000000){
1640         case MONO_TOKEN_TYPE_DEF:
1641                 class = mono_class_create_from_typedef (image, type_token);
1642                 break;          
1643         case MONO_TOKEN_TYPE_REF:
1644                 class = mono_class_from_typeref (image, type_token);
1645                 break;
1646         case MONO_TOKEN_TYPE_SPEC:
1647                 class = mono_class_create_from_typespec (image, type_token);
1648                 break;
1649         default:
1650                 g_warning ("unknown token type %x", type_token & 0xff000000);
1651                 g_assert_not_reached ();
1652         }
1653
1654         if (!class)
1655                 g_warning ("Could not load class from token 0x%08x in %s", type_token, image->name);
1656
1657         return class;
1658 }
1659
1660 MonoClass *
1661 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
1662 {
1663         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
1664         guint32 cols [MONO_TYPEDEF_SIZE];
1665         const char *n;
1666         const char *nspace;
1667         guint32 i, visib;
1668
1669         /* add a cache if needed */
1670         for (i = 1; i <= t->rows; ++i) {
1671                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
1672                 /* nested types are accessed from the nesting name */
1673                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
1674                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
1675                         continue;
1676                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1677                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1678                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
1679                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
1680         }
1681         return NULL;
1682 }
1683
1684 MonoClass *
1685 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
1686 {
1687         GHashTable *nspace_table;
1688         guint32 token;
1689
1690         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
1691         if (!nspace_table)
1692                 return 0;
1693         token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
1694         
1695         if (!token) {
1696                 /*g_warning ("token not found for %s.%s in image %s", name_space, name, image->name);*/
1697                 return NULL;
1698         }
1699
1700         token = MONO_TOKEN_TYPE_DEF | token;
1701
1702         return mono_class_get (image, token);
1703 }
1704
1705 /*
1706  * Returns the nnumber of bytes an element of type klass
1707  * uses when stored into an array.
1708  */
1709 gint32
1710 mono_class_array_element_size (MonoClass *klass)
1711 {
1712         int t = klass->byval_arg.type;
1713         
1714 handle_enum:
1715         switch (t) {
1716         case MONO_TYPE_I1:
1717         case MONO_TYPE_U1:
1718         case MONO_TYPE_BOOLEAN:
1719                 return 1;
1720         case MONO_TYPE_I2:
1721         case MONO_TYPE_U2:
1722         case MONO_TYPE_CHAR:
1723                 return 2;
1724         case MONO_TYPE_I4:
1725         case MONO_TYPE_U4:
1726         case MONO_TYPE_R4:
1727                 return 4;
1728         case MONO_TYPE_I:
1729         case MONO_TYPE_U:
1730         case MONO_TYPE_PTR:
1731         case MONO_TYPE_CLASS:
1732         case MONO_TYPE_STRING:
1733         case MONO_TYPE_OBJECT:
1734         case MONO_TYPE_SZARRAY:
1735         case MONO_TYPE_ARRAY:    
1736                 return sizeof (gpointer);
1737         case MONO_TYPE_I8:
1738         case MONO_TYPE_U8:
1739         case MONO_TYPE_R8:
1740                 return 8;
1741         case MONO_TYPE_VALUETYPE:
1742                 if (klass->enumtype) {
1743                         t = klass->enum_basetype->type;
1744                         goto handle_enum;
1745                 }
1746                 return mono_class_instance_size (klass) - sizeof (MonoObject);
1747         default:
1748                 g_error ("unknown type 0x%02x in mono_class_array_element_size", t);
1749         }
1750         return -1;
1751 }
1752
1753 /**
1754  * mono_array_element_size:
1755  * @ac: pointer to a #MonoArrayClass
1756  *
1757  * Returns: the size of single array element.
1758  */
1759 gint32
1760 mono_array_element_size (MonoClass *ac)
1761 {
1762         return mono_class_array_element_size (ac->element_class);
1763 }
1764
1765 gpointer
1766 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class)
1767 {
1768         switch (token & 0xff000000) {
1769         case MONO_TOKEN_TYPE_DEF:
1770         case MONO_TOKEN_TYPE_REF: {
1771                 MonoClass *class;
1772                 if (handle_class)
1773                         *handle_class = mono_defaults.typehandle_class;
1774                 class = mono_class_get (image, token);
1775                 mono_class_init (class);
1776                 /* We return a MonoType* as handle */
1777                 return &class->byval_arg;
1778         }
1779         case MONO_TOKEN_TYPE_SPEC: {
1780                 MonoClass *class;
1781                 if (handle_class)
1782                         *handle_class = mono_defaults.typehandle_class;
1783                 class = mono_class_create_from_typespec (image, token);
1784                 mono_class_init (class);
1785                 return &class->byval_arg;
1786         }
1787         case MONO_TOKEN_FIELD_DEF: {
1788                 MonoClass *class;
1789                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
1790                 class = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1791                 mono_class_init (class);
1792                 if (handle_class)
1793                                 *handle_class = mono_class_from_name (mono_defaults.corlib, "System", "RuntimeFieldHandle");
1794                 return mono_class_get_field (class, token);
1795         }
1796         case MONO_TOKEN_METHOD_DEF:
1797         case MONO_TOKEN_MEMBER_REF:
1798         default:
1799                 g_warning ("Unknown token 0x%08x in ldtoken", token);
1800                 break;
1801         }
1802         return NULL;
1803 }
1804