OSDN Git Service

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