aboutsummaryrefslogtreecommitdiff
path: root/java/com/google/turbine/bytecode/ClassReader.java
blob: 1a98ce31ea54e164c8e90f1ffdee0feced3ba544 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.turbine.bytecode;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.turbine.bytecode.ClassFile.AnnotationInfo.ElementValue;
import com.google.turbine.bytecode.ClassFile.AnnotationInfo.ElementValue.ConstClassValue;
import com.google.turbine.bytecode.ClassFile.AnnotationInfo.ElementValue.EnumConstValue;
import com.google.turbine.bytecode.ClassFile.ModuleInfo;
import com.google.turbine.bytecode.ClassFile.ModuleInfo.ExportInfo;
import com.google.turbine.bytecode.ClassFile.ModuleInfo.OpenInfo;
import com.google.turbine.bytecode.ClassFile.ModuleInfo.ProvideInfo;
import com.google.turbine.bytecode.ClassFile.ModuleInfo.RequireInfo;
import com.google.turbine.bytecode.ClassFile.ModuleInfo.UseInfo;
import com.google.turbine.model.Const;
import com.google.turbine.model.TurbineFlag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;

/** A JVMS §4 class file reader. */
public class ClassReader {

  /** Reads the given bytes into an {@link ClassFile}. */
  @Deprecated
  public static ClassFile read(byte[] bytes) {
    return read(null, bytes);
  }

  /** Reads the given bytes into an {@link ClassFile}. */
  public static ClassFile read(@Nullable String path, byte[] bytes) {
    return new ClassReader(path, bytes).read();
  }

  @Nullable private final String path;
  private final ByteReader reader;

  private ClassReader(@Nullable String path, byte[] bytes) {
    this.path = path;
    this.reader = new ByteReader(bytes, 0);
  }

  @CheckReturnValue
  Error error(String format, Object... args) {
    StringBuilder sb = new StringBuilder();
    if (path != null) {
      sb.append(path).append(": ");
    }
    sb.append(String.format(format, args));
    return new AssertionError(sb.toString());
  }

  private ClassFile read() {
    int magic = reader.u4();
    if (magic != 0xcafebabe) {
      throw error("bad magic: 0x%x", path, magic);
    }
    int minorVersion = reader.u2();
    int majorVersion = reader.u2();
    if (majorVersion < 45) {
      throw error("bad version: %d.%d", majorVersion, minorVersion);
    }
    ConstantPoolReader constantPool = ConstantPoolReader.readConstantPool(reader);
    int accessFlags = reader.u2();
    String thisClass = constantPool.classInfo(reader.u2());
    int superClassIndex = reader.u2();
    String superClass;
    if (superClassIndex != 0) {
      superClass = constantPool.classInfo(superClassIndex);
    } else {
      superClass = null;
    }
    int interfacesCount = reader.u2();
    List<String> interfaces = new ArrayList<>();
    for (int i = 0; i < interfacesCount; i++) {
      interfaces.add(constantPool.classInfo(reader.u2()));
    }

    List<ClassFile.FieldInfo> fieldinfos = readFields(constantPool);

    List<ClassFile.MethodInfo> methodinfos = readMethods(constantPool);

    String signature = null;
    List<ClassFile.InnerClass> innerclasses = Collections.emptyList();
    List<ClassFile.AnnotationInfo> annotations = Collections.emptyList();
    ClassFile.ModuleInfo module = null;
    int attributesCount = reader.u2();
    for (int j = 0; j < attributesCount; j++) {
      int attributeNameIndex = reader.u2();
      String name = constantPool.utf8(attributeNameIndex);
      switch (name) {
        case "RuntimeVisibleAnnotations":
          annotations = readAnnotations(constantPool, accessFlags);
          break;
        case "Signature":
          signature = readSignature(constantPool);
          break;
        case "InnerClasses":
          innerclasses = readInnerClasses(constantPool, thisClass);
          break;
        case "Module":
          module = readModule(constantPool);
          break;
        default:
          reader.skip(reader.u4());
          break;
      }
    }

    return new ClassFile(
        accessFlags,
        thisClass,
        signature,
        superClass,
        interfaces,
        methodinfos,
        fieldinfos,
        annotations,
        innerclasses,
        ImmutableList.of(),
        module);
  }

