OSDN Git Service

* gcj.texi: @code{gcj} becomes @command{gcj}.
[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 @c Note: When reading this manual you'll find lots of strange
6 @c circumlocutions like ``compiler for the Java language''.
7 @c This is necessary due to Sun's restrictions on the use of
8 @c the word ``Java'.
9
10 @c When this manual is copyrighted.
11 @set copyrights-gcj 2001, 2002
12
13 @c Versions
14 @set version-gcc 3.1
15 @set which-gcj GCC-@value{version-gcc}
16
17 @macro gcctabopt{body}
18 @code{\body\}
19 @end macro
20
21 @ifinfo
22 @format
23 @dircategory Programming
24 @direntry
25 * Gcj: (gcj).               Ahead-of-time compiler for the Java language
26 @end direntry
27
28 @dircategory Individual utilities
29 @direntry
30 * gcjh: (gcj)Invoking gcjh.
31                             Generate header files from Java class files
32 * jv-scan: (gcj)Invoking jv-scan.
33                             Print information about Java source files
34 * jcf-dump: (gcj)Invoking jcf-dump.
35                             Print information about Java class files
36 * gij: (gcj)Invoking gij.   GNU interpreter for Java bytecode
37 * jv-convert: (gcj)Invoking jv-convert.
38                             Convert file from one encoding to another
39 @end direntry
40 @end format
41
42 @c man begin COPYRIGHT
43 Copyright (C) @value{copyrights-gcj} Free Software Foundation, Inc.
44
45 Permission is granted to copy, distribute and/or modify this document
46 under the terms of the GNU Free Documentation License, Version 1.1 or
47 any later version published by the Free Software Foundation; with the
48 Invariant Sections being ``GNU General Public License'', the Front-Cover
49 texts being (a) (see below), and with the Back-Cover Texts being (b)
50 (see below).  A copy of the license is included in the
51 @c man end
52 section entitled
53 ``GNU Free Documentation License''.
54 @ignore
55 @c man begin COPYRIGHT
56 man page gfdl(7).
57 @c man end
58 @end ignore
59
60 (a) The FSF's Front-Cover Text is:
61
62      A GNU Manual
63
64 (b) The FSF's Back-Cover Text is:
65
66      You have freedom to copy and modify this GNU Manual, like GNU
67      software.  Copies published by the Free Software Foundation raise
68      funds for GNU development.
69 @end ifinfo
70
71 @titlepage
72 @title GNU gcj
73 @author Tom Tromey
74
75 @page
76 @vskip 0pt plus 1filll
77 Copyright @copyright{} @value{copyrights-gcj} Free Software Foundation, Inc.
78 @sp 2
79 For the @value{which-gcj} Version*
80 @sp 1
81 Published by the Free Software Foundation @*
82 59 Temple Place - Suite 330@*
83 Boston, MA 02111-1307, USA@*
84 @sp 1
85 Permission is granted to copy, distribute and/or modify this document
86 under the terms of the GNU Free Documentation License, Version 1.1 or
87 any later version published by the Free Software Foundation; with the
88 Invariant Sections being ``GNU General Public License'', the Front-Cover
89 texts being (a) (see below), and with the Back-Cover Texts being (b)
90 (see below).  A copy of the license is included in the section entitled
91 ``GNU Free Documentation License''.
92
93 (a) The FSF's Front-Cover Text is:
94
95      A GNU Manual
96
97 (b) The FSF's Back-Cover Text is:
98
99      You have freedom to copy and modify this GNU Manual, like GNU
100      software.  Copies published by the Free Software Foundation raise
101      funds for GNU development.
102 @end titlepage
103 @contents
104 @page
105
106
107 @node Top
108 @top Introduction
109
110 This manual describes how to use @command{gcj}, the GNU compiler for the
111 Java programming language.  @command{gcj} can generate both @file{.class}
112 files and object files, and it can read both Java source code and
113 @file{.class} files.
114
115 @menu
116 * Copying::             The GNU General Public License
117 * GNU Free Documentation License::
118                         How you can share and copy this manual
119 * Invoking gcj::        Compiler options supported by @command{gcj}
120 * Compatibility::       Compatibility between gcj and other tools for Java
121 * Invoking gcjh::       Generate header files from class files
122 * Invoking jv-scan::    Print information about source files
123 * Invoking jcf-dump::   Print information about class files
124 * Invoking gij::        Interpreting Java bytecodes
125 * Invoking jv-convert:: Converting from one encoding to another
126 * About CNI::           Description of the Cygnus Native Interface
127 * Resources::           Where to look for more information
128 @end menu
129
130
131 @include gpl.texi
132
133 @include fdl.texi
134
135
136 @node Invoking gcj
137 @chapter Invoking gcj
138
139 @c man title gcj Ahead-of-time compiler for the Java language
140
141 @ignore
142 @c man begin SYNOPSIS gcj
143 gcj [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
144     [@option{--CLASSPATH}=@var{path}] [@option{--classpath}=@var{path}]
145     [@option{-f}@var{option}@dots{}] [@option{--encoding}=@var{name}]
146     [@option{--main}=@var{classname}] [@option{-D}@var{name}[=@var{value}]@dots{}]
147     [@option{-C}] [@option{-R} @var{resource-name}] [@option{-d} @var{directory}]
148     [@option{-W}@var{warn}@dots{}]
149     @var{sourcefile}@dots{}
150 @c man end
151 @c man begin SEEALSO gcj
152 gcc(1), gcjh(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
153 and the Info entries for @file{gcj} and @file{gcc}.
154 @c man end
155 @end ignore
156
157 @c man begin DESCRIPTION gcj
158
159 As @command{gcj} is just another front end to @command{gcc}, it supports many
160 of the same options as gcc.  @xref{Option Summary, , Option Summary,
161 gcc, Using the GNU Compiler Collection (GCC)}.  This manual only documents the
162 options specific to @command{gcj}.
163
164 @c man end
165
166 @menu
167 * Input and output files::
168 * Input Options::               How gcj finds files
169 * Encodings::                   Options controlling source file encoding
170 * Warnings::                    Options controlling warnings specific to gcj
171 * Code Generation::             Options controlling the output of gcj
172 * Configure-time Options::      Options you won't use
173 @end menu
174
175 @c man begin OPTIONS gcj
176
177 @node Input and output files
178 @section Input and output files
179
180 A @command{gcj} command is like a @command{gcc} command, in that it
181 consists of a number of options and file names.  The following kinds
182 of input file names are supported:
183
184 @table @gcctabopt
185 @item @var{file}.java
186 Java source files.
187 @item @var{file}.class
188 Java bytecode files.
189 @item @var{file}.zip
190 @itemx @var{file}.jar
191 An archive containing one or more @code{.class} files, all of
192 which are compiled.  The archive may be compressed.
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{-R}.
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 imported, 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 CLASSPATH
255 This is an environment variable which holds a list of paths.
256 @end table
257
258 The final class path is constructed like so:
259
260 @itemize @bullet
261 @item
262 First come all directories specified via @code{-I}.
263
264 @item
265 If @option{--classpath} is specified, its value is appended.
266 Otherwise, if the @code{CLASSPATH} environment variable is specified,
267 then its value is appended.
268 Otherwise, the current directory (@code{"."}) is appended.
269
270 @item
271 Finally, if @code{--bootclasspath} was specified, append its value.
272 Otherwise, append the built-in system directory, @file{libgcj.jar}.
273 @end itemize
274
275 The classfile built by @command{gcj} for the class @code{java.lang.Object}
276 (and placed in @code{libgcj.jar}) contains a special zero length
277 attribute @code{gnu.gcj.gcj-compiled}. The compiler looks for this
278 attribute when loading @code{java.lang.Object} and will report an error
279 if it isn't found, unless it compiles to bytecode (the option
280 @code{-fforce-classes-archive-check} can be used to override this
281 behavior in this particular case.)
282
283 @table @gcctabopt
284 @item -fforce-classes-archive-check
285 This forces the compiler to always check for the special zero length
286 attribute @code{gnu.gcj.gcj-compiled} in @code{java.lang.Object} and
287 issue an error if it isn't found.
288 @end table
289
290 @node Encodings
291 @section Encodings
292
293 The Java programming language uses Unicode throughout.  In an effort to
294 integrate well with other locales, @command{gcj} allows @file{.java} files
295 to be written using almost any encoding.  @command{gcj} knows how to
296 convert these encodings into its internal encoding at compile time.
297
298 You can use the @code{--encoding=@var{NAME}} option to specify an
299 encoding (of a particular character set) to use for source files.  If
300 this is not specified, the default encoding comes from your current
301 locale.  If your host system has insufficient locale support, then
302 @command{gcj} assumes the default encoding to be the @samp{UTF-8} encoding
303 of Unicode.
304
305 To implement @code{--encoding}, @command{gcj} simply uses the host
306 platform's @code{iconv} conversion routine.  This means that in practice
307 @command{gcj} is limited by the capabilities of the host platform.
308
309 The names allowed for the argument @code{--encoding} vary from platform
310 to platform (since they are not standardized anywhere).  However,
311 @command{gcj} implements the encoding named @samp{UTF-8} internally, so if
312 you choose to use this for your source files you can be assured that it
313 will work on every host.
314
315
316 @node Warnings
317 @section Warnings
318
319 @command{gcj} implements several warnings.  As with other generic
320 @command{gcc} warnings, if an option of the form @code{-Wfoo} enables a
321 warning, then @code{-Wno-foo} will disable it.  Here we've chosen to
322 document the form of the warning which will have an effect -- the
323 default being the opposite of what is listed.
324
325 @table @gcctabopt
326 @item -Wredundant-modifiers
327 With this flag, @command{gcj} will warn about redundant modifiers.  For
328 instance, it will warn if an interface method is declared @code{public}.
329
330 @item -Wextraneous-semicolon
331 This causes @command{gcj} to warn about empty statements.  Empty statements
332 have been deprecated.
333
334 @item -Wno-out-of-date
335 This option will cause @command{gcj} not to warn when a source file is
336 newer than its matching class file.  By default @command{gcj} will warn
337 about this.
338
339 @item -Wunused
340 This is the same as @command{gcc}'s @code{-Wunused}.
341
342 @item -Wall
343 This is the same as @code{-Wredundant-modifiers -Wextraneous-semicolon
344 -Wunused}.
345 @end table
346
347
348 @node Code Generation
349 @section Code Generation
350
351 In addition to the many @command{gcc} options controlling code generation,
352 @command{gcj} has several options specific to itself.
353
354 @table @gcctabopt
355 @item --main=@var{CLASSNAME}
356 This option is used when linking to specify the name of the class whose
357 @code{main} method should be invoked when the resulting executable is
358 run.  @footnote{The linker by default looks for a global function named
359 @code{main}.  Since Java does not have global functions, and a
360 collection of Java classes may have more than one class with a
361 @code{main} method, you need to let the linker know which of those
362 @code{main} methods it should invoke when starting the application.}
363
364 @item -D@var{name}[=@var{value}]
365 This option can only be used with @code{--main}.  It defines a system
366 property named @var{name} with value @var{value}.  If @var{value} is not
367 specified then it defaults to the empty string.  These system properties
368 are initialized at the program's startup and can be retrieved at runtime
369 using the @code{java.lang.System.getProperty} method.
370
371 @item -C
372 This option is used to tell @command{gcj} to generate bytecode
373 (@file{.class} files) rather than object code.
374
375 @item -R @var{resource-name}
376 This option is used to tell @command{gcj} to compile the contents of a
377 given file to object code so it may be accessed at runtime with the core
378 protocol handler as @var{core:/resource-name}.
379
380 @item -d @var{directory}
381 When used with @code{-C}, this causes all generated @file{.class} files
382 to be put in the appropriate subdirectory of @var{directory}.  By
383 default they will be put in subdirectories of the current working
384 directory.
385
386 @item -fno-bounds-check
387 By default, @command{gcj} generates code which checks the bounds of all
388 array indexing operations.  With this option, these checks are omitted, which
389 can improve performance for code that uses arrays extensively.  Note that this 
390 can result in unpredictable behavior if the code in question actually does 
391 violate array bounds constraints.  It is safe to use this option if you are 
392 sure that your code will never throw an @code{ArrayIndexOutOfBoundsException}.
393
394 @item -fno-store-check
395 Don't generate array store checks.  When storing objects into arrays, a runtime
396 check is normally generated in order to ensure that the object is assignment
397 compatible with the component type of the array (which may not be known
398 at compile-time).  With this option, these checks are omitted.  This can 
399 improve performance for code which stores objects into arrays frequently.
400 It is safe to use this option if you are sure your code will never throw an 
401 @code{ArrayStoreException}.
402
403 @item -fjni
404 With @command{gcj} there are two options for writing native methods: CNI
405 and JNI@.  By default @command{gcj} assumes you are using CNI@.  If you are
406 compiling a class with native methods, and these methods are implemented
407 using JNI, then you must use @code{-fjni}.  This option causes
408 @command{gcj} to generate stubs which will invoke the underlying JNI
409 methods.
410
411 @item -fno-optimize-static-class-initialization
412 When the optimization level is greather or equal to @code{-O2},
413 @command{gcj} will try to optimize the way calls into the runtime are made
414 to initialize static classes upon their first use (this optimization
415 isn't carried out if @code{-C} was specified.) When compiling to native
416 code, @code{-fno-optimize-static-class-initialization} will turn this
417 optimization off, regardless of the optimization level in use.
418 @end table
419
420
421 @node Configure-time Options
422 @section Configure-time Options
423
424 Some @command{gcj} code generations options affect the resulting ABI, and
425 so can only be meaningfully given when @code{libgcj}, the runtime
426 package, is configured.  @code{libgcj} puts the appropriate options from
427 this group into a @samp{spec} file which is read by @command{gcj}.  These
428 options are listed here for completeness; if you are using @code{libgcj}
429 then you won't want to touch these options.
430
431 @table @gcctabopt
432 @item -fuse-boehm-gc
433 This enables the use of the Boehm GC bitmap marking code.  In particular
434 this causes @command{gcj} to put an object marking descriptor into each
435 vtable.
436
437 @item -fhash-synchronization
438 By default, synchronization data (the data used for @code{synchronize},
439 @code{wait}, and @code{notify}) is pointed to by a word in each object.
440 With this option @command{gcj} assumes that this information is stored in a
441 hash table and not in the object itself.
442
443 @item -fuse-divide-subroutine
444 On some systems, a library routine is called to perform integer
445 division.  This is required to get exception handling correct when
446 dividing by zero.
447
448 @item -fcheck-references
449 On some systems it's necessary to insert inline checks whenever
450 accessing an object via a reference.  On other systems you won't need
451 this because null pointer accesses are caught automatically by the
452 processor.
453 @end table
454
455 @c man end
456
457 @node Compatibility
458 @chapter Compatibility with the Java Platform
459
460 As we believe it is important that the Java platform not be fragmented,
461 @command{gcj} and @code{libgcj} try to conform to the relevant Java
462 specifications.  However, limited manpower and incomplete and unclear
463 documentation work against us.  So, there are caveats to using
464 @command{gcj}.
465
466 This list of compatibility issues is by no means complete.
467
468 @itemize @bullet
469 @item
470 @command{gcj} implements the JDK 1.1 language.  It supports inner classes,
471 though these are known to still be buggy.  It does not yet support the
472 Java 2 @code{strictfp} keyword (it recognizes the keyword but ignores
473 it).
474
475 @item
476 @code{libgcj} is largely compatible with the JDK 1.2 libraries.
477 However, @code{libgcj} is missing many packages, most notably
478 @code{java.awt}.  There are also individual missing classes and methods.
479 We currently do not have a list showing differences between
480 @code{libgcj} and the Java 2 platform.
481
482 @item
483 Sometimes the @code{libgcj} implementation of a method or class differs
484 from the JDK implementation.  This is not always a bug.  Still, if it
485 affects you, it probably makes sense to report it so that we can discuss
486 the appropriate response.
487 @end itemize
488
489
490 @node Invoking gcjh
491 @chapter Invoking gcjh
492
493 @c man title gcjh generate header files from Java class files
494
495 @c man begin DESCRIPTION gcjh
496
497 The @code{gcjh} program is used to generate header files from class
498 files.  It can generate both CNI and JNI header files, as well as stub
499 implementation files which can be used as a basis for implementing the
500 required native methods.
501
502 @c man end
503
504 @ignore
505 @c man begin SYNOPSIS gcjh
506 gcjh [@option{-stubs}] [@option{-jni}]
507     [@option{-add} @var{text}] [@option{-append} @var{text}] [@option{-friend} @var{text}]
508     [@option{-preprend} @var{text}]
509     [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
510     [@option{-I}@var{dir}@dots{}] [@option{-d} @var{dir}@dots{}]
511     [@option{-o} @var{file}] [@option{-td} @var{dir}]
512     [@option{-M}] [@option{-MM}] [@option{-MD}] [@option{-MMD}]
513     [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
514     @var{classname}@dots{}
515 @c man end
516 @c man begin SEEALSO gcjh
517 gcc(1), gcj(1), gij(1), jv-scan(1), jcf-dump(1), gfdl(7),
518 and the Info entries for @file{gcj} and @file{gcc}.
519 @c man end
520 @end ignore
521
522 @c man begin OPTIONS gcjh
523
524 @table @gcctabopt
525 @item -stubs
526 This causes @code{gcjh} to generate stub files instead of header files.
527 By default the stub file will be named after the class, with a suffix of
528 @samp{.cc}.  In JNI mode, the default output file will have the suffix
529 @samp{.c}.
530
531 @item -jni
532 This tells @code{gcjh} to generate a JNI header or stub.  By default,
533 CNI headers are generated.
534
535 @item -add @var{text}
536 Inserts @var{text} into the class body.  This is ignored in JNI mode.
537
538 @item -append @var{text}
539 Inserts @var{text} into the header file after the class declaration.
540 This is ignored in JNI mode.
541
542 @item -friend @var{text}
543 Inserts @var{text} into the class as a @code{friend} declaration.
544 This is ignored in JNI mode.
545
546 @item -prepend @var{text}
547 Inserts @var{text} into the header file before the class declaration.
548 This is ignored in JNI mode.
549
550 @item --classpath=@var{path}
551 @itemx --CLASSPATH=@var{path}
552 @itemx -I@var{directory}
553 @itemx -d @var{directory}
554 @itemx -o @var{file}
555 These options are all identical to the corresponding @command{gcj} options.
556
557 @item -o @var{file}
558 Sets the output file name.  This cannot be used if there is more than
559 one class on the command line.
560
561 @item -td @var{directory}
562 Sets the name of the directory to use for temporary files.
563
564 @item -M
565 Print all dependencies to stdout; suppress ordinary output.
566
567 @item -MM
568 Print non-system dependencies to stdout; suppress ordinary output.
569
570 @item -MD
571 Print all dependencies to stdout.
572
573 @item -MMD
574 Print non-system dependencies to stdout.
575
576 @item --help
577 Print help about @code{gcjh} and exit.  No further processing is done.
578
579 @item --version
580 Print version information for @code{gcjh} and exit.  No further
581 processing is done.
582
583 @item -v, --verbose
584 Print extra information while running.
585 @end table
586
587 All remaining options are considered to be names of classes.
588
589 @c man end
590
591 @node Invoking jv-scan
592 @chapter Invoking jv-scan
593
594 @c man title jv-scan print information about Java source file
595
596 @c man begin DESCRIPTION jv-scan
597
598 The @code{jv-scan} program can be used to print information about a Java
599 source file (@file{.java} file).
600
601 @c man end
602
603 @ignore
604 @c man begin SYNOPSIS jv-scan
605 jv-scan [@option{--complexity}] [@option{--encoding}=@var{name}]
606     [@option{--print-main}] [@option{--list-class}] [@option{--list-filename}]
607     [@option{--version}] [@option{--help}]
608     [@option{-o} @var{file}] @var{inputfile}@dots{}
609 @c man end
610 @c man begin SEEALSO jv-scan
611 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
612 and the Info entries for @file{gcj} and @file{gcc}.
613 @c man end
614 @end ignore
615
616 @c man begin OPTIONS jv-scan
617
618 @table @gcctabopt
619 @item --complexity
620 This prints a complexity measure, related to cyclomatic complexity, for
621 each input file.
622
623 @item --encoding=@var{name}
624 This works like the corresponding @command{gcj} option.
625
626 @item --print-main
627 This prints the name of the class in this file containing a @code{main}
628 method.
629
630 @item --list-class
631 This lists the names of all classes defined in the input files.
632
633 @item --list-filename
634 If @code{--list-class} is given, this option causes @code{jv-scan} to
635 also print the name of the file in which each class was found.
636
637 @item -o @var{file}
638 Print output to the named file.
639
640 @item --help
641 Print help, then exit.
642
643 @item --version
644 Print version number, then exit.
645 @end table
646
647 @c man end
648
649 @node Invoking jcf-dump
650 @chapter Invoking jcf-dump
651
652 @c man title jcf-dump print information about Java class files
653
654 @ignore
655 @c man begin SYNOPSIS jcf-dump
656 jcf-dump [@option{-c}] [@option{--javap}]
657     [@option{--classpath}=@var{path}] [@option{--CLASSPATH}=@var{path}]
658     [@option{-I}@var{dir}@dots{}] [@option{-o} @var{file}]
659     [@option{--version}] [@option{--help}] [@option{-v}] [@option{--verbose}]
660     @var{classname}@dots{}
661 @c man end
662 @c man begin SEEALSO jcf-dump
663 gcc(1), gcj(1), gcjh(1), gij(1), jcf-dump(1), gfdl(7),
664 and the Info entries for @file{gcj} and @file{gcc}.
665 @c man end
666 @end ignore
667
668 @c man begin DESCRIPTION jcf-dump
669
670 This is a class file examiner, similar to @code{javap}.  It will print
671 information about a number of classes, which are specifed by class name
672 or file name.
673
674 @c man end
675
676 @c man begin OPTIONS jcf-dump
677
678 @table @gcctabopt
679 @item -c
680 Disassemble method bodies.  By default method bodies are not printed.
681
682 @item --javap
683 Generate output in @code{javap} format.  The implementation of this
684 feature is very incomplete.
685
686 @item --classpath=@var{path}
687 @itemx --CLASSPATH=@var{path}
688 @itemx -I@var{directory}
689 @itemx -o @var{file}
690 These options as the same as the corresponding @command{gcj} options.
691
692 @item --help
693 Print help, then exit.
694
695 @item --version
696 Print version number, then exit.
697
698 @item -v, --verbose
699 Print extra information while running.
700 @end table
701
702 @c man end
703
704 @node Invoking gij
705 @chapter Invoking gij
706
707 @c man title gij GNU interpreter for Java bytecode
708
709 @ignore
710 @c man begin SYNOPSIS gij
711 gij [@option{OPTION}] @dots{} @var{JARFILE} [@var{ARGS}@dots{}]
712
713 gij [@option{-jar}] [@option{OPTION}] @dots{} @var{CLASS} [@var{ARGS}@dots{}]
714   [@option{-D}@var{name}[=@var{value}]@dots{}]
715   [@option{-ms=}@var{number}] [@option{-mx=}@var{number}]
716   [@option{--version}] [@option{--help}]
717 @c man end
718 @c man begin SEEALSO gij
719 gcc(1), gcj(1), gcjh(1), jv-scan(1), jcf-dump(1), gfdl(7),
720 and the Info entries for @file{gcj} and @file{gcc}.
721 @c man end
722 @end ignore
723
724 @c man begin DESCRIPTION gij
725
726 @code{gij} is a Java bytecode interpreter included with @code{libgcj}.
727 @code{gij} is not available on every platform; porting it requires a
728 small amount of assembly programming which has not been done for all the
729 targets supported by @command{gcj}.
730
731 The primary argument to @code{gij} is the name of a class or, with
732 @code{-jar}, a jar file.  Options before this argument are interpreted
733 by @code{gij}; remaining options are passed to the interpreted program.
734
735 If a class name is specified and this class does not have a @code{main}
736 method with the appropriate signature (a @code{static void} method with
737 a @code{String[]} as its sole argument), then @code{gij} will print an
738 error and exit.
739
740 If a jar file is specified then @code{gij} will use information in it to
741 determine which class' @code{main} method will be invoked.
742
743 @code{gij} will invoke the @code{main} method with all the remaining
744 command-line options.
745
746 Note that @code{gij} is not limited to interpreting code.  Because
747 @code{libgcj} includes a class loader which can dynamically load shared
748 objects, it is possible to give @code{gij} the name of a class which has
749 been compiled and put into a shared library on the class path.
750
751 @c man end
752
753 @c man begin OPTIONS gij
754
755 @table @gcctabopt
756 @item -D@var{name}[=@var{value}]
757 This defines a system property named @var{name} with value @var{value}.
758 If @var{value} is not specified then it defaults to the empty string.
759 These system properties are initialized at the program's startup and can
760 be retrieved at runtime using the @code{java.lang.System.getProperty}
761 method.
762
763 @item -ms=@var{number}
764 This sets the initial heap size.
765
766 @item -mx=@var{number}
767 This sets the maximum heap size.
768
769 @item -jar
770 This indicates that the name passed to @code{gij} should be interpreted
771 as the name of a jar file, not a class.
772
773 @item --help
774 Print help, then exit.
775
776 @item --version
777 Print version number, then exit.
778 @end table
779
780 @c man end
781
782 @node Invoking jv-convert
783 @chapter Invoking jv-convert
784
785 @c man title jv-convert Convert file from one encoding to another
786
787 @c man begin synopsis jv-convert
788 @command{jv-convert} [@option{OPTION}] @dots{} [@var{INPUTFILE} [@var{OUTPUTFILE}]]
789 @ignore
790
791   [@option{--encoding} @var{name}]
792   [@option{--from} @var{name}]
793   [@option{--to} @var{name}]
794   [@option{-i} @var{file}] [@option{-o} @var{file}]
795   [@option{--reverse}] [@option{--help}] [@option{--version}]
796 @end ignore
797 @c man end
798
799 @c man begin DESCRIPTION jv-convert
800
801 @command{jv-convert} is a utility included with @code{libgcj} which
802 converts a file from one encoding to another.  It is similar to the Unix
803 @command{iconv} utility.
804
805 The encodings supported by @command{jv-convert} are platform-dependent.
806 Currently there is no way to get a list of all supported encodings.
807
808 @c man end
809
810 @c man begin OPTIONS jv-convert
811
812 @table @gcctabopt
813 @item --encoding @var{name}
814 @itemx --from @var{name}
815 Use @var{name} as the input encoding.  The default is the current
816 locale's encoding.
817
818 @item --to @var{name}
819 Use @var{name} as the output encoding.  The default is the
820 @code{JavaSrc} encoding; this is ASCII with @samp{\u} escapes for
821 non-ASCII characters.
822
823 @item -i @var{file}
824 Read from @var{file}.  The default is to read from standard input.
825
826 @item -o @var{file}
827 Write to @var{file}.  The default is to write to standard output.
828
829 @item --reverse
830 Swap the input and output encodings.
831
832 @item --help
833 Print a help message, then exit.
834
835 @item --version
836 Print version information, then exit.
837 @end table
838
839 @c man end
840
841 @node About CNI
842 @chapter About CNI
843
844 This documents CNI, the Cygnus Native Interface,
845 which is is a convenient way to write Java native methods using C++.
846 This is a more efficient, more convenient, but less portable
847 alternative to the standard JNI (Java Native Interface).
848
849 @menu
850 * Basic concepts::              Introduction to using CNI@.
851 * Packages::                    How packages are mapped to C++.
852 * Primitive types::             Handling Java types in C++.
853 * Interfaces::                  How Java interfaces map to C++.
854 * Objects and Classes::         C++ and Java classes.
855 * Class Initialization::        How objects are initialized.
856 * Object allocation::           How to create Java objects in C++.
857 * Arrays::                      Dealing with Java arrays in C++.
858 * Methods::                     Java methods in C++.
859 * Strings::                     Information about Java Strings.
860 * Mixing with C++::             How CNI can interoperate with C++.
861 * Exception Handling::          How exceptions are handled.
862 * Synchronization::             Synchronizing between Java and C++.
863 * Reflection::                  Using reflection from C++.
864 @end menu
865
866
867 @node Basic concepts
868 @section Basic concepts
869
870 In terms of languages features, Java is mostly a subset
871 of C++.  Java has a few important extensions, plus a powerful standard
872 class library, but on the whole that does not change the basic similarity.
873 Java is a hybrid object-oriented language, with a few native types,
874 in addition to class types.  It is class-based, where a class may have
875 static as well as per-object fields, and static as well as instance methods.
876 Non-static methods may be virtual, and may be overloaded.  Overloading is
877 resolved at compile time by matching the actual argument types against
878 the parameter types.  Virtual methods are implemented using indirect calls
879 through a dispatch table (virtual function table).  Objects are
880 allocated on the heap, and initialized using a constructor method.
881 Classes are organized in a package hierarchy.
882
883 All of the listed attributes are also true of C++, though C++ has
884 extra features (for example in C++ objects may be allocated not just
885 on the heap, but also statically or in a local stack frame).  Because
886 @command{gcj} uses the same compiler technology as G++ (the GNU
887 C++ compiler), it is possible to make the intersection of the two
888 languages use the same ABI (object representation and calling
889 conventions).  The key idea in CNI is that Java objects are C++
890 objects, and all Java classes are C++ classes (but not the other way
891 around).  So the most important task in integrating Java and C++ is to
892 remove gratuitous incompatibilities.
893
894 You write CNI code as a regular C++ source file.  (You do have to use
895 a Java/CNI-aware C++ compiler, specifically a recent version of G++.)
896
897 @noindent A CNI C++ source file must have:
898
899 @example
900 #include <gcj/cni.h>
901 @end example
902
903 @noindent and then must include one header file for each Java class it uses, e.g.:
904
905 @example
906 #include <java/lang/Character.h>
907 #include <java/util/Date.h>
908 #include <java/lang/IndexOutOfBoundsException.h>
909 @end example
910
911 @noindent These header files are automatically generated by @code{gcjh}.
912
913
914 CNI provides some functions and macros to make using Java objects and
915 primitive types from C++ easier.  In general, these CNI functions and
916 macros start with the @code{Jv} prefix, for example the function
917 @code{JvNewObjectArray}.  This convention is used to avoid conflicts
918 with other libraries.  Internal functions in CNI start with the prefix
919 @code{_Jv_}.  You should not call these; if you find a need to, let us
920 know and we will try to come up with an alternate solution.  (This
921 manual lists @code{_Jv_AllocBytes} as an example; CNI should instead
922 provide a @code{JvAllocBytes} function.)
923
924
925 @subsection Limitations
926
927 Whilst a Java class is just a C++ class that doesn't mean that you are
928 freed from the shackles of Java, a @acronym{CNI} C++ class must adhere to the
929 rules of the Java programming language.
930
931 For example: it is not possible to declare a method in a CNI class
932 that will take a C string (@code{char*}) as an argument, or to declare a
933 member variable of some non-Java datatype.
934
935
936 @node Packages
937 @section Packages
938
939 The only global names in Java are class names, and packages.  A
940 @dfn{package} can contain zero or more classes, and also zero or more
941 sub-packages.  Every class belongs to either an unnamed package or a
942 package that has a hierarchical and globally unique name.
943
944 A Java package is mapped to a C++ @dfn{namespace}.  The Java class
945 @code{java.lang.String} is in the package @code{java.lang}, which is a
946 sub-package of @code{java}.  The C++ equivalent is the class
947 @code{java::lang::String}, which is in the namespace @code{java::lang}
948 which is in the namespace @code{java}.
949
950 @noindent Here is how you could express this:
951
952 @example
953 (// @r{Declare the class(es), possibly in a header file:}
954 namespace java @{
955   namespace lang @{
956     class Object;
957     class String;
958     ...
959   @}
960 @}
961
962 class java::lang::String : public java::lang::Object
963 @{
964   ...
965 @};
966 @end example
967
968 @noindent The @code{gcjh} tool automatically generates the nessary namespace
969 declarations.
970
971
972 @subsection Leaving out package names
973
974 Always using the fully-qualified name of a java class can be
975 tiresomely verbose.  Using the full qualified name also ties the code
976 to a single package making code changes necessary should the class
977 move from one package to another.  The Java @code{package} declaration
978 specifies that the following class declarations are in the named
979 package, without having to explicitly name the full package
980 qualifiers.  The @code{package} declaration can be
981 followed by zero or more @code{import} declarations, which
982 allows either a single class or all the classes in a package to be
983 named by a simple identifier.  C++ provides something similar with the
984 @code{using} declaration and directive.
985
986 @noindent In Java:
987
988 @example
989 import @var{package-name}.@var{class-name};
990 @end example
991
992 @noindent allows the program text to refer to @var{class-name} as a shorthand for 
993 the fully qualified name: @code{@var{package-name}.@var{class-name}}.
994
995
996 @noindent To achieve the same effect C++, you have to do this:
997
998 @example
999 using @var{package-name}::@var{class-name};
1000 @end example
1001
1002
1003 @noindent Java can also cause imports on demand, like this:
1004
1005 @example
1006 import @var{package-name}.*;
1007 @end example
1008
1009 @noindent Doing this allows any class from the package @var{package-name} to be
1010 refered to only by its class-name within the program text.
1011
1012
1013 @noindent The same effect can be achieved in C++ like this:
1014
1015 @example
1016 using namespace @var{package-name};
1017 @end example
1018
1019
1020 @node Primitive types
1021 @section Primitive types
1022
1023 Java provides 8 @dfn{primitives} types which represent integers, floats, 
1024 characters and booleans (and also the void type).  C++ has its own
1025 very similar concrete types.  Such types in C++ however are not always
1026 implemented in the same way (an int might be 16, 32 or 64 bits for example) 
1027 so CNI provides a special C++ type for each primitive Java type:
1028
1029 @multitable @columnfractions .20 .25 .60
1030 @item @strong{Java type}   @tab @strong{C/C++ typename} @tab @strong{Description}
1031 @item @code{char}        @tab @code{jchar}          @tab 16 bit Unicode character
1032 @item @code{boolean}     @tab @code{jboolean}       @tab logical (true or false) values
1033 @item @code{byte}        @tab @code{jbyte}          @tab 8-bit signed integer
1034 @item @code{short}       @tab @code{jshort}         @tab 16 bit signed integer
1035 @item @code{int}         @tab @code{jint}           @tab 32 bit signed integer
1036 @item @code{long}        @tab @code{jlong}          @tab 64 bit signed integer
1037 @item @code{float}       @tab @code{jfloat}         @tab 32 bit IEEE floating point number
1038 @item @code{double}      @tab @code{jdouble}        @tab 64 bit IEEE floating point number
1039 @item @code{void}        @tab @code{void}           @tab no value
1040 @end multitable
1041
1042 When refering to a Java type You should always use these C++ typenames (e.g.: @code{jint})
1043 to avoid disappointment.
1044
1045
1046 @subsection Reference types associated with primitive types
1047
1048 In Java each primitive type has an associated reference type, 
1049 e.g.: @code{boolean} has an associated @code{java.lang.Boolean} class.
1050 In order to make working with such classes easier GCJ provides the macro
1051 @code{JvPrimClass}:
1052
1053 @deffn macro JvPrimClass type
1054 Return a pointer to the @code{Class} object corresponding to the type supplied.
1055
1056 @example
1057 JvPrimClass(void) @result{} java.lang.Void.TYPE
1058 @end example
1059
1060 @end deffn
1061
1062
1063 @node Interfaces
1064 @section Interfaces
1065
1066 A Java class can @dfn{implement} zero or more
1067 @dfn{interfaces}, in addition to inheriting from
1068 a single base class. 
1069
1070 @acronym{CNI} allows CNI code to implement methods of interfaces.
1071 You can also call methods through interface references, with some
1072 limitations.
1073
1074 @acronym{CNI} doesn't understand interface inheritance at all yet.  So,
1075 you can only call an interface method when the declared type of the
1076 field being called matches the interface which declares that
1077 method.  The workaround is to cast the interface reference to the right
1078 superinterface.
1079  
1080 For example if you have: 
1081
1082 @example 
1083 interface A 
1084 @{ 
1085   void a(); 
1086 @} 
1087  
1088 interface B extends A 
1089 @{ 
1090   void b(); 
1091 @} 
1092 @end example
1093  
1094 and declare a variable of type @code{B} in C++, you can't call
1095 @code{a()} unless you cast it to an @code{A} first.
1096
1097 @node Objects and Classes
1098 @section Objects and Classes
1099
1100 @subsection Classes
1101
1102 All Java classes are derived from @code{java.lang.Object}.  C++ does
1103 not have a unique root class, but we use the C++ class
1104 @code{java::lang::Object} as the C++ version of the
1105 @code{java.lang.Object} Java class.  All other Java classes are mapped
1106 into corresponding C++ classes derived from @code{java::lang::Object}.
1107
1108 Interface inheritance (the @code{implements} keyword) is currently not
1109 reflected in the C++ mapping.
1110
1111
1112 @subsection Object fields
1113
1114 Each object contains an object header, followed by the instance fields
1115 of the class, in order.  The object header consists of a single
1116 pointer to a dispatch or virtual function table.  (There may be extra
1117 fields @emph{in front of} the object, for example for memory
1118 management, but this is invisible to the application, and the
1119 reference to the object points to the dispatch table pointer.)
1120
1121 The fields are laid out in the same order, alignment, and size as in
1122 C++.  Specifically, 8-bite and 16-bit native types (@code{byte},
1123 @code{short}, @code{char}, and @code{boolean}) are @emph{not} widened
1124 to 32 bits.  Note that the Java VM does extend 8-bit and 16-bit types
1125 to 32 bits when on the VM stack or temporary registers.
1126
1127 If you include the @code{gcjh}-generated header for a
1128 class, you can access fields of Java classes in the @emph{natural}
1129 way.  For example, given the following Java class:
1130
1131 @example
1132 public class Int
1133 @{
1134   public int i;
1135   public Integer (int i) @{ this.i = i; @}
1136   public static zero = new Integer(0);
1137 @}
1138 @end example
1139
1140 you can write:
1141
1142 @example
1143 #include <gcj/cni.h>;
1144 #include <Int>;
1145
1146 Int*
1147 mult (Int *p, jint k)
1148 @{
1149   if (k == 0)
1150     return Int::zero;  // @r{Static member access.}
1151   return new Int(p->i * k);
1152 @}
1153 @end example
1154
1155
1156 @subsection Access specifiers
1157
1158 CNI does not strictly enforce the Java access
1159 specifiers, because Java permissions cannot be directly mapped
1160 into C++ permission.  Private Java fields and methods are mapped
1161 to private C++ fields and methods, but other fields and methods
1162 are mapped to public fields and methods.
1163
1164
1165
1166 @node Class Initialization
1167 @section Class Initialization
1168
1169 Java requires that each class be automatically initialized at the time 
1170 of the first active use.  Initializing a class involves 
1171 initializing the static fields, running code in class initializer 
1172 methods, and initializing base classes.  There may also be 
1173 some implementation specific actions, such as allocating 
1174 @code{String} objects corresponding to string literals in
1175 the code.
1176
1177 The GCJ compiler inserts calls to @code{JvInitClass} at appropriate
1178 places to ensure that a class is initialized when required.  The C++
1179 compiler does not insert these calls automatically---it is the
1180 programmer's responsibility to make sure classes are initialized.
1181 However, this is fairly painless because of the conventions assumed by
1182 the Java system.
1183
1184 First, @code{libgcj} will make sure a class is initialized
1185 before an instance of that object is created.  This is one
1186 of the responsibilities of the @code{new} operation.  This is
1187 taken care of both in Java code, and in C++ code.  (When the G++
1188 compiler sees a @code{new} of a Java class, it will call
1189 a routine in @code{libgcj} to allocate the object, and that
1190 routine will take care of initializing the class.)  It follows that you can
1191 access an instance field, or call an instance (non-static)
1192 method and be safe in the knowledge that the class and all
1193 of its base classes have been initialized.
1194
1195 Invoking a static method is also safe.  This is because the
1196 Java compiler adds code to the start of a static method to make sure
1197 the class is initialized.  However, the C++ compiler does not
1198 add this extra code.  Hence, if you write a native static method
1199 using CNI, you are responsible for calling @code{JvInitClass}
1200 before doing anything else in the method (unless you are sure
1201 it is safe to leave it out).
1202
1203 Accessing a static field also requires the class of the
1204 field to be initialized.  The Java compiler will generate code
1205 to call @code{Jv_InitClass} before getting or setting the field.
1206 However, the C++ compiler will not generate this extra code,
1207 so it is your responsibility to make sure the class is
1208 initialized before you access a static field from C++.
1209
1210
1211 @node Object allocation
1212 @section Object allocation
1213
1214 New Java objects are allocated using a
1215 @dfn{class instance creation expression}, e.g.:
1216
1217 @example
1218 new @var{Type} ( ... )
1219 @end example
1220
1221 The same syntax is used in C++.  The main difference is that
1222 C++ objects have to be explicitly deleted; in Java they are
1223 automatically deleted by the garbage collector.
1224 Using @acronym{CNI}, you can allocate a new Java object
1225 using standard C++ syntax and the C++ compiler will allocate
1226 memory from the garbage collector.  If you have overloaded
1227 constructors, the compiler will choose the correct one
1228 using standard C++ overload resolution rules.  
1229
1230 @noindent For example:
1231
1232 @example
1233 java::util::Hashtable *ht = new java::util::Hashtable(120);
1234 @end example
1235
1236 @deftypefun void* _Jv_AllocBytes (jsize @var{size})
1237 Allocates @var{size} bytes from the heap.  The memory is not scanned
1238 by the garbage collector but it freed if no references to it are discovered.
1239 @end deftypefun
1240
1241
1242 @node Arrays
1243 @section Arrays
1244
1245 While in many ways Java is similar to C and C++, it is quite different
1246 in its treatment of arrays.  C arrays are based on the idea of pointer
1247 arithmetic, which would be incompatible with Java's security
1248 requirements.  Java arrays are true objects (array types inherit from
1249 @code{java.lang.Object}).  An array-valued variable is one that
1250 contains a reference (pointer) to an array object.
1251
1252 Referencing a Java array in C++ code is done using the
1253 @code{JArray} template, which as defined as follows:
1254
1255 @example
1256 class __JArray : public java::lang::Object
1257 @{
1258 public:
1259   int length;
1260 @};
1261
1262 template<class T>
1263 class JArray : public __JArray
1264 @{
1265   T data[0];
1266 public:
1267   T& operator[](jint i) @{ return data[i]; @}
1268 @};
1269 @end example
1270
1271
1272 There are a number of @code{typedef}s which correspond to @code{typedef}s 
1273 from the @acronym{JNI}.  Each is the type of an array holding objects
1274 of the relevant type:
1275
1276 @example
1277 typedef __JArray *jarray;
1278 typedef JArray<jobject> *jobjectArray;
1279 typedef JArray<jboolean> *jbooleanArray;
1280 typedef JArray<jbyte> *jbyteArray;
1281 typedef JArray<jchar> *jcharArray;
1282 typedef JArray<jshort> *jshortArray;
1283 typedef JArray<jint> *jintArray;
1284 typedef JArray<jlong> *jlongArray;
1285 typedef JArray<jfloat> *jfloatArray;
1286 typedef JArray<jdouble> *jdoubleArray;
1287 @end example
1288
1289
1290 @deftypemethod {template<class T>} T* elements (JArray<T> @var{array})
1291 This template function can be used to get a pointer to the elements of
1292 the @code{array}.  For instance, you can fetch a pointer to the
1293 integers that make up an @code{int[]} like so:
1294
1295 @example
1296 extern jintArray foo;
1297 jint *intp = elements (foo);
1298 @end example
1299
1300 The name of this function may change in the future.
1301 @end deftypemethod
1302
1303
1304 @deftypefun jobjectArray JvNewObjectArray (jsize @var{length}, jclass @var{klass}, jobject @var{init})
1305 Here @code{klass} is the type of elements of the array and
1306 @code{init} is the initial value put into every slot in the array.
1307 @end deftypefun
1308
1309
1310 @subsection Creating arrays
1311
1312 For each primitive type there is a function which can be used to
1313 create a new array of that type.  The name of the function is of the
1314 form:
1315
1316 @example
1317 JvNew@var{Type}Array
1318 @end example
1319
1320 @noindent For example:
1321
1322 @example
1323 JvNewBooleanArray
1324 @end example
1325
1326 @noindent can be used to create an array of Java primitive boolean types.
1327
1328 @noindent The following function definition is the template for all such functions:
1329
1330 @deftypefun jbooleanArray JvNewBooleanArray (jint @var{length})
1331 Create's an array @var{length} indices long.
1332 @end deftypefun
1333
1334 @deftypefun jsize JvGetArrayLength (jarray @var{array})
1335 Returns the length of the @var{array}.
1336 @end deftypefun
1337
1338
1339 @node Methods
1340 @section Methods
1341
1342 Java methods are mapped directly into C++ methods.
1343 The header files generated by @code{gcjh}
1344 include the appropriate method definitions.
1345 Basically, the generated methods have the same names and
1346 @emph{corresponding} types as the Java methods,
1347 and are called in the natural manner.
1348
1349 @subsection Overloading
1350
1351 Both Java and C++ provide method overloading, where multiple
1352 methods in a class have the same name, and the correct one is chosen
1353 (at compile time) depending on the argument types.
1354 The rules for choosing the correct method are (as expected) more complicated
1355 in C++ than in Java, but given a set of overloaded methods
1356 generated by @code{gcjh} the C++ compiler will choose
1357 the expected one.
1358
1359 Common assemblers and linkers are not aware of C++ overloading,
1360 so the standard implementation strategy is to encode the
1361 parameter types of a method into its assembly-level name.
1362 This encoding is called @dfn{mangling},
1363 and the encoded name is the @dfn{mangled name}.
1364 The same mechanism is used to implement Java overloading.
1365 For C++/Java interoperability, it is important that both the Java
1366 and C++ compilers use the @emph{same} encoding scheme.
1367
1368 @subsection Static methods
1369
1370 Static Java methods are invoked in @acronym{CNI} using the standard
1371 C++ syntax, using the @code{::} operator rather
1372 than the @code{.} operator.  
1373
1374 @noindent For example:
1375
1376 @example
1377 jint i = java::lang::Math::round((jfloat) 2.3);
1378 @end example
1379
1380 @noindent C++ method definition syntax is used to define a static native method.
1381 For example:
1382
1383 @example
1384 #include <java/lang/Integer>
1385 java::lang::Integer*
1386 java::lang::Integer::getInteger(jstring str)
1387 @{
1388   ...
1389 @}
1390 @end example
1391
1392
1393 @subsection Object Constructors
1394
1395 Constructors are called implicitly as part of object allocation
1396 using the @code{new} operator.  
1397
1398 @noindent For example:
1399
1400 @example
1401 java::lang::Integer *x = new java::lang::Integer(234);
1402 @end example
1403
1404 Java does not allow a constructor to be a native method.
1405 This limitation can be coded round however because a constructor
1406 can @emph{call} a native method.
1407
1408
1409 @subsection Instance methods
1410
1411 Calling a Java instance method from a C++ @acronym{CNI} method is done 
1412 using the standard C++ syntax, e.g.:
1413
1414 @example
1415 // @r{First create the Java object.}
1416 java::lang::Integer *x = new java::lang::Integer(234);
1417 // @r{Now call a method.}
1418 jint prim_value = x->intValue();
1419 if (x->longValue == 0) 
1420   ...
1421 @end example
1422
1423 @noindent Defining a Java native instance method is also done the natural way:
1424
1425 @example
1426 #include <java/lang/Integer.h>
1427
1428 jdouble
1429 java::lang:Integer::doubleValue()
1430 @{
1431   return (jdouble) value;
1432 @}
1433 @end example
1434
1435
1436 @subsection Interface methods
1437
1438 In Java you can call a method using an interface reference.  This is
1439 supported, but not completly.  @xref{Interfaces}.
1440
1441
1442
1443
1444 @node Strings
1445 @section Strings
1446
1447 @acronym{CNI} provides a number of utility functions for
1448 working with Java Java @code{String} objects.
1449 The names and interfaces are analogous to those of @acronym{JNI}.
1450
1451
1452 @deftypefun jstring JvNewString (const char* @var{chars}, jsize @var{len})
1453 Returns a Java @code{String} object with characters from the C string
1454 @var{chars} up to the index @var{len} in that array.
1455 @end deftypefun
1456
1457 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes}, jsize @var{len})
1458 Returns a Java @code{String} made up of @var{len} bytes from @var{bytes}.
1459 @end deftypefun
1460
1461
1462 @deftypefun jstring JvNewStringLatin1 (const char* @var{bytes})
1463 As above but the length of the @code{String} is @code{strlen(@var{bytes})}.
1464 @end deftypefun
1465
1466 @deftypefun jstring JvNewStringUTF (const char* @var{bytes})
1467 Returns a @code{String} which is made up of the UTF encoded characters
1468 present in the C string @var{bytes}.
1469 @end deftypefun
1470
1471 @deftypefun jchar* JvGetStringChars (jstring @var{str})
1472 Returns a pointer to an array of characters making up the @code{String} @var{str}.
1473 @end deftypefun
1474
1475 @deftypefun int JvGetStringUTFLength (jstring @var{str})
1476 Returns the number of bytes required to encode the contents of the
1477 @code{String} @var{str} in UTF-8.
1478 @end deftypefun
1479
1480 @deftypefun jsize JvGetStringUTFRegion (jstring @var{str}, jsize @var{start}, jsize @var{len}, char* @var{buf})
1481 Puts the UTF-8 encoding of a region of the @code{String} @var{str} into 
1482 the buffer @code{buf}.  The region to fetch is marked by @var{start} and @var{len}.
1483
1484 Note that @var{buf} is a buffer, not a C string.  It is @emph{not} 
1485 null terminated.
1486 @end deftypefun
1487
1488
1489 @node Mixing with C++
1490 @section Interoperating with C/C++
1491
1492 Because @acronym{CNI} is designed to represent Java classes and methods it
1493 cannot be mixed readily with C/C++ types.
1494
1495 One important restriction is that Java classes cannot have non-Java
1496 type instance or static variables and cannot have methods which take
1497 non-Java types as arguments or return non-Java types.
1498
1499 @noindent None of the following is possible with CNI:
1500
1501 @example
1502
1503 class ::MyClass : public java::lang::Object
1504 @{
1505    char* variable;  // @r{char* is not a valid Java type.}
1506 @}
1507
1508
1509 uint
1510 ::SomeClass::someMethod (char *arg)
1511 @{
1512   .
1513   .
1514   .
1515 @}   // @r{@code{uint} is not a valid Java type, neither is @code{char*}}
1516 @end example
1517
1518 @noindent Of course, it is ok to use C/C++ types within the scope of a method:
1519
1520
1521 @example
1522 jint
1523 ::SomeClass::otherMethod (jstring str)
1524 @{
1525    char *arg = ...
1526    .
1527    .
1528    .
1529 @}
1530 @end example
1531
1532 But this restriction can cause a problem so @acronym{CNI} includes the
1533 @code{gnu.gcj.RawData} class.  The @code{RawData} class is a
1534 @dfn{non-scanned reference} type.  In other words variables declared
1535 of type @code{RawData} can contain any data and are not checked by the
1536 compiler in any way.
1537
1538 This means that you can put C/C++ data structures (including classes)
1539 in your @acronym{CNI} classes, as long as you use the appropriate cast.
1540
1541 @noindent Here are some examples:
1542
1543 @example
1544
1545 class ::MyClass : public java::lang::Object
1546 @{
1547    GcjRaw string;
1548
1549    MyClass ();
1550    gnu.gcj.RawData getText ();
1551    void printText ();
1552 @}
1553
1554 ::MyClass::MyClass ()
1555 @{
1556    char* text = ...
1557    string = text;
1558 @}
1559
1560 gnu.gcj.RawData
1561 ::MyClass::getText ()
1562 @{
1563    return string;
1564 @}
1565
1566 void
1567 ::MyClass::printText ()
1568 @{
1569   printf("%s\n", (char*) string);
1570 @}
1571 @end example
1572
1573
1574 @node Exception Handling
1575 @section Exception Handling
1576
1577 While C++ and Java share a common exception handling framework,
1578 things are not yet perfectly integrated.  The main issue is that the
1579 run-time type information facilities of the two
1580 languages are not integrated.
1581
1582 Still, things work fairly well.  You can throw a Java exception from
1583 C++ using the ordinary @code{throw} construct, and this
1584 exception can be caught by Java code.  Similarly, you can catch an
1585 exception thrown from Java using the C++ @code{catch}
1586 construct.
1587
1588 @noindent Here is an example:
1589
1590 @example
1591 if (i >= count)
1592    throw new java::lang::IndexOutOfBoundsException();
1593 @end example
1594
1595 Normally, G++ will automatically detect when you are writing C++
1596 code that uses Java exceptions, and handle them appropriately.
1597 However, if C++ code only needs to execute destructors when Java
1598 exceptions are thrown through it, GCC will guess incorrectly.  Sample
1599 problematic code:
1600
1601 @example
1602 struct S @{ ~S(); @};
1603
1604 extern void bar();    // @r{Is implemented in Java and may throw exceptions.}
1605
1606 void foo()
1607 @{
1608   S s;
1609   bar();
1610 @}
1611 @end example
1612
1613 The usual effect of an incorrect guess is a link failure, complaining of
1614 a missing routine called @code{__gxx_personality_v0}.
1615
1616 You can inform the compiler that Java exceptions are to be used in a
1617 translation unit, irrespective of what it might think, by writing
1618 @code{#pragma GCC java_exceptions} at the head of the
1619 file.  This @code{#pragma} must appear before any
1620 functions that throw or catch exceptions, or run destructors when
1621 exceptions are thrown through them.
1622
1623 @node Synchronization
1624 @section Synchronization
1625
1626 Each Java object has an implicit monitor.
1627 The Java VM uses the instruction @code{monitorenter} to acquire
1628 and lock a monitor, and @code{monitorexit} to release it.
1629
1630 The corresponding CNI macros are @code{JvMonitorEnter} and 
1631 @code{JvMonitorExit} (JNI has similar  methods @code{MonitorEnter}
1632 and @code{MonitorExit}).  
1633
1634
1635 The Java source language does not provide direct access to these primitives.
1636 Instead, there is a @code{synchronized} statement that does an
1637 implicit @code{monitorenter} before entry to the block,
1638 and does a @code{monitorexit} on exit from the block.
1639 Note that the lock has to be released even when the block is abnormally
1640 terminated by an exception, which means there is an implicit
1641 @code{try finally} surrounding synchronization locks.
1642
1643 From C++, it makes sense to use a destructor to release a lock.
1644 @acronym{CNI} defines the following utility class:
1645
1646 @example
1647 class JvSynchronize() @{
1648   jobject obj;
1649   JvSynchronize(jobject o) @{ obj = o; JvMonitorEnter(o); @}
1650   ~JvSynchronize() @{ JvMonitorExit(obj); @}
1651 @};
1652 @end example
1653
1654 So this Java code:
1655
1656 @example
1657 synchronized (OBJ)
1658 @{
1659    CODE
1660 @}
1661 @end example
1662
1663 @noindent might become this C++ code:
1664
1665 @example
1666 @{
1667    JvSynchronize dummy (OBJ);
1668    CODE;
1669 @}
1670 @end example
1671
1672 Java also has methods with the @code{synchronized} attribute.
1673 This is equivalent to wrapping the entire method body in a
1674 @code{synchronized} statement.
1675 (Alternatively, an implementation could require the caller to do
1676 the synchronization.  This is not practical for a compiler, because
1677 each virtual method call would have to test at run-time if
1678 synchronization is needed.)  Since in @command{gcj}
1679 the @code{synchronized} attribute is handled by the
1680 method implementation, it is up to the programmer
1681 of a synchronized native method to handle the synchronization
1682 (in the C++ implementation of the method).
1683 In otherwords, you need to manually add @code{JvSynchronize}
1684 in a @code{native synchornized} method.
1685
1686
1687 @node Reflection
1688 @section Reflection
1689
1690 Reflection is possible with CNI code, it functions similarly to how it
1691 functions with JNI@.
1692
1693 @c clean this up...  I mean, what are the types jfieldID and jmethodID in JNI?
1694 The types @code{jfieldID} and @code{jmethodID}
1695 are as in JNI@.
1696
1697 @noindent The functions:
1698
1699 @itemize
1700 @item @code{JvFromReflectedField},
1701 @item @code{JvFromReflectedMethod},
1702 @item @code{JvToReflectedField}
1703 @item @code{JvToFromReflectedMethod}
1704 @end itemize
1705
1706 @noindent will be added shortly, as will other functions corresponding to JNI@.
1707
1708
1709
1710 @node Resources
1711 @chapter Resources
1712
1713 While writing @command{gcj} and @code{libgcj} we have, of course, relied
1714 heavily on documentation from Sun Microsystems.  In particular we have
1715 used The Java Language Specification (both first and second editions),
1716 the Java Class Libraries (volumes one and two), and the Java Virtual
1717 Machine Specification.  In addition we've used the online documentation
1718 at @uref{http://java.sun.com/}.
1719
1720 The current @command{gcj} home page is
1721 @uref{http://gcc.gnu.org/java/}.
1722
1723 For more information on gcc, see @uref{http://gcc.gnu.org/}.
1724
1725 Some @code{libgcj} testing is done using the Mauve test suite.  This is
1726 a free software Java class library test suite which is being written
1727 because the JCK is not free.  See
1728 @uref{http://sources.redhat.com/mauve/} for more information.
1729
1730 @bye