2008-05-30 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / gcc / java / gcj.texi
blob40e1cd6c10bf7e0471df80b733eb8b2c27f95fc1
1 \input texinfo @c -*-texinfo-*-
2 @setfilename gcj.info
3 @settitle Guide to GNU gcj
5 @c Merge the standard indexes into a single one.
6 @syncodeindex fn cp
7 @syncodeindex vr cp
8 @syncodeindex ky cp
9 @syncodeindex pg cp
10 @syncodeindex tp cp
12 @include gcc-common.texi
14 @c Note: When reading this manual you'll find lots of strange
15 @c circumlocutions like ``compiler for the Java language''.
16 @c This is necessary due to Sun's restrictions on the use of
17 @c the word ``Java'.
19 @c When this manual is copyrighted.
20 @set copyrights-gcj 2001, 2002, 2003, 2004, 2005, 2006, 2007
22 @copying
23 @c man begin COPYRIGHT
24 Copyright @copyright{} @value{copyrights-gcj} Free Software Foundation, Inc.
26 Permission is granted to copy, distribute and/or modify this document
27 under the terms of the GNU Free Documentation License, Version 1.2 or
28 any later version published by the Free Software Foundation; with the
29 Invariant Sections being ``GNU General Public License'', the Front-Cover
30 texts being (a) (see below), and with the Back-Cover Texts being (b)
31 (see below).  A copy of the license is included in the
32 @c man end
33 section entitled
34 ``GNU Free Documentation License''.
35 @ignore
36 @c man begin COPYRIGHT
37 man page gfdl(7).
38 @c man end
39 @end ignore
41 @c man begin COPYRIGHT
43 (a) The FSF's Front-Cover Text is:
45      A GNU Manual
47 (b) The FSF's Back-Cover Text is:
49      You have freedom to copy and modify this GNU Manual, like GNU
50      software.  Copies published by the Free Software Foundation raise
51      funds for GNU development.
52 @c man end
53 @end copying
55 @ifinfo
56 @format
57 @dircategory Software development
58 @direntry
59 * Gcj: (gcj).               Ahead-of-time compiler for the Java language
60 @end direntry
62 @dircategory Individual utilities
63 @direntry
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 * gcj-dbtool: (gcj)Invoking gcj-dbtool.
68                             Tool for manipulating class file databases.
69 * jv-convert: (gcj)Invoking jv-convert.
70                             Convert file from one encoding to another
71 * grmic: (gcj)Invoking grmic.
72                             Generate stubs for Remote Method Invocation.
73 * gc-analyze: (gcj)Invoking gc-analyze.
74                             Analyze Garbage Collector (GC) memory dumps.
75 @end direntry
76 @end format
78 @insertcopying
79 @end ifinfo
81 @titlepage
82 @title GNU gcj
83 @versionsubtitle
84 @author Tom Tromey
86 @page
87 @vskip 0pt plus 1filll
88 Published by the Free Software Foundation @*
89 51 Franklin Street, Fifth Floor@*
90 Boston, MA 02110-1301, USA@*
91 @sp 1
92 @insertcopying
93 @end titlepage
94 @contents
95 @page
98 @node Top
99 @top Introduction
101 This manual describes how to use @command{gcj}, the GNU compiler for the
102 Java programming language.  @command{gcj} can generate both @file{.class}
103 files and object files, and it can read both Java source code and
104 @file{.class} files.
106 @menu
107 * Copying::              The GNU General Public License
108 * GNU Free Documentation License::
109                         How you can share and copy this manual
110 * Invoking gcj::        Compiler options supported by @command{gcj}
111 * Compatibility::       Compatibility between gcj and other tools for Java
112 * Invoking jcf-dump::   Print information about class files
113 * Invoking gij::        Interpreting Java bytecodes
114 * Invoking gcj-dbtool:: Tool for manipulating class file databases.
115 * Invoking jv-convert:: Converting from one encoding to another
116 * Invoking grmic::      Generate stubs for Remote Method Invocation.
117 * Invoking gc-analyze:: Analyze Garbage Collector (GC) memory dumps.
118 * About CNI::           Description of the Compiled Native Interface
119 * System properties::   Modifying runtime behavior of the libgcj library
120 * Resources::           Where to look for more information
121 * Index::               Index.
122 @end menu
125 @include gpl_v3.texi
127 @include fdl.texi
130 @node Invoking gcj
131 @chapter Invoking gcj
133 @c man title gcj Ahead-of-time compiler for the Java language
135 @ignore
136 @c man begin SYNOPSIS gcj
137 gcj [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
138     [@option{--CLASSPATH}=@var{path}] [@option{--classpath}=@var{path}]
139     [@option{-f}@var{option}@dots{}] [@option{--encoding}=@var{name}]
140     [@option{--main}=@var{classname}] [@option{-D}@var{name}[=@var{value}]@dots{}]
141     [@option{-C}] [@option{--resource} @var{resource-name}] [@option{-d} @var{directory}]
142     [@option{-W}@var{warn}@dots{}]
143     @var{sourcefile}@dots{}
144 @c man end
145 @c man begin SEEALSO gcj
146 gcc(1), gcjh(1), gjnih(1), gij(1), jcf-dump(1), gfdl(7),
147 and the Info entries for @file{gcj} and @file{gcc}.
148 @c man end
149 @end ignore
151 @c man begin DESCRIPTION gcj
153 As @command{gcj} is just another front end to @command{gcc}, it supports many
154 of the same options as gcc.  @xref{Option Summary, , Option Summary,
155 gcc, Using the GNU Compiler Collection (GCC)}.  This manual only documents the
156 options specific to @command{gcj}.
158 @c man end
160 @menu
161 * Input and output files::
162 * Input Options::               How gcj finds files
163 * Encodings::                   Options controlling source file encoding
164 * Warnings::                    Options controlling warnings specific to gcj
165 * Linking::                     Options for making an executable
166 * Code Generation::             Options controlling the output of gcj
167 * Configure-time Options::      Options you won't use
168 @end menu
170 @c man begin OPTIONS gcj
172 @node Input and output files
173 @section Input and output files
175 A @command{gcj} command is like a @command{gcc} command, in that it
176 consists of a number of options and file names.  The following kinds
177 of input file names are supported:
179 @table @gcctabopt
180 @item @var{file}.java
181 Java source files.
182 @item @var{file}.class
183 Java bytecode files.
184 @item @var{file}.zip
185 @itemx @var{file}.jar
186 An archive containing one or more @code{.class} files, all of
187 which are compiled.  The archive may be compressed.  Files in
188 an archive which don't end with @samp{.class} are treated as
189 resource files; they are compiled into the resulting object file
190 as @samp{core:} URLs.
191 @item @@@var{file}
192 A file containing a whitespace-separated list of input file names.
193 (Currently, these must all be @code{.java} source files, but that
194 may change.)
195 Each named file is compiled, just as if it had been on the command line.
196 @item @var{library}.a
197 @itemx @var{library}.so
198 @itemx -l@var{libname}
199 Libraries to use when linking.  See the @command{gcc} manual.
200 @end table
202 You can specify more than one input file on the @command{gcj} command line,
203 in which case they will all be compiled.  If you specify a
204 @code{-o @var{FILENAME}}
205 option, all the input files will be compiled together, producing a
206 single output file, named @var{FILENAME}.
207 This is allowed even when using @code{-S} or @code{-c},
208 but not when using @code{-C} or @code{--resource}.
209 (This is an extension beyond the what plain @command{gcc} allows.)
210 (If more than one input file is specified, all must currently
211 be @code{.java} files, though we hope to fix this.)
213 @node Input Options
214 @section Input Options
216 @cindex class path
218 @command{gcj} has options to control where it looks to find files it needs.
219 For instance, @command{gcj} might need to load a class that is referenced
220 by the file it has been asked to compile.  Like other compilers for the
221 Java language, @command{gcj} has a notion of a @dfn{class path}.  There are
222 several options and environment variables which can be used to
223 manipulate the class path.  When @command{gcj} looks for a given class, it
224 searches the class path looking for matching @file{.class} or
225 @file{.java} file.  @command{gcj} comes with a built-in class path which
226 points at the installed @file{libgcj.jar}, a file which contains all the
227 standard classes.
229 In the text below, a directory or path component can refer either to an
230 actual directory on the filesystem, or to a @file{.zip} or @file{.jar}
231 file, which @command{gcj} will search as if it is a directory.
233 @table @gcctabopt
234 @item -I@var{dir}
235 All directories specified by @code{-I} are kept in order and prepended
236 to the class path constructed from all the other options.  Unless
237 compatibility with tools like @code{javac} is important, we recommend
238 always using @code{-I} instead of the other options for manipulating the
239 class path.
241 @item --classpath=@var{path}
242 This sets the class path to @var{path}, a colon-separated list of paths
243 (on Windows-based systems, a semicolon-separate list of paths).
244 This does not override the builtin (``boot'') search path.
246 @item --CLASSPATH=@var{path}
247 Deprecated synonym for @code{--classpath}.
249 @item --bootclasspath=@var{path}
250 Where to find the standard builtin classes, such as @code{java.lang.String}.
252 @item --extdirs=@var{path}
253 For each directory in the @var{path}, place the contents of that
254 directory at the end of the class path.
256 @item CLASSPATH
257 This is an environment variable which holds a list of paths.
258 @end table
260 The final class path is constructed like so:
262 @itemize @bullet
263 @item
264 First come all directories specified via @code{-I}.
266 @item
267 If @option{--classpath} is specified, its value is appended.
268 Otherwise, if the @code{CLASSPATH} environment variable is specified,
269 then its value is appended.
270 Otherwise, the current directory (@code{"."}) is appended.
272 @item
273 If @code{--bootclasspath} was specified, append its value.
274 Otherwise, append the built-in system directory, @file{libgcj.jar}.
276 @item
277 Finally, if @code{--extdirs} was specified, append the contents of the
278 specified directories at the end of the class path.  Otherwise, append
279 the contents of the built-in extdirs at @code{$(prefix)/share/java/ext}.
280 @end itemize
282 The classfile built by @command{gcj} for the class @code{java.lang.Object}
283 (and placed in @code{libgcj.jar}) contains a special zero length
284 attribute @code{gnu.gcj.gcj-compiled}. The compiler looks for this
285 attribute when loading @code{java.lang.Object} and will report an error
286 if it isn't found, unless it compiles to bytecode (the option
287 @code{-fforce-classes-archive-check} can be used to override this
288 behavior in this particular case.)
290 @table @gcctabopt
291 @item -fforce-classes-archive-check
292 This forces the compiler to always check for the special zero length
293 attribute @code{gnu.gcj.gcj-compiled} in @code{java.lang.Object} and
294 issue an error if it isn't found.
296 @item -fsource=@var{VERSION}
297 This option is used to choose the source version accepted by
298 @command{gcj}.  The default is @samp{1.5}.
299 @end table
301 @node Encodings
302 @section Encodings
304 The Java programming language uses Unicode throughout.  In an effort to
305 integrate well with other locales, @command{gcj} allows @file{.java} files
306 to be written using almost any encoding.  @command{gcj} knows how to
307 convert these encodings into its internal encoding at compile time.
309 You can use the @code{--encoding=@var{NAME}} option to specify an
310 encoding (of a particular character set) to use for source files.  If
311 this is not specified, the default encoding comes from your current
312 locale.  If your host system has insufficient locale support, then
313 @command{gcj} assumes the default encoding to be the @samp{UTF-8} encoding
314 of Unicode.
316 To implement @code{--encoding}, @command{gcj} simply uses the host
317 platform's @code{iconv} conversion routine.  This means that in practice
318 @command{gcj} is limited by the capabilities of the host platform.
320 The names allowed for the argument @code{--encoding} vary from platform
321 to platform (since they are not standardized anywhere).  However,
322 @command{gcj} implements the encoding named @samp{UTF-8} internally, so if
323 you choose to use this for your source files you can be assured that it
324 will work on every host.
327 @node Warnings
328 @section Warnings
330 @command{gcj} implements several warnings.  As with other generic
331 @command{gcc} warnings, if an option of the form @code{-Wfoo} enables a
332 warning, then @code{-Wno-foo} will disable it.  Here we've chosen to
333 document the form of the warning which will have an effect -- the
334 default being the opposite of what is listed.
336 @table @gcctabopt
337 @item -Wredundant-modifiers
338 With this flag, @command{gcj} will warn about redundant modifiers.  For
339 instance, it will warn if an interface method is declared @code{public}.
341 @item -Wextraneous-semicolon
342 This causes @command{gcj} to warn about empty statements.  Empty statements
343 have been deprecated.
345 @item -Wno-out-of-date
346 This option will cause @command{gcj} not to warn when a source file is
347 newer than its matching class file.  By default @command{gcj} will warn
348 about this.
350 @item -Wno-deprecated
351 Warn if a deprecated class, method, or field is referred to.
353 @item -Wunused
354 This is the same as @command{gcc}'s @code{-Wunused}.
356 @item -Wall
357 This is the same as @code{-Wredundant-modifiers -Wextraneous-semicolon
358 -Wunused}.
359 @end table
362 @node Linking
363 @section Linking
365 To turn a Java application into an executable program,
366 you need to link it with the needed libraries, just as for C or C++.
367 The linker by default looks for a global function named @code{main}.
368 Since Java does not have global functions, and a
369 collection of Java classes may have more than one class with a
370 @code{main} method, you need to let the linker know which of those
371 @code{main} methods it should invoke when starting the application.
372 You can do that in any of these ways:
374 @itemize @bullet
375 @item
376 Specify the class containing the desired @code{main} method
377 when you link the application, using the @code{--main} flag,
378 described below.
379 @item
380 Link the Java package(s) into a shared library (dll) rather than an
381 executable.  Then invoke the application using the @code{gij} program,
382 making sure that @code{gij} can find the libraries it needs.
383 @item
384 Link the Java packages(s) with the flag @code{-lgij}, which links
385 in the @code{main} routine from the @code{gij} command.
386 This allows you to select the class whose @code{main} method you
387 want to run when you run the application.  You can also use
388 other @code{gij} flags, such as @code{-D} flags to set properties.
389 Using the @code{-lgij} library (rather than the @code{gij} program
390 of the previous mechanism) has some advantages: it is compatible with
391 static linking, and does not require configuring or installing libraries.
392 @end itemize
394 These @code{gij} options relate to linking an executable:
396 @table @gcctabopt
397 @item --main=@var{CLASSNAME}
398 This option is used when linking to specify the name of the class whose
399 @code{main} method should be invoked when the resulting executable is
400 run.
402 @item -D@var{name}[=@var{value}]
403 This option can only be used with @code{--main}.  It defines a system
404 property named @var{name} with value @var{value}.  If @var{value} is not
405 specified then it defaults to the empty string.  These system properties
406 are initialized at the program's startup and can be retrieved at runtime
407 using the @code{java.lang.System.getProperty} method.
409 @item -lgij
410 Create an application whose command-line processing is that
411 of the @code{gij} command.
413 This option is an alternative to using @code{--main}; you cannot use both.
415 @item -static-libgcj
416 This option causes linking to be done against a static version of the
417 libgcj runtime library.  This option is only available if
418 corresponding linker support exists.
420 @strong{Caution:} Static linking of libgcj may cause essential parts
421 of libgcj to be omitted.  Some parts of libgcj use reflection to load
422 classes at runtime.  Since the linker does not see these references at
423 link time, it can omit the referred to classes.  The result is usually
424 (but not always) a @code{ClassNotFoundException} being thrown at
425 runtime. Caution must be used when using this option.  For more
426 details see:
427 @w{@uref{http://gcc.gnu.org/wiki/Statically%20linking%20libgcj}}
428 @end table
430 @node Code Generation
431 @section Code Generation
433 In addition to the many @command{gcc} options controlling code generation,
434 @command{gcj} has several options specific to itself.
436 @table @gcctabopt
438 @item -C
439 This option is used to tell @command{gcj} to generate bytecode
440 (@file{.class} files) rather than object code.
442 @item --resource @var{resource-name}
443 This option is used to tell @command{gcj} to compile the contents of a
444 given file to object code so it may be accessed at runtime with the core
445 protocol handler as @samp{core:/@var{resource-name}}.  Note that
446 @var{resource-name} is the name of the resource as found at runtime; for
447 instance, it could be used in a call to @code{ResourceBundle.getBundle}.
448 The actual file name to be compiled this way must be specified
449 separately.
451 @item -ftarget=@var{VERSION}
452 This can be used with @option{-C} to choose the version of bytecode
453 emitted by @command{gcj}.  The default is @samp{1.5}.  When not
454 generating bytecode, this option has no effect.
456 @item -d @var{directory}
457 When used with @code{-C}, this causes all generated @file{.class} files
458 to be put in the appropriate subdirectory of @var{directory}.  By
459 default they will be put in subdirectories of the current working
460 directory.
462 @item -fno-bounds-check
463 By default, @command{gcj} generates code which checks the bounds of all
464 array indexing operations.  With this option, these checks are omitted, which
465 can improve performance for code that uses arrays extensively.  Note that this 
466 can result in unpredictable behavior if the code in question actually does 
467 violate array bounds constraints.  It is safe to use this option if you are 
468 sure that your code will never throw an @code{ArrayIndexOutOfBoundsException}.
470 @item -fno-store-check
471 Don't generate array store checks.  When storing objects into arrays, a runtime
472 check is normally generated in order to ensure that the object is assignment
473 compatible with the component type of the array (which may not be known
474 at compile-time).  With this option, these checks are omitted.  This can 
475 improve performance for code which stores objects into arrays frequently.
476 It is safe to use this option if you are sure your code will never throw an 
477 @code{ArrayStoreException}.
479 @item -fjni
480 With @command{gcj} there are two options for writing native methods: CNI
481 and JNI@.  By default @command{gcj} assumes you are using CNI@.  If you are
482 compiling a class with native methods, and these methods are implemented
483 using JNI, then you must use @code{-fjni}.  This option causes
484 @command{gcj} to generate stubs which will invoke the underlying JNI
485 methods.
487 @item -fno-assert
488 Don't recognize the @code{assert} keyword.  This is for compatibility
489 with older versions of the language specification.
491 @item -fno-optimize-static-class-initialization
492 When the optimization level is greater or equal to @code{-O2},
493 @command{gcj} will try to optimize the way calls into the runtime are made
494 to initialize static classes upon their first use (this optimization
495 isn't carried out if @code{-C} was specified.) When compiling to native
496 code, @code{-fno-optimize-static-class-initialization} will turn this
497 optimization off, regardless of the optimization level in use.
499 @item --disable-assertions[=@var{class-or-package}]
500 Don't include code for checking assertions in the compiled code.
501 If @code{=@var{class-or-package}} is missing disables assertion code
502 generation for all classes, unless overridden by a more
503 specific @code{--enable-assertions} flag.
504 If @var{class-or-package} is a class name, only disables generating
505 assertion checks within the named class or its inner classes.
506 If @var{class-or-package} is a package name, disables generating
507 assertion checks within the named package or a subpackage.
509 By default, assertions are enabled when generating class files
510 or when not optimizing, and disabled when generating optimized binaries.
512 @item --enable-assertions[=@var{class-or-package}]
513 Generates code to check assertions.  The option is perhaps misnamed,
514 as you still need to turn on assertion checking at run-time,
515 and we don't support any easy way to do that.
516 So this flag isn't very useful yet, except to partially override
517 @code{--disable-assertions}.
519 @item -findirect-dispatch
520 @command{gcj} has a special binary compatibility ABI, which is enabled
521 by the @code{-findirect-dispatch} option.  In this mode, the code
522 generated by @command{gcj} honors the binary compatibility guarantees
523 in the Java Language Specification, and the resulting object files do
524 not need to be directly linked against their dependencies.  Instead,
525 all dependencies are looked up at runtime.  This allows free mixing of
526 interpreted and compiled code.
528 Note that, at present, @code{-findirect-dispatch} can only be used
529 when compiling @file{.class} files.  It will not work when compiling
530 from source.  CNI also does not yet work with the binary compatibility
531 ABI.  These restrictions will be lifted in some future release.
533 However, if you compile CNI code with the standard ABI, you can call
534 it from code built with the binary compatibility ABI.
536 @item -fbootstrap-classes
537 This option can be use to tell @code{libgcj} that the compiled classes
538 should be loaded by the bootstrap loader, not the system class loader.
539 By default, if you compile a class and link it into an executable, it
540 will be treated as if it was loaded using the system class loader.
541 This is convenient, as it means that things like
542 @code{Class.forName()} will search @samp{CLASSPATH} to find the
543 desired class.
545 @item -freduced-reflection
546 This option causes the code generated by @command{gcj} to contain a
547 reduced amount of the class meta-data used to support runtime
548 reflection. The cost of this savings is the loss of
549 the ability to use certain reflection capabilities of the standard
550 Java runtime environment. When set all meta-data except for that
551 which is needed to obtain correct runtime semantics is eliminated.
553 For code that does not use reflection (i.e. the methods in the
554 @code{java.lang.reflect} package), @code{-freduced-reflection}
555 will result in proper operation with a savings in executable code size.
557 JNI (@code{-fjni}) and the binary compatibility ABI
558 (@code{-findirect-dispatch}) do not work properly without full
559 reflection meta-data.  Because of this, it is an error to use these options
560 with @code{-freduced-reflection}.
562 @strong{Caution:} If there is no reflection meta-data, code that uses
563 a @code{SecurityManager} may not work properly.  Also calling
564 @code{Class.forName()} may fail if the calling method has no
565 reflection meta-data.
567 @end table
570 @node Configure-time Options
571 @section Configure-time Options
573 Some @command{gcj} code generations options affect the resulting ABI, and
574 so can only be meaningfully given when @code{libgcj}, the runtime
575 package, is configured.  @code{libgcj} puts the appropriate options from
576 this group into a @samp{spec} file which is read by @command{gcj}.  These
577 options are listed here for completeness; if you are using @code{libgcj}
578 then you won't want to touch these options.
580 @table @gcctabopt
581 @item -fuse-boehm-gc
582 This enables the use of the Boehm GC bitmap marking code.  In particular
583 this causes @command{gcj} to put an object marking descriptor into each
584 vtable.
586 @item -fhash-synchronization
587 By default, synchronization data (the data used for @code{synchronize},
588 @code{wait}, and @code{notify}) is pointed to by a word in each object.
589 With this option @command{gcj} assumes that this information is stored in a
590 hash table and not in the object itself.
592 @item -fuse-divide-subroutine
593 On some systems, a library routine is called to perform integer
594 division.  This is required to get exception handling correct when
595 dividing by zero.
597 @item -fcheck-references
598 On some systems it's necessary to insert inline checks whenever
599 accessing an object via a reference.  On other systems you won't need
600 this because null pointer accesses are caught automatically by the
601 processor.
602 @end table
604 @c man end
606 @node Compatibility
607 @chapter Compatibility with the Java Platform
609 As we believe it is important that the Java platform not be fragmented,
610 @command{gcj} and @code{libgcj} try to conform to the relevant Java
611 specifications.  However, limited manpower and incomplete and unclear
612 documentation work against us.  So, there are caveats to using
613 @command{gcj}.
615 @menu
616 * Limitations::                 
617 * Extensions::                  
618 @end menu
620 @node Limitations
621 @section Standard features not yet supported
623 This list of compatibility issues is by no means complete.
625 @itemize @bullet
626 @item
627 @command{gcj} implements the JDK 1.2 language.  It supports inner classes
628 and the new 1.4 @code{assert} keyword.  It does not yet support the Java 2
629 @code{strictfp} keyword (it recognizes the keyword but ignores it).  
631 @item
632 @code{libgcj} is largely compatible with the JDK 1.2 libraries.
633 However, @code{libgcj} is missing many packages, most notably
634 @code{java.awt}.  There are also individual missing classes and methods.
635 We currently do not have a list showing differences between
636 @code{libgcj} and the Java 2 platform.
638 @item
639 Sometimes the @code{libgcj} implementation of a method or class differs
640 from the JDK implementation.  This is not always a bug.  Still, if it
641 affects you, it probably makes sense to report it so that we can discuss
642 the appropriate response.
644 @item
645 @command{gcj} does not currently allow for piecemeal replacement of
646 components within @code{libgcj}. Unfortunately, programmers often want
647 to use newer versions of certain packages, such as those provided by
648 the Apache Software Foundation's Jakarta project.  This has forced us
649 to place the @code{org.w3c.dom} and @code{org.xml.sax} packages into
650 their own libraries, separate from @code{libgcj}.  If you intend to
651 use these classes, you must link them explicitly with
652 @code{-l-org-w3c-dom} and @code{-l-org-xml-sax}.  Future versions of
653 @command{gcj} may not have this restriction.
654 @end itemize
656 @node Extensions
657 @section Extra features unique to gcj
659 The main feature of @command{gcj} is that it can compile programs written in
660 the Java programming language to native code.  Most extensions that have been
661 added are to facilitate this functionality.
663 @itemize @bullet
664 @item
665 @command{gcj} makes it easy and efficient to mix code written in Java and C++.
666 @xref{About CNI}, for more info on how to use this in your programs.
668 @item
669 When you compile your classes into a shared library using
670 @code{-findirect-dispatch} then add them to the system-wide
671 classmap.db file using @code{gcj-dbtool}, they will be automatically
672 loaded by the @code{libgcj} system classloader.  This is the new,
673 preferred classname-to-library resolution mechanism.  @xref{Invoking
674 gcj-dbtool}, for more information on using the classmap database.
676 @item
677 The old classname-to-library lookup mechanism is still supported
678 through the @code{gnu.gcj.runtime.VMClassLoader.library_control}
679 property, but it is deprecated and will likely be removed in some
680 future release.  When trying to load a class @code{gnu.pkg.SomeClass}
681 the system classloader will first try to load the shared library
682 @file{lib-gnu-pkg-SomeClass.so}, if that fails to load the class then
683 it will try to load @file{lib-gnu-pkg.so} and finally when the class
684 is still not loaded it will try to load @file{lib-gnu.so}.  Note that
685 all @samp{.}s will be transformed into @samp{-}s and that searching
686 for inner classes starts with their outermost outer class.  If the
687 class cannot be found this way the system classloader tries to use the
688 @code{libgcj} bytecode interpreter to load the class from the standard
689 classpath.  This process can be controlled to some degree via the
690 @code{gnu.gcj.runtime.VMClassLoader.library_control} property;
691 @xref{libgcj Runtime Properties}.
693 @item
694 @code{libgcj} includes a special @samp{gcjlib} URL type.  A URL of
695 this form is like a @code{jar} URL, and looks like
696 @samp{gcjlib:/path/to/shared/library.so!/path/to/resource}.  An access
697 to one of these URLs causes the shared library to be @code{dlopen()}d,
698 and then the resource is looked for in that library.  These URLs are
699 most useful when used in conjunction with @code{java.net.URLClassLoader}.
700 Note that, due to implementation limitations, currently any such URL
701 can be accessed by only one class loader, and libraries are never
702 unloaded.  This means some care must be exercised to make sure that
703 a @code{gcjlib} URL is not accessed by more than one class loader at once.
704 In a future release this limitation will be lifted, and such
705 libraries will be mapped privately.
707 @item
708 A program compiled by @command{gcj} will examine the
709 @env{GCJ_PROPERTIES} environment variable and change its behavior in
710 some ways.  In particular @env{GCJ_PROPERTIES} holds a list of
711 assignments to global properties, such as would be set with the
712 @option{-D} option to @command{java}.  For instance,
713 @samp{java.compiler=gcj} is a valid (but currently meaningless)
714 setting.
715 @cindex GCJ_PROPERTIES
716 @vindex GCJ_PROPERTIES
718 @end itemize
721 @node Invoking jcf-dump
722 @chapter Invoking jcf-dump
724 @c man title jcf-dump print information about Java class files
726 @ignore
727 @c man begin SYNOPSIS jcf-dump
728 jcf-dump [@option{-c}] [@option{--javap}]
729     [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
730     [@option{-I}@var{dir}@dots{}] [@option{-o} @var{file}]
731     [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
732     @var{classname}@dots{}
733 @c man end
734 @c man begin SEEALSO jcf-dump
735 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
736 and the Info entries for @file{gcj} and @file{gcc}.
737 @c man end
738 @end ignore
740 @c man begin DESCRIPTION jcf-dump
742 This is a class file examiner, similar to @code{javap}.  It will print
743 information about a number of classes, which are specified by class name
744 or file name.
746 @c man end
748 @c man begin OPTIONS jcf-dump
750 @table @gcctabopt
751 @item -c
752 Disassemble method bodies.  By default method bodies are not printed.
754 @item --print-constants
755 Print the constant pool.  When printing a reference to a constant
756 also print its index in the constant pool.
758 @item --javap
759 Generate output in @code{javap} format.  The implementation of this
760 feature is very incomplete.
762 @item --classpath=@var{path}
763 @itemx --CLASSPATH=@var{path}
764 @itemx -I@var{directory}
765 @itemx -o @var{file}
766 These options as the same as the corresponding @command{gcj} options.
768 @item --help
769 Print help, then exit.
771 @item --version
772 Print version number, then exit.
774 @item -v, --verbose
775 Print extra information while running.
776 Implies @code{--print-constants}.
777 @end table
779 @c man end
781 @node Invoking gij
782 @chapter Invoking gij
784 @c man title gij GNU interpreter for Java bytecode
786 @ignore
787 @c man begin SYNOPSIS gij
788 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
790 gij [@option{-jar}] [@option{OPTION}] @dots{} @var{CLASS} [@var{ARGS}@dots{}]
791   [@option{-cp} @var{path}] [@option{-classpath} @var{path}]
792   [@option{-D}@var{name}[=@var{value}]@dots{}]
793   [@option{-ms=}@var{number}] [@option{-mx=}@var{number}]
794   [@option{-X@var{argument}}] [@option{-verbose}] [@option{-verbose:class}]
795   [@option{--showversion}] [@option{--version}] [@option{--help}][@option{-?}]
796 @c man end
797 @c man begin SEEALSO gij
798 gcc(1), gcj(1), gcjh(1), jcf-dump(1), gfdl(7),
799 and the Info entries for @file{gcj} and @file{gcc}.
800 @c man end
801 @end ignore
803 @c man begin DESCRIPTION gij
805 @code{gij} is a Java bytecode interpreter included with @code{libgcj}.
806 @code{gij} is not available on every platform; porting it requires a
807 small amount of assembly programming which has not been done for all the
808 targets supported by @command{gcj}.
810 The primary argument to @code{gij} is the name of a class or, with
811 @code{-jar}, a jar file.  Options before this argument are interpreted
812 by @code{gij}; remaining options are passed to the interpreted program.
814 If a class name is specified and this class does not have a @code{main}
815 method with the appropriate signature (a @code{static void} method with
816 a @code{String[]} as its sole argument), then @code{gij} will print an
817 error and exit.
819 If a jar file is specified then @code{gij} will use information in it to
820 determine which class' @code{main} method will be invoked.
822 @code{gij} will invoke the @code{main} method with all the remaining
823 command-line options.
825 Note that @code{gij} is not limited to interpreting code.  Because
826 @code{libgcj} includes a class loader which can dynamically load shared
827 objects, it is possible to give @code{gij} the name of a class which has
828 been compiled and put into a shared library on the class path.
830 @c man end
832 @c man begin OPTIONS gij
834 @table @gcctabopt
835 @item -cp @var{path}
836 @itemx -classpath @var{path}
837 Set the initial class path.  The class path is used for finding
838 class and resource files.  If specified, this option overrides the
839 @code{CLASSPATH} environment variable.  Note that this option is
840 ignored if @code{-jar} is used.
842 @item -D@var{name}[=@var{value}]
843 This defines a system property named @var{name} with value @var{value}.
844 If @var{value} is not specified then it defaults to the empty string.
845 These system properties are initialized at the program's startup and can
846 be retrieved at runtime using the @code{java.lang.System.getProperty}
847 method.
849 @item -ms=@var{number}
850 Equivalent to @code{-Xms}.
852 @item -mx=@var{number}
853 Equivalent to @code{-Xmx}.
855 @item -noverify
856 Do not verify compliance of bytecode with the VM specification. In addition,
857 this option disables type verification which is otherwise performed on BC-ABI
858 compiled code.
860 @item -X
861 @itemx -X@var{argument}
862 Supplying @code{-X} by itself will cause @code{gij} to list all the
863 supported @code{-X} options.  Currently these options are supported:
865 @table @gcctabopt
866 @item -Xms@var{size}
867 Set the initial heap size.
869 @item -Xmx@var{size}
870 Set the maximum heap size.
872 @item -Xss@var{size}
873 Set the thread stack size.
874 @end table
876 Unrecognized @code{-X} options are ignored, for compatibility with
877 other runtimes.
879 @item -jar
880 This indicates that the name passed to @code{gij} should be interpreted
881 as the name of a jar file, not a class.
883 @item --help
884 @itemx -?
885 Print help, then exit.
887 @item --showversion
888 Print version number and continue.
890 @item --fullversion
891 Print detailed version information, then exit.
893 @item --version
894 Print version number, then exit.
896 @item -verbose
897 @itemx -verbose:class
898 Each time a class is initialized, print a short message on standard error.
899 @end table
901 @code{gij} also recognizes and ignores the following options, for
902 compatibility with existing application launch scripts:
903 @code{-client}, @code{-server}, @code{-hotspot}, @code{-jrockit},
904 @code{-agentlib}, @code{-agentpath}, @code{-debug}, @code{-d32},
905 @code{-d64}, @code{-javaagent}, @code{-noclassgc}, @code{-verify},
906 and @code{-verifyremote}.
908 @c man end
910 @node Invoking gcj-dbtool
911 @chapter Invoking gcj-dbtool.
913 @c man title gcj-dbtool Manipulate class file mapping databases for libgcj
915 @ignore
916 @c man begin SYNOPSIS gcj-dbtool
917 gcj-dbtool @option{OPTION} @var{DBFILE} [@option{MORE}] @dots{}
919 gcj-dbtool [@option{-0}] [@option{-}] [@option{-n}] [@option{-a}] [@option{-f}]
920   [@option{-t}] [@option{-l}] [@option{-p} [@var{LIBDIR}]]
921   [@option{-v}] [@option{-m}] [@option{--version}] [@option{--help}]
923 @c man end
924 @c man begin SEEALSO gij
925 gcc(1), gcj(1), gcjh(1), jcf-dump(1), gfdl(7),
926 and the Info entries for @file{gcj} and @file{gcc}.
927 @c man end
928 @end ignore
930 @c man begin DESCRIPTION gcj-dbtool
932 @code{gcj-dbtool} is a tool for creating and manipulating class file
933 mapping databases.  @code{libgcj} can use these databases to find a
934 shared library corresponding to the bytecode representation of a
935 class.  This functionality is useful for ahead-of-time compilation of
936 a program that has no knowledge of @code{gcj}.
938 @code{gcj-dbtool} works best if all the jar files added to it are
939 compiled using @code{-findirect-dispatch}.
941 Note that @code{gcj-dbtool} is currently available as ``preview
942 technology''.  We believe it is a reasonable way to allow
943 application-transparent ahead-of-time compilation, but this is an
944 unexplored area.  We welcome your comments.
946 @c man end
948 @c man begin OPTIONS gcj-dbtool
950 @table @gcctabopt
951 @item -n @var{DBFILE} [@var{SIZE}]
952 This creates a new database.  Currently, databases cannot be resized;
953 you can choose a larger initial size if desired.  The default size is
954 32,749.
956 @item -a @var{DBFILE} @var{JARFILE} @var{LIB}
957 @itemx -f @var{DBFILE} @var{JARFILE} @var{LIB}
958 This adds a jar file to the database.  For each class file in the jar,
959 a cryptographic signature of the bytecode representation of the class
960 is recorded in the database.  At runtime, a class is looked up by its
961 signature and the compiled form of the class is looked for in the
962 corresponding shared library.  The @option{-a} option will verify
963 that @var{LIB} exists before adding it to the database; @option{-f}
964 skips this check.
966 @item [@option{-}][@option{-0}] -m @var{DBFILE} @var{DBFILE},[@var{DBFILE}]
967 Merge a number of databases.  The output database overwrites any
968 existing database.  To add databases into an existing database,
969 include the destination in the list of sources.
971 If @option{-} or @option{-0} are used, the list of files to read is
972 taken from standard input instead of the command line.  For
973 @option{-0}, Input filenames are terminated by a null character
974 instead of by whitespace.  Useful when arguments might contain white
975 space.  The GNU find -print0 option produces input suitable for this
976 mode.
978 @item -t @var{DBFILE}
979 Test a database.
981 @item -l @var{DBFILE}
982 List the contents of a database.
984 @item -p
985 Print the name of the default database.  If there is no default
986 database, this prints a blank line.  If @var{LIBDIR} is specified, use
987 it instead of the default library directory component of the database
988 name.
990 @item --help
991 Print a help message, then exit.
993 @item --version
994 @itemx -v
995 Print version information, then exit.
997 @end table
999 @c man end
1001 @node Invoking jv-convert
1002 @chapter Invoking jv-convert
1004 @c man title jv-convert Convert file from one encoding to another
1006 @c man begin SYNOPSIS jv-convert
1007 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
1008 @ignore
1010   [@option{--encoding} @var{name}]
1011   [@option{--from} @var{name}]
1012   [@option{--to} @var{name}]
1013   [@option{-i} @var{file}] [@option{-o} @var{file}]
1014   [@option{--reverse}] [@option{--help}] [@option{--version}]
1015 @end ignore
1016 @c man end
1018 @c man begin DESCRIPTION jv-convert
1020 @command{jv-convert} is a utility included with @code{libgcj} which
1021 converts a file from one encoding to another.  It is similar to the Unix
1022 @command{iconv} utility.
1024 The encodings supported by @command{jv-convert} are platform-dependent.
1025 Currently there is no way to get a list of all supported encodings.
1027 @c man end
1029 @c man begin OPTIONS jv-convert
1031 @table @gcctabopt
1032 @item --encoding @var{name}
1033 @itemx --from @var{name}
1034 Use @var{name} as the input encoding.  The default is the current
1035 locale's encoding.
1037 @item --to @var{name}
1038 Use @var{name} as the output encoding.  The default is the
1039 @code{JavaSrc} encoding; this is ASCII with @samp{\u} escapes for
1040 non-ASCII characters.
1042 @item -i @var{file}
1043 Read from @var{file}.  The default is to read from standard input.
1045 @item -o @var{file}
1046 Write to @var{file}.  The default is to write to standard output.
1048 @item --reverse
1049 Swap the input and output encodings.
1051 @item --help
1052 Print a help message, then exit.
1054 @item --version
1055 Print version information, then exit.
1056 @end table
1058 @c man end
1060 @node Invoking grmic
1061 @chapter Invoking grmic
1063 @c man title grmic Generate stubs for Remote Method Invocation
1065 @c man begin SYNOPSIS grmic
1066 @command{grmic} [@option{OPTION}] @dots{} @var{class} @dots{}
1067 @ignore
1068   [@option{-keep}]
1069   [@option{-keepgenerated}]
1070   [@option{-v1.1}]
1071   [@option{-vcompat}]
1072   [@option{-v1.2}]
1073   [@option{-nocompile}]
1074   [@option{-verbose}]
1075   [@option{-d} @var{directory}]
1076   [@option{-help}]
1077   [@option{-version}]
1078 @end ignore
1079 @c man end
1081 @c man begin DESCRIPTION grmic
1083 @command{grmic} is a utility included with @code{libgcj} which generates
1084 stubs for remote objects.
1086 @c FIXME: Add real information here.
1087 @c This really isn't much more than the --help output.
1089 Note that this program isn't yet fully compatible with the JDK
1090 @command{grmic}.  Some options, such as @option{-classpath}, are
1091 recognized but currently ignored.  We have left these options
1092 undocumented for now.
1094 Long options can also be given with a GNU-style leading @samp{--}.  For
1095 instance, @option{--help} is accepted.
1097 @c man end
1099 @c man begin OPTIONS grmic
1101 @table @gcctabopt
1102 @item -keep
1103 @itemx -keepgenerated
1104 By default, @command{grmic} deletes intermediate files.  Either of these
1105 options causes it not to delete such files.
1107 @item -v1.1
1108 Cause @command{grmic} to create stubs and skeletons for the 1.1
1109 protocol version.
1111 @item -vcompat
1112 Cause @command{grmic} to create stubs and skeletons compatible with both
1113 the 1.1 and 1.2 protocol versions.  This is the default.
1115 @item -v1.2
1116 Cause @command{grmic} to create stubs and skeletons for the 1.2
1117 protocol version.
1119 @item -nocompile
1120 Don't compile the generated files.
1122 @item -verbose
1123 Print information about what @command{grmic} is doing.
1125 @item -d @var{directory}
1126 Put output files in @var{directory}.  By default the files are put in
1127 the current working directory.
1129 @item -help
1130 Print a help message, then exit.
1132 @item -version
1133 Print version information, then exit.
1134 @end table
1136 @c man end
1139 @node Invoking gc-analyze
1140 @chapter Invoking gc-analyze
1142 @c man title gc-analyze Analyze Garbage Collector (GC) memory dumps
1144 @c man begin SYNOPSIS gc-analyze
1145 @command{gc-analyze} [@option{OPTION}] @dots{} [@var{file}]
1146 @ignore
1147   [@option{-v}]
1148   [@option{--verbose}]
1149   [@option{-p} @var{tool-prefix}]
1150   [@option{-d} @var{directory}]
1151   [@option{--version}]
1152   [@option{--help}]
1153 @end ignore
1154 @c man end
1156 @c man begin DESCRIPTION gc-analyze
1158 @command{gc-analyze} prints an analysis of a GC memory dump to
1159 standard out.
1161 The memory dumps may be created by calling
1162 @code{gnu.gcj.util.GCInfo.enumerate(String namePrefix)} from java
1163 code.  A memory dump will be created on an out of memory condition if
1164 @code{gnu.gcj.util.GCInfo.setOOMDump(String namePrefix)} is called
1165 before the out of memory occurs.
1167 Running this program will create two files: @file{TestDump001} and
1168 @file{TestDump001.bytes}.
1170 @example
1171 import gnu.gcj.util.*;
1172 import java.util.*;
1174 public class GCDumpTest
1176     static public void main(String args[])
1177     @{
1178         ArrayList<String> l = new ArrayList<String>(1000);
1179         
1180         for (int i = 1; i < 1500; i++) @{
1181             l.add("This is string #" + i);
1182         @}
1183         GCInfo.enumerate("TestDump");
1184     @}
1186 @end example
1188 The memory dump may then be displayed by running:
1190 @example
1191 gc-analyze -v TestDump001
1192 @end example
1194 @c FIXME: Add real information here.
1195 @c This really isn't much more than the --help output.
1197 @c man end
1199 @c man begin OPTIONS gc-analyze
1201 @table @gcctabopt
1202 @item --verbose
1203 @itemx -v
1204 Verbose output.
1206 @item -p @var{tool-prefix}
1207 Prefix added to the names of the @command{nm} and @command{readelf} commands.
1209 @item -d @var{directory}
1210 Directory that contains the executable and shared libraries used when
1211 the dump was generated.
1213 @item --help
1214 Print a help message, then exit.
1216 @item --version
1217 Print version information, then exit.
1218 @end table
1220 @c man end
1222 @node About CNI
1223 @chapter About CNI
1225 This documents CNI, the Compiled Native Interface,
1226 which is is a convenient way to write Java native methods using C++.
1227 This is a more efficient, more convenient, but less portable
1228 alternative to the standard JNI (Java Native Interface).
1230 @menu
1231 * Basic concepts::              Introduction to using CNI@.
1232 * Packages::                    How packages are mapped to C++.
1233 * Primitive types::             Handling primitive Java types in C++.
1234 * Reference types::             Handling Java reference types in C++.
1235 * Interfaces::                  How Java interfaces map to C++.
1236 * Objects and Classes::         C++ and Java classes.
1237 * Class Initialization::        How objects are initialized.
1238 * Object allocation::           How to create Java objects in C++.
1239 * Memory allocation::           How to allocate and free memory.
1240 * Arrays::                      Dealing with Java arrays in C++.
1241 * Methods::                     Java methods in C++.
1242 * Strings::                     Information about Java Strings.
1243 * Mixing with C++::             How CNI can interoperate with C++.
1244 * Exception Handling::          How exceptions are handled.
1245 * Synchronization::             Synchronizing between Java and C++.
1246 * Invocation::                  Starting the Java runtime from C++.
1247 * Reflection::                  Using reflection from C++.
1248 @end menu
1251 @node Basic concepts
1252 @section Basic concepts
1254 In terms of languages features, Java is mostly a subset
1255 of C++.  Java has a few important extensions, plus a powerful standard
1256 class library, but on the whole that does not change the basic similarity.
1257 Java is a hybrid object-oriented language, with a few native types,
1258 in addition to class types.  It is class-based, where a class may have
1259 static as well as per-object fields, and static as well as instance methods.
1260 Non-static methods may be virtual, and may be overloaded.  Overloading is
1261 resolved at compile time by matching the actual argument types against
1262 the parameter types.  Virtual methods are implemented using indirect calls
1263 through a dispatch table (virtual function table).  Objects are
1264 allocated on the heap, and initialized using a constructor method.
1265 Classes are organized in a package hierarchy.
1267 All of the listed attributes are also true of C++, though C++ has
1268 extra features (for example in C++ objects may be allocated not just
1269 on the heap, but also statically or in a local stack frame).  Because
1270 @command{gcj} uses the same compiler technology as G++ (the GNU
1271 C++ compiler), it is possible to make the intersection of the two
1272 languages use the same ABI (object representation and calling
1273 conventions).  The key idea in CNI is that Java objects are C++
1274 objects, and all Java classes are C++ classes (but not the other way
1275 around).  So the most important task in integrating Java and C++ is to
1276 remove gratuitous incompatibilities.
1278 You write CNI code as a regular C++ source file.  (You do have to use
1279 a Java/CNI-aware C++ compiler, specifically a recent version of G++.)
1281 @noindent A CNI C++ source file must have:
1283 @example
1284 #include <gcj/cni.h>
1285 @end example
1287 @noindent and then must include one header file for each Java class it uses, e.g.:
1289 @example
1290 #include <java/lang/Character.h>
1291 #include <java/util/Date.h>
1292 #include <java/lang/IndexOutOfBoundsException.h>
1293 @end example
1295 @noindent These header files are automatically generated by @code{gcjh}.
1298 CNI provides some functions and macros to make using Java objects and
1299 primitive types from C++ easier.  In general, these CNI functions and
1300 macros start with the @code{Jv} prefix, for example the function
1301 @code{JvNewObjectArray}.  This convention is used to avoid conflicts
1302 with other libraries.  Internal functions in CNI start with the prefix
1303 @code{_Jv_}.  You should not call these; if you find a need to, let us
1304 know and we will try to come up with an alternate solution.
1307 @subsection Limitations
1309 Whilst a Java class is just a C++ class that doesn't mean that you are
1310 freed from the shackles of Java, a @acronym{CNI} C++ class must adhere to the
1311 rules of the Java programming language.
1313 For example: it is not possible to declare a method in a CNI class
1314 that will take a C string (@code{char*}) as an argument, or to declare a
1315 member variable of some non-Java datatype.
1318 @node Packages
1319 @section Packages
1321 The only global names in Java are class names, and packages.  A
1322 @dfn{package} can contain zero or more classes, and also zero or more
1323 sub-packages.  Every class belongs to either an unnamed package or a
1324 package that has a hierarchical and globally unique name.
1326 A Java package is mapped to a C++ @dfn{namespace}.  The Java class
1327 @code{java.lang.String} is in the package @code{java.lang}, which is a
1328 sub-package of @code{java}.  The C++ equivalent is the class
1329 @code{java::lang::String}, which is in the namespace @code{java::lang}
1330 which is in the namespace @code{java}.
1332 @noindent Here is how you could express this:
1334 @example
1335 (// @r{Declare the class(es), possibly in a header file:}
1336 namespace java @{
1337   namespace lang @{
1338     class Object;
1339     class String;
1340     ...
1341   @}
1344 class java::lang::String : public java::lang::Object
1346   ...
1348 @end example
1350 @noindent The @code{gcjh} tool automatically generates the necessary namespace
1351 declarations.
1354 @subsection Leaving out package names
1356 Always using the fully-qualified name of a java class can be
1357 tiresomely verbose.  Using the full qualified name also ties the code
1358 to a single package making code changes necessary should the class
1359 move from one package to another.  The Java @code{package} declaration
1360 specifies that the following class declarations are in the named
1361 package, without having to explicitly name the full package
1362 qualifiers.  The @code{package} declaration can be
1363 followed by zero or more @code{import} declarations, which
1364 allows either a single class or all the classes in a package to be
1365 named by a simple identifier.  C++ provides something similar with the
1366 @code{using} declaration and directive.
1368 @noindent In Java:
1370 @example
1371 import @var{package-name}.@var{class-name};
1372 @end example
1374 @noindent allows the program text to refer to @var{class-name} as a shorthand for 
1375 the fully qualified name: @code{@var{package-name}.@var{class-name}}.
1378 @noindent To achieve the same effect C++, you have to do this:
1380 @example
1381 using @var{package-name}::@var{class-name};
1382 @end example
1385 @noindent Java can also cause imports on demand, like this:
1387 @example
1388 import @var{package-name}.*;
1389 @end example
1391 @noindent Doing this allows any class from the package @var{package-name} to be
1392 referred to only by its class-name within the program text.
1395 @noindent The same effect can be achieved in C++ like this:
1397 @example
1398 using namespace @var{package-name};
1399 @end example
1402 @node Primitive types
1403 @section Primitive types
1405 Java provides 8 @dfn{primitives} types which represent integers, floats, 
1406 characters and booleans (and also the void type).  C++ has its own
1407 very similar concrete types.  Such types in C++ however are not always
1408 implemented in the same way (an int might be 16, 32 or 64 bits for example) 
1409 so CNI provides a special C++ type for each primitive Java type:
1411 @multitable @columnfractions .20 .25 .60
1412 @item @strong{Java type}   @tab @strong{C/C++ typename} @tab @strong{Description}
1413 @item @code{char}        @tab @code{jchar}          @tab 16 bit Unicode character
1414 @item @code{boolean}     @tab @code{jboolean}       @tab logical (true or false) values
1415 @item @code{byte}        @tab @code{jbyte}          @tab 8-bit signed integer
1416 @item @code{short}       @tab @code{jshort}         @tab 16 bit signed integer
1417 @item @code{int}         @tab @code{jint}           @tab 32 bit signed integer
1418 @item @code{long}        @tab @code{jlong}          @tab 64 bit signed integer
1419 @item @code{float}       @tab @code{jfloat}         @tab 32 bit IEEE floating point number
1420 @item @code{double}      @tab @code{jdouble}        @tab 64 bit IEEE floating point number
1421 @item @code{void}        @tab @code{void}           @tab no value
1422 @end multitable
1424 When referring to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1425 to avoid disappointment.
1428 @subsection Reference types associated with primitive types
1430 In Java each primitive type has an associated reference type, 
1431 e.g.: @code{boolean} has an associated @code{java.lang.Boolean.TYPE} class.
1432 In order to make working with such classes easier GCJ provides the macro
1433 @code{JvPrimClass}:
1435 @deffn macro JvPrimClass type
1436 Return a pointer to the @code{Class} object corresponding to the type supplied.
1438 @example
1439 JvPrimClass(void) @result{} java.lang.Void.TYPE
1440 @end example
1442 @end deffn
1445 @node Reference types
1446 @section Reference types
1448 A Java reference type is treated as a class in C++.  Classes and
1449 interfaces are handled this way.  A Java reference is translated to a
1450 C++ pointer, so for instance a Java @code{java.lang.String} becomes,
1451 in C++, @code{java::lang::String *}.
1453 CNI provides a few built-in typedefs for the most common classes:
1454 @multitable @columnfractions .30 .25 .60
1455 @item @strong{Java type} @tab @strong{C++ typename} @tab @strong{Description}
1456 @item @code{java.lang.Object} @tab @code{jobject} @tab Object type
1457 @item @code{java.lang.String} @tab @code{jstring} @tab String type
1458 @item @code{java.lang.Class} @tab @code{jclass} @tab Class type
1459 @end multitable
1460 @cindex jobject
1461 @cindex jstring
1462 @cindex jclass
1464 Every Java class or interface has a corresponding @code{Class}
1465 instance.  These can be accessed in CNI via the static @code{class$}
1466 field of a class.  The @code{class$} field is of type @code{Class}
1467 (and not @code{Class *}), so you will typically take the address of
1469 @cindex class$
1471 Here is how you can refer to the class of @code{String}, which in
1472 Java would be written @code{String.class}:
1474 @example
1475 using namespace java::lang;
1476 doSomething (&String::class$);
1477 @end example
1480 @node Interfaces
1481 @section Interfaces
1483 A Java class can @dfn{implement} zero or more
1484 @dfn{interfaces}, in addition to inheriting from
1485 a single base class. 
1487 @acronym{CNI} allows CNI code to implement methods of interfaces.
1488 You can also call methods through interface references, with some
1489 limitations.
1491 @acronym{CNI} doesn't understand interface inheritance at all yet.  So,
1492 you can only call an interface method when the declared type of the
1493 field being called matches the interface which declares that
1494 method.  The workaround is to cast the interface reference to the right
1495 superinterface.
1497 For example if you have: 
1499 @example 
1500 interface A 
1501 @{ 
1502   void a(); 
1503 @} 
1505 interface B extends A 
1506 @{ 
1507   void b(); 
1508 @} 
1509 @end example
1511 and declare a variable of type @code{B} in C++, you can't call
1512 @code{a()} unless you cast it to an @code{A} first.
1514 @node Objects and Classes
1515 @section Objects and Classes
1517 @subsection Classes
1519 All Java classes are derived from @code{java.lang.Object}.  C++ does
1520 not have a unique root class, but we use the C++ class
1521 @code{java::lang::Object} as the C++ version of the
1522 @code{java.lang.Object} Java class.  All other Java classes are mapped
1523 into corresponding C++ classes derived from @code{java::lang::Object}.
1525 Interface inheritance (the @code{implements} keyword) is currently not
1526 reflected in the C++ mapping.
1529 @subsection Object fields
1531 Each object contains an object header, followed by the instance fields
1532 of the class, in order.  The object header consists of a single
1533 pointer to a dispatch or virtual function table.  (There may be extra
1534 fields @emph{in front of} the object, for example for memory
1535 management, but this is invisible to the application, and the
1536 reference to the object points to the dispatch table pointer.)
1538 The fields are laid out in the same order, alignment, and size as in
1539 C++.  Specifically, 8-bit and 16-bit native types (@code{byte},
1540 @code{short}, @code{char}, and @code{boolean}) are @emph{not} widened
1541 to 32 bits.  Note that the Java VM does extend 8-bit and 16-bit types
1542 to 32 bits when on the VM stack or temporary registers.
1544 If you include the @code{gcjh}-generated header for a
1545 class, you can access fields of Java classes in the @emph{natural}
1546 way.  For example, given the following Java class:
1548 @example
1549 public class Int
1551   public int i;
1552   public Int (int i) @{ this.i = i; @}
1553   public static Int zero = new Int(0);
1555 @end example
1557 you can write:
1559 @example
1560 #include <gcj/cni.h>;
1561 #include <Int>;
1563 Int*
1564 mult (Int *p, jint k)
1566   if (k == 0)
1567     return Int::zero;  // @r{Static member access.}
1568   return new Int(p->i * k);
1570 @end example
1573 @subsection Access specifiers
1575 CNI does not strictly enforce the Java access
1576 specifiers, because Java permissions cannot be directly mapped
1577 into C++ permission.  Private Java fields and methods are mapped
1578 to private C++ fields and methods, but other fields and methods
1579 are mapped to public fields and methods.
1583 @node Class Initialization
1584 @section Class Initialization
1586 Java requires that each class be automatically initialized at the time 
1587 of the first active use.  Initializing a class involves 
1588 initializing the static fields, running code in class initializer 
1589 methods, and initializing base classes.  There may also be 
1590 some implementation specific actions, such as allocating 
1591 @code{String} objects corresponding to string literals in
1592 the code.
1594 The GCJ compiler inserts calls to @code{JvInitClass} at appropriate
1595 places to ensure that a class is initialized when required.  The C++
1596 compiler does not insert these calls automatically---it is the
1597 programmer's responsibility to make sure classes are initialized.
1598 However, this is fairly painless because of the conventions assumed by
1599 the Java system.
1601 First, @code{libgcj} will make sure a class is initialized before an
1602 instance of that object is created.  This is one of the
1603 responsibilities of the @code{new} operation.  This is taken care of
1604 both in Java code, and in C++ code.  When G++ sees a @code{new} of a
1605 Java class, it will call a routine in @code{libgcj} to allocate the
1606 object, and that routine will take care of initializing the class.
1607 Note however that this does not happen for Java arrays; you must
1608 allocate those using the appropriate CNI function.  It follows that
1609 you can access an instance field, or call an instance (non-static)
1610 method and be safe in the knowledge that the class and all of its base
1611 classes have been initialized.
1613 Invoking a static method is also safe.  This is because the
1614 Java compiler adds code to the start of a static method to make sure
1615 the class is initialized.  However, the C++ compiler does not
1616 add this extra code.  Hence, if you write a native static method
1617 using CNI, you are responsible for calling @code{JvInitClass}
1618 before doing anything else in the method (unless you are sure
1619 it is safe to leave it out).
1621 Accessing a static field also requires the class of the
1622 field to be initialized.  The Java compiler will generate code
1623 to call @code{JvInitClass} before getting or setting the field.
1624 However, the C++ compiler will not generate this extra code,
1625 so it is your responsibility to make sure the class is
1626 initialized before you access a static field from C++.
1629 @node Object allocation
1630 @section Object allocation
1632 New Java objects are allocated using a
1633 @dfn{class instance creation expression}, e.g.:
1635 @example
1636 new @var{Type} ( ... )
1637 @end example
1639 The same syntax is used in C++.  The main difference is that
1640 C++ objects have to be explicitly deleted; in Java they are
1641 automatically deleted by the garbage collector.
1642 Using @acronym{CNI}, you can allocate a new Java object
1643 using standard C++ syntax and the C++ compiler will allocate
1644 memory from the garbage collector.  If you have overloaded
1645 constructors, the compiler will choose the correct one
1646 using standard C++ overload resolution rules.  
1648 @noindent For example:
1650 @example
1651 java::util::Hashtable *ht = new java::util::Hashtable(120);
1652 @end example
1655 @node Memory allocation
1656 @section Memory allocation
1658 When allocating memory in @acronym{CNI} methods it is best to handle
1659 out-of-memory conditions by throwing a Java exception.  These
1660 functions are provided for that purpose:
1662 @deftypefun void* JvMalloc (jsize @var{size})
1663 Calls malloc.  Throws @code{java.lang.OutOfMemoryError} if allocation
1664 fails.
1665 @end deftypefun
1667 @deftypefun void* JvRealloc (void* @var{ptr}, jsize @var{size})
1668 Calls realloc.  Throws @code{java.lang.OutOfMemoryError} if
1669 reallocation fails.
1670 @end deftypefun
1672 @deftypefun void JvFree (void* @var{ptr})
1673 Calls free.
1674 @end deftypefun
1676 @node Arrays
1677 @section Arrays
1679 While in many ways Java is similar to C and C++, it is quite different
1680 in its treatment of arrays.  C arrays are based on the idea of pointer
1681 arithmetic, which would be incompatible with Java's security
1682 requirements.  Java arrays are true objects (array types inherit from
1683 @code{java.lang.Object}).  An array-valued variable is one that
1684 contains a reference (pointer) to an array object.
1686 Referencing a Java array in C++ code is done using the
1687 @code{JArray} template, which as defined as follows:
1689 @example
1690 class __JArray : public java::lang::Object
1692 public:
1693   int length;
1696 template<class T>
1697 class JArray : public __JArray
1699   T data[0];
1700 public:
1701   T& operator[](jint i) @{ return data[i]; @}
1703 @end example
1706 There are a number of @code{typedef}s which correspond to @code{typedef}s 
1707 from the @acronym{JNI}.  Each is the type of an array holding objects
1708 of the relevant type:
1710 @example
1711 typedef __JArray *jarray;
1712 typedef JArray<jobject> *jobjectArray;
1713 typedef JArray<jboolean> *jbooleanArray;
1714 typedef JArray<jbyte> *jbyteArray;
1715 typedef JArray<jchar> *jcharArray;
1716 typedef JArray<jshort> *jshortArray;
1717 typedef JArray<jint> *jintArray;
1718 typedef JArray<jlong> *jlongArray;
1719 typedef JArray<jfloat> *jfloatArray;
1720 typedef JArray<jdouble> *jdoubleArray;
1721 @end example
1724 @deftypemethod {template<class T>} T* elements (JArray<T> @var{array})
1725 This template function can be used to get a pointer to the elements of
1726 the @code{array}.  For instance, you can fetch a pointer to the
1727 integers that make up an @code{int[]} like so:
1729 @example
1730 extern jintArray foo;
1731 jint *intp = elements (foo);
1732 @end example
1734 The name of this function may change in the future.
1735 @end deftypemethod
1738 @deftypefun jobjectArray JvNewObjectArray (jsize @var{length}, jclass @var{klass}, jobject @var{init})
1739 This creates a new array whose elements have reference type.
1740 @code{klass} is the type of elements of the array and
1741 @code{init} is the initial value put into every slot in the array.
1742 @end deftypefun
1744 @example
1745 using namespace java::lang;
1746 JArray<String *> *array
1747   = (JArray<String *> *) JvNewObjectArray(length, &String::class$, NULL);
1748 @end example
1751 @subsection Creating arrays
1753 For each primitive type there is a function which can be used to
1754 create a new array of that type.  The name of the function is of the
1755 form:
1757 @example
1758 JvNew@var{Type}Array
1759 @end example
1761 @noindent For example:
1763 @example
1764 JvNewBooleanArray
1765 @end example
1767 @noindent can be used to create an array of Java primitive boolean types.
1769 @noindent The following function definition is the template for all such functions:
1771 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1772 Creates an array @var{length} indices long.
1773 @end deftypefun
1775 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1776 Returns the length of the @var{array}.
1777 @end deftypefun
1780 @node Methods
1781 @section Methods
1783 Java methods are mapped directly into C++ methods.
1784 The header files generated by @code{gcjh}
1785 include the appropriate method definitions.
1786 Basically, the generated methods have the same names and
1787 @emph{corresponding} types as the Java methods,
1788 and are called in the natural manner.
1790 @subsection Overloading
1792 Both Java and C++ provide method overloading, where multiple
1793 methods in a class have the same name, and the correct one is chosen
1794 (at compile time) depending on the argument types.
1795 The rules for choosing the correct method are (as expected) more complicated
1796 in C++ than in Java, but given a set of overloaded methods
1797 generated by @code{gcjh} the C++ compiler will choose
1798 the expected one.
1800 Common assemblers and linkers are not aware of C++ overloading,
1801 so the standard implementation strategy is to encode the
1802 parameter types of a method into its assembly-level name.
1803 This encoding is called @dfn{mangling},
1804 and the encoded name is the @dfn{mangled name}.
1805 The same mechanism is used to implement Java overloading.
1806 For C++/Java interoperability, it is important that both the Java
1807 and C++ compilers use the @emph{same} encoding scheme.
1809 @subsection Static methods
1811 Static Java methods are invoked in @acronym{CNI} using the standard
1812 C++ syntax, using the @code{::} operator rather
1813 than the @code{.} operator.  
1815 @noindent For example:
1817 @example
1818 jint i = java::lang::Math::round((jfloat) 2.3);
1819 @end example
1821 @noindent C++ method definition syntax is used to define a static native method.
1822 For example:
1824 @example
1825 #include <java/lang/Integer>
1826 java::lang::Integer*
1827 java::lang::Integer::getInteger(jstring str)
1829   ...
1831 @end example
1834 @subsection Object Constructors
1836 Constructors are called implicitly as part of object allocation
1837 using the @code{new} operator.  
1839 @noindent For example:
1841 @example
1842 java::lang::Integer *x = new java::lang::Integer(234);
1843 @end example
1845 Java does not allow a constructor to be a native method.
1846 This limitation can be coded round however because a constructor
1847 can @emph{call} a native method.
1850 @subsection Instance methods
1852 Calling a Java instance method from a C++ @acronym{CNI} method is done 
1853 using the standard C++ syntax, e.g.:
1855 @example
1856 // @r{First create the Java object.}
1857 java::lang::Integer *x = new java::lang::Integer(234);
1858 // @r{Now call a method.}
1859 jint prim_value = x->intValue();
1860 if (x->longValue == 0) 
1861   ...
1862 @end example
1864 @noindent Defining a Java native instance method is also done the natural way:
1866 @example
1867 #include <java/lang/Integer.h>
1869 jdouble
1870 java::lang:Integer::doubleValue()
1872   return (jdouble) value;
1874 @end example
1877 @subsection Interface methods
1879 In Java you can call a method using an interface reference.  This is
1880 supported, but not completely.  @xref{Interfaces}.
1885 @node Strings
1886 @section Strings
1888 @acronym{CNI} provides a number of utility functions for
1889 working with Java Java @code{String} objects.
1890 The names and interfaces are analogous to those of @acronym{JNI}.
1893 @deftypefun jstring JvNewString (const jchar* @var{chars}, jsize @var{len})
1894 Returns a Java @code{String} object with characters from the array of 
1895 Unicode characters @var{chars} up to the index @var{len} in that array.
1896 @end deftypefun
1898 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes}, jsize @var{len})
1899 Returns a Java @code{String} made up of @var{len} bytes from @var{bytes}.
1900 @end deftypefun
1903 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1904 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
1905 @end deftypefun
1907 @deftypefun jstring JvNewStringUTF (const char* @var{bytes})
1908 Returns a @code{String} which is made up of the UTF encoded characters
1909 present in the C string @var{bytes}.
1910 @end deftypefun
1912 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1913 Returns a pointer to an array of characters making up the @code{String} @var{str}.
1914 @end deftypefun
1916 @deftypefun int JvGetStringUTFLength (jstring @var{str})
1917 Returns the number of bytes required to encode the contents of the
1918 @code{String} @var{str} in UTF-8.
1919 @end deftypefun
1921 @deftypefun jsize JvGetStringUTFRegion (jstring @var{str}, jsize @var{start}, jsize @var{len}, char* @var{buf})
1922 Puts the UTF-8 encoding of a region of the @code{String} @var{str} into 
1923 the buffer @code{buf}.  The region to fetch is marked by @var{start} and @var{len}.
1925 Note that @var{buf} is a buffer, not a C string.  It is @emph{not} 
1926 null terminated.
1927 @end deftypefun
1930 @node Mixing with C++
1931 @section Interoperating with C/C++
1933 Because @acronym{CNI} is designed to represent Java classes and methods it
1934 cannot be mixed readily with C/C++ types.
1936 One important restriction is that Java classes cannot have non-Java
1937 type instance or static variables and cannot have methods which take
1938 non-Java types as arguments or return non-Java types.
1940 @noindent None of the following is possible with CNI:
1942 @example
1944 class ::MyClass : public java::lang::Object
1946    char* variable;  // @r{char* is not a valid Java type.}
1950 uint
1951 ::SomeClass::someMethod (char *arg)
1953   .
1954   .
1955   .
1956 @}   // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1957 @end example
1959 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1962 @example
1963 jint
1964 ::SomeClass::otherMethod (jstring str)
1966    char *arg = ...
1967    .
1968    .
1969    .
1971 @end example
1973 @subsection RawData
1975 The above restriction can be problematic, so @acronym{CNI} includes the
1976 @code{gnu.gcj.RawData} class.  The @code{RawData} class is a
1977 @dfn{non-scanned reference} type.  In other words variables declared
1978 of type @code{RawData} can contain any data and are not checked by the
1979 compiler or memory manager in any way.
1981 This means that you can put C/C++ data structures (including classes)
1982 in your @acronym{CNI} classes, as long as you use the appropriate cast.
1984 @noindent Here are some examples:
1986 @example
1988 class ::MyClass : public java::lang::Object
1990    gnu.gcj.RawData string;
1992    MyClass ();
1993    gnu.gcj.RawData getText ();
1994    void printText ();
1997 ::MyClass::MyClass ()
1999    char* text = ...
2000    string = text;
2003 gnu.gcj.RawData
2004 ::MyClass::getText ()
2006    return string;
2009 void
2010 ::MyClass::printText ()
2012   printf("%s\n", (char*) string);
2014 @end example
2017 @subsection RawDataManaged
2019 @code{gnu.gcj.RawDataManaged} is another type used to indicate special data used 
2020 by native code. Unlike the @code{RawData} type, fields declared as 
2021 @code{RawDataManaged} will be "marked" by the memory manager and 
2022 considered for garbage collection.  
2024 Native data which is allocated using CNI's @code{JvAllocBytes()}
2025 function and stored in a @code{RawDataManaged} will be automatically 
2026 freed when the Java object it is associated with becomes unreachable.
2028 @subsection Native memory allocation
2030 @deftypefun void* JvAllocBytes (jsize @var{size})
2031 Allocates @var{size} bytes from the heap.  The memory returned is zeroed.
2032 This memory is not scanned for pointers by the garbage collector, but will 
2033 be freed if no references to it are discovered.
2035 This function can be useful if you need to associate some native data with a
2036 Java object. Using a CNI's special @code{RawDataManaged} type, native data 
2037 allocated with @code{JvAllocBytes} will be automatically freed when the Java 
2038 object itself becomes unreachable.
2039 @end deftypefun
2041 @subsection Posix signals
2043 On Posix based systems the @code{libgcj} library uses several signals
2044 internally.  @acronym{CNI} code should not attempt to use the same
2045 signals as doing so may cause @code{libgcj} and/or the @acronym{CNI}
2046 code to fail.
2048 SIGSEGV is used on many systems to generate
2049 @code{NullPointerExceptions}.  SIGCHLD is used internally by
2050 @code{Runtime.exec()}.  Several other signals (that vary from platform to
2051 platform) can be used by the memory manager and by
2052 @code{Thread.interrupt()}.
2054 @node Exception Handling
2055 @section Exception Handling
2057 While C++ and Java share a common exception handling framework,
2058 things are not yet perfectly integrated.  The main issue is that the
2059 run-time type information facilities of the two
2060 languages are not integrated.
2062 Still, things work fairly well.  You can throw a Java exception from
2063 C++ using the ordinary @code{throw} construct, and this
2064 exception can be caught by Java code.  Similarly, you can catch an
2065 exception thrown from Java using the C++ @code{catch}
2066 construct.
2068 @noindent Here is an example:
2070 @example
2071 if (i >= count)
2072    throw new java::lang::IndexOutOfBoundsException();
2073 @end example
2075 Normally, G++ will automatically detect when you are writing C++
2076 code that uses Java exceptions, and handle them appropriately.
2077 However, if C++ code only needs to execute destructors when Java
2078 exceptions are thrown through it, GCC will guess incorrectly.  Sample
2079 problematic code:
2081 @example
2082 struct S @{ ~S(); @};
2084 extern void bar();    // @r{Is implemented in Java and may throw exceptions.}
2086 void foo()
2088   S s;
2089   bar();
2091 @end example
2093 The usual effect of an incorrect guess is a link failure, complaining of
2094 a missing routine called @code{__gxx_personality_v0}.
2096 You can inform the compiler that Java exceptions are to be used in a
2097 translation unit, irrespective of what it might think, by writing
2098 @code{#pragma GCC java_exceptions} at the head of the
2099 file.  This @code{#pragma} must appear before any
2100 functions that throw or catch exceptions, or run destructors when
2101 exceptions are thrown through them.
2103 @node Synchronization
2104 @section Synchronization
2106 Each Java object has an implicit monitor.
2107 The Java VM uses the instruction @code{monitorenter} to acquire
2108 and lock a monitor, and @code{monitorexit} to release it.
2110 The corresponding CNI macros are @code{JvMonitorEnter} and 
2111 @code{JvMonitorExit} (JNI has similar  methods @code{MonitorEnter}
2112 and @code{MonitorExit}).  
2115 The Java source language does not provide direct access to these primitives.
2116 Instead, there is a @code{synchronized} statement that does an
2117 implicit @code{monitorenter} before entry to the block,
2118 and does a @code{monitorexit} on exit from the block.
2119 Note that the lock has to be released even when the block is abnormally
2120 terminated by an exception, which means there is an implicit
2121 @code{try finally} surrounding synchronization locks.
2123 From C++, it makes sense to use a destructor to release a lock.
2124 @acronym{CNI} defines the following utility class:
2126 @example
2127 class JvSynchronize() @{
2128   jobject obj;
2129   JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
2130   ~JvSynchronize() @{ JvMonitorExit(obj); @}
2132 @end example
2134 So this Java code:
2136 @example
2137 synchronized (OBJ)
2139    CODE
2141 @end example
2143 @noindent might become this C++ code:
2145 @example
2147    JvSynchronize dummy (OBJ);
2148    CODE;
2150 @end example
2152 Java also has methods with the @code{synchronized} attribute.
2153 This is equivalent to wrapping the entire method body in a
2154 @code{synchronized} statement.
2155 (Alternatively, an implementation could require the caller to do
2156 the synchronization.  This is not practical for a compiler, because
2157 each virtual method call would have to test at run-time if
2158 synchronization is needed.)  Since in @command{gcj}
2159 the @code{synchronized} attribute is handled by the
2160 method implementation, it is up to the programmer
2161 of a synchronized native method to handle the synchronization
2162 (in the C++ implementation of the method).
2163 In other words, you need to manually add @code{JvSynchronize}
2164 in a @code{native synchronized} method.
2166 @node Invocation
2167 @section Invocation
2169 CNI permits C++ applications to make calls into Java classes, in addition to
2170 allowing Java code to call into C++. Several functions, known as the 
2171 @dfn{invocation API}, are provided to support this.
2173 @deftypefun jint JvCreateJavaVM (JvVMInitArgs* @var{vm_args})
2175 Initializes the Java runtime. This function performs essential initialization
2176 of the threads interface, garbage collector, exception handling and other key
2177 aspects of the runtime. It must be called once by an application with
2178 a non-Java @code{main()} function, before any other Java or CNI calls are made.
2179 It is safe, but not recommended, to call @code{JvCreateJavaVM()} more than
2180 once provided it is only called from a single thread.
2181 The @var{vmargs} parameter can be used to specify initialization parameters 
2182 for the Java runtime. It may be @code{NULL}.
2184 JvVMInitArgs represents a list of virtual machine initialization
2185 arguments. @code{JvCreateJavaVM()} ignores the version field.
2187 @example
2188 typedef struct JvVMOption
2190   // a VM initialization option
2191   char* optionString;
2192   // extra information associated with this option
2193   void* extraInfo;
2194 @} JvVMOption;
2196 typedef struct JvVMInitArgs
2198   // for compatibility with JavaVMInitArgs
2199   jint version;
2201   // number of VM initialization options
2202   jint nOptions;
2204   // an array of VM initialization options
2205   JvVMOption* options;
2207   // true if the option parser should ignore unrecognized options
2208   jboolean ignoreUnrecognized;
2209 @} JvVMInitArgs;
2210 @end example
2212 @code{JvCreateJavaVM()} returns @code{0} upon success, or @code{-1} if
2213 the runtime is already initialized.
2215 @emph{Note:} In GCJ 3.1, the @code{vm_args} parameter is ignored. It
2216 is recognized and used as of release 4.0.
2217 @end deftypefun
2219 @deftypefun java::lang::Thread* JvAttachCurrentThread (jstring @var{name}, java::lang::ThreadGroup* @var{group})
2220 Registers an existing thread with the Java runtime.  This must be called once
2221 from each thread, before that thread makes any other Java or CNI calls. It
2222 must be called after @code{JvCreateJavaVM}.
2223 @var{name} specifies a name for the thread. It may be @code{NULL}, in which 
2224 case a name will be generated.
2225 @var{group} is the ThreadGroup in which this thread will be a member. If it
2226 is @code{NULL}, the thread will be a member of the main thread group.
2227 The return value is the Java @code{Thread} object that represents the thread.
2228 It is safe to call @code{JvAttachCurrentThread()} more than once from the same
2229 thread. If the thread is already attached, the call is ignored and the current
2230 thread object is returned.
2231 @end deftypefun
2233 @deftypefun jint JvDetachCurrentThread ()
2234 Unregisters a thread from the Java runtime. This should be called by threads
2235 that were attached using @code{JvAttachCurrentThread()}, after they have 
2236 finished making calls to Java code. This ensures that any resources associated
2237 with the thread become eligible for garbage collection.
2238 This function returns @code{0} upon success, or @code{-1} if the current thread
2239 is not attached.
2240 @end deftypefun
2242 @subsection Handling uncaught exceptions
2244 If an exception is thrown from Java code called using the invocation API, and
2245 no handler for the exception can be found, the runtime will abort the
2246 application. In order to make the application more robust, it is recommended 
2247 that code which uses the invocation API be wrapped by a top-level try/catch 
2248 block that catches all Java exceptions.
2250 @subsection Example
2252 The following code demonstrates the use of the invocation API. In this
2253 example, the C++ application initializes the Java runtime and attaches
2254 itself. The @code{java.lang.System} class is initialized in order to
2255 access its @code{out} field, and a Java string is printed. Finally, the thread
2256 is detached from the runtime once it has finished making Java calls. Everything
2257 is wrapped with a try/catch block to provide a default handler for any uncaught 
2258 exceptions.
2260 The example can be compiled with @command{c++ -c test.cc; gcj test.o}.
2262 @example
2263 // test.cc
2264 #include <gcj/cni.h>
2265 #include <java/lang/System.h>
2266 #include <java/io/PrintStream.h>
2267 #include <java/lang/Throwable.h>
2269 int main(int argc, char *argv[])
2271   using namespace java::lang;
2272   
2273   try
2274   @{
2275     JvCreateJavaVM(NULL);
2276     JvAttachCurrentThread(NULL, NULL);
2278     String *message = JvNewStringLatin1("Hello from C++");
2279     JvInitClass(&System::class$);
2280     System::out->println(message);
2282     JvDetachCurrentThread();
2283   @}
2284   catch (Throwable *t)
2285   @{
2286     System::err->println(JvNewStringLatin1("Unhandled Java exception:"));
2287     t->printStackTrace();
2288   @}
2290 @end example
2292 @node Reflection
2293 @section Reflection
2295 Reflection is possible with CNI code, it functions similarly to how it
2296 functions with JNI@.
2298 @c clean this up...  I mean, what are the types jfieldID and jmethodID in JNI?
2299 The types @code{jfieldID} and @code{jmethodID}
2300 are as in JNI@.
2302 @noindent The functions:
2304 @itemize
2305 @item @code{JvFromReflectedField},
2306 @item @code{JvFromReflectedMethod},
2307 @item @code{JvToReflectedField}
2308 @item @code{JvToFromReflectedMethod}
2309 @end itemize
2311 @noindent will be added shortly, as will other functions corresponding to JNI@.
2314 @node System properties
2315 @chapter System properties
2317 The runtime behavior of the @code{libgcj} library can be modified by setting
2318 certain system properties.  These properties can be compiled into the program
2319 using the @code{-D@var{name}[=@var{value}]} option to @command{gcj} or by
2320 setting them explicitly in the program by calling the
2321 @code{java.lang.System.setProperty()} method.  Some system properties are only
2322 used for informational purposes (like giving a version number or a user name).
2323 A program can inspect the current value of a property by calling the
2324 @code{java.lang.System.getProperty()} method.
2326 @menu
2327 * Standard Properties::         Standard properties supported by @code{libgcj}
2328 * GNU Classpath Properties::    Properties found in Classpath based libraries
2329 * libgcj Runtime Properties::   Properties specific to @code{libgcj}
2330 @end menu
2332 @node Standard Properties
2333 @section Standard Properties
2335 The following properties are normally found in all implementations of the core
2336 libraries for the Java language.
2338 @table @gcctabopt
2340 @item java.version
2341 The @code{libgcj} version number.
2343 @item java.vendor
2344 Set to @samp{The Free Software Foundation, Inc.}
2346 @item java.vendor.url
2347 Set to @uref{http://gcc.gnu.org/java/}.
2349 @item java.home
2350 The directory where @code{gcj} was installed.  Taken from the @code{--prefix}
2351 option given to @command{configure}.
2353 @item java.class.version
2354 The class format version number supported by the libgcj byte code interpreter.
2355 (Currently @samp{46.0})
2357 @item java.vm.specification.version
2358 The Virtual Machine Specification version implemented by @code{libgcj}.
2359 (Currently @samp{1.0})
2361 @item java.vm.specification.vendor
2362 The name of the Virtual Machine specification designer.
2364 @item java.vm.specification.name
2365 The name of the Virtual Machine specification
2366 (Set to @samp{Java Virtual Machine Specification}).
2368 @item java.vm.version
2369 The @command{gcj} version number.
2371 @item java.vm.vendor
2372 Set to @samp{The Free Software Foundation, Inc.}
2374 @item java.vm.name
2375 Set to @samp{GNU libgcj}.
2377 @item java.specification.version
2378 The Runtime Environment specification version implemented by @code{libgcj}.
2379 (Currently set to @samp{1.3})
2381 @item java.specification.vendor
2382 The Runtime Environment specification designer.
2384 @item java.specification.name
2385 The name of the Runtime Environment specification
2386 (Set to @samp{Java Platform API Specification}).
2388 @item java.class.path
2389 The paths (jar files, zip files and directories) used for finding class files.
2391 @item java.library.path
2392 Directory path used for finding native libraries.
2394 @item java.io.tmpdir
2395 The directory used to put temporary files in.
2397 @item java.compiler
2398 Name of the Just In Time compiler to use by the byte code interpreter.
2399 Currently not used in @code{libgcj}.
2401 @item java.ext.dirs
2402 Directories containing jar files with extra libraries.  Will be used when
2403 resolving classes.
2405 @item java.protocol.handler.pkgs
2406 A @samp{|} separated list of package names that is used to find classes that
2407 implement handlers for @code{java.net.URL}.
2409 @item java.rmi.server.codebase
2410 A list of URLs that is used by the @code{java.rmi.server.RMIClassLoader}
2411 to load classes from.
2413 @item jdbc.drivers
2414 A list of class names that will be loaded by the @code{java.sql.DriverManager}
2415 when it starts up.
2417 @item file.separator
2418 The separator used in when directories are included in a filename
2419 (normally @samp{/} or @samp{\} ).
2421 @item file.encoding
2422 The default character encoding used when converting platform native files to
2423 Unicode (usually set to @samp{8859_1}).
2425 @item path.separator
2426 The standard separator used when a string contains multiple paths
2427 (normally @samp{:} or @samp{;}), the string is usually not a valid character
2428 to use in normal directory names.)
2430 @item line.separator
2431 The default line separator used on the platform (normally @samp{\n}, @samp{\r}
2432 or a combination of those two characters).
2434 @item policy.provider
2435 The class name used for the default policy provider returned by
2436 @code{java.security.Policy.getPolicy}.
2438 @item user.name
2439 The name of the user running the program.  Can be the full name, the login name
2440 or empty if unknown.
2442 @item user.home
2443 The default directory to put user specific files in.
2445 @item user.dir
2446 The current working directory from which the program was started.
2448 @item user.language
2449 The default language as used by the @code{java.util.Locale} class.
2451 @item user.region
2452 The default region as used by the @code{java.util.Local} class.
2454 @item user.variant
2455 The default variant of the language and region local used.
2457 @item user.timezone
2458 The default timezone as used by the @code{java.util.TimeZone} class.
2460 @item os.name
2461 The operating system/kernel name that the program runs on.
2463 @item os.arch
2464 The hardware that we are running on.
2466 @item os.version
2467 The version number of the operating system/kernel.
2469 @item awt.appletWarning
2470 The string to display when an untrusted applet is displayed.
2471 Returned by @code{java.awt.Window.getWarningString()} when the window is
2472 ``insecure''.
2474 @item awt.toolkit
2475 The class name used for initializing the default @code{java.awt.Toolkit}. 
2476 Defaults to @code{gnu.awt.gtk.GtkToolkit}.
2478 @item http.proxyHost
2479 Name of proxy host for http connections.
2481 @item http.proxyPort
2482 Port number to use when a proxy host is in use.
2484 @end table
2486 @node GNU Classpath Properties
2487 @section GNU Classpath Properties
2489 @code{libgcj} is based on the GNU Classpath (Essential Libraries for Java) a
2490 GNU project to create free core class libraries for use with virtual machines
2491 and compilers for the Java language.  The following properties are common to
2492 libraries based on GNU Classpath.
2494 @table @gcctabopt
2496 @item gcj.dumpobject
2497 Enables printing serialization debugging by the @code{java.io.ObjectInput} and
2498 @code{java.io.ObjectOutput} classes when set to something else then the empty
2499 string.  Only used when running a debug build of the library.
2501 @item gnu.classpath.vm.shortname
2502 This is a succinct name of the virtual machine.  For @code{libgcj},
2503 this will always be @samp{libgcj}.
2505 @item gnu.classpath.home.url
2506 A base URL used for finding system property files (e.g.,
2507 @file{classpath.security}).  By default this is a @samp{file:} URL
2508 pointing to the @file{lib} directory under @samp{java.home}.
2510 @end table
2512 @node libgcj Runtime Properties
2513 @section libgcj Runtime Properties
2515 The following properties are specific to the @code{libgcj} runtime and will
2516 normally not be found in other core libraries for the java language.
2518 @table @gcctabopt
2520 @item java.fullversion
2521 The combination of @code{java.vm.name} and @code{java.vm.version}.
2523 @item java.vm.info
2524 Same as @code{java.fullversion}.
2526 @item impl.prefix
2527 Used by the @code{java.net.DatagramSocket} class when set to something else
2528 then the empty string.  When set all newly created @code{DatagramSocket}s will
2529 try to load a class @code{java.net.[impl.prefix]DatagramSocketImpl} instead of
2530 the normal @code{java.net.PlainDatagramSocketImpl}.
2532 @item gnu.gcj.progname
2533 The class or binary name that was used to invoke the program. This will be
2534 the name of the "main" class in the case where the @code{gij} front end is
2535 used, or the program binary name in the case where an application is compiled 
2536 to a native binary.
2538 @item gnu.gcj.user.realname
2539 The real name of the user, as taken from the password file.  This may
2540 not always hold only the user's name (as some sites put extra
2541 information in this field).  Also, this property is not available on
2542 all platforms.
2544 @item gnu.gcj.runtime.NameFinder.use_addr2line
2545 Whether an external process, @command{addr2line}, should be used to determine
2546 line number information when tracing the stack. Setting this to @code{false} 
2547 may suppress line numbers when printing stack traces and when using
2548 the java.util.logging infrastructure. However, performance may improve
2549 significantly for applications that print stack traces or make logging calls
2550 frequently.
2552 @item gnu.gcj.runtime.NameFinder.show_raw
2553 Whether the address of a stack frame should be printed when the line
2554 number is unavailable. Setting this to @code{true} will cause the name
2555 of the object and the offset within that object to be printed when no
2556 line number is available.  This allows for off-line decoding of
2557 stack traces if necessary debug information is available.  The default
2558 is @code{false}, no raw addresses are printed.
2560 @item gnu.gcj.runtime.NameFinder.remove_unknown
2561 Whether stack frames for non-java code should be included in a stack
2562 trace.  The default value is @code{true}, stack frames for non-java
2563 code are suppressed.  Setting this to @code{false} will cause any
2564 non-java stack frames to be printed in addition to frames for the java
2565 code.
2567 @item gnu.gcj.runtime.VMClassLoader.library_control
2568 This controls how shared libraries are automatically loaded by the
2569 built-in class loader.  If this property is set to @samp{full}, a full
2570 search is done for each requested class.  If this property is set to
2571 @samp{cache}, then any failed lookups are cached and not tried again.
2572 If this property is set to @samp{never} (the default), then lookups
2573 are never done.  For more information, @xref{Extensions}.
2575 @item gnu.gcj.runtime.endorsed.dirs
2576 This is like the standard @code{java.endorsed.dirs}, property, but
2577 specifies some extra directories which are searched after the standard
2578 endorsed directories.  This is primarily useful for telling
2579 @code{libgcj} about additional libraries which are ordinarily
2580 incorporated into the JDK, and which should be loaded by the bootstrap
2581 class loader, but which are not yet part of @code{libgcj} itself for
2582 some reason.
2584 @item gnu.gcj.jit.compiler
2585 @c FIXME we should probably have a whole node on this...
2586 This is the full path to @command{gcj} executable which should be
2587 used to compile classes just-in-time when
2588 @code{ClassLoader.defineClass} is called.  If not set, @command{gcj}
2589 will not be invoked by the runtime; this can also be controlled via
2590 @code{Compiler.disable}.
2592 @item gnu.gcj.jit.options
2593 This is a space-separated string of options which should be passed to
2594 @command{gcj} when in JIT mode.  If not set, a sensible default is
2595 chosen.
2597 @item gnu.gcj.jit.cachedir
2598 This is the directory where cached shared library files are
2599 stored.  If not set, JIT compilation is disabled.  This should never
2600 be set to a directory that is writable by any other user.
2602 @item gnu.gcj.precompiled.db.path
2603 This is a sequence of file names, each referring to a file created by
2604 @command{gcj-dbtool}.  These files will be used by @code{libgcj} to
2605 find shared libraries corresponding to classes that are loaded from
2606 bytecode.  @code{libgcj} often has a built-in default database; it
2607 can be queried using @code{gcj-dbtool -p}.
2609 @end table
2612 @node Resources
2613 @chapter Resources
2615 While writing @command{gcj} and @code{libgcj} we have, of course, relied
2616 heavily on documentation from Sun Microsystems.  In particular we have
2617 used The Java Language Specification (both first and second editions),
2618 the Java Class Libraries (volumes one and two), and the Java Virtual
2619 Machine Specification.  In addition we've used the online documentation
2620 at @uref{http://java.sun.com/}.
2622 The current @command{gcj} home page is
2623 @uref{http://gcc.gnu.org/java/}.
2625 For more information on gcc, see @uref{http://gcc.gnu.org/}.
2627 Some @code{libgcj} testing is done using the Mauve test suite.  This is
2628 a free software Java class library test suite which is being written
2629 because the JCK is not free.  See
2630 @uref{http://sources.redhat.com/mauve/} for more information.
2633 @node Index
2634 @unnumbered Index
2636 @printindex cp
2638 @bye