1 @\input texinfo @c -*-texinfo-*-
3 @settitle Guide to GNU gcj
5 @include gcc-common.texi
7 @c Note: When reading this manual you'll find lots of strange
8 @c circumlocutions like ``compiler for the Java language''.
9 @c This is necessary due to Sun's restrictions on the use of
12 @c When this manual is copyrighted.
13 @set copyrights-gcj 2001, 2002
16 @set which-gcj GCC-@value{version-GCC}
19 @c man begin COPYRIGHT
20 Copyright @copyright{} @value{copyrights-gcj} Free Software Foundation, Inc.
22 Permission is granted to copy, distribute and/or modify this document
23 under the terms of the GNU Free Documentation License, Version 1.1 or
24 any later version published by the Free Software Foundation; with the
25 Invariant Sections being ``GNU General Public License'', the Front-Cover
26 texts being (a) (see below), and with the Back-Cover Texts being (b)
27 (see below). A copy of the license is included in the
30 ``GNU Free Documentation License''.
32 @c man begin COPYRIGHT
37 @c man begin COPYRIGHT
39 (a) The FSF's Front-Cover Text is:
43 (b) The FSF's Back-Cover Text is:
45 You have freedom to copy and modify this GNU Manual, like GNU
46 software. Copies published by the Free Software Foundation raise
47 funds for GNU development.
53 @dircategory Programming
55 * Gcj: (gcj). Ahead-of-time compiler for the Java language
58 @dircategory Individual utilities
60 * gcjh: (gcj)Invoking gcjh.
61 Generate header files from Java class files
62 * jv-scan: (gcj)Invoking jv-scan.
63 Print information about Java source files
64 * jcf-dump: (gcj)Invoking jcf-dump.
65 Print information about Java class files
66 * gij: (gcj)Invoking gij. GNU interpreter for Java bytecode
67 * jv-convert: (gcj)Invoking jv-convert.
68 Convert file from one encoding to another
69 * rmic: (gcj)Invoking rmic.
70 Generate stubs for Remote Method Invocation.
71 * rmiregistry: (gcj)Invoking rmiregistry.
72 The remote object registry.
84 @vskip 0pt plus 1filll
85 For the @value{which-gcj} Version*
87 Published by the Free Software Foundation @*
88 59 Temple Place - Suite 330@*
89 Boston, MA 02111-1307, USA@*
100 This manual describes how to use @command{gcj}, the GNU compiler for the
101 Java programming language. @command{gcj} can generate both @file{.class}
102 files and object files, and it can read both Java source code and
106 * Copying:: The GNU General Public License
107 * GNU Free Documentation License::
108 How you can share and copy this manual
109 * Invoking gcj:: Compiler options supported by @command{gcj}
110 * Compatibility:: Compatibility between gcj and other tools for Java
111 * Invoking gcjh:: Generate header files from class files
112 * Invoking jv-scan:: Print information about source files
113 * Invoking jcf-dump:: Print information about class files
114 * Invoking gij:: Interpreting Java bytecodes
115 * Invoking jv-convert:: Converting from one encoding to another
116 * Invoking rmic:: Generate stubs for Remote Method Invocation.
117 * Invoking rmiregistry:: The remote object registry.
118 * About CNI:: Description of the Cygnus Native Interface
119 * System properties:: Modifying runtime behavior of the libgcj library
120 * Resources:: Where to look for more information
130 @chapter Invoking gcj
132 @c man title gcj Ahead-of-time compiler for the Java language
135 @c man begin SYNOPSIS gcj
136 gcj [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
137 [@option{--CLASSPATH}=@var{path}] [@option{--classpath}=@var{path}]
138 [@option{-f}@var{option}@dots{}] [@option{--encoding}=@var{name}]
139 [@option{--main}=@var{classname}] [@option{-D}@var{name}[=@var{value}]@dots{}]
140 [@option{-C}] [@option{--resource} @var{resource-name}] [@option{-d} @var{directory}]
141 [@option{-W}@var{warn}@dots{}]
142 @var{sourcefile}@dots{}
144 @c man begin SEEALSO gcj
145 gcc(1), gcjh(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
146 and the Info entries for @file{gcj} and @file{gcc}.
150 @c man begin DESCRIPTION gcj
152 As @command{gcj} is just another front end to @command{gcc}, it supports many
153 of the same options as gcc. @xref{Option Summary, , Option Summary,
154 gcc, Using the GNU Compiler Collection (GCC)}. This manual only documents the
155 options specific to @command{gcj}.
160 * Input and output files::
161 * Input Options:: How gcj finds files
162 * Encodings:: Options controlling source file encoding
163 * Warnings:: Options controlling warnings specific to gcj
164 * Code Generation:: Options controlling the output of gcj
165 * Configure-time Options:: Options you won't use
168 @c man begin OPTIONS gcj
170 @node Input and output files
171 @section Input and output files
173 A @command{gcj} command is like a @command{gcc} command, in that it
174 consists of a number of options and file names. The following kinds
175 of input file names are supported:
178 @item @var{file}.java
180 @item @var{file}.class
183 @itemx @var{file}.jar
184 An archive containing one or more @code{.class} files, all of
185 which are compiled. The archive may be compressed. Files in
186 an archive which don't end with @samp{.class} are treated as
187 resource files; they are copmiled into the resulting object file
188 as @samp{core:} URLs.
190 A file containing a whitespace-separated list of input file names.
191 (Currently, these must all be @code{.java} source files, but that
193 Each named file is compiled, just as if it had been on the command line.
194 @item @var{library}.a
195 @itemx @var{library}.so
196 @itemx -l@var{libname}
197 Libraries to use when linking. See the @command{gcc} manual.
200 You can specify more than one input file on the @command{gcj} command line,
201 in which case they will all be compiled. If you specify a
202 @code{-o @var{FILENAME}}
203 option, all the input files will be compiled together, producing a
204 single output file, named @var{FILENAME}.
205 This is allowed even when using @code{-S} or @code{-c},
206 but not when using @code{-C} or @code{--resource}.
207 (This is an extension beyond the what plain @command{gcc} allows.)
208 (If more than one input file is specified, all must currently
209 be @code{.java} files, though we hope to fix this.)
212 @section Input Options
216 @command{gcj} has options to control where it looks to find files it needs.
217 For instance, @command{gcj} might need to load a class that is referenced
218 by the file it has been asked to compile. Like other compilers for the
219 Java language, @command{gcj} has a notion of a @dfn{class path}. There are
220 several options and environment variables which can be used to
221 manipulate the class path. When @command{gcj} looks for a given class, it
222 searches the class path looking for matching @file{.class} or
223 @file{.java} file. @command{gcj} comes with a built-in class path which
224 points at the installed @file{libgcj.jar}, a file which contains all the
227 In the below, a directory or path component can refer either to an
228 actual directory on the filesystem, or to a @file{.zip} or @file{.jar}
229 file, which @command{gcj} will search as if it is a directory.
233 All directories specified by @code{-I} are kept in order and prepended
234 to the class path constructed from all the other options. Unless
235 compatibility with tools like @code{javac} is important, we recommend
236 always using @code{-I} instead of the other options for manipulating the
239 @item --classpath=@var{path}
240 This sets the class path to @var{path}, a colon-separated list of paths
241 (on Windows-based systems, a semicolon-separate list of paths).
242 This does not override the builtin (``boot'') search path.
244 @item --CLASSPATH=@var{path}
245 Deprecated synonym for @code{--classpath}.
247 @item --bootclasspath=@var{path}
248 Where to find the standard builtin classes, such as @code{java.lang.String}.
250 @item --extdirs=@var{path}
251 For each directory in the @var{path}, place the contents of that
252 directory at the end of the class path.
255 This is an environment variable which holds a list of paths.
258 The final class path is constructed like so:
262 First come all directories specified via @code{-I}.
265 If @option{--classpath} is specified, its value is appended.
266 Otherwise, if the @code{CLASSPATH} environment variable is specified,
267 then its value is appended.
268 Otherwise, the current directory (@code{"."}) is appended.
271 If @code{--bootclasspath} was specified, append its value.
272 Otherwise, append the built-in system directory, @file{libgcj.jar}.
275 Finally, if @code{--extdirs} was specified, append the contents of the
276 specified directories at the end of the class path. Otherwise, append
277 the contents of the built-in extdirs at @code{$(prefix)/share/java/ext}.
280 The classfile built by @command{gcj} for the class @code{java.lang.Object}
281 (and placed in @code{libgcj.jar}) contains a special zero length
282 attribute @code{gnu.gcj.gcj-compiled}. The compiler looks for this
283 attribute when loading @code{java.lang.Object} and will report an error
284 if it isn't found, unless it compiles to bytecode (the option
285 @code{-fforce-classes-archive-check} can be used to override this
286 behavior in this particular case.)
289 @item -fforce-classes-archive-check
290 This forces the compiler to always check for the special zero length
291 attribute @code{gnu.gcj.gcj-compiled} in @code{java.lang.Object} and
292 issue an error if it isn't found.
298 The Java programming language uses Unicode throughout. In an effort to
299 integrate well with other locales, @command{gcj} allows @file{.java} files
300 to be written using almost any encoding. @command{gcj} knows how to
301 convert these encodings into its internal encoding at compile time.
303 You can use the @code{--encoding=@var{NAME}} option to specify an
304 encoding (of a particular character set) to use for source files. If
305 this is not specified, the default encoding comes from your current
306 locale. If your host system has insufficient locale support, then
307 @command{gcj} assumes the default encoding to be the @samp{UTF-8} encoding
310 To implement @code{--encoding}, @command{gcj} simply uses the host
311 platform's @code{iconv} conversion routine. This means that in practice
312 @command{gcj} is limited by the capabilities of the host platform.
314 The names allowed for the argument @code{--encoding} vary from platform
315 to platform (since they are not standardized anywhere). However,
316 @command{gcj} implements the encoding named @samp{UTF-8} internally, so if
317 you choose to use this for your source files you can be assured that it
318 will work on every host.
324 @command{gcj} implements several warnings. As with other generic
325 @command{gcc} warnings, if an option of the form @code{-Wfoo} enables a
326 warning, then @code{-Wno-foo} will disable it. Here we've chosen to
327 document the form of the warning which will have an effect -- the
328 default being the opposite of what is listed.
331 @item -Wredundant-modifiers
332 With this flag, @command{gcj} will warn about redundant modifiers. For
333 instance, it will warn if an interface method is declared @code{public}.
335 @item -Wextraneous-semicolon
336 This causes @command{gcj} to warn about empty statements. Empty statements
337 have been deprecated.
339 @item -Wno-out-of-date
340 This option will cause @command{gcj} not to warn when a source file is
341 newer than its matching class file. By default @command{gcj} will warn
345 This is the same as @command{gcc}'s @code{-Wunused}.
348 This is the same as @code{-Wredundant-modifiers -Wextraneous-semicolon
353 @node Code Generation
354 @section Code Generation
356 In addition to the many @command{gcc} options controlling code generation,
357 @command{gcj} has several options specific to itself.
360 @item --main=@var{CLASSNAME}
361 This option is used when linking to specify the name of the class whose
362 @code{main} method should be invoked when the resulting executable is
363 run. @footnote{The linker by default looks for a global function named
364 @code{main}. Since Java does not have global functions, and a
365 collection of Java classes may have more than one class with a
366 @code{main} method, you need to let the linker know which of those
367 @code{main} methods it should invoke when starting the application.}
369 @item -D@var{name}[=@var{value}]
370 This option can only be used with @code{--main}. It defines a system
371 property named @var{name} with value @var{value}. If @var{value} is not
372 specified then it defaults to the empty string. These system properties
373 are initialized at the program's startup and can be retrieved at runtime
374 using the @code{java.lang.System.getProperty} method.
377 This option is used to tell @command{gcj} to generate bytecode
378 (@file{.class} files) rather than object code.
380 @item --resource @var{resource-name}
381 This option is used to tell @command{gcj} to compile the contents of a
382 given file to object code so it may be accessed at runtime with the core
383 protocol handler as @samp{core:/@var{resource-name}}. Note that
384 @var{resource-name} is the name of the resource as found at runtime; for
385 instance, it could be used in a call to @code{ResourceBundle.getBundle}.
386 The actual file name to be compiled this way must be specified
389 @item -d @var{directory}
390 When used with @code{-C}, this causes all generated @file{.class} files
391 to be put in the appropriate subdirectory of @var{directory}. By
392 default they will be put in subdirectories of the current working
395 @item -fno-bounds-check
396 By default, @command{gcj} generates code which checks the bounds of all
397 array indexing operations. With this option, these checks are omitted, which
398 can improve performance for code that uses arrays extensively. Note that this
399 can result in unpredictable behavior if the code in question actually does
400 violate array bounds constraints. It is safe to use this option if you are
401 sure that your code will never throw an @code{ArrayIndexOutOfBoundsException}.
403 @item -fno-store-check
404 Don't generate array store checks. When storing objects into arrays, a runtime
405 check is normally generated in order to ensure that the object is assignment
406 compatible with the component type of the array (which may not be known
407 at compile-time). With this option, these checks are omitted. This can
408 improve performance for code which stores objects into arrays frequently.
409 It is safe to use this option if you are sure your code will never throw an
410 @code{ArrayStoreException}.
413 With @command{gcj} there are two options for writing native methods: CNI
414 and JNI@. By default @command{gcj} assumes you are using CNI@. If you are
415 compiling a class with native methods, and these methods are implemented
416 using JNI, then you must use @code{-fjni}. This option causes
417 @command{gcj} to generate stubs which will invoke the underlying JNI
421 Don't recognize the @code{assert} keyword. This is for compatibility
422 with older versions of the language specification.
424 @item -fno-optimize-static-class-initialization
425 When the optimization level is greater or equal to @code{-O2},
426 @command{gcj} will try to optimize the way calls into the runtime are made
427 to initialize static classes upon their first use (this optimization
428 isn't carried out if @code{-C} was specified.) When compiling to native
429 code, @code{-fno-optimize-static-class-initialization} will turn this
430 optimization off, regardless of the optimization level in use.
434 @node Configure-time Options
435 @section Configure-time Options
437 Some @command{gcj} code generations options affect the resulting ABI, and
438 so can only be meaningfully given when @code{libgcj}, the runtime
439 package, is configured. @code{libgcj} puts the appropriate options from
440 this group into a @samp{spec} file which is read by @command{gcj}. These
441 options are listed here for completeness; if you are using @code{libgcj}
442 then you won't want to touch these options.
446 This enables the use of the Boehm GC bitmap marking code. In particular
447 this causes @command{gcj} to put an object marking descriptor into each
450 @item -fhash-synchronization
451 By default, synchronization data (the data used for @code{synchronize},
452 @code{wait}, and @code{notify}) is pointed to by a word in each object.
453 With this option @command{gcj} assumes that this information is stored in a
454 hash table and not in the object itself.
456 @item -fuse-divide-subroutine
457 On some systems, a library routine is called to perform integer
458 division. This is required to get exception handling correct when
461 @item -fcheck-references
462 On some systems it's necessary to insert inline checks whenever
463 accessing an object via a reference. On other systems you won't need
464 this because null pointer accesses are caught automatically by the
471 @chapter Compatibility with the Java Platform
473 As we believe it is important that the Java platform not be fragmented,
474 @command{gcj} and @code{libgcj} try to conform to the relevant Java
475 specifications. However, limited manpower and incomplete and unclear
476 documentation work against us. So, there are caveats to using
485 @section Standard features not yet supported
487 This list of compatibility issues is by no means complete.
491 @command{gcj} implements the JDK 1.2 language. It supports inner classes
492 and the new 1.4 @code{assert} keyword. It does not yet support the Java 2
493 @code{strictfp} keyword (it recognizes the keyword but ignores it).
496 @code{libgcj} is largely compatible with the JDK 1.2 libraries.
497 However, @code{libgcj} is missing many packages, most notably
498 @code{java.awt}. There are also individual missing classes and methods.
499 We currently do not have a list showing differences between
500 @code{libgcj} and the Java 2 platform.
503 Sometimes the @code{libgcj} implementation of a method or class differs
504 from the JDK implementation. This is not always a bug. Still, if it
505 affects you, it probably makes sense to report it so that we can discuss
506 the appropriate response.
509 @command{gcj} does not currently allow for piecemeal replacement of
510 components within @code{libgcj}. Unfortunately, programmers often want
511 to use newer versions of certain packages, such as those provided by
512 the Apache Software Foundation's Jakarta project. This has forced us
513 to place the @code{org.w3c.dom} and @code{org.xml.sax} packages into
514 their own libraries, separate from @code{libgcj}. If you intend to
515 use these classes, you must link them explicitly with
516 @code{-l-org-w3c-dom} and @code{-l-org-xml-sax}. Future versions of
517 @command{gcj} may not have this restriction.
521 @section Extra features unique to gcj
523 The main feature of @command{gcj} is that it can compile programs written in
524 the Java programming language to native code. Most extensions that have been
525 added are to facilitate this functionality.
529 @command{gcj} makes it easy and efficient to mix code written in Java and C++.
530 @xref{About CNI}, for more info on how to use this in your programs.
533 When you compile your classes into a shared library they can be automatically
534 loaded by the @code{libgcj} system classloader. When trying to load a class
535 @code{gnu.pkg.SomeClass} the system classloader will first try to load the
536 shared library @file{lib-gnu-pkg-SomeClass.so}, if that fails to load the
537 class then it will try to load @file{lib-gnu-pkg.so} and finally when the
538 class is still not loaded it will try to load @file{lib-gnu.so}. Note that
539 all @samp{.}s will be transformed into @samp{-}s and that searching
540 for inner classes starts with their outermost outer class. If the class
541 cannot be found this way the system classloader tries to use
542 the @code{libgcj} bytecode interpreter to load the class from the standard
547 @chapter Invoking gcjh
549 @c man title gcjh generate header files from Java class files
551 @c man begin DESCRIPTION gcjh
553 The @code{gcjh} program is used to generate header files from class
554 files. It can generate both CNI and JNI header files, as well as stub
555 implementation files which can be used as a basis for implementing the
556 required native methods.
561 @c man begin SYNOPSIS gcjh
562 gcjh [@option{-stubs}] [@option{-jni}]
563 [@option{-add} @var{text}] [@option{-append} @var{text}] [@option{-friend} @var{text}]
564 [@option{-preprend} @var{text}]
565 [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
566 [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
567 [@option{-o} @var{file}] [@option{-td} @var{dir}]
568 [@option{-M}] [@option{-MM}] [@option{-MD}] [@option{-MMD}]
569 [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
570 @var{classname}@dots{}
572 @c man begin SEEALSO gcjh
573 gcc(1), gcj(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
574 and the Info entries for @file{gcj} and @file{gcc}.
578 @c man begin OPTIONS gcjh
582 This causes @code{gcjh} to generate stub files instead of header files.
583 By default the stub file will be named after the class, with a suffix of
584 @samp{.cc}. In JNI mode, the default output file will have the suffix
588 This tells @code{gcjh} to generate a JNI header or stub. By default,
589 CNI headers are generated.
591 @item -add @var{text}
592 Inserts @var{text} into the class body. This is ignored in JNI mode.
594 @item -append @var{text}
595 Inserts @var{text} into the header file after the class declaration.
596 This is ignored in JNI mode.
598 @item -friend @var{text}
599 Inserts @var{text} into the class as a @code{friend} declaration.
600 This is ignored in JNI mode.
602 @item -prepend @var{text}
603 Inserts @var{text} into the header file before the class declaration.
604 This is ignored in JNI mode.
606 @item --classpath=@var{path}
607 @itemx --CLASSPATH=@var{path}
608 @itemx -I@var{directory}
609 @itemx -d @var{directory}
611 These options are all identical to the corresponding @command{gcj} options.
614 Sets the output file name. This cannot be used if there is more than
615 one class on the command line.
617 @item -td @var{directory}
618 Sets the name of the directory to use for temporary files.
621 Print all dependencies to stdout; suppress ordinary output.
624 Print non-system dependencies to stdout; suppress ordinary output.
627 Print all dependencies to stdout.
630 Print non-system dependencies to stdout.
633 Print help about @code{gcjh} and exit. No further processing is done.
636 Print version information for @code{gcjh} and exit. No further
640 Print extra information while running.
643 All remaining options are considered to be names of classes.
647 @node Invoking jv-scan
648 @chapter Invoking jv-scan
650 @c man title jv-scan print information about Java source file
652 @c man begin DESCRIPTION jv-scan
654 The @code{jv-scan} program can be used to print information about a Java
655 source file (@file{.java} file).
660 @c man begin SYNOPSIS jv-scan
661 jv-scan [@option{--no-assert}] [@option{--complexity}]
662 [@option{--encoding}=@var{name}] [@option{--print-main}]
663 [@option{--list-class}] [@option{--list-filename}]
664 [@option{--version}] [@option{--help}]
665 [@option{-o} @var{file}] @var{inputfile}@dots{}
667 @c man begin SEEALSO jv-scan
668 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
669 and the Info entries for @file{gcj} and @file{gcc}.
673 @c man begin OPTIONS jv-scan
677 Don't recognize the @code{assert} keyword, for backwards compatibility
678 with older versions of the language specification.
681 This prints a complexity measure, related to cyclomatic complexity, for
684 @item --encoding=@var{name}
685 This works like the corresponding @command{gcj} option.
688 This prints the name of the class in this file containing a @code{main}
692 This lists the names of all classes defined in the input files.
694 @item --list-filename
695 If @code{--list-class} is given, this option causes @code{jv-scan} to
696 also print the name of the file in which each class was found.
699 Print output to the named file.
702 Print help, then exit.
705 Print version number, then exit.
710 @node Invoking jcf-dump
711 @chapter Invoking jcf-dump
713 @c man title jcf-dump print information about Java class files
716 @c man begin SYNOPSIS jcf-dump
717 jcf-dump [@option{-c}] [@option{--javap}]
718 [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
719 [@option{-I}@var{dir}@dots{}] [@option{-o} @var{file}]
720 [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
721 @var{classname}@dots{}
723 @c man begin SEEALSO jcf-dump
724 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
725 and the Info entries for @file{gcj} and @file{gcc}.
729 @c man begin DESCRIPTION jcf-dump
731 This is a class file examiner, similar to @code{javap}. It will print
732 information about a number of classes, which are specified by class name
737 @c man begin OPTIONS jcf-dump
741 Disassemble method bodies. By default method bodies are not printed.
744 Generate output in @code{javap} format. The implementation of this
745 feature is very incomplete.
747 @item --classpath=@var{path}
748 @itemx --CLASSPATH=@var{path}
749 @itemx -I@var{directory}
751 These options as the same as the corresponding @command{gcj} options.
754 Print help, then exit.
757 Print version number, then exit.
760 Print extra information while running.
766 @chapter Invoking gij
768 @c man title gij GNU interpreter for Java bytecode
771 @c man begin SYNOPSIS gij
772 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
774 gij [@option{-jar}] [@option{OPTION}] @dots{} @var{CLASS} [@var{ARGS}@dots{}]
775 [@option{-cp} @var{path}] [@option{-classpath} @var{path}]
776 [@option{-D}@var{name}[=@var{value}]@dots{}]
777 [@option{-ms=}@var{number}] [@option{-mx=}@var{number}]
778 [@option{--showversion}] [@option{--version}] [@option{--help}]
780 @c man begin SEEALSO gij
781 gcc(1), gcj(1), gcjh(1), jv-scan(1), jcf-dump(1), gfdl(7),
782 and the Info entries for @file{gcj} and @file{gcc}.
786 @c man begin DESCRIPTION gij
788 @code{gij} is a Java bytecode interpreter included with @code{libgcj}.
789 @code{gij} is not available on every platform; porting it requires a
790 small amount of assembly programming which has not been done for all the
791 targets supported by @command{gcj}.
793 The primary argument to @code{gij} is the name of a class or, with
794 @code{-jar}, a jar file. Options before this argument are interpreted
795 by @code{gij}; remaining options are passed to the interpreted program.
797 If a class name is specified and this class does not have a @code{main}
798 method with the appropriate signature (a @code{static void} method with
799 a @code{String[]} as its sole argument), then @code{gij} will print an
802 If a jar file is specified then @code{gij} will use information in it to
803 determine which class' @code{main} method will be invoked.
805 @code{gij} will invoke the @code{main} method with all the remaining
806 command-line options.
808 Note that @code{gij} is not limited to interpreting code. Because
809 @code{libgcj} includes a class loader which can dynamically load shared
810 objects, it is possible to give @code{gij} the name of a class which has
811 been compiled and put into a shared library on the class path.
815 @c man begin OPTIONS gij
819 @itemx -classpath @var{path}
820 Set the initial class path. The class path is used for finding
821 class and resource files. If specified, this option overrides the
822 @code{CLASSPATH} environment variable. Note that this option is
823 ignored if @code{-jar} is used.
825 @item -D@var{name}[=@var{value}]
826 This defines a system property named @var{name} with value @var{value}.
827 If @var{value} is not specified then it defaults to the empty string.
828 These system properties are initialized at the program's startup and can
829 be retrieved at runtime using the @code{java.lang.System.getProperty}
832 @item -ms=@var{number}
833 This sets the initial heap size.
835 @item -mx=@var{number}
836 This sets the maximum heap size.
839 This indicates that the name passed to @code{gij} should be interpreted
840 as the name of a jar file, not a class.
843 Print help, then exit.
846 Print version number and continue.
849 Print version number, then exit.
854 @node Invoking jv-convert
855 @chapter Invoking jv-convert
857 @c man title jv-convert Convert file from one encoding to another
859 @c man begin SYNOPSIS jv-convert
860 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
863 [@option{--encoding} @var{name}]
864 [@option{--from} @var{name}]
865 [@option{--to} @var{name}]
866 [@option{-i} @var{file}] [@option{-o} @var{file}]
867 [@option{--reverse}] [@option{--help}] [@option{--version}]
871 @c man begin DESCRIPTION jv-convert
873 @command{jv-convert} is a utility included with @code{libgcj} which
874 converts a file from one encoding to another. It is similar to the Unix
875 @command{iconv} utility.
877 The encodings supported by @command{jv-convert} are platform-dependent.
878 Currently there is no way to get a list of all supported encodings.
882 @c man begin OPTIONS jv-convert
885 @item --encoding @var{name}
886 @itemx --from @var{name}
887 Use @var{name} as the input encoding. The default is the current
890 @item --to @var{name}
891 Use @var{name} as the output encoding. The default is the
892 @code{JavaSrc} encoding; this is ASCII with @samp{\u} escapes for
893 non-ASCII characters.
896 Read from @var{file}. The default is to read from standard input.
899 Write to @var{file}. The default is to write to standard output.
902 Swap the input and output encodings.
905 Print a help message, then exit.
908 Print version information, then exit.
914 @chapter Invoking rmic
916 @c man title rmic Generate stubs for Remote Method Invocation
918 @c man begin SYNOPSIS rmic
919 @command{rmic} [@option{OPTION}] @dots{} @var{class} @dots{}
922 [@option{-keepgenerated}]
926 [@option{-nocompile}]
928 [@option{-d} @var{directory}]
934 @c man begin DESCRIPTION rmic
936 @command{rmic} is a utility included with @code{libgcj} which generates
937 stubs for remote objects.
939 @c FIXME: Add real information here.
940 @c This really isn't much more than the --help output.
942 Note that this program isn't yet fully compatible with the JDK
943 @command{rmic}. Some options, such as @option{-classpath}, are
944 recognized but currently ignored. We have left these options
945 undocumented for now.
947 Long options can also be given with a GNU-style leading @samp{--}. For
948 instance, @option{--help} is accepted.
952 @c man begin OPTIONS rmic
956 @itemx -keepgenerated
957 By default, @command{rmic} deletes intermediate files. Either of these
958 options causes it not to delete such files.
961 Cause @command{rmic} to create stubs and skeletons for the 1.1
965 Cause @command{rmic} to create stubs and skeletons compatible with both
966 the 1.1 and 1.2 protocol versions. This is the default.
969 Cause @command{rmic} to create stubs and skeletons for the 1.2
973 Don't compile the generated files.
976 Print information about what @command{rmic} is doing.
978 @item -d @var{directory}
979 Put output files in @var{directory}. By default the files are put in
980 the current working directory.
983 Print a help message, then exit.
986 Print version information, then exit.
992 @node Invoking rmiregistry
993 @chapter Invoking rmiregistry
995 @c man title rmiregistry Remote object registry
997 @c man begin SYNOPSIS rmiregistry
998 @command{rmic} [@option{OPTION}] @dots{} [@var{port}]
1001 [@option{--version}]
1005 @c man begin DESCRIPTION rmiregistry
1007 @command{rmiregistry} starts a remote object registry on the current
1008 host. If no port number is specified, then port 1099 is used.
1010 @c FIXME: Add real information here.
1011 @c This really isn't much more than the --help output.
1015 @c man begin OPTIONS rmiregistry
1019 Print a help message, then exit.
1022 Print version information, then exit.
1031 This documents CNI, the Cygnus Native Interface,
1032 which is is a convenient way to write Java native methods using C++.
1033 This is a more efficient, more convenient, but less portable
1034 alternative to the standard JNI (Java Native Interface).
1037 * Basic concepts:: Introduction to using CNI@.
1038 * Packages:: How packages are mapped to C++.
1039 * Primitive types:: Handling Java types in C++.
1040 * Interfaces:: How Java interfaces map to C++.
1041 * Objects and Classes:: C++ and Java classes.
1042 * Class Initialization:: How objects are initialized.
1043 * Object allocation:: How to create Java objects in C++.
1044 * Arrays:: Dealing with Java arrays in C++.
1045 * Methods:: Java methods in C++.
1046 * Strings:: Information about Java Strings.
1047 * Mixing with C++:: How CNI can interoperate with C++.
1048 * Exception Handling:: How exceptions are handled.
1049 * Synchronization:: Synchronizing between Java and C++.
1050 * Invocation:: Starting the Java runtime from C++.
1051 * Reflection:: Using reflection from C++.
1055 @node Basic concepts
1056 @section Basic concepts
1058 In terms of languages features, Java is mostly a subset
1059 of C++. Java has a few important extensions, plus a powerful standard
1060 class library, but on the whole that does not change the basic similarity.
1061 Java is a hybrid object-oriented language, with a few native types,
1062 in addition to class types. It is class-based, where a class may have
1063 static as well as per-object fields, and static as well as instance methods.
1064 Non-static methods may be virtual, and may be overloaded. Overloading is
1065 resolved at compile time by matching the actual argument types against
1066 the parameter types. Virtual methods are implemented using indirect calls
1067 through a dispatch table (virtual function table). Objects are
1068 allocated on the heap, and initialized using a constructor method.
1069 Classes are organized in a package hierarchy.
1071 All of the listed attributes are also true of C++, though C++ has
1072 extra features (for example in C++ objects may be allocated not just
1073 on the heap, but also statically or in a local stack frame). Because
1074 @command{gcj} uses the same compiler technology as G++ (the GNU
1075 C++ compiler), it is possible to make the intersection of the two
1076 languages use the same ABI (object representation and calling
1077 conventions). The key idea in CNI is that Java objects are C++
1078 objects, and all Java classes are C++ classes (but not the other way
1079 around). So the most important task in integrating Java and C++ is to
1080 remove gratuitous incompatibilities.
1082 You write CNI code as a regular C++ source file. (You do have to use
1083 a Java/CNI-aware C++ compiler, specifically a recent version of G++.)
1085 @noindent A CNI C++ source file must have:
1088 #include <gcj/cni.h>
1091 @noindent and then must include one header file for each Java class it uses, e.g.:
1094 #include <java/lang/Character.h>
1095 #include <java/util/Date.h>
1096 #include <java/lang/IndexOutOfBoundsException.h>
1099 @noindent These header files are automatically generated by @code{gcjh}.
1102 CNI provides some functions and macros to make using Java objects and
1103 primitive types from C++ easier. In general, these CNI functions and
1104 macros start with the @code{Jv} prefix, for example the function
1105 @code{JvNewObjectArray}. This convention is used to avoid conflicts
1106 with other libraries. Internal functions in CNI start with the prefix
1107 @code{_Jv_}. You should not call these; if you find a need to, let us
1108 know and we will try to come up with an alternate solution. (This
1109 manual lists @code{_Jv_AllocBytes} as an example; CNI should instead
1110 provide a @code{JvAllocBytes} function.)
1113 @subsection Limitations
1115 Whilst a Java class is just a C++ class that doesn't mean that you are
1116 freed from the shackles of Java, a @acronym{CNI} C++ class must adhere to the
1117 rules of the Java programming language.
1119 For example: it is not possible to declare a method in a CNI class
1120 that will take a C string (@code{char*}) as an argument, or to declare a
1121 member variable of some non-Java datatype.
1127 The only global names in Java are class names, and packages. A
1128 @dfn{package} can contain zero or more classes, and also zero or more
1129 sub-packages. Every class belongs to either an unnamed package or a
1130 package that has a hierarchical and globally unique name.
1132 A Java package is mapped to a C++ @dfn{namespace}. The Java class
1133 @code{java.lang.String} is in the package @code{java.lang}, which is a
1134 sub-package of @code{java}. The C++ equivalent is the class
1135 @code{java::lang::String}, which is in the namespace @code{java::lang}
1136 which is in the namespace @code{java}.
1138 @noindent Here is how you could express this:
1141 (// @r{Declare the class(es), possibly in a header file:}
1150 class java::lang::String : public java::lang::Object
1156 @noindent The @code{gcjh} tool automatically generates the necessary namespace
1160 @subsection Leaving out package names
1162 Always using the fully-qualified name of a java class can be
1163 tiresomely verbose. Using the full qualified name also ties the code
1164 to a single package making code changes necessary should the class
1165 move from one package to another. The Java @code{package} declaration
1166 specifies that the following class declarations are in the named
1167 package, without having to explicitly name the full package
1168 qualifiers. The @code{package} declaration can be
1169 followed by zero or more @code{import} declarations, which
1170 allows either a single class or all the classes in a package to be
1171 named by a simple identifier. C++ provides something similar with the
1172 @code{using} declaration and directive.
1177 import @var{package-name}.@var{class-name};
1180 @noindent allows the program text to refer to @var{class-name} as a shorthand for
1181 the fully qualified name: @code{@var{package-name}.@var{class-name}}.
1184 @noindent To achieve the same effect C++, you have to do this:
1187 using @var{package-name}::@var{class-name};
1191 @noindent Java can also cause imports on demand, like this:
1194 import @var{package-name}.*;
1197 @noindent Doing this allows any class from the package @var{package-name} to be
1198 referred to only by its class-name within the program text.
1201 @noindent The same effect can be achieved in C++ like this:
1204 using namespace @var{package-name};
1208 @node Primitive types
1209 @section Primitive types
1211 Java provides 8 @dfn{primitives} types which represent integers, floats,
1212 characters and booleans (and also the void type). C++ has its own
1213 very similar concrete types. Such types in C++ however are not always
1214 implemented in the same way (an int might be 16, 32 or 64 bits for example)
1215 so CNI provides a special C++ type for each primitive Java type:
1217 @multitable @columnfractions .20 .25 .60
1218 @item @strong{Java type} @tab @strong{C/C++ typename} @tab @strong{Description}
1219 @item @code{char} @tab @code{jchar} @tab 16 bit Unicode character
1220 @item @code{boolean} @tab @code{jboolean} @tab logical (true or false) values
1221 @item @code{byte} @tab @code{jbyte} @tab 8-bit signed integer
1222 @item @code{short} @tab @code{jshort} @tab 16 bit signed integer
1223 @item @code{int} @tab @code{jint} @tab 32 bit signed integer
1224 @item @code{long} @tab @code{jlong} @tab 64 bit signed integer
1225 @item @code{float} @tab @code{jfloat} @tab 32 bit IEEE floating point number
1226 @item @code{double} @tab @code{jdouble} @tab 64 bit IEEE floating point number
1227 @item @code{void} @tab @code{void} @tab no value
1230 When referring to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1231 to avoid disappointment.
1234 @subsection Reference types associated with primitive types
1236 In Java each primitive type has an associated reference type,
1237 e.g.: @code{boolean} has an associated @code{java.lang.Boolean} class.
1238 In order to make working with such classes easier GCJ provides the macro
1241 @deffn macro JvPrimClass type
1242 Return a pointer to the @code{Class} object corresponding to the type supplied.
1245 JvPrimClass(void) @result{} java.lang.Void.TYPE
1254 A Java class can @dfn{implement} zero or more
1255 @dfn{interfaces}, in addition to inheriting from
1256 a single base class.
1258 @acronym{CNI} allows CNI code to implement methods of interfaces.
1259 You can also call methods through interface references, with some
1262 @acronym{CNI} doesn't understand interface inheritance at all yet. So,
1263 you can only call an interface method when the declared type of the
1264 field being called matches the interface which declares that
1265 method. The workaround is to cast the interface reference to the right
1268 For example if you have:
1276 interface B extends A
1282 and declare a variable of type @code{B} in C++, you can't call
1283 @code{a()} unless you cast it to an @code{A} first.
1285 @node Objects and Classes
1286 @section Objects and Classes
1290 All Java classes are derived from @code{java.lang.Object}. C++ does
1291 not have a unique root class, but we use the C++ class
1292 @code{java::lang::Object} as the C++ version of the
1293 @code{java.lang.Object} Java class. All other Java classes are mapped
1294 into corresponding C++ classes derived from @code{java::lang::Object}.
1296 Interface inheritance (the @code{implements} keyword) is currently not
1297 reflected in the C++ mapping.
1300 @subsection Object fields
1302 Each object contains an object header, followed by the instance fields
1303 of the class, in order. The object header consists of a single
1304 pointer to a dispatch or virtual function table. (There may be extra
1305 fields @emph{in front of} the object, for example for memory
1306 management, but this is invisible to the application, and the
1307 reference to the object points to the dispatch table pointer.)
1309 The fields are laid out in the same order, alignment, and size as in
1310 C++. Specifically, 8-bite and 16-bit native types (@code{byte},
1311 @code{short}, @code{char}, and @code{boolean}) are @emph{not} widened
1312 to 32 bits. Note that the Java VM does extend 8-bit and 16-bit types
1313 to 32 bits when on the VM stack or temporary registers.
1315 If you include the @code{gcjh}-generated header for a
1316 class, you can access fields of Java classes in the @emph{natural}
1317 way. For example, given the following Java class:
1323 public Integer (int i) @{ this.i = i; @}
1324 public static zero = new Integer(0);
1331 #include <gcj/cni.h>;
1335 mult (Int *p, jint k)
1338 return Int::zero; // @r{Static member access.}
1339 return new Int(p->i * k);
1344 @subsection Access specifiers
1346 CNI does not strictly enforce the Java access
1347 specifiers, because Java permissions cannot be directly mapped
1348 into C++ permission. Private Java fields and methods are mapped
1349 to private C++ fields and methods, but other fields and methods
1350 are mapped to public fields and methods.
1354 @node Class Initialization
1355 @section Class Initialization
1357 Java requires that each class be automatically initialized at the time
1358 of the first active use. Initializing a class involves
1359 initializing the static fields, running code in class initializer
1360 methods, and initializing base classes. There may also be
1361 some implementation specific actions, such as allocating
1362 @code{String} objects corresponding to string literals in
1365 The GCJ compiler inserts calls to @code{JvInitClass} at appropriate
1366 places to ensure that a class is initialized when required. The C++
1367 compiler does not insert these calls automatically---it is the
1368 programmer's responsibility to make sure classes are initialized.
1369 However, this is fairly painless because of the conventions assumed by
1372 First, @code{libgcj} will make sure a class is initialized before an
1373 instance of that object is created. This is one of the
1374 responsibilities of the @code{new} operation. This is taken care of
1375 both in Java code, and in C++ code. When G++ sees a @code{new} of a
1376 Java class, it will call a routine in @code{libgcj} to allocate the
1377 object, and that routine will take care of initializing the class.
1378 Note however that this does not happen for Java arrays; you must
1379 allocate those using the appropriate CNI function. It follows that
1380 you can access an instance field, or call an instance (non-static)
1381 method and be safe in the knowledge that the class and all of its base
1382 classes have been initialized.
1384 Invoking a static method is also safe. This is because the
1385 Java compiler adds code to the start of a static method to make sure
1386 the class is initialized. However, the C++ compiler does not
1387 add this extra code. Hence, if you write a native static method
1388 using CNI, you are responsible for calling @code{JvInitClass}
1389 before doing anything else in the method (unless you are sure
1390 it is safe to leave it out).
1392 Accessing a static field also requires the class of the
1393 field to be initialized. The Java compiler will generate code
1394 to call @code{Jv_InitClass} before getting or setting the field.
1395 However, the C++ compiler will not generate this extra code,
1396 so it is your responsibility to make sure the class is
1397 initialized before you access a static field from C++.
1400 @node Object allocation
1401 @section Object allocation
1403 New Java objects are allocated using a
1404 @dfn{class instance creation expression}, e.g.:
1407 new @var{Type} ( ... )
1410 The same syntax is used in C++. The main difference is that
1411 C++ objects have to be explicitly deleted; in Java they are
1412 automatically deleted by the garbage collector.
1413 Using @acronym{CNI}, you can allocate a new Java object
1414 using standard C++ syntax and the C++ compiler will allocate
1415 memory from the garbage collector. If you have overloaded
1416 constructors, the compiler will choose the correct one
1417 using standard C++ overload resolution rules.
1419 @noindent For example:
1422 java::util::Hashtable *ht = new java::util::Hashtable(120);
1425 @deftypefun void* _Jv_AllocBytes (jsize @var{size})
1426 Allocates @var{size} bytes from the heap. The memory is not scanned
1427 by the garbage collector but it freed if no references to it are discovered.
1434 While in many ways Java is similar to C and C++, it is quite different
1435 in its treatment of arrays. C arrays are based on the idea of pointer
1436 arithmetic, which would be incompatible with Java's security
1437 requirements. Java arrays are true objects (array types inherit from
1438 @code{java.lang.Object}). An array-valued variable is one that
1439 contains a reference (pointer) to an array object.
1441 Referencing a Java array in C++ code is done using the
1442 @code{JArray} template, which as defined as follows:
1445 class __JArray : public java::lang::Object
1452 class JArray : public __JArray
1456 T& operator[](jint i) @{ return data[i]; @}
1461 There are a number of @code{typedef}s which correspond to @code{typedef}s
1462 from the @acronym{JNI}. Each is the type of an array holding objects
1463 of the relevant type:
1466 typedef __JArray *jarray;
1467 typedef JArray<jobject> *jobjectArray;
1468 typedef JArray<jboolean> *jbooleanArray;
1469 typedef JArray<jbyte> *jbyteArray;
1470 typedef JArray<jchar> *jcharArray;
1471 typedef JArray<jshort> *jshortArray;
1472 typedef JArray<jint> *jintArray;
1473 typedef JArray<jlong> *jlongArray;
1474 typedef JArray<jfloat> *jfloatArray;
1475 typedef JArray<jdouble> *jdoubleArray;
1479 @deftypemethod {template<class T>} T* elements (JArray<T> @var{array})
1480 This template function can be used to get a pointer to the elements of
1481 the @code{array}. For instance, you can fetch a pointer to the
1482 integers that make up an @code{int[]} like so:
1485 extern jintArray foo;
1486 jint *intp = elements (foo);
1489 The name of this function may change in the future.
1493 @deftypefun jobjectArray JvNewObjectArray (jsize @var{length}, jclass @var{klass}, jobject @var{init})
1494 Here @code{klass} is the type of elements of the array and
1495 @code{init} is the initial value put into every slot in the array.
1499 @subsection Creating arrays
1501 For each primitive type there is a function which can be used to
1502 create a new array of that type. The name of the function is of the
1506 JvNew@var{Type}Array
1509 @noindent For example:
1515 @noindent can be used to create an array of Java primitive boolean types.
1517 @noindent The following function definition is the template for all such functions:
1519 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1520 Create's an array @var{length} indices long.
1523 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1524 Returns the length of the @var{array}.
1531 Java methods are mapped directly into C++ methods.
1532 The header files generated by @code{gcjh}
1533 include the appropriate method definitions.
1534 Basically, the generated methods have the same names and
1535 @emph{corresponding} types as the Java methods,
1536 and are called in the natural manner.
1538 @subsection Overloading
1540 Both Java and C++ provide method overloading, where multiple
1541 methods in a class have the same name, and the correct one is chosen
1542 (at compile time) depending on the argument types.
1543 The rules for choosing the correct method are (as expected) more complicated
1544 in C++ than in Java, but given a set of overloaded methods
1545 generated by @code{gcjh} the C++ compiler will choose
1548 Common assemblers and linkers are not aware of C++ overloading,
1549 so the standard implementation strategy is to encode the
1550 parameter types of a method into its assembly-level name.
1551 This encoding is called @dfn{mangling},
1552 and the encoded name is the @dfn{mangled name}.
1553 The same mechanism is used to implement Java overloading.
1554 For C++/Java interoperability, it is important that both the Java
1555 and C++ compilers use the @emph{same} encoding scheme.
1557 @subsection Static methods
1559 Static Java methods are invoked in @acronym{CNI} using the standard
1560 C++ syntax, using the @code{::} operator rather
1561 than the @code{.} operator.
1563 @noindent For example:
1566 jint i = java::lang::Math::round((jfloat) 2.3);
1569 @noindent C++ method definition syntax is used to define a static native method.
1573 #include <java/lang/Integer>
1574 java::lang::Integer*
1575 java::lang::Integer::getInteger(jstring str)
1582 @subsection Object Constructors
1584 Constructors are called implicitly as part of object allocation
1585 using the @code{new} operator.
1587 @noindent For example:
1590 java::lang::Integer *x = new java::lang::Integer(234);
1593 Java does not allow a constructor to be a native method.
1594 This limitation can be coded round however because a constructor
1595 can @emph{call} a native method.
1598 @subsection Instance methods
1600 Calling a Java instance method from a C++ @acronym{CNI} method is done
1601 using the standard C++ syntax, e.g.:
1604 // @r{First create the Java object.}
1605 java::lang::Integer *x = new java::lang::Integer(234);
1606 // @r{Now call a method.}
1607 jint prim_value = x->intValue();
1608 if (x->longValue == 0)
1612 @noindent Defining a Java native instance method is also done the natural way:
1615 #include <java/lang/Integer.h>
1618 java::lang:Integer::doubleValue()
1620 return (jdouble) value;
1625 @subsection Interface methods
1627 In Java you can call a method using an interface reference. This is
1628 supported, but not completely. @xref{Interfaces}.
1636 @acronym{CNI} provides a number of utility functions for
1637 working with Java Java @code{String} objects.
1638 The names and interfaces are analogous to those of @acronym{JNI}.
1641 @deftypefun jstring JvNewString (const char* @var{chars}, jsize @var{len})
1642 Returns a Java @code{String} object with characters from the C string
1643 @var{chars} up to the index @var{len} in that array.
1646 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes}, jsize @var{len})
1647 Returns a Java @code{String} made up of @var{len} bytes from @var{bytes}.
1651 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1652 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
1655 @deftypefun jstring JvNewStringUTF (const char* @var{bytes})
1656 Returns a @code{String} which is made up of the UTF encoded characters
1657 present in the C string @var{bytes}.
1660 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1661 Returns a pointer to an array of characters making up the @code{String} @var{str}.
1664 @deftypefun int JvGetStringUTFLength (jstring @var{str})
1665 Returns the number of bytes required to encode the contents of the
1666 @code{String} @var{str} in UTF-8.
1669 @deftypefun jsize JvGetStringUTFRegion (jstring @var{str}, jsize @var{start}, jsize @var{len}, char* @var{buf})
1670 Puts the UTF-8 encoding of a region of the @code{String} @var{str} into
1671 the buffer @code{buf}. The region to fetch is marked by @var{start} and @var{len}.
1673 Note that @var{buf} is a buffer, not a C string. It is @emph{not}
1678 @node Mixing with C++
1679 @section Interoperating with C/C++
1681 Because @acronym{CNI} is designed to represent Java classes and methods it
1682 cannot be mixed readily with C/C++ types.
1684 One important restriction is that Java classes cannot have non-Java
1685 type instance or static variables and cannot have methods which take
1686 non-Java types as arguments or return non-Java types.
1688 @noindent None of the following is possible with CNI:
1692 class ::MyClass : public java::lang::Object
1694 char* variable; // @r{char* is not a valid Java type.}
1699 ::SomeClass::someMethod (char *arg)
1704 @} // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1707 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1712 ::SomeClass::otherMethod (jstring str)
1721 But this restriction can cause a problem so @acronym{CNI} includes the
1722 @code{gnu.gcj.RawData} class. The @code{RawData} class is a
1723 @dfn{non-scanned reference} type. In other words variables declared
1724 of type @code{RawData} can contain any data and are not checked by the
1725 compiler in any way.
1727 This means that you can put C/C++ data structures (including classes)
1728 in your @acronym{CNI} classes, as long as you use the appropriate cast.
1730 @noindent Here are some examples:
1734 class ::MyClass : public java::lang::Object
1736 gnu.gcj.RawData string;
1739 gnu.gcj.RawData getText ();
1743 ::MyClass::MyClass ()
1750 ::MyClass::getText ()
1756 ::MyClass::printText ()
1758 printf("%s\n", (char*) string);
1763 @node Exception Handling
1764 @section Exception Handling
1766 While C++ and Java share a common exception handling framework,
1767 things are not yet perfectly integrated. The main issue is that the
1768 run-time type information facilities of the two
1769 languages are not integrated.
1771 Still, things work fairly well. You can throw a Java exception from
1772 C++ using the ordinary @code{throw} construct, and this
1773 exception can be caught by Java code. Similarly, you can catch an
1774 exception thrown from Java using the C++ @code{catch}
1777 @noindent Here is an example:
1781 throw new java::lang::IndexOutOfBoundsException();
1784 Normally, G++ will automatically detect when you are writing C++
1785 code that uses Java exceptions, and handle them appropriately.
1786 However, if C++ code only needs to execute destructors when Java
1787 exceptions are thrown through it, GCC will guess incorrectly. Sample
1791 struct S @{ ~S(); @};
1793 extern void bar(); // @r{Is implemented in Java and may throw exceptions.}
1802 The usual effect of an incorrect guess is a link failure, complaining of
1803 a missing routine called @code{__gxx_personality_v0}.
1805 You can inform the compiler that Java exceptions are to be used in a
1806 translation unit, irrespective of what it might think, by writing
1807 @code{#pragma GCC java_exceptions} at the head of the
1808 file. This @code{#pragma} must appear before any
1809 functions that throw or catch exceptions, or run destructors when
1810 exceptions are thrown through them.
1812 @node Synchronization
1813 @section Synchronization
1815 Each Java object has an implicit monitor.
1816 The Java VM uses the instruction @code{monitorenter} to acquire
1817 and lock a monitor, and @code{monitorexit} to release it.
1819 The corresponding CNI macros are @code{JvMonitorEnter} and
1820 @code{JvMonitorExit} (JNI has similar methods @code{MonitorEnter}
1821 and @code{MonitorExit}).
1824 The Java source language does not provide direct access to these primitives.
1825 Instead, there is a @code{synchronized} statement that does an
1826 implicit @code{monitorenter} before entry to the block,
1827 and does a @code{monitorexit} on exit from the block.
1828 Note that the lock has to be released even when the block is abnormally
1829 terminated by an exception, which means there is an implicit
1830 @code{try finally} surrounding synchronization locks.
1832 From C++, it makes sense to use a destructor to release a lock.
1833 @acronym{CNI} defines the following utility class:
1836 class JvSynchronize() @{
1838 JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
1839 ~JvSynchronize() @{ JvMonitorExit(obj); @}
1852 @noindent might become this C++ code:
1856 JvSynchronize dummy (OBJ);
1861 Java also has methods with the @code{synchronized} attribute.
1862 This is equivalent to wrapping the entire method body in a
1863 @code{synchronized} statement.
1864 (Alternatively, an implementation could require the caller to do
1865 the synchronization. This is not practical for a compiler, because
1866 each virtual method call would have to test at run-time if
1867 synchronization is needed.) Since in @command{gcj}
1868 the @code{synchronized} attribute is handled by the
1869 method implementation, it is up to the programmer
1870 of a synchronized native method to handle the synchronization
1871 (in the C++ implementation of the method).
1872 In other words, you need to manually add @code{JvSynchronize}
1873 in a @code{native synchronized} method.
1878 CNI permits C++ applications to make calls into Java classes, in addition to
1879 allowing Java code to call into C++. Several functions, known as the
1880 @dfn{invocation API}, are provided to support this.
1882 @deftypefun jint JvCreateJavaVM (void* @var{vm_args})
1883 Initializes the Java runtime. This function performs essential initialization
1884 of the threads interface, garbage collector, exception handling and other key
1885 aspects of the runtime. It must be called once by an application with
1886 a non-Java @code{main()} function, before any other Java or CNI calls are made.
1887 It is safe, but not recommended, to call @code{JvCreateJavaVM()} more than
1888 once provided it is only called from a single thread.
1889 The @var{vmargs} parameter can be used to specify initialization parameters
1890 for the Java runtime. It may be @code{NULL}.
1891 This function returns @code{0} upon success, or @code{-1} if the runtime is
1892 already initialized.
1894 @emph{Note:} In GCJ 3.1, the @code{vm_args} parameter is ignored. It may be
1895 used in a future release.
1898 @deftypefun java::lang::Thread* JvAttachCurrentThread (jstring @var{name}, java::lang::ThreadGroup* @var{group})
1899 Registers an existing thread with the Java runtime. This must be called once
1900 from each thread, before that thread makes any other Java or CNI calls. It
1901 must be called after @code{JvCreateJavaVM}.
1902 @var{name} specifies a name for the thread. It may be @code{NULL}, in which
1903 case a name will be generated.
1904 @var{group} is the ThreadGroup in which this thread will be a member. If it
1905 is @code{NULL}, the thread will be a member of the main thread group.
1906 The return value is the Java @code{Thread} object that represents the thread.
1907 It is safe to call @code{JvAttachCurrentThread()} more than once from the same
1908 thread. If the thread is already attached, the call is ignored and the current
1909 thread object is returned.
1912 @deftypefun jint JvDetachCurrentThread ()
1913 Unregisters a thread from the Java runtime. This should be called by threads
1914 that were attached using @code{JvAttachCurrentThread()}, after they have
1915 finished making calls to Java code. This ensures that any resources associated
1916 with the thread become eligible for garbage collection.
1917 This function returns @code{0} upon success, or @code{-1} if the current thread
1921 @subsection Handling uncaught exceptions
1923 If an exception is thrown from Java code called using the invocation API, and
1924 no handler for the exception can be found, the runtime will abort the
1925 application. In order to make the application more robust, it is recommended
1926 that code which uses the invocation API be wrapped by a top-level try/catch
1927 block that catches all Java exceptions.
1931 The following code demonstrates the use of the invocation API. In this
1932 example, the C++ application initializes the Java runtime and attaches
1933 itself. The @code{java.lang.System} class is initialized in order to
1934 access its @code{out} field, and a Java string is printed. Finally, the thread
1935 is detached from the runtime once it has finished making Java calls. Everything
1936 is wrapped with a try/catch block to provide a default handler for any uncaught
1939 The example can be compiled with @command{c++ test.cc -lgcj}.
1943 #include <gcj/cni.h>
1944 #include <java/lang/System.h>
1945 #include <java/io/PrintStream.h>
1946 #include <java/lang/Throwable.h>
1948 int main(int argc, char *argv)
1950 using namespace java::lang;
1954 JvCreateJavaVM(NULL);
1955 JvAttachCurrentThread(NULL, NULL);
1957 String *message = JvNewStringLatin1("Hello from C++");
1958 JvInitClass(&System::class$);
1959 System::out->println(message);
1961 JvDetachCurrentThread();
1963 catch (Throwable *t)
1965 System::err->println(JvNewStringLatin1("Unhandled Java exception:"));
1966 t->printStackTrace();
1974 Reflection is possible with CNI code, it functions similarly to how it
1975 functions with JNI@.
1977 @c clean this up... I mean, what are the types jfieldID and jmethodID in JNI?
1978 The types @code{jfieldID} and @code{jmethodID}
1981 @noindent The functions:
1984 @item @code{JvFromReflectedField},
1985 @item @code{JvFromReflectedMethod},
1986 @item @code{JvToReflectedField}
1987 @item @code{JvToFromReflectedMethod}
1990 @noindent will be added shortly, as will other functions corresponding to JNI@.
1993 @node System properties
1994 @chapter System properties
1996 The runtime behavior of the @code{libgcj} library can be modified by setting
1997 certain system properties. These properties can be compiled into the program
1998 using the @code{-D@var{name}[=@var{value}]} option to @command{gcj} or by
1999 setting them explicitly in the program by calling the
2000 @code{java.lang.System.setProperty()} method. Some system properties are only
2001 used for informational purposes (like giving a version number or a user name).
2002 A program can inspect the current value of a property by calling the
2003 @code{java.lang.System.getProperty()} method.
2006 * Standard Properties:: Standard properties supported by @code{libgcj}
2007 * GNU Classpath Properties:: Properties found in Classpath based libraries
2008 * libgcj Runtime Properties:: Properties specific to @code{libgcj}
2011 @node Standard Properties
2012 @section Standard Properties
2014 The following properties are normally found in all implementations of the core
2015 libraries for the Java language.
2020 The @code{libgcj} version number.
2023 Set to @samp{The Free Software Foundation, Inc.}
2025 @item java.vendor.url
2026 Set to @uref{http://gcc.gnu.org/java/}.
2029 The directory where @code{gcj} was installed. Taken from the @code{--prefix}
2030 option given to @command{configure}.
2032 @item java.class.version
2033 The class format version number supported by the libgcj byte code interpreter.
2034 (Currently @samp{46.0})
2036 @item java.vm.specification.version
2037 The Virtual Machine Specification version implemented by @code{libgcj}.
2038 (Currently @samp{1.0})
2040 @item java.vm.specification.vendor
2041 The name of the Virtual Machine specification designer.
2043 @item java.vm.specification.name
2044 The name of the Virtual Machine specification
2045 (Set to @samp{Java Virtual Machine Specification}).
2047 @item java.vm.version
2048 The @command{gcj} version number.
2050 @item java.vm.vendor
2051 Set to @samp{The Free Software Foundation, Inc.}
2054 Set to @samp{GNU libgcj}.
2056 @item java.specification.version
2057 The Runtime Environment specification version implemented by @code{libgcj}.
2058 (Currently set to @samp{1.3})
2060 @item java.specification.vendor
2061 The Runtime Environment specification designer.
2063 @item java.specification.name
2064 The name of the Runtime Environment specification
2065 (Set to @samp{Java Platform API Specification}).
2067 @item java.class.path
2068 The paths (jar files, zip files and directories) used for finding class files.
2070 @item java.library.path
2071 Directory path used for finding native libraries.
2073 @item java.io.tmpdir
2074 The directory used to put temporary files in.
2077 Name of the Just In Time compiler to use by the byte code interpreter.
2078 Currently not used in @code{libgcj}.
2081 Directories containing jar files with extra libraries. Will be used when
2082 resolving classes. Currently not used in @code{libgcj}.
2084 @item java.protocol.handler.pkgs
2085 A @samp{|} separated list of package names that is used to find classes that
2086 implement handlers for @code{java.net.URL}.
2088 @item java.rmi.server.codebase
2089 A list of URLs that is used by the @code{java.rmi.server.RMIClassLoader}
2090 to load classes from.
2093 A list of class names that will be loaded by the @code{java.sql.DriverManager}
2096 @item file.separator
2097 The separator used in when directories are included in a filename
2098 (normally @samp{/} or @samp{\} ).
2101 The default character encoding used when converting platform native files to
2102 Unicode (usually set to @samp{8859_1}).
2104 @item path.separator
2105 The standard separator used when a string contains multiple paths
2106 (normally @samp{:} or @samp{;}), the string is usually not a valid character
2107 to use in normal directory names.)
2109 @item line.separator
2110 The default line separator used on the platform (normally @samp{\n}, @samp{\r}
2111 or a combination of those two characters).
2113 @item policy.provider
2114 The class name used for the default policy provider returned by
2115 @code{java.security.Policy.getPolicy}.
2118 The name of the user running the program. Can be the full name, the login name
2119 or empty if unknown.
2122 The default directory to put user specific files in.
2125 The current working directory from which the program was started.
2128 The default language as used by the @code{java.util.Locale} class.
2131 The default region as used by the @code{java.util.Local} class.
2134 The default variant of the language and region local used.
2137 The default timezone as used by the @code{java.util.TimeZone} class.
2140 The operating system/kernel name that the program runs on.
2143 The hardware that we are running on.
2146 The version number of the operating system/kernel.
2148 @item awt.appletWarning
2149 The string to display when an untrusted applet is displayed.
2150 Returned by @code{java.awt.Window.getWarningString()} when the window is
2154 The class name used for initializing the default @code{java.awt.Toolkit}.
2155 Defaults to @code{gnu.awt.gtk.GtkToolkit}.
2157 @item http.proxyHost
2158 Name of proxy host for http connections.
2160 @item http.proxyPort
2161 Port number to use when a proxy host is in use.
2165 @node GNU Classpath Properties
2166 @section GNU Classpath Properties
2168 @code{libgcj} is based on the GNU Classpath (Essential Libraries for Java) a
2169 GNU project to create free core class libraries for use with virtual machines
2170 and compilers for the Java language. The following properties are common to
2171 libraries based on GNU Classpath.
2175 @item gcj.dumpobject
2176 Enables printing serialization debugging by the @code{java.io.ObjectInput} and
2177 @code{java.io.ObjectOutput} classes when set to something else then the empty
2178 string. Only used when running a debug build of the library.
2180 @item gnu.classpath.vm.shortname
2181 This is a succint name of the virtual machine. For @code{libgcj},
2182 this will always be @samp{libgcj}.
2184 @item gnu.classpath.home.url
2185 A base URL used for finding system property files (e.g.,
2186 @file{classpath.security}). By default this is a @samp{file:} URL
2187 pointing to the @file{lib} directory under @samp{java.home}.
2191 @node libgcj Runtime Properties
2192 @section libgcj Runtime Properties
2194 The following properties are specific to the @code{libgcj} runtime and will
2195 normally not be found in other core libraries for the java language.
2199 @item java.fullversion
2200 The combination of @code{java.vm.name} and @code{java.vm.version}.
2203 Same as @code{java.fullversion}.
2206 Used by the @code{java.net.DatagramSocket} class when set to something else
2207 then the empty string. When set all newly created @code{DatagramSocket}s will
2208 try to load a class @code{java.net.[impl.prefix]DatagramSocketImpl} instead of
2209 the normal @code{java.net.PlainDatagramSocketImpl}.
2211 @item gnu.gcj.progname
2212 The name that was used to invoked the program.
2214 @item gnu.gcj.runtime.NameFinder.demangle
2215 Whether names in a stack trace should be demangled. Defaults to @code{true}.
2217 @item gnu.gcj.runtime.NameFinder.sanitize
2218 Whether calls to initialize exceptions and starting the runtime system
2219 should be removed from the stack trace. Only done when names are
2220 demangled. Defaults to @code{true}.
2222 @item gnu.gcj.runtime.NameFinder.remove_unknown
2223 Whether calls to unknown functions (class and method names are unknown)
2224 should be removed from the stack trace. Only done when the stack is
2225 sanitized. Ignored if this means no stack trace information would be
2226 available anymore. Defaults to @code{true}.
2228 @item gnu.gcj.runtime.NameFinder.remove_interpreter
2229 Whether runtime interpreter calls (methods in the @code{_Jv_InterpMethod} class
2230 and functions starting with @samp{ffi_}) should be removed from the stack
2231 trace. Only done when the stack is sanitized. Defaults to @code{true}.
2234 @item gnu.gcj.runtime.NameFinder.use_addr2line
2235 Whether an external process (@command{addr2line} or @command{addr2name.awk})
2236 should be used as fallback to convert the addresses to function names when
2237 the runtime is unable to do it through @code{dladdr}.
2245 While writing @command{gcj} and @code{libgcj} we have, of course, relied
2246 heavily on documentation from Sun Microsystems. In particular we have
2247 used The Java Language Specification (both first and second editions),
2248 the Java Class Libraries (volumes one and two), and the Java Virtual
2249 Machine Specification. In addition we've used the online documentation
2250 at @uref{http://java.sun.com/}.
2252 The current @command{gcj} home page is
2253 @uref{http://gcc.gnu.org/java/}.
2255 For more information on gcc, see @uref{http://gcc.gnu.org/}.
2257 Some @code{libgcj} testing is done using the Mauve test suite. This is
2258 a free software Java class library test suite which is being written
2259 because the JCK is not free. See
2260 @uref{http://sources.redhat.com/mauve/} for more information.