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