OSDN Git Service

2002-06-04 Michael Koch <konqueror@gmx.de>
[pf3gnuchains/gcc-fork.git] / gcc / java / gcj.texi
1 @\input texinfo @c -*-texinfo-*-
2 @setfilename gcj.info
3 @settitle Guide to GNU gcj
4
5 @c Note: When reading this manual you'll find lots of strange
6 @c circumlocutions like ``compiler for the Java language''.
7 @c This is necessary due to Sun's restrictions on the use of
8 @c the word ``Java'.
9
10 @c When this manual is copyrighted.
11 @set copyrights-gcj 2001, 2002
12
13 @c Versions
14 @set version-gcc 3.1
15 @set which-gcj GCC-@value{version-gcc}
16
17 @macro gcctabopt{body}
18 @code{\body\}
19 @end macro
20
21 @ifinfo
22 @format
23 @dircategory Programming
24 @direntry
25 * Gcj: (gcj).               Ahead-of-time compiler for the Java language
26 @end direntry
27
28 @dircategory Individual utilities
29 @direntry
30 * gcjh: (gcj)Invoking gcjh.
31                             Generate header files from Java class files
32 * jv-scan: (gcj)Invoking jv-scan.
33                             Print information about Java source files
34 * jcf-dump: (gcj)Invoking jcf-dump.
35                             Print information about Java class files
36 * gij: (gcj)Invoking gij.   GNU interpreter for Java bytecode
37 * jv-convert: (gcj)Invoking jv-convert.
38                             Convert file from one encoding to another
39 * rmic: (gcj)Invoking rmic.
40                             Generate stubs for Remote Method Invocation.
41 * rmiregistry: (gcj)Invoking rmiregistry.
42                             The remote object registry.
43 @end direntry
44 @end format
45
46 @c man begin COPYRIGHT
47 Copyright (C) @value{copyrights-gcj} Free Software Foundation, Inc.
48
49 Permission is granted to copy, distribute and/or modify this document
50 under the terms of the GNU Free Documentation License, Version 1.1 or
51 any later version published by the Free Software Foundation; with the
52 Invariant Sections being ``GNU General Public License'', the Front-Cover
53 texts being (a) (see below), and with the Back-Cover Texts being (b)
54 (see below).  A copy of the license is included in the
55 @c man end
56 section entitled
57 ``GNU Free Documentation License''.
58 @ignore
59 @c man begin COPYRIGHT
60 man page gfdl(7).
61 @c man end
62 @end ignore
63
64 (a) The FSF's Front-Cover Text is:
65
66      A GNU Manual
67
68 (b) The FSF's Back-Cover Text is:
69
70      You have freedom to copy and modify this GNU Manual, like GNU
71      software.  Copies published by the Free Software Foundation raise
72      funds for GNU development.
73 @end ifinfo
74
75 @titlepage
76 @title GNU gcj
77 @author Tom Tromey
78
79 @page
80 @vskip 0pt plus 1filll
81 Copyright @copyright{} @value{copyrights-gcj} Free Software Foundation, Inc.
82 @sp 2
83 For the @value{which-gcj} Version*
84 @sp 1
85 Published by the Free Software Foundation @*
86 59 Temple Place - Suite 330@*
87 Boston, MA 02111-1307, USA@*
88 @sp 1
89 Permission is granted to copy, distribute and/or modify this document
90 under the terms of the GNU Free Documentation License, Version 1.1 or
91 any later version published by the Free Software Foundation; with the
92 Invariant Sections being ``GNU General Public License'', the Front-Cover
93 texts being (a) (see below), and with the Back-Cover Texts being (b)
94 (see below).  A copy of the license is included in the section entitled
95 ``GNU Free Documentation License''.
96
97 (a) The FSF's Front-Cover Text is:
98
99      A GNU Manual
100
101 (b) The FSF's Back-Cover Text is:
102
103      You have freedom to copy and modify this GNU Manual, like GNU
104      software.  Copies published by the Free Software Foundation raise
105      funds for GNU development.
106 @end titlepage
107 @contents
108 @page
109
110
111 @node Top
112 @top Introduction
113
114 This manual describes how to use @command{gcj}, the GNU compiler for the
115 Java programming language.  @command{gcj} can generate both @file{.class}
116 files and object files, and it can read both Java source code and
117 @file{.class} files.
118
119 @menu
120 * Copying::              The GNU General Public License
121 * GNU Free Documentation License::
122                         How you can share and copy this manual
123 * Invoking gcj::        Compiler options supported by @command{gcj}
124 * Compatibility::       Compatibility between gcj and other tools for Java
125 * Invoking gcjh::       Generate header files from class files
126 * Invoking jv-scan::    Print information about source files
127 * Invoking jcf-dump::   Print information about class files
128 * Invoking gij::        Interpreting Java bytecodes
129 * Invoking jv-convert:: Converting from one encoding to another
130 * Invoking rmic::        Generate stubs for Remote Method Invocation.
131 * Invoking rmiregistry:: The remote object registry.
132 * About CNI::           Description of the Cygnus Native Interface
133 * Resources::           Where to look for more information
134 @end menu
135
136
137 @include gpl.texi
138
139 @include fdl.texi
140
141
142 @node Invoking gcj
143 @chapter Invoking gcj
144
145 @c man title gcj Ahead-of-time compiler for the Java language
146
147 @ignore
148 @c man begin SYNOPSIS gcj
149 gcj [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
150     [@option{--CLASSPATH}=@var{path}] [@option{--classpath}=@var{path}]
151     [@option{-f}@var{option}@dots{}] [@option{--encoding}=@var{name}]
152     [@option{--main}=@var{classname}] [@option{-D}@var{name}[=@var{value}]@dots{}]
153     [@option{-C}] [@option{--resource} @var{resource-name}] [@option{-d} @var{directory}]
154     [@option{-W}@var{warn}@dots{}]
155     @var{sourcefile}@dots{}
156 @c man end
157 @c man begin SEEALSO gcj
158 gcc(1), gcjh(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
159 and the Info entries for @file{gcj} and @file{gcc}.
160 @c man end
161 @end ignore
162
163 @c man begin DESCRIPTION gcj
164
165 As @command{gcj} is just another front end to @command{gcc}, it supports many
166 of the same options as gcc.  @xref{Option Summary, , Option Summary,
167 gcc, Using the GNU Compiler Collection (GCC)}.  This manual only documents the
168 options specific to @command{gcj}.
169
170 @c man end
171
172 @menu
173 * Input and output files::
174 * Input Options::               How gcj finds files
175 * Encodings::                   Options controlling source file encoding
176 * Warnings::                    Options controlling warnings specific to gcj
177 * Code Generation::             Options controlling the output of gcj
178 * Configure-time Options::      Options you won't use
179 @end menu
180
181 @c man begin OPTIONS gcj
182
183 @node Input and output files
184 @section Input and output files
185
186 A @command{gcj} command is like a @command{gcc} command, in that it
187 consists of a number of options and file names.  The following kinds
188 of input file names are supported:
189
190 @table @gcctabopt
191 @item @var{file}.java
192 Java source files.
193 @item @var{file}.class
194 Java bytecode files.
195 @item @var{file}.zip
196 @itemx @var{file}.jar
197 An archive containing one or more @code{.class} files, all of
198 which are compiled.  The archive may be compressed.
199 @item @@@var{file}
200 A file containing a whitespace-separated list of input file names.
201 (Currently, these must all be @code{.java} source files, but that
202 may change.)
203 Each named file is compiled, just as if it had been on the command line.
204 @item @var{library}.a
205 @itemx @var{library}.so
206 @itemx -l@var{libname}
207 Libraries to use when linking.  See the @command{gcc} manual.
208 @end table
209
210 You can specify more than one input file on the @command{gcj} command line,
211 in which case they will all be compiled.  If you specify a
212 @code{-o @var{FILENAME}}
213 option, all the input files will be compiled together, producing a
214 single output file, named @var{FILENAME}.
215 This is allowed even when using @code{-S} or @code{-c},
216 but not when using @code{-C} or @code{--resource}.
217 (This is an extension beyond the what plain @command{gcc} allows.)
218 (If more than one input file is specified, all must currently
219 be @code{.java} files, though we hope to fix this.)
220
221 @node Input Options
222 @section Input Options
223
224 @cindex class path
225
226 @command{gcj} has options to control where it looks to find files it needs.
227 For instance, @command{gcj} might need to load a class that is referenced
228 by the file it has been asked to compile.  Like other compilers for the
229 Java language, @command{gcj} has a notion of a @dfn{class path}.  There are
230 several options and environment variables which can be used to
231 manipulate the class path.  When @command{gcj} looks for a given class, it
232 searches the class path looking for matching @file{.class} or
233 @file{.java} file.  @command{gcj} comes with a built-in class path which
234 points at the installed @file{libgcj.jar}, a file which contains all the
235 standard classes.
236
237 In the below, a directory or path component can refer either to an
238 actual directory on the filesystem, or to a @file{.zip} or @file{.jar}
239 file, which @command{gcj} will search as if it is a directory.
240
241 @table @gcctabopt
242 @item -I@var{dir}
243 All directories specified by @code{-I} are kept in order and prepended
244 to the class path constructed from all the other options.  Unless
245 compatibility with tools like @code{javac} is important, we recommend
246 always using @code{-I} instead of the other options for manipulating the
247 class path.
248
249 @item --classpath=@var{path}
250 This sets the class path to @var{path}, a colon-separated list of paths
251 (on Windows-based systems, a semicolon-separate list of paths).
252 This does not override the builtin (``boot'') search path.
253
254 @item --CLASSPATH=@var{path}
255 Deprecated synonym for @code{--classpath}.
256
257 @item --bootclasspath=@var{path}
258 Where to find the standard builtin classes, such as @code{java.lang.String}.
259
260 @item --extdirs=@var{path}
261 For each directory in the @var{path}, place the contents of that
262 directory at the end of the class path.
263
264 @item CLASSPATH
265 This is an environment variable which holds a list of paths.
266 @end table
267
268 The final class path is constructed like so:
269
270 @itemize @bullet
271 @item
272 First come all directories specified via @code{-I}.
273
274 @item
275 If @option{--classpath} is specified, its value is appended.
276 Otherwise, if the @code{CLASSPATH} environment variable is specified,
277 then its value is appended.
278 Otherwise, the current directory (@code{"."}) is appended.
279
280 @item
281 If @code{--bootclasspath} was specified, append its value.
282 Otherwise, append the built-in system directory, @file{libgcj.jar}.
283
284 @item
285 Finaly, if @code{--extdirs} was specified, append the contents of the
286 specified directories at the end of the class path.  Otherwise, append
287 the contents of the built-in extdirs at @code{$(prefix)/share/java/ext}.
288 @end itemize
289
290 The classfile built by @command{gcj} for the class @code{java.lang.Object}
291 (and placed in @code{libgcj.jar}) contains a special zero length
292 attribute @code{gnu.gcj.gcj-compiled}. The compiler looks for this
293 attribute when loading @code{java.lang.Object} and will report an error
294 if it isn't found, unless it compiles to bytecode (the option
295 @code{-fforce-classes-archive-check} can be used to override this
296 behavior in this particular case.)
297
298 @table @gcctabopt
299 @item -fforce-classes-archive-check
300 This forces the compiler to always check for the special zero length
301 attribute @code{gnu.gcj.gcj-compiled} in @code{java.lang.Object} and
302 issue an error if it isn't found.
303 @end table
304
305 @node Encodings
306 @section Encodings
307
308 The Java programming language uses Unicode throughout.  In an effort to
309 integrate well with other locales, @command{gcj} allows @file{.java} files
310 to be written using almost any encoding.  @command{gcj} knows how to
311 convert these encodings into its internal encoding at compile time.
312
313 You can use the @code{--encoding=@var{NAME}} option to specify an
314 encoding (of a particular character set) to use for source files.  If
315 this is not specified, the default encoding comes from your current
316 locale.  If your host system has insufficient locale support, then
317 @command{gcj} assumes the default encoding to be the @samp{UTF-8} encoding
318 of Unicode.
319
320 To implement @code{--encoding}, @command{gcj} simply uses the host
321 platform's @code{iconv} conversion routine.  This means that in practice
322 @command{gcj} is limited by the capabilities of the host platform.
323
324 The names allowed for the argument @code{--encoding} vary from platform
325 to platform (since they are not standardized anywhere).  However,
326 @command{gcj} implements the encoding named @samp{UTF-8} internally, so if
327 you choose to use this for your source files you can be assured that it
328 will work on every host.
329
330
331 @node Warnings
332 @section Warnings
333
334 @command{gcj} implements several warnings.  As with other generic
335 @command{gcc} warnings, if an option of the form @code{-Wfoo} enables a
336 warning, then @code{-Wno-foo} will disable it.  Here we've chosen to
337 document the form of the warning which will have an effect -- the
338 default being the opposite of what is listed.
339
340 @table @gcctabopt
341 @item -Wredundant-modifiers
342 With this flag, @command{gcj} will warn about redundant modifiers.  For
343 instance, it will warn if an interface method is declared @code{public}.
344
345 @item -Wextraneous-semicolon
346 This causes @command{gcj} to warn about empty statements.  Empty statements
347 have been deprecated.
348
349 @item -Wno-out-of-date
350 This option will cause @command{gcj} not to warn when a source file is
351 newer than its matching class file.  By default @command{gcj} will warn
352 about this.
353
354 @item -Wunused
355 This is the same as @command{gcc}'s @code{-Wunused}.
356
357 @item -Wall
358 This is the same as @code{-Wredundant-modifiers -Wextraneous-semicolon
359 -Wunused}.
360 @end table
361
362
363 @node Code Generation
364 @section Code Generation
365
366 In addition to the many @command{gcc} options controlling code generation,
367 @command{gcj} has several options specific to itself.
368
369 @table @gcctabopt
370 @item --main=@var{CLASSNAME}
371 This option is used when linking to specify the name of the class whose
372 @code{main} method should be invoked when the resulting executable is
373 run.  @footnote{The linker by default looks for a global function named
374 @code{main}.  Since Java does not have global functions, and a
375 collection of Java classes may have more than one class with a
376 @code{main} method, you need to let the linker know which of those
377 @code{main} methods it should invoke when starting the application.}
378
379 @item -D@var{name}[=@var{value}]
380 This option can only be used with @code{--main}.  It defines a system
381 property named @var{name} with value @var{value}.  If @var{value} is not
382 specified then it defaults to the empty string.  These system properties
383 are initialized at the program's startup and can be retrieved at runtime
384 using the @code{java.lang.System.getProperty} method.
385
386 @item -C
387 This option is used to tell @command{gcj} to generate bytecode
388 (@file{.class} files) rather than object code.
389
390 @item --resource @var{resource-name}
391 This option is used to tell @command{gcj} to compile the contents of a
392 given file to object code so it may be accessed at runtime with the core
393 protocol handler as @samp{core:/@var{resource-name}}.  Note that
394 @var{resource-name} is the name of the resource as found at runtime; for
395 instance, it could be used in a call to @code{ResourceBundle.getBundle}.
396 The actual file name to be compiled this way must be specified
397 separately.
398
399 @item -d @var{directory}
400 When used with @code{-C}, this causes all generated @file{.class} files
401 to be put in the appropriate subdirectory of @var{directory}.  By
402 default they will be put in subdirectories of the current working
403 directory.
404
405 @item -fno-bounds-check
406 By default, @command{gcj} generates code which checks the bounds of all
407 array indexing operations.  With this option, these checks are omitted, which
408 can improve performance for code that uses arrays extensively.  Note that this 
409 can result in unpredictable behavior if the code in question actually does 
410 violate array bounds constraints.  It is safe to use this option if you are 
411 sure that your code will never throw an @code{ArrayIndexOutOfBoundsException}.
412
413 @item -fno-store-check
414 Don't generate array store checks.  When storing objects into arrays, a runtime
415 check is normally generated in order to ensure that the object is assignment
416 compatible with the component type of the array (which may not be known
417 at compile-time).  With this option, these checks are omitted.  This can 
418 improve performance for code which stores objects into arrays frequently.
419 It is safe to use this option if you are sure your code will never throw an 
420 @code{ArrayStoreException}.
421
422 @item -fjni
423 With @command{gcj} there are two options for writing native methods: CNI
424 and JNI@.  By default @command{gcj} assumes you are using CNI@.  If you are
425 compiling a class with native methods, and these methods are implemented
426 using JNI, then you must use @code{-fjni}.  This option causes
427 @command{gcj} to generate stubs which will invoke the underlying JNI
428 methods.
429
430 @item -fno-optimize-static-class-initialization
431 When the optimization level is greather or equal to @code{-O2},
432 @command{gcj} will try to optimize the way calls into the runtime are made
433 to initialize static classes upon their first use (this optimization
434 isn't carried out if @code{-C} was specified.) When compiling to native
435 code, @code{-fno-optimize-static-class-initialization} will turn this
436 optimization off, regardless of the optimization level in use.
437 @end table
438
439
440 @node Configure-time Options
441 @section Configure-time Options
442
443 Some @command{gcj} code generations options affect the resulting ABI, and
444 so can only be meaningfully given when @code{libgcj}, the runtime
445 package, is configured.  @code{libgcj} puts the appropriate options from
446 this group into a @samp{spec} file which is read by @command{gcj}.  These
447 options are listed here for completeness; if you are using @code{libgcj}
448 then you won't want to touch these options.
449
450 @table @gcctabopt
451 @item -fuse-boehm-gc
452 This enables the use of the Boehm GC bitmap marking code.  In particular
453 this causes @command{gcj} to put an object marking descriptor into each
454 vtable.
455
456 @item -fhash-synchronization
457 By default, synchronization data (the data used for @code{synchronize},
458 @code{wait}, and @code{notify}) is pointed to by a word in each object.
459 With this option @command{gcj} assumes that this information is stored in a
460 hash table and not in the object itself.
461
462 @item -fuse-divide-subroutine
463 On some systems, a library routine is called to perform integer
464 division.  This is required to get exception handling correct when
465 dividing by zero.
466
467 @item -fcheck-references
468 On some systems it's necessary to insert inline checks whenever
469 accessing an object via a reference.  On other systems you won't need
470 this because null pointer accesses are caught automatically by the
471 processor.
472 @end table
473
474 @c man end
475
476 @node Compatibility
477 @chapter Compatibility with the Java Platform
478
479 As we believe it is important that the Java platform not be fragmented,
480 @command{gcj} and @code{libgcj} try to conform to the relevant Java
481 specifications.  However, limited manpower and incomplete and unclear
482 documentation work against us.  So, there are caveats to using
483 @command{gcj}.
484
485 This list of compatibility issues is by no means complete.
486
487 @itemize @bullet
488 @item
489 @command{gcj} implements the JDK 1.1 language.  It supports inner classes,
490 though these are known to still be buggy.  It does not yet support the
491 Java 2 @code{strictfp} keyword (it recognizes the keyword but ignores
492 it).
493
494 @item
495 @code{libgcj} is largely compatible with the JDK 1.2 libraries.
496 However, @code{libgcj} is missing many packages, most notably
497 @code{java.awt}.  There are also individual missing classes and methods.
498 We currently do not have a list showing differences between
499 @code{libgcj} and the Java 2 platform.
500
501 @item
502 Sometimes the @code{libgcj} implementation of a method or class differs
503 from the JDK implementation.  This is not always a bug.  Still, if it
504 affects you, it probably makes sense to report it so that we can discuss
505 the appropriate response.
506 @end itemize
507
508
509 @node Invoking gcjh
510 @chapter Invoking gcjh
511
512 @c man title gcjh generate header files from Java class files
513
514 @c man begin DESCRIPTION gcjh
515
516 The @code{gcjh} program is used to generate header files from class
517 files.  It can generate both CNI and JNI header files, as well as stub
518 implementation files which can be used as a basis for implementing the
519 required native methods.
520
521 @c man end
522
523 @ignore
524 @c man begin SYNOPSIS gcjh
525 gcjh [@option{-stubs}] [@option{-jni}]
526     [@option{-add} @var{text}] [@option{-append} @var{text}] [@option{-friend} @var{text}]
527     [@option{-preprend} @var{text}]
528     [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
529     [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
530     [@option{-o} @var{file}] [@option{-td} @var{dir}]
531     [@option{-M}] [@option{-MM}] [@option{-MD}] [@option{-MMD}]
532     [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
533     @var{classname}@dots{}
534 @c man end
535 @c man begin SEEALSO gcjh
536 gcc(1), gcj(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
537 and the Info entries for @file{gcj} and @file{gcc}.
538 @c man end
539 @end ignore
540
541 @c man begin OPTIONS gcjh
542
543 @table @gcctabopt
544 @item -stubs
545 This causes @code{gcjh} to generate stub files instead of header files.
546 By default the stub file will be named after the class, with a suffix of
547 @samp{.cc}.  In JNI mode, the default output file will have the suffix
548 @samp{.c}.
549
550 @item -jni
551 This tells @code{gcjh} to generate a JNI header or stub.  By default,
552 CNI headers are generated.
553
554 @item -add @var{text}
555 Inserts @var{text} into the class body.  This is ignored in JNI mode.
556
557 @item -append @var{text}
558 Inserts @var{text} into the header file after the class declaration.
559 This is ignored in JNI mode.
560
561 @item -friend @var{text}
562 Inserts @var{text} into the class as a @code{friend} declaration.
563 This is ignored in JNI mode.
564
565 @item -prepend @var{text}
566 Inserts @var{text} into the header file before the class declaration.
567 This is ignored in JNI mode.
568
569 @item --classpath=@var{path}
570 @itemx --CLASSPATH=@var{path}
571 @itemx -I@var{directory}
572 @itemx -d @var{directory}
573 @itemx -o @var{file}
574 These options are all identical to the corresponding @command{gcj} options.
575
576 @item -o @var{file}
577 Sets the output file name.  This cannot be used if there is more than
578 one class on the command line.
579
580 @item -td @var{directory}
581 Sets the name of the directory to use for temporary files.
582
583 @item -M
584 Print all dependencies to stdout; suppress ordinary output.
585
586 @item -MM
587 Print non-system dependencies to stdout; suppress ordinary output.
588
589 @item -MD
590 Print all dependencies to stdout.
591
592 @item -MMD
593 Print non-system dependencies to stdout.
594
595 @item --help
596 Print help about @code{gcjh} and exit.  No further processing is done.
597
598 @item --version
599 Print version information for @code{gcjh} and exit.  No further
600 processing is done.
601
602 @item -v, --verbose
603 Print extra information while running.
604 @end table
605
606 All remaining options are considered to be names of classes.
607
608 @c man end
609
610 @node Invoking jv-scan
611 @chapter Invoking jv-scan
612
613 @c man title jv-scan print information about Java source file
614
615 @c man begin DESCRIPTION jv-scan
616
617 The @code{jv-scan} program can be used to print information about a Java
618 source file (@file{.java} file).
619
620 @c man end
621
622 @ignore
623 @c man begin SYNOPSIS jv-scan
624 jv-scan [@option{--complexity}] [@option{--encoding}=@var{name}]
625     [@option{--print-main}] [@option{--list-class}] [@option{--list-filename}]
626     [@option{--version}] [@option{--help}]
627     [@option{-o} @var{file}] @var{inputfile}@dots{}
628 @c man end
629 @c man begin SEEALSO jv-scan
630 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
631 and the Info entries for @file{gcj} and @file{gcc}.
632 @c man end
633 @end ignore
634
635 @c man begin OPTIONS jv-scan
636
637 @table @gcctabopt
638 @item --complexity
639 This prints a complexity measure, related to cyclomatic complexity, for
640 each input file.
641
642 @item --encoding=@var{name}
643 This works like the corresponding @command{gcj} option.
644
645 @item --print-main
646 This prints the name of the class in this file containing a @code{main}
647 method.
648
649 @item --list-class
650 This lists the names of all classes defined in the input files.
651
652 @item --list-filename
653 If @code{--list-class} is given, this option causes @code{jv-scan} to
654 also print the name of the file in which each class was found.
655
656 @item -o @var{file}
657 Print output to the named file.
658
659 @item --help
660 Print help, then exit.
661
662 @item --version
663 Print version number, then exit.
664 @end table
665
666 @c man end
667
668 @node Invoking jcf-dump
669 @chapter Invoking jcf-dump
670
671 @c man title jcf-dump print information about Java class files
672
673 @ignore
674 @c man begin SYNOPSIS jcf-dump
675 jcf-dump [@option{-c}] [@option{--javap}]
676     [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
677     [@option{-I}@var{dir}@dots{}] [@option{-o} @var{file}]
678     [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
679     @var{classname}@dots{}
680 @c man end
681 @c man begin SEEALSO jcf-dump
682 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
683 and the Info entries for @file{gcj} and @file{gcc}.
684 @c man end
685 @end ignore
686
687 @c man begin DESCRIPTION jcf-dump
688
689 This is a class file examiner, similar to @code{javap}.  It will print
690 information about a number of classes, which are specifed by class name
691 or file name.
692
693 @c man end
694
695 @c man begin OPTIONS jcf-dump
696
697 @table @gcctabopt
698 @item -c
699 Disassemble method bodies.  By default method bodies are not printed.
700
701 @item --javap
702 Generate output in @code{javap} format.  The implementation of this
703 feature is very incomplete.
704
705 @item --classpath=@var{path}
706 @itemx --CLASSPATH=@var{path}
707 @itemx -I@var{directory}
708 @itemx -o @var{file}
709 These options as the same as the corresponding @command{gcj} options.
710
711 @item --help
712 Print help, then exit.
713
714 @item --version
715 Print version number, then exit.
716
717 @item -v, --verbose
718 Print extra information while running.
719 @end table
720
721 @c man end
722
723 @node Invoking gij
724 @chapter Invoking gij
725
726 @c man title gij GNU interpreter for Java bytecode
727
728 @ignore
729 @c man begin SYNOPSIS gij
730 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
731
732 gij [@option{-jar}] [@option{OPTION}] @dots{} @var{CLASS} [@var{ARGS}@dots{}]
733   [@option{-D}@var{name}[=@var{value}]@dots{}]
734   [@option{-ms=}@var{number}] [@option{-mx=}@var{number}]
735   [@option{--version}] [@option{--help}]
736 @c man end
737 @c man begin SEEALSO gij
738 gcc(1), gcj(1), gcjh(1), jv-scan(1), jcf-dump(1), gfdl(7),
739 and the Info entries for @file{gcj} and @file{gcc}.
740 @c man end
741 @end ignore
742
743 @c man begin DESCRIPTION gij
744
745 @code{gij} is a Java bytecode interpreter included with @code{libgcj}.
746 @code{gij} is not available on every platform; porting it requires a
747 small amount of assembly programming which has not been done for all the
748 targets supported by @command{gcj}.
749
750 The primary argument to @code{gij} is the name of a class or, with
751 @code{-jar}, a jar file.  Options before this argument are interpreted
752 by @code{gij}; remaining options are passed to the interpreted program.
753
754 If a class name is specified and this class does not have a @code{main}
755 method with the appropriate signature (a @code{static void} method with
756 a @code{String[]} as its sole argument), then @code{gij} will print an
757 error and exit.
758
759 If a jar file is specified then @code{gij} will use information in it to
760 determine which class' @code{main} method will be invoked.
761
762 @code{gij} will invoke the @code{main} method with all the remaining
763 command-line options.
764
765 Note that @code{gij} is not limited to interpreting code.  Because
766 @code{libgcj} includes a class loader which can dynamically load shared
767 objects, it is possible to give @code{gij} the name of a class which has
768 been compiled and put into a shared library on the class path.
769
770 @c man end
771
772 @c man begin OPTIONS gij
773
774 @table @gcctabopt
775 @item -D@var{name}[=@var{value}]
776 This defines a system property named @var{name} with value @var{value}.
777 If @var{value} is not specified then it defaults to the empty string.
778 These system properties are initialized at the program's startup and can
779 be retrieved at runtime using the @code{java.lang.System.getProperty}
780 method.
781
782 @item -ms=@var{number}
783 This sets the initial heap size.
784
785 @item -mx=@var{number}
786 This sets the maximum heap size.
787
788 @item -jar
789 This indicates that the name passed to @code{gij} should be interpreted
790 as the name of a jar file, not a class.
791
792 @item --help
793 Print help, then exit.
794
795 @item --version
796 Print version number, then exit.
797 @end table
798
799 @c man end
800
801 @node Invoking jv-convert
802 @chapter Invoking jv-convert
803
804 @c man title jv-convert Convert file from one encoding to another
805
806 @c man begin SYNOPSIS jv-convert
807 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
808 @ignore
809
810   [@option{--encoding} @var{name}]
811   [@option{--from} @var{name}]
812   [@option{--to} @var{name}]
813   [@option{-i} @var{file}] [@option{-o} @var{file}]
814   [@option{--reverse}] [@option{--help}] [@option{--version}]
815 @end ignore
816 @c man end
817
818 @c man begin DESCRIPTION jv-convert
819
820 @command{jv-convert} is a utility included with @code{libgcj} which
821 converts a file from one encoding to another.  It is similar to the Unix
822 @command{iconv} utility.
823
824 The encodings supported by @command{jv-convert} are platform-dependent.
825 Currently there is no way to get a list of all supported encodings.
826
827 @c man end
828
829 @c man begin OPTIONS jv-convert
830
831 @table @gcctabopt
832 @item --encoding @var{name}
833 @itemx --from @var{name}
834 Use @var{name} as the input encoding.  The default is the current
835 locale's encoding.
836
837 @item --to @var{name}
838 Use @var{name} as the output encoding.  The default is the
839 @code{JavaSrc} encoding; this is ASCII with @samp{\u} escapes for
840 non-ASCII characters.
841
842 @item -i @var{file}
843 Read from @var{file}.  The default is to read from standard input.
844
845 @item -o @var{file}
846 Write to @var{file}.  The default is to write to standard output.
847
848 @item --reverse
849 Swap the input and output encodings.
850
851 @item --help
852 Print a help message, then exit.
853
854 @item --version
855 Print version information, then exit.
856 @end table
857
858 @c man end
859
860 @node Invoking rmic
861 @chapter Invoking rmic
862
863 @c man title rmic Generate stubs for Remote Method Invocation
864
865 @c man begin SYNOPSIS rmic
866 @command{rmic} [@option{OPTION}] @dots{} @var{class} @dots{}
867 @ignore
868   [@option{-keep}]
869   [@option{-keepgenerated}]
870   [@option{-v1.1}]
871   [@option{-vcompat}]
872   [@option{-v1.2}]
873   [@option{-nocompile}]
874   [@option{-verbose}]
875   [@option{-d} @var{directory}]
876   [@option{-help}]
877   [@option{-version}]
878 @end ignore
879 @c man end
880
881 @c man begin DESCRIPTION rmic
882
883 @command{rmic} is a utility included with @code{libgcj} which generates
884 stubs for remote objects.
885
886 @c FIXME: Add real information here.
887 @c This really isn't much more than the --help output.
888
889 Note that this program isn't yet fully compatible with the JDK
890 @command{rmic}.  Some options, such as @option{-classpath}, are
891 recognized but currently ignored.  We have left these options
892 undocumented for now.
893
894 Long options can also be given with a GNU-style leading @samp{--}.  For
895 instance, @option{--help} is accepted.
896
897 @c man end
898
899 @c man begin OPTIONS rmic
900
901 @table @gcctabopt
902 @item -keep
903 @itemx -keepgenerated
904 By default, @command{rmic} deletes intermediate files.  Either of these
905 options causes it not to delete such files.
906
907 @item -v1.1
908 Cause @command{rmic} to create stubs and skeletons for the 1.1
909 protocol version.
910
911 @item -vcompat
912 Cause @command{rmic} to create stubs and skeletons compatible with both
913 the 1.1 and 1.2 protocol versions.  This is the default.
914
915 @item -v1.2
916 Cause @command{rmic} to create stubs and skeletons for the 1.2
917 protocol version.
918
919 @item -nocompile
920 Don't compile the generated files.
921
922 @item -verbose
923 Print information about what @command{rmic} is doing.
924
925 @item -d @var{directory}
926 Put output files in @var{directory}.  By default the files are put in
927 the current working directory.
928
929 @item -help
930 Print a help message, then exit.
931
932 @item -version
933 Print version information, then exit.
934 @end table
935
936 @c man end
937
938
939 @node Invoking rmiregistry
940 @chapter Invoking rmiregistry
941
942 @c man title rmiregistry Remote object registry
943
944 @c man begin SYNOPSIS rmiregistry
945 @command{rmic} [@option{OPTION}] @dots{} [@var{port}]
946 @ignore
947   [@option{--help}]
948   [@option{--version}]
949 @end ignore
950 @c man end
951
952 @c man begin DESCRIPTION rmiregistry
953
954 @command{rmiregistry} starts a remote object registry on the current
955 host.  If no port number is specified, then port 1099 is used.
956
957 @c FIXME: Add real information here.
958 @c This really isn't much more than the --help output.
959
960 @c man end
961
962 @c man begin OPTIONS rmiregistry
963
964 @table @gcctabopt
965 @item --help
966 Print a help message, then exit.
967
968 @item --version
969 Print version information, then exit.
970 @end table
971
972 @c man end
973
974
975 @node About CNI
976 @chapter About CNI
977
978 This documents CNI, the Cygnus Native Interface,
979 which is is a convenient way to write Java native methods using C++.
980 This is a more efficient, more convenient, but less portable
981 alternative to the standard JNI (Java Native Interface).
982
983 @menu
984 * Basic concepts::              Introduction to using CNI@.
985 * Packages::                    How packages are mapped to C++.
986 * Primitive types::             Handling Java types in C++.
987 * Interfaces::                  How Java interfaces map to C++.
988 * Objects and Classes::         C++ and Java classes.
989 * Class Initialization::        How objects are initialized.
990 * Object allocation::           How to create Java objects in C++.
991 * Arrays::                      Dealing with Java arrays in C++.
992 * Methods::                     Java methods in C++.
993 * Strings::                     Information about Java Strings.
994 * Mixing with C++::             How CNI can interoperate with C++.
995 * Exception Handling::          How exceptions are handled.
996 * Synchronization::             Synchronizing between Java and C++.
997 * Invocation::                  Starting the Java runtime from C++.
998 * Reflection::                  Using reflection from C++.
999 @end menu
1000
1001
1002 @node Basic concepts
1003 @section Basic concepts
1004
1005 In terms of languages features, Java is mostly a subset
1006 of C++.  Java has a few important extensions, plus a powerful standard
1007 class library, but on the whole that does not change the basic similarity.
1008 Java is a hybrid object-oriented language, with a few native types,
1009 in addition to class types.  It is class-based, where a class may have
1010 static as well as per-object fields, and static as well as instance methods.
1011 Non-static methods may be virtual, and may be overloaded.  Overloading is
1012 resolved at compile time by matching the actual argument types against
1013 the parameter types.  Virtual methods are implemented using indirect calls
1014 through a dispatch table (virtual function table).  Objects are
1015 allocated on the heap, and initialized using a constructor method.
1016 Classes are organized in a package hierarchy.
1017
1018 All of the listed attributes are also true of C++, though C++ has
1019 extra features (for example in C++ objects may be allocated not just
1020 on the heap, but also statically or in a local stack frame).  Because
1021 @command{gcj} uses the same compiler technology as G++ (the GNU
1022 C++ compiler), it is possible to make the intersection of the two
1023 languages use the same ABI (object representation and calling
1024 conventions).  The key idea in CNI is that Java objects are C++
1025 objects, and all Java classes are C++ classes (but not the other way
1026 around).  So the most important task in integrating Java and C++ is to
1027 remove gratuitous incompatibilities.
1028
1029 You write CNI code as a regular C++ source file.  (You do have to use
1030 a Java/CNI-aware C++ compiler, specifically a recent version of G++.)
1031
1032 @noindent A CNI C++ source file must have:
1033
1034 @example
1035 #include <gcj/cni.h>
1036 @end example
1037
1038 @noindent and then must include one header file for each Java class it uses, e.g.:
1039
1040 @example
1041 #include <java/lang/Character.h>
1042 #include <java/util/Date.h>
1043 #include <java/lang/IndexOutOfBoundsException.h>
1044 @end example
1045
1046 @noindent These header files are automatically generated by @code{gcjh}.
1047
1048
1049 CNI provides some functions and macros to make using Java objects and
1050 primitive types from C++ easier.  In general, these CNI functions and
1051 macros start with the @code{Jv} prefix, for example the function
1052 @code{JvNewObjectArray}.  This convention is used to avoid conflicts
1053 with other libraries.  Internal functions in CNI start with the prefix
1054 @code{_Jv_}.  You should not call these; if you find a need to, let us
1055 know and we will try to come up with an alternate solution.  (This
1056 manual lists @code{_Jv_AllocBytes} as an example; CNI should instead
1057 provide a @code{JvAllocBytes} function.)
1058
1059
1060 @subsection Limitations
1061
1062 Whilst a Java class is just a C++ class that doesn't mean that you are
1063 freed from the shackles of Java, a @acronym{CNI} C++ class must adhere to the
1064 rules of the Java programming language.
1065
1066 For example: it is not possible to declare a method in a CNI class
1067 that will take a C string (@code{char*}) as an argument, or to declare a
1068 member variable of some non-Java datatype.
1069
1070
1071 @node Packages
1072 @section Packages
1073
1074 The only global names in Java are class names, and packages.  A
1075 @dfn{package} can contain zero or more classes, and also zero or more
1076 sub-packages.  Every class belongs to either an unnamed package or a
1077 package that has a hierarchical and globally unique name.
1078
1079 A Java package is mapped to a C++ @dfn{namespace}.  The Java class
1080 @code{java.lang.String} is in the package @code{java.lang}, which is a
1081 sub-package of @code{java}.  The C++ equivalent is the class
1082 @code{java::lang::String}, which is in the namespace @code{java::lang}
1083 which is in the namespace @code{java}.
1084
1085 @noindent Here is how you could express this:
1086
1087 @example
1088 (// @r{Declare the class(es), possibly in a header file:}
1089 namespace java @{
1090   namespace lang @{
1091     class Object;
1092     class String;
1093     ...
1094   @}
1095 @}
1096
1097 class java::lang::String : public java::lang::Object
1098 @{
1099   ...
1100 @};
1101 @end example
1102
1103 @noindent The @code{gcjh} tool automatically generates the nessary namespace
1104 declarations.
1105
1106
1107 @subsection Leaving out package names
1108
1109 Always using the fully-qualified name of a java class can be
1110 tiresomely verbose.  Using the full qualified name also ties the code
1111 to a single package making code changes necessary should the class
1112 move from one package to another.  The Java @code{package} declaration
1113 specifies that the following class declarations are in the named
1114 package, without having to explicitly name the full package
1115 qualifiers.  The @code{package} declaration can be
1116 followed by zero or more @code{import} declarations, which
1117 allows either a single class or all the classes in a package to be
1118 named by a simple identifier.  C++ provides something similar with the
1119 @code{using} declaration and directive.
1120
1121 @noindent In Java:
1122
1123 @example
1124 import @var{package-name}.@var{class-name};
1125 @end example
1126
1127 @noindent allows the program text to refer to @var{class-name} as a shorthand for 
1128 the fully qualified name: @code{@var{package-name}.@var{class-name}}.
1129
1130
1131 @noindent To achieve the same effect C++, you have to do this:
1132
1133 @example
1134 using @var{package-name}::@var{class-name};
1135 @end example
1136
1137
1138 @noindent Java can also cause imports on demand, like this:
1139
1140 @example
1141 import @var{package-name}.*;
1142 @end example
1143
1144 @noindent Doing this allows any class from the package @var{package-name} to be
1145 refered to only by its class-name within the program text.
1146
1147
1148 @noindent The same effect can be achieved in C++ like this:
1149
1150 @example
1151 using namespace @var{package-name};
1152 @end example
1153
1154
1155 @node Primitive types
1156 @section Primitive types
1157
1158 Java provides 8 @dfn{primitives} types which represent integers, floats, 
1159 characters and booleans (and also the void type).  C++ has its own
1160 very similar concrete types.  Such types in C++ however are not always
1161 implemented in the same way (an int might be 16, 32 or 64 bits for example) 
1162 so CNI provides a special C++ type for each primitive Java type:
1163
1164 @multitable @columnfractions .20 .25 .60
1165 @item @strong{Java type}   @tab @strong{C/C++ typename} @tab @strong{Description}
1166 @item @code{char}        @tab @code{jchar}          @tab 16 bit Unicode character
1167 @item @code{boolean}     @tab @code{jboolean}       @tab logical (true or false) values
1168 @item @code{byte}        @tab @code{jbyte}          @tab 8-bit signed integer
1169 @item @code{short}       @tab @code{jshort}         @tab 16 bit signed integer
1170 @item @code{int}         @tab @code{jint}           @tab 32 bit signed integer
1171 @item @code{long}        @tab @code{jlong}          @tab 64 bit signed integer
1172 @item @code{float}       @tab @code{jfloat}         @tab 32 bit IEEE floating point number
1173 @item @code{double}      @tab @code{jdouble}        @tab 64 bit IEEE floating point number
1174 @item @code{void}        @tab @code{void}           @tab no value
1175 @end multitable
1176
1177 When refering to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1178 to avoid disappointment.
1179
1180
1181 @subsection Reference types associated with primitive types
1182
1183 In Java each primitive type has an associated reference type, 
1184 e.g.: @code{boolean} has an associated @code{java.lang.Boolean} class.
1185 In order to make working with such classes easier GCJ provides the macro
1186 @code{JvPrimClass}:
1187
1188 @deffn macro JvPrimClass type
1189 Return a pointer to the @code{Class} object corresponding to the type supplied.
1190
1191 @example
1192 JvPrimClass(void) @result{} java.lang.Void.TYPE
1193 @end example
1194
1195 @end deffn
1196
1197
1198 @node Interfaces
1199 @section Interfaces
1200
1201 A Java class can @dfn{implement} zero or more
1202 @dfn{interfaces}, in addition to inheriting from
1203 a single base class. 
1204
1205 @acronym{CNI} allows CNI code to implement methods of interfaces.
1206 You can also call methods through interface references, with some
1207 limitations.
1208
1209 @acronym{CNI} doesn't understand interface inheritance at all yet.  So,
1210 you can only call an interface method when the declared type of the
1211 field being called matches the interface which declares that
1212 method.  The workaround is to cast the interface reference to the right
1213 superinterface.
1214  
1215 For example if you have: 
1216
1217 @example 
1218 interface A 
1219 @{ 
1220   void a(); 
1221 @} 
1222  
1223 interface B extends A 
1224 @{ 
1225   void b(); 
1226 @} 
1227 @end example
1228  
1229 and declare a variable of type @code{B} in C++, you can't call
1230 @code{a()} unless you cast it to an @code{A} first.
1231
1232 @node Objects and Classes
1233 @section Objects and Classes
1234
1235 @subsection Classes
1236
1237 All Java classes are derived from @code{java.lang.Object}.  C++ does
1238 not have a unique root class, but we use the C++ class
1239 @code{java::lang::Object} as the C++ version of the
1240 @code{java.lang.Object} Java class.  All other Java classes are mapped
1241 into corresponding C++ classes derived from @code{java::lang::Object}.
1242
1243 Interface inheritance (the @code{implements} keyword) is currently not
1244 reflected in the C++ mapping.
1245
1246
1247 @subsection Object fields
1248
1249 Each object contains an object header, followed by the instance fields
1250 of the class, in order.  The object header consists of a single
1251 pointer to a dispatch or virtual function table.  (There may be extra
1252 fields @emph{in front of} the object, for example for memory
1253 management, but this is invisible to the application, and the
1254 reference to the object points to the dispatch table pointer.)
1255
1256 The fields are laid out in the same order, alignment, and size as in
1257 C++.  Specifically, 8-bite and 16-bit native types (@code{byte},
1258 @code{short}, @code{char}, and @code{boolean}) are @emph{not} widened
1259 to 32 bits.  Note that the Java VM does extend 8-bit and 16-bit types
1260 to 32 bits when on the VM stack or temporary registers.
1261
1262 If you include the @code{gcjh}-generated header for a
1263 class, you can access fields of Java classes in the @emph{natural}
1264 way.  For example, given the following Java class:
1265
1266 @example
1267 public class Int
1268 @{
1269   public int i;
1270   public Integer (int i) @{ this.i = i; @}
1271   public static zero = new Integer(0);
1272 @}
1273 @end example
1274
1275 you can write:
1276
1277 @example
1278 #include <gcj/cni.h>;
1279 #include <Int>;
1280
1281 Int*
1282 mult (Int *p, jint k)
1283 @{
1284   if (k == 0)
1285     return Int::zero;  // @r{Static member access.}
1286   return new Int(p->i * k);
1287 @}
1288 @end example
1289
1290
1291 @subsection Access specifiers
1292
1293 CNI does not strictly enforce the Java access
1294 specifiers, because Java permissions cannot be directly mapped
1295 into C++ permission.  Private Java fields and methods are mapped
1296 to private C++ fields and methods, but other fields and methods
1297 are mapped to public fields and methods.
1298
1299
1300
1301 @node Class Initialization
1302 @section Class Initialization
1303
1304 Java requires that each class be automatically initialized at the time 
1305 of the first active use.  Initializing a class involves 
1306 initializing the static fields, running code in class initializer 
1307 methods, and initializing base classes.  There may also be 
1308 some implementation specific actions, such as allocating 
1309 @code{String} objects corresponding to string literals in
1310 the code.
1311
1312 The GCJ compiler inserts calls to @code{JvInitClass} at appropriate
1313 places to ensure that a class is initialized when required.  The C++
1314 compiler does not insert these calls automatically---it is the
1315 programmer's responsibility to make sure classes are initialized.
1316 However, this is fairly painless because of the conventions assumed by
1317 the Java system.
1318
1319 First, @code{libgcj} will make sure a class is initialized
1320 before an instance of that object is created.  This is one
1321 of the responsibilities of the @code{new} operation.  This is
1322 taken care of both in Java code, and in C++ code.  (When the G++
1323 compiler sees a @code{new} of a Java class, it will call
1324 a routine in @code{libgcj} to allocate the object, and that
1325 routine will take care of initializing the class.)  It follows that you can
1326 access an instance field, or call an instance (non-static)
1327 method and be safe in the knowledge that the class and all
1328 of its base classes have been initialized.
1329
1330 Invoking a static method is also safe.  This is because the
1331 Java compiler adds code to the start of a static method to make sure
1332 the class is initialized.  However, the C++ compiler does not
1333 add this extra code.  Hence, if you write a native static method
1334 using CNI, you are responsible for calling @code{JvInitClass}
1335 before doing anything else in the method (unless you are sure
1336 it is safe to leave it out).
1337
1338 Accessing a static field also requires the class of the
1339 field to be initialized.  The Java compiler will generate code
1340 to call @code{Jv_InitClass} before getting or setting the field.
1341 However, the C++ compiler will not generate this extra code,
1342 so it is your responsibility to make sure the class is
1343 initialized before you access a static field from C++.
1344
1345
1346 @node Object allocation
1347 @section Object allocation
1348
1349 New Java objects are allocated using a
1350 @dfn{class instance creation expression}, e.g.:
1351
1352 @example
1353 new @var{Type} ( ... )
1354 @end example
1355
1356 The same syntax is used in C++.  The main difference is that
1357 C++ objects have to be explicitly deleted; in Java they are
1358 automatically deleted by the garbage collector.
1359 Using @acronym{CNI}, you can allocate a new Java object
1360 using standard C++ syntax and the C++ compiler will allocate
1361 memory from the garbage collector.  If you have overloaded
1362 constructors, the compiler will choose the correct one
1363 using standard C++ overload resolution rules.  
1364
1365 @noindent For example:
1366
1367 @example
1368 java::util::Hashtable *ht = new java::util::Hashtable(120);
1369 @end example
1370
1371 @deftypefun void* _Jv_AllocBytes (jsize @var{size})
1372 Allocates @var{size} bytes from the heap.  The memory is not scanned
1373 by the garbage collector but it freed if no references to it are discovered.
1374 @end deftypefun
1375
1376
1377 @node Arrays
1378 @section Arrays
1379
1380 While in many ways Java is similar to C and C++, it is quite different
1381 in its treatment of arrays.  C arrays are based on the idea of pointer
1382 arithmetic, which would be incompatible with Java's security
1383 requirements.  Java arrays are true objects (array types inherit from
1384 @code{java.lang.Object}).  An array-valued variable is one that
1385 contains a reference (pointer) to an array object.
1386
1387 Referencing a Java array in C++ code is done using the
1388 @code{JArray} template, which as defined as follows:
1389
1390 @example
1391 class __JArray : public java::lang::Object
1392 @{
1393 public:
1394   int length;
1395 @};
1396
1397 template<class T>
1398 class JArray : public __JArray
1399 @{
1400   T data[0];
1401 public:
1402   T& operator[](jint i) @{ return data[i]; @}
1403 @};
1404 @end example
1405
1406
1407 There are a number of @code{typedef}s which correspond to @code{typedef}s 
1408 from the @acronym{JNI}.  Each is the type of an array holding objects
1409 of the relevant type:
1410
1411 @example
1412 typedef __JArray *jarray;
1413 typedef JArray<jobject> *jobjectArray;
1414 typedef JArray<jboolean> *jbooleanArray;
1415 typedef JArray<jbyte> *jbyteArray;
1416 typedef JArray<jchar> *jcharArray;
1417 typedef JArray<jshort> *jshortArray;
1418 typedef JArray<jint> *jintArray;
1419 typedef JArray<jlong> *jlongArray;
1420 typedef JArray<jfloat> *jfloatArray;
1421 typedef JArray<jdouble> *jdoubleArray;
1422 @end example
1423
1424
1425 @deftypemethod {template<class T>} T* elements (JArray<T> @var{array})
1426 This template function can be used to get a pointer to the elements of
1427 the @code{array}.  For instance, you can fetch a pointer to the
1428 integers that make up an @code{int[]} like so:
1429
1430 @example
1431 extern jintArray foo;
1432 jint *intp = elements (foo);
1433 @end example
1434
1435 The name of this function may change in the future.
1436 @end deftypemethod
1437
1438
1439 @deftypefun jobjectArray JvNewObjectArray (jsize @var{length}, jclass @var{klass}, jobject @var{init})
1440 Here @code{klass} is the type of elements of the array and
1441 @code{init} is the initial value put into every slot in the array.
1442 @end deftypefun
1443
1444
1445 @subsection Creating arrays
1446
1447 For each primitive type there is a function which can be used to
1448 create a new array of that type.  The name of the function is of the
1449 form:
1450
1451 @example
1452 JvNew@var{Type}Array
1453 @end example
1454
1455 @noindent For example:
1456
1457 @example
1458 JvNewBooleanArray
1459 @end example
1460
1461 @noindent can be used to create an array of Java primitive boolean types.
1462
1463 @noindent The following function definition is the template for all such functions:
1464
1465 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1466 Create's an array @var{length} indices long.
1467 @end deftypefun
1468
1469 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1470 Returns the length of the @var{array}.
1471 @end deftypefun
1472
1473
1474 @node Methods
1475 @section Methods
1476
1477 Java methods are mapped directly into C++ methods.
1478 The header files generated by @code{gcjh}
1479 include the appropriate method definitions.
1480 Basically, the generated methods have the same names and
1481 @emph{corresponding} types as the Java methods,
1482 and are called in the natural manner.
1483
1484 @subsection Overloading
1485
1486 Both Java and C++ provide method overloading, where multiple
1487 methods in a class have the same name, and the correct one is chosen
1488 (at compile time) depending on the argument types.
1489 The rules for choosing the correct method are (as expected) more complicated
1490 in C++ than in Java, but given a set of overloaded methods
1491 generated by @code{gcjh} the C++ compiler will choose
1492 the expected one.
1493
1494 Common assemblers and linkers are not aware of C++ overloading,
1495 so the standard implementation strategy is to encode the
1496 parameter types of a method into its assembly-level name.
1497 This encoding is called @dfn{mangling},
1498 and the encoded name is the @dfn{mangled name}.
1499 The same mechanism is used to implement Java overloading.
1500 For C++/Java interoperability, it is important that both the Java
1501 and C++ compilers use the @emph{same} encoding scheme.
1502
1503 @subsection Static methods
1504
1505 Static Java methods are invoked in @acronym{CNI} using the standard
1506 C++ syntax, using the @code{::} operator rather
1507 than the @code{.} operator.  
1508
1509 @noindent For example:
1510
1511 @example
1512 jint i = java::lang::Math::round((jfloat) 2.3);
1513 @end example
1514
1515 @noindent C++ method definition syntax is used to define a static native method.
1516 For example:
1517
1518 @example
1519 #include <java/lang/Integer>
1520 java::lang::Integer*
1521 java::lang::Integer::getInteger(jstring str)
1522 @{
1523   ...
1524 @}
1525 @end example
1526
1527
1528 @subsection Object Constructors
1529
1530 Constructors are called implicitly as part of object allocation
1531 using the @code{new} operator.  
1532
1533 @noindent For example:
1534
1535 @example
1536 java::lang::Integer *x = new java::lang::Integer(234);
1537 @end example
1538
1539 Java does not allow a constructor to be a native method.
1540 This limitation can be coded round however because a constructor
1541 can @emph{call} a native method.
1542
1543
1544 @subsection Instance methods
1545
1546 Calling a Java instance method from a C++ @acronym{CNI} method is done 
1547 using the standard C++ syntax, e.g.:
1548
1549 @example
1550 // @r{First create the Java object.}
1551 java::lang::Integer *x = new java::lang::Integer(234);
1552 // @r{Now call a method.}
1553 jint prim_value = x->intValue();
1554 if (x->longValue == 0) 
1555   ...
1556 @end example
1557
1558 @noindent Defining a Java native instance method is also done the natural way:
1559
1560 @example
1561 #include <java/lang/Integer.h>
1562
1563 jdouble
1564 java::lang:Integer::doubleValue()
1565 @{
1566   return (jdouble) value;
1567 @}
1568 @end example
1569
1570
1571 @subsection Interface methods
1572
1573 In Java you can call a method using an interface reference.  This is
1574 supported, but not completly.  @xref{Interfaces}.
1575
1576
1577
1578
1579 @node Strings
1580 @section Strings
1581
1582 @acronym{CNI} provides a number of utility functions for
1583 working with Java Java @code{String} objects.
1584 The names and interfaces are analogous to those of @acronym{JNI}.
1585
1586
1587 @deftypefun jstring JvNewString (const char* @var{chars}, jsize @var{len})
1588 Returns a Java @code{String} object with characters from the C string
1589 @var{chars} up to the index @var{len} in that array.
1590 @end deftypefun
1591
1592 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes}, jsize @var{len})
1593 Returns a Java @code{String} made up of @var{len} bytes from @var{bytes}.
1594 @end deftypefun
1595
1596
1597 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1598 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
1599 @end deftypefun
1600
1601 @deftypefun jstring JvNewStringUTF (const char* @var{bytes})
1602 Returns a @code{String} which is made up of the UTF encoded characters
1603 present in the C string @var{bytes}.
1604 @end deftypefun
1605
1606 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1607 Returns a pointer to an array of characters making up the @code{String} @var{str}.
1608 @end deftypefun
1609
1610 @deftypefun int JvGetStringUTFLength (jstring @var{str})
1611 Returns the number of bytes required to encode the contents of the
1612 @code{String} @var{str} in UTF-8.
1613 @end deftypefun
1614
1615 @deftypefun jsize JvGetStringUTFRegion (jstring @var{str}, jsize @var{start}, jsize @var{len}, char* @var{buf})
1616 Puts the UTF-8 encoding of a region of the @code{String} @var{str} into 
1617 the buffer @code{buf}.  The region to fetch is marked by @var{start} and @var{len}.
1618
1619 Note that @var{buf} is a buffer, not a C string.  It is @emph{not} 
1620 null terminated.
1621 @end deftypefun
1622
1623
1624 @node Mixing with C++
1625 @section Interoperating with C/C++
1626
1627 Because @acronym{CNI} is designed to represent Java classes and methods it
1628 cannot be mixed readily with C/C++ types.
1629
1630 One important restriction is that Java classes cannot have non-Java
1631 type instance or static variables and cannot have methods which take
1632 non-Java types as arguments or return non-Java types.
1633
1634 @noindent None of the following is possible with CNI:
1635
1636 @example
1637
1638 class ::MyClass : public java::lang::Object
1639 @{
1640    char* variable;  // @r{char* is not a valid Java type.}
1641 @}
1642
1643
1644 uint
1645 ::SomeClass::someMethod (char *arg)
1646 @{
1647   .
1648   .
1649   .
1650 @}   // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1651 @end example
1652
1653 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1654
1655
1656 @example
1657 jint
1658 ::SomeClass::otherMethod (jstring str)
1659 @{
1660    char *arg = ...
1661    .
1662    .
1663    .
1664 @}
1665 @end example
1666
1667 But this restriction can cause a problem so @acronym{CNI} includes the
1668 @code{gnu.gcj.RawData} class.  The @code{RawData} class is a
1669 @dfn{non-scanned reference} type.  In other words variables declared
1670 of type @code{RawData} can contain any data and are not checked by the
1671 compiler in any way.
1672
1673 This means that you can put C/C++ data structures (including classes)
1674 in your @acronym{CNI} classes, as long as you use the appropriate cast.
1675
1676 @noindent Here are some examples:
1677
1678 @example
1679
1680 class ::MyClass : public java::lang::Object
1681 @{
1682    gnu.gcj.RawData string;
1683
1684    MyClass ();
1685    gnu.gcj.RawData getText ();
1686    void printText ();
1687 @}
1688
1689 ::MyClass::MyClass ()
1690 @{
1691    char* text = ...
1692    string = text;
1693 @}
1694
1695 gnu.gcj.RawData
1696 ::MyClass::getText ()
1697 @{
1698    return string;
1699 @}
1700
1701 void
1702 ::MyClass::printText ()
1703 @{
1704   printf("%s\n", (char*) string);
1705 @}
1706 @end example
1707
1708
1709 @node Exception Handling
1710 @section Exception Handling
1711
1712 While C++ and Java share a common exception handling framework,
1713 things are not yet perfectly integrated.  The main issue is that the
1714 run-time type information facilities of the two
1715 languages are not integrated.
1716
1717 Still, things work fairly well.  You can throw a Java exception from
1718 C++ using the ordinary @code{throw} construct, and this
1719 exception can be caught by Java code.  Similarly, you can catch an
1720 exception thrown from Java using the C++ @code{catch}
1721 construct.
1722
1723 @noindent Here is an example:
1724
1725 @example
1726 if (i >= count)
1727    throw new java::lang::IndexOutOfBoundsException();
1728 @end example
1729
1730 Normally, G++ will automatically detect when you are writing C++
1731 code that uses Java exceptions, and handle them appropriately.
1732 However, if C++ code only needs to execute destructors when Java
1733 exceptions are thrown through it, GCC will guess incorrectly.  Sample
1734 problematic code:
1735
1736 @example
1737 struct S @{ ~S(); @};
1738
1739 extern void bar();    // @r{Is implemented in Java and may throw exceptions.}
1740
1741 void foo()
1742 @{
1743   S s;
1744   bar();
1745 @}
1746 @end example
1747
1748 The usual effect of an incorrect guess is a link failure, complaining of
1749 a missing routine called @code{__gxx_personality_v0}.
1750
1751 You can inform the compiler that Java exceptions are to be used in a
1752 translation unit, irrespective of what it might think, by writing
1753 @code{#pragma GCC java_exceptions} at the head of the
1754 file.  This @code{#pragma} must appear before any
1755 functions that throw or catch exceptions, or run destructors when
1756 exceptions are thrown through them.
1757
1758 @node Synchronization
1759 @section Synchronization
1760
1761 Each Java object has an implicit monitor.
1762 The Java VM uses the instruction @code{monitorenter} to acquire
1763 and lock a monitor, and @code{monitorexit} to release it.
1764
1765 The corresponding CNI macros are @code{JvMonitorEnter} and 
1766 @code{JvMonitorExit} (JNI has similar  methods @code{MonitorEnter}
1767 and @code{MonitorExit}).  
1768
1769
1770 The Java source language does not provide direct access to these primitives.
1771 Instead, there is a @code{synchronized} statement that does an
1772 implicit @code{monitorenter} before entry to the block,
1773 and does a @code{monitorexit} on exit from the block.
1774 Note that the lock has to be released even when the block is abnormally
1775 terminated by an exception, which means there is an implicit
1776 @code{try finally} surrounding synchronization locks.
1777
1778 From C++, it makes sense to use a destructor to release a lock.
1779 @acronym{CNI} defines the following utility class:
1780
1781 @example
1782 class JvSynchronize() @{
1783   jobject obj;
1784   JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
1785   ~JvSynchronize() @{ JvMonitorExit(obj); @}
1786 @};
1787 @end example
1788
1789 So this Java code:
1790
1791 @example
1792 synchronized (OBJ)
1793 @{
1794    CODE
1795 @}
1796 @end example
1797
1798 @noindent might become this C++ code:
1799
1800 @example
1801 @{
1802    JvSynchronize dummy (OBJ);
1803    CODE;
1804 @}
1805 @end example
1806
1807 Java also has methods with the @code{synchronized} attribute.
1808 This is equivalent to wrapping the entire method body in a
1809 @code{synchronized} statement.
1810 (Alternatively, an implementation could require the caller to do
1811 the synchronization.  This is not practical for a compiler, because
1812 each virtual method call would have to test at run-time if
1813 synchronization is needed.)  Since in @command{gcj}
1814 the @code{synchronized} attribute is handled by the
1815 method implementation, it is up to the programmer
1816 of a synchronized native method to handle the synchronization
1817 (in the C++ implementation of the method).
1818 In otherwords, you need to manually add @code{JvSynchronize}
1819 in a @code{native synchornized} method.
1820
1821 @node Invocation
1822 @section Invocation
1823
1824 CNI permits C++ applications to make calls into Java classes, in addition to
1825 allowing Java code to call into C++. Several functions, known as the 
1826 @dfn{invocation API}, are provided to support this.
1827
1828 @deftypefun jint JvCreateJavaVM (void* @var{vm_args})
1829 Initializes the Java runtime. This function performs essential initialization
1830 of the threads interface, garbage collector, exception handling and other key
1831 aspects of the runtime. It must be called once by an application with
1832 a non-Java @code{main()} function, before any other Java or CNI calls are made.
1833 It is safe, but not recommended, to call @code{JvCreateJavaVM()} more than
1834 once provided it is only called from a single thread.
1835 The @var{vmargs} parameter can be used to specify initialization parameters 
1836 for the Java runtime. It may be @code{NULL}.
1837 This function returns @code{0} upon success, or @code{-1} if the runtime is
1838 already initialized.
1839
1840 @emph{Note:} In GCJ 3.1, the @code{vm_args} parameter is ignored. It may be 
1841 used in a future release.
1842 @end deftypefun
1843
1844 @deftypefun java::lang::Thread* JvAttachCurrentThread (jstring @var{name}, java::lang::ThreadGroup* @var{group})
1845 Registers an existing thread with the Java runtime.  This must be called once
1846 from each thread, before that thread makes any other Java or CNI calls. It
1847 must be called after @code{JvCreateJavaVM}.
1848 @var{name} specifies a name for the thread. It may be @code{NULL}, in which 
1849 case a name will be generated.
1850 @var{group} is the ThreadGroup in which this thread will be a member. If it
1851 is @code{NULL}, the thread will be a member of the main thread group.
1852 The return value is the Java @code{Thread} object that represents the thread.
1853 It is safe to call @code{JvAttachCurrentThread()} more than once from the same
1854 thread. If the thread is already attached, the call is ignored and the current
1855 thread object is returned.
1856 @end deftypefun
1857
1858 @deftypefun jint JvDetachCurrentThread ()
1859 Unregisters a thread from the Java runtime. This should be called by threads
1860 that were attached using @code{JvAttachCurrentThread()}, after they have 
1861 finished making calls to Java code. This ensures that any resources associated
1862 with the thread become eligible for garbage collection.
1863 This function returns @code{0} upon success, or @code{-1} if the current thread
1864 is not attached.
1865 @end deftypefun
1866
1867 @subsection Handling uncaught exceptions
1868
1869 If an exception is thrown from Java code called using the invocation API, and
1870 no handler for the exception can be found, the runtime will abort the
1871 application. In order to make the application more robust, it is recommended 
1872 that code which uses the invocation API be wrapped by a top-level try/catch 
1873 block that catches all Java exceptions.
1874
1875 @subsection Example
1876
1877 The following code demonstrates the use of the invocation API. In this
1878 example, the C++ application initializes the Java runtime and attaches
1879 itself. The @code{java.lang.System} class is initialized in order to
1880 access its @code{out} field, and a Java string is printed. Finally, the thread
1881 is detached from the runtime once it has finished making Java calls. Everything
1882 is wrapped with a try/catch block to provide a default handler for any uncaught 
1883 exceptions.
1884
1885 The example can be compiled with @command{c++ test.cc -lgcj}.
1886
1887 @example
1888 // test.cc
1889 #include <gcj/cni.h>
1890 #include <java/lang/System.h>
1891 #include <java/io/PrintStream.h>
1892 #include <java/lang/Throwable.h>
1893
1894 int main(int argc, char *argv)
1895 @{
1896   using namespace java::lang;
1897   
1898   try
1899   @{
1900     JvCreateJavaVM(NULL);
1901     JvAttachCurrentThread(NULL, NULL);
1902
1903     String *message = JvNewStringLatin1("Hello from C++");
1904     JvInitClass(&System.class$);
1905     System::out->println(message);
1906
1907     JvDetachCurrentThread();
1908   @}
1909   catch (Throwable *t)
1910   @{
1911     System::err->println(JvNewStringLatin1("Unhandled Java exception:"));
1912     t->printStackTrace();
1913   @}
1914 @}
1915 @end example
1916
1917 @node Reflection
1918 @section Reflection
1919
1920 Reflection is possible with CNI code, it functions similarly to how it
1921 functions with JNI@.
1922
1923 @c clean this up...  I mean, what are the types jfieldID and jmethodID in JNI?
1924 The types @code{jfieldID} and @code{jmethodID}
1925 are as in JNI@.
1926
1927 @noindent The functions:
1928
1929 @itemize
1930 @item @code{JvFromReflectedField},
1931 @item @code{JvFromReflectedMethod},
1932 @item @code{JvToReflectedField}
1933 @item @code{JvToFromReflectedMethod}
1934 @end itemize
1935
1936 @noindent will be added shortly, as will other functions corresponding to JNI@.
1937
1938
1939
1940 @node Resources
1941 @chapter Resources
1942
1943 While writing @command{gcj} and @code{libgcj} we have, of course, relied
1944 heavily on documentation from Sun Microsystems.  In particular we have
1945 used The Java Language Specification (both first and second editions),
1946 the Java Class Libraries (volumes one and two), and the Java Virtual
1947 Machine Specification.  In addition we've used the online documentation
1948 at @uref{http://java.sun.com/}.
1949
1950 The current @command{gcj} home page is
1951 @uref{http://gcc.gnu.org/java/}.
1952
1953 For more information on gcc, see @uref{http://gcc.gnu.org/}.
1954
1955 Some @code{libgcj} testing is done using the Mauve test suite.  This is
1956 a free software Java class library test suite which is being written
1957 because the JCK is not free.  See
1958 @uref{http://sources.redhat.com/mauve/} for more information.
1959
1960 @bye