  /** Reads a JVMS 4.7.9 Signature attribute. */
  private String readSignature(ConstantPoolReader constantPool) {
    String signature;
    reader.u4(); // length
    signature = constantPool.utf8(reader.u2());
    return signature;
  }

  /** Reads JVMS 4.7.6 InnerClasses attributes. */
  private List<ClassFile.InnerClass> readInnerClasses(
      ConstantPoolReader constantPool, String thisClass) {
    reader.u4(); // length
    int numberOfClasses = reader.u2();
    List<ClassFile.InnerClass> innerclasses = new ArrayList<>();
    for (int i = 0; i < numberOfClasses; i++) {
      int innerClassInfoIndex = reader.u2();
      String innerClass = constantPool.classInfo(innerClassInfoIndex);
      int outerClassInfoIndex = reader.u2();
      String outerClass =
          outerClassInfoIndex != 0 ? constantPool.classInfo(outerClassInfoIndex) : null;
      int innerNameIndex = reader.u2();
      String innerName = innerNameIndex != 0 ? constantPool.utf8(innerNameIndex) : null;
      int innerClassAccessFlags = reader.u2();
      if (innerName != null && (thisClass.equals(innerClass) || thisClass.equals(outerClass))) {
        innerclasses.add(
            new ClassFile.InnerClass(innerClass, outerClass, innerName, innerClassAccessFlags));
      }
    }
    return innerclasses;
  }

  /**
   * Processes a JVMS 4.7.16 RuntimeVisibleAnnotations attribute.
   *
   * <p>The only annotations that affect header compilation are {@link @Retention} and
   * {@link @Target} on annotation declarations.
   */
  private List<ClassFile.AnnotationInfo> readAnnotations(
      ConstantPoolReader constantPool, int accessFlags) {
    List<ClassFile.AnnotationInfo> annotations = new ArrayList<>();
    if ((accessFlags & TurbineFlag.ACC_ANNOTATION) == 0) {
      reader.skip(reader.u4());
      return ImmutableList.of();
    }
    reader.u4(); // length
    int numAnnotations = reader.u2();
    for (int n = 0; n < numAnnotations; n++) {
      ClassFile.AnnotationInfo tmp = readAnnotation(constantPool);
      if (tmp != null) {
        annotations.add(tmp);
      }
    }
    return annotations;
  }

