Some changes.
[cacao.git] / doc / handbook / loader.tex
1 \chapter{Class Loader}
2
3
4 \section{Introduction}
5
6 A \textit{Java Virtual Machine} (JVM) dynamically loads, links and
7 initializes classes and interfaces when they are needed. Loading a
8 class or interface means locating the binary representation---the
9 class files---and creating a class of interface structure from that
10 binary representation. Linking takes a loaded class or interface and
11 transfers it into the runtime state of the \textit{Java Virtual
12 Machine} so that it can be executed. Initialization of a class or
13 interface means executing the static class of interface initializer
14 \texttt{<clinit>}.
15
16 The following sections describe the process of loading, linking and
17 initalizing a class or interface in the CACAO \textit{Java Virtual
18 Machine} in greater detail. Further the used data structures and
19 techniques used in CACAO and the interaction with the GNU classpath
20 are described.
21
22
23 \section{System class loader}
24 \label{sectionsystemclassloader}
25
26 The class loader of a \textit{Java Virtual Machine} (JVM) is
27 responsible for loading all type of classes and interfaces into the
28 runtime system of the JVM. Every JVM has a \textit{system class
29 loader} which is implemented in \texttt{java.lang.ClassLoader} and
30 this class interacts via native function calls with the JVM itself.
31
32 \begingroup
33 \tolerance 10000
34 The \textit{GNU classpath} implements the system class loader in
35 \texttt{gnu.java.lang.SystemClassLoader} which extends
36 \texttt{java.lang.ClassLoader} and interacts with the JVM. The
37 \textit{bootstrap class loader} is implemented in
38 \texttt{java.lang.ClassLoader} plus the JVM depended class
39 \texttt{java.lang.VMClassLoader}. \texttt{java.lang.VMClassLoader} is
40 the main class how the bootstrap class loader of the GNU classpath
41 interacts with the JVM. The main functions of this class is
42
43 \endgroup
44
45 \begin{verbatim}
46         static final native Class loadClass(String name, boolean resolve)
47           throws ClassNotFoundException;
48 \end{verbatim}
49
50 \begingroup
51 \tolerance 10000
52 This is a native function implemented in the CACAO JVM, which is
53 located in \texttt{nat/VMClassLoader.c} and calls the internal loader
54 functions of CACAO. If the \texttt{name} argument is \texttt{NULL}, a
55 new \texttt{java.lang.NullPointerException} is created and the
56 function returns \texttt{NULL}.
57
58 \endgroup
59
60 If the \texttt{name} is non-NULL a new UTF8 string of the class' name
61 is created in the internal \textit{symbol table} via
62
63 \begin{verbatim}
64         utf *javastring_toutf(java_lang_String *string, bool isclassname);
65 \end{verbatim}
66
67 This function converts a \texttt{java.lang.String} string into the
68 internal used UTF8 string representation. \texttt{isclassname} tells
69 the function to convert any \texttt{.} (periods) found in the class
70 name into \texttt{/} (slashes), so the class loader can find the
71 specified class.
72
73 Then a new \texttt{classinfo} structure is created via the
74
75 \begin{verbatim}
76         classinfo *class_new(utf *classname);
77 \end{verbatim}
78
79 function call. This function creates a unique representation of this
80 class, identified by its name, in the JVM's internal \textit{class
81 hashtable}. The newly created \texttt{classinfo} structure (see
82 figure~\ref{classinfostructure}) is initialized with correct values,
83 like \texttt{loaded = false;}, \texttt{linked = false;} and
84 \texttt{initialized = false;}. This guarantees a definite state of a
85 new class.
86
87 \begin{figure}
88 \begin{verbatim}
89     struct classinfo {                /* class structure                          */
90         ...
91         s4          flags;            /* ACC flags                                */
92         utf        *name;             /* class name                               */
93
94         s4          cpcount;          /* number of entries in constant pool       */
95         u1         *cptags;           /* constant pool tags                       */
96         voidptr    *cpinfos;          /* pointer to constant pool info structures */
97
98         classinfo  *super;            /* super class pointer                      */
99         classinfo  *sub;              /* sub class pointer                        */
100         classinfo  *nextsub;          /* pointer to next class in sub class list  */
101
102         s4          interfacescount;  /* number of interfaces                     */
103         classinfo **interfaces;       /* pointer to interfaces                    */
104
105         s4          fieldscount;      /* number of fields                         */
106         fieldinfo  *fields;           /* field table                              */
107
108         s4          methodscount;     /* number of methods                        */
109         methodinfo *methods;          /* method table                             */
110         ...
111         bool        initialized;      /* true, if class already initialized       */
112         bool        initializing;     /* flag for the compiler                    */
113         bool        loaded;           /* true, if class already loaded            */
114         bool        linked;           /* true, if class already linked            */
115         s4          index;            /* hierarchy depth (classes) or index       */
116                                       /* (interfaces)                             */
117         s4          instancesize;     /* size of an instance of this class        */
118     #ifdef SIZE_FROM_CLASSINFO
119         s4          alignedsize;      /* size of an instance, aligned to the      */
120                                       /* allocation size on the heap              */
121     #endif
122
123         vftbl_t    *vftbl;            /* pointer to virtual function table        */
124
125         methodinfo *finalizer;        /* finalizer method                         */
126
127         u2          innerclasscount;  /* number of inner classes                  */
128         innerclassinfo *innerclass;
129         ...
130         utf        *packagename;      /* full name of the package                 */
131         utf        *sourcefile;       /* classfile name containing this class     */
132         java_objectheader *classloader; /* NULL for bootstrap classloader         */
133     };
134 \end{verbatim}
135 \caption{\texttt{classinfo} structure}
136 \label{classinfostructure}
137 \end{figure}
138
139 The next step is to actually load the class requested. Thus the main
140 loader function
141
142 \begin{verbatim}
143         classinfo *class_load(classinfo *c);
144 \end{verbatim}
145
146 is called, which is a wrapper function to the real loader function
147
148 \begin{verbatim}
149         classinfo *class_load_intern(classbuffer *cb);
150 \end{verbatim}
151
152 This wrapper function is required to ensure some requirements:
153
154 \begin{itemize}
155  \item enter a monitor on the \texttt{classinfo} structure, so that
156  only one thread can load the same class or interface at the same time
157
158  \item check if the class or interface is \texttt{loaded}, if it is
159  \texttt{true}, leave the monitor and return immediately
160
161  \item measure the loading time if requested
162
163  \item initialize the \texttt{classbuffer} structure with the actual
164  class file data
165
166  \item reset the \texttt{loaded} field of the \texttt{classinfo}
167  structure to \texttt{false} amd remove the \texttt{classinfo}
168  structure from the internal class hashtable if we got an error or
169  exception during loading
170
171  \item free any allocated memory
172
173  \item leave the monitor
174 \end{itemize}
175
176 The \texttt{class\_load} function is implemented to be
177 \textit{reentrant}. This must be the case for the \textit{eager class
178 loading} algorithm implemented in CACAO (described in more detail in
179 section \ref{sectioneagerclassloading}). Furthermore this means that
180 serveral threads can load different classes or interfaces at the same
181 time on multiprocessor machines.
182
183 The \texttt{class\_load\_intern} functions preforms the actual loading
184 of the binary representation of the class or interface. During loading
185 some verifier checks are performed which can throw an error. This
186 error can be a \texttt{java.lang.ClassFormatError} or a
187 \texttt{java.lang.NoClassDefFoundError}. Some of these
188 \texttt{java.lang.ClassFormatError} checks are
189
190 \begin{itemize}
191  \item \textit{Truncated class file} --- unexpected end of class file
192  data
193
194  \item \textit{Bad magic number} --- class file does not start with
195  the magic bytes (\texttt{0xCAFEBABE})
196
197  \item \textit{Unsupported major.minor version} --- the bytecode
198  version of the given class file is not supported by the JVM
199 \end{itemize}
200
201 The actual loading of the bytes from the binary representation is done
202 via the \texttt{suck\_*} functions. These functions are
203
204 \begin{itemize}
205  \item \texttt{suck\_u1}: load one \texttt{unsigned byte} (8 bit)
206
207  \item \texttt{suck\_u2}: load two \texttt{unsigned byte}s (16 bit)
208
209  \item \texttt{suck\_u4}: load four \texttt{unsigned byte}s (32 bit)
210
211  \item \texttt{suck\_u8}: load eight \texttt{unsigned byte}s (64 bit)
212
213  \item \texttt{suck\_float}: load four \texttt{byte}s (32 bit)
214  converted into a \texttt{float} value
215
216  \item \texttt{suck\_double}: load eight \texttt{byte}s (64 bit)
217  converted into a \texttt{double} value
218
219  \item \texttt{suck\_nbytes}: load \textit{n} bytes
220 \end{itemize}
221
222 Loading \texttt{signed} values is done via the
223 \texttt{suck\_s[1,2,4,8]} macros which cast the loaded bytes to
224 \texttt{signed} values. All these functions take a
225 \texttt{classbuffer} (see figure~\ref{classbufferstructure})
226 structure pointer as argument.
227
228 \begin{figure}[h]
229 \begin{verbatim}
230         typedef struct classbuffer {
231             classinfo *class;               /* pointer to classinfo structure     */
232             u1        *data;                /* pointer to byte code               */
233             s4         size;                /* size of the byte code              */
234             u1        *pos;                 /* current read position              */
235         } classbuffer;
236 \end{verbatim}
237 \caption{\texttt{classbuffer} structure}
238 \label{classbufferstructure}
239 \end{figure}
240
241 This \texttt{classbuffer} structure is filled with data via the
242
243 \begin{verbatim}
244         classbuffer *suck_start(classinfo *c);
245 \end{verbatim}
246
247 function. This function tries to locate the class, specifed with the
248 \texttt{classinfo} structure, in the \texttt{CLASSPATH}. This can be
249 a plain class file in the filesystem or a file in a
250 \texttt{zip}/\texttt{jar} file. If the class file is found, the
251 \texttt{classbuffer} is filled with data collected from the class
252 file, including the class file size and the binary representation of
253 the class.
254
255 Before reading any byte of the binary representation with a
256 \texttt{suck\_*} function, the remaining bytes in the
257 \texttt{classbuffer} data array must be checked with the
258
259 \begin{verbatim}
260         static inline bool check_classbuffer_size(classbuffer *cb, s4 len);
261 \end{verbatim}
262
263 function. If the remaining bytes number is less than the amount of the
264 bytes to be read, specified by the \texttt{len} argument, a
265 \texttt{java.lang.ClassFormatError} with the detail message
266 \textit{Truncated class file}---as mentioned before---is thrown.
267
268 The following subsections describe chronologically in greater detail
269 the individual loading steps of a class or interface from it's binary
270 representation.
271
272
273 \subsection{Constant pool loading}
274 \label{sectionconstantpoolloading}
275
276 The class' constant pool is loaded via
277
278 \begin{verbatim}
279         static bool class_loadcpool(classbuffer *cb, classinfo *c);
280 \end{verbatim}
281
282 from the \texttt{constant\_pool} table in the binary representation of
283 the class of interface. The \texttt{classinfo} structure has two
284 pointers to arrays which contain the class' constant pool infos,
285 namely: \texttt{cptags} and \texttt{cpinfos}. \texttt{cptags} contains
286 the type of the constant pool entry. \texttt{cpinfos} contains a
287 pointer to the constant pool entry itself.
288
289 The constant pool needs to be parsed in two passes. In the first pass
290 the information loaded is saved in temporary structures, which are
291 further processed in the second pass, when the complete constant pool
292 has been traversed. Only when all constant pool entries have been
293 processed, every constant pool entry can be completely resolved, but
294 this resolving can only be done in a specific order:
295
296 \begin{enumerate}
297  \item \texttt{CONSTANT\_Class}
298
299  \item \texttt{CONSTANT\_String}
300
301  \item \texttt{CONSTANT\_NameAndType}
302
303  \item \texttt{CONSTANT\_Fieldref} \\ \texttt{CONSTANT\_Methodref} \\
304  \texttt{CONSTANT\_InterfaceMethodref} --- these entries are combined
305  into one structure
306 \end{enumerate}
307
308 The temporary structures which are used to \textit{forward} the data
309 from the first pass into the second, are shown in
310 figure~\ref{constantpoolstructures}.
311
312 \begin{figure}[h]
313 \begin{verbatim}
314         /* CONSTANT_Class entries */
315         typedef struct forward_class {
316             struct forward_class *next;
317             u2 thisindex;
318             u2 name_index;
319         } forward_class;
320
321         /* CONSTANT_String */
322         typedef struct forward_string {
323             struct forward_string *next;
324             u2 thisindex;
325             u2 string_index;
326         } forward_string;
327
328         /* CONSTANT_NameAndType */
329         typedef struct forward_nameandtype {
330             struct forward_nameandtype *next;
331             u2 thisindex;
332             u2 name_index;
333             u2 sig_index;
334         } forward_nameandtype;
335
336         /* CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref */
337         typedef struct forward_fieldmethint {
338             struct forward_fieldmethint *next;
339             u2 thisindex;
340             u1 tag;
341             u2 class_index;
342             u2 nameandtype_index;
343         } forward_fieldmethint;
344 \end{verbatim}
345 \caption{temporary constant pool structures}
346 \label{constantpoolstructures}
347 \end{figure}
348
349 The following list describes how the constant pool entries, which need
350 two passes, are processed in the first pass.
351
352 \begin{itemize}
353
354  \item \texttt{CONSTANT\_Class}
355
356  \begin{itemize}
357   \item create a new \texttt{forward\_class} structure
358
359   \item add the \texttt{forward\_class} structure to the
360   \texttt{forward\_classes} list
361
362   \item store the current constant pool index into the
363   \texttt{thisindex} field
364
365   \item read the index of the class' name via \texttt{suck\_u2} and
366   store it into the \texttt{name\_index} field
367
368   \item increase the constant pool index by one
369  \end{itemize}
370
371  \item \texttt{CONSTANT\_String}
372
373  \begin{itemize}
374   \item create a new \texttt{forward\_string} structure
375
376   \item add the \texttt{forward\_string} structure to the \texttt{forward\_strings} list
377
378   \item store the current constant pool index into the \texttt{thisindex} field
379
380   \item read the index of the UTF8 string via \texttt{suck\_u2} and store it into the \texttt{name\_index} field
381
382   \item increase the constant pool index by one
383  \end{itemize}
384
385  \item \texttt{CONSTANT\_NameAndType}
386
387  \begin{itemize}
388   \item create a new \texttt{forward\_nameandtype} structure
389
390   \item add the \texttt{forward\_nameandtype} structure to the
391   \texttt{forward\_nameandtypes} list
392
393   \item store the current constant pool index into the
394   \texttt{thisindex} field
395
396   \item read the index of the UTF8 string containing the name via
397   \texttt{suck\_u2} and store it into the \texttt{name\_index} field
398
399   \item read the index of the UTF8 string containing the field or
400   method descriptor via \texttt{suck\_u2} and store it into the
401   \texttt{sig\_index} field
402
403   \item increase the constant pool index by one
404  \end{itemize}
405
406  \item \texttt{CONSTANT\_Fieldref} \\ \texttt{CONSTANT\_Methodref} \\
407  \texttt{CONSTANT\_InterfaceMethodref}
408
409  \begin{itemize}
410   \item create a new \texttt{forward\_fieldmethint} structure
411
412   \item add the \texttt{forward\_fieldmethint} structure to the
413   \texttt{forward\_fieldmethints} list
414
415   \item store the current constant pool index into the
416   \texttt{thisindex} field
417
418   \item store the current constant pool type into the \texttt{tag}
419   field
420
421   \item read the constant pool index of the \texttt{CONSTANT\_Class}
422   entry that contains the declaration of the field or method via
423   \texttt{suck\_u2} and store it into the \texttt{class\_index} field
424
425   \item read the constant pool index of the
426   \texttt{CONSTANT\_NameAndType} entry that contains the name and
427   descriptor of the field or method and store it into the
428   \texttt{nameandtype\_index} field
429
430   \item increase the constant pool index by one
431
432  \end{itemize}
433
434 \end{itemize}
435
436 The remaining constant pool types can be completely resolved in the
437 first pass and need no further processing. These types, including the
438 actions taken in the first pass, are as follows:
439
440 \begin{itemize}
441
442  \item \texttt{CONSTANT\_Integer}
443
444  \begin{itemize}
445
446   \item create a new \texttt{constant\_integer} structure (see
447   figure~\ref{constantintegerstructure})
448
449   \item read a 4 byte \texttt{signed integer} value via
450   \texttt{suck\_s4} from the binary representation
451
452   \item store the value into the \texttt{value} field of the
453   \texttt{constant\_integer} structure
454
455   \item store the type \texttt{CONSTANT\_Integer} into \texttt{cptags}
456   and the pointer to the \texttt{constant\_integer} structure into
457   \texttt{cpinfos} at the appropriate index
458
459   \item increase the constant pool index by one
460
461  \end{itemize}
462
463 \begin{figure}[h]
464 \begin{verbatim}
465         typedef struct {            /* Integer                                    */
466             s4 value;
467         } constant_integer;
468 \end{verbatim}
469 \caption{\texttt{constant\_integer} structure}
470 \label{constantintegerstructure}
471 \end{figure}
472
473  \item \texttt{CONSTANT\_Float}
474
475  \begin{itemize}
476
477   \item create a new \texttt{constant\_float} structure (see
478   figure~\ref{constantfloatstructure})
479
480   \item read a 4 byte \texttt{float} value via \texttt{suck\_float}
481   from the binary representation
482
483   \item store the value into the \texttt{value} field of the
484   \texttt{constant\_float} structure
485
486   \item store the type \texttt{CONSTANT\_Float} into \texttt{cptags}
487   and the pointer to the \texttt{constant\_float} structure into
488   \texttt{cpinfos} at the appropriate index
489
490   \item increase the constant pool index by one
491
492  \end{itemize}
493
494 \begin{figure}[h]
495 \begin{verbatim}
496         typedef struct {            /* Float                                      */
497             float value;
498         } constant_float;
499 \end{verbatim}
500 \caption{\texttt{constant\_float} structure}
501 \label{constantfloatstructure}
502 \end{figure}
503
504  \item \texttt{CONSTANT\_Long}
505
506  \begin{itemize}
507
508   \item create a new \texttt{constant\_long} structure (see
509   figure~\ref{constantlongstructure})
510
511   \item read a 8 byte \texttt{signed long} value via \texttt{suck\_s8}
512   from the binary representation
513
514   \item store the value into the \texttt{value} field of the
515   \texttt{constant\_long} structure
516
517   \item store the type \texttt{CONSTANT\_Long} into \texttt{cptags}
518   and the pointer to the \texttt{constant\_long} structure into
519   \texttt{cpinfos} at the appropriate index
520
521   \item increase the constant pool index by two
522
523  \end{itemize}
524
525 \begin{figure}[h]
526 \begin{verbatim}
527         typedef struct {            /* Long                                       */
528             s8 value;
529         } constant_long;
530 \end{verbatim}
531 \caption{\texttt{constant\_long} structure}
532 \label{constantlongstructure}
533 \end{figure}
534
535  \item \texttt{CONSTANT\_Double}
536
537  \begin{itemize}
538
539   \item create a new \texttt{constant\_double} structure (see
540   figure~\ref{constantdoublestructure})
541
542   \item read a 8 byte \texttt{double} value via \texttt{suck\_double}
543   from the binary representation
544
545   \item store the value into the \texttt{value} field of the
546   \texttt{constant\_double} structure
547
548   \item store the type \texttt{CONSTANT\_Double} into \texttt{cptags}
549   and the pointer to the \texttt{constant\_double} structure into
550   \texttt{cpinfos} at the appropriate index
551
552   \item increase the constant pool index by two
553
554  \end{itemize}
555
556 \begin{figure}[h]
557 \begin{verbatim}
558         typedef struct {            /* Double                                     */
559             double value;
560         } constant_double;
561 \end{verbatim}
562 \caption{\texttt{constant\_double} structure}
563 \label{constantdoublestructure}
564 \end{figure}
565
566  \item \texttt{CONSTANT\_Utf8}
567
568  \begin{itemize}
569
570   \item read the length of the UTF8 string via \texttt{suck\_u2}
571
572   \item store the type \texttt{CONSTANT\_Utf8} into \texttt{cptags} at
573   the appropriate index
574
575   \item create a new UTF8 string in the runtime environment of the
576   Java Virtual Machine via \texttt{utf\_new\_intern}
577
578   \item store the pointer of the newly created UTF8 string into
579   \texttt{cpinfos} at the appropriate index
580
581   \item skip \texttt{length} bytes in the binary representation of the
582   class or interface via \texttt{skip\_nbytes}
583
584   \item increase the constant pool index by one
585
586  \end{itemize}
587
588 \end{itemize}
589
590 In the second pass, the references are resolved and the runtime
591 structures are created. In further detail this includes for
592
593 \begin{itemize}
594
595  \item \texttt{CONSTANT\_Class}
596
597   \begin{itemize}
598
599    \item resolve the UTF8 name string from the class' constant pool
600
601    \item store the type \texttt{CONSTANT\_Class} in \texttt{cptags} at
602    the appropriate index
603
604    \item create a class in the class hashtable with the UTF8 name
605
606    \item store the pointer to the new class in \texttt{cpinfos} at the
607    appropriate index
608
609   \end{itemize}
610
611  \item \texttt{CONSTANT\_String}
612
613   \begin{itemize}
614
615    \item resolve the UTF8 string of the referenced string from the
616    class' constant pool
617
618    \item store type \texttt{CONSTANT\_String} in \texttt{cptags} and
619    store the UTF8 string pointer into \texttt{cpinfos} at the
620    appropriate index
621
622   \end{itemize}
623
624  \item \texttt{CONSTANT\_NameAndType}
625
626   \begin{itemize}
627
628    \item create a new \texttt{constant\_nameandtype} structure (see
629    figure~\ref{constantnameandtype})
630
631    \item resolve the UTF8 name and description string of the field or
632    method and store them into the \texttt{constant\_nameandtype}
633    structure
634
635    \item store type \texttt{CONSTANT\_NameAndType} into
636   \texttt{cptags} and store a pointer to the
637   \texttt{constant\_nameandtype} structure into \texttt{cpinfos}
638
639   \end{itemize}
640
641 \begin{figure}[h]
642 \begin{verbatim}
643         typedef struct {            /* NameAndType (Field or Method)       */
644             utf *name;              /* field/method name                   */
645             utf *descriptor;        /* field/method type descriptor string */
646         } constant_nameandtype;
647 \end{verbatim}
648 \caption{\texttt{constant\_nameandtype} structure}
649 \label{constantnameandtype}
650 \end{figure}
651
652  \item \texttt{CONSTANT\_Fieldref} \\
653        \texttt{CONSTANT\_Methodref} \\
654        \texttt{CONSTANT\_InterfaceMethodref}
655
656   \begin{itemize}
657
658    \item create a new \texttt{constant\_FMIref} structure (see
659    figure~\ref{constantFMIref})
660
661    \item resolve the referenced \texttt{constant\_nameandtype}
662    structure which contains the name and descriptor resolved in a
663    previous step and store the name and descriptor into the
664    \texttt{constant\_FMIref} structure
665
666    \item resolve the pointer of the referenced class which was created
667    in a previous step and store the pointer of the class into the
668    \texttt{constant\_FMIref} structure
669
670    \item store the type of the current constant pool entry in
671    \texttt{cptags} and store the pointer to \texttt{constant\_FMIref}
672    in \texttt{cpinfos} at the appropriate index
673
674   \end{itemize}
675
676 \begin{figure}[h]
677 \begin{verbatim}
678         typedef struct {           /* Fieldref, Methodref and InterfaceMethodref    */
679             classinfo *class;      /* class containing this field/method/interface  */
680             utf       *name;       /* field/method/interface name                   */
681             utf       *descriptor; /* field/method/interface type descriptor string */
682         } constant_FMIref;
683 \end{verbatim}
684 \caption{\texttt{constant\_FMIref} structure}
685 \label{constantFMIref}
686 \end{figure}
687
688 \end{itemize}
689
690 Any UTF8 strings, \texttt{constant\_nameandtype} structures or
691 referenced classes are resolved with the
692
693 \begin{verbatim}
694         voidptr class_getconstant(classinfo *c, u4 pos, u4 ctype);
695 \end{verbatim}
696
697 function. This functions checks for type equality and then returns the
698 requested \texttt{cpinfos} slot of the specified class.
699
700
701 \subsection{Interface loading}
702
703 Interface loading is very simple and straightforward. After reading
704 the number of interfaces, for every interface referenced, a
705 \texttt{u2} constant pool index is read from the currently loading
706 class or interface. This index is used to resolve the interface class
707 via the \texttt{class\_getconstant} function from the class' constant
708 pool. This means, interface \textit{loading} is more interface
709 \textit{resolving} than loading. The resolved interfaces are stored
710 in an \texttt{classinfo *} array allocated by the class loader. The
711 memory pointer of the array is assigned to the \texttt{interfaces}
712 field of the \texttt{clasinfo} structure.
713
714
715 \subsection{Field loading}
716
717 The number of fields of the class or interface is read as \texttt{u2}
718 value. For each field the function
719
720 \begin{verbatim}
721         static bool field_load(classbuffer *cb, classinfo *c, fieldinfo *f);
722 \end{verbatim}
723
724 is called. The \texttt{fieldinfo *} argument is a pointer to a
725 \texttt{fieldinfo} structure (see figure~\ref{fieldinfostructure})
726 allocated by the class loader. The fields' \texttt{name} and
727 \texttt{descriptor} are resolved from the class constant pool via
728 \texttt{class\_getconstant}. If the verifier option is turned on, the
729 fields' \texttt{flags}, \texttt{name} and \texttt{descriptor} are
730 checked for validity and can result in a
731 \texttt{java.lang.ClassFormatError}.
732
733 \begin{figure}[h]
734 \begin{verbatim}
735     struct fieldinfo {        /* field of a class                                 */
736         s4   flags;           /* ACC flags                                        */
737         s4   type;            /* basic data type                                  */
738         utf *name;            /* name of field                                    */
739         utf *descriptor;      /* JavaVM descriptor string of field                */
740         
741         s4   offset;          /* offset from start of object (instance variables) */
742
743         imm_union  value;     /* storage for static values (class variables)      */
744
745         classinfo *class;     /* needed by typechecker. Could be optimized        */
746                               /* away by using constant_FMIref instead of         */
747                               /* fieldinfo throughout the compiler.               */
748         ...
749     };
750 \end{verbatim}
751 \caption{\texttt{fieldinfo} structure}
752 \label{fieldinfostructure}
753 \end{figure}
754
755 Each field can have some attributes. The number of attributes is read
756 as \texttt{u2} value from the binary representation. If the field has
757 the \texttt{ACC\_FINAL} bit set in the flags, the
758 \texttt{ConstantValue} attribute is available. This is the only
759 attribute processed by \texttt{field\_load} and can occur only once,
760 otherwise a \texttt{java.lang.ClassFormatError} is thrown. The
761 \texttt{ConstantValue} entry in the constant pool contains the value
762 for the \texttt{final} field. Depending on the fields' type, the
763 proper constant pool entry is resolved and assigned.
764
765
766 \subsection{Method loading}
767
768 As for the fields, the number of the class or interface methods is read from
769 the binary representation as \texttt{u2} value. For each method the function
770
771 \begin{verbatim}
772         static bool method_load(classbuffer *cb, classinfo *c, methodinfo *m);
773 \end{verbatim}
774
775 is called. The beginning of the method loading code is nearly the same
776 as the field loading code. The \texttt{methodinfo *} argument is a
777 pointer to a \texttt{methodinfo} structure allocated by the class
778 loader. The method's \texttt{name} and \texttt{descriptor} are
779 resolved from the class constant pool via
780 \texttt{class\_getconstant}. With the verifier turned on, some method
781 checks are carried out. These include \texttt{flags}, \texttt{name}
782 and \texttt{descriptor} checks and argument count check.
783
784 \begin{figure}[h]
785 \begin{verbatim}
786     struct methodinfo {                 /* method structure                       */
787         java_objectheader header;       /* we need this in jit's monitorenter     */
788         s4          flags;              /* ACC flags                              */
789         utf        *name;               /* name of method                         */
790         utf        *descriptor;         /* JavaVM descriptor string of method     */
791         ...
792         bool        isleafmethod;       /* does method call subroutines           */
793
794         classinfo  *class;              /* class, the method belongs to           */
795         s4          vftblindex;         /* index of method in virtual function    */
796                                         /* table (if it is a virtual method)      */
797         s4          maxstack;           /* maximum stack depth of method          */
798         s4          maxlocals;          /* maximum number of local variables      */
799         s4          jcodelength;        /* length of JavaVM code                  */
800         u1         *jcode;              /* pointer to JavaVM code                 */
801         ...
802         s4          exceptiontablelength;/* exceptiontable length                 */
803         exceptiontable *exceptiontable; /* the exceptiontable                     */
804
805         u2          thrownexceptionscount;/* number of exceptions attribute       */
806         classinfo **thrownexceptions;   /* checked exceptions a method may throw  */
807
808         u2          linenumbercount;    /* number of linenumber attributes        */
809         lineinfo   *linenumbers;        /* array of lineinfo items                */
810         ...
811         u1         *stubroutine;        /* stub for compiling or calling natives  */
812         ...
813     };
814 \end{verbatim}
815 \caption{\texttt{methodinfo} structure}
816 \label{methodinfostructure}
817 \end{figure}
818
819 The method loading function has to distinguish between a
820 \texttt{native} and a ''normal'' JAVA method. Depending on the
821 \texttt{ACC\_NATIVE} flags, a different stub is created.
822
823 For a JAVA method, a \textit{compiler stub} is created. The purpose of
824 this stub is to call the CACAO jit compiler with a pointer to the byte
825 code of the JAVA method as argument to compile the method into machine
826 code. During code generation a pointer to this compiler stub routine
827 is used as a temporary method call, if the method is not compiled
828 yet. After the target method is compiled, the new entry point of the
829 method is patched into the generated code and the compiler stub is
830 needless, thus it is freed.
831
832 If the method is a \texttt{native} method, the loader tries to find
833 the native function. If the function was found, a \textit{native stub}
834 is generated. This stub is responsible to manipulate the method's
835 arguments to be suitable for the \texttt{native} method called. This
836 includes inserting the \textit{JNI environment} pointer as first
837 argument and, if the \texttt{native} method has the
838 \texttt{ACC\_STATIC} flag set, inserting a pointer to the methods
839 class as second argument. If the \texttt{native} method is
840 \texttt{static}, the native stub also checks if the method's class is
841 already initialized. If the method's class is not initialized as the
842 native stub is generated, a \texttt{asm\_check\_clinit} calling code
843 is emitted.
844
845 Each method can have some attributes. The method loading function
846 processes two of them: \texttt{Code} and \texttt{Exceptions}.
847
848 The \texttt{Code} attribute is a \textit{variable-length} attribute
849 which contains the Java Virtual Machine instructions---the byte
850 code---of the JAVA method. If the method is either \texttt{native} or
851 \texttt{abstract}, it must not have a \texttt{Code} attribute,
852 otherwise it must have exactly one \texttt{Code}
853 attribute. Additionally to the byte code, the \texttt{Code} attribute
854 contains the exception table and attributes to \texttt{Code} attribute
855 itself. One exception table entry contains the \texttt{start\_pc},
856 \texttt{end\_pc} and
857 \texttt{handler\_pc} of the \texttt{try-catch} block, each read as
858 \texttt{u2} value, plus a reference to the class of the
859 \texttt{catch\_type}. Currently there are two attributes of the
860 \texttt{Code} attribute defined in the JVM specification:
861 \texttt{LineNumberTable} and \texttt{LocalVariableTable}. CACAO only
862 processes the \texttt{LineNumberTable} attribute. A
863 \texttt{LineNumberTable} entry consist of the \texttt{start\_pc} and
864 the \texttt{line\_number}, which are stored in a \texttt{lineinfo}
865 structure (see figure~\ref{lineinfostructure}).
866
867 \begin{figure}[h]
868 \begin{verbatim}
869     struct lineinfo {
870         u2 start_pc;
871         u2 line_number;
872     };
873 \end{verbatim}
874 \caption{\texttt{lineinfo} structure}
875 \label{lineinfostructure}
876 \end{figure}
877
878 The linenumber count and the memory pointer of the \texttt{lineinfo}
879 structure array are assigned to the \texttt{classinfo} fields
880 \texttt{linenumbercount} and \texttt{linenumbers} respectively.
881
882 The \texttt{Exceptions} attribute is a \textit{variable-length}
883 attribute and contains the checked exceptions the JAVA method may
884 throw. The \texttt{Exceptions} attribute consist of the count of
885 exceptions, which is stored in the \texttt{classinfo} field
886 \texttt{thrownexceptionscount}, and the adequate amount of \texttt{u2}
887 constant pool index values. The exception classes are resolved from
888 the constant pool and stored in an allocated \texttt{classinfo *}
889 array, whose memory pointer is assigned to the
890 \texttt{thrownexceptions} field of the \texttt{classinfo} structure.
891
892 Any attributes which are not processed by the CACAO class loading
893 system, are skipped via
894
895 \begin{verbatim}
896         static bool skipattributebody(classbuffer *cb);
897 \end{verbatim}
898
899 which skips one attribute or
900
901 \begin{verbatim}
902         static bool skipattributes(classbuffer *cb, u4 num);
903 \end{verbatim}
904
905 which skips a specified number \texttt{num} of attributes. If any
906 problem occurs in the method loading function, a
907 \texttt{java.lang.ClassFormatError} with a specific detail message is
908 thrown.
909
910
911 \subsection{Attribute loading}
912
913 Attribute loading is done via the
914
915 \begin{verbatim}
916         static bool attribute_load(classbuffer *cb, classinfo *c, u4 num);
917 \end{verbatim}
918
919 function. The currently loading class or interface can contain some
920 additional attributes which have not already been loaded. The CACAO
921 system class loader processes two of them: \texttt{InnerClasses} and
922 \texttt{SourceFile}.
923
924 The \texttt{InnerClass} attribute is a \textit{variable-length}
925 attribute in the \texttt{attributes} table of the binary
926 representation of the class or interface. A \texttt{InnerClass} entry
927 contains the \texttt{inner\_class} constant pool index itself, the
928 \texttt{outer\_class} index, the \texttt{name} index of the inner
929 class' name and the inner class' \texttt{flags} bitmask. All these
930 values are read in \texttt{u2} chunks.
931
932 The constant pool indexes are used with the
933
934 \begin{verbatim}
935         voidptr innerclass_getconstant(classinfo *c, u4 pos, u4 ctype);
936 \end{verbatim}
937
938 function call to resolve the classes or UTF8 strings. After resolving
939 is done, all values are stored in the \texttt{innerclassinfo}
940 structure (see figure~\ref{innerclassinfostructure}).
941
942 \begin{figure}[h]
943 \begin{verbatim}
944     struct innerclassinfo {
945         classinfo *inner_class;       /* inner class pointer                      */
946         classinfo *outer_class;       /* outer class pointer                      */
947         utf       *name;              /* innerclass name                          */
948         s4         flags;             /* ACC flags                                */
949     };
950 \end{verbatim}
951 \caption{\texttt{innerclassinfo} structure}
952 \label{innerclassinfostructure}
953 \end{figure}
954
955 The other attribute, \texttt{SourceFile}, is just one \texttt{u2}
956 constant pool index value to get the UTF8 string reference of the
957 class' \texttt{SourceFile} name. The string pointer is assigned to the
958 \texttt{sourcefile} field of the \texttt{classinfo} structure.
959
960 Both attributes must occur only once. Other attributes than these two
961 are skipped with the earlier mentioned \texttt{skipattributebody}
962 function.
963
964 After the attribute loading is done and no error occured, the
965 \texttt{class\_load\_intern} function returns the \texttt{classinfo}
966 pointer to signal that there was no problem. If \texttt{NULL} is
967 returned, there was an exception.
968
969
970 %\section{Dynamic class loader}
971
972
973 \section{Eager - lazy class loading}
974
975 A Java Virtual Machine can implement two different algorithms for the
976 system class loader to load classes or interfaces: \textit{eager class
977 loading} and \textit{lazy class loading}.
978
979
980 \subsection{Eager class loading}
981 \label{sectioneagerclassloading}
982
983 The Java Virtual Machine initially creates, loads and links the class
984 of the main program with the system class loader. The creation of the
985 class is done via the \texttt{class\_new} function call (see section
986 \ref{sectionsystemclassloader}). In this function, with \textit{eager
987 loading} enabled, firstly the currently created class or interface is
988 loaded with \texttt{class\_load}. CACAO uses the \textit{eager class
989 loading} algorithm with the command line switch \texttt{-eager}. As
990 described in the ''Constant pool loading'' section (see
991 \ref{sectionconstantpoolloading}), the binary representation of a
992 class or interface contains references to other classes or
993 interfaces. With \textit{eager loading} enabled, referenced classes or
994 interfaces are loaded immediately.
995
996 If a class reference is found in the second pass of the constant pool
997 loading process, the class is created in the class hashtable with
998 \texttt{class\_new\_intern}. CACAO uses the intern function here
999 because the normal \texttt{class\_new} function, which is a wrapper
1000 function, instantly tries to \textit{link} all referenced
1001 classes. This must not happen until all classes or interfaces
1002 referenced are loaded, otherwise the Java Virtual Machine gets into an
1003 indefinite state.
1004
1005 After the \texttt{classinfo} of the class referenced is created, the
1006 class or interface is \textit{loaded} via the \texttt{class\_load}
1007 function (described in more detail in section
1008 \ref{sectionsystemclassloader}). When the class loading function
1009 returns, the current referenced class or interface is added to a list
1010 called \texttt{unlinkedclasses}, which contains all loaded but
1011 unlinked classes referenced by the currently loaded class or
1012 interface. This list is processed in the \texttt{class\_new} function
1013 of the currently created class or interface after \texttt{class\_load}
1014 returns. For each entry in the \texttt{unlinkedclasses} list,
1015 \texttt{class\_link} is called which finally \textit{links} the class
1016 (described in more detail in section \ref{sectionlinking}) and then
1017 the class entry is removed from the list. When all referenced classes
1018 or interfaces are linked, the currently created class or interface is
1019 linked and the \texttt{class\_new} functions returns.
1020
1021
1022 \subsection{Lazy class loading}
1023 \label{sectionlazyclassloading}
1024
1025 Usually it takes much more time for a Java Virtual Machine to start a
1026 program with \textit{eager class loading} as with \textit{lazy class
1027 loading}. With \textit{eager class loading}, a typical
1028 \texttt{HelloWorld} program needs 513 class loads with the current GNU
1029 classpath CACAO is using. When using \textit{lazy class loading},
1030 CACAO only needs 121 class loads for the same \texttt{HelloWorld}
1031 program. This means with \textit{lazy class loading} CACAO needs to
1032 load more than four times less class files. Furthermore CACAO does
1033 also \textit{lazy class linking}, which saves much more run-time here.
1034
1035 CACAO's \textit{lazy class loading} implementation does not completely
1036 follow the JVM specification. A Java Virtual Machine which implements
1037 \textit{lazy class loading} should load and link requested classes or
1038 interfaces at runtime. But CACAO does class loading and linking at
1039 parse time, because of some problems not resolved yet. That means, if
1040 a Java Virtual Machine instruction is parsed which uses any class or
1041 interface references, like \texttt{JAVA\_PUTSTATIC},
1042 \texttt{JAVA\_GETFIELD} or any \texttt{JAVA\_INVOKE*} instructions,
1043 the referenced class or interface is loaded and linked immediately
1044 during the parse pass of currently compiled method. This introduces
1045 some incompatibilities with other Java Virtual Machines like Sun's
1046 JVM, IBM's JVM or Kaffe.
1047
1048 Given a code snippet like this
1049
1050 \begin{verbatim}
1051         void sub(boolean b) {
1052             if (b) {
1053                 new A();
1054             }
1055             System.out.println("foobar");
1056         }
1057 \end{verbatim}
1058
1059 If the function is called with \texttt{b} equal \texttt{false} and the
1060 class file \texttt{A.class} does not exist, a Java Virtual Machine
1061 should execute the code without any problems, print \texttt{foobar}
1062 and exit the Java Virtual Machine with exit code 0. Due to the fact
1063 that CACAO does class loading and linking at parse time, the CACAO
1064 Virtual Machine throws an \texttt{java.lang.NoClassDefFoundError:~A}
1065 exception which is not caught and thus discontinues the execution
1066 without printing \texttt{foobar} and exits.
1067
1068 The CACAO development team has not yet a solution for this
1069 problem. It's not trivial to move the loading and linking process from
1070 the compilation phase into runtime, especially CACAO was initially
1071 designed for \textit{eager class loading} and \textit{lazy class
1072 loading} was implemented at a later time to optimize class loading and
1073 to get a little closer to the JVM specification. \textit{Lazy class
1074 loading} at runtime is one of the most important features to be
1075 implemented in the future. It is essential to make CACAO a standard
1076 compliant Java Virtual Machine.
1077
1078
1079 \section{Linking}
1080 \label{sectionlinking}
1081
1082 Linking is the process of preparing a previously loaded class or
1083 interface to be used in the Java Virtual Machine's runtime
1084 environment. The function which performs the linking in CACAO is
1085
1086 \begin{verbatim}
1087         classinfo *class_link(classinfo *c);
1088 \end{verbatim}
1089
1090 This function, as for class loading, is just a wrapper function to the
1091 main linking function
1092
1093 \begin{verbatim}
1094         static classinfo *class_link_intern(classinfo *c);
1095 \end{verbatim}
1096
1097 This function should not be called directly and is thus declared as
1098 \texttt{static}. The purposes of the wrapper function are
1099
1100 \begin{itemize}
1101  \item enter a monitor on the \texttt{classinfo} structure, so that
1102  only one thread can link the same class or interface at the same time
1103
1104  \item check if the class or interface is \texttt{linked}, if it is
1105  \texttt{true}, leave the monitor and return immediately
1106
1107  \item measure linking time if requested
1108
1109  \item check if the intern linking function has thrown an error or an
1110  exception and reset the \texttt{linked} field of the
1111  \texttt{classinfo} structure
1112
1113  \item leave the monitor
1114 \end{itemize}
1115
1116 The \texttt{class\_link} function, like the \texttt{class\_load}
1117 function, is implemented to be \textit{reentrant}. This must be the
1118 case for the linking algorithm implemented in CACAO. Furthermore this
1119 means that serveral threads can link different classes or interfaces
1120 at the same time on multiprocessor machines.
1121
1122 The first step in the \texttt{class\_link\_intern} function is to set
1123 the \texttt{linked} field of the currently linked \texttt{classinfo}
1124 structure to \texttt{true}. This is essential, that the linker does
1125 not try to link a class or interface again, while it's already in the
1126 linking process. Such a case can occur because the linker also
1127 processes the class' direct superclass and direct superinterfaces.
1128
1129 In CACAO's linker the direct superinterfaces are processed first. For
1130 each interface in the \texttt{interfaces} field of the
1131 \texttt{classinfo} structure is checked if there occured an
1132 \texttt{java.lang.ClassCircularityError}, which happens when the
1133 currently linked class or interface is equal the interface which
1134 should be processed. Otherwise the interface is loaded and linked if
1135 not already done. After the interface is loaded successfully, the
1136 interface flags are checked for the \texttt{ACC\_INTERFACE} bit. If
1137 this is not the case, a
1138 \texttt{java.lang.IncompatibleClassChangeError} is thrown and
1139 \texttt{class\_link\_intern} returns.
1140
1141 Then the direct superclass is handled. If the direct superclass is
1142 equal \texttt{NULL}, we have the special case of linking
1143 \texttt{java.lang.Object}. There are only set some \texttt{classinfo}
1144 fields to special values for \texttt{java.lang.Object} like
1145
1146 \begin{verbatim}
1147         c->index = 0;
1148         c->instancesize = sizeof(java_objectheader);
1149         vftbllength = 0;
1150         c->finalizer = NULL;
1151 \end{verbatim}
1152
1153 If the direct superclass is non-\texttt{NULL}, CACAO firstly detects
1154 class circularity as for interfaces. If no
1155 \texttt{java.lang.ClassCircularityError} was thrown, the superclass is
1156 loaded and linked if not already done before. Then some flag bits of
1157 the superclass are checked: \texttt{ACC\_INTERFACE} and
1158 \texttt{ACC\_FINAL}. If one of these bits is set an error is thrown.
1159
1160 If the currently linked class is an array, CACAO calls a special array
1161 linking function
1162
1163 \begin{verbatim}
1164         static arraydescriptor *class_link_array(classinfo *c);
1165 \end{verbatim}
1166
1167 This function firstly checks if the passed \texttt{classinfo} is an
1168 \textit{array of arrays} or an \textit{array of objects}. In both
1169 cases the component type is created in the class hashtable via
1170 \texttt{class\_new} and then loaded and linked if not already
1171 done. If none is the case, the passed array is a \textit{primitive
1172 type array}. No matter of which type the array is, an
1173 \texttt{arraydescriptor} structure (see
1174 figure~\ref{arraydescriptorstructure}) is allocated and filled with
1175 the appropriate values of the given array type.
1176
1177 \begin{figure}[h]
1178 \begin{verbatim}
1179     struct arraydescriptor {
1180         vftbl_t *componentvftbl; /* vftbl of the component type, NULL for primit. */
1181         vftbl_t *elementvftbl;   /* vftbl of the element type, NULL for primitive */
1182         s2       arraytype;      /* ARRAYTYPE_* constant                          */
1183         s2       dimension;      /* dimension of the array (always >= 1)          */
1184         s4       dataoffset;     /* offset of the array data from object pointer  */
1185         s4       componentsize;  /* size of a component in bytes                  */
1186         s2       elementtype;    /* ARRAYTYPE_* constant                          */
1187     };
1188 \end{verbatim}
1189 \caption{\texttt{arraydescriptor} structure}
1190 \label{arraydescriptorstructure}
1191 \end{figure}
1192
1193 After the \texttt{class\_link\_array} function call, the class
1194 \texttt{index} is calculated. For interfaces---classes with
1195 \texttt{ACC\_INTERFACE} flag bit set---the class' \texttt{index} is
1196 the global \texttt{interfaceindex} plus one. Any other classes get the
1197 \texttt{index} of the superclass plus one.
1198
1199 Other \texttt{classinfo} fields are also set from the superclass like,
1200 \texttt{instancesize}, \texttt{vftbllength} and the \texttt{finalizer}
1201 function. All these values are temporary ones and can be overwritten
1202 at a later time.
1203
1204 The next step in \texttt{class\_load\_intern} is to compute the
1205 \textit{virtual function table length}. For each method in
1206 \texttt{classinfo}'s \texttt{methods} field which has not the
1207 \texttt{ACC\_STATIC} flag bit set, thus is an instance method, the
1208 direct superclasses up to \texttt{java.lang.Object} are checked with
1209
1210 \begin{verbatim}
1211         static bool method_canoverwrite(methodinfo *m, methodinfo *old);
1212 \end{verbatim}
1213
1214 if the current method can overwrite the superclass method, if there
1215 exists one. If the found superclass method has the
1216 \texttt{ACC\_PRIVATE} flag bit set, the current method's
1217 \textit{virtual function table index} is the current \textit{virtual
1218 function table length} plus one:
1219
1220 \begin{verbatim}
1221         m->vftblindex = (vftbllength++);
1222 \end{verbatim}
1223
1224 If the current method has the \texttt{ACC\_FINAL} flag bit set, the
1225 CACAO class linker throws a \texttt{java.lang.VerifyError}. Otherwise
1226 the current method's \textit{virtual function table index} is the same
1227 as the index from the superclass method:
1228
1229 \begin{verbatim}
1230         m->vftblindex = tc->methods[j].vftblindex;
1231 \end{verbatim}
1232
1233 After processing the \textit{virtual function table length}, the CACAO
1234 linker computes the \textit{interface table length}. For the current
1235 class' and every superclass' interfaces, the function
1236
1237 \begin{verbatim}
1238         static s4 class_highestinterface(classinfo *c);
1239 \end{verbatim}
1240
1241 is called. This function computes the highest interface \texttt{index}
1242 of the passed interface and returns the value. This is done by
1243 recursively calling \texttt{class\_highestinterface} with each
1244 interface from the \texttt{interfaces} array of the passed interface
1245 as argument. The highest \texttt{index} value found is the
1246 \textit{interface table length} of the currently linking class or
1247 interface.
1248
1249 Now that the linker has completely computed the size of the
1250 \textit{virtual function table}, the memory can be allocated, casted
1251 to an \texttt{vftbl} structure (see figure~\ref{vftblstructure}) and
1252 filled with the previously calculated values.
1253
1254 \begin{figure}
1255 \begin{verbatim}
1256     struct vftbl {
1257         methodptr   *interfacetable[1];    /* interface table (access via macro)  */
1258
1259         classinfo   *class;                /* class, the vtbl belongs to          */
1260
1261         arraydescriptor *arraydesc;        /* for array classes, otherwise NULL   */
1262
1263         s4           vftbllength;          /* virtual function table length       */
1264         s4           interfacetablelength; /* interface table length              */
1265
1266         s4           baseval;              /* base for runtime type check         */
1267                                            /* (-index for interfaces)             */
1268         s4           diffval;              /* high - base for runtime type check  */
1269
1270         s4          *interfacevftbllength; /* length of interface vftbls          */
1271         
1272         methodptr    table[1];             /* class vftbl                         */
1273     };
1274 \end{verbatim}
1275 \caption{\texttt{vftbl} structure}
1276 \label{vftblstructure}
1277 \end{figure}
1278
1279 Some important values are
1280
1281 \begin{verbatim}
1282         c->header.vftbl = c->vftbl = v;
1283         v->class = c;
1284         v->vftbllength = vftbllength;
1285         v->interfacetablelength = interfacetablelength;
1286         v->arraydesc = arraydesc;
1287 \end{verbatim}
1288
1289 If the currently linked class is an interface, the \texttt{baseval} of
1290 the interface's \textit{virtual function table} is set to
1291 \texttt{-(c->index)}. Then the \textit{virtual function table} of the
1292 direct superclass is copied into the \texttt{table} field of the
1293 current \textit{virtual function table} and for each
1294 non-\texttt{static} method in the current's class or interface
1295 \texttt{methods} field, the pointer to the \textit{stubroutine} of the
1296 method in stored in the \textit{virtual function table}.
1297
1298 Now the fields of the currently linked class or interface are
1299 processed. The CACAO linker computes the instance size of the class or
1300 interface and the offset of each field inside. For each field in the
1301 \texttt{classinfo} field \texttt{fields} which is non-\texttt{static},
1302 the type-size is resolved via the \texttt{desc\_typesize} function
1303 call. Then a new \texttt{instancesize} is calculated with
1304
1305 \begin{verbatim}
1306         c->instancesize = ALIGN(c->instancesize, dsize);
1307 \end{verbatim}
1308
1309 which does memory alignment suitable for the next field. This newly
1310 computed \texttt{instancesize} is the \texttt{offset} of the currently
1311 processed field. The type-size is then added to get the real
1312 \texttt{instancesize}.
1313
1314 The next step of the CACAO linker is to initialize two \textit{virtual
1315 function table} fields, namely \texttt{interfacevftbllength} and
1316 \texttt{interfacetable}. For \texttt{interfacevftbllength} an
1317 \texttt{s4} array of \texttt{interfacetablelength} elements is
1318 allocated. Each \texttt{interfacevftbllength} element is initialized
1319 with \texttt{0} and the elements in \texttt{interfacetable} with
1320 \texttt{NULL}. After the initialization is done, the interfaces of the
1321 currently linked class and all it's superclasses, up to
1322 \texttt{java.lang.Object}, are processed via the
1323
1324 \begin{verbatim}
1325         static void class_addinterface(classinfo *c, classinfo *ic);
1326 \end{verbatim}
1327
1328 function call. This function adds the methods of the passed interface
1329 to the \textit{virtual function table} of the passed class or
1330 interface. If the method count of the passed interface is zero, the
1331 function adds a method fake entry, which is needed for subtype
1332 tests:
1333
1334 \begin{verbatim}
1335         v->interfacevftbllength[i] = 1;
1336         v->interfacetable[-i] = MNEW(methodptr, 1);
1337         v->interfacetable[-i][0] = NULL;
1338 \end{verbatim}
1339
1340 \texttt{i} represents the \texttt{index} of the passed interface
1341 \texttt{ic}, \texttt{v} the \textit{virtual function table} of the
1342 passed class or interface \texttt{c}.
1343
1344 If the method count is non-zero, an \texttt{methodptr} array of
1345 \texttt{ic->methodscount} elements is allocated and the method count
1346 value is stored in the particular position of the
1347 \texttt{interfacevftbllength} array:
1348
1349 \begin{verbatim}
1350         v->interfacevftbllength[i] = ic->methodscount;
1351         v->interfacetable[-i] = MNEW(methodptr, ic->methodscount);
1352 \end{verbatim}
1353
1354 For each method of the passed interface, the methods of the passed
1355 target class or interface and all superclass methods, up to
1356 \texttt{java.lang.Object}, are checked if they can overwrite the
1357 interface method via \texttt{method\_canoverwrite}. If the function
1358 returns \texttt{true}, the corresponding function is resolved from the
1359 \texttt{table} field of the \textit{virtual function table} and stored
1360 it the particular position of the \texttt{interfacetable}:
1361
1362 \begin{verbatim}
1363         v->interfacetable[-i][j] = v->table[mi->vftblindex];
1364 \end{verbatim}
1365
1366 The \texttt{class\_addinterface} function is also called recursively
1367 for all interfaces the interface passed implements.
1368
1369 After the interfaces were added and the currently linked class or
1370 interface is not \texttt{java.lang.Object}, the CACAO linker tries to
1371 find a function which name and descriptor matches
1372 \texttt{finalize()V}. If an appropriate function was found and the
1373 function is non-\texttt{static}, it is assigned to the
1374 \texttt{finalizer} field of the \texttt{classinfo} structure. CACAO
1375 does not assign the \texttt{finalize()V} function to
1376 \texttt{java.lang.Object}, because this function is inherited to all
1377 subclasses which do not explicitly implement a \texttt{finalize()V}
1378 method. This would mean, for each instantiated object, which is marked
1379 for collection in the Java Virtual Machine, an empty function would be
1380 called from the garbage collector when a garbage collection takes
1381 place.
1382
1383 The final task of the linker is to compute the \texttt{baseval} and
1384 \texttt{diffval} values from the subclasses of the currently linked
1385 class or interface. These values are used for \textit{runtime type
1386 checking} (described in more detail in
1387 section~\ref{sectionruntimetypechecking}). The calculation is done via
1388 the
1389
1390 \begin{verbatim}
1391         void loader_compute_subclasses(classinfo *c);
1392 \end{verbatim}
1393
1394 function call. This function sets the \texttt{nextsub} and
1395 \texttt{sub} fields of the \texttt{classinfo} structure, resets the
1396 global \texttt{classvalue} variable to zero and calls the
1397
1398 \begin{verbatim}
1399         static void loader_compute_class_values(classinfo *c);
1400 \end{verbatim}
1401
1402 function with \texttt{java.lang.Object} as parameter. First of the
1403 all, the \texttt{baseval} is set of the currently passed class or
1404 interface. The \texttt{baseval} is the global \texttt{classvalue}
1405 variable plus one:
1406
1407 \begin{verbatim}
1408         c->vftbl->baseval = ++classvalue;
1409 \end{verbatim}
1410
1411 Then all subclasses of the currently passed class or interface are
1412 processed. For each subclass found,
1413 \texttt{loader\_compute\_class\_values} is recursively called. After
1414 all subclasses have been processed, the \texttt{diffval} of the
1415 currently passed class or interface is calculated. It is the
1416 difference of the current global \texttt{classvalue} variable value
1417 and the previously \texttt{baseval} set:
1418
1419 \begin{verbatim}
1420         c->vftbl->diffval = classvalue - c->vftbl->baseval;
1421 \end{verbatim}
1422
1423 After the \texttt{baseval} and \texttt{diffval} values are newly
1424 calculated for all classes and interfaces in the Java Virtual Machine,
1425 the internal linker function \texttt{class\_link\_intern} returns the
1426 currently linking \texttt{classinfo} structure pointer, to indicate
1427 that the linker function did not raise an error or exception.
1428
1429
1430 \section{Initialization}
1431 \label{sectioninitialization}
1432
1433 A class or interface can have a \texttt{static} initialization
1434 function called \textit{static class initializer}. The function has
1435 the name \texttt{<clinit>()V}. This function must be invoked before a
1436 \texttt{static} function of the class is called or a \texttt{static}
1437 field is accessed via \texttt{ICMD\_PUTSTATIC} or
1438 \texttt{ICMD\_GETSTATIC}. In CACAO
1439
1440 \begin{verbatim}
1441         classinfo *class_init(classinfo *c);
1442 \end{verbatim}
1443
1444 is responsible for the invocation of the \textit{static class
1445 initializer}. It is, like for class loading and class linking, just a
1446 wrapper function to the main initializing function
1447
1448 \begin{verbatim}
1449         static classinfo *class_init_intern(classinfo *c);
1450 \end{verbatim}
1451
1452 The wrapper function has the following purposes:
1453
1454 \begin{itemize}
1455  \item enter a monitor on the \texttt{classinfo} structure, so that
1456  only one thread can initialize the same class or interface at the
1457  same time
1458
1459  \item check if the class or interface is \texttt{initialized} or
1460  \texttt{initializing}, if one is \texttt{true}, leave the monitor and
1461  return
1462
1463  \item tag the class or interface as \texttt{initializing}
1464
1465  \item call the internal initialization function
1466  \texttt{class\_init\_intern}
1467
1468  \item if the internal initialization function returns
1469  non-\texttt{NULL}, the class or interface is tagged as
1470  \texttt{initialized}
1471
1472  \item reset the \texttt{initializing} flag
1473
1474  \item leave the monitor
1475 \end{itemize}
1476
1477 The intern initializing function should not be called directly,
1478 because of race conditions of concurrent threads. Two or more
1479 different threads could access a \texttt{static} field or call a
1480 \texttt{static} function of an uninitialized class at almost the same
1481 time. This means that each single thread would invoke the
1482 \textit{static class initializer} and this would lead into some
1483 problems.
1484
1485 The CACAO initializer needs to tag the class or interface as currently
1486 initializing. This is done by setting the \texttt{initializing} field
1487 of the \texttt{classinfo} structure to \texttt{true}. CACAO needs this
1488 field in addition to the \texttt{initialized} field for two reasons:
1489
1490 \begin{itemize}
1491  \item Another concurrently running thread can access a
1492  \texttt{static} field of the currently initializing class or
1493  interface. If the class or interface of the \texttt{static} field was
1494  not initialized during code generation, some special code was
1495  generated for the \texttt{ICMD\_PUTSTATIC} and
1496  \texttt{ICMD\_GETSTATIC} intermediate commands. This special code is
1497  a call to an architecture dependent assembler function named
1498  \texttt{asm\_check\_clinit}. Since this function is speed optimized
1499  for the case that the target class is already initialized, it only
1500  checks for the \texttt{initialized} field and does not take care of
1501  any monitor that may have been entered. If the \texttt{initialized}
1502  flag is \texttt{false}, the assembler function calls the
1503  \texttt{class\_init} function where it probably stops at the monitor
1504  enter. Due to this fact, the thread which does the initialization can
1505  not set the \texttt{initialized} flag to \texttt{true} when the
1506  initialization starts, otherwise potential concurrently running
1507  threads would continue their execution although the \textit{static
1508  class initializer} has not finished yet.
1509
1510  \item The thread which is currently \texttt{initializing} the class
1511  or interface can pass the monitor which has been entered and thus
1512  needs to know if this class or interface is currently initialized.
1513 \end{itemize}
1514
1515 Firstly \texttt{class\_init\_intern} checks if the passed class or
1516 interface is loaded and linked. If not, the particular action is
1517 taken. This is just a safety measure, because---CACAO
1518 internally---each class or interface should have been already loaded
1519 and linked before \texttt{class\_init} is called.
1520
1521 Then the superclass, if any specified, is checked if it is already
1522 initialized. If not, the initialization is done immediately. The same
1523 check is performed for each interface in the \texttt{interfaces} array
1524 of the \texttt{classinfo} structure of the current class or interface.
1525
1526 After the superclass and all interfaces are initialized, CACAO tries
1527 to find the \textit{static class initializer} function, where the
1528 method name matches \texttt{<clinit>} and the method descriptor
1529 \texttt{()V}. If no \textit{static class initializer} method is found in the
1530 current class or interface, the \texttt{class\_link\_intern} functions
1531 returns immediately without an error. If a \textit{static class
1532 initializer} method is found, it's called with the architecture
1533 dependent assembler function \texttt{asm\_calljavafunction}.
1534
1535 Exception handling of an exception thrown in an \textit{static class
1536 initializer} is a bit different than usual. It depends on the type of
1537 exception. If the exception thrown is an instance of
1538 \texttt{java.lang.Error}, the \texttt{class\_init\_intern} function
1539 just returns \texttt{NULL}. If the exception thrown is an instance of
1540 \texttt{java.lang.Exception}, the exception is wrapped into a
1541 \texttt{java.lang.ExceptionInInitializerError}. This is done via the
1542 \texttt{new\_exception\_throwable} function call. The newly generated
1543 error is set as exception thrown and the \texttt{class\_init\_intern}
1544 returns \texttt{NULL}.
1545
1546 If no exception occurred in the \textit{static class initializer}, the
1547 internal initializing function returns the current \texttt{classinfo}
1548 structure pointer to indicate, that the initialization was successful.