OSDN Git Service

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