  /** Processes a JVMS 4.7.25 Module attribute. */
  private ModuleInfo readModule(ConstantPoolReader constantPool) {
    reader.u4(); // length
    String name = constantPool.moduleInfo(reader.u2());
    int flags = reader.u2();
    int versionIndex = reader.u2();
    String version = (versionIndex != 0) ? constantPool.utf8(versionIndex) : null;

    ImmutableList.Builder<ClassFile.ModuleInfo.RequireInfo> requires = ImmutableList.builder();
    int numRequires = reader.u2();
    for (int i = 0; i < numRequires; i++) {
      String requiresModule = constantPool.moduleInfo(reader.u2());
      int requiresFlags = reader.u2();
      int requiresVersionIndex = reader.u2();
      String requiresVersion =
          (requiresVersionIndex != 0) ? constantPool.utf8(requiresVersionIndex) : null;
      requires.add(new RequireInfo(requiresModule, requiresFlags, requiresVersion));
    }

    ImmutableList.Builder<ClassFile.ModuleInfo.ExportInfo> exports = ImmutableList.builder();
    int numExports = reader.u2();
    for (int i = 0; i < numExports; i++) {
      String exportsModule = constantPool.packageInfo(reader.u2());
      int exportsFlags = reader.u2();
      int numExportsTo = reader.u2();
      ImmutableList.Builder<String> exportsToModules = ImmutableList.builder();
      for (int n = 0; n < numExportsTo; n++) {
        String exportsToModule = constantPool.moduleInfo(reader.u2());
        exportsToModules.add(exportsToModule);
      }
      exports.add(new ExportInfo(exportsModule, exportsFlags, exportsToModules.build()));
    }

    ImmutableList.Builder<ClassFile.ModuleInfo.OpenInfo> opens = ImmutableList.builder();
    int numOpens = reader.u2();
    for (int i = 0; i < numOpens; i++) {
      String opensModule = constantPool.packageInfo(reader.u2());
      int opensFlags = reader.u2();
      int numOpensTo = reader.u2();
      ImmutableList.Builder<String> opensToModules = ImmutableList.builder();
      for (int n = 0; n < numOpensTo; n++) {
        String opensToModule = constantPool.moduleInfo(reader.u2());
        opensToModules.add(opensToModule);
      }
      opens.add(new OpenInfo(opensModule, opensFlags, opensToModules.build()));
    }

    ImmutableList.Builder<ClassFile.ModuleInfo.UseInfo> uses = ImmutableList.builder();
    int numUses = reader.u2();
    for (int i = 0; i < numUses; i++) {
      String use = constantPool.classInfo(reader.u2());
      uses.add(new UseInfo(use));
    }

    ImmutableList.Builder<ClassFile.ModuleInfo.ProvideInfo> provides = ImmutableList.builder();
    int numProvides = reader.u2();
    for (int i = 0; i < numProvides; i++) {
      String typeName = constantPool.classInfo(reader.u2());
      int numProvidesWith = reader.u2();
      ImmutableList.Builder<String> impls = ImmutableList.builder();
      for (int n = 0; n < numProvidesWith; n++) {
        String impl = constantPool.classInfo(reader.u2());
        impls.add(impl);
      }
      provides.add(new ProvideInfo(typeName, impls.build()));
    }

    return new ClassFile.ModuleInfo(
        name,
        flags,
        version,
        requires.build(),
        exports.build(),
        opens.build(),
        uses.build(),
        provides.build());
  }

  /**
   * Extracts an {@link @Retention} or {@link ElementType} {@link ClassFile.AnnotationInfo}, or else
   * skips over the annotation.
   */
  private ClassFile.AnnotationInfo readAnnotation(ConstantPoolReader constantPool) {
    int typeIndex = reader.u2();
    String annotationType = constantPool.utf8(typeIndex);
    boolean read;
    switch (annotationType) {
      case "Ljava/lang/annotation/Retention;":
      case "Ljava/lang/annotation/Target;":
      case "Ljava/lang/annotation/Repeatable;":
        read = true;
        break;
      default:
        read = false;
        break;
    }
    int numElementValuePairs = reader.u2();
    ClassFile.AnnotationInfo result = null;
    for (int e = 0; e < numElementValuePairs; e++) {
      int elementNameIndex = reader.u2();
      String key = constantPool.utf8(elementNameIndex);
      boolean value = read && key.equals("value");
      ElementValue tmp = readElementValue(constantPool, value);
      if (tmp != null) {
        result = new ClassFile.AnnotationInfo(annotationType, true, ImmutableMap.of(key, tmp));
      }
    }
    return result;
  }

