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{--resource} @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{--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.)
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 important, 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}.
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.
265 This is an environment variable which holds a list of paths.
268 The final class path is constructed like so:
272 First come all directories specified via @code{-I}.
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.
281 If @code{--bootclasspath} was specified, append its value.
282 Otherwise, append the built-in system directory, @file{libgcj.jar}.
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}.
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.)
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.
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.
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
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.
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.
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.
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}.
345 @item -Wextraneous-semicolon
346 This causes @command{gcj} to warn about empty statements. Empty statements
347 have been deprecated.
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
355 This is the same as @command{gcc}'s @code{-Wunused}.
358 This is the same as @code{-Wredundant-modifiers -Wextraneous-semicolon
363 @node Code Generation
364 @section Code Generation
366 In addition to the many @command{gcc} options controlling code generation,
367 @command{gcj} has several options specific to itself.
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.}
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.
387 This option is used to tell @command{gcj} to generate bytecode
388 (@file{.class} files) rather than object code.
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
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
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}.
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}.
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
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.
440 @node Configure-time Options
441 @section Configure-time Options
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.
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
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.
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
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
477 @chapter Compatibility with the Java Platform
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
485 This list of compatibility issues is by no means complete.
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
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.
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.
510 @chapter Invoking gcjh
512 @c man title gcjh generate header files from Java class files
514 @c man begin DESCRIPTION gcjh
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.
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{}
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}.
541 @c man begin OPTIONS gcjh
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
551 This tells @code{gcjh} to generate a JNI header or stub. By default,
552 CNI headers are generated.
554 @item -add @var{text}
555 Inserts @var{text} into the class body. This is ignored in JNI mode.
557 @item -append @var{text}
558 Inserts @var{text} into the header file after the class declaration.
559 This is ignored in JNI mode.
561 @item -friend @var{text}
562 Inserts @var{text} into the class as a @code{friend} declaration.
563 This is ignored in JNI mode.
565 @item -prepend @var{text}
566 Inserts @var{text} into the header file before the class declaration.
567 This is ignored in JNI mode.
569 @item --classpath=@var{path}
570 @itemx --CLASSPATH=@var{path}
571 @itemx -I@var{directory}
572 @itemx -d @var{directory}
574 These options are all identical to the corresponding @command{gcj} options.
577 Sets the output file name. This cannot be used if there is more than
578 one class on the command line.
580 @item -td @var{directory}
581 Sets the name of the directory to use for temporary files.
584 Print all dependencies to stdout; suppress ordinary output.
587 Print non-system dependencies to stdout; suppress ordinary output.
590 Print all dependencies to stdout.
593 Print non-system dependencies to stdout.
596 Print help about @code{gcjh} and exit. No further processing is done.
599 Print version information for @code{gcjh} and exit. No further
603 Print extra information while running.
606 All remaining options are considered to be names of classes.
610 @node Invoking jv-scan
611 @chapter Invoking jv-scan
613 @c man title jv-scan print information about Java source file
615 @c man begin DESCRIPTION jv-scan
617 The @code{jv-scan} program can be used to print information about a Java
618 source file (@file{.java} file).
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{}
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}.
635 @c man begin OPTIONS jv-scan
639 This prints a complexity measure, related to cyclomatic complexity, for
642 @item --encoding=@var{name}
643 This works like the corresponding @command{gcj} option.
646 This prints the name of the class in this file containing a @code{main}
650 This lists the names of all classes defined in the input files.
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.
657 Print output to the named file.
660 Print help, then exit.
663 Print version number, then exit.
668 @node Invoking jcf-dump
669 @chapter Invoking jcf-dump
671 @c man title jcf-dump print information about Java class files
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{}
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}.
687 @c man begin DESCRIPTION jcf-dump
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
695 @c man begin OPTIONS jcf-dump
699 Disassemble method bodies. By default method bodies are not printed.
702 Generate output in @code{javap} format. The implementation of this
703 feature is very incomplete.
705 @item --classpath=@var{path}
706 @itemx --CLASSPATH=@var{path}
707 @itemx -I@var{directory}
709 These options as the same as the corresponding @command{gcj} options.
712 Print help, then exit.
715 Print version number, then exit.
718 Print extra information while running.
724 @chapter Invoking gij
726 @c man title gij GNU interpreter for Java bytecode
729 @c man begin SYNOPSIS gij
730 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
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}]
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}.
743 @c man begin DESCRIPTION gij
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}.
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.
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
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.
762 @code{gij} will invoke the @code{main} method with all the remaining
763 command-line options.
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.
772 @c man begin OPTIONS gij
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}
782 @item -ms=@var{number}
783 This sets the initial heap size.
785 @item -mx=@var{number}
786 This sets the maximum heap size.
789 This indicates that the name passed to @code{gij} should be interpreted
790 as the name of a jar file, not a class.
793 Print help, then exit.
796 Print version number, then exit.
801 @node Invoking jv-convert
802 @chapter Invoking jv-convert
804 @c man title jv-convert Convert file from one encoding to another
806 @c man begin SYNOPSIS jv-convert
807 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
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}]
818 @c man begin DESCRIPTION jv-convert
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.
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.
829 @c man begin OPTIONS jv-convert
832 @item --encoding @var{name}
833 @itemx --from @var{name}
834 Use @var{name} as the input encoding. The default is the current
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.
843 Read from @var{file}. The default is to read from standard input.
846 Write to @var{file}. The default is to write to standard output.
849 Swap the input and output encodings.
852 Print a help message, then exit.
855 Print version information, then exit.
861 @chapter Invoking rmic
863 @c man title rmic Generate stubs for Remote Method Invocation
865 @c man begin SYNOPSIS rmic
866 @command{rmic} [@option{OPTION}] @dots{} @var{class} @dots{}
869 [@option{-keepgenerated}]
873 [@option{-nocompile}]
875 [@option{-d} @var{directory}]
881 @c man begin DESCRIPTION rmic
883 @command{rmic} is a utility included with @code{libgcj} which generates
884 stubs for remote objects.
886 @c FIXME: Add real information here.
887 @c This really isn't much more than the --help output.
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.
894 Long options can also be given with a GNU-style leading @samp{--}. For
895 instance, @option{--help} is accepted.
899 @c man begin OPTIONS rmic
903 @itemx -keepgenerated
904 By default, @command{rmic} deletes intermediate files. Either of these
905 options causes it not to delete such files.
908 Cause @command{rmic} to create stubs and skeletons for the 1.1
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.
916 Cause @command{rmic} to create stubs and skeletons for the 1.2
920 Don't compile the generated files.
923 Print information about what @command{rmic} is doing.
925 @item -d @var{directory}
926 Put output files in @var{directory}. By default the files are put in
927 the current working directory.
930 Print a help message, then exit.
933 Print version information, then exit.
939 @node Invoking rmiregistry
940 @chapter Invoking rmiregistry
942 @c man title rmiregistry Remote object registry
944 @c man begin SYNOPSIS rmiregistry
945 @command{rmic} [@option{OPTION}] @dots{} [@var{port}]
952 @c man begin DESCRIPTION rmiregistry
954 @command{rmiregistry} starts a remote object registry on the current
955 host. If no port number is specified, then port 1099 is used.
957 @c FIXME: Add real information here.
958 @c This really isn't much more than the --help output.
962 @c man begin OPTIONS rmiregistry
966 Print a help message, then exit.
969 Print version information, then exit.
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).
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++.
1002 @node Basic concepts
1003 @section Basic concepts
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.
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.
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++.)
1032 @noindent A CNI C++ source file must have:
1035 #include <gcj/cni.h>
1038 @noindent and then must include one header file for each Java class it uses, e.g.:
1041 #include <java/lang/Character.h>
1042 #include <java/util/Date.h>
1043 #include <java/lang/IndexOutOfBoundsException.h>
1046 @noindent These header files are automatically generated by @code{gcjh}.
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.)
1060 @subsection Limitations
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.
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.
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.
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}.
1085 @noindent Here is how you could express this:
1088 (// @r{Declare the class(es), possibly in a header file:}
1097 class java::lang::String : public java::lang::Object
1103 @noindent The @code{gcjh} tool automatically generates the nessary namespace
1107 @subsection Leaving out package names
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.
1124 import @var{package-name}.@var{class-name};
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}}.
1131 @noindent To achieve the same effect C++, you have to do this:
1134 using @var{package-name}::@var{class-name};
1138 @noindent Java can also cause imports on demand, like this:
1141 import @var{package-name}.*;
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.
1148 @noindent The same effect can be achieved in C++ like this:
1151 using namespace @var{package-name};
1155 @node Primitive types
1156 @section Primitive types
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:
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
1177 When refering to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1178 to avoid disappointment.
1181 @subsection Reference types associated with primitive types
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
1188 @deffn macro JvPrimClass type
1189 Return a pointer to the @code{Class} object corresponding to the type supplied.
1192 JvPrimClass(void) @result{} java.lang.Void.TYPE
1201 A Java class can @dfn{implement} zero or more
1202 @dfn{interfaces}, in addition to inheriting from
1203 a single base class.
1205 @acronym{CNI} allows CNI code to implement methods of interfaces.
1206 You can also call methods through interface references, with some
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
1215 For example if you have:
1223 interface B extends A
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.
1232 @node Objects and Classes
1233 @section Objects and Classes
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}.
1243 Interface inheritance (the @code{implements} keyword) is currently not
1244 reflected in the C++ mapping.
1247 @subsection Object fields
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.)
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.
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:
1270 public Integer (int i) @{ this.i = i; @}
1271 public static zero = new Integer(0);
1278 #include <gcj/cni.h>;
1282 mult (Int *p, jint k)
1285 return Int::zero; // @r{Static member access.}
1286 return new Int(p->i * k);
1291 @subsection Access specifiers
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.
1301 @node Class Initialization
1302 @section Class Initialization
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
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
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.
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).
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++.
1346 @node Object allocation
1347 @section Object allocation
1349 New Java objects are allocated using a
1350 @dfn{class instance creation expression}, e.g.:
1353 new @var{Type} ( ... )
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.
1365 @noindent For example:
1368 java::util::Hashtable *ht = new java::util::Hashtable(120);
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.
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.
1387 Referencing a Java array in C++ code is done using the
1388 @code{JArray} template, which as defined as follows:
1391 class __JArray : public java::lang::Object
1398 class JArray : public __JArray
1402 T& operator[](jint i) @{ return data[i]; @}
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:
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;
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:
1431 extern jintArray foo;
1432 jint *intp = elements (foo);
1435 The name of this function may change in the future.
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.
1445 @subsection Creating arrays
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
1452 JvNew@var{Type}Array
1455 @noindent For example:
1461 @noindent can be used to create an array of Java primitive boolean types.
1463 @noindent The following function definition is the template for all such functions:
1465 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1466 Create's an array @var{length} indices long.
1469 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1470 Returns the length of the @var{array}.
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.
1484 @subsection Overloading
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
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.
1503 @subsection Static methods
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.
1509 @noindent For example:
1512 jint i = java::lang::Math::round((jfloat) 2.3);
1515 @noindent C++ method definition syntax is used to define a static native method.
1519 #include <java/lang/Integer>
1520 java::lang::Integer*
1521 java::lang::Integer::getInteger(jstring str)
1528 @subsection Object Constructors
1530 Constructors are called implicitly as part of object allocation
1531 using the @code{new} operator.
1533 @noindent For example:
1536 java::lang::Integer *x = new java::lang::Integer(234);
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.
1544 @subsection Instance methods
1546 Calling a Java instance method from a C++ @acronym{CNI} method is done
1547 using the standard C++ syntax, e.g.:
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)
1558 @noindent Defining a Java native instance method is also done the natural way:
1561 #include <java/lang/Integer.h>
1564 java::lang:Integer::doubleValue()
1566 return (jdouble) value;
1571 @subsection Interface methods
1573 In Java you can call a method using an interface reference. This is
1574 supported, but not completly. @xref{Interfaces}.
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}.
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.
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}.
1597 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1598 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
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}.
1606 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1607 Returns a pointer to an array of characters making up the @code{String} @var{str}.
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.
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}.
1619 Note that @var{buf} is a buffer, not a C string. It is @emph{not}
1624 @node Mixing with C++
1625 @section Interoperating with C/C++
1627 Because @acronym{CNI} is designed to represent Java classes and methods it
1628 cannot be mixed readily with C/C++ types.
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.
1634 @noindent None of the following is possible with CNI:
1638 class ::MyClass : public java::lang::Object
1640 char* variable; // @r{char* is not a valid Java type.}
1645 ::SomeClass::someMethod (char *arg)
1650 @} // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1653 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1658 ::SomeClass::otherMethod (jstring str)
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.
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.
1676 @noindent Here are some examples:
1680 class ::MyClass : public java::lang::Object
1682 gnu.gcj.RawData string;
1685 gnu.gcj.RawData getText ();
1689 ::MyClass::MyClass ()
1696 ::MyClass::getText ()
1702 ::MyClass::printText ()
1704 printf("%s\n", (char*) string);
1709 @node Exception Handling
1710 @section Exception Handling
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.
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}
1723 @noindent Here is an example:
1727 throw new java::lang::IndexOutOfBoundsException();
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
1737 struct S @{ ~S(); @};
1739 extern void bar(); // @r{Is implemented in Java and may throw exceptions.}
1748 The usual effect of an incorrect guess is a link failure, complaining of
1749 a missing routine called @code{__gxx_personality_v0}.
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.
1758 @node Synchronization
1759 @section Synchronization
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.
1765 The corresponding CNI macros are @code{JvMonitorEnter} and
1766 @code{JvMonitorExit} (JNI has similar methods @code{MonitorEnter}
1767 and @code{MonitorExit}).
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.
1778 From C++, it makes sense to use a destructor to release a lock.
1779 @acronym{CNI} defines the following utility class:
1782 class JvSynchronize() @{
1784 JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
1785 ~JvSynchronize() @{ JvMonitorExit(obj); @}
1798 @noindent might become this C++ code:
1802 JvSynchronize dummy (OBJ);
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.
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.
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.
1840 @emph{Note:} In GCJ 3.1, the @code{vm_args} parameter is ignored. It may be
1841 used in a future release.
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.
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
1867 @subsection Handling uncaught exceptions
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.
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
1885 The example can be compiled with @command{c++ test.cc -lgcj}.
1889 #include <gcj/cni.h>
1890 #include <java/lang/System.h>
1891 #include <java/io/PrintStream.h>
1892 #include <java/lang/Throwable.h>
1894 int main(int argc, char *argv)
1896 using namespace java::lang;
1900 JvCreateJavaVM(NULL);
1901 JvAttachCurrentThread(NULL, NULL);
1903 String *message = JvNewStringLatin1("Hello from C++");
1904 JvInitClass(&System::class$);
1905 System::out->println(message);
1907 JvDetachCurrentThread();
1909 catch (Throwable *t)
1911 System::err->println(JvNewStringLatin1("Unhandled Java exception:"));
1912 t->printStackTrace();
1920 Reflection is possible with CNI code, it functions similarly to how it
1921 functions with JNI@.
1923 @c clean this up... I mean, what are the types jfieldID and jmethodID in JNI?
1924 The types @code{jfieldID} and @code{jmethodID}
1927 @noindent The functions:
1930 @item @code{JvFromReflectedField},
1931 @item @code{JvFromReflectedMethod},
1932 @item @code{JvToReflectedField}
1933 @item @code{JvToFromReflectedMethod}
1936 @noindent will be added shortly, as will other functions corresponding to JNI@.
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/}.
1950 The current @command{gcj} home page is
1951 @uref{http://gcc.gnu.org/java/}.
1953 For more information on gcc, see @uref{http://gcc.gnu.org/}.
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.