1 @\input texinfo @c -*-texinfo-*-
3 @settitle Guide to GNU gcj
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
10 @c When this manual is copyrighted.
11 @set copyrights-gcj 2001, 2002
15 @set which-gcj GCC-@value{version-gcc}
17 @macro gcctabopt{body}
23 @dircategory Programming
25 * Gcj: (gcj). Ahead-of-time compiler for the Java language
28 @dircategory Individual utilities
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.
46 @c man begin COPYRIGHT
47 Copyright (C) @value{copyrights-gcj} Free Software Foundation, Inc.
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
57 ``GNU Free Documentation License''.
59 @c man begin COPYRIGHT
64 (a) The FSF's Front-Cover Text is:
68 (b) The FSF's Back-Cover Text is:
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.
80 @vskip 0pt plus 1filll
81 Copyright @copyright{} @value{copyrights-gcj} Free Software Foundation, Inc.
83 For the @value{which-gcj} Version*
85 Published by the Free Software Foundation @*
86 59 Temple Place - Suite 330@*
87 Boston, MA 02111-1307, USA@*
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''.
97 (a) The FSF's Front-Cover Text is:
101 (b) The FSF's Back-Cover Text is:
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.
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
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
143 @chapter Invoking gcj
145 @c man title gcj Ahead-of-time compiler for the Java language
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{-R} @var{resource-name}] [@option{-d} @var{directory}]
154 [@option{-W}@var{warn}@dots{}]
155 @var{sourcefile}@dots{}
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}.
163 @c man begin DESCRIPTION gcj
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}.
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
181 @c man begin OPTIONS gcj
183 @node Input and output files
184 @section Input and output files
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:
191 @item @var{file}.java
193 @item @var{file}.class
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.
200 A file containing a whitespace-separated list of input file names.
201 (Currently, these must all be @code{.java} source files, but that
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.
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{-R}.
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.)
222 @section Input Options
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
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.
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 imported, we recommend
246 always using @code{-I} instead of the other options for manipulating the
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.
254 @item --CLASSPATH=@var{path}
255 Deprecated synonym for @code{--classpath}.
257 @item --bootclasspath=@var{path}
258 Where to find the standard builtin classes, such as @code{java.lang.String}.
261 This is an environment variable which holds a list of paths.
264 The final class path is constructed like so:
268 First come all directories specified via @code{-I}.
271 If @option{--classpath} is specified, its value is appended.
272 Otherwise, if the @code{CLASSPATH} environment variable is specified,
273 then its value is appended.
274 Otherwise, the current directory (@code{"."}) is appended.
277 Finally, if @code{--bootclasspath} was specified, append its value.
278 Otherwise, append the built-in system directory, @file{libgcj.jar}.
281 The classfile built by @command{gcj} for the class @code{java.lang.Object}
282 (and placed in @code{libgcj.jar}) contains a special zero length
283 attribute @code{gnu.gcj.gcj-compiled}. The compiler looks for this
284 attribute when loading @code{java.lang.Object} and will report an error
285 if it isn't found, unless it compiles to bytecode (the option
286 @code{-fforce-classes-archive-check} can be used to override this
287 behavior in this particular case.)
290 @item -fforce-classes-archive-check
291 This forces the compiler to always check for the special zero length
292 attribute @code{gnu.gcj.gcj-compiled} in @code{java.lang.Object} and
293 issue an error if it isn't found.
299 The Java programming language uses Unicode throughout. In an effort to
300 integrate well with other locales, @command{gcj} allows @file{.java} files
301 to be written using almost any encoding. @command{gcj} knows how to
302 convert these encodings into its internal encoding at compile time.
304 You can use the @code{--encoding=@var{NAME}} option to specify an
305 encoding (of a particular character set) to use for source files. If
306 this is not specified, the default encoding comes from your current
307 locale. If your host system has insufficient locale support, then
308 @command{gcj} assumes the default encoding to be the @samp{UTF-8} encoding
311 To implement @code{--encoding}, @command{gcj} simply uses the host
312 platform's @code{iconv} conversion routine. This means that in practice
313 @command{gcj} is limited by the capabilities of the host platform.
315 The names allowed for the argument @code{--encoding} vary from platform
316 to platform (since they are not standardized anywhere). However,
317 @command{gcj} implements the encoding named @samp{UTF-8} internally, so if
318 you choose to use this for your source files you can be assured that it
319 will work on every host.
325 @command{gcj} implements several warnings. As with other generic
326 @command{gcc} warnings, if an option of the form @code{-Wfoo} enables a
327 warning, then @code{-Wno-foo} will disable it. Here we've chosen to
328 document the form of the warning which will have an effect -- the
329 default being the opposite of what is listed.
332 @item -Wredundant-modifiers
333 With this flag, @command{gcj} will warn about redundant modifiers. For
334 instance, it will warn if an interface method is declared @code{public}.
336 @item -Wextraneous-semicolon
337 This causes @command{gcj} to warn about empty statements. Empty statements
338 have been deprecated.
340 @item -Wno-out-of-date
341 This option will cause @command{gcj} not to warn when a source file is
342 newer than its matching class file. By default @command{gcj} will warn
346 This is the same as @command{gcc}'s @code{-Wunused}.
349 This is the same as @code{-Wredundant-modifiers -Wextraneous-semicolon
354 @node Code Generation
355 @section Code Generation
357 In addition to the many @command{gcc} options controlling code generation,
358 @command{gcj} has several options specific to itself.
361 @item --main=@var{CLASSNAME}
362 This option is used when linking to specify the name of the class whose
363 @code{main} method should be invoked when the resulting executable is
364 run. @footnote{The linker by default looks for a global function named
365 @code{main}. Since Java does not have global functions, and a
366 collection of Java classes may have more than one class with a
367 @code{main} method, you need to let the linker know which of those
368 @code{main} methods it should invoke when starting the application.}
370 @item -D@var{name}[=@var{value}]
371 This option can only be used with @code{--main}. It defines a system
372 property named @var{name} with value @var{value}. If @var{value} is not
373 specified then it defaults to the empty string. These system properties
374 are initialized at the program's startup and can be retrieved at runtime
375 using the @code{java.lang.System.getProperty} method.
378 This option is used to tell @command{gcj} to generate bytecode
379 (@file{.class} files) rather than object code.
381 @item -R @var{resource-name}
382 This option is used to tell @command{gcj} to compile the contents of a
383 given file to object code so it may be accessed at runtime with the core
384 protocol handler as @var{core:/resource-name}.
386 @item -d @var{directory}
387 When used with @code{-C}, this causes all generated @file{.class} files
388 to be put in the appropriate subdirectory of @var{directory}. By
389 default they will be put in subdirectories of the current working
392 @item -fno-bounds-check
393 By default, @command{gcj} generates code which checks the bounds of all
394 array indexing operations. With this option, these checks are omitted, which
395 can improve performance for code that uses arrays extensively. Note that this
396 can result in unpredictable behavior if the code in question actually does
397 violate array bounds constraints. It is safe to use this option if you are
398 sure that your code will never throw an @code{ArrayIndexOutOfBoundsException}.
400 @item -fno-store-check
401 Don't generate array store checks. When storing objects into arrays, a runtime
402 check is normally generated in order to ensure that the object is assignment
403 compatible with the component type of the array (which may not be known
404 at compile-time). With this option, these checks are omitted. This can
405 improve performance for code which stores objects into arrays frequently.
406 It is safe to use this option if you are sure your code will never throw an
407 @code{ArrayStoreException}.
410 With @command{gcj} there are two options for writing native methods: CNI
411 and JNI@. By default @command{gcj} assumes you are using CNI@. If you are
412 compiling a class with native methods, and these methods are implemented
413 using JNI, then you must use @code{-fjni}. This option causes
414 @command{gcj} to generate stubs which will invoke the underlying JNI
417 @item -fno-optimize-static-class-initialization
418 When the optimization level is greather or equal to @code{-O2},
419 @command{gcj} will try to optimize the way calls into the runtime are made
420 to initialize static classes upon their first use (this optimization
421 isn't carried out if @code{-C} was specified.) When compiling to native
422 code, @code{-fno-optimize-static-class-initialization} will turn this
423 optimization off, regardless of the optimization level in use.
427 @node Configure-time Options
428 @section Configure-time Options
430 Some @command{gcj} code generations options affect the resulting ABI, and
431 so can only be meaningfully given when @code{libgcj}, the runtime
432 package, is configured. @code{libgcj} puts the appropriate options from
433 this group into a @samp{spec} file which is read by @command{gcj}. These
434 options are listed here for completeness; if you are using @code{libgcj}
435 then you won't want to touch these options.
439 This enables the use of the Boehm GC bitmap marking code. In particular
440 this causes @command{gcj} to put an object marking descriptor into each
443 @item -fhash-synchronization
444 By default, synchronization data (the data used for @code{synchronize},
445 @code{wait}, and @code{notify}) is pointed to by a word in each object.
446 With this option @command{gcj} assumes that this information is stored in a
447 hash table and not in the object itself.
449 @item -fuse-divide-subroutine
450 On some systems, a library routine is called to perform integer
451 division. This is required to get exception handling correct when
454 @item -fcheck-references
455 On some systems it's necessary to insert inline checks whenever
456 accessing an object via a reference. On other systems you won't need
457 this because null pointer accesses are caught automatically by the
464 @chapter Compatibility with the Java Platform
466 As we believe it is important that the Java platform not be fragmented,
467 @command{gcj} and @code{libgcj} try to conform to the relevant Java
468 specifications. However, limited manpower and incomplete and unclear
469 documentation work against us. So, there are caveats to using
472 This list of compatibility issues is by no means complete.
476 @command{gcj} implements the JDK 1.1 language. It supports inner classes,
477 though these are known to still be buggy. It does not yet support the
478 Java 2 @code{strictfp} keyword (it recognizes the keyword but ignores
482 @code{libgcj} is largely compatible with the JDK 1.2 libraries.
483 However, @code{libgcj} is missing many packages, most notably
484 @code{java.awt}. There are also individual missing classes and methods.
485 We currently do not have a list showing differences between
486 @code{libgcj} and the Java 2 platform.
489 Sometimes the @code{libgcj} implementation of a method or class differs
490 from the JDK implementation. This is not always a bug. Still, if it
491 affects you, it probably makes sense to report it so that we can discuss
492 the appropriate response.
497 @chapter Invoking gcjh
499 @c man title gcjh generate header files from Java class files
501 @c man begin DESCRIPTION gcjh
503 The @code{gcjh} program is used to generate header files from class
504 files. It can generate both CNI and JNI header files, as well as stub
505 implementation files which can be used as a basis for implementing the
506 required native methods.
511 @c man begin SYNOPSIS gcjh
512 gcjh [@option{-stubs}] [@option{-jni}]
513 [@option{-add} @var{text}] [@option{-append} @var{text}] [@option{-friend} @var{text}]
514 [@option{-preprend} @var{text}]
515 [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
516 [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
517 [@option{-o} @var{file}] [@option{-td} @var{dir}]
518 [@option{-M}] [@option{-MM}] [@option{-MD}] [@option{-MMD}]
519 [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
520 @var{classname}@dots{}
522 @c man begin SEEALSO gcjh
523 gcc(1), gcj(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
524 and the Info entries for @file{gcj} and @file{gcc}.
528 @c man begin OPTIONS gcjh
532 This causes @code{gcjh} to generate stub files instead of header files.
533 By default the stub file will be named after the class, with a suffix of
534 @samp{.cc}. In JNI mode, the default output file will have the suffix
538 This tells @code{gcjh} to generate a JNI header or stub. By default,
539 CNI headers are generated.
541 @item -add @var{text}
542 Inserts @var{text} into the class body. This is ignored in JNI mode.
544 @item -append @var{text}
545 Inserts @var{text} into the header file after the class declaration.
546 This is ignored in JNI mode.
548 @item -friend @var{text}
549 Inserts @var{text} into the class as a @code{friend} declaration.
550 This is ignored in JNI mode.
552 @item -prepend @var{text}
553 Inserts @var{text} into the header file before the class declaration.
554 This is ignored in JNI mode.
556 @item --classpath=@var{path}
557 @itemx --CLASSPATH=@var{path}
558 @itemx -I@var{directory}
559 @itemx -d @var{directory}
561 These options are all identical to the corresponding @command{gcj} options.
564 Sets the output file name. This cannot be used if there is more than
565 one class on the command line.
567 @item -td @var{directory}
568 Sets the name of the directory to use for temporary files.
571 Print all dependencies to stdout; suppress ordinary output.
574 Print non-system dependencies to stdout; suppress ordinary output.
577 Print all dependencies to stdout.
580 Print non-system dependencies to stdout.
583 Print help about @code{gcjh} and exit. No further processing is done.
586 Print version information for @code{gcjh} and exit. No further
590 Print extra information while running.
593 All remaining options are considered to be names of classes.
597 @node Invoking jv-scan
598 @chapter Invoking jv-scan
600 @c man title jv-scan print information about Java source file
602 @c man begin DESCRIPTION jv-scan
604 The @code{jv-scan} program can be used to print information about a Java
605 source file (@file{.java} file).
610 @c man begin SYNOPSIS jv-scan
611 jv-scan [@option{--complexity}] [@option{--encoding}=@var{name}]
612 [@option{--print-main}] [@option{--list-class}] [@option{--list-filename}]
613 [@option{--version}] [@option{--help}]
614 [@option{-o} @var{file}] @var{inputfile}@dots{}
616 @c man begin SEEALSO jv-scan
617 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
618 and the Info entries for @file{gcj} and @file{gcc}.
622 @c man begin OPTIONS jv-scan
626 This prints a complexity measure, related to cyclomatic complexity, for
629 @item --encoding=@var{name}
630 This works like the corresponding @command{gcj} option.
633 This prints the name of the class in this file containing a @code{main}
637 This lists the names of all classes defined in the input files.
639 @item --list-filename
640 If @code{--list-class} is given, this option causes @code{jv-scan} to
641 also print the name of the file in which each class was found.
644 Print output to the named file.
647 Print help, then exit.
650 Print version number, then exit.
655 @node Invoking jcf-dump
656 @chapter Invoking jcf-dump
658 @c man title jcf-dump print information about Java class files
661 @c man begin SYNOPSIS jcf-dump
662 jcf-dump [@option{-c}] [@option{--javap}]
663 [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
664 [@option{-I}@var{dir}@dots{}] [@option{-o} @var{file}]
665 [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
666 @var{classname}@dots{}
668 @c man begin SEEALSO jcf-dump
669 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
670 and the Info entries for @file{gcj} and @file{gcc}.
674 @c man begin DESCRIPTION jcf-dump
676 This is a class file examiner, similar to @code{javap}. It will print
677 information about a number of classes, which are specifed by class name
682 @c man begin OPTIONS jcf-dump
686 Disassemble method bodies. By default method bodies are not printed.
689 Generate output in @code{javap} format. The implementation of this
690 feature is very incomplete.
692 @item --classpath=@var{path}
693 @itemx --CLASSPATH=@var{path}
694 @itemx -I@var{directory}
696 These options as the same as the corresponding @command{gcj} options.
699 Print help, then exit.
702 Print version number, then exit.
705 Print extra information while running.
711 @chapter Invoking gij
713 @c man title gij GNU interpreter for Java bytecode
716 @c man begin SYNOPSIS gij
717 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
719 gij [@option{-jar}] [@option{OPTION}] @dots{} @var{CLASS} [@var{ARGS}@dots{}]
720 [@option{-D}@var{name}[=@var{value}]@dots{}]
721 [@option{-ms=}@var{number}] [@option{-mx=}@var{number}]
722 [@option{--version}] [@option{--help}]
724 @c man begin SEEALSO gij
725 gcc(1), gcj(1), gcjh(1), jv-scan(1), jcf-dump(1), gfdl(7),
726 and the Info entries for @file{gcj} and @file{gcc}.
730 @c man begin DESCRIPTION gij
732 @code{gij} is a Java bytecode interpreter included with @code{libgcj}.
733 @code{gij} is not available on every platform; porting it requires a
734 small amount of assembly programming which has not been done for all the
735 targets supported by @command{gcj}.
737 The primary argument to @code{gij} is the name of a class or, with
738 @code{-jar}, a jar file. Options before this argument are interpreted
739 by @code{gij}; remaining options are passed to the interpreted program.
741 If a class name is specified and this class does not have a @code{main}
742 method with the appropriate signature (a @code{static void} method with
743 a @code{String[]} as its sole argument), then @code{gij} will print an
746 If a jar file is specified then @code{gij} will use information in it to
747 determine which class' @code{main} method will be invoked.
749 @code{gij} will invoke the @code{main} method with all the remaining
750 command-line options.
752 Note that @code{gij} is not limited to interpreting code. Because
753 @code{libgcj} includes a class loader which can dynamically load shared
754 objects, it is possible to give @code{gij} the name of a class which has
755 been compiled and put into a shared library on the class path.
759 @c man begin OPTIONS gij
762 @item -D@var{name}[=@var{value}]
763 This defines a system property named @var{name} with value @var{value}.
764 If @var{value} is not specified then it defaults to the empty string.
765 These system properties are initialized at the program's startup and can
766 be retrieved at runtime using the @code{java.lang.System.getProperty}
769 @item -ms=@var{number}
770 This sets the initial heap size.
772 @item -mx=@var{number}
773 This sets the maximum heap size.
776 This indicates that the name passed to @code{gij} should be interpreted
777 as the name of a jar file, not a class.
780 Print help, then exit.
783 Print version number, then exit.
788 @node Invoking jv-convert
789 @chapter Invoking jv-convert
791 @c man title jv-convert Convert file from one encoding to another
793 @c man begin SYNOPSIS jv-convert
794 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
797 [@option{--encoding} @var{name}]
798 [@option{--from} @var{name}]
799 [@option{--to} @var{name}]
800 [@option{-i} @var{file}] [@option{-o} @var{file}]
801 [@option{--reverse}] [@option{--help}] [@option{--version}]
805 @c man begin DESCRIPTION jv-convert
807 @command{jv-convert} is a utility included with @code{libgcj} which
808 converts a file from one encoding to another. It is similar to the Unix
809 @command{iconv} utility.
811 The encodings supported by @command{jv-convert} are platform-dependent.
812 Currently there is no way to get a list of all supported encodings.
816 @c man begin OPTIONS jv-convert
819 @item --encoding @var{name}
820 @itemx --from @var{name}
821 Use @var{name} as the input encoding. The default is the current
824 @item --to @var{name}
825 Use @var{name} as the output encoding. The default is the
826 @code{JavaSrc} encoding; this is ASCII with @samp{\u} escapes for
827 non-ASCII characters.
830 Read from @var{file}. The default is to read from standard input.
833 Write to @var{file}. The default is to write to standard output.
836 Swap the input and output encodings.
839 Print a help message, then exit.
842 Print version information, then exit.
848 @chapter Invoking rmic
850 @c man title rmic Generate stubs for Remote Method Invocation
852 @c man begin SYNOPSIS rmic
853 @command{rmic} [@option{OPTION}] @dots{} @var{class} @dots{}
856 [@option{-keepgenerated}]
860 [@option{-nocompile}]
862 [@option{-d} @var{directory}]
868 @c man begin DESCRIPTION rmic
870 @command{rmic} is a utility included with @code{libgcj} which generates
871 stubs for remote objects.
873 @c FIXME: Add real information here.
874 @c This really isn't much more than the --help output.
876 Note that this program isn't yet fully compatible with the JDK
877 @command{rmic}. Some options, such as @option{-classpath}, are
878 recognized but currently ignored. We have left these options
879 undocumented for now.
881 Long options can also be given with a GNU-style leading @samp{--}. For
882 instance, @option{--help} is accepted.
886 @c man begin OPTIONS rmic
890 @itemx -keepgenerated
891 By default, @command{rmic} deletes intermediate files. Either of these
892 options causes it not to delete such files.
895 Cause @command{rmic} to create stubs and skeletons for the 1.1
899 Cause @command{rmic} to create stubs and skeletons compatible with both
900 the 1.1 and 1.2 protocol versions. This is the default.
903 Cause @command{rmic} to create stubs and skeletons for the 1.2
907 Don't compile the generated files.
910 Print information about what @command{rmic} is doing.
912 @item -d @var{directory}
913 Put output files in @var{directory}. By default the files are put in
914 the current working directory.
917 Print a help message, then exit.
920 Print version information, then exit.
926 @node Invoking rmiregistry
927 @chapter Invoking rmiregistry
929 @c man title rmiregistry Remote object registry
931 @c man begin SYNOPSIS rmiregistry
932 @command{rmic} [@option{OPTION}] @dots{} [@var{port}]
939 @c man begin DESCRIPTION rmiregistry
941 @command{rmiregistry} starts a remote object registry on the current
942 host. If no port number is specified, then port 1099 is used.
944 @c FIXME: Add real information here.
945 @c This really isn't much more than the --help output.
949 @c man begin OPTIONS rmiregistry
953 Print a help message, then exit.
956 Print version information, then exit.
965 This documents CNI, the Cygnus Native Interface,
966 which is is a convenient way to write Java native methods using C++.
967 This is a more efficient, more convenient, but less portable
968 alternative to the standard JNI (Java Native Interface).
971 * Basic concepts:: Introduction to using CNI@.
972 * Packages:: How packages are mapped to C++.
973 * Primitive types:: Handling Java types in C++.
974 * Interfaces:: How Java interfaces map to C++.
975 * Objects and Classes:: C++ and Java classes.
976 * Class Initialization:: How objects are initialized.
977 * Object allocation:: How to create Java objects in C++.
978 * Arrays:: Dealing with Java arrays in C++.
979 * Methods:: Java methods in C++.
980 * Strings:: Information about Java Strings.
981 * Mixing with C++:: How CNI can interoperate with C++.
982 * Exception Handling:: How exceptions are handled.
983 * Synchronization:: Synchronizing between Java and C++.
984 * Invocation:: Starting the Java runtime from C++.
985 * Reflection:: Using reflection from C++.
990 @section Basic concepts
992 In terms of languages features, Java is mostly a subset
993 of C++. Java has a few important extensions, plus a powerful standard
994 class library, but on the whole that does not change the basic similarity.
995 Java is a hybrid object-oriented language, with a few native types,
996 in addition to class types. It is class-based, where a class may have
997 static as well as per-object fields, and static as well as instance methods.
998 Non-static methods may be virtual, and may be overloaded. Overloading is
999 resolved at compile time by matching the actual argument types against
1000 the parameter types. Virtual methods are implemented using indirect calls
1001 through a dispatch table (virtual function table). Objects are
1002 allocated on the heap, and initialized using a constructor method.
1003 Classes are organized in a package hierarchy.
1005 All of the listed attributes are also true of C++, though C++ has
1006 extra features (for example in C++ objects may be allocated not just
1007 on the heap, but also statically or in a local stack frame). Because
1008 @command{gcj} uses the same compiler technology as G++ (the GNU
1009 C++ compiler), it is possible to make the intersection of the two
1010 languages use the same ABI (object representation and calling
1011 conventions). The key idea in CNI is that Java objects are C++
1012 objects, and all Java classes are C++ classes (but not the other way
1013 around). So the most important task in integrating Java and C++ is to
1014 remove gratuitous incompatibilities.
1016 You write CNI code as a regular C++ source file. (You do have to use
1017 a Java/CNI-aware C++ compiler, specifically a recent version of G++.)
1019 @noindent A CNI C++ source file must have:
1022 #include <gcj/cni.h>
1025 @noindent and then must include one header file for each Java class it uses, e.g.:
1028 #include <java/lang/Character.h>
1029 #include <java/util/Date.h>
1030 #include <java/lang/IndexOutOfBoundsException.h>
1033 @noindent These header files are automatically generated by @code{gcjh}.
1036 CNI provides some functions and macros to make using Java objects and
1037 primitive types from C++ easier. In general, these CNI functions and
1038 macros start with the @code{Jv} prefix, for example the function
1039 @code{JvNewObjectArray}. This convention is used to avoid conflicts
1040 with other libraries. Internal functions in CNI start with the prefix
1041 @code{_Jv_}. You should not call these; if you find a need to, let us
1042 know and we will try to come up with an alternate solution. (This
1043 manual lists @code{_Jv_AllocBytes} as an example; CNI should instead
1044 provide a @code{JvAllocBytes} function.)
1047 @subsection Limitations
1049 Whilst a Java class is just a C++ class that doesn't mean that you are
1050 freed from the shackles of Java, a @acronym{CNI} C++ class must adhere to the
1051 rules of the Java programming language.
1053 For example: it is not possible to declare a method in a CNI class
1054 that will take a C string (@code{char*}) as an argument, or to declare a
1055 member variable of some non-Java datatype.
1061 The only global names in Java are class names, and packages. A
1062 @dfn{package} can contain zero or more classes, and also zero or more
1063 sub-packages. Every class belongs to either an unnamed package or a
1064 package that has a hierarchical and globally unique name.
1066 A Java package is mapped to a C++ @dfn{namespace}. The Java class
1067 @code{java.lang.String} is in the package @code{java.lang}, which is a
1068 sub-package of @code{java}. The C++ equivalent is the class
1069 @code{java::lang::String}, which is in the namespace @code{java::lang}
1070 which is in the namespace @code{java}.
1072 @noindent Here is how you could express this:
1075 (// @r{Declare the class(es), possibly in a header file:}
1084 class java::lang::String : public java::lang::Object
1090 @noindent The @code{gcjh} tool automatically generates the nessary namespace
1094 @subsection Leaving out package names
1096 Always using the fully-qualified name of a java class can be
1097 tiresomely verbose. Using the full qualified name also ties the code
1098 to a single package making code changes necessary should the class
1099 move from one package to another. The Java @code{package} declaration
1100 specifies that the following class declarations are in the named
1101 package, without having to explicitly name the full package
1102 qualifiers. The @code{package} declaration can be
1103 followed by zero or more @code{import} declarations, which
1104 allows either a single class or all the classes in a package to be
1105 named by a simple identifier. C++ provides something similar with the
1106 @code{using} declaration and directive.
1111 import @var{package-name}.@var{class-name};
1114 @noindent allows the program text to refer to @var{class-name} as a shorthand for
1115 the fully qualified name: @code{@var{package-name}.@var{class-name}}.
1118 @noindent To achieve the same effect C++, you have to do this:
1121 using @var{package-name}::@var{class-name};
1125 @noindent Java can also cause imports on demand, like this:
1128 import @var{package-name}.*;
1131 @noindent Doing this allows any class from the package @var{package-name} to be
1132 refered to only by its class-name within the program text.
1135 @noindent The same effect can be achieved in C++ like this:
1138 using namespace @var{package-name};
1142 @node Primitive types
1143 @section Primitive types
1145 Java provides 8 @dfn{primitives} types which represent integers, floats,
1146 characters and booleans (and also the void type). C++ has its own
1147 very similar concrete types. Such types in C++ however are not always
1148 implemented in the same way (an int might be 16, 32 or 64 bits for example)
1149 so CNI provides a special C++ type for each primitive Java type:
1151 @multitable @columnfractions .20 .25 .60
1152 @item @strong{Java type} @tab @strong{C/C++ typename} @tab @strong{Description}
1153 @item @code{char} @tab @code{jchar} @tab 16 bit Unicode character
1154 @item @code{boolean} @tab @code{jboolean} @tab logical (true or false) values
1155 @item @code{byte} @tab @code{jbyte} @tab 8-bit signed integer
1156 @item @code{short} @tab @code{jshort} @tab 16 bit signed integer
1157 @item @code{int} @tab @code{jint} @tab 32 bit signed integer
1158 @item @code{long} @tab @code{jlong} @tab 64 bit signed integer
1159 @item @code{float} @tab @code{jfloat} @tab 32 bit IEEE floating point number
1160 @item @code{double} @tab @code{jdouble} @tab 64 bit IEEE floating point number
1161 @item @code{void} @tab @code{void} @tab no value
1164 When refering to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1165 to avoid disappointment.
1168 @subsection Reference types associated with primitive types
1170 In Java each primitive type has an associated reference type,
1171 e.g.: @code{boolean} has an associated @code{java.lang.Boolean} class.
1172 In order to make working with such classes easier GCJ provides the macro
1175 @deffn macro JvPrimClass type
1176 Return a pointer to the @code{Class} object corresponding to the type supplied.
1179 JvPrimClass(void) @result{} java.lang.Void.TYPE
1188 A Java class can @dfn{implement} zero or more
1189 @dfn{interfaces}, in addition to inheriting from
1190 a single base class.
1192 @acronym{CNI} allows CNI code to implement methods of interfaces.
1193 You can also call methods through interface references, with some
1196 @acronym{CNI} doesn't understand interface inheritance at all yet. So,
1197 you can only call an interface method when the declared type of the
1198 field being called matches the interface which declares that
1199 method. The workaround is to cast the interface reference to the right
1202 For example if you have:
1210 interface B extends A
1216 and declare a variable of type @code{B} in C++, you can't call
1217 @code{a()} unless you cast it to an @code{A} first.
1219 @node Objects and Classes
1220 @section Objects and Classes
1224 All Java classes are derived from @code{java.lang.Object}. C++ does
1225 not have a unique root class, but we use the C++ class
1226 @code{java::lang::Object} as the C++ version of the
1227 @code{java.lang.Object} Java class. All other Java classes are mapped
1228 into corresponding C++ classes derived from @code{java::lang::Object}.
1230 Interface inheritance (the @code{implements} keyword) is currently not
1231 reflected in the C++ mapping.
1234 @subsection Object fields
1236 Each object contains an object header, followed by the instance fields
1237 of the class, in order. The object header consists of a single
1238 pointer to a dispatch or virtual function table. (There may be extra
1239 fields @emph{in front of} the object, for example for memory
1240 management, but this is invisible to the application, and the
1241 reference to the object points to the dispatch table pointer.)
1243 The fields are laid out in the same order, alignment, and size as in
1244 C++. Specifically, 8-bite and 16-bit native types (@code{byte},
1245 @code{short}, @code{char}, and @code{boolean}) are @emph{not} widened
1246 to 32 bits. Note that the Java VM does extend 8-bit and 16-bit types
1247 to 32 bits when on the VM stack or temporary registers.
1249 If you include the @code{gcjh}-generated header for a
1250 class, you can access fields of Java classes in the @emph{natural}
1251 way. For example, given the following Java class:
1257 public Integer (int i) @{ this.i = i; @}
1258 public static zero = new Integer(0);
1265 #include <gcj/cni.h>;
1269 mult (Int *p, jint k)
1272 return Int::zero; // @r{Static member access.}
1273 return new Int(p->i * k);
1278 @subsection Access specifiers
1280 CNI does not strictly enforce the Java access
1281 specifiers, because Java permissions cannot be directly mapped
1282 into C++ permission. Private Java fields and methods are mapped
1283 to private C++ fields and methods, but other fields and methods
1284 are mapped to public fields and methods.
1288 @node Class Initialization
1289 @section Class Initialization
1291 Java requires that each class be automatically initialized at the time
1292 of the first active use. Initializing a class involves
1293 initializing the static fields, running code in class initializer
1294 methods, and initializing base classes. There may also be
1295 some implementation specific actions, such as allocating
1296 @code{String} objects corresponding to string literals in
1299 The GCJ compiler inserts calls to @code{JvInitClass} at appropriate
1300 places to ensure that a class is initialized when required. The C++
1301 compiler does not insert these calls automatically---it is the
1302 programmer's responsibility to make sure classes are initialized.
1303 However, this is fairly painless because of the conventions assumed by
1306 First, @code{libgcj} will make sure a class is initialized
1307 before an instance of that object is created. This is one
1308 of the responsibilities of the @code{new} operation. This is
1309 taken care of both in Java code, and in C++ code. (When the G++
1310 compiler sees a @code{new} of a Java class, it will call
1311 a routine in @code{libgcj} to allocate the object, and that
1312 routine will take care of initializing the class.) It follows that you can
1313 access an instance field, or call an instance (non-static)
1314 method and be safe in the knowledge that the class and all
1315 of its base classes have been initialized.
1317 Invoking a static method is also safe. This is because the
1318 Java compiler adds code to the start of a static method to make sure
1319 the class is initialized. However, the C++ compiler does not
1320 add this extra code. Hence, if you write a native static method
1321 using CNI, you are responsible for calling @code{JvInitClass}
1322 before doing anything else in the method (unless you are sure
1323 it is safe to leave it out).
1325 Accessing a static field also requires the class of the
1326 field to be initialized. The Java compiler will generate code
1327 to call @code{Jv_InitClass} before getting or setting the field.
1328 However, the C++ compiler will not generate this extra code,
1329 so it is your responsibility to make sure the class is
1330 initialized before you access a static field from C++.
1333 @node Object allocation
1334 @section Object allocation
1336 New Java objects are allocated using a
1337 @dfn{class instance creation expression}, e.g.:
1340 new @var{Type} ( ... )
1343 The same syntax is used in C++. The main difference is that
1344 C++ objects have to be explicitly deleted; in Java they are
1345 automatically deleted by the garbage collector.
1346 Using @acronym{CNI}, you can allocate a new Java object
1347 using standard C++ syntax and the C++ compiler will allocate
1348 memory from the garbage collector. If you have overloaded
1349 constructors, the compiler will choose the correct one
1350 using standard C++ overload resolution rules.
1352 @noindent For example:
1355 java::util::Hashtable *ht = new java::util::Hashtable(120);
1358 @deftypefun void* _Jv_AllocBytes (jsize @var{size})
1359 Allocates @var{size} bytes from the heap. The memory is not scanned
1360 by the garbage collector but it freed if no references to it are discovered.
1367 While in many ways Java is similar to C and C++, it is quite different
1368 in its treatment of arrays. C arrays are based on the idea of pointer
1369 arithmetic, which would be incompatible with Java's security
1370 requirements. Java arrays are true objects (array types inherit from
1371 @code{java.lang.Object}). An array-valued variable is one that
1372 contains a reference (pointer) to an array object.
1374 Referencing a Java array in C++ code is done using the
1375 @code{JArray} template, which as defined as follows:
1378 class __JArray : public java::lang::Object
1385 class JArray : public __JArray
1389 T& operator[](jint i) @{ return data[i]; @}
1394 There are a number of @code{typedef}s which correspond to @code{typedef}s
1395 from the @acronym{JNI}. Each is the type of an array holding objects
1396 of the relevant type:
1399 typedef __JArray *jarray;
1400 typedef JArray<jobject> *jobjectArray;
1401 typedef JArray<jboolean> *jbooleanArray;
1402 typedef JArray<jbyte> *jbyteArray;
1403 typedef JArray<jchar> *jcharArray;
1404 typedef JArray<jshort> *jshortArray;
1405 typedef JArray<jint> *jintArray;
1406 typedef JArray<jlong> *jlongArray;
1407 typedef JArray<jfloat> *jfloatArray;
1408 typedef JArray<jdouble> *jdoubleArray;
1412 @deftypemethod {template<class T>} T* elements (JArray<T> @var{array})
1413 This template function can be used to get a pointer to the elements of
1414 the @code{array}. For instance, you can fetch a pointer to the
1415 integers that make up an @code{int[]} like so:
1418 extern jintArray foo;
1419 jint *intp = elements (foo);
1422 The name of this function may change in the future.
1426 @deftypefun jobjectArray JvNewObjectArray (jsize @var{length}, jclass @var{klass}, jobject @var{init})
1427 Here @code{klass} is the type of elements of the array and
1428 @code{init} is the initial value put into every slot in the array.
1432 @subsection Creating arrays
1434 For each primitive type there is a function which can be used to
1435 create a new array of that type. The name of the function is of the
1439 JvNew@var{Type}Array
1442 @noindent For example:
1448 @noindent can be used to create an array of Java primitive boolean types.
1450 @noindent The following function definition is the template for all such functions:
1452 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1453 Create's an array @var{length} indices long.
1456 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1457 Returns the length of the @var{array}.
1464 Java methods are mapped directly into C++ methods.
1465 The header files generated by @code{gcjh}
1466 include the appropriate method definitions.
1467 Basically, the generated methods have the same names and
1468 @emph{corresponding} types as the Java methods,
1469 and are called in the natural manner.
1471 @subsection Overloading
1473 Both Java and C++ provide method overloading, where multiple
1474 methods in a class have the same name, and the correct one is chosen
1475 (at compile time) depending on the argument types.
1476 The rules for choosing the correct method are (as expected) more complicated
1477 in C++ than in Java, but given a set of overloaded methods
1478 generated by @code{gcjh} the C++ compiler will choose
1481 Common assemblers and linkers are not aware of C++ overloading,
1482 so the standard implementation strategy is to encode the
1483 parameter types of a method into its assembly-level name.
1484 This encoding is called @dfn{mangling},
1485 and the encoded name is the @dfn{mangled name}.
1486 The same mechanism is used to implement Java overloading.
1487 For C++/Java interoperability, it is important that both the Java
1488 and C++ compilers use the @emph{same} encoding scheme.
1490 @subsection Static methods
1492 Static Java methods are invoked in @acronym{CNI} using the standard
1493 C++ syntax, using the @code{::} operator rather
1494 than the @code{.} operator.
1496 @noindent For example:
1499 jint i = java::lang::Math::round((jfloat) 2.3);
1502 @noindent C++ method definition syntax is used to define a static native method.
1506 #include <java/lang/Integer>
1507 java::lang::Integer*
1508 java::lang::Integer::getInteger(jstring str)
1515 @subsection Object Constructors
1517 Constructors are called implicitly as part of object allocation
1518 using the @code{new} operator.
1520 @noindent For example:
1523 java::lang::Integer *x = new java::lang::Integer(234);
1526 Java does not allow a constructor to be a native method.
1527 This limitation can be coded round however because a constructor
1528 can @emph{call} a native method.
1531 @subsection Instance methods
1533 Calling a Java instance method from a C++ @acronym{CNI} method is done
1534 using the standard C++ syntax, e.g.:
1537 // @r{First create the Java object.}
1538 java::lang::Integer *x = new java::lang::Integer(234);
1539 // @r{Now call a method.}
1540 jint prim_value = x->intValue();
1541 if (x->longValue == 0)
1545 @noindent Defining a Java native instance method is also done the natural way:
1548 #include <java/lang/Integer.h>
1551 java::lang:Integer::doubleValue()
1553 return (jdouble) value;
1558 @subsection Interface methods
1560 In Java you can call a method using an interface reference. This is
1561 supported, but not completly. @xref{Interfaces}.
1569 @acronym{CNI} provides a number of utility functions for
1570 working with Java Java @code{String} objects.
1571 The names and interfaces are analogous to those of @acronym{JNI}.
1574 @deftypefun jstring JvNewString (const char* @var{chars}, jsize @var{len})
1575 Returns a Java @code{String} object with characters from the C string
1576 @var{chars} up to the index @var{len} in that array.
1579 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes}, jsize @var{len})
1580 Returns a Java @code{String} made up of @var{len} bytes from @var{bytes}.
1584 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1585 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
1588 @deftypefun jstring JvNewStringUTF (const char* @var{bytes})
1589 Returns a @code{String} which is made up of the UTF encoded characters
1590 present in the C string @var{bytes}.
1593 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1594 Returns a pointer to an array of characters making up the @code{String} @var{str}.
1597 @deftypefun int JvGetStringUTFLength (jstring @var{str})
1598 Returns the number of bytes required to encode the contents of the
1599 @code{String} @var{str} in UTF-8.
1602 @deftypefun jsize JvGetStringUTFRegion (jstring @var{str}, jsize @var{start}, jsize @var{len}, char* @var{buf})
1603 Puts the UTF-8 encoding of a region of the @code{String} @var{str} into
1604 the buffer @code{buf}. The region to fetch is marked by @var{start} and @var{len}.
1606 Note that @var{buf} is a buffer, not a C string. It is @emph{not}
1611 @node Mixing with C++
1612 @section Interoperating with C/C++
1614 Because @acronym{CNI} is designed to represent Java classes and methods it
1615 cannot be mixed readily with C/C++ types.
1617 One important restriction is that Java classes cannot have non-Java
1618 type instance or static variables and cannot have methods which take
1619 non-Java types as arguments or return non-Java types.
1621 @noindent None of the following is possible with CNI:
1625 class ::MyClass : public java::lang::Object
1627 char* variable; // @r{char* is not a valid Java type.}
1632 ::SomeClass::someMethod (char *arg)
1637 @} // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1640 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1645 ::SomeClass::otherMethod (jstring str)
1654 But this restriction can cause a problem so @acronym{CNI} includes the
1655 @code{gnu.gcj.RawData} class. The @code{RawData} class is a
1656 @dfn{non-scanned reference} type. In other words variables declared
1657 of type @code{RawData} can contain any data and are not checked by the
1658 compiler in any way.
1660 This means that you can put C/C++ data structures (including classes)
1661 in your @acronym{CNI} classes, as long as you use the appropriate cast.
1663 @noindent Here are some examples:
1667 class ::MyClass : public java::lang::Object
1669 gnu.gcj.RawData string;
1672 gnu.gcj.RawData getText ();
1676 ::MyClass::MyClass ()
1683 ::MyClass::getText ()
1689 ::MyClass::printText ()
1691 printf("%s\n", (char*) string);
1696 @node Exception Handling
1697 @section Exception Handling
1699 While C++ and Java share a common exception handling framework,
1700 things are not yet perfectly integrated. The main issue is that the
1701 run-time type information facilities of the two
1702 languages are not integrated.
1704 Still, things work fairly well. You can throw a Java exception from
1705 C++ using the ordinary @code{throw} construct, and this
1706 exception can be caught by Java code. Similarly, you can catch an
1707 exception thrown from Java using the C++ @code{catch}
1710 @noindent Here is an example:
1714 throw new java::lang::IndexOutOfBoundsException();
1717 Normally, G++ will automatically detect when you are writing C++
1718 code that uses Java exceptions, and handle them appropriately.
1719 However, if C++ code only needs to execute destructors when Java
1720 exceptions are thrown through it, GCC will guess incorrectly. Sample
1724 struct S @{ ~S(); @};
1726 extern void bar(); // @r{Is implemented in Java and may throw exceptions.}
1735 The usual effect of an incorrect guess is a link failure, complaining of
1736 a missing routine called @code{__gxx_personality_v0}.
1738 You can inform the compiler that Java exceptions are to be used in a
1739 translation unit, irrespective of what it might think, by writing
1740 @code{#pragma GCC java_exceptions} at the head of the
1741 file. This @code{#pragma} must appear before any
1742 functions that throw or catch exceptions, or run destructors when
1743 exceptions are thrown through them.
1745 @node Synchronization
1746 @section Synchronization
1748 Each Java object has an implicit monitor.
1749 The Java VM uses the instruction @code{monitorenter} to acquire
1750 and lock a monitor, and @code{monitorexit} to release it.
1752 The corresponding CNI macros are @code{JvMonitorEnter} and
1753 @code{JvMonitorExit} (JNI has similar methods @code{MonitorEnter}
1754 and @code{MonitorExit}).
1757 The Java source language does not provide direct access to these primitives.
1758 Instead, there is a @code{synchronized} statement that does an
1759 implicit @code{monitorenter} before entry to the block,
1760 and does a @code{monitorexit} on exit from the block.
1761 Note that the lock has to be released even when the block is abnormally
1762 terminated by an exception, which means there is an implicit
1763 @code{try finally} surrounding synchronization locks.
1765 From C++, it makes sense to use a destructor to release a lock.
1766 @acronym{CNI} defines the following utility class:
1769 class JvSynchronize() @{
1771 JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
1772 ~JvSynchronize() @{ JvMonitorExit(obj); @}
1785 @noindent might become this C++ code:
1789 JvSynchronize dummy (OBJ);
1794 Java also has methods with the @code{synchronized} attribute.
1795 This is equivalent to wrapping the entire method body in a
1796 @code{synchronized} statement.
1797 (Alternatively, an implementation could require the caller to do
1798 the synchronization. This is not practical for a compiler, because
1799 each virtual method call would have to test at run-time if
1800 synchronization is needed.) Since in @command{gcj}
1801 the @code{synchronized} attribute is handled by the
1802 method implementation, it is up to the programmer
1803 of a synchronized native method to handle the synchronization
1804 (in the C++ implementation of the method).
1805 In otherwords, you need to manually add @code{JvSynchronize}
1806 in a @code{native synchornized} method.
1811 CNI permits C++ applications to make calls into Java classes, in addition to
1812 allowing Java code to call into C++. Several functions, known as the
1813 @dfn{invocation API}, are provided to support this.
1815 @deftypefun jint JvCreateJavaVM (void* @var{vm_args})
1816 Initializes the Java runtime. This function performs essential initialization
1817 of the threads interface, garbage collector, exception handling and other key
1818 aspects of the runtime. It must be called once by an application with
1819 a non-Java @code{main()} function, before any other Java or CNI calls are made.
1820 It is safe, but not recommended, to call @code{JvCreateJavaVM()} more than
1821 once provided it is only called from a single thread.
1822 The @var{vmargs} parameter can be used to specify initialization parameters
1823 for the Java runtime. It may be @code{NULL}.
1824 This function returns @code{0} upon success, or @code{-1} if the runtime is
1825 already initialized.
1827 @emph{Note:} In GCJ 3.1, the @code{vm_args} parameter is ignored. It may be
1828 used in a future release.
1831 @deftypefun java::lang::Thread* JvAttachCurrentThread (jstring @var{name}, java::lang::ThreadGroup* @var{group})
1832 Registers an existing thread with the Java runtime. This must be called once
1833 from each thread, before that thread makes any other Java or CNI calls. It
1834 must be called after @code{JvCreateJavaVM}.
1835 @var{name} specifies a name for the thread. It may be @code{NULL}, in which
1836 case a name will be generated.
1837 @var{group} is the ThreadGroup in which this thread will be a member. If it
1838 is @code{NULL}, the thread will be a member of the main thread group.
1839 The return value is the Java @code{Thread} object that represents the thread.
1840 It is safe to call @code{JvAttachCurrentThread()} more than once from the same
1841 thread. If the thread is already attached, the call is ignored and the current
1842 thread object is returned.
1845 @deftypefun jint JvDetachCurrentThread ()
1846 Unregisters a thread from the Java runtime. This should be called by threads
1847 that were attached using @code{JvAttachCurrentThread()}, after they have
1848 finished making calls to Java code. This ensures that any resources associated
1849 with the thread become eligible for garbage collection.
1850 This function returns @code{0} upon success, or @code{-1} if the current thread
1854 @subsection Handling uncaught exceptions
1856 If an exception is thrown from Java code called using the invocation API, and
1857 no handler for the exception can be found, the runtime will abort the
1858 application. In order to make the application more robust, it is recommended
1859 that code which uses the invocation API be wrapped by a top-level try/catch
1860 block that catches all Java exceptions.
1864 The following code demonstrates the use of the invocation API. In this
1865 example, the C++ application initializes the Java runtime and attaches
1866 itself. The @code{java.lang.System} class is initialized in order to
1867 access its @code{out} field, and a Java string is printed. Finally, the thread
1868 is detached from the runtime once it has finished making Java calls. Everything
1869 is wrapped with a try/catch block to provide a default handler for any uncaught
1872 The example can be compiled with @command{c++ test.cc -lgcj}.
1876 #include <gcj/cni.h>
1877 #include <java/lang/System.h>
1878 #include <java/io/PrintStream.h>
1879 #include <java/lang/Throwable.h>
1881 int main(int argc, char *argv)
1883 using namespace java::lang;
1887 JvCreateJavaVM(NULL);
1888 JvAttachCurrentThread(NULL, NULL);
1890 String *message = JvNewStringLatin1("Hello from C++");
1891 JvInitClass(&System.class$);
1892 System::out->println(message);
1894 JvDetachCurrentThread();
1896 catch (Throwable *t)
1898 System::err->println(JvNewStringLatin1("Unhandled Java exception:"));
1899 t->printStackTrace();
1907 Reflection is possible with CNI code, it functions similarly to how it
1908 functions with JNI@.
1910 @c clean this up... I mean, what are the types jfieldID and jmethodID in JNI?
1911 The types @code{jfieldID} and @code{jmethodID}
1914 @noindent The functions:
1917 @item @code{JvFromReflectedField},
1918 @item @code{JvFromReflectedMethod},
1919 @item @code{JvToReflectedField}
1920 @item @code{JvToFromReflectedMethod}
1923 @noindent will be added shortly, as will other functions corresponding to JNI@.
1930 While writing @command{gcj} and @code{libgcj} we have, of course, relied
1931 heavily on documentation from Sun Microsystems. In particular we have
1932 used The Java Language Specification (both first and second editions),
1933 the Java Class Libraries (volumes one and two), and the Java Virtual
1934 Machine Specification. In addition we've used the online documentation
1935 at @uref{http://java.sun.com/}.
1937 The current @command{gcj} home page is
1938 @uref{http://gcc.gnu.org/java/}.
1940 For more information on gcc, see @uref{http://gcc.gnu.org/}.
1942 Some @code{libgcj} testing is done using the Mauve test suite. This is
1943 a free software Java class library test suite which is being written
1944 because the JCK is not free. See
1945 @uref{http://sources.redhat.com/mauve/} for more information.