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}.
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 -R @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 @var{core:/resource-name}.
395 @item -d @var{directory}
396 When used with @code{-C}, this causes all generated @file{.class} files
397 to be put in the appropriate subdirectory of @var{directory}. By
398 default they will be put in subdirectories of the current working
401 @item -fno-bounds-check
402 By default, @command{gcj} generates code which checks the bounds of all
403 array indexing operations. With this option, these checks are omitted, which
404 can improve performance for code that uses arrays extensively. Note that this
405 can result in unpredictable behavior if the code in question actually does
406 violate array bounds constraints. It is safe to use this option if you are
407 sure that your code will never throw an @code{ArrayIndexOutOfBoundsException}.
409 @item -fno-store-check
410 Don't generate array store checks. When storing objects into arrays, a runtime
411 check is normally generated in order to ensure that the object is assignment
412 compatible with the component type of the array (which may not be known
413 at compile-time). With this option, these checks are omitted. This can
414 improve performance for code which stores objects into arrays frequently.
415 It is safe to use this option if you are sure your code will never throw an
416 @code{ArrayStoreException}.
419 With @command{gcj} there are two options for writing native methods: CNI
420 and JNI@. By default @command{gcj} assumes you are using CNI@. If you are
421 compiling a class with native methods, and these methods are implemented
422 using JNI, then you must use @code{-fjni}. This option causes
423 @command{gcj} to generate stubs which will invoke the underlying JNI
426 @item -fno-optimize-static-class-initialization
427 When the optimization level is greather or equal to @code{-O2},
428 @command{gcj} will try to optimize the way calls into the runtime are made
429 to initialize static classes upon their first use (this optimization
430 isn't carried out if @code{-C} was specified.) When compiling to native
431 code, @code{-fno-optimize-static-class-initialization} will turn this
432 optimization off, regardless of the optimization level in use.
436 @node Configure-time Options
437 @section Configure-time Options
439 Some @command{gcj} code generations options affect the resulting ABI, and
440 so can only be meaningfully given when @code{libgcj}, the runtime
441 package, is configured. @code{libgcj} puts the appropriate options from
442 this group into a @samp{spec} file which is read by @command{gcj}. These
443 options are listed here for completeness; if you are using @code{libgcj}
444 then you won't want to touch these options.
448 This enables the use of the Boehm GC bitmap marking code. In particular
449 this causes @command{gcj} to put an object marking descriptor into each
452 @item -fhash-synchronization
453 By default, synchronization data (the data used for @code{synchronize},
454 @code{wait}, and @code{notify}) is pointed to by a word in each object.
455 With this option @command{gcj} assumes that this information is stored in a
456 hash table and not in the object itself.
458 @item -fuse-divide-subroutine
459 On some systems, a library routine is called to perform integer
460 division. This is required to get exception handling correct when
463 @item -fcheck-references
464 On some systems it's necessary to insert inline checks whenever
465 accessing an object via a reference. On other systems you won't need
466 this because null pointer accesses are caught automatically by the
473 @chapter Compatibility with the Java Platform
475 As we believe it is important that the Java platform not be fragmented,
476 @command{gcj} and @code{libgcj} try to conform to the relevant Java
477 specifications. However, limited manpower and incomplete and unclear
478 documentation work against us. So, there are caveats to using
481 This list of compatibility issues is by no means complete.
485 @command{gcj} implements the JDK 1.1 language. It supports inner classes,
486 though these are known to still be buggy. It does not yet support the
487 Java 2 @code{strictfp} keyword (it recognizes the keyword but ignores
491 @code{libgcj} is largely compatible with the JDK 1.2 libraries.
492 However, @code{libgcj} is missing many packages, most notably
493 @code{java.awt}. There are also individual missing classes and methods.
494 We currently do not have a list showing differences between
495 @code{libgcj} and the Java 2 platform.
498 Sometimes the @code{libgcj} implementation of a method or class differs
499 from the JDK implementation. This is not always a bug. Still, if it
500 affects you, it probably makes sense to report it so that we can discuss
501 the appropriate response.
506 @chapter Invoking gcjh
508 @c man title gcjh generate header files from Java class files
510 @c man begin DESCRIPTION gcjh
512 The @code{gcjh} program is used to generate header files from class
513 files. It can generate both CNI and JNI header files, as well as stub
514 implementation files which can be used as a basis for implementing the
515 required native methods.
520 @c man begin SYNOPSIS gcjh
521 gcjh [@option{-stubs}] [@option{-jni}]
522 [@option{-add} @var{text}] [@option{-append} @var{text}] [@option{-friend} @var{text}]
523 [@option{-preprend} @var{text}]
524 [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
525 [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
526 [@option{-o} @var{file}] [@option{-td} @var{dir}]
527 [@option{-M}] [@option{-MM}] [@option{-MD}] [@option{-MMD}]
528 [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
529 @var{classname}@dots{}
531 @c man begin SEEALSO gcjh
532 gcc(1), gcj(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
533 and the Info entries for @file{gcj} and @file{gcc}.
537 @c man begin OPTIONS gcjh
541 This causes @code{gcjh} to generate stub files instead of header files.
542 By default the stub file will be named after the class, with a suffix of
543 @samp{.cc}. In JNI mode, the default output file will have the suffix
547 This tells @code{gcjh} to generate a JNI header or stub. By default,
548 CNI headers are generated.
550 @item -add @var{text}
551 Inserts @var{text} into the class body. This is ignored in JNI mode.
553 @item -append @var{text}
554 Inserts @var{text} into the header file after the class declaration.
555 This is ignored in JNI mode.
557 @item -friend @var{text}
558 Inserts @var{text} into the class as a @code{friend} declaration.
559 This is ignored in JNI mode.
561 @item -prepend @var{text}
562 Inserts @var{text} into the header file before the class declaration.
563 This is ignored in JNI mode.
565 @item --classpath=@var{path}
566 @itemx --CLASSPATH=@var{path}
567 @itemx -I@var{directory}
568 @itemx -d @var{directory}
570 These options are all identical to the corresponding @command{gcj} options.
573 Sets the output file name. This cannot be used if there is more than
574 one class on the command line.
576 @item -td @var{directory}
577 Sets the name of the directory to use for temporary files.
580 Print all dependencies to stdout; suppress ordinary output.
583 Print non-system dependencies to stdout; suppress ordinary output.
586 Print all dependencies to stdout.
589 Print non-system dependencies to stdout.
592 Print help about @code{gcjh} and exit. No further processing is done.
595 Print version information for @code{gcjh} and exit. No further
599 Print extra information while running.
602 All remaining options are considered to be names of classes.
606 @node Invoking jv-scan
607 @chapter Invoking jv-scan
609 @c man title jv-scan print information about Java source file
611 @c man begin DESCRIPTION jv-scan
613 The @code{jv-scan} program can be used to print information about a Java
614 source file (@file{.java} file).
619 @c man begin SYNOPSIS jv-scan
620 jv-scan [@option{--complexity}] [@option{--encoding}=@var{name}]
621 [@option{--print-main}] [@option{--list-class}] [@option{--list-filename}]
622 [@option{--version}] [@option{--help}]
623 [@option{-o} @var{file}] @var{inputfile}@dots{}
625 @c man begin SEEALSO jv-scan
626 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
627 and the Info entries for @file{gcj} and @file{gcc}.
631 @c man begin OPTIONS jv-scan
635 This prints a complexity measure, related to cyclomatic complexity, for
638 @item --encoding=@var{name}
639 This works like the corresponding @command{gcj} option.
642 This prints the name of the class in this file containing a @code{main}
646 This lists the names of all classes defined in the input files.
648 @item --list-filename
649 If @code{--list-class} is given, this option causes @code{jv-scan} to
650 also print the name of the file in which each class was found.
653 Print output to the named file.
656 Print help, then exit.
659 Print version number, then exit.
664 @node Invoking jcf-dump
665 @chapter Invoking jcf-dump
667 @c man title jcf-dump print information about Java class files
670 @c man begin SYNOPSIS jcf-dump
671 jcf-dump [@option{-c}] [@option{--javap}]
672 [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
673 [@option{-I}@var{dir}@dots{}] [@option{-o} @var{file}]
674 [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
675 @var{classname}@dots{}
677 @c man begin SEEALSO jcf-dump
678 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
679 and the Info entries for @file{gcj} and @file{gcc}.
683 @c man begin DESCRIPTION jcf-dump
685 This is a class file examiner, similar to @code{javap}. It will print
686 information about a number of classes, which are specifed by class name
691 @c man begin OPTIONS jcf-dump
695 Disassemble method bodies. By default method bodies are not printed.
698 Generate output in @code{javap} format. The implementation of this
699 feature is very incomplete.
701 @item --classpath=@var{path}
702 @itemx --CLASSPATH=@var{path}
703 @itemx -I@var{directory}
705 These options as the same as the corresponding @command{gcj} options.
708 Print help, then exit.
711 Print version number, then exit.
714 Print extra information while running.
720 @chapter Invoking gij
722 @c man title gij GNU interpreter for Java bytecode
725 @c man begin SYNOPSIS gij
726 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
728 gij [@option{-jar}] [@option{OPTION}] @dots{} @var{CLASS} [@var{ARGS}@dots{}]
729 [@option{-D}@var{name}[=@var{value}]@dots{}]
730 [@option{-ms=}@var{number}] [@option{-mx=}@var{number}]
731 [@option{--version}] [@option{--help}]
733 @c man begin SEEALSO gij
734 gcc(1), gcj(1), gcjh(1), jv-scan(1), jcf-dump(1), gfdl(7),
735 and the Info entries for @file{gcj} and @file{gcc}.
739 @c man begin DESCRIPTION gij
741 @code{gij} is a Java bytecode interpreter included with @code{libgcj}.
742 @code{gij} is not available on every platform; porting it requires a
743 small amount of assembly programming which has not been done for all the
744 targets supported by @command{gcj}.
746 The primary argument to @code{gij} is the name of a class or, with
747 @code{-jar}, a jar file. Options before this argument are interpreted
748 by @code{gij}; remaining options are passed to the interpreted program.
750 If a class name is specified and this class does not have a @code{main}
751 method with the appropriate signature (a @code{static void} method with
752 a @code{String[]} as its sole argument), then @code{gij} will print an
755 If a jar file is specified then @code{gij} will use information in it to
756 determine which class' @code{main} method will be invoked.
758 @code{gij} will invoke the @code{main} method with all the remaining
759 command-line options.
761 Note that @code{gij} is not limited to interpreting code. Because
762 @code{libgcj} includes a class loader which can dynamically load shared
763 objects, it is possible to give @code{gij} the name of a class which has
764 been compiled and put into a shared library on the class path.
768 @c man begin OPTIONS gij
771 @item -D@var{name}[=@var{value}]
772 This defines a system property named @var{name} with value @var{value}.
773 If @var{value} is not specified then it defaults to the empty string.
774 These system properties are initialized at the program's startup and can
775 be retrieved at runtime using the @code{java.lang.System.getProperty}
778 @item -ms=@var{number}
779 This sets the initial heap size.
781 @item -mx=@var{number}
782 This sets the maximum heap size.
785 This indicates that the name passed to @code{gij} should be interpreted
786 as the name of a jar file, not a class.
789 Print help, then exit.
792 Print version number, then exit.
797 @node Invoking jv-convert
798 @chapter Invoking jv-convert
800 @c man title jv-convert Convert file from one encoding to another
802 @c man begin SYNOPSIS jv-convert
803 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
806 [@option{--encoding} @var{name}]
807 [@option{--from} @var{name}]
808 [@option{--to} @var{name}]
809 [@option{-i} @var{file}] [@option{-o} @var{file}]
810 [@option{--reverse}] [@option{--help}] [@option{--version}]
814 @c man begin DESCRIPTION jv-convert
816 @command{jv-convert} is a utility included with @code{libgcj} which
817 converts a file from one encoding to another. It is similar to the Unix
818 @command{iconv} utility.
820 The encodings supported by @command{jv-convert} are platform-dependent.
821 Currently there is no way to get a list of all supported encodings.
825 @c man begin OPTIONS jv-convert
828 @item --encoding @var{name}
829 @itemx --from @var{name}
830 Use @var{name} as the input encoding. The default is the current
833 @item --to @var{name}
834 Use @var{name} as the output encoding. The default is the
835 @code{JavaSrc} encoding; this is ASCII with @samp{\u} escapes for
836 non-ASCII characters.
839 Read from @var{file}. The default is to read from standard input.
842 Write to @var{file}. The default is to write to standard output.
845 Swap the input and output encodings.
848 Print a help message, then exit.
851 Print version information, then exit.
857 @chapter Invoking rmic
859 @c man title rmic Generate stubs for Remote Method Invocation
861 @c man begin SYNOPSIS rmic
862 @command{rmic} [@option{OPTION}] @dots{} @var{class} @dots{}
865 [@option{-keepgenerated}]
869 [@option{-nocompile}]
871 [@option{-d} @var{directory}]
877 @c man begin DESCRIPTION rmic
879 @command{rmic} is a utility included with @code{libgcj} which generates
880 stubs for remote objects.
882 @c FIXME: Add real information here.
883 @c This really isn't much more than the --help output.
885 Note that this program isn't yet fully compatible with the JDK
886 @command{rmic}. Some options, such as @option{-classpath}, are
887 recognized but currently ignored. We have left these options
888 undocumented for now.
890 Long options can also be given with a GNU-style leading @samp{--}. For
891 instance, @option{--help} is accepted.
895 @c man begin OPTIONS rmic
899 @itemx -keepgenerated
900 By default, @command{rmic} deletes intermediate files. Either of these
901 options causes it not to delete such files.
904 Cause @command{rmic} to create stubs and skeletons for the 1.1
908 Cause @command{rmic} to create stubs and skeletons compatible with both
909 the 1.1 and 1.2 protocol versions. This is the default.
912 Cause @command{rmic} to create stubs and skeletons for the 1.2
916 Don't compile the generated files.
919 Print information about what @command{rmic} is doing.
921 @item -d @var{directory}
922 Put output files in @var{directory}. By default the files are put in
923 the current working directory.
926 Print a help message, then exit.
929 Print version information, then exit.
935 @node Invoking rmiregistry
936 @chapter Invoking rmiregistry
938 @c man title rmiregistry Remote object registry
940 @c man begin SYNOPSIS rmiregistry
941 @command{rmic} [@option{OPTION}] @dots{} [@var{port}]
948 @c man begin DESCRIPTION rmiregistry
950 @command{rmiregistry} starts a remote object registry on the current
951 host. If no port number is specified, then port 1099 is used.
953 @c FIXME: Add real information here.
954 @c This really isn't much more than the --help output.
958 @c man begin OPTIONS rmiregistry
962 Print a help message, then exit.
965 Print version information, then exit.
974 This documents CNI, the Cygnus Native Interface,
975 which is is a convenient way to write Java native methods using C++.
976 This is a more efficient, more convenient, but less portable
977 alternative to the standard JNI (Java Native Interface).
980 * Basic concepts:: Introduction to using CNI@.
981 * Packages:: How packages are mapped to C++.
982 * Primitive types:: Handling Java types in C++.
983 * Interfaces:: How Java interfaces map to C++.
984 * Objects and Classes:: C++ and Java classes.
985 * Class Initialization:: How objects are initialized.
986 * Object allocation:: How to create Java objects in C++.
987 * Arrays:: Dealing with Java arrays in C++.
988 * Methods:: Java methods in C++.
989 * Strings:: Information about Java Strings.
990 * Mixing with C++:: How CNI can interoperate with C++.
991 * Exception Handling:: How exceptions are handled.
992 * Synchronization:: Synchronizing between Java and C++.
993 * Invocation:: Starting the Java runtime from C++.
994 * Reflection:: Using reflection from C++.
999 @section Basic concepts
1001 In terms of languages features, Java is mostly a subset
1002 of C++. Java has a few important extensions, plus a powerful standard
1003 class library, but on the whole that does not change the basic similarity.
1004 Java is a hybrid object-oriented language, with a few native types,
1005 in addition to class types. It is class-based, where a class may have
1006 static as well as per-object fields, and static as well as instance methods.
1007 Non-static methods may be virtual, and may be overloaded. Overloading is
1008 resolved at compile time by matching the actual argument types against
1009 the parameter types. Virtual methods are implemented using indirect calls
1010 through a dispatch table (virtual function table). Objects are
1011 allocated on the heap, and initialized using a constructor method.
1012 Classes are organized in a package hierarchy.
1014 All of the listed attributes are also true of C++, though C++ has
1015 extra features (for example in C++ objects may be allocated not just
1016 on the heap, but also statically or in a local stack frame). Because
1017 @command{gcj} uses the same compiler technology as G++ (the GNU
1018 C++ compiler), it is possible to make the intersection of the two
1019 languages use the same ABI (object representation and calling
1020 conventions). The key idea in CNI is that Java objects are C++
1021 objects, and all Java classes are C++ classes (but not the other way
1022 around). So the most important task in integrating Java and C++ is to
1023 remove gratuitous incompatibilities.
1025 You write CNI code as a regular C++ source file. (You do have to use
1026 a Java/CNI-aware C++ compiler, specifically a recent version of G++.)
1028 @noindent A CNI C++ source file must have:
1031 #include <gcj/cni.h>
1034 @noindent and then must include one header file for each Java class it uses, e.g.:
1037 #include <java/lang/Character.h>
1038 #include <java/util/Date.h>
1039 #include <java/lang/IndexOutOfBoundsException.h>
1042 @noindent These header files are automatically generated by @code{gcjh}.
1045 CNI provides some functions and macros to make using Java objects and
1046 primitive types from C++ easier. In general, these CNI functions and
1047 macros start with the @code{Jv} prefix, for example the function
1048 @code{JvNewObjectArray}. This convention is used to avoid conflicts
1049 with other libraries. Internal functions in CNI start with the prefix
1050 @code{_Jv_}. You should not call these; if you find a need to, let us
1051 know and we will try to come up with an alternate solution. (This
1052 manual lists @code{_Jv_AllocBytes} as an example; CNI should instead
1053 provide a @code{JvAllocBytes} function.)
1056 @subsection Limitations
1058 Whilst a Java class is just a C++ class that doesn't mean that you are
1059 freed from the shackles of Java, a @acronym{CNI} C++ class must adhere to the
1060 rules of the Java programming language.
1062 For example: it is not possible to declare a method in a CNI class
1063 that will take a C string (@code{char*}) as an argument, or to declare a
1064 member variable of some non-Java datatype.
1070 The only global names in Java are class names, and packages. A
1071 @dfn{package} can contain zero or more classes, and also zero or more
1072 sub-packages. Every class belongs to either an unnamed package or a
1073 package that has a hierarchical and globally unique name.
1075 A Java package is mapped to a C++ @dfn{namespace}. The Java class
1076 @code{java.lang.String} is in the package @code{java.lang}, which is a
1077 sub-package of @code{java}. The C++ equivalent is the class
1078 @code{java::lang::String}, which is in the namespace @code{java::lang}
1079 which is in the namespace @code{java}.
1081 @noindent Here is how you could express this:
1084 (// @r{Declare the class(es), possibly in a header file:}
1093 class java::lang::String : public java::lang::Object
1099 @noindent The @code{gcjh} tool automatically generates the nessary namespace
1103 @subsection Leaving out package names
1105 Always using the fully-qualified name of a java class can be
1106 tiresomely verbose. Using the full qualified name also ties the code
1107 to a single package making code changes necessary should the class
1108 move from one package to another. The Java @code{package} declaration
1109 specifies that the following class declarations are in the named
1110 package, without having to explicitly name the full package
1111 qualifiers. The @code{package} declaration can be
1112 followed by zero or more @code{import} declarations, which
1113 allows either a single class or all the classes in a package to be
1114 named by a simple identifier. C++ provides something similar with the
1115 @code{using} declaration and directive.
1120 import @var{package-name}.@var{class-name};
1123 @noindent allows the program text to refer to @var{class-name} as a shorthand for
1124 the fully qualified name: @code{@var{package-name}.@var{class-name}}.
1127 @noindent To achieve the same effect C++, you have to do this:
1130 using @var{package-name}::@var{class-name};
1134 @noindent Java can also cause imports on demand, like this:
1137 import @var{package-name}.*;
1140 @noindent Doing this allows any class from the package @var{package-name} to be
1141 refered to only by its class-name within the program text.
1144 @noindent The same effect can be achieved in C++ like this:
1147 using namespace @var{package-name};
1151 @node Primitive types
1152 @section Primitive types
1154 Java provides 8 @dfn{primitives} types which represent integers, floats,
1155 characters and booleans (and also the void type). C++ has its own
1156 very similar concrete types. Such types in C++ however are not always
1157 implemented in the same way (an int might be 16, 32 or 64 bits for example)
1158 so CNI provides a special C++ type for each primitive Java type:
1160 @multitable @columnfractions .20 .25 .60
1161 @item @strong{Java type} @tab @strong{C/C++ typename} @tab @strong{Description}
1162 @item @code{char} @tab @code{jchar} @tab 16 bit Unicode character
1163 @item @code{boolean} @tab @code{jboolean} @tab logical (true or false) values
1164 @item @code{byte} @tab @code{jbyte} @tab 8-bit signed integer
1165 @item @code{short} @tab @code{jshort} @tab 16 bit signed integer
1166 @item @code{int} @tab @code{jint} @tab 32 bit signed integer
1167 @item @code{long} @tab @code{jlong} @tab 64 bit signed integer
1168 @item @code{float} @tab @code{jfloat} @tab 32 bit IEEE floating point number
1169 @item @code{double} @tab @code{jdouble} @tab 64 bit IEEE floating point number
1170 @item @code{void} @tab @code{void} @tab no value
1173 When refering to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1174 to avoid disappointment.
1177 @subsection Reference types associated with primitive types
1179 In Java each primitive type has an associated reference type,
1180 e.g.: @code{boolean} has an associated @code{java.lang.Boolean} class.
1181 In order to make working with such classes easier GCJ provides the macro
1184 @deffn macro JvPrimClass type
1185 Return a pointer to the @code{Class} object corresponding to the type supplied.
1188 JvPrimClass(void) @result{} java.lang.Void.TYPE
1197 A Java class can @dfn{implement} zero or more
1198 @dfn{interfaces}, in addition to inheriting from
1199 a single base class.
1201 @acronym{CNI} allows CNI code to implement methods of interfaces.
1202 You can also call methods through interface references, with some
1205 @acronym{CNI} doesn't understand interface inheritance at all yet. So,
1206 you can only call an interface method when the declared type of the
1207 field being called matches the interface which declares that
1208 method. The workaround is to cast the interface reference to the right
1211 For example if you have:
1219 interface B extends A
1225 and declare a variable of type @code{B} in C++, you can't call
1226 @code{a()} unless you cast it to an @code{A} first.
1228 @node Objects and Classes
1229 @section Objects and Classes
1233 All Java classes are derived from @code{java.lang.Object}. C++ does
1234 not have a unique root class, but we use the C++ class
1235 @code{java::lang::Object} as the C++ version of the
1236 @code{java.lang.Object} Java class. All other Java classes are mapped
1237 into corresponding C++ classes derived from @code{java::lang::Object}.
1239 Interface inheritance (the @code{implements} keyword) is currently not
1240 reflected in the C++ mapping.
1243 @subsection Object fields
1245 Each object contains an object header, followed by the instance fields
1246 of the class, in order. The object header consists of a single
1247 pointer to a dispatch or virtual function table. (There may be extra
1248 fields @emph{in front of} the object, for example for memory
1249 management, but this is invisible to the application, and the
1250 reference to the object points to the dispatch table pointer.)
1252 The fields are laid out in the same order, alignment, and size as in
1253 C++. Specifically, 8-bite and 16-bit native types (@code{byte},
1254 @code{short}, @code{char}, and @code{boolean}) are @emph{not} widened
1255 to 32 bits. Note that the Java VM does extend 8-bit and 16-bit types
1256 to 32 bits when on the VM stack or temporary registers.
1258 If you include the @code{gcjh}-generated header for a
1259 class, you can access fields of Java classes in the @emph{natural}
1260 way. For example, given the following Java class:
1266 public Integer (int i) @{ this.i = i; @}
1267 public static zero = new Integer(0);
1274 #include <gcj/cni.h>;
1278 mult (Int *p, jint k)
1281 return Int::zero; // @r{Static member access.}
1282 return new Int(p->i * k);
1287 @subsection Access specifiers
1289 CNI does not strictly enforce the Java access
1290 specifiers, because Java permissions cannot be directly mapped
1291 into C++ permission. Private Java fields and methods are mapped
1292 to private C++ fields and methods, but other fields and methods
1293 are mapped to public fields and methods.
1297 @node Class Initialization
1298 @section Class Initialization
1300 Java requires that each class be automatically initialized at the time
1301 of the first active use. Initializing a class involves
1302 initializing the static fields, running code in class initializer
1303 methods, and initializing base classes. There may also be
1304 some implementation specific actions, such as allocating
1305 @code{String} objects corresponding to string literals in
1308 The GCJ compiler inserts calls to @code{JvInitClass} at appropriate
1309 places to ensure that a class is initialized when required. The C++
1310 compiler does not insert these calls automatically---it is the
1311 programmer's responsibility to make sure classes are initialized.
1312 However, this is fairly painless because of the conventions assumed by
1315 First, @code{libgcj} will make sure a class is initialized
1316 before an instance of that object is created. This is one
1317 of the responsibilities of the @code{new} operation. This is
1318 taken care of both in Java code, and in C++ code. (When the G++
1319 compiler sees a @code{new} of a Java class, it will call
1320 a routine in @code{libgcj} to allocate the object, and that
1321 routine will take care of initializing the class.) It follows that you can
1322 access an instance field, or call an instance (non-static)
1323 method and be safe in the knowledge that the class and all
1324 of its base classes have been initialized.
1326 Invoking a static method is also safe. This is because the
1327 Java compiler adds code to the start of a static method to make sure
1328 the class is initialized. However, the C++ compiler does not
1329 add this extra code. Hence, if you write a native static method
1330 using CNI, you are responsible for calling @code{JvInitClass}
1331 before doing anything else in the method (unless you are sure
1332 it is safe to leave it out).
1334 Accessing a static field also requires the class of the
1335 field to be initialized. The Java compiler will generate code
1336 to call @code{Jv_InitClass} before getting or setting the field.
1337 However, the C++ compiler will not generate this extra code,
1338 so it is your responsibility to make sure the class is
1339 initialized before you access a static field from C++.
1342 @node Object allocation
1343 @section Object allocation
1345 New Java objects are allocated using a
1346 @dfn{class instance creation expression}, e.g.:
1349 new @var{Type} ( ... )
1352 The same syntax is used in C++. The main difference is that
1353 C++ objects have to be explicitly deleted; in Java they are
1354 automatically deleted by the garbage collector.
1355 Using @acronym{CNI}, you can allocate a new Java object
1356 using standard C++ syntax and the C++ compiler will allocate
1357 memory from the garbage collector. If you have overloaded
1358 constructors, the compiler will choose the correct one
1359 using standard C++ overload resolution rules.
1361 @noindent For example:
1364 java::util::Hashtable *ht = new java::util::Hashtable(120);
1367 @deftypefun void* _Jv_AllocBytes (jsize @var{size})
1368 Allocates @var{size} bytes from the heap. The memory is not scanned
1369 by the garbage collector but it freed if no references to it are discovered.
1376 While in many ways Java is similar to C and C++, it is quite different
1377 in its treatment of arrays. C arrays are based on the idea of pointer
1378 arithmetic, which would be incompatible with Java's security
1379 requirements. Java arrays are true objects (array types inherit from
1380 @code{java.lang.Object}). An array-valued variable is one that
1381 contains a reference (pointer) to an array object.
1383 Referencing a Java array in C++ code is done using the
1384 @code{JArray} template, which as defined as follows:
1387 class __JArray : public java::lang::Object
1394 class JArray : public __JArray
1398 T& operator[](jint i) @{ return data[i]; @}
1403 There are a number of @code{typedef}s which correspond to @code{typedef}s
1404 from the @acronym{JNI}. Each is the type of an array holding objects
1405 of the relevant type:
1408 typedef __JArray *jarray;
1409 typedef JArray<jobject> *jobjectArray;
1410 typedef JArray<jboolean> *jbooleanArray;
1411 typedef JArray<jbyte> *jbyteArray;
1412 typedef JArray<jchar> *jcharArray;
1413 typedef JArray<jshort> *jshortArray;
1414 typedef JArray<jint> *jintArray;
1415 typedef JArray<jlong> *jlongArray;
1416 typedef JArray<jfloat> *jfloatArray;
1417 typedef JArray<jdouble> *jdoubleArray;
1421 @deftypemethod {template<class T>} T* elements (JArray<T> @var{array})
1422 This template function can be used to get a pointer to the elements of
1423 the @code{array}. For instance, you can fetch a pointer to the
1424 integers that make up an @code{int[]} like so:
1427 extern jintArray foo;
1428 jint *intp = elements (foo);
1431 The name of this function may change in the future.
1435 @deftypefun jobjectArray JvNewObjectArray (jsize @var{length}, jclass @var{klass}, jobject @var{init})
1436 Here @code{klass} is the type of elements of the array and
1437 @code{init} is the initial value put into every slot in the array.
1441 @subsection Creating arrays
1443 For each primitive type there is a function which can be used to
1444 create a new array of that type. The name of the function is of the
1448 JvNew@var{Type}Array
1451 @noindent For example:
1457 @noindent can be used to create an array of Java primitive boolean types.
1459 @noindent The following function definition is the template for all such functions:
1461 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1462 Create's an array @var{length} indices long.
1465 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1466 Returns the length of the @var{array}.
1473 Java methods are mapped directly into C++ methods.
1474 The header files generated by @code{gcjh}
1475 include the appropriate method definitions.
1476 Basically, the generated methods have the same names and
1477 @emph{corresponding} types as the Java methods,
1478 and are called in the natural manner.
1480 @subsection Overloading
1482 Both Java and C++ provide method overloading, where multiple
1483 methods in a class have the same name, and the correct one is chosen
1484 (at compile time) depending on the argument types.
1485 The rules for choosing the correct method are (as expected) more complicated
1486 in C++ than in Java, but given a set of overloaded methods
1487 generated by @code{gcjh} the C++ compiler will choose
1490 Common assemblers and linkers are not aware of C++ overloading,
1491 so the standard implementation strategy is to encode the
1492 parameter types of a method into its assembly-level name.
1493 This encoding is called @dfn{mangling},
1494 and the encoded name is the @dfn{mangled name}.
1495 The same mechanism is used to implement Java overloading.
1496 For C++/Java interoperability, it is important that both the Java
1497 and C++ compilers use the @emph{same} encoding scheme.
1499 @subsection Static methods
1501 Static Java methods are invoked in @acronym{CNI} using the standard
1502 C++ syntax, using the @code{::} operator rather
1503 than the @code{.} operator.
1505 @noindent For example:
1508 jint i = java::lang::Math::round((jfloat) 2.3);
1511 @noindent C++ method definition syntax is used to define a static native method.
1515 #include <java/lang/Integer>
1516 java::lang::Integer*
1517 java::lang::Integer::getInteger(jstring str)
1524 @subsection Object Constructors
1526 Constructors are called implicitly as part of object allocation
1527 using the @code{new} operator.
1529 @noindent For example:
1532 java::lang::Integer *x = new java::lang::Integer(234);
1535 Java does not allow a constructor to be a native method.
1536 This limitation can be coded round however because a constructor
1537 can @emph{call} a native method.
1540 @subsection Instance methods
1542 Calling a Java instance method from a C++ @acronym{CNI} method is done
1543 using the standard C++ syntax, e.g.:
1546 // @r{First create the Java object.}
1547 java::lang::Integer *x = new java::lang::Integer(234);
1548 // @r{Now call a method.}
1549 jint prim_value = x->intValue();
1550 if (x->longValue == 0)
1554 @noindent Defining a Java native instance method is also done the natural way:
1557 #include <java/lang/Integer.h>
1560 java::lang:Integer::doubleValue()
1562 return (jdouble) value;
1567 @subsection Interface methods
1569 In Java you can call a method using an interface reference. This is
1570 supported, but not completly. @xref{Interfaces}.
1578 @acronym{CNI} provides a number of utility functions for
1579 working with Java Java @code{String} objects.
1580 The names and interfaces are analogous to those of @acronym{JNI}.
1583 @deftypefun jstring JvNewString (const char* @var{chars}, jsize @var{len})
1584 Returns a Java @code{String} object with characters from the C string
1585 @var{chars} up to the index @var{len} in that array.
1588 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes}, jsize @var{len})
1589 Returns a Java @code{String} made up of @var{len} bytes from @var{bytes}.
1593 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1594 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
1597 @deftypefun jstring JvNewStringUTF (const char* @var{bytes})
1598 Returns a @code{String} which is made up of the UTF encoded characters
1599 present in the C string @var{bytes}.
1602 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1603 Returns a pointer to an array of characters making up the @code{String} @var{str}.
1606 @deftypefun int JvGetStringUTFLength (jstring @var{str})
1607 Returns the number of bytes required to encode the contents of the
1608 @code{String} @var{str} in UTF-8.
1611 @deftypefun jsize JvGetStringUTFRegion (jstring @var{str}, jsize @var{start}, jsize @var{len}, char* @var{buf})
1612 Puts the UTF-8 encoding of a region of the @code{String} @var{str} into
1613 the buffer @code{buf}. The region to fetch is marked by @var{start} and @var{len}.
1615 Note that @var{buf} is a buffer, not a C string. It is @emph{not}
1620 @node Mixing with C++
1621 @section Interoperating with C/C++
1623 Because @acronym{CNI} is designed to represent Java classes and methods it
1624 cannot be mixed readily with C/C++ types.
1626 One important restriction is that Java classes cannot have non-Java
1627 type instance or static variables and cannot have methods which take
1628 non-Java types as arguments or return non-Java types.
1630 @noindent None of the following is possible with CNI:
1634 class ::MyClass : public java::lang::Object
1636 char* variable; // @r{char* is not a valid Java type.}
1641 ::SomeClass::someMethod (char *arg)
1646 @} // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1649 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1654 ::SomeClass::otherMethod (jstring str)
1663 But this restriction can cause a problem so @acronym{CNI} includes the
1664 @code{gnu.gcj.RawData} class. The @code{RawData} class is a
1665 @dfn{non-scanned reference} type. In other words variables declared
1666 of type @code{RawData} can contain any data and are not checked by the
1667 compiler in any way.
1669 This means that you can put C/C++ data structures (including classes)
1670 in your @acronym{CNI} classes, as long as you use the appropriate cast.
1672 @noindent Here are some examples:
1676 class ::MyClass : public java::lang::Object
1678 gnu.gcj.RawData string;
1681 gnu.gcj.RawData getText ();
1685 ::MyClass::MyClass ()
1692 ::MyClass::getText ()
1698 ::MyClass::printText ()
1700 printf("%s\n", (char*) string);
1705 @node Exception Handling
1706 @section Exception Handling
1708 While C++ and Java share a common exception handling framework,
1709 things are not yet perfectly integrated. The main issue is that the
1710 run-time type information facilities of the two
1711 languages are not integrated.
1713 Still, things work fairly well. You can throw a Java exception from
1714 C++ using the ordinary @code{throw} construct, and this
1715 exception can be caught by Java code. Similarly, you can catch an
1716 exception thrown from Java using the C++ @code{catch}
1719 @noindent Here is an example:
1723 throw new java::lang::IndexOutOfBoundsException();
1726 Normally, G++ will automatically detect when you are writing C++
1727 code that uses Java exceptions, and handle them appropriately.
1728 However, if C++ code only needs to execute destructors when Java
1729 exceptions are thrown through it, GCC will guess incorrectly. Sample
1733 struct S @{ ~S(); @};
1735 extern void bar(); // @r{Is implemented in Java and may throw exceptions.}
1744 The usual effect of an incorrect guess is a link failure, complaining of
1745 a missing routine called @code{__gxx_personality_v0}.
1747 You can inform the compiler that Java exceptions are to be used in a
1748 translation unit, irrespective of what it might think, by writing
1749 @code{#pragma GCC java_exceptions} at the head of the
1750 file. This @code{#pragma} must appear before any
1751 functions that throw or catch exceptions, or run destructors when
1752 exceptions are thrown through them.
1754 @node Synchronization
1755 @section Synchronization
1757 Each Java object has an implicit monitor.
1758 The Java VM uses the instruction @code{monitorenter} to acquire
1759 and lock a monitor, and @code{monitorexit} to release it.
1761 The corresponding CNI macros are @code{JvMonitorEnter} and
1762 @code{JvMonitorExit} (JNI has similar methods @code{MonitorEnter}
1763 and @code{MonitorExit}).
1766 The Java source language does not provide direct access to these primitives.
1767 Instead, there is a @code{synchronized} statement that does an
1768 implicit @code{monitorenter} before entry to the block,
1769 and does a @code{monitorexit} on exit from the block.
1770 Note that the lock has to be released even when the block is abnormally
1771 terminated by an exception, which means there is an implicit
1772 @code{try finally} surrounding synchronization locks.
1774 From C++, it makes sense to use a destructor to release a lock.
1775 @acronym{CNI} defines the following utility class:
1778 class JvSynchronize() @{
1780 JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
1781 ~JvSynchronize() @{ JvMonitorExit(obj); @}
1794 @noindent might become this C++ code:
1798 JvSynchronize dummy (OBJ);
1803 Java also has methods with the @code{synchronized} attribute.
1804 This is equivalent to wrapping the entire method body in a
1805 @code{synchronized} statement.
1806 (Alternatively, an implementation could require the caller to do
1807 the synchronization. This is not practical for a compiler, because
1808 each virtual method call would have to test at run-time if
1809 synchronization is needed.) Since in @command{gcj}
1810 the @code{synchronized} attribute is handled by the
1811 method implementation, it is up to the programmer
1812 of a synchronized native method to handle the synchronization
1813 (in the C++ implementation of the method).
1814 In otherwords, you need to manually add @code{JvSynchronize}
1815 in a @code{native synchornized} method.
1820 CNI permits C++ applications to make calls into Java classes, in addition to
1821 allowing Java code to call into C++. Several functions, known as the
1822 @dfn{invocation API}, are provided to support this.
1824 @deftypefun jint JvCreateJavaVM (void* @var{vm_args})
1825 Initializes the Java runtime. This function performs essential initialization
1826 of the threads interface, garbage collector, exception handling and other key
1827 aspects of the runtime. It must be called once by an application with
1828 a non-Java @code{main()} function, before any other Java or CNI calls are made.
1829 It is safe, but not recommended, to call @code{JvCreateJavaVM()} more than
1830 once provided it is only called from a single thread.
1831 The @var{vmargs} parameter can be used to specify initialization parameters
1832 for the Java runtime. It may be @code{NULL}.
1833 This function returns @code{0} upon success, or @code{-1} if the runtime is
1834 already initialized.
1836 @emph{Note:} In GCJ 3.1, the @code{vm_args} parameter is ignored. It may be
1837 used in a future release.
1840 @deftypefun java::lang::Thread* JvAttachCurrentThread (jstring @var{name}, java::lang::ThreadGroup* @var{group})
1841 Registers an existing thread with the Java runtime. This must be called once
1842 from each thread, before that thread makes any other Java or CNI calls. It
1843 must be called after @code{JvCreateJavaVM}.
1844 @var{name} specifies a name for the thread. It may be @code{NULL}, in which
1845 case a name will be generated.
1846 @var{group} is the ThreadGroup in which this thread will be a member. If it
1847 is @code{NULL}, the thread will be a member of the main thread group.
1848 The return value is the Java @code{Thread} object that represents the thread.
1849 It is safe to call @code{JvAttachCurrentThread()} more than once from the same
1850 thread. If the thread is already attached, the call is ignored and the current
1851 thread object is returned.
1854 @deftypefun jint JvDetachCurrentThread ()
1855 Unregisters a thread from the Java runtime. This should be called by threads
1856 that were attached using @code{JvAttachCurrentThread()}, after they have
1857 finished making calls to Java code. This ensures that any resources associated
1858 with the thread become eligible for garbage collection.
1859 This function returns @code{0} upon success, or @code{-1} if the current thread
1863 @subsection Handling uncaught exceptions
1865 If an exception is thrown from Java code called using the invocation API, and
1866 no handler for the exception can be found, the runtime will abort the
1867 application. In order to make the application more robust, it is recommended
1868 that code which uses the invocation API be wrapped by a top-level try/catch
1869 block that catches all Java exceptions.
1873 The following code demonstrates the use of the invocation API. In this
1874 example, the C++ application initializes the Java runtime and attaches
1875 itself. The @code{java.lang.System} class is initialized in order to
1876 access its @code{out} field, and a Java string is printed. Finally, the thread
1877 is detached from the runtime once it has finished making Java calls. Everything
1878 is wrapped with a try/catch block to provide a default handler for any uncaught
1881 The example can be compiled with @command{c++ test.cc -lgcj}.
1885 #include <gcj/cni.h>
1886 #include <java/lang/System.h>
1887 #include <java/io/PrintStream.h>
1888 #include <java/lang/Throwable.h>
1890 int main(int argc, char *argv)
1892 using namespace java::lang;
1896 JvCreateJavaVM(NULL);
1897 JvAttachCurrentThread(NULL, NULL);
1899 String *message = JvNewStringLatin1("Hello from C++");
1900 JvInitClass(&System.class$);
1901 System::out->println(message);
1903 JvDetachCurrentThread();
1905 catch (Throwable *t)
1907 System::err->println(JvNewStringLatin1("Unhandled Java exception:"));
1908 t->printStackTrace();
1916 Reflection is possible with CNI code, it functions similarly to how it
1917 functions with JNI@.
1919 @c clean this up... I mean, what are the types jfieldID and jmethodID in JNI?
1920 The types @code{jfieldID} and @code{jmethodID}
1923 @noindent The functions:
1926 @item @code{JvFromReflectedField},
1927 @item @code{JvFromReflectedMethod},
1928 @item @code{JvToReflectedField}
1929 @item @code{JvToFromReflectedMethod}
1932 @noindent will be added shortly, as will other functions corresponding to JNI@.
1939 While writing @command{gcj} and @code{libgcj} we have, of course, relied
1940 heavily on documentation from Sun Microsystems. In particular we have
1941 used The Java Language Specification (both first and second editions),
1942 the Java Class Libraries (volumes one and two), and the Java Virtual
1943 Machine Specification. In addition we've used the online documentation
1944 at @uref{http://java.sun.com/}.
1946 The current @command{gcj} home page is
1947 @uref{http://gcc.gnu.org/java/}.
1949 For more information on gcc, see @uref{http://gcc.gnu.org/}.
1951 Some @code{libgcj} testing is done using the Mauve test suite. This is
1952 a free software Java class library test suite which is being written
1953 because the JCK is not free. See
1954 @uref{http://sources.redhat.com/mauve/} for more information.