1 /*
2 * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 /**
27 * <h2>Provides classfile parsing, generation, and transformation library.</h2>
28 * The {@code java.lang.classfile} package contains API models for reading,
29 * writing, and modifying Java class files, as specified in Chapter {@jvms 4} of
30 * the <cite>Java Virtual Machine Specification</cite>. This package, {@link
31 * java.lang.classfile.attribute}, {@link java.lang.classfile.constantpool},
32 * and {@link java.lang.classfile.instruction} form the Class-File API.
33 *
34 * <h2>Reading classfiles</h2>
35 * The main class for reading classfiles is {@link ClassModel}; we
36 * convert bytes into a {@link ClassModel} with {@link
37 * ClassFile#parse(byte[])}:
38 *
39 * {@snippet lang=java :
40 * ClassModel cm = ClassFile.of().parse(bytes);
41 * }
42 *
43 * There are several additional overloads of {@code parse} that let you specify
44 * various processing options.
45 * <p>
46 * A {@link ClassModel} is an immutable description of a class
47 * file. It provides accessor methods to get at class metadata (e.g., {@link
48 * ClassModel#thisClass()}, {@link ClassModel#flags()}),
49 * as well as subordinate classfile entities ({@link ClassModel#fields()},
50 * {@link ClassModel#attributes()}). A {@link
51 * ClassModel} is inflated lazily; most parts of the classfile are
52 * not parsed until they are actually needed. Due to the laziness, these models
53 * may not be thread safe. Additionally, invocations to accessor methods on
54 * models may lead to {@link IllegalArgumentException} due to malformed {@code
55 * class} file format, as parsing happens lazily.
56 * <p>
57 * We can enumerate the names of the fields and methods in a class by:
58 * {@snippet lang="java" class="PackageSnippets" region="enumerateFieldsMethods1"}
59 * <p>
60 * When we enumerate the methods, we get a {@link MethodModel} for each method; like a
61 * {@code ClassModel}, it gives us access to method metadata and
62 * the ability to descend into subordinate entities such as the bytecodes of the
63 * method body. In this way, a {@code ClassModel} is the root of a
64 * tree, with children for fields, methods, and attributes, and {@code MethodModel} in
65 * turn has its own children (attributes, {@code CodeModel}, etc.)
66 * <p>
67 * Methods like {@link ClassModel#methods} allows us to traverse the class structure
68 * explicitly, going straight to the parts we are interested in. This is useful
69 * for certain kinds of analysis, but if we wanted to process the whole
70 * classfile, we may want something more organized. A {@link
71 * ClassModel} also provides us with a view of the classfile as a
72 * series of class <em>elements</em>, which may include methods, fields, attributes,
73 * and more, and which can be distinguished with pattern matching. We could
74 * rewrite the above example as:
75 * {@snippet lang="java" class="PackageSnippets" region="enumerateFieldsMethods2"}
76 * <p>
77 * The models returned as elements from traversing {@code ClassModel} can in
78 * turn be sources of elements. If we wanted to
79 * traverse a classfile and enumerate all the classes for which we access fields
80 * and methods, we can pick out the class elements that describe methods, then
81 * in turn pick out the method elements that describe the code attribute, and
82 * finally pick out the code elements that describe field access and invocation
83 * instructions:
84 * {@snippet lang="java" class="PackageSnippets" region="gatherDependencies1"}
85 * <p>
86 * This same query could alternately be processed as a stream pipeline over
87 * class elements:
88 * {@snippet lang="java" class="PackageSnippets" region="gatherDependencies2"}
89 *
90 * <h3>Models and elements</h3>
91 * The view of classfiles presented by this API is framed in terms of
92 * <em>models</em> and <em>elements</em>. Models represent complex structures,
93 * such as classes, methods, fields, record elements, or the code body of a
94 * method. Models can be explored either via random-access navigation (such as
95 * the {@link ClassModel#methods()} accessor) or as a linear
96 * sequence of <em>elements</em>. (Elements can in turn also be models; a {@link
97 * FieldModel} is also an element of a class.) For each model type
98 * (e.g., {@link MethodModel}), there is a corresponding element
99 * type ({@link MethodElement}). Models and elements are immutable
100 * and are inflated lazily so creating a model does not necessarily require
101 * processing its entire content.
102 *
103 * <h3>The constant pool</h3>
104 * Much of the interesting content in a classfile lives in the <em>constant
105 * pool</em>. {@link ClassModel} provides a lazily-inflated,
106 * read-only view of the constant pool via {@link ClassModel#constantPool()}.
107 * Descriptions of classfile content is often exposed in the form of various
108 * subtypes of {@link PoolEntry}, such as {@link
109 * ClassEntry} or {@link Utf8Entry}.
110 * <p>
111 * Constant pool entries are also exposed through models and elements; in the
112 * above traversal example, the {@link InvokeInstruction}
113 * element exposed a method for {@code owner} that corresponds to a {@code
114 * Constant_Class_info} entry in the constant pool.
115 *
116 * <h3>Attributes</h3>
117 * Much of the contents of a classfile is stored in attributes; attributes are
118 * found on classes, methods, fields, record components, and on the {@code Code}
119 * attribute. Most attributes are surfaced as elements; for example, {@link
120 * SignatureAttribute} is a {@link
121 * ClassElement}, {@link MethodElement}, and {@link
122 * FieldElement} since it can appear in all of those places, and is
123 * included when iterating the elements of the corresponding model.
124 * <p>
125 * Some attributes are not surfaced as elements; these are attributes that are
126 * tightly coupled to -- and logically part of -- other parts of the class file.
127 * These include the {@code BootstrapMethods}, {@code LineNumberTable}, {@code
128 * StackMapTable}, {@code LocalVariableTable}, and {@code
129 * LocalVariableTypeTable} attributes. These are processed by the library and
130 * treated as part of the structure they are coupled to (the entries of the
131 * {@code BootstrapMethods} attribute are treated as part of the constant pool;
132 * line numbers and local variable metadata are modeled as elements of {@link
133 * CodeModel}.)
134 * <p>
135 * The {@code Code} attribute, in addition to being modeled as a {@link
136 * MethodElement}, is also a model in its own right ({@link
137 * CodeModel}) due to its complex structure.
138 * <p>
139 * Each standard attribute has an interface (in {@code java.lang.classfile.attribute})
140 * which exposes the contents of the attribute and provides factories to
141 * construct the attribute. For example, the {@code Signature} attribute is
142 * defined by the {@link SignatureAttribute} class, and
143 * provides accessors for {@link SignatureAttribute#signature()}
144 * as well as factories taking {@link Utf8Entry} or
145 * {@link String}.
146 *
147 * <h3>Custom attributes</h3>
148 * Attributes are converted between their classfile form and their corresponding
149 * object form via an {@link AttributeMapper}. An {@code
150 * AttributeMapper} provides the
151 * {@link AttributeMapper#readAttribute(AttributedElement,
152 * ClassReader, int)} method for mapping from the classfile format
153 * to an attribute instance, and the
154 * {@link AttributeMapper#writeAttribute(BufWriter,
155 * Attribute)} method for mapping back to the classfile format. It also
156 * contains metadata including the attribute name, the set of classfile entities
157 * where the attribute is applicable, and whether multiple attributes of the
158 * same kind are allowed on a single entity.
159 * <p>
160 * There are built-in attribute mappers (in {@link Attributes}) for
161 * each of the attribute types defined in section {@jvms 4.7} of <cite>The Java Virtual
162 * Machine Specification</cite>, as well as several common nonstandard attributes used by the
163 * JDK such as {@code CharacterRangeTable}.
164 * <p>
165 * Unrecognized attributes are delivered as elements of type {@link
166 * UnknownAttribute}, which provide access only to the
167 * {@code byte[]} contents of the attribute.
168 * <p>
169 * For nonstandard attributes, user-provided attribute mappers can be specified
170 * through the use of the {@link
171 * ClassFile.AttributeMapperOption#of(Function)}
172 * classfile option. Implementations of custom attributes should extend {@link
173 * CustomAttribute}.
174 *
175 * <h3 id="options">Options</h3>
176 * <p>
177 * {@link ClassFile#of(ClassFile.Option[])}
178 * accepts a list of options. {@link ClassFile.Option} is a base interface
179 * for some statically enumerated options, as well as factories for more complex options,
180 * including:
181 * <ul>
182 * <li>{@link ClassFile.AttributeMapperOption#of(Function)}
183 * -- specify format of custom attributes</li>
184 * <li>{@link ClassFile.AttributesProcessingOption}
185 * -- unrecognized or problematic original attributes (default is {@code PASS_ALL_ATTRIBUTES})</li>
186 * <li>{@link ClassFile.ClassHierarchyResolverOption#of(ClassHierarchyResolver)}
187 * -- specify a custom class hierarchy resolver used by stack map generation</li>
188 * <li>{@link ClassFile.ConstantPoolSharingOption}
189 * -- share constant pool when transforming (default is {@code SHARED_POOL})</li>
190 * <li>{@link ClassFile.DeadCodeOption}
191 * -- patch out unreachable code (default is {@code PATCH_DEAD_CODE})</li>
192 * <li>{@link ClassFile.DeadLabelsOption}
193 * -- filter unresolved labels (default is {@code FAIL_ON_DEAD_LABELS})</li>
194 * <li>{@link ClassFile.DebugElementsOption}
195 * -- processing of debug information, such as local variable metadata (default is {@code PASS_DEBUG}) </li>
196 * <li>{@link ClassFile.LineNumbersOption}
197 * -- processing of line numbers (default is {@code PASS_LINE_NUMBERS}) </li>
198 * <li>{@link ClassFile.ShortJumpsOption}
199 * -- automatically rewrite short jumps to long when necessary (default is {@code FIX_SHORT_JUMPS})</li>
200 * <li>{@link ClassFile.StackMapsOption}
201 * -- generate stackmaps (default is {@code STACK_MAPS_WHEN_REQUIRED})</li>
202 * </ul>
203 * <p>
204 * {@link ClassFile.AttributeMapperOption} and {@link ClassFile.ClassHierarchyResolverOption}
205 * are critical to the correctness of {@code class} file parsing and generation.
206 * The attribute mapper is required to parse custom attributes. A correct
207 * resolver is required to generate {@code class} files that refer to classes
208 * not available to the system class loader in its bytecode, or in corner cases,
209 * when generation wishes to avoid loading system classes, such as in agents.
210 * <p>
211 * Most options allow you to request that certain parts of the classfile be
212 * skipped during traversal, such as debug information or unrecognized
213 * attributes. Some options allow you to suppress generation of portions of the
214 * classfile, such as stack maps. Many of these options are to access
215 * performance tradeoffs; processing debug information and line numbers has a
216 * cost (both in writing and reading.) If you don't need this information, you
217 * can suppress it with options to gain some performance.
218 *
219 * <h2>Writing classfiles</h2>
220 * ClassFile generation is accomplished through <em>builders</em>. For each
221 * entity type that has a model, there is also a corresponding builder type;
222 * classes are built through {@link ClassBuilder}, methods through
223 * {@link MethodBuilder}, etc.
224 * <p>
225 * Rather than creating builders directly, builders are provided as an argument
226 * to a user-provided lambda. To generate the familiar "hello world" program,
227 * we ask for a class builder, and use that class builder to create method
228 * builders for the constructor and {@code main} method, and in turn use the
229 * method builders to create a {@code Code} attribute and use the code builders
230 * to generate the instructions:
231 * {@snippet lang="java" class="PackageSnippets" region="helloWorld1"}
232 * <p>
233 * The convenience methods {@code ClassBuilder.buildMethodBody} allows us to ask
234 * {@link ClassBuilder} to create code builders to build method bodies directly,
235 * skipping the method builder custom lambda:
236 * {@snippet lang="java" class="PackageSnippets" region="helloWorld2"}
237 * <p>
238 * Builders often support multiple ways of expressing the same entity at
239 * different levels of abstraction. For example, the {@code invokevirtual}
240 * instruction invoking {@code println} could have been generated with {@link
241 * CodeBuilder#invokevirtual(ClassDesc,
242 * String, MethodTypeDesc) CodeBuilder.invokevirtual}, {@link
243 * CodeBuilder#invoke(Opcode,
244 * ClassDesc, String, MethodTypeDesc,
245 * boolean) CodeBuilder.invoke}, or {@link
246 * CodeBuilder#with(ClassFileElement)
247 * CodeBuilder.with}.
248 * <p>
249 * The convenience method {@code CodeBuilder.invokevirtual} behaves as if it calls
250 * the convenience method {@code CodeBuilder.invoke}, which in turn behaves
251 * as if it calls method {@code CodeBuilder.with}. This composing of method calls on the
252 * builder enables the composing of transforms (as described later).
253 *
254 * <h3>Symbolic information</h3>
255 * To describe symbolic information for classes and types, the API uses the
256 * nominal descriptor abstractions from {@link java.lang.constant} such as {@link
257 * ClassDesc} and {@link MethodTypeDesc},
258 * which is less error-prone than using raw strings.
259 * <p>
260 * If a constant pool entry has a nominal representation then it provides a
261 * method returning the corresponding nominal descriptor type e.g.
262 * method {@link ClassEntry#asSymbol} returns
263 * {@code ClassDesc}.
264 * <p>
265 * Where appropriate builders provide two methods for building an element with
266 * symbolic information, one accepting nominal descriptors, and the other
267 * accepting constant pool entries.
268 *
269 * <h3 id="checks">Consistency checks, syntax checks and verification</h3>
270 * The Class-File API performs checks to ensure arguments to construct {@code
271 * class} file structures are representable in the {@code class} file format.
272 * An argument value that cannot be representable by its data type is rejected
273 * with an {@link IllegalArgumentException}. For example, an {@code int} value
274 * cannot be out of the range of its {@linkplain java.lang.classfile##data-types
275 * data type}; a {@code List} cannot exceed the maximum representable size of
276 * its table data type, or contain an unrepresentable element. Restrictions
277 * based on underlying data type, such as the {@code int} and {@code List} ones
278 * before, are specified on the corresponding APIs. Unless otherwise noted, in
279 * all structures, a {@code String} cannot exceed {@code 65535} bytes when
280 * represented in modified UTF-8 format.
281 * <p>
282 * Unless otherwise noted, passing null or an array or collection that contains
283 * null as an element to a constructor or method of any Class-File API class or
284 * interface will cause a {@link NullPointerException} to be thrown.
285 * <p>
286 * No consistency checks are performed while building or transforming classfiles
287 * (except for null and representable arguments checks). All builders and
288 * classfile elements factory methods accepts the provided information without
289 * implicit validation, as long as they are representable in the {@code class}
290 * file format. However, fatal inconsistencies (like invalid code sequence or
291 * unresolved labels) affects internal tools and may cause exceptions later in
292 * the classfile building process. These fatal exceptions are thrown as
293 * {@code IllegalArgumentException}.
294 * <p>
295 * Using nominal descriptors assures the right serial form is applied by the
296 * ClassFile API library based on the actual context. Also these nominal
297 * descriptors are validated during their construction, so it is not possible to
298 * create them with invalid content by mistake. Following example pass class
299 * name to the {@link ClassDesc#of} method for validation
300 * and the library performs automatic conversion to the right internal form of
301 * the class name when serialized in the constant pool as a class entry.
302 * {@snippet lang=java :
303 * var validClassEntry = constantPoolBuilder.classEntry(ClassDesc.of("mypackage.MyClass"));
304 * }
305 * <p>
306 * On the other hand it is possible to use builders methods and factories accepting
307 * constant pool entries directly. Constant pool entries can be constructed also
308 * directly from raw values, with no additional conversions or validations, as
309 * long as they are representable. Following example uses intentionally wrong
310 * class name form, which is applied without any validation or conversion.
311 * {@snippet lang=java :
312 * var invalidClassEntry = constantPoolBuilder.classEntry(
313 * constantPoolBuilder.utf8Entry("mypackage.MyClass"));
314 * }
315 * <p>
316 * More complex verification of a classfile can be achieved by invocation of
317 * {@link ClassFile#verify}.
318 *
319 * <h2>Transforming classfiles</h2>
320 * ClassFile Processing APIs are most frequently used to combine reading and
321 * writing into transformation, where a classfile is read, localized changes are
322 * made, but much of the classfile is passed through unchanged. For each kind
323 * of builder, {@code XxxBuilder} has a method {@code with(XxxElement)} so that
324 * elements that we wish to pass through unchanged can be handed directly back
325 * to the builder.
326 * <p>
327 * If we wanted to strip out methods whose names starts with "debug", we could
328 * get an existing {@link ClassModel}, build a new classfile that
329 * provides a {@link ClassBuilder}, iterate the elements of the
330 * original {@link ClassModel}, and pass through all of them to
331 * the builder except the methods we want to drop:
332 * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods1"}
333 * <p>
334 * This hands every class element, except for those corresponding to methods
335 * whose names start with {@code debug}, back to the builder. Transformations
336 * can of course be more complicated, diving into method bodies and instructions
337 * and transforming those as well, but the same structure is repeated at every
338 * level, since every entity has corresponding model, builder, and element
339 * abstractions.
340 * <p>
341 * Transformation can be viewed as a "flatMap" operation on the sequence of
342 * elements; for every element, we could pass it through unchanged, drop it, or
343 * replace it with one or more elements. Because transformation is such a
344 * common operation on classfiles, each model type has a corresponding {@code
345 * XxxTransform} type (which describes a transform on a sequence of {@code
346 * XxxElement}) and each builder type has {@code transformYyy} methods for transforming
347 * its child models. A transform is simply a functional interface that takes a
348 * builder and an element, and an implementation "flatMap"s elements
349 * into the builder. We could express the above as:
350 * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods2"}
351 * <p>
352 * {@code ClassTransform.dropping} convenience method allow us to simplify the same
353 * transformation construction and express the above as:
354 * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods3"}
355 *
356 * <h3>Lifting transforms</h3>
357 * While the example using transformations are only slightly shorter, the
358 * advantage of expressing transformation in this way is that the transform
359 * operations can be more easily combined. Suppose we want to redirect
360 * invocations of static methods on {@code Foo} to the corresponding method on
361 * {@code Bar} instead. We could express this as a transformation on {@link
362 * CodeElement}:
363 * {@snippet lang="java" class="PackageSnippets" region="fooToBarTransform"}
364 * <p>
365 * We can then <em>lift</em> this transformation on code elements into a
366 * transformation on method elements. This intercepts method elements that
367 * correspond to a {@code Code} attribute, dives into its code elements, and
368 * applies the code transform to them, and passes other method elements through
369 * unchanged:
370 * {@snippet lang=java :
371 * MethodTransform mt = MethodTransform.transformingCode(fooToBar);
372 * }
373 * <p>
374 * and further lift the transform on method elements into one on class
375 * elements:
376 * {@snippet lang=java :
377 * ClassTransform ct = ClassTransform.transformingMethods(mt);
378 * }
379 * <p>
380 * or lift the code transform into the class transform directly:
381 * {@snippet lang=java :
382 * ClassTransform ct = ClassTransform.transformingMethodBodies(fooToBar);
383 * }
384 * <p>
385 * and then transform the classfile:
386 * {@snippet lang=java :
387 * var cc = ClassFile.of();
388 * byte[] newBytes = cc.transformClass(cc.parse(bytes), ct);
389 * }
390 * <p>
391 * This is much more concise (and less error-prone) than the equivalent
392 * expressed by traversing the classfile structure directly:
393 * {@snippet lang="java" class="PackageSnippets" region="fooToBarUnrolled"}
394 *
395 * <h3>Composing transforms</h3>
396 * Transforms on the same type of element can be composed in sequence, where the
397 * output of the first is fed to the input of the second. Suppose we want to
398 * instrument all method calls, where we print the name of a method before
399 * calling it:
400 * {@snippet lang="java" class="PackageSnippets" region="instrumentCallsTransform"}
401 * <p>
402 * Then we can compose {@code fooToBar} and {@code instrumentCalls} with {@link
403 * CodeTransform#andThen(CodeTransform)}:
404 *
405 * {@snippet lang=java :
406 * var cc = ClassFile.of();
407 * byte[] newBytes = cc.transformClass(cc.parse(bytes),
408 * ClassTransform.transformingMethods(
409 * MethodTransform.transformingCode(
410 * fooToBar.andThen(instrumentCalls))));
411 * }
412 *
413 * Transform {@code instrumentCalls} will receive all code elements produced by
414 * transform {@code forToBar}, either those code elements from the original classfile
415 * or replacements (replacing static invocations to {@code Foo} with those to {@code Bar}).
416 *
417 * <h3>Constant pool sharing</h3>
418 * Transformation doesn't merely handle the logistics of reading, transforming
419 * elements, and writing. Most of the time when we are transforming a
420 * classfile, we are making relatively minor changes. To optimize such cases,
421 * transformation seeds the new classfile with a copy of the constant pool from
422 * the original classfile; this enables significant optimizations (methods and
423 * attributes that are not transformed can be processed by bulk-copying their
424 * bytes, rather than parsing them and regenerating their contents.) If
425 * constant pool sharing is not desired it can be suppressed
426 * with the {@link ClassFile.ConstantPoolSharingOption} option.
427 * Such suppression may be beneficial when transformation removes many elements,
428 * resulting in many unreferenced constant pool entries.
429 *
430 * <h3>Transformation handling of unknown classfile elements</h3>
431 * Custom classfile transformations might be unaware of classfile elements
432 * introduced by future JDK releases. To achieve deterministic stability,
433 * classfile transforms interested in consuming all classfile elements should be
434 * implemented strictly to throw exceptions if running on a newer JDK, if the
435 * transformed class file is a newer version, or if a new and unknown classfile
436 * element appears. As for example in the following strict compatibility-checking
437 * transformation snippets:
438 * {@snippet lang="java" class="PackageSnippets" region="strictTransform1"}
439 * {@snippet lang="java" class="PackageSnippets" region="strictTransform2"}
440 * {@snippet lang="java" class="PackageSnippets" region="strictTransform3"}
441 * <p>
442 * Conversely, classfile transforms that are only interested in consuming a portion
443 * of classfile elements do not need to concern with new and unknown classfile
444 * elements and may pass them through. Following example shows such future-proof
445 * code transformation:
446 * {@snippet lang="java" class="PackageSnippets" region="benevolentTransform"}
447 *
448 * <h2>API conventions</h2>
449 * <p>
450 * The API is largely derived from a <a href="#data_model"><em>data model</em></a>
451 * for the classfile format, which defines each element kind (which includes models and
452 * attributes) and its properties. For each element kind, there is a
453 * corresponding interface to describe that element, and factory methods to
454 * create that element. Some element kinds also have convenience methods on the
455 * corresponding builder (e.g., {@link
456 * CodeBuilder#invokevirtual(ClassDesc,
457 * String, MethodTypeDesc)}).
458 * <p>
459 * Most symbolic information in elements is represented by constant pool entries
460 * (for example, the owner of a field is represented by a {@link
461 * ClassEntry}.) Factories and builders also
462 * accept nominal descriptors from {@link java.lang.constant} (e.g., {@link
463 * ClassDesc}.)
464 *
465 * <h3 id="data-types">Conventional data types</h3>
466 * Chapter {@jvms 4} of the <cite>Java Virtual Machine Specification</cite>
467 * defines a few conventional data types in the {@code class} file format.
468 * They are consistently represented as {@code int} in the API model.
469 * Out-of-bound values provided for these data types to the API result in {@link
470 * IllegalArgumentException}.
471 * <dl>
472 * <dt id="u1">{@code u1}</dt>
473 * <dd>One-byte {@linkplain Byte#toUnsignedInt(byte) unsigned} integer, in the
474 * range {@code [0, 255]}.
475 * <br>See {@link java.io.DataInput#readUnsignedByte()}.</dd>
476 * <dt id="u2">{@code u2}</dt>
477 * <dd>Two-byte {@linkplain Short#toUnsignedInt(short) unsigned} integer, in the
478 * range {@code [0, 65535]}.
479 * <br>Equivalent to a Java {@link Character char}. Frequently used for flag
480 * fields and indices and sizes of list structures.
481 * <br>See {@link java.io.DataInput#readUnsignedShort()}.</dd>
482 * <dt id="u4">{@code u4}</dt>
483 * <dd>Four-byte {@linkplain Integer#toUnsignedLong(int) unsigned} integer, in
484 * the range {@code [0, 4294967295]}.
485 * <br>See {@link java.io.DataInput#readInt()}.</dd>
486 * </dl>
487 *
488 * <h2><a id="data_model"></a>Data model</h2>
489 * We define each kind of element by its name, an optional arity indicator (zero
490 * or more, zero or one, exactly one), and a list of components. The elements
491 * of a class are fields, methods, and the attributes that can appear on
492 * classes:
493 *
494 * {@snippet lang="text" :
495 * ClassElement =
496 * FieldModel*(UtfEntry name, Utf8Entry descriptor)
497 * | MethodModel*(UtfEntry name, Utf8Entry descriptor)
498 * | ModuleAttribute?(int flags, ModuleEntry moduleName, UtfEntry moduleVersion,
499 * List<ModuleRequireInfo> requires, List<ModuleOpenInfo> opens,
500 * List<ModuleExportInfo> exports, List<ModuleProvidesInfo> provides,
501 * List<ClassEntry> uses)
502 * | ModulePackagesAttribute?(List<PackageEntry> packages)
503 * | ModuleTargetAttribute?(Utf8Entry targetPlatform)
504 * | ModuleHashesAttribute?(Utf8Entry algorithm, List<HashInfo> hashes)
505 * | ModuleResolutionAttribute?(int resolutionFlags)
506 * | SourceFileAttribute?(Utf8Entry sourceFile)
507 * | SourceDebugExtensionsAttribute?(byte[] contents)
508 * | CompilationIDAttribute?(Utf8Entry compilationId)
509 * | SourceIDAttribute?(Utf8Entry sourceId)
510 * | NestHostAttribute?(ClassEntry nestHost)
511 * | NestMembersAttribute?(List<ClassEntry> nestMembers)
512 * | RecordAttribute?(List<RecordComponent> components)
513 * | EnclosingMethodAttribute?(ClassEntry className, NameAndTypeEntry method)
514 * | InnerClassesAttribute?(List<InnerClassInfo> classes)
515 * | PermittedSubclassesAttribute?(List<ClassEntry> permittedSubclasses)
516 * | DeclarationElement*
517 * }
518 *
519 * where {@code DeclarationElement} are the elements that are common to all declarations
520 * (classes, methods, fields) and so are factored out:
521 *
522 * {@snippet lang="text" :
523 * DeclarationElement =
524 * SignatureAttribute?(Utf8Entry signature)
525 * | SyntheticAttribute?()
526 * | DeprecatedAttribute?()
527 * | RuntimeInvisibleAnnotationsAttribute?(List<Annotation> annotations)
528 * | RuntimeVisibleAnnotationsAttribute?(List<Annotation> annotations)
529 * | CustomAttribute*
530 * | UnknownAttribute*
531 * }
532 *
533 * Fields and methods are models with their own elements. The elements of fields
534 * and methods are fairly simple; most of the complexity of methods lives in the
535 * {@link CodeModel} (which models the {@code Code} attribute
536 * along with the code-related attributes: stack map table, local variable table,
537 * line number table, etc.)
538 *
539 * {@snippet lang="text" :
540 * FieldElement =
541 * DeclarationElement
542 * | ConstantValueAttribute?(ConstantValueEntry constant)
543 *
544 * MethodElement =
545 * DeclarationElement
546 * | CodeModel?()
547 * | AnnotationDefaultAttribute?(ElementValue defaultValue)
548 * | MethodParametersAttribute?(List<MethodParameterInfo> parameters)
549 * | ExceptionsAttribute?(List<ClassEntry> exceptions)
550 * }
551 *
552 * {@link CodeModel} is unique in that its elements are <em>ordered</em>.
553 * Elements of {@code Code} include ordinary bytecodes, as well as a number of pseudo-instructions
554 * representing branch targets, line number metadata, local variable metadata, and
555 * catch blocks.
556 *
557 * {@snippet lang="text" :
558 * CodeElement = Instruction | PseudoInstruction
559 *
560 * Instruction =
561 * LoadInstruction(TypeKind type, int slot)
562 * | StoreInstruction(TypeKind type, int slot)
563 * | IncrementInstruction(int slot, int constant)
564 * | BranchInstruction(Opcode opcode, Label target)
565 * | LookupSwitchInstruction(Label defaultTarget, List<SwitchCase> cases)
566 * | TableSwitchInstruction(Label defaultTarget, int low, int high,
567 * List<SwitchCase> cases)
568 * | ReturnInstruction(TypeKind kind)
569 * | ThrowInstruction()
570 * | FieldInstruction(Opcode opcode, FieldRefEntry field)
571 * | InvokeInstruction(Opcode opcode, MemberRefEntry method, boolean isInterface)
572 * | InvokeDynamicInstruction(InvokeDynamicEntry invokedynamic)
573 * | NewObjectInstruction(ClassEntry className)
574 * | NewReferenceArrayInstruction(ClassEntry componentType)
575 * | NewPrimitiveArrayInstruction(TypeKind typeKind)
576 * | NewMultiArrayInstruction(ClassEntry componentType, int dims)
577 * | ArrayLoadInstruction(Opcode opcode)
578 * | ArrayStoreInstruction(Opcode opcode)
579 * | TypeCheckInstruction(Opcode opcode, ClassEntry className)
580 * | ConvertInstruction(TypeKind from, TypeKind to)
581 * | OperatorInstruction(Opcode opcode)
582 * | ConstantInstruction(ConstantDesc constant)
583 * | StackInstruction(Opcode opcode)
584 * | MonitorInstruction(Opcode opcode)
585 * | NopInstruction()
586 *
587 * PseudoInstruction =
588 * | LabelTarget(Label label)
589 * | LineNumber(int line)
590 * | ExceptionCatch(Label tryStart, Label tryEnd, Label handler, ClassEntry exception)
591 * | LocalVariable(int slot, UtfEntry name, Utf8Entry type, Label startScope, Label endScope)
592 * | LocalVariableType(int slot, Utf8Entry name, Utf8Entry type, Label startScope, Label endScope)
593 * | CharacterRange(int rangeStart, int rangeEnd, int flags, Label startScope, Label endScope)
594 * }
595 *
596 * @since 24
597 */
598 package java.lang.classfile;
599
600 import java.lang.classfile.attribute.SignatureAttribute;
601 import java.lang.classfile.attribute.UnknownAttribute;
602 import java.lang.classfile.constantpool.ClassEntry;
603 import java.lang.classfile.constantpool.PoolEntry;
604 import java.lang.classfile.constantpool.Utf8Entry;
605 import java.lang.classfile.instruction.InvokeInstruction;
606 import java.lang.constant.ClassDesc;
607 import java.lang.constant.MethodTypeDesc;
608 import java.util.function.Function;
--- EOF ---