  /**
   * Extracts the value of an annotation declaration meta-annotation, or else skips over the element
   * value pair.
   */
  private ElementValue readElementValue(ConstantPoolReader constantPool, boolean value) {
    int tag = reader.u1();
    switch (tag) {
      case 'B':
      case 'C':
      case 'D':
      case 'F':
      case 'I':
      case 'J':
      case 'S':
      case 'Z':
      case 's':
        reader.u2(); // constValueIndex
        break;
      case 'e':
        {
          int typeNameIndex = reader.u2();
          int constNameIndex = reader.u2();
          if (value) {
            String typeName = constantPool.utf8(typeNameIndex);
            switch (typeName) {
              case "Ljava/lang/annotation/RetentionPolicy;":
              case "Ljava/lang/annotation/ElementType;":
                String constName = constantPool.utf8(constNameIndex);
                return new EnumConstValue(typeName, constName);
              default:
                break;
            }
          }
          break;
        }
      case 'c':
        int classInfoIndex = reader.u2();
        String className = constantPool.utf8(classInfoIndex);
        return new ConstClassValue(className);
      case '@':
        readAnnotation(constantPool);
        break;
      case '[':
        {
          int numValues = reader.u2();
          if (value) {
            ImmutableList.Builder<ElementValue> elements = ImmutableList.builder();
            for (int i = 0; i < numValues; i++) {
              elements.add(readElementValue(constantPool, true));
            }
            return new ElementValue.ArrayValue(elements.build());
          } else {
            for (int i = 0; i < numValues; i++) {
              readElementValue(constantPool, false);
            }
          }
          break;
        }
      default:
        throw error("bad tag value %c", tag);
    }
    return null;
  }

  /** Reads JVMS 4.6 method_infos. */
  private List<ClassFile.MethodInfo> readMethods(ConstantPoolReader constantPool) {
    int methodsCount = reader.u2();
    List<ClassFile.MethodInfo> methods = new ArrayList<>();
    for (int i = 0; i < methodsCount; i++) {
      int accessFlags = reader.u2();
      int nameIndex = reader.u2();
      String name = constantPool.utf8(nameIndex);
      int descriptorIndex = reader.u2();
      String desc = constantPool.utf8(descriptorIndex);
      int attributesCount = reader.u2();
      String signature = null;
      ImmutableList<String> exceptions = ImmutableList.of();
      for (int j = 0; j < attributesCount; j++) {
        String attributeName = constantPool.utf8(reader.u2());
        switch (attributeName) {
          case "Exceptions":
            exceptions = readExceptions(constantPool);
            break;
          case "Signature":
            signature = readSignature(constantPool);
            break;
          default:
            reader.skip(reader.u4());
            break;
        }
      }
      methods.add(
          new ClassFile.MethodInfo(
              accessFlags,
              name,
              desc,
              signature,
              exceptions,
              null,
              ImmutableList.of(),
              ImmutableList.of(),
              ImmutableList.of(),
              ImmutableList.of()));
    }
    return methods;
  }

  /** Reads an Exceptions attribute. */
  private ImmutableList<String> readExceptions(ConstantPoolReader constantPool) {
    ImmutableList.Builder<String> exceptions = ImmutableList.builder();
    reader.u4(); // length
    int numberOfExceptions = reader.u2();
    for (int exceptionIndex = 0; exceptionIndex < numberOfExceptions; exceptionIndex++) {
      exceptions.add(constantPool.classInfo(reader.u2()));
    }
    return exceptions.build();
  }

  /** Reads JVMS 4.5 field_infos. */
  private List<ClassFile.FieldInfo> readFields(ConstantPoolReader constantPool) {
    int fieldsCount = reader.u2();
    List<ClassFile.FieldInfo> fields = new ArrayList<>();
    for (int i = 0; i < fieldsCount; i++) {
      int accessFlags = reader.u2();
      int nameIndex = reader.u2();
      String name = constantPool.utf8(nameIndex);
      int descriptorIndex = reader.u2();
      String desc = constantPool.utf8(descriptorIndex);
      int attributesCount = reader.u2();
      Const.Value value = null;
      for (int j = 0; j < attributesCount; j++) {
        String attributeName = constantPool.utf8(reader.u2());
        switch (attributeName) {
          case "ConstantValue":
            reader.u4(); // length
            value = constantPool.constant(reader.u2());
            break;
          default:
            reader.skip(reader.u4());
            break;
        }
      }
      fields.add(
          new ClassFile.FieldInfo(
              accessFlags,
              name,
              desc,
              /*signature*/ null,
              value,
              ImmutableList.of(),
              ImmutableList.of()));
    }
    return fields;
  }
}