View Javadoc
1   package org.codehaus.plexus.languages.java.jpms;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.DataInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.util.ArrayList;
26  import java.util.HashSet;
27  import java.util.LinkedHashSet;
28  import java.util.List;
29  import java.util.Set;
30  
31  /**
32   * Reads the {@code Module} attribute (JVMS 4.7.25) directly out of a {@code module-info.class} file,
33   * without depending on a bytecode library or on the class-file support of the running JDK.
34   *
35   * <p>Only the class file's overall shape (constant pool, then fields, then methods, then attributes)
36   * needs to be understood to reach the {@code Module} attribute; every other section is skipped using
37   * its own declared length rather than parsed. The {@code Module} attribute format has been stable
38   * since it was introduced in Java 9, and this parser never looks at the class file's major/minor
39   * version, so it reads a {@code module-info.class} produced by any future JDK just as well as one
40   * from Java 9.
41   *
42   * @author Robert Scholte
43   * @since 1.7.0
44   */
45  class ModuleInfoClassParser extends AbstractBinaryModuleInfoParser {
46  
47      private static final int MAGIC = 0xCAFEBABE;
48  
49      // Constant pool tags, JVMS 4.4, Table 4.4-A.
50      private static final int CONSTANT_UTF8 = 1;
51      private static final int CONSTANT_INTEGER = 3;
52      private static final int CONSTANT_FLOAT = 4;
53      private static final int CONSTANT_LONG = 5;
54      private static final int CONSTANT_DOUBLE = 6;
55      private static final int CONSTANT_CLASS = 7;
56      private static final int CONSTANT_STRING = 8;
57      private static final int CONSTANT_FIELDREF = 9;
58      private static final int CONSTANT_METHODREF = 10;
59      private static final int CONSTANT_INTERFACE_METHODREF = 11;
60      private static final int CONSTANT_NAME_AND_TYPE = 12;
61      private static final int CONSTANT_METHOD_HANDLE = 15;
62      private static final int CONSTANT_METHOD_TYPE = 16;
63      private static final int CONSTANT_DYNAMIC = 17;
64      private static final int CONSTANT_INVOKE_DYNAMIC = 18;
65      private static final int CONSTANT_MODULE = 19;
66      private static final int CONSTANT_PACKAGE = 20;
67  
68      private static final String MODULE_ATTRIBUTE_NAME = "Module";
69  
70      // Module_attribute requires_flags, JVMS 4.7.25.
71      private static final int ACC_TRANSITIVE = 0x0020;
72      private static final int ACC_STATIC_PHASE = 0x0040;
73  
74      @Override
75      JavaModuleDescriptor parse(InputStream in) throws IOException {
76          DataInputStream dis = (in instanceof DataInputStream) ? (DataInputStream) in : new DataInputStream(in);
77  
78          int magic = dis.readInt();
79          if (magic != MAGIC) {
80              throw new IOException("Not a class file, bad magic number: 0x" + Integer.toHexString(magic));
81          }
82  
83          dis.readUnsignedShort(); // minor_version, unused
84          dis.readUnsignedShort(); // major_version, deliberately unchecked: the Module attribute below
85          // has the same layout no matter which major version produced the file.
86  
87          ConstantPool pool = ConstantPool.read(dis);
88  
89          dis.readUnsignedShort(); // access_flags
90          dis.readUnsignedShort(); // this_class
91          dis.readUnsignedShort(); // super_class
92  
93          int interfacesCount = dis.readUnsignedShort();
94          skipFully(dis, 2L * interfacesCount);
95  
96          skipMembers(dis); // fields
97          skipMembers(dis); // methods
98  
99          int attributesCount = dis.readUnsignedShort();
100         for (int i = 0; i < attributesCount; i++) {
101             int attributeNameIndex = dis.readUnsignedShort();
102             long attributeLength = readU4(dis);
103             if (MODULE_ATTRIBUTE_NAME.equals(pool.utf8(attributeNameIndex))) {
104                 return readModuleAttribute(dis, pool);
105             }
106             skipFully(dis, attributeLength);
107         }
108 
109         throw new IOException("Not a module: no Module attribute found");
110     }
111 
112     /**
113      * Skips over a {@code fields} or {@code methods} array: same {@code field_info}/{@code method_info}
114      * shape, each with its own list of attributes that are skipped by their declared length.
115      */
116     private static void skipMembers(DataInputStream dis) throws IOException {
117         int count = dis.readUnsignedShort();
118         for (int i = 0; i < count; i++) {
119             skipFully(dis, 6); // access_flags, name_index, descriptor_index
120             int attributesCount = dis.readUnsignedShort();
121             for (int j = 0; j < attributesCount; j++) {
122                 skipFully(dis, 2); // attribute_name_index
123                 long attributeLength = readU4(dis);
124                 skipFully(dis, attributeLength);
125             }
126         }
127     }
128 
129     /**
130      * Reads the body of the {@code Module} attribute (JVMS 4.7.25), mapping it onto a
131      * {@link JavaModuleDescriptor} the same way {@code java.lang.module.ModuleDescriptor} does.
132      */
133     private static JavaModuleDescriptor readModuleAttribute(DataInputStream dis, ConstantPool pool) throws IOException {
134         String moduleName = pool.moduleName(dis.readUnsignedShort());
135         JavaModuleDescriptor.Builder builder = JavaModuleDescriptor.newModule(moduleName);
136 
137         dis.readUnsignedShort(); // module_flags
138         dis.readUnsignedShort(); // module_version_index
139 
140         int requiresCount = dis.readUnsignedShort();
141         for (int i = 0; i < requiresCount; i++) {
142             int requiresIndex = dis.readUnsignedShort();
143             int requiresFlags = dis.readUnsignedShort();
144             dis.readUnsignedShort(); // requires_version_index
145 
146             String requiredModule = pool.moduleName(requiresIndex);
147             if ((requiresFlags & (ACC_STATIC_PHASE | ACC_TRANSITIVE)) != 0) {
148                 Set<JavaModuleDescriptor.JavaRequires.JavaModifier> modifiers = new LinkedHashSet<>();
149                 if ((requiresFlags & ACC_STATIC_PHASE) != 0) {
150                     modifiers.add(JavaModuleDescriptor.JavaRequires.JavaModifier.STATIC);
151                 }
152                 if ((requiresFlags & ACC_TRANSITIVE) != 0) {
153                     modifiers.add(JavaModuleDescriptor.JavaRequires.JavaModifier.TRANSITIVE);
154                 }
155                 builder.requires(modifiers, requiredModule);
156             } else {
157                 builder.requires(requiredModule);
158             }
159         }
160 
161         int exportsCount = dis.readUnsignedShort();
162         for (int i = 0; i < exportsCount; i++) {
163             int exportsIndex = dis.readUnsignedShort();
164             dis.readUnsignedShort(); // exports_flags
165             int exportsToCount = dis.readUnsignedShort();
166             String pkg = pool.packageName(exportsIndex);
167             if (exportsToCount == 0) {
168                 builder.exports(pkg);
169             } else {
170                 Set<String> targets = new HashSet<>();
171                 for (int j = 0; j < exportsToCount; j++) {
172                     targets.add(pool.moduleName(dis.readUnsignedShort()));
173                 }
174                 builder.exports(pkg, targets);
175             }
176         }
177 
178         int opensCount = dis.readUnsignedShort();
179         for (int i = 0; i < opensCount; i++) {
180             dis.readUnsignedShort(); // opens_index
181             dis.readUnsignedShort(); // opens_flags
182             int opensToCount = dis.readUnsignedShort();
183             skipFully(dis, 2L * opensToCount);
184         }
185 
186         int usesCount = dis.readUnsignedShort();
187         for (int i = 0; i < usesCount; i++) {
188             builder.uses(pool.className(dis.readUnsignedShort()));
189         }
190 
191         int providesCount = dis.readUnsignedShort();
192         for (int i = 0; i < providesCount; i++) {
193             String service = pool.className(dis.readUnsignedShort());
194             int withCount = dis.readUnsignedShort();
195             List<String> providers = new ArrayList<>(withCount);
196             for (int j = 0; j < withCount; j++) {
197                 providers.add(pool.className(dis.readUnsignedShort()));
198             }
199             builder.provides(service, providers);
200         }
201 
202         return builder.build();
203     }
204 
205     private static long readU4(DataInputStream dis) throws IOException {
206         return dis.readInt() & 0xFFFFFFFFL;
207     }
208 
209     private static void skipFully(DataInputStream dis, long length) throws IOException {
210         long remaining = length;
211         while (remaining > 0) {
212             long skipped = dis.skip(remaining);
213             if (skipped <= 0) {
214                 // skip() may legitimately return 0 near the end of the stream; fall back to read()
215                 if (dis.read() < 0) {
216                     throw new IOException("Unexpected end of class file");
217                 }
218                 skipped = 1;
219             }
220             remaining -= skipped;
221         }
222     }
223 
224     /**
225      * The subset of the constant pool this parser needs: the raw UTF-8 entries, and, for the
226      * Class/Module/Package entries, which UTF-8 entry holds their name. All three of those tags
227      * have the same one-field shape (JVMS 4.4.1, 4.4.8, 4.4.9): {@code u1 tag; u2 name_index;}.
228      */
229     private static final class ConstantPool {
230         private final String[] utf8;
231         private final int[] classLikeNameIndex;
232 
233         private ConstantPool(String[] utf8, int[] classLikeNameIndex) {
234             this.utf8 = utf8;
235             this.classLikeNameIndex = classLikeNameIndex;
236         }
237 
238         static ConstantPool read(DataInputStream dis) throws IOException {
239             int constantPoolCount = dis.readUnsignedShort();
240             String[] utf8 = new String[constantPoolCount];
241             int[] classLikeNameIndex = new int[constantPoolCount];
242 
243             for (int i = 1; i < constantPoolCount; i++) {
244                 int tag = dis.readUnsignedByte();
245                 switch (tag) {
246                     case CONSTANT_UTF8:
247                         utf8[i] = dis.readUTF();
248                         break;
249                     case CONSTANT_CLASS:
250                     case CONSTANT_MODULE:
251                     case CONSTANT_PACKAGE:
252                         classLikeNameIndex[i] = dis.readUnsignedShort();
253                         break;
254                     case CONSTANT_STRING:
255                         skipFully(dis, 2);
256                         break;
257                     case CONSTANT_INTEGER:
258                     case CONSTANT_FLOAT:
259                     case CONSTANT_FIELDREF:
260                     case CONSTANT_METHODREF:
261                     case CONSTANT_INTERFACE_METHODREF:
262                     case CONSTANT_NAME_AND_TYPE:
263                     case CONSTANT_DYNAMIC:
264                     case CONSTANT_INVOKE_DYNAMIC:
265                         skipFully(dis, 4);
266                         break;
267                     case CONSTANT_LONG:
268                     case CONSTANT_DOUBLE:
269                         skipFully(dis, 8);
270                         // long/double take up two consecutive constant pool entries; the second is unused
271                         i++;
272                         break;
273                     case CONSTANT_METHOD_HANDLE:
274                         skipFully(dis, 3);
275                         break;
276                     case CONSTANT_METHOD_TYPE:
277                         skipFully(dis, 2);
278                         break;
279                     default:
280                         throw new IOException("Unsupported constant pool tag " + tag + " at index " + i);
281                 }
282             }
283             return new ConstantPool(utf8, classLikeNameIndex);
284         }
285 
286         String utf8(int index) {
287             return utf8[index];
288         }
289 
290         String moduleName(int index) {
291             return utf8[classLikeNameIndex[index]];
292         }
293 
294         String packageName(int index) {
295             return utf8[classLikeNameIndex[index]].replace('/', '.');
296         }
297 
298         String className(int index) {
299             return utf8[classLikeNameIndex[index]].replace('/', '.');
300         }
301     }
302 }