OSDN Git Service

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